@faststore/api 4.7.0 → 4.7.1-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const an=require("@graphql-tools/merge"),on=require("@graphql-tools/schema"),V=require("@graphql-tools/utils"),ce=require("graphql"),B=require("@faststore/diagnostics"),Hn=require("isomorphic-unfetch"),ne=require("cookie"),Ae=require("p-limit"),ge=require("dataloader"),Xn=require("sanitize-html"),Pe=require("fast-deep-equal"),Yn=require("node:crypto");var sn=(e=>(e.Personal="personal",e.Shared="shared",e))(sn||{}),cn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(cn||{}),ln=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(ln||{}),dn=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(dn||{}),un=(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))(un||{}),pn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(pn||{}),gn=(e=>(e.Input="Input",e.Output="Output",e))(gn||{});const Jn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new W("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Kn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Z("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Z("Authentication required"):r===403?new W("You are not allowed to access this resource"):new Z("Authentication required")}},Qn="auth",mn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>V.mapSchema(e,{[V.MapperKind.OBJECT_FIELD]:n=>{if(V.getDirective(e,n,Qn)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Kn(o),r?.(i,a,o,s))}return n}})},Zn="cacheControl",et=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},_e=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,nt=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,hn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>V.mapSchema(e,{[V.MapperKind.OBJECT_FIELD]:n=>{const t=V.getDirective(e,n,Zn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,d,u)=>(d.cacheControl={sMaxAge:_e(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:_e(d.cacheControl?.staleWhileRevalidate,i),scope:nt(d.cacheControl?.scope,a)},o?.(s,c,d,u))}return n}})},fn=e=>(n,t)=>{const r=an.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,on.makeExecutableSchema({typeDefs:r,resolvers:n}))},Sn="@faststore/api",yn="4.7.0-dev.9",ke={name:Sn,version:yn},tt=B.logger("@faststore/api"),rt=(e,n="Unknown Graphql Resolver")=>(t,r,i,a)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,a);const o=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":yn,"@faststore_package_name":Sn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":a?.parentType?.name,"@faststore_resolver_field_name":a?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),o);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,a));return c instanceof Promise?c.then(d=>(o.end(),d),d=>Ue(d,o,n)):(o.end(),c)}catch(c){return Ue(c,o,n)}};function Ue(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),tt("error",`Error at resolver: %s
3
- %o`,t,e),e}class H extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends H{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Z extends H{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class W extends H{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class N extends H{constructor(n){super({status:404,type:"NotFoundError"},n)}}const it=e=>e?.name==="FastStoreError",at=e=>e?.extensions?.type==="BadRequestError",ot=e=>e?.extensions?.type==="UnauthorizedError",In=e=>e?.extensions?.type==="ForbiddenError",x=e=>e?.extensions?.type==="NotFoundError",st=`${ke.name}@${ke.version}`,y=async(e,n,t)=>{const r=await Hn(e,{...n,headers:{...n?.headers??{},"User-Agent":st}});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 Z(i);case 403:throw new W(i);case 404:throw new N(i);default:throw new H({status:r.status,type:"UnknownError"},i)}throw new Error(i)},ct=({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"}})}},vn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),c=a.substring(o+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},lt=/^([^=]+)=([^;]*)/,dt=(e,n)=>{const t=n.match(lt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},ut=(e,n)=>{n.getSetCookie().forEach(t=>dt(e,t))},pt=e=>n=>ut(e,n),he=e=>{if(!e.headers?.cookie)return null;const n=vn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>gt(r,i,a),n)},On=e=>function(t){const r=he(e);return r?{...t,cookie:r}:t},$=(e,n)=>{const t=vn(e);return ne.parse(t)[`VtexIdclientAutCookie_${n}`]||""},gt=(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){if(!e)return null;try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString())}catch{return null}}const mt="storefront/faststore.recommendation-shelf@v4",Y={method:"POST",headers:{"content-type":"application/json"}},ht=e=>e.split("/").map(encodeURIComponent).join("/"),me=e=>e?{headers:{"Accept-Language":e}}:void 0,ft=/^\d{4}-\d{2}-\d{2}$/,St=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function yt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o}){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",a],["expiresAtTo",o]])if(c&&!ft.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!St.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function It({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,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),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const vt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=pt(i),s=On(i),c=Jn(),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=`${a}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${mt}`}),v=(l={})=>{const g=$(he(i)??"",e);return s({...l,"X-FORWARDED-HOST":p,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:l=>y(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>y(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>y(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>y(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},byLinkId:{category:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/category/by-linkid/${ht(l)}`,me(g))}catch(m){if(x(m))return null;throw m}},brand:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,me(g))}catch(m){if(x(m))return null;throw m}},collection:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,me(g))}catch(m){if(x(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(`${a}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:o})}}},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(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...Y,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:g,deliveryMode:m,selectedAddresses:S},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:g},(I,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...Y,headers:_,body:JSON.stringify(C)},{storeCookies:o})},marketingData:({id:l,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},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}),C=new URLSearchParams;(!S||!l)&&C.set("sc",O),l&&C.set("refreshOutdatedData",g.toString());const _=l?`/${l}`:"",I=`${a}/api/checkout/pub/orderForm${_}?${C}`;return y(I,{...Y,headers:w,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...Y,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}),C=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:C,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:g,key:m,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/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=`${a}/api/checkout/pub/regions/?${O.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(w,{headers:C},{storeCookies:o})},address:async({postalCode:l,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/postal-code/${g}/${l}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:g,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/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(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:l})},{storeCookies:o})}},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(`${a}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>y(`${a}/api/dataentities/NL/documents/`,{...Y,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:l,status:g,dateInitial:m,dateFinal:S,text:O,clientEmail:w,perPage:C,pendingMyApproval:_})=>{const I=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(S){const A=new Date(S).setHours(23,59,59,999);S=new Date(A).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()),C&&I.append("per_page",C.toString()),_&&I.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders?${I.toString()}`,{method:"GET",headers:D},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:m,approved:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p}),_={params:{ruleId:m,dimensionId:g,score:S?100:0}};return y(`${a}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(_)},{storeCookies:o})}},savedCards:{listCreditCards:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/saved-cards/credit-card?an=${e}`,{method:"GET",headers:l},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/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(`${a}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/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(`${a}/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(`${a}/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(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})},isResourceGranted:({userId:l,resourceKey:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/bff/users/${l}/resources/${g}/granted?an=${e}`,{method:"GET",headers:m},{})}},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(`${a}/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(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:l=>{yt(l);const g=It(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p}),g=$(he(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:o})}},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
- `,_=/^[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: ${_}`,"",""].join(w),A=`${w}--${O}--${w}`,E=Buffer.from(D),P=Buffer.from(A),R=new Uint8Array(E.byteLength+l.byteLength+P.byteLength);let b=0;return R.set(E,b),b+=E.byteLength,R.set(l,b),b+=l.byteLength,R.set(P,b),y(`${a}/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(`${a}/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(`${a}/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(`${a}/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(`${a}/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:o})},startRecommendationSession:()=>{const l=new URLSearchParams({an:e});return y(`${f}/users/start-session?${l.toString()}`,{method:"POST",headers:h},{storeCookies:o})}}}},ee=e=>e.discoveryConfig?.localization??{},j=e=>ee(e).enabled===!0,Ot=e=>Object.keys(ee(e).locales??{}),bt=e=>ee(e).defaultLocale,ae=e=>j(e)&&e.storage.locale||void 0,fe="fuzzy",Se="operator",ye="pickupPoint",Re="shipping",Fe="delivery-options",Ct="in-stock",wt="trade-policy",Dt="region-id",At=new Set([wt,Dt,fe,Se,ye]),Pt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Ne=e=>encodeURI(decodeURI(e)),Et=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Tt=/^pickup-in-point-(.+)$/;function bn(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 _t(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const a=r.slice(0,i),o=r.slice(i+1);!a||!o||(Pt.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function kt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=_t(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 wn(e){return Tt.exec(e)?.[1]}function Ut(e){const n=e.find(r=>r.key==="shipping"),t=n?wn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Rt(e,n){const t=Ut(n);return t===void 0?e:{...e,pickupPoint:t}}function Ft(e){return e.map(n=>n.key!=="shipping"||wn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Nt(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")),Ft(t)}function Lt(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)}/${Et(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Bt=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 Mt(e,n){const{segmentParams:t,extraFacets:r}=kt(e??{}),i=n?.salesChannel??t.sc,a=n?.regionId??t.regionId,o=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...a?{regionId:a}:{},locale:o},extraFacets:r}}function zt(e,n){const t=e.filter(({key:c})=>!At.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,a=[...t],o=a.some(({key:c})=>c===Re),s=a.some(({key:c})=>c===Fe);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),Nt(a,n)}function qt(e,n){const t=e.find(({key:a})=>a===fe)??null,r=e.find(({key:a})=>a===Se)??null,i=e.find(({key:a})=>a===ye)??null;t&&Bt(t)&&n.append(fe,t.value),r&&$t(r)&&n.append(Se,r.value),i&&n.append(ye,i.value)}function Le(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:u,hideUnavailableItems:p,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const g=a*o,m=o===0?g:g+o-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=Rt(t.segmentParams,c);if(Cn(h,v??t.segmentParams),qt(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=Lt(zt(c,t.extraFacets));return{params:h,path:l}}function Vt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return Cn(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function J(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function K(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=Mt(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Le(i,r,a,{includePagination:!0,includeSort:!0});return J(s,o)}case"catalog-count":{const{params:o,path:s}=Le(i,r,a,{includePagination:!1,includeSort:!1});return J(s,o)}case"products":{const o=Vt(i,a.segmentParams);return J("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return J("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return J("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const xt=10;function jt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Wt(e){const t=bn(e.headers?.cookie).cultureInfo||"";return j(e)?e.storage.locale||t:t||e.storage.locale||""}const Gt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=On(o),d=bn(o.headers?.cookie),u=()=>({salesChannel:o.storage.channel.salesChannel,regionId:jt(o),locale:Wt(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",f=a&&a.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 A=I==="facets"?"facets":"product-search",E=K({endpoint:A,segment:d,defaults:u(),args:D});return y(`${s}/api/intelligent-search/v1/${A}/${E.path}?${E.params.toString()}`,{headers:v})},g=I=>l({...I,type:"product_search"}),m=({field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E})=>{const P=K({endpoint:"products",segment:d,defaults:u(),args:{field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E}});return y(`${s}/api/intelligent-search/v1/products?${P.params.toString()}`,{headers:v})};return{facets:I=>l({...I,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:I,values:D,showInvisibleItems:A,hideUnavailableItems:E})=>{const P=Ae(xt);return(await Promise.all(D.map(b=>P(async()=>{try{return await m({field:I,value:b,hideUnavailableItems:E,showInvisibleItems:A})}catch{return null}})))).filter(b=>b!==null)},suggestedTerms:I=>{const D=K({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=K({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=K({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})}}},Ht=(e,n)=>{const t=Gt(e,n),r=vt(e,n),i=ct(e);return{search:t,commerce:r,catalog:i}},Xt=20,Yt=e=>e.entityType==="category",Ie=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Jt=(e,n)=>{const t=Ae(Xt),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const d=await n.commerce.catalog.byLinkId.brand(o,s);if(d)return{...d,entityType:"brand"};const u=await n.commerce.catalog.byLinkId.collection(o,s);if(u)return{...u,entityType:"collection"};throw new N(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new ge(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},Kt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ge(t)},Qt=1,Zt=(e,n)=>{const t=Ae(Qt),r=async a=>{const o=a.reduce((p,{items:f})=>[...p,f],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[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=o.reduce((p,f)=>[...p,f.length+p[p.length-1]],[0]);return o.map((p,f)=>({...c,items:d.slice(u[f],u[f+1]).filter(h=>!!h)}))},i=async a=>t(r,a);return new ge(i,{maxBatchSize:50})},er=(e,n)=>Xn(e,n);function nr(e){return{...e,description:e.description?er(e.description):e.description}}const F=(e,n)=>({...e,isVariantOf:nr(n)}),tr=({flags:e},n)=>{const t=async r=>{const i=r.map(u=>u.split("-")[0]),a=r.some(u=>u.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...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 ge(t,{maxBatchSize:99})},rr=(e,n)=>{const{clients:t}=n,r=tr(e,t),i=Zt(e,t),a=Jt(e,t),o=Kt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},M=e=>e.AvailableQuantity>0,G=e=>e.spotPrice??0,ir=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",Dn=(e,n)=>M(e)&&!M(n)?-1:!M(e)&&M(n)?1:G(e)-G(n),ar=e=>e==="available",q=(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(M),r=t[t.length-1],i=r?G(r):0;return n.includeTaxes?q(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter(M),r=t?G(t):0;return n.includeTaxes?q(r,t?.Tax,t?.product?.unitMultiplier):r},sr={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},cr={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",lr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",dr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),lr.charAt(t));return n},ur=e=>e.replace(/[·/_,:]/,"-");function le(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ur(dr(t)).toLowerCase()}const Q=e=>Yt(e)?e.slug:Ie(e)?e.linkId:e.linkId??le(e.name),An={id:({id:e})=>e.toString(),slug:e=>Q(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>Ie(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=Q(e);if(Ie(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t),a=r.split("/").filter(Boolean),o=a.map((d,u)=>a.slice(0,u+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(o.map(d=>s.load({slug:d,locale:ae(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,a=Q(e).split("/").filter(Boolean),o=a.map((c,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(c=>r.load({slug:c,locale:ae(t)})));return{itemListElement:s.map((c,d)=>({item:`/${Q(c)}`,name:c.name,position:d+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 a=t.storage.locale,o=Q(e),s=o.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:ae(t)})))}catch(p){return console.warn("[otherLocales] failed to load collection entities:",p),null}return i.map(p=>{if(p===a)return{locale:p,slug:o};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},pr=e=>typeof Pn[e]=="string",gr=e=>{const n=e?.filter(t=>pr(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},mr=e=>e?.find(n=>n.key==="slug")?.value??null,hr=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,ve=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},fr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Sr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},yr={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??""),o=ve(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=ve(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Ir={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},vr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function En(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 Or(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 br=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=En(r);return{isPendingForOtherAuthorizer:!i&&Or(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})},wr=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},Dr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),Ar=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new T("Missing required fields: fileContent, fileName, mimeType");const o=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(o.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(o))throw new T("Invalid Base64 fileContent");const u=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:u,fileName:i,mimeType:a})};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 de=(e,n)=>{e.storage.channel=te.parse(n)},Oe=(e,n)=>{e.storage.locale=n},Tn=e=>Yn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function _n(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Er(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function kn(e){return Tn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Tr=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,a=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&a!==null?[a,i]:[]}return[r]},_r=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,a=e?.shippingData?.availableAddresses??[],o=e?.shippingData?.selectedAddresses??[];if(!t&&o.length>0)return[o[0]];if(t&&a.length>0)for(const s of a){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},Un=(e,n)=>{if(!kr(n))return{updateShipping:!1,addressChanged:!1};if(!Nr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Ur(t,n.postalCode)||Rr(t,n.geoCoordinates)||Fr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Lr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},kr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Ur=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Rr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Fr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Nr=e=>e.items.length!==0,Lr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,u=r&&s!==r;return c?.some(p=>d&&p.deliveryChannel===t||u&&p.id===r?!0:i&&a&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==a)&&p.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===a))})},Rn=e=>e.valueReference===re.attachment,be=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Rn).map(kn).join("-")].filter(Boolean).join("::"),ue=(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(_n)},index:n}),Br=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Rn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),We=e=>e.reduce((n,t)=>{const r=be(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),$r=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:d}),r=n.items.map(ue).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Pe(r,i);return a&&o};function Fn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Nn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const a=Nn(e.items,r.id)||Fn(e.items,r.id)?`${be(ue(r))}::${i}`:be(ue(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((o,s)=>o+s.quantity,0),a=t.reduce((o,s)=>o+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:a/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:a})=>({text:i,status:a.toUpperCase()}))}),Ln=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Tn(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:Ln(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"),sn=require("@graphql-tools/schema"),x=require("@graphql-tools/utils"),ce=require("graphql"),B=require("@faststore/diagnostics"),Yn=require("isomorphic-unfetch"),ne=require("cookie"),Pe=require("p-limit"),ge=require("dataloader"),Jn=require("sanitize-html"),Ee=require("fast-deep-equal"),Kn=require("node:crypto");var cn=(e=>(e.Personal="personal",e.Shared="shared",e))(cn||{}),ln=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(ln||{}),dn=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(dn||{}),un=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(un||{}),pn=(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))(pn||{}),gn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(gn||{}),mn=(e=>(e.Input="Input",e.Output="Output",e))(mn||{});const Qn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new G("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Zn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Z("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Z("Authentication required"):r===403?new G("You are not allowed to access this resource"):new Z("Authentication required")}},et="auth",hn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>x.mapSchema(e,{[x.MapperKind.OBJECT_FIELD]:n=>{if(x.getDirective(e,n,et)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Zn(o),r?.(i,a,o,s))}return n}})},nt="cacheControl",tt=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},ke=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,rt=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,fn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>x.mapSchema(e,{[x.MapperKind.OBJECT_FIELD]:n=>{const t=x.getDirective(e,n,nt)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,u,d)=>(u.cacheControl={sMaxAge:ke(u.cacheControl?.sMaxAge,r),staleWhileRevalidate:ke(u.cacheControl?.staleWhileRevalidate,i),scope:rt(u.cacheControl?.scope,a)},o?.(s,c,u,d))}return n}})},Sn=e=>(n,t)=>{const r=on.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,sn.makeExecutableSchema({typeDefs:r,resolvers:n}))},yn="@faststore/api",In="4.7.1-dev.0",Ue={name:yn,version:In},it=B.logger("@faststore/api"),at=(e,n="Unknown Graphql Resolver")=>(t,r,i,a)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,a);const o=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":In,"@faststore_package_name":yn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":a?.parentType?.name,"@faststore_resolver_field_name":a?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),o);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,a));return c instanceof Promise?c.then(u=>(o.end(),u),u=>Re(u,o,n)):(o.end(),c)}catch(c){return Re(c,o,n)}};function Re(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),it("error",`Error at resolver: %s
3
+ %o`,t,e),e}class X extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends X{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Z extends X{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class G extends X{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class N extends X{constructor(n){super({status:404,type:"NotFoundError"},n)}}const ot=e=>e?.name==="FastStoreError",st=e=>e?.extensions?.type==="BadRequestError",ct=e=>e?.extensions?.type==="UnauthorizedError",vn=e=>e?.extensions?.type==="ForbiddenError",j=e=>e?.extensions?.type==="NotFoundError",lt=`${Ue.name}@${Ue.version}`,y=async(e,n,t)=>{const r=await Yn(e,{...n,headers:{...n?.headers??{},"User-Agent":lt}});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 Z(i);case 403:throw new G(i);case 404:throw new N(i);default:throw new X({status:r.status,type:"UnknownError"},i)}throw new Error(i)},dt=({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"}})}},On=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),c=a.substring(o+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},ut=/^([^=]+)=([^;]*)/,pt=(e,n)=>{const t=n.match(ut);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},gt=(e,n)=>{n.getSetCookie().forEach(t=>pt(e,t))},mt=e=>n=>gt(e,n),fe=e=>{if(!e.headers?.cookie)return null;const n=On(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>ht(r,i,a),n)},bn=e=>function(t){const r=fe(e);return r?{...t,cookie:r}:t},$=(e,n)=>{const t=On(e);return ne.parse(t)[`VtexIdclientAutCookie_${n}`]||""},ht=(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){if(!e)return null;try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString())}catch{return null}}const ft="storefront/faststore.recommendation-shelf@v4",J={method:"POST",headers:{"content-type":"application/json"}},St=e=>e.split("/").map(encodeURIComponent).join("/"),me=e=>e?{headers:{"Accept-Language":e}}:void 0,yt=/^\d{4}-\d{2}-\d{2}$/,It=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function vt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o}){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",a],["expiresAtTo",o]])if(c&&!yt.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!It.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function Ot({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(u=>c.append("status",u)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const bt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=mt(i),s=bn(i),c=Qn(),u=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",d=r&&r.map(l=>l+".").find(l=>u.includes(l))||"",g=u.replace(d,""),f=`${a}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${ft}`}),b=(l={})=>{const p=$(fe(i)??"",e);return s({...l,"X-FORWARDED-HOST":g,...p?{[`VtexIdclientAutCookie_${e}`]:p}:{}})};return{catalog:{salesChannel:l=>y(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>y(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>y(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>y(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},byLinkId:{category:async(l,p)=>{try{return await y(`${a}/api/catalog_system/pub/category/by-linkid/${St(l)}`,me(p))}catch(m){if(j(m))return null;throw m}},brand:async(l,p)=>{try{return await y(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,me(p))}catch(m){if(j(m))return null;throw m}},collection:async(l,p)=>{try{return await y(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,me(p))}catch(m){if(j(m))return null;throw m}}},products:{crossselling:({type:l,productId:p,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${a}/api/catalog_system/pub/products/crossselling/${l}/${p}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:p}=i.storage.channel)=>{const m=new URLSearchParams({sc:p}),S=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...J,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:p,deliveryMode:m,selectedAddresses:S},v)=>{const w=v?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:p},(I,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...J,headers:_,body:JSON.stringify(C)},{storeCookies:o})},marketingData:({id:l,marketingData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:p=!0,channel:m=i.storage.channel,preserveSalesChannel:S=!1})=>{const{salesChannel:v}=m,w=s({"content-type":"application/json","X-FORWARDED-HOST":g}),C=new URLSearchParams;(!S||!l)&&C.set("sc",v),l&&C.set("refreshOutdatedData",p.toString());const _=l?`/${l}`:"",I=`${a}/api/checkout/pub/orderForm${_}?${C}`;return y(I,{...J,headers:w,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...J,headers:p,body:"{}"})},updateOrderFormItems:({id:l,orderItems:p,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:v=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:S}),C=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:C,body:JSON.stringify({orderItems:p,noSplitItem:!v}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:p,key:m,value:S})=>{const v=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/customData/${p}/${m}`,{headers:v,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:p,country:m,salesChannel:S})=>{const v=new URLSearchParams({country:m,sc:S??""});l?v.append("postalCode",l):v.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${v.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(w,{headers:C},{storeCookies:o})},address:async({postalCode:l,country:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/postal-code/${p}/${l}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:p,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:p,reason:m})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:p,body:JSON.stringify({coordinate:l})},{storeCookies:o})}},session:l=>{const p=new URLSearchParams(l);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"}),S=ne.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${a}/api/sessions?${p.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>y(`${a}/api/dataentities/NL/documents/`,{...J,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:p},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:p},{storeCookies:o})},listUserOrders:({page:l,status:p,dateInitial:m,dateFinal:S,text:v,clientEmail:w,perPage:C,pendingMyApproval:_})=>{const I=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(S){const A=new Date(S).setHours(23,59,59,999);S=new Date(A).toISOString()}v&&I.append("text",v),p&&p.length>0&&I.append("status",p.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()),C&&I.append("per_page",C.toString()),_&&I.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/oms/user/orders?${I.toString()}`,{method:"GET",headers:D},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:p},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:p,ruleId:m,approved:S})=>{const v=s({"content-type":"application/json","X-FORWARDED-HOST":g}),_={params:{ruleId:m,dimensionId:p,score:S?100:0}};return y(`${a}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:v,body:JSON.stringify(_)},{storeCookies:o})}},savedCards:{listCreditCards:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/saved-cards/credit-card?an=${e}`,{method:"GET",headers:l},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:p},{})},getOrgUnitById:({orgUnitId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/units/v1/${l}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:p},{})}},licenseManager:{getUserById:({userId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:p},{})},getUserByEmail:({email:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:p},{})},getUserRoles:({userId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:p},{})},isResourceGranted:({userId:l,resourceKey:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/license-manager/storefront/bff/users/${l}/resources/${p}/granted?an=${e}`,{method:"GET",headers:m},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new T("Missing contractId to fetch CL fields.");const p=b({Accept:"application/json","content-type":"application/json"});return y(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:p},{})},getShopperById:({userId:l})=>{if(!l)throw new T("Missing userId to fetch shopper name.");const p=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":g}),m=l.replace(/-/g,"");return y(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:p},{})}},quotes:{listUserQuotes:l=>{vt(l);const p=Ot(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/quoting/quotes?${p.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":g}),p=$(fe(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:p}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:p,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":g}),v=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
4
+ `,_=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",I=p.replaceAll(/[\r\n"]/g,"_"),D=[`--${v}`,`Content-Disposition: form-data; name="file"; filename="${I}"`,`Content-Type: ${_}`,"",""].join(w),A=`${w}--${v}--${w}`,E=Buffer.from(D),P=Buffer.from(A),R=new Uint8Array(E.byteLength+l.byteLength+P.byteLength);let O=0;return R.set(E,O),O+=E.byteLength,R.set(l,O),O+=l.byteLength,R.set(P,O),y(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${v}`},body:R.buffer},{})},startOperation:({objectKey:l,orderFormId:p,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":g}),v=JSON.stringify({objectKey:l,orderFormId:p,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:v},{})},getOperation:({operationId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:p},{})},createOrderForm:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:l,body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:p},{})}},recommendation:{recommendations:({campaignVrn:l,userId:p,products:m=[],salesChannel:S,locale:v})=>{const w=new URLSearchParams({an:e,campaignVrn:l});return p&&w.append("userId",p),m.length>0&&w.append("products",m.join(",")),S&&w.append("salesChannel",S),v&&w.append("locale",v),y(`${f}/recommendations?${w.toString()}`,{headers:h},{storeCookies:o})},startRecommendationSession:()=>{const l=new URLSearchParams({an:e});return y(`${f}/users/start-session?${l.toString()}`,{method:"POST",headers:h},{storeCookies:o})}}}},ee=e=>e.discoveryConfig?.localization??{},W=e=>ee(e).enabled===!0,Ct=e=>Object.keys(ee(e).locales??{}),wt=e=>ee(e).defaultLocale,Cn=e=>W(e)&&e.storage.locale||void 0,Se="fuzzy",ye="operator",Ie="pickupPoint",Fe="shipping",Ne="delivery-options",Dt="in-stock",At="trade-policy",Pt="region-id",Et=new Set([At,Pt,Se,ye,Ie]),Tt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Le=e=>encodeURI(decodeURI(e)),_t=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),kt=/^pickup-in-point-(.+)$/;function wn(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 Ut(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const a=r.slice(0,i),o=r.slice(i+1);!a||!o||(Tt.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function Rt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=Ut(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 Dn(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 An(e){return kt.exec(e)?.[1]}function Ft(e){const n=e.find(r=>r.key==="shipping"),t=n?An(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Nt(e,n){const t=Ft(n);return t===void 0?e:{...e,pickupPoint:t}}function Lt(e){return e.map(n=>n.key!=="shipping"||An(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Bt(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")),Lt(t)}function $t(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}${Le(r)}/${_t(Le(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Mt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),zt=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function qt(e,n){const{segmentParams:t,extraFacets:r}=Rt(e??{}),i=n?.salesChannel??t.sc,a=n?.regionId??t.regionId,o=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...a?{regionId:a}:{},locale:o},extraFacets:r}}function Vt(e,n){const t=e.filter(({key:c})=>!Et.has(c)),r=e.find(({key:c,value:u})=>c===Fe&&u!=="all-delivery-methods")??null,i=e.find(({key:c,value:u})=>c===Ne&&u!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===Fe),s=a.some(({key:c})=>c===Ne);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),Bt(a,n)}function xt(e,n){const t=e.find(({key:a})=>a===Se)??null,r=e.find(({key:a})=>a===ye)??null,i=e.find(({key:a})=>a===Ie)??null;t&&Mt(t)&&n.append(Se,t.value),r&&zt(r)&&n.append(ye,r.value),i&&n.append(Ie,i.value)}function Be(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:u,sponsoredCount:d,hideUnavailableItems:g,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const p=a*o,m=o===0?p:p+o-1;h.append("from",p.toString()),h.append("to",m.toString())}i&&h.append("query",i),r.includeSort&&s&&h.append("sort",s);const b=Nt(t.segmentParams,c);if(Dn(h,b??t.segmentParams),xt(c,h),u&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const p=c.find(({key:S})=>S===Dt),m=p?p.value:g?.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()),d!==void 0&&h.append("sponsoredCount",d.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=$t(Vt(c,t.extraFacets));return{params:h,path:l}}function jt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return Dn(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function K(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function Q(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=qt(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Be(i,r,a,{includePagination:!0,includeSort:!0});return K(s,o)}case"catalog-count":{const{params:o,path:s}=Be(i,r,a,{includePagination:!1,includeSort:!1});return K(s,o)}case"products":{const o=jt(i,a.segmentParams);return K("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return K("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return K("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const Wt=10;function Gt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Ht(e){const t=wn(e.headers?.cookie).cultureInfo||"";return W(e)?e.storage.locale||t:t||e.storage.locale||""}const Xt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=bn(o),u=wn(o.headers?.cookie),d=()=>({salesChannel:o.storage.channel.salesChannel,regionId:Gt(o),locale:Ht(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),g=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",f=a&&a.map(I=>I+".").find(I=>g.includes(I))||"",h=g.replace(f,""),b=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:I,...D})=>{const A=I==="facets"?"facets":"product-search",E=Q({endpoint:A,segment:u,defaults:d(),args:D});return y(`${s}/api/intelligent-search/v1/${A}/${E.path}?${E.params.toString()}`,{headers:b})},p=I=>l({...I,type:"product_search"}),m=({field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E})=>{const P=Q({endpoint:"products",segment:u,defaults:d(),args:{field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E}});return y(`${s}/api/intelligent-search/v1/products?${P.params.toString()}`,{headers:b})};return{facets:I=>l({...I,type:"facets"}),products:p,fetchProduct:m,productsByIdentifier:async({field:I,values:D,showInvisibleItems:A,hideUnavailableItems:E})=>{const P=Pe(Wt);return(await Promise.all(D.map(O=>P(async()=>{try{return await m({field:I,value:O,hideUnavailableItems:E,showInvisibleItems:A})}catch{return null}})))).filter(O=>O!==null)},suggestedTerms:I=>{const D=Q({endpoint:"search-suggestions",segment:u,defaults:d(),args:{query:I.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:b})},topSearches:()=>{const I=Q({endpoint:"top-searches",segment:u,defaults:d()});return y(`${s}/api/intelligent-search/v1/top-searches?${I.params.toString()}`,{headers:b})},productCount:I=>{const D=Q({endpoint:"catalog-count",segment:u,defaults:d(),args:I});return y(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:b})}}},Yt=(e,n)=>{const t=Xt(e,n),r=bt(e,n),i=dt(e);return{search:t,commerce:r,catalog:i}},Jt=20,Kt=e=>e.entityType==="category",ve=e=>e.entityType==="brand",$e=e=>e.entityType==="collection",Qt=(e,n)=>{const t=Pe(Jt),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const u=await n.commerce.catalog.byLinkId.brand(o,s);if(u)return{...u,entityType:"brand"};const d=await n.commerce.catalog.byLinkId.collection(o,s);if(d)return{...d,entityType:"collection"};throw new N(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new ge(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},Zt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ge(t)},er=1,nr=(e,n)=>{const t=Pe(er),r=async a=>{const o=a.reduce((g,{items:f})=>[...g,f],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),u=c.items.reduce((g,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<g.length&&(g[h]=f),g},Array(s.length).fill(null)),d=o.reduce((g,f)=>[...g,f.length+g[g.length-1]],[0]);return o.map((g,f)=>({...c,items:u.slice(d[f],d[f+1]).filter(h=>!!h)}))},i=async a=>t(r,a);return new ge(i,{maxBatchSize:50})},tr=(e,n)=>Jn(e,n);function rr(e){return{...e,description:e.description?tr(e.description):e.description}}const F=(e,n)=>({...e,isVariantOf:rr(n)}),ir=({flags:e},n)=>{const t=async r=>{const i=r.map(d=>d.split("-")[0]),a=r.some(d=>d.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((d,g)=>{for(const f of g.items)d[f.itemId]=F(f,g);return d},{}),c=i.map(d=>s[d]),u=i.filter(d=>!s[d]);if(u.length>0)throw new N(`Search API did not found the following skus: ${u.join(",")}`);return c};return new ge(t,{maxBatchSize:99})},ar=(e,n)=>{const{clients:t}=n,r=ir(e,t),i=nr(e,t),a=Qt(e,t),o=Zt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},M=e=>e.AvailableQuantity>0,H=e=>e.spotPrice??0,or=e=>e.Price??0,Me=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",Pn=(e,n)=>M(e)&&!M(n)?-1:!M(e)&&M(n)?1:H(e)-H(n),sr=e=>e==="available",V=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},cr=(e,n={includeTaxes:!1})=>{const t=e.filter(M),r=t[t.length-1],i=r?H(r):0;return n.includeTaxes?V(i,r?.Tax,r?.product?.unitMultiplier):i},ze=(e,n={includeTaxes:!1})=>{const[t]=e.filter(M),r=t?H(t):0;return n.includeTaxes?V(r,t?.Tax,t?.product?.unitMultiplier):r},lr={highPrice:e=>cr(e),lowPrice:e=>ze(e),lowPriceWithTaxes:e=>ze(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},dr={ratingValue:()=>5,reviewCount:()=>0},qe="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",ur="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",pr=e=>{let n=e.slice(0);for(let t=0;t<qe.length;t++)n=n.replace(new RegExp(qe.charAt(t),"g"),ur.charAt(t));return n},gr=e=>e.replace(/[·/_,:]/,"-");function le(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return gr(pr(t)).toLowerCase()}const he=e=>e.toLowerCase(),ae=(e,n)=>{const t=n.split("/").filter(Boolean),{loaders:{collectionLoader:r}}=e;return Promise.all(t.map((i,a)=>r.load({slug:t.slice(0,a+1).join("/"),locale:Cn(e)})))},z=e=>Kt(e)?e.slug:ve(e)?e.linkId:e.linkId??le(e.name),En={id:({id:e})=>e.toString(),slug:e=>z(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ve(e)?"Brand":$e(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=z(e);if(ve(e))return{selectedFacets:[{key:"brand",value:r}]};if($e(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t);return{selectedFacets:(await ae(t,r)).map((o,s)=>({key:`category-${s+1}`,value:i&&o.availableLinkIds?.[i]||o.linkId}))}},breadcrumbList:async(e,n,t)=>{const r=await ae(t,z(e));return{itemListElement:r.map((i,a)=>({item:`/${z(i)}`,name:i.name,position:a+1})),numberOfItems:r.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 a=z(e);if(a.split("/").filter(Boolean).length===0)return null;let o;try{o=await ae(t,a)}catch(s){return console.warn("[otherLocales] failed to load collection entities:",s),null}return i.map(s=>{const c=[];for(const u of o){const d=u.availableLinkIds?.[s];if(!d)return null;c.push(d)}return c.length>0?{locale:s,slug:he(c.join("/"))}:null}).filter(s=>s!==null)},canonicalSlug:async(e,n,t)=>{const r=z(e);if(r.split("/").filter(Boolean).length===0)return null;let i;try{i=await ae(t,r)}catch(o){return console.warn("[canonicalSlug] failed to load collection entities:",o),null}const a=i.map(o=>o.linkId);return a.every(o=>!!o)?he(a.join("/")):he(r)}},Tn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Ve=({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}}},xe=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},mr=e=>typeof Tn[e]=="string",hr=e=>{const n=e?.filter(t=>mr(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},fr=e=>e?.find(n=>n.key==="slug")?.value??null,Sr=e=>e?.find(n=>n.key==="id")?.value??null,je=e=>e?.find(n=>n.key==="locale")?.value??null,We=e=>e?.find(n=>n.key==="channel")?.value??null,Oe=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},yr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Ir={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},vr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=xe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Oe(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=xe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Oe(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Or={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},br=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function _n(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 Cr(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 wr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=_n(r);return{isPendingForOtherAuthorizer:!i&&Cr(r),ruleForAuthorization:i}},Dr=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})},Ar=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},Pr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),Er=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new T("Missing required fields: fileContent, fileName, mimeType");const o=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(o.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(o))throw new T("Invalid Base64 fileContent");const d=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:d,fileName:i,mimeType:a})};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 Tr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:te.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}const de=(e,n)=>{e.storage.channel=te.parse(n)},be=(e,n)=>{e.storage.locale=n},kn=e=>Kn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Un(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function _r(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Rn(e){return kn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const kr=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,a=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&a!==null?[a,i]:[]}return[r]},Ur=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,a=e?.shippingData?.availableAddresses??[],o=e?.shippingData?.selectedAddresses??[];if(!t&&o.length>0)return[o[0]];if(t&&a.length>0)for(const s of a){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},Fn=(e,n)=>{if(!Rr(n))return{updateShipping:!1,addressChanged:!1};if(!Br(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Fr(t,n.postalCode)||Nr(t,n.geoCoordinates)||Lr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return $r(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Rr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Fr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Nr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Lr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Br=e=>e.items.length!==0,$r=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const u=t&&o!==t,d=r&&s!==r;return c?.some(g=>u&&g.deliveryChannel===t||d&&g.id===r?!0:i&&a&&g.deliveryChannel===t&&g.id===r&&(!g?.deliveryWindow||g?.deliveryWindow?.startDateUtc!==i||g?.deliveryWindow?.endDateUtc!==a)&&g.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===a))})},Nn=e=>e.valueReference===re.attachment,Ce=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Nn).map(Rn).join("-")].filter(Boolean).join("::"),ue=(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(Un)},index:n}),Mr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Nn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),Ge=e=>e.reduce((n,t)=>{const r=Ce(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),zr=(e,n)=>{const t=({priceToken:s,...c},u)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:u}),r=n.items.map(ue).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Ee(r,i);return a&&o};function Ln(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Bn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const He=e=>{const n=e.items.reduce((t,r,i)=>{const a=Bn(e.items,r.id)||Ln(e.items,r.id)?`${Ce(ue(r))}::${i}`:Ce(ue(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((o,s)=>o+s.quantity,0),a=t.reduce((o,s)=>o+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:a/i}})}},we=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:a})=>({text:i,status:a.toUpperCase()}))}),$n=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return kn(JSON.stringify({sessionId:n?.id??"",items:t}))},Xe=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.
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}},Mr=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:Ln(e,n)!==r},zr=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}=Un(e,n);if(r){const a=_r(e,n,i),s=a||Tr(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},qr=(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?(de(e,t),n.salesChannel?String(n.salesChannel):null):null},Je=(e,n,t,r)=>r?Ce(e,n,t,r):null,Vr=async(e,{cart:{order:n},session:t},r)=>{const i=qr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&de(r,s),c&&Oe(r,c);const d=i||void 0,u=await a.checkout.orderForm({id:d,channel:r.storage.channel,preserveSalesChannel:!!d}),p=u.orderFormId;u.messages.length!==0&&await zr(p,r);const f=ne.parse(r?.headers?.cookie??"")?.vtex_session,h=z(f),{acceptedOffer:v,shouldSplitItem:l}=n;if(Mr(u,h)){const b=Ye(r,u),L=await He(u,a,h).then(Ge);if(p)return Ce(L,o,l,b)}const m=Ye(r,u),S=We(v),O=We(u.items.map(ue)),w=Array.from(O.entries()),C=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:I}=C.reduce((b,[L,Ee])=>{const Te=O.get(L);if(!Te)return Ee.forEach(X=>b.itemsToAdd.push(X)),b;const[ie,...jn]=Te;if(Nn(u.items,ie.itemOffered.sku)||Fn(u.items,ie.itemOffered.sku))return b.itemsToUpdate.push(ie),b;const Wn=Ee.reduce((X,Gn)=>X+Gn.quantity,0);return b.itemsToUpdate.push({...ie,quantity:Wn}),jn.forEach(X=>b.itemsToUpdate.push({...X,quantity:0})),b},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([b])=>!S.has(b)).flatMap(([,b])=>b.map(L=>({...L,quantity:0}))),A=[..._,...I,...D].map(Br),{updateShipping:E}=t?Un(u,t):{updateShipping:!1};if(A.length===0&&!E)return Je(u,o,l,m);let P;A.length>0?P=await a.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:A,shouldSplitItem:l}).then(b=>Xe(b,t,r)):P=await Xe(u,t,r),P=await Promise.resolve(P).then(b=>{if(t?.marketingData){const L={...b.marketingData,...t.marketingData};return a.checkout.marketingData({id:u.orderFormId,marketingData:L})}return b}).then(b=>c&&b.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:b.orderFormId,clientPreferencesData:{...b.clientPreferencesData,locale:c}}):b).then(b=>He(b,a,h)).then(Ge);const R=Pe(u.messages,P.messages);return $r(n,P)&&R?Je(P,o,l,m):Ce(P,o,l,m)};function xr(e,n,t,r){const i=e.hasOnlyDefaultSalesChannel===!1,a=n??void 0,o=t??e.regionId;return te.stringify({salesChannel:i?e.salesChannel||a:a??e.salesChannel,regionId:o??void 0,seller:r,hasOnlyDefaultSalesChannel:i?!1:!a})}const jr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Wr=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"},Gr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Wr):[]},Hr=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()??"",Xr=(e,n="")=>{const t=n.trim();return e.filter(Hr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Bn=(e,n)=>{const t=jr(e);return t||(n?.firstName?.value??"").trim()};async function Yr(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 Jr(e,n,t,r,i,a){const o=new URLSearchParams(e);return o.has("facets")&&o.delete("facets"),o.set("sc",o.get("sc")??n.salesChannel),t&&o.set("postalCode",t),r&&o.set("country",r),i&&o.set("geoCoordinates",`${i.longitude},${i.latitude}`),o.set("locale",a),o}function Kr(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 Qr(e,n,t){const r=z($(n??"",t));let i=!1;if(r)try{i=(await e.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(a){console.warn("JWT validation failed:",a),i=!1}return{isRepresentative:i?!!r?.isRepresentative:!1,customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function Zr(e,n,t,r,i,a){return!n.seller||!(t||r)?void 0:(await e.commerce.checkout.region({postalCode:t,geoCoordinates:r,country:i,salesChannel:a}))?.[0]?.sellers.find(c=>n.seller===c.id)?.id}function Qe(e){return typeof e?.value=="string"?e.value:""}function ei(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:Bn(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ni(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ti=async(e,{session:n,search:t},{clients:r,headers:i,account:a})=>{const o=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 P=await Yr(r,c,s);d=P.city,u=P.geoCoordinates}const f=Jr(t,o,s,c,u,n.locale),h=Kr(f,n.marketingData),{isRepresentative:v,customerId:l,unitId:g}=await Qr(r,i?.cookie,a),m=await r.commerce.session(f.toString()).catch(()=>null),S=m?.namespaces.profile??null,O=m?.namespaces.shopper??null,w=m?.namespaces.store??null,C=m?.namespaces.authentication??null,_=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 A=await Zr(r,o,s,u,c,f.get("sc")??o.salesChannel),E={...n,currency:{code:w?.currencyCode?.value??n.currency.code,symbol:w?.currencySymbol?.value??n.currency.symbol},country:w?.countryCode?.value??c,channel:xr(o,w?.channel?.value,_?.regionId?.value,A),b2b:ei({isRepresentative:v,authentication:C,shopper:O,publicData:I,profile:S,contract:D,customerId:l,unitId:g}),marketingData:h,person:ni(S),geoCoordinates:u?.latitude&&u?.longitude&&u||null,city:d};return Pe(n,E)?null:E},ri={validateCart:Vr,validateSession:ti,subscribeToNewsletter:Dr,cancelOrder:vr,processOrderAuthorization:br,uploadFileToOrderEntry:Ar,startOrderEntryOperation:Cr,startRecommendationSession:wr};var we;(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"})(we||(we={}));const ii=e=>typeof e=="string"?$n(e):null;function $n(e){try{return JSON.parse(e)}catch{return e}}const ai=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,oi=new ce.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:ii,serialize:ai,parseLiteral(e){return e.kind===we.STRING?$n(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,U=e=>"skuName"in e,si={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??"":U(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>k(e)?$e(M(e)):U(e)?$e(ar(e.availability)):null,seller:(e,n,t)=>k(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:U(e)?{identifier:e.seller}:null,price:e=>k(e)?G(e):U(e)?e.sellingPrice/100:null,priceWithTaxes:e=>k(e)?q(G(e),e?.Tax,e.product.unitMultiplier):U(e)?q(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>k(e)?ir(e):U(e)?e.sellingPrice/100:null,listPrice:e=>k(e)?e.ListPrice??0:U(e)?e.listPrice/100:null,listPriceWithTaxes:e=>k(e)?q(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):U(e)?q(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>k(e)?e.product:U(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>k(e)?e.AvailableQuantity??0:U(e)?e.quantity:null,isGift:e=>U(e)?e.isGift??!1:null,priceToken:e=>k(e)?e.PriceToken??null:null},ci=({linkText:e})=>`/${e}/p`,li=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),di=1e11,ui=e=>/^\d+$/.test(e),pi=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,gi=e=>{if(!ui(e))return new Date(pi.test(e)?`${e}Z`:e);const n=Number(e);return new Date(n>=di?n:n*1e3)},mi=e=>{if(e==null)return"";const n=String(e).trim();if(n==="")return"";const t=gi(n);return Number.isNaN(t.getTime())?"":t.toISOString().slice(0,10)},hi={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,Ze=(e,n)=>`/${oe(e,n)}/p`,fi=e=>Array.isArray(e)&&e.length>0?e:null;function De(e){return e.replace(/^\/+|\/+$/g,"")}async function se(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,a=i.get(r);if(a)return a;const o=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch(s){return console.warn(`[getLocalizedProductEntry] failed to load product ${n} for locale ${t}:`,s),null}})();return i.set(r,o),o}const Si=(e,n)=>{const t=e.findIndex(r=>De(r).split("/").at(-1)===n);return t<0?0:t},yi={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:ci(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:d}=e,u=Si(s,o),p=r[u],f=De(p).split("/"),h=t.storage.locale;if(j(t)&&h){const v=await se(t,c,h);if(v){const l=new Set(De(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(le).join("/")}/`;return{name:v,item:g,position:l+1}}),{name:i,item:Ze(a,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(fi(e)??[hi]).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 a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.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=>li({offer:n.commertialOffer,seller:n,product:e})).sort(Dn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:re.specification}))),i=n.map(_n),a=t.map(Er);return[...r,...i,...a]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>mi(e),advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!j(t))return null;const r=Ot(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=await se(t,i,o);if(!s?.availableLinkIds)return null;const{availableLinkIds:c}=s;return r.map(d=>{const u=c[d];return u?{locale:d,slug:oe(u,a)}:null}).filter(d=>d!==null)},defaultLocaleSlug:async(e,n,t)=>{if(!j(t))return null;const r=bt(t);if(!r)return null;const{productId:i,linkText:a}=e.isVariantOf,o=e.itemId,c=(await se(t,i,t.storage.locale))?.availableLinkIds?.[r]??a;return oe(c,o)}},Ii=new Set(["allSpecifications"]),vi={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=>!Ii.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},Oi={propertyID:e=>e.propertyID||kn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},pe=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=ve(n,({offer:r},{offer:i})=>Dn(r,i));return t?t.sku:e[0]},Mn=e=>e!==""&&!Number.isNaN(Number(e)),bi=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Ci=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!bi.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 a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:u,correlationId:p}=d;return{products:(d.products??[]).map(h=>{const v=pe(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:""},wi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Di=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 Ai(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await se(e,t,r))?.linkId===i}const zn="Invalid SkuId",qn="Slug was set but the fetched sku does not satisfy the slug condition.",Pi="UseAdHocCard",Ei=e=>x(e)||e instanceof Error&&(e.message===zn||e.message.startsWith(qn));async function Ti(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||j(e)&&r&&Mn(t.split("-").pop()??"")&&await Ai(e,t,a,r)))throw new Error(`${qn} slug: ${t}, linkText: ${i}`)}async function _i(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 a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new N(`No product found for id ${i.id}`);return F(pe(a.items),a)}const ki={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),a=hr(n),o=mr(n);r&&de(t,r),i&&Oe(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!Mn(c))throw new Error(zn);const d=await s.load(c);return await Ti(t,d,o,i),d}catch(c){if(!Ei(c))throw c;return _i(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ae(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=je(a),d=xe(a),u=gr(a);c&&de(s,c),d&&Oe(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:a?.flatMap(qe)??[],sponsoredCount:o??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,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/n),count:n}),s=o.products.flatMap(c=>c.items.map(d=>F(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(a+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>F(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,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:le(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=[...o.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:le(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!An.slug(h,null,r,null));return{pageInfo:{hasNextPage:f.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,f.length-a)-1).toString(),totalCount:f.length},edges:f.slice(a,a+n).map((h,v)=>({node:h,cursor:(a+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:n,items:t,postalCode:r}),o.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},a)=>{const{clients:{commerce:o}}=a,c=(await o.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 a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(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 a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=En(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")&&!!a,ruleForAuthorization:a,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let a={};try{const s=JSON.parse(i);a=s.error||s}catch{a={message:i}}const o=a?.message||i;throw x(r)?new N(`No order found for id ${n}. ${o}.`):In(r)?new W(`You are forbidden to interact with order with id ${n}. ${o}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(a=>({orderId:a.orderId,creationDate:a.creationDate,clientName:a.clientName,items:a.items,totalValue:a.totalValue,status:a.status,statusDescription:a.statusDescription,ShippingEstimatedDate:a.ShippingEstimatedDate,customFields:a.customFields,currencyCode:a.currencyCode})),paging:i.paging}},listCreditCards:async(e,n,t)=>{const{clients:{commerce:r}}=t;return{list:(await r.savedCards.listCreditCards())?.map(a=>({accountId:a.accountId,bin:a.bin,cardNumber:a.cardNumber,cardLabel:a.cardLabel,paymentSystem:a.paymentSystem,paymentSystemName:a.paymentSystemName,isDefault:a.isDefault,isActive:a.isActive,origin:a.origin}))}},hasAdHocCardAccess:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=z($(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:Pi}).catch(()=>null);return typeof c=="boolean"?c:!0},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const u=[d.firstName,d.lastName].filter(Boolean).join(" ");u&&o.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?o.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:a}}=t,s=z($(i?.cookie??"",r))?.userId??"",[c,d,u]=await Promise.all([a.session("").catch(()=>null),s?a.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?a.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:a}}=t,o=z($(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.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)||o?.customerId?.trim()||"";let h=null;if(f)try{h=await a.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:Bn(h,d)||v||"",email:d?.email?.value||p?.storeUserEmail?.value||"",id:d?.id?.value||p?.customerId?.value||o?.customerId?.trim()||""}}const s=await a.licenseManager.getUserById({userId:o?.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:a}}=t,o=await a.session("").catch(()=>null),s=$(i?.cookie??"",r);let c=null;try{c=s?z(s):null}catch{c=null}const d=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new W("You are not allowed to list contracts for this organization unit");const u=Gr(o?.namespaces.shopper),p=Ke(o)||c?.customerId?.trim()||"";return Xr(u,p)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:wi,orderFormItems:Di,recommendations:Ci},Ui={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Ri=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Fi={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:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(u=>{const p=pe(u.items);return p&&F(p,u)}).filter(u=>!!u),{searches:d}=o;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=pe(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),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!Ri(d,o,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},Ni={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Li=["bd","d","h","m"],Bi=e=>Li.includes(e),$i={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"}},Vn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Bi(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return $i[t][a].replace("#",n)??""},Mi={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Vn(e.shippingEstimate):""},nn="skuvariation";function tn(e,n){const t=`${nn}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===nn);return i||e[0]}function zi(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function rn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function qi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Vi(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function xi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>Vi(i.value,a.value));return n}function ji(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=tn(a.images,n),u={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(u):r[o.name]=[u];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const u=tn(a.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]})}),xi(r)}const Wi={activeVariations:e=>rn(e.variations),allVariantsByName:e=>qi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>zi(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 ji(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},Gi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Hi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=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?Vn(u?.shippingEstimate):"",S=u?.shippingEstimateDate||"",O=u?.addressId||"",w=u?.itemIndex??0,C=t?.[w],_=C?.seller||"",I=`${p}|${f}|${h}|${_}|${g}|${S}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(b=>b?.addressId===O),A=`${Gi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:P}=Xi(C?.priceTags??[]),R=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(E??0);return d[I]||(d[I]={selectedSla:p,deliveryChannel:f,deliveryCompany:h,deliveryWindow:v,shippingEstimate:g,shippingEstimateDate:S,seller:_,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[I]&&(d[I].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:P??[],taxPriceTagsTotal:E??0,tax:C?.tax||0,total:R}),d[I].quantityOfDifferentItems=(d[I].quantityOfDifferentItems??0)+1,d[I].total=(d[I].total??0)+R),d},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function Xi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,a)=>i+(a.rawValue?a.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Yi={StoreCollection:An,StoreAggregateOffer:sr,StoreProduct:yi,StoreSeo:Ni,StoreFacet:fr,StoreFacetBoolean:Sr,StoreFacetRange:yr,StoreFacetValueBoolean:Ir,StoreOffer:si,StoreAggregateRating:cr,StoreReview:Ui,StoreProductGroup:vi,StoreSearchResult:Fi,StorePropertyValue:Oi,SkuVariants:Wi,ShippingSLA:Mi,UserOrderResult:Hi,ObjectOrString:oi,Query:ki,Mutation:ri},Ji=()=>Yi,Ki=`"""
7
+ More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},qr=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:$n(e,n)!==r},Vr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Ye=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=Fn(e,n);if(r){const a=Ur(e,n,i),s=a||kr(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},xr=(e,n)=>{if(!e)return"";const r=ne.parse(e)[n];return r?r.split("=")[1]:""},Je=(e,n)=>{const t=Tr(e.storage.channel,n.salesChannel);return t?(de(e,t),n.salesChannel?String(n.salesChannel):null):null},Ke=(e,n,t,r)=>r?we(e,n,t,r):null,jr=async(e,{cart:{order:n},session:t},r)=>{const i=xr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&de(r,s),c&&be(r,c);const u=i||void 0,d=await a.checkout.orderForm({id:u,channel:r.storage.channel,preserveSalesChannel:!!u}),g=d.orderFormId;d.messages.length!==0&&await Vr(g,r);const f=ne.parse(r?.headers?.cookie??"")?.vtex_session,h=q(f),{acceptedOffer:b,shouldSplitItem:l}=n;if(qr(d,h)){const O=Je(r,d),L=await Xe(d,a,h).then(He);if(g)return we(L,o,l,O)}const m=Je(r,d),S=Ge(b),v=Ge(d.items.map(ue)),w=Array.from(v.entries()),C=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:I}=C.reduce((O,[L,Te])=>{const _e=v.get(L);if(!_e)return Te.forEach(Y=>O.itemsToAdd.push(Y)),O;const[ie,...Gn]=_e;if(Bn(d.items,ie.itemOffered.sku)||Ln(d.items,ie.itemOffered.sku))return O.itemsToUpdate.push(ie),O;const Hn=Te.reduce((Y,Xn)=>Y+Xn.quantity,0);return O.itemsToUpdate.push({...ie,quantity:Hn}),Gn.forEach(Y=>O.itemsToUpdate.push({...Y,quantity:0})),O},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([O])=>!S.has(O)).flatMap(([,O])=>O.map(L=>({...L,quantity:0}))),A=[..._,...I,...D].map(Mr),{updateShipping:E}=t?Fn(d,t):{updateShipping:!1};if(A.length===0&&!E)return Ke(d,o,l,m);let P;A.length>0?P=await a.checkout.updateOrderFormItems({id:d.orderFormId,orderItems:A,shouldSplitItem:l}).then(O=>Ye(O,t,r)):P=await Ye(d,t,r),P=await Promise.resolve(P).then(O=>{if(t?.marketingData){const L={...O.marketingData,...t.marketingData};return a.checkout.marketingData({id:d.orderFormId,marketingData:L})}return O}).then(O=>c&&O.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:O.orderFormId,clientPreferencesData:{...O.clientPreferencesData,locale:c}}):O).then(O=>Xe(O,a,h)).then(He);const R=Ee(d.messages,P.messages);return zr(n,P)&&R?Ke(P,o,l,m):we(P,o,l,m)};function Wr(e,n,t,r){const i=e.hasOnlyDefaultSalesChannel===!1,a=n??void 0,o=t??e.regionId;return te.stringify({salesChannel:i?e.salesChannel||a:a??e.salesChannel,regionId:o??void 0,seller:r,hasOnlyDefaultSalesChannel:i?!1:!a})}const Gr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Hr=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"},Xr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Hr):[]},Yr=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Qe=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Jr=(e,n="")=>{const t=n.trim();return e.filter(Yr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Mn=(e,n)=>{const t=Gr(e);return t||(n?.firstName?.value??"").trim()};async function Kr(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 Qr(e,n,t,r,i,a){const o=new URLSearchParams(e);return o.has("facets")&&o.delete("facets"),o.set("sc",o.get("sc")??n.salesChannel),t&&o.set("postalCode",t),r&&o.set("country",r),i&&o.set("geoCoordinates",`${i.longitude},${i.latitude}`),o.set("locale",a),o}function Zr(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 ei(e,n,t){const r=q($(n??"",t));let i=!1;if(r)try{i=(await e.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(a){console.warn("JWT validation failed:",a),i=!1}return{isRepresentative:i?!!r?.isRepresentative:!1,customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function ni(e,n,t,r,i,a){return!n.seller||!(t||r)?void 0:(await e.commerce.checkout.region({postalCode:t,geoCoordinates:r,country:i,salesChannel:a}))?.[0]?.sellers.find(c=>n.seller===c.id)?.id}function Ze(e){return typeof e?.value=="string"?e.value:""}function ti(e){if(!e.isRepresentative)return null;const n=Ze(e.shopper?.firstName),t=Ze(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:Mn(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ri(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ii=async(e,{session:n,search:t},{clients:r,headers:i,account:a})=>{const o=te.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let u=n.city??null,d=n.geoCoordinates??null;if((!u||!d)&&s!==""&&c!==""){const P=await Kr(r,c,s);u=P.city,d=P.geoCoordinates}const f=Qr(t,o,s,c,d,n.locale),h=Zr(f,n.marketingData),{isRepresentative:b,customerId:l,unitId:p}=await ei(r,i?.cookie,a),m=await r.commerce.session(f.toString()).catch(()=>null),S=m?.namespaces.profile??null,v=m?.namespaces.shopper??null,w=m?.namespaces.store??null,C=m?.namespaces.authentication??null,_=m?.namespaces.checkout??null,I=m?.namespaces.public??null;let D=null;if(b&&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 A=await ni(r,o,s,d,c,f.get("sc")??o.salesChannel),E={...n,currency:{code:w?.currencyCode?.value??n.currency.code,symbol:w?.currencySymbol?.value??n.currency.symbol},country:w?.countryCode?.value??c,channel:Wr(o,w?.channel?.value,_?.regionId?.value,A),b2b:ti({isRepresentative:b,authentication:C,shopper:v,publicData:I,profile:S,contract:D,customerId:l,unitId:p}),marketingData:h,person:ri(S),geoCoordinates:d?.latitude&&d?.longitude&&d||null,city:u};return Ee(n,E)?null:E},ai={validateCart:jr,validateSession:ii,subscribeToNewsletter:Pr,cancelOrder:br,processOrderAuthorization:wr,uploadFileToOrderEntry:Er,startOrderEntryOperation:Dr,startRecommendationSession:Ar};var De;(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"})(De||(De={}));const oi=e=>typeof e=="string"?zn(e):null;function zn(e){try{return JSON.parse(e)}catch{return e}}const si=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,ci=new ce.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:oi,serialize:si,parseLiteral(e){return e.kind===De.STRING?zn(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,U=e=>"skuName"in e,li={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??"":U(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>k(e)?Me(M(e)):U(e)?Me(sr(e.availability)):null,seller:(e,n,t)=>k(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:U(e)?{identifier:e.seller}:null,price:e=>k(e)?H(e):U(e)?e.sellingPrice/100:null,priceWithTaxes:e=>k(e)?V(H(e),e?.Tax,e.product.unitMultiplier):U(e)?V(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>k(e)?or(e):U(e)?e.sellingPrice/100:null,listPrice:e=>k(e)?e.ListPrice??0:U(e)?e.listPrice/100:null,listPriceWithTaxes:e=>k(e)?V(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):U(e)?V(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>k(e)?e.product:U(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>k(e)?e.AvailableQuantity??0:U(e)?e.quantity:null,isGift:e=>U(e)?e.isGift??!1:null,priceToken:e=>k(e)?e.PriceToken??null:null},di=({linkText:e})=>`/${e}/p`,ui=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),pi=1e11,gi=e=>/^\d+$/.test(e),mi=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,hi=e=>{if(!gi(e))return new Date(mi.test(e)?`${e}Z`:e);const n=Number(e);return new Date(n>=pi?n:n*1e3)},fi=e=>{if(e==null)return"";const n=String(e).trim();if(n==="")return"";const t=hi(n);return Number.isNaN(t.getTime())?"":t.toISOString().slice(0,10)},Si={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,en=(e,n)=>`/${oe(e,n)}/p`,yi=e=>Array.isArray(e)&&e.length>0?e:null;function Ae(e){return e.replace(/^\/+|\/+$/g,"")}async function se(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,a=i.get(r);if(a)return a;const o=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch(s){return console.warn(`[getLocalizedProductEntry] failed to load product ${n} for locale ${t}:`,s),null}})();return i.set(r,o),o}const Ii=(e,n)=>{const t=e.findIndex(r=>Ae(r).split("/").at(-1)===n);return t<0?0:t},vi={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:di(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:u}=e,d=Ii(s,o),g=r[d],f=Ae(g).split("/"),h=t.storage.locale;if(W(t)&&h){const b=await se(t,c,h);if(b){const l=new Set(Ae(s[d]).split("/").filter(Boolean)),p=b.categories.filter(S=>l.has(S.id.toString())).sort((S,v)=>S.fullPath.split("/").length-v.fullPath.split("/").length);if(p.length===f.length)return{itemListElement:[...p.map((S,v)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:v+1})),{name:i,item:en(b.linkId,u),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((b,l)=>{const p=`/${f.slice(0,l+1).map(le).join("/")}/`;return{name:b,item:p,position:l+1}}),{name:i,item:en(a,u),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(yi(e)??[Si]).map(({imageUrl:s,imageText:c,imageLabel:u})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:u}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.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=>ui({offer:n.commertialOffer,seller:n,product:e})).sort(Pn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:re.specification}))),i=n.map(Un),a=t.map(_r);return[...r,...i,...a]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>fi(e),advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!W(t))return null;const r=Ct(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=await se(t,i,o);if(!s?.availableLinkIds)return null;const{availableLinkIds:c}=s;return r.map(u=>{const d=c[u];return d?{locale:u,slug:oe(d,a)}:null}).filter(u=>u!==null)},defaultLocaleSlug:async(e,n,t)=>{if(!W(t))return null;const r=wt(t);if(!r)return null;const{productId:i,linkText:a}=e.isVariantOf,o=e.itemId,c=(await se(t,i,t.storage.locale))?.availableLinkIds?.[r]??a;return oe(c,o)}},Oi=new Set(["allSpecifications"]),bi={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=>!Oi.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},Ci={propertyID:e=>e.propertyID||Rn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},pe=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Oe(n,({offer:r},{offer:i})=>Pn(r,i));return t?t.sku:e[0]},qn=e=>e!==""&&!Number.isNaN(Number(e)),wi=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Di=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!wi.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 u=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:d,correlationId:g}=u;return{products:(u.products??[]).map(h=>{const b=pe(h.items);return b?F(b,h):null}).filter(h=>!!h),correlationId:g,campaign:d}},nn={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:""},Ai=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Pi=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 Ei(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await se(e,t,r))?.linkId===i}const Vn="Invalid SkuId",xn="Slug was set but the fetched sku does not satisfy the slug condition.",Ti="UseAdHocCard",_i=e=>j(e)||e instanceof Error&&(e.message===Vn||e.message.startsWith(xn));async function ki(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||W(e)&&r&&qn(t.split("-").pop()??"")&&await Ei(e,t,a,r)))throw new Error(`${xn} slug: ${t}, linkText: ${i}`)}async function Ui(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 a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new N(`No product found for id ${i.id}`);return F(pe(a.items),a)}const Ri={product:async(e,{locator:n},t)=>{const r=We(n),i=je(n),a=Sr(n),o=fr(n);r&&de(t,r),i&&be(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!qn(c))throw new Error(Vn);const u=await s.load(c);return await ki(t,u,o,i),u}catch(c){if(!_i(c))throw c;return Ui(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:Cn(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=We(a),u=je(a),d=hr(a);c&&de(s,c),u&&be(s,u);const g=t?Number(t):0,f={page:Math.ceil(g/n)||0,count:n,query:i??void 0,sort:nn[r??"score_desc"]??nn.score_desc,selectedFacets:a?.flatMap(Ve)??[],sponsoredCount:o??void 0};if(d){const l=(await s.clients.commerce.catalog.products.crossselling({type:Tn[d.key],productId:d.value})).map(m=>m.productId).slice(0,n),p=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:p}}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,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/n),count:n}),s=o.products.flatMap(c=>c.items.map(u=>F(u,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,u)=>({node:c,cursor:(a+u).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>F(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],u=(h,b)=>{c.push({id:h.id,name:h.name,fatherCategoryId:b,linkId:le(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)u(l,h.id)};for(const h of s)u(h,null);const f=[...o.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:le(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!En.slug(h,null,r,null));return{pageInfo:{hasNextPage:f.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,f.length-a)-1).toString(),totalCount:f.length},edges:f.slice(a,a+n).map((h,b)=>({node:h,cursor:(a+b).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:n,items:t,postalCode:r}),o.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(Ve)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:u,sellers:d}=c;return{id:u,sellers:d}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(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 a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=_n(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")&&!!a,ruleForAuthorization:a,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let a={};try{const s=JSON.parse(i);a=s.error||s}catch{a={message:i}}const o=a?.message||i;throw j(r)?new N(`No order found for id ${n}. ${o}.`):vn(r)?new G(`You are forbidden to interact with order with id ${n}. ${o}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(a=>({orderId:a.orderId,creationDate:a.creationDate,clientName:a.clientName,items:a.items,totalValue:a.totalValue,status:a.status,statusDescription:a.statusDescription,ShippingEstimatedDate:a.ShippingEstimatedDate,customFields:a.customFields,currencyCode:a.currencyCode})),paging:i.paging}},listCreditCards:async(e,n,t)=>{const{clients:{commerce:r}}=t;return{list:(await r.savedCards.listCreditCards())?.map(a=>({accountId:a.accountId,bin:a.bin,cardNumber:a.cardNumber,cardLabel:a.cardLabel,paymentSystem:a.paymentSystem,paymentSystemName:a.paymentSystemName,isDefault:a.isDefault,isActive:a.isActive,origin:a.origin}))}},hasAdHocCardAccess:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=q($(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:Ti}).catch(()=>null);return typeof c=="boolean"?c:!0},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[u]=await r.masterData.getShopperById({userId:c});if(u){const d=[u.firstName,u.lastName].filter(Boolean).join(" ");d&&o.set(c,d)}}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?o.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:a}}=t,s=q($(i?.cookie??"",r))?.userId??"",[c,u,d]=await Promise.all([a.session("").catch(()=>null),s?a.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?a.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),g=u?.[0],f=c?.namespaces.authentication??null,h=`${(g?.firstName??"").trim()} ${(g?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:g?.phone??"",role:d?.Roles?.map(b=>b.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=q($(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const u=c.namespaces.profile??null,d=c.namespaces.shopper??null,g=c.namespaces.authentication??null,f=Qe(c)||o?.customerId?.trim()||"";let h=null;if(f)try{h=await a.masterData.getContractById({contractId:f})}catch(p){console.error(`Error while getting contract data for contract ID (${f}).`,p)}const b=`${(d?.firstName?.value??"").trim()} ${(d?.lastName?.value??"").trim()}`.trim();return{name:Mn(h,u)||b||"",email:u?.email?.value||g?.storeUserEmail?.value||"",id:u?.id?.value||g?.customerId?.value||o?.customerId?.trim()||""}}const s=await a.licenseManager.getUserById({userId:o?.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:a}}=t,o=await a.session("").catch(()=>null),s=$(i?.cookie??"",r);let c=null;try{c=s?q(s):null}catch{c=null}const u=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!u||u!==n)throw new G("You are not allowed to list contracts for this organization unit");const d=Xr(o?.namespaces.shopper),g=Qe(o)||c?.customerId?.trim()||"";return Jr(d,g)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:Ai,orderFormItems:Pi,recommendations:Di},Fi={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Ni=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Li={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(g=>({value:g.term,count:g.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(d=>{const g=pe(d.items);return g&&F(g,d)}).filter(d=>!!d),{searches:u}=o;return{terms:u.map(d=>({value:d.term,count:d.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=pe(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),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(u=>!a||!Ni(u,o,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},Bi={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},$i=["bd","d","h","m"],Mi=e=>$i.includes(e),zi={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"}},jn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Mi(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return zi[t][a].replace("#",n)??""},qi={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?jn(e.shippingEstimate):""},tn="skuvariation";function rn(e,n){const t=`${tn}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===tn);return i||e[0]}function Vi(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,u)=>u.name===n?c:c+`-${u.name}-${u.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function an(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function xi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function ji(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Wi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>ji(i.value,a.value));return n}function Gi(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const u=rn(a.images,n),d={src:u.imageUrl,alt:u.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(d):r[o.name]=[d];return}a.variations.forEach(c=>{const u=`${c.name}-${c.values[0]}`;if(i.has(u))return;i.add(u);const d=rn(a.images,c.name),g={src:d.imageUrl,alt:d.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(g):r[c.name]=[g]})}),Wi(r)}const Hi={activeVariations:e=>an(e.variations),allVariantsByName:e=>xi(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=an(e.variations)[t];return Gi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},Xi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Yi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((u,d)=>{const g=d?.selectedSla||"",f=d?.selectedDeliveryChannel||d?.deliveryChannel||"",h=d?.deliveryCompany||"",b=d?.deliveryWindow,l=d?.pickupStoreInfo,p=d?.shippingEstimate||"",m=d?.shippingEstimate?jn(d?.shippingEstimate):"",S=d?.shippingEstimateDate||"",v=d?.addressId||"",w=d?.itemIndex??0,C=t?.[w],_=C?.seller||"",I=`${g}|${f}|${h}|${_}|${p}|${S}|${v}|${b?.startDateUtc}|${b?.endDateUtc}`,D=i?.find(O=>O?.addressId===v),A=`${Xi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:P}=Ji(C?.priceTags??[]),R=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(E??0);return u[I]||(u[I]={selectedSla:g,deliveryChannel:f,deliveryCompany:h,deliveryWindow:b,shippingEstimate:p,shippingEstimateDate:S,seller:_,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),u[I]&&(u[I].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:P??[],taxPriceTagsTotal:E??0,tax:C?.tax||0,total:R}),u[I].quantityOfDifferentItems=(u[I].quantityOfDifferentItems??0)+1,u[I].total=(u[I].total??0)+R),u},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function Ji(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,a)=>i+(a.rawValue?a.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Ki={StoreCollection:En,StoreAggregateOffer:lr,StoreProduct:vi,StoreSeo:Bi,StoreFacet:yr,StoreFacetBoolean:Ir,StoreFacetRange:vr,StoreFacetValueBoolean:Or,StoreOffer:li,StoreAggregateRating:dr,StoreReview:Fi,StoreProductGroup:bi,StoreSearchResult:Li,StorePropertyValue:Ci,SkuVariants:Hi,ShippingSLA:qi,UserOrderResult:Yi,ObjectOrString:ci,Query:Ri,Mutation:ai},Qi=()=>Ki,Zi=`"""
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
- `,Qi=`"""
54
+ `,ea=`"""
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
- `,Zi=`"""
79
+ `,na=`"""
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
- `,ea=`"""
108
+ `,ta=`"""
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
- `,na=`"""
121
+ `,ra=`"""
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
- `,ta=`"""
130
+ `,ia=`"""
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
- `,ra=`"""
139
+ `,aa=`"""
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
- `,ia=`"""
170
+ `,oa=`"""
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
- `,aa=`"""
207
+ `,sa=`"""
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
@@ -301,9 +301,20 @@ type StoreCollection {
301
301
  type: StoreCollectionType!
302
302
  """
303
303
  Localized versions of this collection for all available locales.
304
- Only populated when localization is enabled.
304
+ Only announces slugs the catalog has registered for each locale, so it is safe
305
+ to build hreflang annotations from. Only populated when localization is
306
+ enabled.
305
307
  """
306
308
  otherLocales: [StoreCollectionLocale!]
309
+ """
310
+ Slug the catalog resolves for the requested locale, lowercased.
311
+ Meant for the page's canonical URL: \`slug\` echoes the path the shopper
312
+ visited, and by-linkid matches case-insensitively, so without this every
313
+ casing variant would claim to be canonical. Unlike \`otherLocales\`, it may fall
314
+ back to a slug registered for another locale, so it must never be used to
315
+ build hreflang annotations.
316
+ """
317
+ canonicalSlug: String
307
318
  }
308
319
 
309
320
  """
@@ -319,7 +330,7 @@ type StoreCollectionLocale {
319
330
  """
320
331
  slug: String!
321
332
  }
322
- `,oa=`"""
333
+ `,ca=`"""
323
334
  Delivery Promise badge.
324
335
  """
325
336
  type DeliveryPromiseBadge {
@@ -328,7 +339,7 @@ type DeliveryPromiseBadge {
328
339
  """
329
340
  typeName: String
330
341
  }
331
- `,sa=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
342
+ `,la=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
332
343
 
333
344
  """
334
345
  Search facet range information.
@@ -405,7 +416,7 @@ type StoreFacetValueBoolean {
405
416
  """
406
417
  quantity: Int
407
418
  }
408
- `,ca=`"""
419
+ `,da=`"""
409
420
  Image.
410
421
  """
411
422
  type StoreImage {
@@ -432,7 +443,7 @@ input IStoreImage {
432
443
  """
433
444
  alternateName: String!
434
445
  }
435
- `,la=`type Mutation {
446
+ `,ua=`type Mutation {
436
447
  """
437
448
  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
449
  """
@@ -474,7 +485,7 @@ input IStoreImage {
474
485
  """
475
486
  startRecommendationSession: Boolean!
476
487
  }
477
- `,da=`"""
488
+ `,pa=`"""
478
489
  Newsletter information.
479
490
  """
480
491
  type PersonNewsletter {
@@ -497,8 +508,8 @@ input IPersonNewsletter {
497
508
  """
498
509
  email: String!
499
510
  }
500
- `,ua=`scalar ObjectOrString
501
- `,pa=`"""
511
+ `,ga=`scalar ObjectOrString
512
+ `,ma=`"""
502
513
  Offer information.
503
514
  """
504
515
  type StoreOffer {
@@ -591,7 +602,7 @@ input IStoreOffer {
591
602
  """
592
603
  priceToken: String
593
604
  }
594
- `,ga=`"""
605
+ `,ha=`"""
595
606
  Information of a specific order.
596
607
  """
597
608
  type StoreOrder {
@@ -632,7 +643,7 @@ input IStoreOrder {
632
643
  """
633
644
  shouldSplitItem: Boolean
634
645
  }
635
- `,ma=`"""
646
+ `,fa=`"""
636
647
  Commercial Authorization response.
637
648
  """
638
649
  type CommercialAuthorizationResponse {
@@ -1031,7 +1042,7 @@ type ProcessOrderAuthorizationRule {
1031
1042
  """
1032
1043
  rule: CommercialAuthorizationRule!
1033
1044
  }
1034
- `,ha=`"""
1045
+ `,Sa=`"""
1035
1046
  Input for uploading a file to the Order Entry Service.
1036
1047
  The file is transmitted as a Base64-encoded string so it can travel
1037
1048
  through the standard GraphQL JSON pipeline without multipart support.
@@ -1092,7 +1103,7 @@ type StoreOrderFormCartItem {
1092
1103
  seller: String!
1093
1104
  unitMultiplier: Float
1094
1105
  }
1095
- `,fa=`"""
1106
+ `,ya=`"""
1096
1107
  Organization.
1097
1108
  """
1098
1109
  type StoreOrganization {
@@ -1129,7 +1140,7 @@ type StoreContract {
1129
1140
  """
1130
1141
  isActive: Boolean!
1131
1142
  }
1132
- `,Sa=`"""
1143
+ `,Ia=`"""
1133
1144
  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.
1134
1145
  """
1135
1146
  type StorePageInfo {
@@ -1154,7 +1165,7 @@ type StorePageInfo {
1154
1165
  """
1155
1166
  totalCount: Int!
1156
1167
  }
1157
- `,ya=`"""
1168
+ `,va=`"""
1158
1169
  Input type for setting a new password.
1159
1170
  """
1160
1171
  input ISetPassword {
@@ -1197,7 +1208,7 @@ type SetPasswordResponse {
1197
1208
  """
1198
1209
  message: String
1199
1210
  }
1200
- `,Ia=`"""
1211
+ `,Oa=`"""
1201
1212
  Client profile data.
1202
1213
  """
1203
1214
  type StorePerson {
@@ -1240,7 +1251,7 @@ input IStorePerson {
1240
1251
  """
1241
1252
  familyName: String!
1242
1253
  }
1243
- `,va=`type PickupPointAddress {
1254
+ `,ba=`type PickupPointAddress {
1244
1255
  """
1245
1256
  Address city.
1246
1257
  """
@@ -1319,7 +1330,7 @@ type PickupPoints {
1319
1330
  """
1320
1331
  pickupPointsHash: String
1321
1332
  }
1322
- `,Oa=`"""
1333
+ `,Ca=`"""
1323
1334
  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.
1324
1335
  """
1325
1336
  type StoreProduct {
@@ -1495,7 +1506,7 @@ input IStoreProduct {
1495
1506
  """
1496
1507
  additionalProperty: [IStorePropertyValue!]
1497
1508
  }
1498
- `,ba=`"""
1509
+ `,wa=`"""
1499
1510
  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.
1500
1511
  """
1501
1512
  type StoreProductGroup {
@@ -1522,7 +1533,7 @@ type StoreProductGroup {
1522
1533
  """
1523
1534
  skuVariants: SkuVariants
1524
1535
  }
1525
- `,Ca=`type Profile {
1536
+ `,Da=`type Profile {
1526
1537
  """
1527
1538
  Collection of user's address
1528
1539
  """
@@ -1583,7 +1594,7 @@ type ProfileAddress {
1583
1594
  """
1584
1595
  geoCoordinate: [Float]
1585
1596
  }
1586
- `,wa=`"""
1597
+ `,Aa=`"""
1587
1598
  Properties that can be associated with products and products groups.
1588
1599
  """
1589
1600
  type StorePropertyValue {
@@ -1623,7 +1634,7 @@ input IStorePropertyValue {
1623
1634
  """
1624
1635
  valueReference: ObjectOrString!
1625
1636
  }
1626
- `,Da=`"""
1637
+ `,Pa=`"""
1627
1638
  Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
1628
1639
  """
1629
1640
  type StoreProductEdge {
@@ -2272,7 +2283,7 @@ type StoreAccountProfile {
2272
2283
  email: String
2273
2284
  id: String
2274
2285
  }
2275
- `,Aa=`"""
2286
+ `,Ea=`"""
2276
2287
  Summary of a quote returned in list results.
2277
2288
  """
2278
2289
  type UserQuoteSummary {
@@ -2337,7 +2348,7 @@ type UserQuoteListPaging {
2337
2348
  """
2338
2349
  perPage: Int!
2339
2350
  }
2340
- `,Pa=`type RecommendationResponse {
2351
+ `,Ta=`type RecommendationResponse {
2341
2352
  products: [StoreProduct!]!
2342
2353
  correlationId: String!
2343
2354
  campaign: RecommendationCampaign!
@@ -2348,7 +2359,7 @@ type RecommendationCampaign {
2348
2359
  title: String
2349
2360
  type: String!
2350
2361
  }
2351
- `,Ea=`"""
2362
+ `,_a=`"""
2352
2363
  Information of a given review rating.
2353
2364
  """
2354
2365
  type StoreReviewRating {
@@ -2375,7 +2386,7 @@ type StoreReview {
2375
2386
  """
2376
2387
  author: StoreAuthor!
2377
2388
  }
2378
- `,Ta=`"""
2389
+ `,ka=`"""
2379
2390
  Whether a saved card is personally owned by the buyer or shared by their
2380
2391
  Organization/Contract. Resolved server-side by the Saved-cards service from
2381
2392
  the buyer's \`useAdHocCard\` role — never inferred client-side.
@@ -2439,7 +2450,7 @@ type SavedCardListResult {
2439
2450
  """
2440
2451
  list: [SavedCard!]
2441
2452
  }
2442
- `,_a=`"""
2453
+ `,Ua=`"""
2443
2454
  Search Engine Optimization (SEO) tags data.
2444
2455
  """
2445
2456
  type StoreSeo {
@@ -2460,7 +2471,7 @@ type StoreSeo {
2460
2471
  """
2461
2472
  canonical: String!
2462
2473
  }
2463
- `,ka=`"""
2474
+ `,Ra=`"""
2464
2475
  Currency information.
2465
2476
  """
2466
2477
  type StoreCurrency {
@@ -2735,7 +2746,7 @@ input IStoreSession {
2735
2746
  """
2736
2747
  refreshAfter: String
2737
2748
  }
2738
- `,Ua=`"""
2749
+ `,Fa=`"""
2739
2750
  Shipping Simulation item input.
2740
2751
  """
2741
2752
  input IShippingItem {
@@ -3066,7 +3077,7 @@ type MessageFields {
3066
3077
  """
3067
3078
  skuName: String
3068
3079
  }
3069
- `,Ra=`type SkuVariants {
3080
+ `,Na=`type SkuVariants {
3070
3081
  """
3071
3082
  SKU property values for the current SKU.
3072
3083
  """
@@ -3161,7 +3172,7 @@ Example:
3161
3172
  \`\`\`
3162
3173
  """
3163
3174
  scalar FormattedVariants
3164
- `,Fa=`"""
3175
+ `,La=`"""
3165
3176
  Status used to indicate a message type. For instance, a shopping cart informative or error message.
3166
3177
  """
3167
3178
  enum StoreStatus {
@@ -3169,7 +3180,7 @@ enum StoreStatus {
3169
3180
  WARNING
3170
3181
  ERROR
3171
3182
  }
3172
- `,Na=`scalar JSONObject
3183
+ `,Ba=`scalar JSONObject
3173
3184
 
3174
3185
  type UserOrder {
3175
3186
  orderId: String
@@ -3993,4 +4004,4 @@ type UserOrderBudgetAllocationLinkedEntity {
3993
4004
  type: String
3994
4005
  id: String
3995
4006
  }
3996
- `,La=Object.assign({"./address.graphql":Ki,"./advertisement.graphql":Qi,"./aggregateOffer.graphql":Zi,"./aggregateRating.graphql":ea,"./author.graphql":na,"./brand.graphql":ta,"./breadcrumb.graphql":ra,"./cart.graphql":ia,"./collection.graphql":aa,"./deliveryPromisesBadge.graphql":oa,"./facet.graphql":sa,"./image.graphql":ca,"./mutation.graphql":la,"./newsletter.graphql":da,"./objectOrString.graphql":ua,"./offer.graphql":pa,"./order.graphql":ga,"./orderCommercialAuthorizaton.graphql":ma,"./orderEntry.graphql":ha,"./organization.graphql":fa,"./pageInfo.graphql":Sa,"./password.graphql":ya,"./person.graphql":Ia,"./pickupPoints.graphql":va,"./product.graphql":Oa,"./productGroup.graphql":ba,"./profile.graphql":Ca,"./propertyValue.graphql":wa,"./query.graphql":Da,"./quote.graphql":Aa,"./recommendation.graphql":Pa,"./review.graphql":Ea,"./savedCard.graphql":Ta,"./seo.graphql":_a,"./session.graphql":ka,"./shipping.graphql":Ua,"./skuVariants.graphql":Ra,"./status.graphql":Fa,"./userOrder.graphql":Na}),Ba=ce.print(Object.values(La).map(e=>ce.parse(e)).reduce((e,n)=>an.mergeTypeDefs([e,n],{sort:!0}))),xn=Ba,$a=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=Ht(e,n),n.loaders=rr(e,n),n);function Ma(){const e=Ji(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,rt(a,`${t}(${i})`)]));return n}function za(e){const t=fn([hn,mn])(Ma(),xn);return e&&ce.isSchema(e)?on.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=mn;exports.BadRequestError=T;exports.CacheControlDirective=hn;exports.CardOrigin=sn;exports.CommercialAuthorizationStatus=cn;exports.FastStoreError=H;exports.ForbiddenError=W;exports.GraphqlVtexContextFactory=$a;exports.GraphqlVtexSchema=za;exports.NotFoundError=N;exports.StoreCollectionType=ln;exports.StoreFacetType=dn;exports.StoreSort=un;exports.StoreStatus=pn;exports.UnauthorizedError=Z;exports.UserOrderInvoiceType=gn;exports.isBadRequestError=at;exports.isFastStoreError=it;exports.isForbiddenError=In;exports.isNotFoundError=x;exports.isUnauthorizedError=ot;exports.stringifyCacheControl=et;exports.typeDefs=xn;exports.withDirectives=fn;
4007
+ `,$a=Object.assign({"./address.graphql":Zi,"./advertisement.graphql":ea,"./aggregateOffer.graphql":na,"./aggregateRating.graphql":ta,"./author.graphql":ra,"./brand.graphql":ia,"./breadcrumb.graphql":aa,"./cart.graphql":oa,"./collection.graphql":sa,"./deliveryPromisesBadge.graphql":ca,"./facet.graphql":la,"./image.graphql":da,"./mutation.graphql":ua,"./newsletter.graphql":pa,"./objectOrString.graphql":ga,"./offer.graphql":ma,"./order.graphql":ha,"./orderCommercialAuthorizaton.graphql":fa,"./orderEntry.graphql":Sa,"./organization.graphql":ya,"./pageInfo.graphql":Ia,"./password.graphql":va,"./person.graphql":Oa,"./pickupPoints.graphql":ba,"./product.graphql":Ca,"./productGroup.graphql":wa,"./profile.graphql":Da,"./propertyValue.graphql":Aa,"./query.graphql":Pa,"./quote.graphql":Ea,"./recommendation.graphql":Ta,"./review.graphql":_a,"./savedCard.graphql":ka,"./seo.graphql":Ua,"./session.graphql":Ra,"./shipping.graphql":Fa,"./skuVariants.graphql":Na,"./status.graphql":La,"./userOrder.graphql":Ba}),Ma=ce.print(Object.values($a).map(e=>ce.parse(e)).reduce((e,n)=>on.mergeTypeDefs([e,n],{sort:!0}))),Wn=Ma,za=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=Yt(e,n),n.loaders=ar(e,n),n);function qa(){const e=Qi(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,at(a,`${t}(${i})`)]));return n}function Va(e){const t=Sn([fn,hn])(qa(),Wn);return e&&ce.isSchema(e)?sn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=hn;exports.BadRequestError=T;exports.CacheControlDirective=fn;exports.CardOrigin=cn;exports.CommercialAuthorizationStatus=ln;exports.FastStoreError=X;exports.ForbiddenError=G;exports.GraphqlVtexContextFactory=za;exports.GraphqlVtexSchema=Va;exports.NotFoundError=N;exports.StoreCollectionType=dn;exports.StoreFacetType=un;exports.StoreSort=pn;exports.StoreStatus=gn;exports.UnauthorizedError=Z;exports.UserOrderInvoiceType=mn;exports.isBadRequestError=st;exports.isFastStoreError=ot;exports.isForbiddenError=vn;exports.isNotFoundError=j;exports.isUnauthorizedError=ct;exports.stringifyCacheControl=tt;exports.typeDefs=Wn;exports.withDirectives=Sn;