@faststore/api 4.8.1-dev.0 → 4.8.1-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,12 +1,12 @@
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"),$=require("@faststore/diagnostics"),Jn=require("isomorphic-unfetch"),ne=require("cookie"),Pe=require("p-limit"),ge=require("dataloader"),Kn=require("sanitize-html"),Ee=require("fast-deep-equal"),Qn=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 Zn=()=>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}},hn=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",fn={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 hn(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,Sn={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}})},yn=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}))},In="@faststore/api",vn="4.8.0",Ue={name:In,version:vn},it=$.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=$.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:$.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":vn,"@faststore_package_name":In,"@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=$.OTELAPI.trace.setSpan($.OTELAPI.context.active(),o);try{const c=$.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:$.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
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"),$=require("@faststore/diagnostics"),Jn=require("isomorphic-unfetch"),ne=require("cookie"),Pe=require("p-limit"),ge=require("dataloader"),Kn=require("sanitize-html"),Ee=require("fast-deep-equal"),Qn=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 Zn=()=>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}},hn=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",fn={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 hn(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,Sn={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}})},yn=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}))},In="@faststore/api",vn="4.8.1-dev.1",Ue={name:In,version:vn},it=$.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=$.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:$.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":vn,"@faststore_package_name":In,"@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=$.OTELAPI.trace.setSpan($.OTELAPI.context.active(),o);try{const c=$.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:$.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
2
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 L 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",On=e=>e?.extensions?.type==="ForbiddenError",j=e=>e?.extensions?.type==="NotFoundError",lt=`${Ue.name}@${Ue.version}`,y=async(e,n,t)=>{const r=await Jn(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 L(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"}})}},bn=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=bn(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)},Cn=e=>function(t){const r=fe(e);return r?{...t,cookie:r}:t},N=(e,n)=>{const t=bn(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=Cn(i),c=Zn(),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=N(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=N(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,wn=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 Dn(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 An(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 Pn(e){return kt.exec(e)?.[1]}function Ft(e){const n=e.find(r=>r.key==="shipping"),t=n?Pn(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"||Pn(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(An(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 An(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=Dn(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=Cn(o),u=Dn(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 L(`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)=>Kn(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 L(`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",En=(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:wn(e)})))},z=e=>Kt(e)?e.slug:ve(e)?e.linkId:e.linkId??le(e.name),Tn={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)}},_n={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 _n[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 kn(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=kn(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},Un=e=>Qn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Rn(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 Fn(e){return Un(`${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},Nn=(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))})},Ln=e=>e.valueReference===re.attachment,Ce=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Ln).map(Fn).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(Rn)},index:n}),Mr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Ln)??[]).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 Bn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function $n(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=$n(e.items,r.id)||Bn(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()}))}),Mn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Un(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:Mn(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
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 L 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",On=e=>e?.extensions?.type==="ForbiddenError",j=e=>e?.extensions?.type==="NotFoundError",lt=`${Ue.name}@${Ue.version}`,y=async(e,n,t)=>{const r=await Jn(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 L(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"}})}},Cn=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=Cn(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},N=(e,n)=>{const t=Cn(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 Ct=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=mt(i),s=bn(i),c=Zn(),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}`}),v=(l={})=>{const p=N(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},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,b={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(b)},{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:O}=m,w=s({"content-type":"application/json","X-FORWARDED-HOST":g}),b=new URLSearchParams;(!S||!l)&&b.set("sc",O),l&&b.set("refreshOutdatedData",p.toString());const _=l?`/${l}`:"",I=`${a}/api/checkout/pub/orderForm${_}?${b}`;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:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:S}),b=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:b,body:JSON.stringify({orderItems:p,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:p,key:m,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(`${a}/api/checkout/pub/orderForm/${l}/customData/${p}/${m}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:p,country:m,salesChannel:S})=>{const O=new URLSearchParams({country:m,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${O.toString()}`,b=s({"content-type":"application/json","X-FORWARDED-HOST":g});return y(w,{headers:b},{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})},storeFront:{attachedContracts:l=>{const p=s({"content-type":"application/json"});return y(`https://${e}.myvtex.com/_v/store-front/units/${encodeURIComponent(l)}/contracts/attached?details=true`,{headers:p},{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:O,clientEmail:w,perPage:b,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),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()),b&&I.append("per_page",b.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 O=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:O,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=v({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=N(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}),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=p.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 C=0;return R.set(E,C),C+=E.byteLength,R.set(l,C),C+=l.byteLength,R.set(P,C),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:p,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":g}),O=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:O},{})},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:O})=>{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),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??{},W=e=>ee(e).enabled===!0,bt=e=>Object.keys(ee(e).locales??{}),wt=e=>ee(e).defaultLocale,wn=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 Dn(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 An(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 Pn(e){return kt.exec(e)?.[1]}function Ft(e){const n=e.find(r=>r.key==="shipping"),t=n?Pn(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"||Pn(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 v=Nt(t.segmentParams,c);if(An(h,v??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 An(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=Dn(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=Dn(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,""),v=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:v})},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:v})};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(C=>P(async()=>{try{return await m({field:I,value:C,hideUnavailableItems:E,showInvisibleItems:A})}catch{return null}})))).filter(C=>C!==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:v})},topSearches:()=>{const I=Q({endpoint:"top-searches",segment:u,defaults:d()});return y(`${s}/api/intelligent-search/v1/top-searches?${I.params.toString()}`,{headers:v})},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:v})}}},Yt=(e,n)=>{const t=Xt(e,n),r=Ct(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 L(`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)=>Kn(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 L(`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",En=(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:wn(e)})))},z=e=>Kt(e)?e.slug:ve(e)?e.linkId:e.linkId??le(e.name),Tn={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)}},_n={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 _n[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},Cr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function kn(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 br(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=kn(r);return{isPendingForOtherAuthorizer:!i&&br(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)},Ce=(e,n)=>{e.storage.locale=n},Un=e=>Qn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Rn(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 Fn(e){return Un(`${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},Nn=(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))})},Ln=e=>e.valueReference===re.attachment,be=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Ln).map(Fn).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(Rn)},index:n}),Mr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Ln)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),Ge=e=>e.reduce((n,t)=>{const r=be(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 Bn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function $n(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=$n(e.items,r.id)||Bn(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}})}},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()}))}),Mn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Un(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:Mn(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}},qr=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:Mn(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}=Nn(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),B=await Xe(d,a,h).then(He);if(g)return we(B,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,[B,Te])=>{const _e=v.get(B);if(!_e)return Te.forEach(Y=>O.itemsToAdd.push(Y)),O;const[ie,...Hn]=_e;if($n(d.items,ie.itemOffered.sku)||Bn(d.items,ie.itemOffered.sku))return O.itemsToUpdate.push(ie),O;const Xn=Te.reduce((Y,Yn)=>Y+Yn.quantity,0);return O.itemsToUpdate.push({...ie,quantity:Xn}),Hn.forEach(Y=>O.itemsToUpdate.push({...Y,quantity:0})),O},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([O])=>!S.has(O)).flatMap(([,O])=>O.map(B=>({...B,quantity:0}))),A=[..._,...I,...D].map(Mr),{updateShipping:E}=t?Nn(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 B={...O.marketingData,...t.marketingData};return a.checkout.marketingData({id:d.orderFormId,marketingData:B})}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}))},zn=(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(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:zn(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"?qn(e):null;function qn(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?qn(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(En),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(Rn),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||Fn(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})=>En(r,i));return t?t.sku:e[0]},Vn=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 xn="Invalid SkuId",jn="Slug was set but the fetched sku does not satisfy the slug condition.",Ti="UseAdHocCard",_i=e=>j(e)||e instanceof Error&&(e.message===xn||e.message.startsWith(jn));async function ki(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||W(e)&&r&&Vn(t.split("-").pop()??"")&&await Ei(e,t,a,r)))throw new Error(`${jn} 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 L(`No product found for slug ${n}`);const a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new L(`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(!Vn(c))throw new Error(xn);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:wn(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:_n[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=>!!Tn.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 L(`No order found for id ${n}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=kn(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 L(`No order found for id ${n}. ${o}.`):On(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(N(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(N(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(N(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:zn(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=N(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"}},Wn=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?Wn(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?Wn(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:Tn,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=`"""
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:Mn(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}=Nn(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&&Ce(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:v,shouldSplitItem:l}=n;if(qr(d,h)){const C=Je(r,d),B=await Xe(d,a,h).then(He);if(g)return we(B,o,l,C)}const m=Je(r,d),S=Ge(v),O=Ge(d.items.map(ue)),w=Array.from(O.entries()),b=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:I}=b.reduce((C,[B,Te])=>{const _e=O.get(B);if(!_e)return Te.forEach(Y=>C.itemsToAdd.push(Y)),C;const[ie,...Hn]=_e;if($n(d.items,ie.itemOffered.sku)||Bn(d.items,ie.itemOffered.sku))return C.itemsToUpdate.push(ie),C;const Xn=Te.reduce((Y,Yn)=>Y+Yn.quantity,0);return C.itemsToUpdate.push({...ie,quantity:Xn}),Hn.forEach(Y=>C.itemsToUpdate.push({...Y,quantity:0})),C},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([C])=>!S.has(C)).flatMap(([,C])=>C.map(B=>({...B,quantity:0}))),A=[..._,...I,...D].map(Mr),{updateShipping:E}=t?Nn(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(C=>Ye(C,t,r)):P=await Ye(d,t,r),P=await Promise.resolve(P).then(C=>{if(t?.marketingData){const B={...C.marketingData,...t.marketingData};return a.checkout.marketingData({id:d.orderFormId,marketingData:B})}return C}).then(C=>c&&C.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:C.orderFormId,clientPreferencesData:{...C.clientPreferencesData,locale:c}}):C).then(C=>Xe(C,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=>{if(!Array.isArray(e)||e.length===0)return"";const n=e.find(t=>t?.isDefault===!0)??e[0];return String(n?.id??"").trim()},Kr=(e,n="",t="")=>{const r=n.trim(),i=t.trim();return e.filter(Yr).map(a=>({id:a.customerId,corporateName:a.contractName.trim(),isActive:r?a.customerId===r:a.isCurrent,isDefault:i!==""&&a.customerId===i}))},zn=(e,n)=>{const t=Gr(e);return t||(n?.firstName?.value??"").trim()};async function Qr(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 Zr(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 ei(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 ni(e,n,t){const r=q(N(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 ti(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 ri(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:zn(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ii(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ai=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 Qr(r,c,s);u=P.city,d=P.geoCoordinates}const f=Zr(t,o,s,c,d,n.locale),h=ei(f,n.marketingData),{isRepresentative:v,customerId:l,unitId:p}=await ni(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,b=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 ti(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:ri({isRepresentative:v,authentication:b,shopper:O,publicData:I,profile:S,contract:D,customerId:l,unitId:p}),marketingData:h,person:ii(S),geoCoordinates:d?.latitude&&d?.longitude&&d||null,city:u};return Ee(n,E)?null:E},oi={validateCart:jr,validateSession:ai,subscribeToNewsletter:Pr,cancelOrder:Cr,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 si=e=>typeof e=="string"?qn(e):null;function qn(e){try{return JSON.parse(e)}catch{return e}}const ci=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,li=new ce.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:si,serialize:ci,parseLiteral(e){return e.kind===De.STRING?qn(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,U=e=>"skuName"in e,di={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},ui=({linkText:e})=>`/${e}/p`,pi=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),gi=1e11,mi=e=>/^\d+$/.test(e),hi=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,fi=e=>{if(!mi(e))return new Date(hi.test(e)?`${e}Z`:e);const n=Number(e);return new Date(n>=gi?n:n*1e3)},Si=e=>{if(e==null)return"";const n=String(e).trim();if(n==="")return"";const t=fi(n);return Number.isNaN(t.getTime())?"":t.toISOString().slice(0,10)},yi={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`,Ii=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 vi=(e,n)=>{const t=e.findIndex(r=>Ae(r).split("/").at(-1)===n);return t<0?0:t},Oi={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:ui(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=vi(s,o),g=r[d],f=Ae(g).split("/"),h=t.storage.locale;if(W(t)&&h){const v=await se(t,c,h);if(v){const l=new Set(Ae(s[d]).split("/").filter(Boolean)),p=v.categories.filter(S=>l.has(S.id.toString())).sort((S,O)=>S.fullPath.split("/").length-O.fullPath.split("/").length);if(p.length===f.length)return{itemListElement:[...p.map((S,O)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:O+1})),{name:i,item:en(v.linkId,u),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((v,l)=>{const p=`/${f.slice(0,l+1).map(le).join("/")}/`;return{name:v,item:p,position:l+1}}),{name:i,item:en(a,u),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(Ii(e)??[yi]).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=>pi({offer:n.commertialOffer,seller:n,product:e})).sort(En),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(Rn),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}})=>Si(e),advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!W(t))return null;const r=bt(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)}},Ci=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=>!Ci.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},wi={propertyID:e=>e.propertyID||Fn(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})=>En(r,i));return t?t.sku:e[0]},Vn=e=>e!==""&&!Number.isNaN(Number(e)),Di=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Ai=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!Di.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 v=pe(h.items);return v?F(v,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:""},Pi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Ei=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 Ti(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await se(e,t,r))?.linkId===i}const xn="Invalid SkuId",jn="Slug was set but the fetched sku does not satisfy the slug condition.",_i="UseAdHocCard",ki=e=>j(e)||e instanceof Error&&(e.message===xn||e.message.startsWith(jn));async function Ui(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||W(e)&&r&&Vn(t.split("-").pop()??"")&&await Ti(e,t,a,r)))throw new Error(`${jn} slug: ${t}, linkText: ${i}`)}async function Ri(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 L(`No product found for slug ${n}`);const a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new L(`No product found for id ${i.id}`);return F(pe(a.items),a)}const Fi={product:async(e,{locator:n},t)=>{const r=We(n),i=je(n),a=Sr(n),o=fr(n);r&&de(t,r),i&&Ce(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!Vn(c))throw new Error(xn);const u=await s.load(c);return await Ui(t,u,o,i),u}catch(c){if(!ki(c))throw c;return Ri(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:wn(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&&Ce(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:_n[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,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)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=>!!Tn.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(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 L(`No order found for id ${n}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=kn(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 L(`No order found for id ${n}. ${o}.`):On(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(N(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:_i}).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(N(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(v=>v.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=q(N(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 v=`${(d?.firstName?.value??"").trim()} ${(d?.lastName?.value??"").trim()}`.trim();return{name:zn(h,u)||v||"",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=N(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()||"",f=await a.storeFront.attachedContracts(n).catch(v=>(console.warn("availableContracts: default contract lookup failed",v),null)),h=Jr(f?.contracts);return Kr(d,g,h)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:Pi,orderFormItems:Ei,recommendations:Ai},Ni={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Li=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Bi={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||!Li(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},$i={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Mi=["bd","d","h","m"],zi=e=>Mi.includes(e),qi={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"}},Wn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=zi(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return qi[t][a].replace("#",n)??""},Vi={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Wn(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 xi(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 ji(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Wi(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Gi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>Wi(i.value,a.value));return n}function Hi(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]})}),Gi(r)}const Xi={activeVariations:e=>an(e.variations),allVariantsByName:e=>ji(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>xi(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 Hi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},Yi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Ji={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||"",v=d?.deliveryWindow,l=d?.pickupStoreInfo,p=d?.shippingEstimate||"",m=d?.shippingEstimate?Wn(d?.shippingEstimate):"",S=d?.shippingEstimateDate||"",O=d?.addressId||"",w=d?.itemIndex??0,b=t?.[w],_=b?.seller||"",I=`${g}|${f}|${h}|${_}|${p}|${S}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(C=>C?.addressId===O),A=`${Yi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:P}=Ki(b?.priceTags??[]),R=(b?.sellingPrice??0)*(b?.quantity??0)+(b?.tax??0)+(E??0);return u[I]||(u[I]={selectedSla:g,deliveryChannel:f,deliveryCompany:h,deliveryWindow:v,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:b?.id||"",uniqueId:b?.uniqueId||"",name:b?.name||"",quantity:b?.quantity||0,price:b?.price||0,sellingPrice:b?.sellingPrice||0,imageUrl:b?.imageUrl||"",taxPriceTags:P??[],taxPriceTagsTotal:E??0,tax:b?.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 Ki(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 Qi={StoreCollection:Tn,StoreAggregateOffer:lr,StoreProduct:Oi,StoreSeo:$i,StoreFacet:yr,StoreFacetBoolean:Ir,StoreFacetRange:vr,StoreFacetValueBoolean:Or,StoreOffer:di,StoreAggregateRating:dr,StoreReview:Ni,StoreProductGroup:bi,StoreSearchResult:Bi,StorePropertyValue:wi,SkuVariants:Xi,ShippingSLA:Vi,UserOrderResult:Ji,ObjectOrString:li,Query:Fi,Mutation:oi},Zi=()=>Qi,ea=`"""
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
- `,ea=`"""
54
+ `,na=`"""
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
- `,na=`"""
79
+ `,ta=`"""
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
- `,ta=`"""
108
+ `,ra=`"""
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
- `,ra=`"""
121
+ `,ia=`"""
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
- `,ia=`"""
130
+ `,aa=`"""
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
- `,aa=`"""
139
+ `,oa=`"""
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
- `,oa=`"""
170
+ `,sa=`"""
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
- `,sa=`"""
207
+ `,ca=`"""
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
@@ -330,7 +330,7 @@ type StoreCollectionLocale {
330
330
  """
331
331
  slug: String!
332
332
  }
333
- `,ca=`"""
333
+ `,la=`"""
334
334
  Delivery Promise badge.
335
335
  """
336
336
  type DeliveryPromiseBadge {
@@ -339,7 +339,7 @@ type DeliveryPromiseBadge {
339
339
  """
340
340
  typeName: String
341
341
  }
342
- `,la=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
342
+ `,da=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
343
343
 
344
344
  """
345
345
  Search facet range information.
@@ -416,7 +416,7 @@ type StoreFacetValueBoolean {
416
416
  """
417
417
  quantity: Int
418
418
  }
419
- `,da=`"""
419
+ `,ua=`"""
420
420
  Image.
421
421
  """
422
422
  type StoreImage {
@@ -443,7 +443,7 @@ input IStoreImage {
443
443
  """
444
444
  alternateName: String!
445
445
  }
446
- `,ua=`type Mutation {
446
+ `,pa=`type Mutation {
447
447
  """
448
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\`.
449
449
  """
@@ -485,7 +485,7 @@ input IStoreImage {
485
485
  """
486
486
  startRecommendationSession: Boolean!
487
487
  }
488
- `,pa=`"""
488
+ `,ga=`"""
489
489
  Newsletter information.
490
490
  """
491
491
  type PersonNewsletter {
@@ -508,8 +508,8 @@ input IPersonNewsletter {
508
508
  """
509
509
  email: String!
510
510
  }
511
- `,ga=`scalar ObjectOrString
512
- `,ma=`"""
511
+ `,ma=`scalar ObjectOrString
512
+ `,ha=`"""
513
513
  Offer information.
514
514
  """
515
515
  type StoreOffer {
@@ -602,7 +602,7 @@ input IStoreOffer {
602
602
  """
603
603
  priceToken: String
604
604
  }
605
- `,ha=`"""
605
+ `,fa=`"""
606
606
  Information of a specific order.
607
607
  """
608
608
  type StoreOrder {
@@ -643,7 +643,7 @@ input IStoreOrder {
643
643
  """
644
644
  shouldSplitItem: Boolean
645
645
  }
646
- `,fa=`"""
646
+ `,Sa=`"""
647
647
  Commercial Authorization response.
648
648
  """
649
649
  type CommercialAuthorizationResponse {
@@ -1042,7 +1042,7 @@ type ProcessOrderAuthorizationRule {
1042
1042
  """
1043
1043
  rule: CommercialAuthorizationRule!
1044
1044
  }
1045
- `,Sa=`"""
1045
+ `,ya=`"""
1046
1046
  Input for uploading a file to the Order Entry Service.
1047
1047
  The file is transmitted as a Base64-encoded string so it can travel
1048
1048
  through the standard GraphQL JSON pipeline without multipart support.
@@ -1103,7 +1103,7 @@ type StoreOrderFormCartItem {
1103
1103
  seller: String!
1104
1104
  unitMultiplier: Float
1105
1105
  }
1106
- `,ya=`"""
1106
+ `,Ia=`"""
1107
1107
  Organization.
1108
1108
  """
1109
1109
  type StoreOrganization {
@@ -1139,8 +1139,12 @@ type StoreContract {
1139
1139
  Indicates whether this contract is the one currently active in the session.
1140
1140
  """
1141
1141
  isActive: Boolean!
1142
+ """
1143
+ Indicates whether this contract is the Organization Unit's default contract.
1144
+ """
1145
+ isDefault: Boolean!
1142
1146
  }
1143
- `,Ia=`"""
1147
+ `,va=`"""
1144
1148
  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.
1145
1149
  """
1146
1150
  type StorePageInfo {
@@ -1165,7 +1169,7 @@ type StorePageInfo {
1165
1169
  """
1166
1170
  totalCount: Int!
1167
1171
  }
1168
- `,va=`"""
1172
+ `,Oa=`"""
1169
1173
  Input type for setting a new password.
1170
1174
  """
1171
1175
  input ISetPassword {
@@ -1208,7 +1212,7 @@ type SetPasswordResponse {
1208
1212
  """
1209
1213
  message: String
1210
1214
  }
1211
- `,Oa=`"""
1215
+ `,Ca=`"""
1212
1216
  Client profile data.
1213
1217
  """
1214
1218
  type StorePerson {
@@ -1330,7 +1334,7 @@ type PickupPoints {
1330
1334
  """
1331
1335
  pickupPointsHash: String
1332
1336
  }
1333
- `,Ca=`"""
1337
+ `,wa=`"""
1334
1338
  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.
1335
1339
  """
1336
1340
  type StoreProduct {
@@ -1506,7 +1510,7 @@ input IStoreProduct {
1506
1510
  """
1507
1511
  additionalProperty: [IStorePropertyValue!]
1508
1512
  }
1509
- `,wa=`"""
1513
+ `,Da=`"""
1510
1514
  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.
1511
1515
  """
1512
1516
  type StoreProductGroup {
@@ -1533,7 +1537,7 @@ type StoreProductGroup {
1533
1537
  """
1534
1538
  skuVariants: SkuVariants
1535
1539
  }
1536
- `,Da=`type Profile {
1540
+ `,Aa=`type Profile {
1537
1541
  """
1538
1542
  Collection of user's address
1539
1543
  """
@@ -1594,7 +1598,7 @@ type ProfileAddress {
1594
1598
  """
1595
1599
  geoCoordinate: [Float]
1596
1600
  }
1597
- `,Aa=`"""
1601
+ `,Pa=`"""
1598
1602
  Properties that can be associated with products and products groups.
1599
1603
  """
1600
1604
  type StorePropertyValue {
@@ -1634,7 +1638,7 @@ input IStorePropertyValue {
1634
1638
  """
1635
1639
  valueReference: ObjectOrString!
1636
1640
  }
1637
- `,Pa=`"""
1641
+ `,Ea=`"""
1638
1642
  Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
1639
1643
  """
1640
1644
  type StoreProductEdge {
@@ -2283,7 +2287,7 @@ type StoreAccountProfile {
2283
2287
  email: String
2284
2288
  id: String
2285
2289
  }
2286
- `,Ea=`"""
2290
+ `,Ta=`"""
2287
2291
  Summary of a quote returned in list results.
2288
2292
  """
2289
2293
  type UserQuoteSummary {
@@ -2348,7 +2352,7 @@ type UserQuoteListPaging {
2348
2352
  """
2349
2353
  perPage: Int!
2350
2354
  }
2351
- `,Ta=`type RecommendationResponse {
2355
+ `,_a=`type RecommendationResponse {
2352
2356
  products: [StoreProduct!]!
2353
2357
  correlationId: String!
2354
2358
  campaign: RecommendationCampaign!
@@ -2359,7 +2363,7 @@ type RecommendationCampaign {
2359
2363
  title: String
2360
2364
  type: String!
2361
2365
  }
2362
- `,_a=`"""
2366
+ `,ka=`"""
2363
2367
  Information of a given review rating.
2364
2368
  """
2365
2369
  type StoreReviewRating {
@@ -2386,7 +2390,7 @@ type StoreReview {
2386
2390
  """
2387
2391
  author: StoreAuthor!
2388
2392
  }
2389
- `,ka=`"""
2393
+ `,Ua=`"""
2390
2394
  Whether a saved card is personally owned by the buyer or shared by their
2391
2395
  Organization/Contract. Resolved server-side by the Saved-cards service from
2392
2396
  the buyer's \`useAdHocCard\` role — never inferred client-side.
@@ -2450,7 +2454,7 @@ type SavedCardListResult {
2450
2454
  """
2451
2455
  list: [SavedCard!]
2452
2456
  }
2453
- `,Ua=`"""
2457
+ `,Ra=`"""
2454
2458
  Search Engine Optimization (SEO) tags data.
2455
2459
  """
2456
2460
  type StoreSeo {
@@ -2471,7 +2475,7 @@ type StoreSeo {
2471
2475
  """
2472
2476
  canonical: String!
2473
2477
  }
2474
- `,Ra=`"""
2478
+ `,Fa=`"""
2475
2479
  Currency information.
2476
2480
  """
2477
2481
  type StoreCurrency {
@@ -2746,7 +2750,7 @@ input IStoreSession {
2746
2750
  """
2747
2751
  refreshAfter: String
2748
2752
  }
2749
- `,Fa=`"""
2753
+ `,Na=`"""
2750
2754
  Shipping Simulation item input.
2751
2755
  """
2752
2756
  input IShippingItem {
@@ -3077,7 +3081,7 @@ type MessageFields {
3077
3081
  """
3078
3082
  skuName: String
3079
3083
  }
3080
- `,Na=`type SkuVariants {
3084
+ `,La=`type SkuVariants {
3081
3085
  """
3082
3086
  SKU property values for the current SKU.
3083
3087
  """
@@ -3172,7 +3176,7 @@ Example:
3172
3176
  \`\`\`
3173
3177
  """
3174
3178
  scalar FormattedVariants
3175
- `,La=`"""
3179
+ `,Ba=`"""
3176
3180
  Status used to indicate a message type. For instance, a shopping cart informative or error message.
3177
3181
  """
3178
3182
  enum StoreStatus {
@@ -3180,7 +3184,7 @@ enum StoreStatus {
3180
3184
  WARNING
3181
3185
  ERROR
3182
3186
  }
3183
- `,Ba=`scalar JSONObject
3187
+ `,$a=`scalar JSONObject
3184
3188
 
3185
3189
  type UserOrder {
3186
3190
  orderId: String
@@ -4004,4 +4008,4 @@ type UserOrderBudgetAllocationLinkedEntity {
4004
4008
  type: String
4005
4009
  id: String
4006
4010
  }
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}))),Gn=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=yn([Sn,fn])(qa(),Gn);return e&&ce.isSchema(e)?sn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=fn;exports.BadRequestError=T;exports.CacheControlDirective=Sn;exports.CardOrigin=cn;exports.CommercialAuthorizationStatus=ln;exports.FastStoreError=X;exports.ForbiddenError=G;exports.GraphqlVtexContextFactory=za;exports.GraphqlVtexSchema=Va;exports.NotFoundError=L;exports.StoreCollectionType=dn;exports.StoreFacetType=un;exports.StoreSort=pn;exports.StoreStatus=gn;exports.UnauthorizedError=Z;exports.UserOrderInvoiceType=mn;exports.getAuthCookie=N;exports.isBadRequestError=st;exports.isFastStoreError=ot;exports.isForbiddenError=On;exports.isNotFoundError=j;exports.isUnauthorizedError=ct;exports.stringifyCacheControl=tt;exports.typeDefs=Gn;exports.validateUserAuthentication=hn;exports.withDirectives=yn;
4011
+ `,Ma=Object.assign({"./address.graphql":ea,"./advertisement.graphql":na,"./aggregateOffer.graphql":ta,"./aggregateRating.graphql":ra,"./author.graphql":ia,"./brand.graphql":aa,"./breadcrumb.graphql":oa,"./cart.graphql":sa,"./collection.graphql":ca,"./deliveryPromisesBadge.graphql":la,"./facet.graphql":da,"./image.graphql":ua,"./mutation.graphql":pa,"./newsletter.graphql":ga,"./objectOrString.graphql":ma,"./offer.graphql":ha,"./order.graphql":fa,"./orderCommercialAuthorizaton.graphql":Sa,"./orderEntry.graphql":ya,"./organization.graphql":Ia,"./pageInfo.graphql":va,"./password.graphql":Oa,"./person.graphql":Ca,"./pickupPoints.graphql":ba,"./product.graphql":wa,"./productGroup.graphql":Da,"./profile.graphql":Aa,"./propertyValue.graphql":Pa,"./query.graphql":Ea,"./quote.graphql":Ta,"./recommendation.graphql":_a,"./review.graphql":ka,"./savedCard.graphql":Ua,"./seo.graphql":Ra,"./session.graphql":Fa,"./shipping.graphql":Na,"./skuVariants.graphql":La,"./status.graphql":Ba,"./userOrder.graphql":$a}),za=ce.print(Object.values(Ma).map(e=>ce.parse(e)).reduce((e,n)=>on.mergeTypeDefs([e,n],{sort:!0}))),Gn=za,qa=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 Va(){const e=Zi(),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 xa(e){const t=yn([Sn,fn])(Va(),Gn);return e&&ce.isSchema(e)?sn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=fn;exports.BadRequestError=T;exports.CacheControlDirective=Sn;exports.CardOrigin=cn;exports.CommercialAuthorizationStatus=ln;exports.FastStoreError=X;exports.ForbiddenError=G;exports.GraphqlVtexContextFactory=qa;exports.GraphqlVtexSchema=xa;exports.NotFoundError=L;exports.StoreCollectionType=dn;exports.StoreFacetType=un;exports.StoreSort=pn;exports.StoreStatus=gn;exports.UnauthorizedError=Z;exports.UserOrderInvoiceType=mn;exports.getAuthCookie=N;exports.isBadRequestError=st;exports.isFastStoreError=ot;exports.isForbiddenError=On;exports.isNotFoundError=j;exports.isUnauthorizedError=ct;exports.stringifyCacheControl=tt;exports.typeDefs=Gn;exports.validateUserAuthentication=hn;exports.withDirectives=yn;