@faststore/api 4.10.1-dev.5 → 4.10.1-dev.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cjs/index.js +49 -46
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/index.mjs +1115 -1058
  4. package/dist/es/index.mjs.map +1 -1
  5. package/dist/src/__generated__/schema.d.ts +1 -0
  6. package/dist/src/__generated__/schema.d.ts.map +1 -1
  7. package/dist/src/platforms/vtex/clients/index.d.ts +1 -1
  8. package/dist/src/platforms/vtex/clients/search/index.d.ts +7 -1
  9. package/dist/src/platforms/vtex/clients/search/index.d.ts.map +1 -1
  10. package/dist/src/platforms/vtex/index.d.ts +1 -1
  11. package/dist/src/platforms/vtex/index.d.ts.map +1 -1
  12. package/dist/src/platforms/vtex/loaders/sku.d.ts.map +1 -1
  13. package/dist/src/platforms/vtex/resolvers/index.d.ts +1 -1
  14. package/dist/src/platforms/vtex/resolvers/index.d.ts.map +1 -1
  15. package/dist/src/platforms/vtex/resolvers/query.d.ts +1 -1
  16. package/dist/src/platforms/vtex/resolvers/query.d.ts.map +1 -1
  17. package/dist/src/platforms/vtex/resolvers/validateSession.d.ts.map +1 -1
  18. package/dist/src/platforms/vtex/utils/contractAssortment.d.ts +22 -0
  19. package/dist/src/platforms/vtex/utils/contractAssortment.d.ts.map +1 -0
  20. package/dist/src/platforms/vtex/utils/intelligentSearchRequest.d.ts +5 -0
  21. package/dist/src/platforms/vtex/utils/intelligentSearchRequest.d.ts.map +1 -1
  22. package/dist/src/platforms/vtex/utils/validateSessionHelpers.d.ts +29 -2
  23. package/dist/src/platforms/vtex/utils/validateSessionHelpers.d.ts.map +1 -1
  24. package/package.json +3 -3
  25. package/src/__generated__/schema.ts +1 -0
  26. package/src/platforms/vtex/clients/search/index.ts +13 -1
  27. package/src/platforms/vtex/loaders/sku.ts +1 -0
  28. package/src/platforms/vtex/resolvers/query.ts +51 -37
  29. package/src/platforms/vtex/resolvers/validateSession.ts +3 -3
  30. package/src/platforms/vtex/typeDefs/session.graphql +3 -0
  31. package/src/platforms/vtex/utils/contractAssortment.ts +87 -0
  32. package/src/platforms/vtex/utils/intelligentSearchRequest.ts +10 -0
  33. package/src/platforms/vtex/utils/validateSessionHelpers.ts +47 -5
package/dist/cjs/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Sn=require("@graphql-tools/merge"),yn=require("@graphql-tools/schema"),Y=require("@graphql-tools/utils"),he=require("graphql"),z=require("@faststore/diagnostics"),mt=require("isomorphic-unfetch"),oe=require("cookie"),Re=require("p-limit"),Ie=require("dataloader"),ht=require("sanitize-html"),Ne=require("fast-deep-equal"),ft=require("node:crypto");var In=(e=>(e.Personal="personal",e.Shared="shared",e))(In||{}),vn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(vn||{}),On=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(On||{}),Cn=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(Cn||{}),bn=(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))(bn||{}),wn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(wn||{}),An=(e=>(e.Input="Input",e.Output="Output",e))(An||{});const St=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new Q("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Pn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new re("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new re("Authentication required"):r===403?new Q("You are not allowed to access this resource"):new re("Authentication required")}},yt="auth",Dn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>Y.mapSchema(e,{[Y.MapperKind.OBJECT_FIELD]:n=>{if(Y.getDirective(e,n,yt)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Pn(o),r?.(i,a,o,s))}return n}})},It="cacheControl",vt=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},$e=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,Ot=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,En={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>Y.mapSchema(e,{[Y.MapperKind.OBJECT_FIELD]:n=>{const t=Y.getDirective(e,n,It)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,d,g)=>(d.cacheControl={sMaxAge:$e(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:$e(d.cacheControl?.staleWhileRevalidate,i),scope:Ot(d.cacheControl?.scope,a)},o?.(s,c,d,g))}return n}})},kn=e=>(n,t)=>{const r=Sn.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,yn.makeExecutableSchema({typeDefs:r,resolvers:n}))},Tn="@faststore/api",_n="4.10.1-dev.4",Me={name:Tn,version:_n},Fe=z.logger("@faststore/api"),Ct=(e,n="Unknown Graphql Resolver")=>(t,r,i,a)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,a);const o=z.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:z.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":_n,"@faststore_package_name":Tn,"@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=z.OTELAPI.trace.setSpan(z.OTELAPI.context.active(),o);try{const c=z.OTELAPI.context.with(s,()=>e(t,r,i,a));return c instanceof Promise?c.then(d=>(o.end(),d),d=>ze(d,o,n)):(o.end(),c)}catch(c){return ze(c,o,n)}};function ze(e,n,t){throw n.setStatus({code:z.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
2
- %o`,e),Fe("error",`Error at resolver: %s
3
- %o`,t,e),e}class q extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class k extends q{constructor(n){super({status:400,type:"BadRequestError"},n)}}class re extends q{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class Q extends q{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class $ extends q{constructor(n){super({status:404,type:"NotFoundError"},n)}}const bt=e=>e?.name==="FastStoreError",wt=e=>e?.extensions?.type==="BadRequestError",At=e=>e?.extensions?.type==="UnauthorizedError",Un=e=>e?.extensions?.type==="ForbiddenError",K=e=>e?.extensions?.type==="NotFoundError",Pt=`${Me.name}@${Me.version}`,Dt=/authorization|cookie|token|secret|api-?key|appkey/i,Rn="[redacted]",Ve=e=>{if(!e)return;const n={},t=(r,i)=>{n[r]=Dt.test(r)?Rn:i};return Array.isArray(e)?e.forEach(([r,i])=>t(r,i)):typeof e.forEach=="function"?e.forEach((i,a)=>t(a,i)):Object.entries(e).forEach(([r,i])=>t(r,i)),n},y=async(e,n,t)=>{const r=await mt(e,{...n,headers:{...n?.headers??{},"User-Agent":Pt}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(typeof e=="string"?e:e.url,n&&{...n,headers:Ve(n.headers),body:n.body?Rn:void 0},{status:r.status,statusText:r.statusText,headers:Ve(r.headers)});const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new k(i);case 401:throw new re(i);case 403:throw new Q(i);case 404:throw new $(i);default:throw new q({status:r.status,type:"UnknownError"},i)}throw new Error(i)},Et=({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"}})}},Nn=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("; ")},kt=/^([^=]+)=([^;]*)/,Tt=(e,n)=>{const t=n.match(kt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},_t=(e,n)=>{n.getSetCookie().forEach(t=>Tt(e,t))},Ut=e=>n=>_t(e,n),Ce=e=>{if(!e.headers?.cookie)return null;const n=Nn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Rt(r,i,a),n)},Fn=e=>function(t){const r=Ce(e);return r?{...t,cookie:r}:t},B=(e,n)=>{const t=Nn(e);return oe.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Rt=(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 G(e){if(!e)return null;try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString())}catch{return null}}const Nt="storefront/faststore.recommendation-shelf@v4",te={method:"POST",headers:{"content-type":"application/json"}},Ft=100,de=new Set,Lt=e=>e.split("/").map(encodeURIComponent).join("/"),ve=e=>e?{headers:{"Accept-Language":e}}:void 0,Bt=/^\d{4}-\d{2}-\d{2}$/,$t=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function Mt({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&&!Bt.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!$t.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function zt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(d=>c.append("status",d)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const Vt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=Ut(i),s=Fn(i),c=St(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(l=>l+".").find(l=>d.includes(l))||"",p=d.replace(g,""),f=`${a}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${Nt}`}),I=(l={})=>{const u=B(Ce(i)??"",e);return s({...l,"X-FORWARDED-HOST":p,...u?{[`VtexIdclientAutCookie_${e}`]:u}:{}})};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,u)=>{try{return await y(`${a}/api/catalog_system/pub/category/by-linkid/${Lt(l)}`,ve(u))}catch(m){if(K(m))return null;throw m}},brand:async(l,u)=>{try{return await y(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,ve(u))}catch(m){if(K(m))return null;throw m}},collection:async(l,u)=>{try{return await y(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,ve(u))}catch(m){if(K(m))return null;throw m}}},products:{crossselling:({type:l,productId:u,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}/${u}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:u}=i.storage.channel)=>{const m=new URLSearchParams({sc:u}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...te,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:u,deliveryMode:m,selectedAddresses:S},v)=>{const b=v?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,O={logisticsInfo:Array.from({length:u},(A,C)=>({itemIndex:C,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:b})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...te,headers:_,body:JSON.stringify(O)},{storeCookies:o})},marketingData:({id:l,marketingData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:u=!0,channel:m=i.storage.channel,preserveSalesChannel:S=!1})=>{const{salesChannel:v}=m,b=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=new URLSearchParams;(!S||!l)&&O.set("sc",v),l&&O.set("refreshOutdatedData",u.toString());const _=l?`/${l}`:"",A=`${a}/api/checkout/pub/orderForm${_}?${O}`;return y(A,{...te,headers:b,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...te,headers:u,body:"{}"})},updateOrderFormItems:({id:l,orderItems:u,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:v=!0})=>{const b=new URLSearchParams({allowOutdatedData:m,sc:S}),O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${b}`,{headers:O,body:JSON.stringify({orderItems:u,noSplitItem:!v}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:u,key:m,value:S})=>{const v=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/customData/${u}/${m}`,{headers:v,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:u,country:m,salesChannel:S})=>{const v=new URLSearchParams({country:m,sc:S??""});l?v.append("postalCode",l):v.append("geoCoordinates",`${u?.longitude};${u?.latitude}`);const b=`${a}/api/checkout/pub/regions/?${v.toString()}`,O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(b,{headers:O},{storeCookies:o})},address:async({postalCode:l,country:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/postal-code/${u}/${l}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:u,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:u,reason:m})},{})}},session:l=>{const u=new URLSearchParams(l);u.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=oe.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${a}/api/sessions?${u.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},storeFront:{attachedContracts:l=>{const u=s({"content-type":"application/json"});return y(`https://${e}.myvtex.com/_v/store-front/units/${encodeURIComponent(l)}/contracts/attached?details=true`,{headers:u},{storeCookies:o})}},subscribeToNewsletter:({name:l,email:u})=>{const m=JSON.stringify({...l?{name:l}:{},email:u,isNewsletterOptIn:!0}),S=process.env.FS_NEWSLETTER_APP_KEY,v=process.env.FS_NEWSLETTER_APP_TOKEN;if(S&&v)return y(`${a}/api/dataentities/NL/documents`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json","X-VTEX-API-AppKey":S,"X-VTEX-API-AppToken":v},body:m});if(!de.has(e)){de.size>=Ft&&de.clear(),de.add(e);const b=[!S&&"FS_NEWSLETTER_APP_KEY",!v&&"FS_NEWSLETTER_APP_TOKEN"].filter(Boolean),O=`[subscribeToNewsletter] ${b.join(" and ")} ${b.length>1?"are":"is"} not set. Falling back to an anonymous Master Data request, which requires public fields in the NL entity. Configure both credentials and make the NL fields private.`;console.warn(O),Fe("warn","%s",O)}return y(`${a}/api/dataentities/NL/documents/`,{...te,body:m,method:"PATCH"},{storeCookies:o})},profile:{addresses:async l=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:u},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:u},{storeCookies:o})},listUserOrders:({page:l,status:u,dateInitial:m,dateFinal:S,text:v,clientEmail:b,perPage:O,pendingMyApproval:_})=>{const A=new URLSearchParams;if(m){const D=new Date(m).setHours(0,0,0,0);m=new Date(D).toISOString()}if(S){const D=new Date(S).setHours(23,59,59,999);S=new Date(D).toISOString()}v&&A.append("text",v),u&&u.length>0&&A.append("status",u.filter(Boolean).join(",")),m&&S?A.append("creation_date",`creationDate:[${m} TO ${S}]`):m?A.append("creation_date",`creationDate:[${m} TO *]`):S&&A.append("creation_date",`creationDate:[* TO ${S}]`),b&&A.append("clientEmail",b),l&&A.append("page",l.toString()),O&&A.append("per_page",O.toString()),_&&A.append("my_pending_approvals",String(!0));const C=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders?${A.toString()}`,{method:"GET",headers:C},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:u},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:u,ruleId:m,approved:S})=>{const v=s({"content-type":"application/json","X-FORWARDED-HOST":p}),_={params:{ruleId:m,dimensionId:u,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":p});return y(`${a}/api/saved-cards/credit-card?an=${e}`,{method:"GET",headers:l},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:u},{})},getOrgUnitById:({orgUnitId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}`,{method:"GET",headers:u},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:u},{})}},licenseManager:{getUserById:({userId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:u},{})},getUserByEmail:({email:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:u},{})},getUserRoles:({userId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:u},{})},isResourceGranted:({userId:l,resourceKey:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/bff/users/${l}/resources/${u}/granted?an=${e}`,{method:"GET",headers:m},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new k("Missing contractId to fetch CL fields.");const u=I({Accept:"application/json","content-type":"application/json"});return y(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:u},{})},getShopperById:({userId:l})=>{if(!l)throw new k("Missing userId to fetch shopper name.");const u=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=l.replace(/-/g,"");return y(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:u},{})}},quotes:{listUserQuotes:l=>{Mt(l);const u=zt(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/quoting/quotes?${u.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p}),u=B(Ce(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:u}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:u,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),v=`----FastStoreUploadBoundary${Date.now()}`,b=`\r
4
- `,_=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",A=u.replaceAll(/[\r\n"]/g,"_"),C=[`--${v}`,`Content-Disposition: form-data; name="file"; filename="${A}"`,`Content-Type: ${_}`,"",""].join(b),D=`${b}--${v}--${b}`,P=Buffer.from(C),T=Buffer.from(D),E=new Uint8Array(P.byteLength+l.byteLength+T.byteLength);let U=0;return E.set(P,U),U+=P.byteLength,E.set(l,U),U+=l.byteLength,E.set(T,U),y(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${v}`},body:E.buffer},{})},startOperation:({objectKey:l,orderFormId:u,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),v=JSON.stringify({objectKey:l,orderFormId:u,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:v},{})},getOperation:({operationId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:u},{})},createOrderForm:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:l,body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:u},{})}},recommendation:{recommendations:({campaignVrn:l,userId:u,products:m=[],salesChannel:S,locale:v})=>{const b=new URLSearchParams({an:e,campaignVrn:l});return u&&b.append("userId",u),m.length>0&&b.append("products",m.join(",")),S&&b.append("salesChannel",S),v&&b.append("locale",v),y(`${f}/recommendations?${b.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})}}}},ae=e=>e.discoveryConfig?.localization??{},J=e=>ae(e).enabled===!0,qt=e=>Object.keys(ae(e).locales??{}),xt=e=>ae(e).defaultLocale,Ln=e=>J(e)&&e.storage.locale||void 0,be="fuzzy",we="operator",Ae="pickupPoint",qe="shipping",xe="delivery-options",jt="in-stock",Wt="trade-policy",Ht="region-id",Gt=new Set([Wt,Ht,be,we,Ae]),Xt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),je=e=>encodeURI(decodeURI(e)),Yt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Kt=/^pickup-in-point-(.+)$/;function Bn(e){if(!e)return{};try{const t=oe.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function Jt(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||(Xt.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function Qt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=Jt(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 $n(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 Mn(e){return Kt.exec(e)?.[1]}function Zt(e){const n=e.find(r=>r.key==="shipping"),t=n?Mn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function er(e,n){const t=Zt(n);return t===void 0?e:{...e,pickupPoint:t}}function nr(e){return e.map(n=>n.key!=="shipping"||Mn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function tr(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")),nr(t)}function zn(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}${je(r)}/${Yt(je(i)).replaceAll(/ |%20/g,"-")}/`},"")}const rr=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),ir=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function ar(e,n){const{segmentParams:t,extraFacets:r}=Qt(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 or(e,n){const t=e.filter(({key:c})=>!Gt.has(c)),r=e.find(({key:c,value:d})=>c===qe&&d!=="all-delivery-methods")??null,i=e.find(({key:c,value:d})=>c===xe&&d!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===qe),s=a.some(({key:c})=>c===xe);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),tr(a,n)}function sr(e,n){const t=e.find(({key:a})=>a===be)??null,r=e.find(({key:a})=>a===we)??null,i=e.find(({key:a})=>a===Ae)??null;t&&rr(t)&&n.append(be,t.value),r&&ir(r)&&n.append(we,r.value),i&&n.append(Ae,i.value)}function We(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:g,hideUnavailableItems:p,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const u=a*o,m=o===0?u:u+o-1;h.append("from",u.toString()),h.append("to",m.toString())}i&&h.append("query",i),r.includeSort&&s&&h.append("sort",s);const I=er(t.segmentParams,c);if($n(h,I??t.segmentParams),sr(c,h),d&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const u=c.find(({key:S})=>S===jt),m=u?u.value:p?.toString()??n.hideUnavailableItems.toString();h.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&h.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&h.append("showSponsored",n.showSponsored.toString()),g!==void 0&&h.append("sponsoredCount",g.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=zn(or(c,t.extraFacets));return{params:h,path:l}}function cr(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return $n(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function ue(e){return(e??"").replaceAll(/[\s-]/g,"").toUpperCase()}function lr(e,n){const{segmentParams:t,extraFacets:r}=n,{postalCode:i,country:a,coordinates:o}=e,s=!!i,c=a||t.country,d=s&&ue(i)===ue(t["zip-code"])&&ue(c)===ue(t.country),g=s?i:t["zip-code"],p=s?c:t.country,f=d?t.coordinates:void 0,h=s?o??f:o||t.coordinates,I=!s||d,l=!!(t.deliveryZonesHash&&t.pickupPointHash);if((!g||!p)&&!!!h&&!(I&&l))throw new Error("Missing delivery location for pickup point availability. Provide postalCode and country, coordinates, or a segment with zip-code.");const m=new URLSearchParams,S=(v,b)=>{b!=null&&String(b)!==""&&m.append(v,String(b))};return S("sc",t.sc),S("locale",t.locale),S("country",p),S("zip-code",g),S("coordinates",h),I&&(S("deliveryZonesHash",t.deliveryZonesHash),S("pickupPointsHash",t.pickupPointHash)),{params:m,path:zn(r)}}function j(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function W(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=ar(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=We(i,r,a,{includePagination:!0,includeSort:!0});return j(s,o)}case"catalog-count":{const{params:o,path:s}=We(i,r,a,{includePagination:!1,includeSort:!1});return j(s,o)}case"products":{const o=cr(i,a.segmentParams);return j("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return j("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return j("",o)}case"pickup-point-availability":{const{params:o,path:s}=lr(i,a);return j(s,o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const dr=10;function ur(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function pr(e){const t=Bn(e.headers?.cookie).cultureInfo||"";return J(e)?e.storage.locale||t:t||e.storage.locale||""}const gr=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=Fn(o),d=Bn(o.headers?.cookie),g=()=>({salesChannel:o.storage.channel.salesChannel,regionId:ur(o),locale:pr(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",f=a&&a.map(C=>C+".").find(C=>p.includes(C))||"",h=p.replace(f,""),I=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:C,...D})=>{const P=C==="facets"?"facets":"product-search",T=W({endpoint:P,segment:d,defaults:g(),args:D});return y(`${s}/api/intelligent-search/v1/${P}/${T.path}?${T.params.toString()}`,{headers:I})},u=C=>l({...C,type:"product_search"}),m=({field:C,value:D,hideUnavailableItems:P,showInvisibleItems:T})=>{const E=W({endpoint:"products",segment:d,defaults:g(),args:{field:C,value:D,hideUnavailableItems:P,showInvisibleItems:T}});return y(`${s}/api/intelligent-search/v1/products?${E.params.toString()}`,{headers:I})};return{facets:C=>l({...C,type:"facets"}),products:u,fetchProduct:m,productsByIdentifier:async({field:C,values:D,showInvisibleItems:P,hideUnavailableItems:T})=>{const E=Re(dr);return(await Promise.all(D.map(w=>E(async()=>{try{return await m({field:C,value:w,hideUnavailableItems:T,showInvisibleItems:P})}catch{return null}})))).filter(w=>w!==null)},suggestedTerms:C=>{const D=W({endpoint:"search-suggestions",segment:d,defaults:g(),args:{query:C.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:I})},topSearches:()=>{const C=W({endpoint:"top-searches",segment:d,defaults:g()});return y(`${s}/api/intelligent-search/v1/top-searches?${C.params.toString()}`,{headers:I})},productCount:C=>{const D=W({endpoint:"catalog-count",segment:d,defaults:g(),args:C});return y(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:I})},pickupPointAvailability:({postalCode:C,country:D,coordinates:P})=>{const T=W({endpoint:"pickup-point-availability",segment:d,defaults:g(),args:{postalCode:C,country:D,coordinates:P}}),E=T.path?`/${T.path}`:"";return y(`${s}/api/intelligent-search/v1/pickup-point-availability${E}?${T.params.toString()}`,{headers:I})}}},mr=(e,n)=>{const t=gr(e,n),r=Vt(e,n),i=Et(e);return{search:t,commerce:r,catalog:i}},hr=20,fr=e=>e.entityType==="category",Pe=e=>e.entityType==="brand",He=e=>e.entityType==="collection",Sr=(e,n)=>{const t=Re(hr),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const d=await n.commerce.catalog.byLinkId.brand(o,s);if(d)return{...d,entityType:"brand"};const g=await n.commerce.catalog.byLinkId.collection(o,s);if(g)return{...g,entityType:"collection"};throw new $(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new Ie(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},yr=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new Ie(t)},Ir=1,vr=(e,n)=>{const t=Re(Ir),r=async a=>{const o=a.reduce((p,{items:f})=>[...p,f],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((p,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<p.length&&(p[h]=f),p},Array(s.length).fill(null)),g=o.reduce((p,f)=>[...p,f.length+p[p.length-1]],[0]);return o.map((p,f)=>({...c,items:d.slice(g[f],g[f+1]).filter(h=>!!h)}))},i=async a=>t(r,a);return new Ie(i,{maxBatchSize:50})},Or=(e,n)=>ht(e,n);function Cr(e){return{...e,description:e.description?Or(e.description):e.description}}const L=(e,n)=>({...e,isVariantOf:Cr(n)}),br=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),a=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,p)=>{for(const f of p.items)g[f.itemId]=L(f,p);return g},{}),c=i.map(g=>s[g]),d=i.filter(g=>!s[g]);if(d.length>0)throw new $(`Search API did not found the following skus: ${d.join(",")}`);return c};return new Ie(t,{maxBatchSize:99})},wr=(e,n)=>{const{clients:t}=n,r=br(e,t),i=vr(e,t),a=Sr(e,t),o=yr(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},V=e=>e.AvailableQuantity>0,Z=e=>e.spotPrice??0,Ar=e=>e.Price??0,Ge=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",Vn=(e,n)=>V(e)&&!V(n)?-1:!V(e)&&V(n)?1:Z(e)-Z(n),Pr=e=>e==="available",X=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},Dr=(e,n={includeTaxes:!1})=>{const t=e.filter(V),r=t[t.length-1],i=r?Z(r):0;return n.includeTaxes?X(i,r?.Tax,r?.product?.unitMultiplier):i},Xe=(e,n={includeTaxes:!1})=>{const[t]=e.filter(V),r=t?Z(t):0;return n.includeTaxes?X(r,t?.Tax,t?.product?.unitMultiplier):r},Er={highPrice:e=>Dr(e),lowPrice:e=>Xe(e),lowPriceWithTaxes:e=>Xe(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},kr={ratingValue:()=>5,reviewCount:()=>0},Ye="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",Tr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",_r=e=>{let n=e.slice(0);for(let t=0;t<Ye.length;t++)n=n.replace(new RegExp(Ye.charAt(t),"g"),Tr.charAt(t));return n},Ur=e=>e.replace(/[·/_,:]/,"-");function fe(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return Ur(_r(t)).toLowerCase()}const Oe=e=>e.toLowerCase(),pe=(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:Ln(e)})))},H=e=>fr(e)?e.slug:Pe(e)?e.linkId:e.linkId??fe(e.name),qn={id:({id:e})=>e.toString(),slug:e=>H(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>Pe(e)?"Brand":He(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=H(e);if(Pe(e))return{selectedFacets:[{key:"brand",value:r}]};if(He(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ae(t);return{selectedFacets:(await pe(t,r)).map((o,s)=>({key:`category-${s+1}`,value:i&&o.availableLinkIds?.[i]||o.linkId}))}},breadcrumbList:async(e,n,t)=>{const r=await pe(t,H(e));return{itemListElement:r.map((i,a)=>({item:`/${H(i)}`,name:i.name,position:a+1})),numberOfItems:r.length}},otherLocales:async(e,n,t)=>{const r=ae(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const a=H(e);if(a.split("/").filter(Boolean).length===0)return null;let o;try{o=await pe(t,a)}catch(s){return console.warn("[otherLocales] failed to load collection entities:",s),null}return i.map(s=>{const c=[];for(const d of o){const g=d.availableLinkIds?.[s];if(!g)return null;c.push(g)}return c.length>0?{locale:s,slug:Oe(c.join("/"))}:null}).filter(s=>s!==null)},canonicalSlug:async(e,n,t)=>{const r=H(e);if(r.split("/").filter(Boolean).length===0)return null;let i;try{i=await pe(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)?Oe(a.join("/")):Oe(r)}},xn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Ke=({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}}},Je=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},Rr=e=>typeof xn[e]=="string",Nr=e=>{const n=e?.filter(t=>Rr(t.key));if(Array.isArray(n)&&n.length>1)throw new k(`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,Lr=e=>e?.find(n=>n.key==="id")?.value??null,Qe=e=>e?.find(n=>n.key==="locale")?.value??null,Ze=e=>e?.find(n=>n.key==="channel")?.value??null,De=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},Br={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},$r={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},Mr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Je(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=De(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=Je(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=De(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},zr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},Vr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new k("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function jn(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 qr(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 xr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=jn(r);return{isPendingForOtherAuthorizer:!i&&qr(r),ruleForAuthorization:i}},jr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new k("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},Wr=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},Hr=254,en=100,Gr=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,Xr=async(e,{data:n},{clients:{commerce:t}})=>{const r=n.email?.trim().toLowerCase()??"",i=n.name?.trim()??"";if(r.length>Hr||!Gr.test(r))throw new k("Invalid email");if(i.length>en)throw new k(`Invalid name: must have at most ${en} characters`);return{id:(await t.subscribeToNewsletter({email:r,name:i||void 0}))?.Id}},Yr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new k("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 k("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 k("Invalid Base64 fileContent");const g=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:a})};class se{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 Kr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:se.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}function Jr(e,n,t){return t!=null&&String(e.salesChannel??"")===t&&String(n??"")!==t?!1:e.items.length>0?!0:e.salesChannel==null||e.salesChannel===""?!1:String(e.salesChannel)===String(n??"")}const Wn=e=>{try{return JSON.parse(e??"")??{}}catch{return{}}};function Hn(e,{localizationEnabled:n=!0}={}){const t=Wn(e).salesChannelSource;return t==="url"?n?t:void 0:t==="orderForm"?t:void 0}const Gn=e=>!!e?.localization?.enabled;function Xn(e){const n=Wn(e).rejectedSalesChannel;return(typeof n=="string"||typeof n=="number")&&String(n)||void 0}function Qr(e,n,t,r,i,a){const o=n??void 0,s=t??e.regionId,c=i?e.salesChannel||o:o??e.salesChannel,d=a!=null&&a!==String(c??"");return se.stringify({salesChannel:c,regionId:s??void 0,seller:r,hasOnlyDefaultSalesChannel:!o,...i?{salesChannelSource:i}:{},...d?{rejectedSalesChannel:a}:{}})}const nn="1";function Zr(e,n,t,r){const i=String(e.salesChannel??"");return n===void 0&&i===nn&&!!t&&t!==nn&&!new URLSearchParams(r).has("sc")?t:i}const ie=(e,n)=>{e.storage.channel=se.parse(n)},Ee=(e,n)=>{e.storage.locale=n},Le=e=>ft.createHash("md5").update(e).digest("hex"),x={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE",service:"SERVICE"};function Yn(e){return{name:e.name,value:e.content,valueReference:x.attachment}}function ei(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:x.attribute,visible:e.visible}}}function Kn(e){return Le(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Jn=(e,n)=>e<n?-1:e>n?1:0,ni=(e,n)=>Jn(e.name,n.name),ti=e=>[...e??[]].sort(ni),tn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ri=e=>tn(e)&&typeof e.name=="string"&&tn(e.content),ii=e=>({name:e.name,content:Object.fromEntries(Object.keys(e.content).sort(Jn).map(n=>[n,e.content[n]]))}),Qn=(e,n)=>Le(`SERVICE:${e}:${JSON.stringify(ti((n??[]).filter(ri)).map(ii))}`),ai="SERVICE:unreadable";function Be(e){const n=e.attachments??[];return{propertyID:Qn(e.id,n),name:e.name,value:{id:e.id,price:e.sellingPrice/100,attachments:n},valueReference:x.service}}const oi=e=>{try{return JSON.parse(e)}catch{return null}},si=e=>{const n=typeof e=="string"?oi(e):e;if(n===null||typeof n!="object")return null;const{id:t,attachments:r}=n;return typeof t!="string"&&typeof t!="number"?null:{id:String(t),attachments:r}};function ci(e){const n=si(e.value);return n?Qn(n.id,Array.isArray(n.attachments)?n.attachments:[]):ai}const li=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]},di=(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},Zn=(e,n)=>{if(!ui(n))return{updateShipping:!1,addressChanged:!1};if(!hi(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(pi(t,n.postalCode)||gi(t,n.geoCoordinates)||mi(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return fi(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},ui=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,pi=(e,n)=>typeof n=="string"&&e?.postalCode!==n,gi=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),mi=(e,n)=>typeof n=="string"&&e?.addressType!==n,hi=e=>e.items.length!==0,fi=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,g=r&&s!==r;return c?.some(p=>d&&p.deliveryChannel===t||g&&p.id===r?!0:i&&a&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==a)&&p.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===a))})},et=e=>e.valueReference===x.attachment,Si=e=>e.valueReference===x.service,yi=e=>(e.itemOffered.additionalProperty??[]).filter(Si).map(ci).sort((n,t)=>n.localeCompare(t)),nt=e=>{const n=yi(e);return n.length>0?`services:${n.join("-")}`:void 0},ke=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(et).map(Kn).join("-"),nt(e)].filter(Boolean).join("::"),Se=(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(Yn),...(e.bundleItems??[]).map(Be)]},index:n}),Ii=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(et)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),rn=e=>e.reduce((n,t)=>{const r=ke(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),vi=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},services:nt(c),index:d}),r=n.items.map(Se).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Ne(r,i);return a&&o};function tt(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function rt(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const an=e=>{const n=e.items.reduce((t,r,i)=>{const a=rt(e.items,r.id)||tt(e.items,r.id)?`${ke(Se(r))}::${i}`:ke(Se(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}})}},Te=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()}))}),it=({items:e},n)=>{const t=e.map(r=>{const i=(r.bundleItems??[]).map(Be).map(({propertyID:a})=>a).sort((a,o)=>a.localeCompare(o));return{id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments,...i.length>0?{services:i}:{}}});return Le(JSON.stringify({sessionId:n?.id??"",items:t}))},on=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:it(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const In=require("@graphql-tools/merge"),vn=require("@graphql-tools/schema"),J=require("@graphql-tools/utils"),me=require("graphql"),V=require("@faststore/diagnostics"),St=require("isomorphic-unfetch"),se=require("cookie"),Ue=require("p-limit"),ye=require("dataloader"),yt=require("sanitize-html"),Re=require("fast-deep-equal"),It=require("node:crypto");var On=(e=>(e.Personal="personal",e.Shared="shared",e))(On||{}),Cn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(Cn||{}),bn=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(bn||{}),wn=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(wn||{}),An=(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))(An||{}),Pn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(Pn||{}),Dn=(e=>(e.Input="Input",e.Output="Output",e))(Dn||{});const vt=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new Z("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},En=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new ie("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new ie("Authentication required"):r===403?new Z("You are not allowed to access this resource"):new ie("Authentication required")}},Ot="auth",kn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>J.mapSchema(e,{[J.MapperKind.OBJECT_FIELD]:n=>{if(J.getDirective(e,n,Ot)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await En(o),r?.(i,a,o,s))}return n}})},Ct="cacheControl",bt=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},ze=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,wt=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,Tn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>J.mapSchema(e,{[J.MapperKind.OBJECT_FIELD]:n=>{const t=J.getDirective(e,n,Ct)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,d,g)=>(d.cacheControl={sMaxAge:ze(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:ze(d.cacheControl?.staleWhileRevalidate,i),scope:wt(d.cacheControl?.scope,a)},o?.(s,c,d,g))}return n}})},_n=e=>(n,t)=>{const r=In.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,vn.makeExecutableSchema({typeDefs:r,resolvers:n}))},Un="@faststore/api",Rn="4.10.1-dev.6",Ve={name:Un,version:Rn},Ne=V.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=V.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:V.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":Rn,"@faststore_package_name":Un,"@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=V.OTELAPI.trace.setSpan(V.OTELAPI.context.active(),o);try{const c=V.OTELAPI.context.with(s,()=>e(t,r,i,a));return c instanceof Promise?c.then(d=>(o.end(),d),d=>qe(d,o,n)):(o.end(),c)}catch(c){return qe(c,o,n)}};function qe(e,n,t){throw n.setStatus({code:V.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
2
+ %o`,e),Ne("error",`Error at resolver: %s
3
+ %o`,t,e),e}class j extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class k extends j{constructor(n){super({status:400,type:"BadRequestError"},n)}}class ie extends j{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class Z extends j{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class L extends j{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Pt=e=>e?.name==="FastStoreError",Dt=e=>e?.extensions?.type==="BadRequestError",Et=e=>e?.extensions?.type==="UnauthorizedError",Nn=e=>e?.extensions?.type==="ForbiddenError",x=e=>e?.extensions?.type==="NotFoundError",kt=`${Ve.name}@${Ve.version}`,Tt=/authorization|cookie|token|secret|api-?key|appkey/i,Fn="[redacted]",xe=e=>{if(!e)return;const n={},t=(r,i)=>{n[r]=Tt.test(r)?Fn:i};return Array.isArray(e)?e.forEach(([r,i])=>t(r,i)):typeof e.forEach=="function"?e.forEach((i,a)=>t(a,i)):Object.entries(e).forEach(([r,i])=>t(r,i)),n},y=async(e,n,t)=>{const r=await St(e,{...n,headers:{...n?.headers??{},"User-Agent":kt}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(typeof e=="string"?e:e.url,n&&{...n,headers:xe(n.headers),body:n.body?Fn:void 0},{status:r.status,statusText:r.statusText,headers:xe(r.headers)});const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new k(i);case 401:throw new ie(i);case 403:throw new Z(i);case 404:throw new L(i);default:throw new j({status:r.status,type:"UnknownError"},i)}throw new Error(i)},_t=({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"}})}},Ln=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=/^([^=]+)=([^;]*)/,Rt=(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})}},Nt=(e,n)=>{n.getSetCookie().forEach(t=>Rt(e,t))},Ft=e=>n=>Nt(e,n),Oe=e=>{if(!e.headers?.cookie)return null;const n=Ln(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Lt(r,i,a),n)},Bn=e=>function(t){const r=Oe(e);return r?{...t,cookie:r}:t},$=(e,n)=>{const t=Ln(e);return se.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Lt=(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 Y(e){if(!e)return null;try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString())}catch{return null}}const Bt="storefront/faststore.recommendation-shelf@v4",re={method:"POST",headers:{"content-type":"application/json"}},$t=100,le=new Set,Mt=e=>e.split("/").map(encodeURIComponent).join("/"),Ie=e=>e?{headers:{"Accept-Language":e}}:void 0,zt=/^\d{4}-\d{2}-\d{2}$/,Vt=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function qt({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&&!zt.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!Vt.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function xt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(d=>c.append("status",d)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const jt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=Ft(i),s=Bn(i),c=vt(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(l=>l+".").find(l=>d.includes(l))||"",u=d.replace(g,""),f=`${a}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${Bt}`}),I=(l={})=>{const p=$(Oe(i)??"",e);return s({...l,"X-FORWARDED-HOST":u,...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/${Mt(l)}`,Ie(p))}catch(m){if(x(m))return null;throw m}},brand:async(l,p)=>{try{return await y(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,Ie(p))}catch(m){if(x(m))return null;throw m}},collection:async(l,p)=>{try{return await y(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,Ie(p))}catch(m){if(x(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":u});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...re,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:p,deliveryMode:m,selectedAddresses:S},v)=>{const O=v?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:p},(w,b)=>({itemIndex:b,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:O})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":u});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...re,headers:_,body:JSON.stringify(C)},{storeCookies:o})},marketingData:({id:l,marketingData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u});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,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),C=new URLSearchParams;(!S||!l)&&C.set("sc",v),l&&C.set("refreshOutdatedData",p.toString());const _=l?`/${l}`:"",w=`${a}/api/checkout/pub/orderForm${_}?${C}`;return y(w,{...re,headers:O,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return y(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...re,headers:p,body:"{}"})},updateOrderFormItems:({id:l,orderItems:p,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:v=!0})=>{const O=new URLSearchParams({allowOutdatedData:m,sc:S}),C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${O}`,{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":u});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 O=`${a}/api/checkout/pub/regions/?${v.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return y(O,{headers:C},{storeCookies:o})},address:async({postalCode:l,country:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u});return y(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:p,reason:m})},{})}},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=se.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:({name:l,email:p})=>{const m=JSON.stringify({...l?{name:l}:{},email:p,isNewsletterOptIn:!0}),S=process.env.FS_NEWSLETTER_APP_KEY,v=process.env.FS_NEWSLETTER_APP_TOKEN;if(S&&v)return y(`${a}/api/dataentities/NL/documents`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json","X-VTEX-API-AppKey":S,"X-VTEX-API-AppToken":v},body:m});if(!le.has(e)){le.size>=$t&&le.clear(),le.add(e);const O=[!S&&"FS_NEWSLETTER_APP_KEY",!v&&"FS_NEWSLETTER_APP_TOKEN"].filter(Boolean),C=`[subscribeToNewsletter] ${O.join(" and ")} ${O.length>1?"are":"is"} not set. Falling back to an anonymous Master Data request, which requires public fields in the NL entity. Configure both credentials and make the NL fields private.`;console.warn(C),Ne("warn","%s",C)}return y(`${a}/api/dataentities/NL/documents/`,{...re,body:m,method:"PATCH"},{storeCookies:o})},profile:{addresses:async l=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u});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:O,perPage:C,pendingMyApproval:_})=>{const w=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&&w.append("text",v),p&&p.length>0&&w.append("status",p.filter(Boolean).join(",")),m&&S?w.append("creation_date",`creationDate:[${m} TO ${S}]`):m?w.append("creation_date",`creationDate:[${m} TO *]`):S&&w.append("creation_date",`creationDate:[* TO ${S}]`),O&&w.append("clientEmail",O),l&&w.append("page",l.toString()),C&&w.append("per_page",C.toString()),_&&w.append("my_pending_approvals",String(!0));const b=s({"content-type":"application/json","X-FORWARDED-HOST":u});return y(`${a}/api/oms/user/orders?${w.toString()}`,{method:"GET",headers:b},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u}),_={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":u});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":u});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":u});return y(`${a}/api/units/v1/${l}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u});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":u});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":u});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":u});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 k("Missing contractId to fetch CL fields.");const p=I({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 k("Missing userId to fetch shopper name.");const p=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),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=>{qt(l);const p=xt(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});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":u}),p=$(Oe(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":u}),v=`----FastStoreUploadBoundary${Date.now()}`,O=`\r
4
+ `,_=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",w=p.replaceAll(/[\r\n"]/g,"_"),b=[`--${v}`,`Content-Disposition: form-data; name="file"; filename="${w}"`,`Content-Type: ${_}`,"",""].join(O),A=`${O}--${v}--${O}`,E=Buffer.from(b),T=Buffer.from(A),D=new Uint8Array(E.byteLength+l.byteLength+T.byteLength);let U=0;return D.set(E,U),U+=E.byteLength,D.set(l,U),U+=l.byteLength,D.set(T,U),y(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${v}`},body:D.buffer},{})},startOperation:({objectKey:l,orderFormId:p,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":u}),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":u});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":u});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":u});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 O=new URLSearchParams({an:e,campaignVrn:l});return p&&O.append("userId",p),m.length>0&&O.append("products",m.join(",")),S&&O.append("salesChannel",S),v&&O.append("locale",v),y(`${f}/recommendations?${O.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})}}}},oe=e=>e.discoveryConfig?.localization??{},Q=e=>oe(e).enabled===!0,Wt=e=>Object.keys(oe(e).locales??{}),Ht=e=>oe(e).defaultLocale,$n=e=>Q(e)&&e.storage.locale||void 0,Ce="fuzzy",be="operator",we="pickupPoint",je="shipping",We="delivery-options",Gt="in-stock",Xt="trade-policy",Yt="region-id",Kt=new Set([Xt,Yt,Ce,be,we]),Jt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),He=e=>encodeURI(decodeURI(e)),Qt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Zt=/^pickup-in-point-(.+)$/;function Fe(e){if(!e)return{};try{const t=se.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function er(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||(Jt.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function Mn(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=er(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 nr(e){return Mn(e).extraFacets}function zn(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function Vn(e){return Zt.exec(e)?.[1]}function tr(e){const n=e.find(r=>r.key==="shipping"),t=n?Vn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function rr(e,n){const t=tr(n);return t===void 0?e:{...e,pickupPoint:t}}function ir(e){return e.map(n=>n.key!=="shipping"||Vn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function ar(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")),ir(t)}function qn(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}${He(r)}/${Qt(He(i)).replaceAll(/ |%20/g,"-")}/`},"")}const or=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),sr=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function cr(e,n){const{segmentParams:t,extraFacets:r}=Mn(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 lr(e,n){const t=e.filter(({key:c})=>!Kt.has(c)),r=e.find(({key:c,value:d})=>c===je&&d!=="all-delivery-methods")??null,i=e.find(({key:c,value:d})=>c===We&&d!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===je),s=a.some(({key:c})=>c===We);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),ar(a,n)}function dr(e,n){const t=e.find(({key:a})=>a===Ce)??null,r=e.find(({key:a})=>a===be)??null,i=e.find(({key:a})=>a===we)??null;t&&or(t)&&n.append(Ce,t.value),r&&sr(r)&&n.append(be,r.value),i&&n.append(we,i.value)}function Ge(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:g,hideUnavailableItems:u,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 I=rr(t.segmentParams,c);if(zn(h,I??t.segmentParams),dr(c,h),d&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const p=c.find(({key:S})=>S===Gt),m=p?p.value:u?.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()),g!==void 0&&h.append("sponsoredCount",g.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=qn(lr(c,t.extraFacets));return{params:h,path:l}}function ur(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return zn(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function de(e){return(e??"").replaceAll(/[\s-]/g,"").toUpperCase()}function pr(e,n){const{segmentParams:t,extraFacets:r}=n,{postalCode:i,country:a,coordinates:o}=e,s=!!i,c=a||t.country,d=s&&de(i)===de(t["zip-code"])&&de(c)===de(t.country),g=s?i:t["zip-code"],u=s?c:t.country,f=d?t.coordinates:void 0,h=s?o??f:o||t.coordinates,I=!s||d,l=!!(t.deliveryZonesHash&&t.pickupPointHash);if((!g||!u)&&!!!h&&!(I&&l))throw new Error("Missing delivery location for pickup point availability. Provide postalCode and country, coordinates, or a segment with zip-code.");const m=new URLSearchParams,S=(v,O)=>{O!=null&&String(O)!==""&&m.append(v,String(O))};return S("sc",t.sc),S("locale",t.locale),S("country",u),S("zip-code",g),S("coordinates",h),I&&(S("deliveryZonesHash",t.deliveryZonesHash),S("pickupPointsHash",t.pickupPointHash)),{params:m,path:qn(r)}}function H(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function G(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=cr(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Ge(i,r,a,{includePagination:!0,includeSort:!0});return H(s,o)}case"catalog-count":{const{params:o,path:s}=Ge(i,r,a,{includePagination:!1,includeSort:!1});return H(s,o)}case"products":{const o=ur(i,a.segmentParams);return H("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return H("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return H("",o)}case"pickup-point-availability":{const{params:o,path:s}=pr(i,a);return H(s,o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const gr=10;function mr(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function hr(e){const t=Fe(e.headers?.cookie).cultureInfo||"";return Q(e)?e.storage.locale||t:t||e.storage.locale||""}const fr=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=Bn(o),d=Fe(o.headers?.cookie),g=()=>({salesChannel:o.storage.channel.salesChannel,regionId:mr(o),locale:hr(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",f=a&&a.map(b=>b+".").find(b=>u.includes(b))||"",h=u.replace(f,""),I=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:b,...A})=>{const E=b==="facets"?"facets":"product-search",T=G({endpoint:E,segment:d,defaults:g(),args:A});return y(`${s}/api/intelligent-search/v1/${E}/${T.path}?${T.params.toString()}`,{headers:I})},p=b=>l({...b,type:"product_search"}),m=({field:b,value:A,hideUnavailableItems:E,showInvisibleItems:T})=>{const D=G({endpoint:"products",segment:d,defaults:g(),args:{field:b,value:A,hideUnavailableItems:E,showInvisibleItems:T}});return y(`${s}/api/intelligent-search/v1/products?${D.params.toString()}`,{headers:I})};return{facets:b=>l({...b,type:"facets"}),products:p,fetchProduct:m,productsByIdentifier:async({field:b,values:A,showInvisibleItems:E,hideUnavailableItems:T,throwOnUpstreamError:D=!1})=>{const U=Ue(gr);return(await Promise.all(A.map(R=>U(async()=>{try{return await m({field:b,value:R,hideUnavailableItems:T,showInvisibleItems:E})}catch(M){if(D&&!x(M))throw M;return null}})))).filter(R=>R!==null)},suggestedTerms:b=>{const A=G({endpoint:"search-suggestions",segment:d,defaults:g(),args:{query:b.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${A.params.toString()}`,{headers:I})},topSearches:()=>{const b=G({endpoint:"top-searches",segment:d,defaults:g()});return y(`${s}/api/intelligent-search/v1/top-searches?${b.params.toString()}`,{headers:I})},productCount:b=>{const A=G({endpoint:"catalog-count",segment:d,defaults:g(),args:b});return y(`${s}/api/intelligent-search/v1/catalog-count/${A.path}?${A.params.toString()}`,{headers:I})},pickupPointAvailability:({postalCode:b,country:A,coordinates:E})=>{const T=G({endpoint:"pickup-point-availability",segment:d,defaults:g(),args:{postalCode:b,country:A,coordinates:E}}),D=T.path?`/${T.path}`:"";return y(`${s}/api/intelligent-search/v1/pickup-point-availability${D}?${T.params.toString()}`,{headers:I})}}},Sr=(e,n)=>{const t=fr(e,n),r=jt(e,n),i=_t(e);return{search:t,commerce:r,catalog:i}},yr=20,Ir=e=>e.entityType==="category",Ae=e=>e.entityType==="brand",Xe=e=>e.entityType==="collection",vr=(e,n)=>{const t=Ue(yr),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const d=await n.commerce.catalog.byLinkId.brand(o,s);if(d)return{...d,entityType:"brand"};const g=await n.commerce.catalog.byLinkId.collection(o,s);if(g)return{...g,entityType:"collection"};throw new L(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new ye(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},Or=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ye(t)},Cr=1,br=(e,n)=>{const t=Ue(Cr),r=async a=>{const o=a.reduce((u,{items:f})=>[...u,f],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((u,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<u.length&&(u[h]=f),u},Array(s.length).fill(null)),g=o.reduce((u,f)=>[...u,f.length+u[u.length-1]],[0]);return o.map((u,f)=>({...c,items:d.slice(g[f],g[f+1]).filter(h=>!!h)}))},i=async a=>t(r,a);return new ye(i,{maxBatchSize:50})},wr=(e,n)=>yt(e,n);function Ar(e){return{...e,description:e.description?wr(e.description):e.description}}const B=(e,n)=>({...e,isVariantOf:Ar(n)}),Pr=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),a=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,throwOnUpstreamError:!0,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,u)=>{for(const f of u.items)g[f.itemId]=B(f,u);return g},{}),c=i.map(g=>s[g]),d=i.filter(g=>!s[g]);if(d.length>0)throw new L(`Search API did not found the following skus: ${d.join(",")}`);return c};return new ye(t,{maxBatchSize:99})},Dr=(e,n)=>{const{clients:t}=n,r=Pr(e,t),i=br(e,t),a=vr(e,t),o=Or(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},q=e=>e.AvailableQuantity>0,ee=e=>e.spotPrice??0,Er=e=>e.Price??0,Ye=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",xn=(e,n)=>q(e)&&!q(n)?-1:!q(e)&&q(n)?1:ee(e)-ee(n),kr=e=>e==="available",K=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},Tr=(e,n={includeTaxes:!1})=>{const t=e.filter(q),r=t[t.length-1],i=r?ee(r):0;return n.includeTaxes?K(i,r?.Tax,r?.product?.unitMultiplier):i},Ke=(e,n={includeTaxes:!1})=>{const[t]=e.filter(q),r=t?ee(t):0;return n.includeTaxes?K(r,t?.Tax,t?.product?.unitMultiplier):r},_r={highPrice:e=>Tr(e),lowPrice:e=>Ke(e),lowPriceWithTaxes:e=>Ke(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},Ur={ratingValue:()=>5,reviewCount:()=>0},Je="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",Rr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",Nr=e=>{let n=e.slice(0);for(let t=0;t<Je.length;t++)n=n.replace(new RegExp(Je.charAt(t),"g"),Rr.charAt(t));return n},Fr=e=>e.replace(/[·/_,:]/,"-");function he(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return Fr(Nr(t)).toLowerCase()}const ve=e=>e.toLowerCase(),ue=(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:$n(e)})))},X=e=>Ir(e)?e.slug:Ae(e)?e.linkId:e.linkId??he(e.name),jn={id:({id:e})=>e.toString(),slug:e=>X(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>Ae(e)?"Brand":Xe(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=X(e);if(Ae(e))return{selectedFacets:[{key:"brand",value:r}]};if(Xe(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=oe(t);return{selectedFacets:(await ue(t,r)).map((o,s)=>({key:`category-${s+1}`,value:i&&o.availableLinkIds?.[i]||o.linkId}))}},breadcrumbList:async(e,n,t)=>{const r=await ue(t,X(e));return{itemListElement:r.map((i,a)=>({item:`/${X(i)}`,name:i.name,position:a+1})),numberOfItems:r.length}},otherLocales:async(e,n,t)=>{const r=oe(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const a=X(e);if(a.split("/").filter(Boolean).length===0)return null;let o;try{o=await ue(t,a)}catch(s){return console.warn("[otherLocales] failed to load collection entities:",s),null}return i.map(s=>{const c=[];for(const d of o){const g=d.availableLinkIds?.[s];if(!g)return null;c.push(g)}return c.length>0?{locale:s,slug:ve(c.join("/"))}:null}).filter(s=>s!==null)},canonicalSlug:async(e,n,t)=>{const r=X(e);if(r.split("/").filter(Boolean).length===0)return null;let i;try{i=await ue(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)?ve(a.join("/")):ve(r)}},Wn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ze=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},Lr=e=>typeof Wn[e]=="string",Br=e=>{const n=e?.filter(t=>Lr(t.key));if(Array.isArray(n)&&n.length>1)throw new k(`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},$r=e=>e?.find(n=>n.key==="slug")?.value??null,Mr=e=>e?.find(n=>n.key==="id")?.value??null,en=e=>e?.find(n=>n.key==="locale")?.value??null,nn=e=>e?.find(n=>n.key==="channel")?.value??null,Pe=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},zr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Vr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},qr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ze(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Pe(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=Ze(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Pe(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},xr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},jr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new k("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function Hn(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 Wr(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 Hr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=Hn(r);return{isPendingForOtherAuthorizer:!i&&Wr(r),ruleForAuthorization:i}},Gr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new k("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})},Xr=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},Yr=254,tn=100,Kr=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,Jr=async(e,{data:n},{clients:{commerce:t}})=>{const r=n.email?.trim().toLowerCase()??"",i=n.name?.trim()??"";if(r.length>Yr||!Kr.test(r))throw new k("Invalid email");if(i.length>tn)throw new k(`Invalid name: must have at most ${tn} characters`);return{id:(await t.subscribeToNewsletter({email:r,name:i||void 0}))?.Id}},Qr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new k("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 k("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 k("Invalid Base64 fileContent");const g=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:a})};class ce{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}function Zr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:ce.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}function ei(e,n,t){return t!=null&&String(e.salesChannel??"")===t&&String(n??"")!==t?!1:e.items.length>0?!0:e.salesChannel==null||e.salesChannel===""?!1:String(e.salesChannel)===String(n??"")}const Gn=e=>{try{return JSON.parse(e??"")??{}}catch{return{}}};function Xn(e,{localizationEnabled:n=!0}={}){const t=Gn(e).salesChannelSource;return t==="url"?n?t:void 0:t==="orderForm"?t:void 0}const Yn=e=>!!e?.localization?.enabled;function Kn(e){const n=Gn(e).rejectedSalesChannel;return(typeof n=="string"||typeof n=="number")&&String(n)||void 0}function ni(e,n,t,r,i,a){const o=n??void 0,s=t??e.regionId,c=i?e.salesChannel||o:o??e.salesChannel,d=a!=null&&a!==String(c??"");return ce.stringify({salesChannel:c,regionId:s??void 0,seller:r,hasOnlyDefaultSalesChannel:!o,...i?{salesChannelSource:i}:{},...d?{rejectedSalesChannel:a}:{}})}const rn="1";function ti(e,n,t,r){const i=String(e.salesChannel??"");return n===void 0&&i===rn&&!!t&&t!==rn&&!new URLSearchParams(r).has("sc")?t:i}const ae=(e,n)=>{e.storage.channel=ce.parse(n)},De=(e,n)=>{e.storage.locale=n},Le=e=>It.createHash("md5").update(e).digest("hex"),W={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE",service:"SERVICE"};function Jn(e){return{name:e.name,value:e.content,valueReference:W.attachment}}function ri(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:W.attribute,visible:e.visible}}}function Qn(e){return Le(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Zn=(e,n)=>e<n?-1:e>n?1:0,ii=(e,n)=>Zn(e.name,n.name),ai=e=>[...e??[]].sort(ii),an=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oi=e=>an(e)&&typeof e.name=="string"&&an(e.content),si=e=>({name:e.name,content:Object.fromEntries(Object.keys(e.content).sort(Zn).map(n=>[n,e.content[n]]))}),et=(e,n)=>Le(`SERVICE:${e}:${JSON.stringify(ai((n??[]).filter(oi)).map(si))}`),ci="SERVICE:unreadable";function Be(e){const n=e.attachments??[];return{propertyID:et(e.id,n),name:e.name,value:{id:e.id,price:e.sellingPrice/100,attachments:n},valueReference:W.service}}const li=e=>{try{return JSON.parse(e)}catch{return null}},di=e=>{const n=typeof e=="string"?li(e):e;if(n===null||typeof n!="object")return null;const{id:t,attachments:r}=n;return typeof t!="string"&&typeof t!="number"?null:{id:String(t),attachments:r}};function ui(e){const n=di(e.value);return n?et(n.id,Array.isArray(n.attachments)?n.attachments:[]):ci}const pi=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]},gi=(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},nt=(e,n)=>{if(!mi(n))return{updateShipping:!1,addressChanged:!1};if(!yi(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(hi(t,n.postalCode)||fi(t,n.geoCoordinates)||Si(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Ii(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},mi=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,hi=(e,n)=>typeof n=="string"&&e?.postalCode!==n,fi=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Si=(e,n)=>typeof n=="string"&&e?.addressType!==n,yi=e=>e.items.length!==0,Ii=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,g=r&&s!==r;return c?.some(u=>d&&u.deliveryChannel===t||g&&u.id===r?!0:i&&a&&u.deliveryChannel===t&&u.id===r&&(!u?.deliveryWindow||u?.deliveryWindow?.startDateUtc!==i||u?.deliveryWindow?.endDateUtc!==a)&&u.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===a))})},tt=e=>e.valueReference===W.attachment,vi=e=>e.valueReference===W.service,Oi=e=>(e.itemOffered.additionalProperty??[]).filter(vi).map(ui).sort((n,t)=>n.localeCompare(t)),rt=e=>{const n=Oi(e);return n.length>0?`services:${n.join("-")}`:void 0},Ee=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(tt).map(Qn).join("-"),rt(e)].filter(Boolean).join("::"),fe=(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(Jn),...(e.bundleItems??[]).map(Be)]},index:n}),Ci=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(tt)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),on=e=>e.reduce((n,t)=>{const r=Ee(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),bi=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},services:rt(c),index:d}),r=n.items.map(fe).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Re(r,i);return a&&o};function it(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function at(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const sn=e=>{const n=e.items.reduce((t,r,i)=>{const a=at(e.items,r.id)||it(e.items,r.id)?`${Ee(fe(r))}::${i}`:Ee(fe(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}})}},ke=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()}))}),ot=({items:e},n)=>{const t=e.map(r=>{const i=(r.bundleItems??[]).map(Be).map(({propertyID:a})=>a).sort((a,o)=>a.localeCompare(o));return{id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments,...i.length>0?{services:i}:{}}});return Le(JSON.stringify({sessionId:n?.id??"",items:t}))},cn=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:ot(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}},Oi=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:it(e,n)!==r},Ci=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),sn=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=Zn(e,n);if(r){const a=di(e,n,i),s=a||li(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},bi=(e,n)=>{if(!e)return"";const r=oe.parse(e)[n];return r?r.split("=")[1]:""},wi=async(e,n,t,r)=>{const{commerce:i}=e.clients,a=await i.checkout.orderForm({id:n,channel:e.storage.channel,preserveSalesChannel:!!n&&!t});return!n||Jr(a,e.storage.channel.salesChannel,r)?a:i.checkout.orderForm({id:n,channel:e.storage.channel})},cn=(e,n,t)=>{if(!t||n.items.length===0)return null;const r=Kr(e.storage.channel,n.salesChannel);return r?(ie(e,r),n.salesChannel?String(n.salesChannel):null):null},ln=(e,n,t,r)=>r?Te(e,n,t,r):null,Ai=async(e,{cart:{order:n},session:t},r)=>{const i=bi(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale,d=Hn(s,{localizationEnabled:Gn(r.discoveryConfig)})==="url",g=Xn(s);s&&ie(r,s),c&&Ee(r,c);const p=await wi(r,i||void 0,d,g),f=p.orderFormId;p.messages.length!==0&&await Ci(f,r);const h=oe.parse(r?.headers?.cookie??"")?.vtex_session,I=G(h),{acceptedOffer:l,shouldSplitItem:u}=n;if(Oi(p,I)){const w=cn(r,p,!d),F=await on(p,a,I).then(an);if(f)return Te(F,o,u,w)}const S=cn(r,p,!d),v=rn(l),b=rn(p.items.map(Se)),O=Array.from(b.entries()),_=Array.from(v.entries()),{itemsToAdd:A,itemsToUpdate:C}=_.reduce((w,[F,ee])=>{const ce=b.get(F);if(!ce)return ee.forEach(ne=>w.itemsToAdd.push(ne)),w;const[M,...le]=ce;if(rt(p.items,M.itemOffered.sku)||tt(p.items,M.itemOffered.sku))return w.itemsToUpdate.push(M),w;const pt=ee.reduce((ne,gt)=>ne+gt.quantity,0);return w.itemsToUpdate.push({...M,quantity:pt}),le.forEach(ne=>w.itemsToUpdate.push({...ne,quantity:0})),w},{itemsToAdd:[],itemsToUpdate:[]}),D=O.filter(([w])=>!v.has(w)).flatMap(([,w])=>w.map(F=>({...F,quantity:0}))),P=[...A,...C,...D].map(Ii),{updateShipping:T}=t?Zn(p,t):{updateShipping:!1};if(P.length===0&&!T)return ln(p,o,u,S);let E;P.length>0?E=await a.checkout.updateOrderFormItems({id:p.orderFormId,orderItems:P,shouldSplitItem:u}).then(w=>sn(w,t,r)):E=await sn(p,t,r),E=await Promise.resolve(E).then(w=>{if(t?.marketingData){const F={...w.marketingData,...t.marketingData};return a.checkout.marketingData({id:p.orderFormId,marketingData:F})}return w}).then(w=>c&&w.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:w.orderFormId,clientPreferencesData:{...w.clientPreferencesData,locale:c}}):w).then(w=>on(w,a,I)).then(an);const U=Ne(p.messages,E.messages);return vi(n,E)&&U?ln(E,o,u,S):Te(E,o,u,S)},Pi=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Di=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"},Ei=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Di):[]},ki=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,dn=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Ti=e=>{if(!Array.isArray(e)||e.length===0)return"";const n=e.find(t=>t?.isDefault===!0)??e[0];return String(n?.id??"").trim()},_i=(e,n="",t="")=>{const r=n.trim(),i=t.trim();return e.filter(ki).map(a=>({id:a.customerId,corporateName:a.contractName.trim(),isActive:r?a.customerId===r:a.isCurrent,isDefault:i!==""&&a.customerId===i}))},at=(e,n)=>{const t=Pi(e);return t||(n?.firstName?.value??"").trim()};async function Ui(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 Ri(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 Ni(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 Fi(e,n,t){const r=G(B(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 Li(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 un(e){return typeof e?.value=="string"?e.value:""}function Bi(e){if(!e.isRepresentative)return null;const n=un(e.shopper?.firstName),t=un(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:at(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function $i(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const Mi=e=>e instanceof q&&(e.extensions.status===401||e.extensions.status===403),zi=e=>e instanceof Error&&/sales\s*channel/i.test(e.message),Vi=(e,n,t,r)=>{if(n!=="orderForm"||t!==r)return!1;if(zi(e))return!0;const i=`[validateSession] Session Manager rejected adopted sales channel ${t} with an unrecognized error; keeping the adoption.`,a=e instanceof Error?e.message:e;return console.warn(i,a),Fe("warn","%s %o",i,a),!1},qi=async(e,n,t,r)=>{const i={salesChannelSource:t,rejectedSalesChannel:void 0};try{return{...i,sessionData:await e.commerce.session(n.toString())}}catch(a){if(t==="url"||!Mi(a))return{...i,sessionData:null};const o=n.get("sc")??void 0,s=Vi(a,t,o,r);n.delete("sc");const c=await e.commerce.session(n.toString()).catch(()=>null);return!c||!s?{...i,sessionData:c}:{sessionData:c,salesChannelSource:void 0,rejectedSalesChannel:o}}},xi=async(e,{session:n,search:t},{clients:r,headers:i,account:a,storage:o,discoveryConfig:s})=>{const c=se.parse(n.channel??""),d=Hn(n.channel,{localizationEnabled:Gn(s)}),g={...c,salesChannel:Zr(c,d,o?.channel?.salesChannel?String(o.channel.salesChannel):void 0,t)},p=String(n.postalCode??""),f=n.country??"";let h=n.city??null,I=n.geoCoordinates??null;if((!h||!I)&&p!==""&&f!==""){const le=await Ui(r,f,p);h=le.city,I=le.geoCoordinates}const u=Ri(t,g,p,f,I,n.locale),m=Ni(u,n.marketingData),{isRepresentative:S,customerId:v,unitId:b}=await Fi(r,i?.cookie,a),{sessionData:O,salesChannelSource:_,rejectedSalesChannel:A}=await qi(r,u,d,String(g.salesChannel??"")),C=O?.namespaces.profile??null,D=O?.namespaces.shopper??null,P=O?.namespaces.store??null,T=O?.namespaces.authentication??null,E=O?.namespaces.checkout??null,U=O?.namespaces.public??null;let w=null;if(S&&C?.id?.value)try{w=await r.commerce.masterData.getContractById({contractId:C.id.value})}catch{console.error(`Error while getting contract data for profile ID (${C.id.value}).
9
- `)}const F=await Li(r,g,p,I,f,u.get("sc")??P?.channel?.value??g.salesChannel),ee=$i(C),ce=(n.person?.id??null)===(ee?.id??null)?Xn(n.channel):void 0,M={...n,currency:{code:P?.currencyCode?.value??n.currency.code,symbol:P?.currencySymbol?.value??n.currency.symbol},country:P?.countryCode?.value??f,channel:Qr(g,P?.channel?.value,E?.regionId?.value,F,_,A??ce),b2b:Bi({isRepresentative:S,authentication:T,shopper:D,publicData:U,profile:C,contract:w,customerId:v,unitId:b}),marketingData:m,person:ee,geoCoordinates:I?.latitude&&I?.longitude&&I||null,city:h};return Ne(n,M)?null:M},ji={validateCart:Ai,validateSession:xi,subscribeToNewsletter:Xr,cancelOrder:Vr,processOrderAuthorization:xr,uploadFileToOrderEntry:Yr,startOrderEntryOperation:jr,startRecommendationSession:Wr};var _e;(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"})(_e||(_e={}));const Wi=e=>typeof e=="string"?ot(e):null;function ot(e){try{return JSON.parse(e)}catch{return e}}const Hi=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Gi=new he.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Wi,serialize:Hi,parseLiteral(e){return e.kind===_e.STRING?ot(e.value):null}}),R=e=>"Price"in e&&"seller"in e&&"product"in e,N=e=>"skuName"in e,Xi={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>R(e)?e.PriceValidUntil??"":N(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>R(e)?Ge(V(e)):N(e)?Ge(Pr(e.availability)):null,seller:(e,n,t)=>R(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:N(e)?{identifier:e.seller}:null,price:e=>R(e)?Z(e):N(e)?e.sellingPrice/100:null,priceWithTaxes:e=>R(e)?X(Z(e),e?.Tax,e.product.unitMultiplier):N(e)?X(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>R(e)?Ar(e):N(e)?e.sellingPrice/100:null,listPrice:e=>R(e)?e.ListPrice??0:N(e)?e.listPrice/100:null,listPriceWithTaxes:e=>R(e)?X(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):N(e)?X(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>R(e)?e.product:N(e)?{...e.product,attachmentsValues:e.attachments,servicesValues:e.bundleItems??[]}:null,quantity:e=>R(e)?e.AvailableQuantity??0:N(e)?e.quantity:null,isGift:e=>N(e)?e.isGift??!1:null,priceToken:e=>R(e)?e.PriceToken??null:null},Yi=({linkText:e})=>`/${e}/p`,Ki=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Ji={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},ge=(e,n)=>`${e}-${n}`,pn=(e,n)=>`/${ge(e,n)}/p`,Qi=e=>Array.isArray(e)&&e.length>0?e:null;function Ue(e){return e.replace(/^\/+|\/+$/g,"")}async function me(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 Zi=(e,n)=>{const t=e.findIndex(r=>Ue(r).split("/").at(-1)===n);return t<0?0:t},ea={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>ge(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Yi(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:d}=e,g=Zi(s,o),p=r[g],f=Ue(p).split("/"),h=t.storage.locale;if(J(t)&&h){const I=await me(t,c,h);if(I){const l=new Set(Ue(s[g]).split("/").filter(Boolean)),u=I.categories.filter(S=>l.has(S.id.toString())).sort((S,v)=>S.fullPath.split("/").length-v.fullPath.split("/").length);if(u.length===f.length)return{itemListElement:[...u.map((S,v)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:v+1})),{name:i,item:pn(I.linkId,d),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((I,l)=>{const u=`/${f.slice(0,l+1).map(fe).join("/")}/`;return{name:I,item:u,position:l+1}}),{name:i,item:pn(a,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(Qi(e)??[Ji]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>Ki({offer:n.commertialOffer,seller:n,product:e})).sort(Vn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[],servicesValues:r=[]})=>{const i=e.flatMap(({name:c,values:d})=>d.map(g=>({name:c,value:g,valueReference:x.specification}))),a=n.map(Yn),o=t.map(ei),s=r.map(Be);return[...i,...a,...o,...s]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!J(t))return null;const r=qt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=await me(t,i,o);if(!s?.availableLinkIds)return null;const{availableLinkIds:c}=s;return r.map(d=>{const g=c[d];return g?{locale:d,slug:ge(g,a)}:null}).filter(d=>d!==null)},defaultLocaleSlug:async(e,n,t)=>{if(!J(t))return null;const r=xt(t);if(!r)return null;const{productId:i,linkText:a}=e.isVariantOf,o=e.itemId,c=(await me(t,i,t.storage.locale))?.availableLinkIds?.[r]??a;return ge(c,o)}},na=new Set(["allSpecifications"]),ta={hasVariant:e=>e.isVariantOf.items.map(n=>L(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,productClusters:({isVariantOf:e})=>e.productClusters??[],name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!na.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:x.specification}))))},ra={propertyID:e=>e.propertyID||Kn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},ye=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=De(n,({offer:r},{offer:i})=>Vn(r,i));return t?t.sku:e[0]},st=e=>e!==""&&!Number.isNaN(Number(e)),ia=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,aa=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!ia.test(s))throw new k(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new k("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(h=>!h?.trim())))throw new k("Invalid products: must be an array of non-empty strings");const d=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:g,correlationId:p}=d;return{products:(d.products??[]).map(h=>{const I=ye(h.items);return I?L(I,h):null}).filter(h=>!!h),correlationId:p,campaign:g}},gn={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:""};function oa(e,n){let t;if(Object.hasOwn(n,e)?t=n[e]:Object.hasOwn(gn,e)&&(t=gn[e]),t===void 0)throw new k(`Unknown sort value: ${e}`);return t}const sa=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new k("Missing operationId");return t.orderEntry.getOperation({operationId:n})},ca=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new k("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 la(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await me(e,t,r))?.linkId===i}const ct="Invalid SkuId",lt="Slug was set but the fetched sku does not satisfy the slug condition.",da="UseAdHocCard",ua=e=>K(e)||e instanceof Error&&(e.message===ct||e.message.startsWith(lt));async function pa(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||J(e)&&r&&st(t.split("-").pop()??"")&&await la(e,t,a,r)))throw new Error(`${lt} slug: ${t}, linkText: ${i}`)}async function ga(e,n){if(n==null)throw new k("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 $(`No product found for slug ${n}`);const a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new $(`No product found for id ${i.id}`);return L(ye(a.items),a)}const ma={product:async(e,{locator:n},t)=>{const r=Ze(n),i=Qe(n),a=Lr(n),o=Fr(n);r&&ie(t,r),i&&Ee(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!st(c))throw new Error(ct);const d=await s.load(c);return await pa(t,d,o,i),d}catch(c){if(!ua(c))throw c;return ga(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:Ln(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Ze(a),d=Qe(a),g=Nr(a);c&&ie(s,c),d&&Ee(s,d);const p=t?Number(t):0,f={page:Math.ceil(p/n)||0,count:n,query:i??void 0,sort:oa(r??"score_desc",s.storage.customSortMap),selectedFacets:a?.flatMap(Ke)??[],sponsoredCount:o??void 0};if(g){const l=(await s.clients.commerce.catalog.products.crossselling({type:xn[g.key],productId:g.value})).map(m=>m.productId).slice(0,n),u=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:u}}const h=s.clients.search.products(f);return{searchArgs:f,productSearchPromise:h}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/n),count:n}),s=o.products.flatMap(c=>c.items.map(d=>L(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(a+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>L(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],d=(h,I)=>{c.push({id:h.id,name:h.name,fatherCategoryId:I,linkId:fe(h.name),title:h.Title,description:null,metaTagDescription:h.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(h.url).pathname.slice(1).toLowerCase()});for(const l of h.children)d(l,h.id)};for(const h of s)d(h,null);const f=[...o.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:fe(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!qn.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,I)=>({node:h,cursor:(a+I).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(Ke)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:g}=c;return{id:d,sellers:g}},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 k("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new $(`No order found for id ${n}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=jn(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 K(r)?new $(`No order found for id ${n}. ${o}.`):Un(r)?new Q(`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=G(B(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:da}).catch(()=>null);return typeof c=="boolean"?c:!0},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const g=[d.firstName,d.lastName].filter(Boolean).join(" ");g&&o.set(c,g)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?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=G(B(i?.cookie??"",r))?.userId??"",[c,d,g]=await Promise.all([a.session("").catch(()=>null),s?a.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?a.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),p=d?.[0],f=c?.namespaces.authentication??null,h=`${(p?.firstName??"").trim()} ${(p?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:p?.phone??"",role:g?.Roles?.map(I=>I.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=G(B(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null,g=c.namespaces.shopper??null,p=c.namespaces.authentication??null,f=dn(c)||o?.customerId?.trim()||"";let h=null;if(f)try{h=await a.masterData.getContractById({contractId:f})}catch(u){console.error(`Error while getting contract data for contract ID (${f}).`,u)}const I=`${(g?.firstName?.value??"").trim()} ${(g?.lastName?.value??"").trim()}`.trim();return{name:at(h,d)||I||"",email:d?.email?.value||p?.storeUserEmail?.value||"",id:d?.id?.value||p?.customerId?.value||o?.customerId?.trim()||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new k("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:a}}=t,o=await a.session("").catch(()=>null),s=B(i?.cookie??"",r);let c=null;try{c=s?G(s):null}catch{c=null}const d=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new Q("You are not allowed to list contracts for this organization unit");const g=Ei(o?.namespaces.shopper),p=dn(o)||c?.customerId?.trim()||"",f=await a.storeFront.attachedContracts(n).catch(I=>(console.warn("availableContracts: default contract lookup failed",I),null)),h=Ti(f?.contracts);return _i(g,p,h)},pickupPoints:async(e,{geoCoordinates:n,postalCode:t,country:r,channel:i},a)=>{const{clients:{search:o}}=a;i&&ie(a,i);const s=n?.longitude!=null&&n?.latitude!=null?`${n.longitude},${n.latitude}`:void 0;return{pickupPointDistances:(await o.pickupPointAvailability({postalCode:t??void 0,country:r??void 0,coordinates:s}))?.pickupPointDistances??[],pickupPointsHash:null}},orderEntryOperation:sa,orderFormItems:ca,recommendations:aa},ha={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},fa=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Sa={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(p=>({value:p.term,count:p.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(g=>{const p=ye(g.items);return p&&L(p,g)}).filter(g=>!!g),{searches:d}=o;return{terms:d.map(g=>({value:g.term,count:g.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=ye(r.items);return i&&L(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!fa(d,o,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},ya={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Ia=["bd","d","h","m"],va=e=>Ia.includes(e),Oa={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"}},dt=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=va(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return Oa[t][a].replace("#",n)??""},Ca={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?dt(e.shippingEstimate):""},mn="skuvariation";function hn(e,n){const t=`${mn}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===mn);return i||e[0]}function ba(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function fn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function wa(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Aa(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Pa(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>Aa(i.value,a.value));return n}function Da(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=hn(a.images,n),g={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(g):r[o.name]=[g];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const g=hn(a.images,c.name),p={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(p):r[c.name]=[p]})}),Pa(r)}const Ea={activeVariations:e=>fn(e.variations),allVariantsByName:e=>wa(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>ba(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=fn(e.variations)[t];return Da(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>L(n,e.isVariantOf))},ka={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Ta={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((d,g)=>{const p=g?.selectedSla||"",f=g?.selectedDeliveryChannel||g?.deliveryChannel||"",h=g?.deliveryCompany||"",I=g?.deliveryWindow,l=g?.pickupStoreInfo,u=g?.shippingEstimate||"",m=g?.shippingEstimate?dt(g?.shippingEstimate):"",S=g?.shippingEstimateDate||"",v=g?.addressId||"",b=g?.itemIndex??0,O=t?.[b],_=O?.seller||"",A=`${p}|${f}|${h}|${_}|${u}|${S}|${v}|${I?.startDateUtc}|${I?.endDateUtc}`,C=i?.find(U=>U?.addressId===v),D=`${ka[f]||""} ${m} ${C?.neighborhood?`to ${C?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:P,taxPriceTags:T}=_a(O?.priceTags??[]),E=(O?.sellingPrice??0)*(O?.quantity??0)+(O?.tax??0)+(P??0);return d[A]||(d[A]={selectedSla:p,deliveryChannel:f,deliveryCompany:h,deliveryWindow:I,shippingEstimate:u,shippingEstimateDate:S,seller:_,friendlyShippingEstimate:m,friendlyDeliveryOptionName:D,address:C,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[A]&&(d[A].items?.push({id:O?.id||"",uniqueId:O?.uniqueId||"",name:O?.name||"",quantity:O?.quantity||0,price:O?.price||0,sellingPrice:O?.sellingPrice||0,imageUrl:O?.imageUrl||"",taxPriceTags:T??[],taxPriceTagsTotal:P??0,tax:O?.tax||0,total:E}),d[A].quantityOfDifferentItems=(d[A].quantityOfDifferentItems??0)+1,d[A].total=(d[A].total??0)+E),d},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function _a(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 Ua={StoreCollection:qn,StoreAggregateOffer:Er,StoreProduct:ea,StoreSeo:ya,StoreFacet:Br,StoreFacetBoolean:$r,StoreFacetRange:Mr,StoreFacetValueBoolean:zr,StoreOffer:Xi,StoreAggregateRating:kr,StoreReview:ha,StoreProductGroup:ta,StoreSearchResult:Sa,StorePropertyValue:ra,SkuVariants:Ea,ShippingSLA:Ca,UserOrderResult:Ta,ObjectOrString:Gi,Query:ma,Mutation:ji},Ra=()=>Ua,Na=`"""
7
+ More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},wi=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:ot(e,n)!==r},Ai=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),ln=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=nt(e,n);if(r){const a=gi(e,n,i),s=a||pi(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},Pi=(e,n)=>{if(!e)return"";const r=se.parse(e)[n];return r?r.split("=")[1]:""},Di=async(e,n,t,r)=>{const{commerce:i}=e.clients,a=await i.checkout.orderForm({id:n,channel:e.storage.channel,preserveSalesChannel:!!n&&!t});return!n||ei(a,e.storage.channel.salesChannel,r)?a:i.checkout.orderForm({id:n,channel:e.storage.channel})},dn=(e,n,t)=>{if(!t||n.items.length===0)return null;const r=Zr(e.storage.channel,n.salesChannel);return r?(ae(e,r),n.salesChannel?String(n.salesChannel):null):null},un=(e,n,t,r)=>r?ke(e,n,t,r):null,Ei=async(e,{cart:{order:n},session:t},r)=>{const i=Pi(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale,d=Xn(s,{localizationEnabled:Yn(r.discoveryConfig)})==="url",g=Kn(s);s&&ae(r,s),c&&De(r,c);const u=await Di(r,i||void 0,d,g),f=u.orderFormId;u.messages.length!==0&&await Ai(f,r);const h=se.parse(r?.headers?.cookie??"")?.vtex_session,I=Y(h),{acceptedOffer:l,shouldSplitItem:p}=n;if(wi(u,I)){const P=dn(r,u,!d),R=await cn(u,a,I).then(sn);if(f)return ke(R,o,p,P)}const S=dn(r,u,!d),v=on(l),O=on(u.items.map(fe)),C=Array.from(O.entries()),_=Array.from(v.entries()),{itemsToAdd:w,itemsToUpdate:b}=_.reduce((P,[R,M])=>{const ne=O.get(R);if(!ne)return M.forEach(te=>P.itemsToAdd.push(te)),P;const[z,...mt]=ne;if(at(u.items,z.itemOffered.sku)||it(u.items,z.itemOffered.sku))return P.itemsToUpdate.push(z),P;const ht=M.reduce((te,ft)=>te+ft.quantity,0);return P.itemsToUpdate.push({...z,quantity:ht}),mt.forEach(te=>P.itemsToUpdate.push({...te,quantity:0})),P},{itemsToAdd:[],itemsToUpdate:[]}),A=C.filter(([P])=>!v.has(P)).flatMap(([,P])=>P.map(R=>({...R,quantity:0}))),E=[...w,...b,...A].map(Ci),{updateShipping:T}=t?nt(u,t):{updateShipping:!1};if(E.length===0&&!T)return un(u,o,p,S);let D;E.length>0?D=await a.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:E,shouldSplitItem:p}).then(P=>ln(P,t,r)):D=await ln(u,t,r),D=await Promise.resolve(D).then(P=>{if(t?.marketingData){const R={...P.marketingData,...t.marketingData};return a.checkout.marketingData({id:u.orderFormId,marketingData:R})}return P}).then(P=>c&&P.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:P.orderFormId,clientPreferencesData:{...P.clientPreferencesData,locale:c}}):P).then(P=>cn(P,a,I)).then(sn);const U=Re(u.messages,D.messages);return bi(n,D)&&U?un(D,o,p,S):ke(D,o,p,S)},ki=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Ti=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"},_i=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Ti):[]},Ui=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Ri=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Ni=e=>{if(!Array.isArray(e)||e.length===0)return"";const n=e.find(t=>t?.isDefault===!0)??e[0];return String(n?.id??"").trim()},Fi=(e,n="",t="")=>{const r=n.trim(),i=t.trim();return e.filter(Ui).map(a=>({id:a.customerId,corporateName:a.contractName.trim(),isActive:r?a.customerId===r:a.isCurrent,isDefault:i!==""&&a.customerId===i}))},st=(e,n)=>{const t=ki(e);return t||(n?.firstName?.value??"").trim()};async function Li(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 Bi(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 $i(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 Mi(e,n,t){const r=Y($(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{customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function zi(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 pn(e){return typeof e?.value=="string"?e.value:""}function $e(...e){for(const n of e){const t=typeof n=="string"?n.trim():"";if(t)return t}return""}function Me(e,n){return $e(e?.unitId?.value,n)}function Vi(e){const n=Me(e.authentication,e.unitId),t=$e(e.shopper?.activeContractId?.value,e.authentication?.customerId?.value,e.customerId);if(!n||!t)return null;const r=pn(e.shopper?.firstName),i=pn(e.shopper?.lastName);return{isRepresentative:!0,customerId:t,unitName:e.authentication?.unitName?.value??"",unitId:n,firstName:r,lastName:i,userName:`${r} ${i}`.trim(),userEmail:e.authentication?.storeUserEmail?.value??"",savedPostalCode:e.publicData?.postalCode?.value??"",contractName:st(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function qi(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const xi=e=>e instanceof j&&(e.extensions.status===401||e.extensions.status===403),ji=e=>e instanceof Error&&/sales\s*channel/i.test(e.message),Wi=(e,n,t,r)=>{if(n!=="orderForm"||t!==r)return!1;if(ji(e))return!0;const i=`[validateSession] Session Manager rejected adopted sales channel ${t} with an unrecognized error; keeping the adoption.`,a=e instanceof Error?e.message:e;return console.warn(i,a),Ne("warn","%s %o",i,a),!1},Hi=async(e,n,t,r)=>{const i={salesChannelSource:t,rejectedSalesChannel:void 0};try{return{...i,sessionData:await e.commerce.session(n.toString())}}catch(a){if(t==="url"||!xi(a))return{...i,sessionData:null};const o=n.get("sc")??void 0,s=Wi(a,t,o,r);n.delete("sc");const c=await e.commerce.session(n.toString()).catch(()=>null);return!c||!s?{...i,sessionData:c}:{sessionData:c,salesChannelSource:void 0,rejectedSalesChannel:o}}},Gi=async(e,{session:n,search:t},{clients:r,headers:i,account:a,storage:o,discoveryConfig:s})=>{const c=ce.parse(n.channel??""),d=Xn(n.channel,{localizationEnabled:Yn(s)}),g={...c,salesChannel:ti(c,d,o?.channel?.salesChannel?String(o.channel.salesChannel):void 0,t)},u=String(n.postalCode??""),f=n.country??"";let h=n.city??null,I=n.geoCoordinates??null;if((!h||!I)&&u!==""&&f!==""){const z=await Li(r,f,u);h=z.city,I=z.geoCoordinates}const p=Bi(t,g,u,f,I,n.locale),m=$i(p,n.marketingData),{customerId:S,unitId:v}=await Mi(r,i?.cookie,a),{sessionData:O,salesChannelSource:C,rejectedSalesChannel:_}=await Hi(r,p,d,String(g.salesChannel??"")),w=O?.namespaces.profile??null,b=O?.namespaces.shopper??null,A=O?.namespaces.store??null,E=O?.namespaces.authentication??null,T=O?.namespaces.checkout??null,D=O?.namespaces.public??null;let U=null;if(Me(E,v)&&w?.id?.value)try{U=await r.commerce.masterData.getContractById({contractId:w.id.value})}catch{console.error(`Error while getting contract data for profile ID (${w.id.value}).
9
+ `)}const P=await zi(r,g,u,I,f,p.get("sc")??A?.channel?.value??g.salesChannel),R=qi(w),M=(n.person?.id??null)===(R?.id??null)?Kn(n.channel):void 0,ne={...n,currency:{code:A?.currencyCode?.value??n.currency.code,symbol:A?.currencySymbol?.value??n.currency.symbol},country:A?.countryCode?.value??f,channel:ni(g,A?.channel?.value,T?.regionId?.value,P,C,_??M),b2b:Vi({authentication:E,shopper:b,publicData:D,profile:w,contract:U,customerId:S,unitId:v}),marketingData:m,person:R,geoCoordinates:I?.latitude&&I?.longitude&&I||null,city:h};return Re(n,ne)?null:ne},Xi={validateCart:Ei,validateSession:Gi,subscribeToNewsletter:Jr,cancelOrder:jr,processOrderAuthorization:Hr,uploadFileToOrderEntry:Qr,startOrderEntryOperation:Gr,startRecommendationSession:Xr};var Te;(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"})(Te||(Te={}));const Yi=e=>typeof e=="string"?ct(e):null;function ct(e){try{return JSON.parse(e)}catch{return e}}const Ki=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Ji=new me.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Yi,serialize:Ki,parseLiteral(e){return e.kind===Te.STRING?ct(e.value):null}}),N=e=>"Price"in e&&"seller"in e&&"product"in e,F=e=>"skuName"in e,Qi={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>N(e)?e.PriceValidUntil??"":F(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>N(e)?Ye(q(e)):F(e)?Ye(kr(e.availability)):null,seller:(e,n,t)=>N(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:F(e)?{identifier:e.seller}:null,price:e=>N(e)?ee(e):F(e)?e.sellingPrice/100:null,priceWithTaxes:e=>N(e)?K(ee(e),e?.Tax,e.product.unitMultiplier):F(e)?K(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>N(e)?Er(e):F(e)?e.sellingPrice/100:null,listPrice:e=>N(e)?e.ListPrice??0:F(e)?e.listPrice/100:null,listPriceWithTaxes:e=>N(e)?K(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):F(e)?K(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>N(e)?e.product:F(e)?{...e.product,attachmentsValues:e.attachments,servicesValues:e.bundleItems??[]}:null,quantity:e=>N(e)?e.AvailableQuantity??0:F(e)?e.quantity:null,isGift:e=>F(e)?e.isGift??!1:null,priceToken:e=>N(e)?e.PriceToken??null:null},Zi=({linkText:e})=>`/${e}/p`,ea=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),na={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},pe=(e,n)=>`${e}-${n}`,gn=(e,n)=>`/${pe(e,n)}/p`,ta=e=>Array.isArray(e)&&e.length>0?e:null;function _e(e){return e.replace(/^\/+|\/+$/g,"")}async function ge(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 ra=(e,n)=>{const t=e.findIndex(r=>_e(r).split("/").at(-1)===n);return t<0?0:t},ia={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>pe(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Zi(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:d}=e,g=ra(s,o),u=r[g],f=_e(u).split("/"),h=t.storage.locale;if(Q(t)&&h){const I=await ge(t,c,h);if(I){const l=new Set(_e(s[g]).split("/").filter(Boolean)),p=I.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:gn(I.linkId,d),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((I,l)=>{const p=`/${f.slice(0,l+1).map(he).join("/")}/`;return{name:I,item:p,position:l+1}}),{name:i,item:gn(a,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(ta(e)??[na]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>ea({offer:n.commertialOffer,seller:n,product:e})).sort(xn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[],servicesValues:r=[]})=>{const i=e.flatMap(({name:c,values:d})=>d.map(g=>({name:c,value:g,valueReference:W.specification}))),a=n.map(Jn),o=t.map(ri),s=r.map(Be);return[...i,...a,...o,...s]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!Q(t))return null;const r=Wt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=await ge(t,i,o);if(!s?.availableLinkIds)return null;const{availableLinkIds:c}=s;return r.map(d=>{const g=c[d];return g?{locale:d,slug:pe(g,a)}:null}).filter(d=>d!==null)},defaultLocaleSlug:async(e,n,t)=>{if(!Q(t))return null;const r=Ht(t);if(!r)return null;const{productId:i,linkText:a}=e.isVariantOf,o=e.itemId,c=(await ge(t,i,t.storage.locale))?.availableLinkIds?.[r]??a;return pe(c,o)}},aa=new Set(["allSpecifications"]),oa={hasVariant:e=>e.isVariantOf.items.map(n=>B(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,productClusters:({isVariantOf:e})=>e.productClusters??[],name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!aa.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:W.specification}))))},sa={propertyID:e=>e.propertyID||Qn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},Se=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Pe(n,({offer:r},{offer:i})=>xn(r,i));return t?t.sku:e[0]},lt=e=>e!==""&&!Number.isNaN(Number(e)),ca=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,la=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!ca.test(s))throw new k(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new k("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(h=>!h?.trim())))throw new k("Invalid products: must be an array of non-empty strings");const d=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:g,correlationId:u}=d;return{products:(d.products??[]).map(h=>{const I=Se(h.items);return I?B(I,h):null}).filter(h=>!!h),correlationId:u,campaign:g}},da="productClusterIds",mn="not:";function ua(e){const n=new Set,t=new Set;for(const{key:r,value:i}of nr(e))if(r===da)for(const a of i.split(",")){const o=a.trim();if(o.startsWith(mn)){const s=o.slice(mn.length);s&&t.add(s)}else o&&n.add(o)}return n.size===0&&t.size===0?null:{allowed:n,excluded:t}}function pa(e,{allowed:n,excluded:t}){const r=(e??[]).map(({id:i})=>String(i));return r.some(i=>t.has(i))?!1:n.size===0||r.some(i=>n.has(i))}function ga(e,n){const t=ua(Fe(e.headers?.cookie));if(t&&!pa(n.isVariantOf.productClusters,t))throw new L(`Product ${n.isVariantOf.productId} is not in the shopper's assortment`)}const hn={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:""};function ma(e,n){let t;if(Object.hasOwn(n,e)?t=n[e]:Object.hasOwn(hn,e)&&(t=hn[e]),t===void 0)throw new k(`Unknown sort value: ${e}`);return t}const ha=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new k("Missing operationId");return t.orderEntry.getOperation({operationId:n})},fa=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new k("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 Sa(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await ge(e,t,r))?.linkId===i}const dt="Invalid SkuId",ut="Slug was set but the fetched sku does not satisfy the slug condition.",ya="UseAdHocCard",Ia=e=>x(e)||e instanceof Error&&(e.message===dt||e.message.startsWith(ut));async function va(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||Q(e)&&r&&lt(t.split("-").pop()??"")&&await Sa(e,t,a,r)))throw new Error(`${ut} slug: ${t}, linkText: ${i}`)}async function Oa(e,n){if(n==null)throw new k("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 B(Se(a.items),a)}const Ca={product:async(e,{locator:n},t)=>{const r=nn(n),i=en(n),a=Mr(n),o=$r(n);r&&ae(t,r),i&&De(t,i);const{loaders:{skuLoader:s}}=t,d=await(async()=>{try{const g=a??o?.split("-").pop()??"";if(!lt(g))throw new Error(dt);const u=await s.load(g);return await va(t,u,o,i),u}catch(g){if(!Ia(g))throw g;return Oa(t,o)}})();return ga(t,d),d},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:$n(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=nn(a),d=en(a),g=Br(a);c&&ae(s,c),d&&De(s,d);const u=t?Number(t):0,f={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:ma(r??"score_desc",s.storage.customSortMap),selectedFacets:a?.flatMap(Qe)??[],sponsoredCount:o??void 0};if(g){const l=(await s.clients.commerce.catalog.products.crossselling({type:Wn[g.key],productId:g.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(d=>B(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(a+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>B(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],d=(h,I)=>{c.push({id:h.id,name:h.name,fatherCategoryId:I,linkId:he(h.name),title:h.Title,description:null,metaTagDescription:h.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(h.url).pathname.slice(1).toLowerCase()});for(const l of h.children)d(l,h.id)};for(const h of s)d(h,null);const f=[...o.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:he(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!jn.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,I)=>({node:h,cursor:(a+I).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:n,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(Qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:g}=c;return{id:d,sellers:g}},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 k("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=Hn(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!a,ruleForAuthorization:a,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let a={};try{const s=JSON.parse(i);a=s.error||s}catch{a={message:i}}const o=a?.message||i;throw x(r)?new L(`No order found for id ${n}. ${o}.`):Nn(r)?new Z(`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=Y($(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:ya}).catch(()=>null);return typeof c=="boolean"?c:!0},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const g=[d.firstName,d.lastName].filter(Boolean).join(" ");g&&o.set(c,g)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?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=Y($(i?.cookie??"",r))?.userId??"",[c,d,g]=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)]),u=d?.[0],f=c?.namespaces.authentication??null,h=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:u?.phone??"",role:g?.Roles?.map(I=>I.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=Y($(i?.cookie??"",r));if(!o?.userId)return null;if(Me(null,o.unitId)){const c=await a.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null,g=c.namespaces.shopper??null,u=c.namespaces.authentication??null,f=$e(g?.activeContractId?.value,u?.customerId?.value,o.customerId);if(f){let h=null;try{h=await a.masterData.getContractById({contractId:f})}catch(p){console.error(`Error while getting contract data for contract ID (${f}).`,p)}const I=`${(g?.firstName?.value??"").trim()} ${(g?.lastName?.value??"").trim()}`.trim();return{name:st(h,d)||I||"",email:d?.email?.value||u?.storeUserEmail?.value||"",id:d?.id?.value||f}}}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 k("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:a}}=t,o=await a.session("").catch(()=>null),s=$(i?.cookie??"",r);let c=null;try{c=s?Y(s):null}catch{c=null}const d=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new Z("You are not allowed to list contracts for this organization unit");const g=_i(o?.namespaces.shopper),u=Ri(o)||c?.customerId?.trim()||"",f=await a.storeFront.attachedContracts(n).catch(I=>(console.warn("availableContracts: default contract lookup failed",I),null)),h=Ni(f?.contracts);return Fi(g,u,h)},pickupPoints:async(e,{geoCoordinates:n,postalCode:t,country:r,channel:i},a)=>{const{clients:{search:o}}=a;i&&ae(a,i);const s=n?.longitude!=null&&n?.latitude!=null?`${n.longitude},${n.latitude}`:void 0;return{pickupPointDistances:(await o.pickupPointAvailability({postalCode:t??void 0,country:r??void 0,coordinates:s}))?.pickupPointDistances??[],pickupPointsHash:null}},orderEntryOperation:ha,orderFormItems:fa,recommendations:la},ba={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},wa=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Aa={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(u=>({value:u.term,count:u.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(g=>{const u=Se(g.items);return u&&B(u,g)}).filter(g=>!!g),{searches:d}=o;return{terms:d.map(g=>({value:g.term,count:g.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=Se(r.items);return i&&B(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!wa(d,o,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},Pa={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Da=["bd","d","h","m"],Ea=e=>Da.includes(e),ka={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"}},pt=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Ea(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return ka[t][a].replace("#",n)??""},Ta={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?pt(e.shippingEstimate):""},fn="skuvariation";function Sn(e,n){const t=`${fn}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===fn);return i||e[0]}function _a(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function yn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Ua(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Ra(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Na(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>Ra(i.value,a.value));return n}function Fa(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=Sn(a.images,n),g={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(g):r[o.name]=[g];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const g=Sn(a.images,c.name),u={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),Na(r)}const La={activeVariations:e=>yn(e.variations),allVariantsByName:e=>Ua(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>_a(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=yn(e.variations)[t];return Fa(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>B(n,e.isVariantOf))},Ba={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},$a={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((d,g)=>{const u=g?.selectedSla||"",f=g?.selectedDeliveryChannel||g?.deliveryChannel||"",h=g?.deliveryCompany||"",I=g?.deliveryWindow,l=g?.pickupStoreInfo,p=g?.shippingEstimate||"",m=g?.shippingEstimate?pt(g?.shippingEstimate):"",S=g?.shippingEstimateDate||"",v=g?.addressId||"",O=g?.itemIndex??0,C=t?.[O],_=C?.seller||"",w=`${u}|${f}|${h}|${_}|${p}|${S}|${v}|${I?.startDateUtc}|${I?.endDateUtc}`,b=i?.find(U=>U?.addressId===v),A=`${Ba[f]||""} ${m} ${b?.neighborhood?`to ${b?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:T}=Ma(C?.priceTags??[]),D=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(E??0);return d[w]||(d[w]={selectedSla:u,deliveryChannel:f,deliveryCompany:h,deliveryWindow:I,shippingEstimate:p,shippingEstimateDate:S,seller:_,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:b,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[w]&&(d[w].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:T??[],taxPriceTagsTotal:E??0,tax:C?.tax||0,total:D}),d[w].quantityOfDifferentItems=(d[w].quantityOfDifferentItems??0)+1,d[w].total=(d[w].total??0)+D),d},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function Ma(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 za={StoreCollection:jn,StoreAggregateOffer:_r,StoreProduct:ia,StoreSeo:Pa,StoreFacet:zr,StoreFacetBoolean:Vr,StoreFacetRange:qr,StoreFacetValueBoolean:xr,StoreOffer:Qi,StoreAggregateRating:Ur,StoreReview:ba,StoreProductGroup:oa,StoreSearchResult:Aa,StorePropertyValue:sa,SkuVariants:La,ShippingSLA:Ta,UserOrderResult:$a,ObjectOrString:Ji,Query:Ca,Mutation:Xi},Va=()=>za,qa=`"""
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
- `,Fa=`"""
54
+ `,xa=`"""
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
- `,La=`"""
79
+ `,ja=`"""
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
- `,Ba=`"""
108
+ `,Wa=`"""
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
- `,$a=`"""
121
+ `,Ha=`"""
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
- `,Ma=`"""
130
+ `,Ga=`"""
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
- `,za=`"""
139
+ `,Xa=`"""
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
- `,Va=`"""
170
+ `,Ya=`"""
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
- `,qa=`"""
207
+ `,Ka=`"""
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
- `,xa=`"""
333
+ `,Ja=`"""
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
- `,ja=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
342
+ `,Qa=`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
- `,Wa=`"""
419
+ `,Za=`"""
420
420
  Image.
421
421
  """
422
422
  type StoreImage {
@@ -443,7 +443,7 @@ input IStoreImage {
443
443
  """
444
444
  alternateName: String!
445
445
  }
446
- `,Ha=`type Mutation {
446
+ `,eo=`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
- `,Ga=`"""
488
+ `,no=`"""
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
- `,Xa=`scalar ObjectOrString
512
- `,Ya=`"""
511
+ `,to=`scalar ObjectOrString
512
+ `,ro=`"""
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
- `,Ka=`"""
605
+ `,io=`"""
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
- `,Ja=`"""
646
+ `,ao=`"""
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
- `,Qa=`"""
1045
+ `,oo=`"""
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
- `,Za=`"""
1106
+ `,so=`"""
1107
1107
  Organization.
1108
1108
  """
1109
1109
  type StoreOrganization {
@@ -1144,7 +1144,7 @@ type StoreContract {
1144
1144
  """
1145
1145
  isDefault: Boolean!
1146
1146
  }
1147
- `,eo=`"""
1147
+ `,co=`"""
1148
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.
1149
1149
  """
1150
1150
  type StorePageInfo {
@@ -1169,7 +1169,7 @@ type StorePageInfo {
1169
1169
  """
1170
1170
  totalCount: Int!
1171
1171
  }
1172
- `,no=`"""
1172
+ `,lo=`"""
1173
1173
  Input type for setting a new password.
1174
1174
  """
1175
1175
  input ISetPassword {
@@ -1212,7 +1212,7 @@ type SetPasswordResponse {
1212
1212
  """
1213
1213
  message: String
1214
1214
  }
1215
- `,to=`"""
1215
+ `,uo=`"""
1216
1216
  Client profile data.
1217
1217
  """
1218
1218
  type StorePerson {
@@ -1255,7 +1255,7 @@ input IStorePerson {
1255
1255
  """
1256
1256
  familyName: String!
1257
1257
  }
1258
- `,ro=`type PickupPointAddress {
1258
+ `,po=`type PickupPointAddress {
1259
1259
  """
1260
1260
  Address city.
1261
1261
  """
@@ -1337,7 +1337,7 @@ type PickupPoints {
1337
1337
  reason: "Not returned by Intelligent Search pickup-point-availability. Always null."
1338
1338
  )
1339
1339
  }
1340
- `,io=`"""
1340
+ `,go=`"""
1341
1341
  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.
1342
1342
  """
1343
1343
  type StoreProduct {
@@ -1513,7 +1513,7 @@ input IStoreProduct {
1513
1513
  """
1514
1514
  additionalProperty: [IStorePropertyValue!]
1515
1515
  }
1516
- `,ao=`"""
1516
+ `,mo=`"""
1517
1517
  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.
1518
1518
  """
1519
1519
  type StoreProductGroup {
@@ -1558,7 +1558,7 @@ type StoreProductCluster {
1558
1558
  """
1559
1559
  name: String!
1560
1560
  }
1561
- `,oo=`type Profile {
1561
+ `,ho=`type Profile {
1562
1562
  """
1563
1563
  Collection of user's address
1564
1564
  """
@@ -1619,7 +1619,7 @@ type ProfileAddress {
1619
1619
  """
1620
1620
  geoCoordinate: [Float]
1621
1621
  }
1622
- `,so=`"""
1622
+ `,fo=`"""
1623
1623
  Properties that can be associated with products and products groups.
1624
1624
  """
1625
1625
  type StorePropertyValue {
@@ -1659,7 +1659,7 @@ input IStorePropertyValue {
1659
1659
  """
1660
1660
  valueReference: ObjectOrString!
1661
1661
  }
1662
- `,co=`"""
1662
+ `,So=`"""
1663
1663
  Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
1664
1664
  """
1665
1665
  type StoreProductEdge {
@@ -2320,7 +2320,7 @@ type StoreAccountProfile {
2320
2320
  email: String
2321
2321
  id: String
2322
2322
  }
2323
- `,lo=`"""
2323
+ `,yo=`"""
2324
2324
  Summary of a quote returned in list results.
2325
2325
  """
2326
2326
  type UserQuoteSummary {
@@ -2385,7 +2385,7 @@ type UserQuoteListPaging {
2385
2385
  """
2386
2386
  perPage: Int!
2387
2387
  }
2388
- `,uo=`type RecommendationResponse {
2388
+ `,Io=`type RecommendationResponse {
2389
2389
  products: [StoreProduct!]!
2390
2390
  correlationId: String!
2391
2391
  campaign: RecommendationCampaign!
@@ -2396,7 +2396,7 @@ type RecommendationCampaign {
2396
2396
  title: String
2397
2397
  type: String!
2398
2398
  }
2399
- `,po=`"""
2399
+ `,vo=`"""
2400
2400
  Information of a given review rating.
2401
2401
  """
2402
2402
  type StoreReviewRating {
@@ -2423,7 +2423,7 @@ type StoreReview {
2423
2423
  """
2424
2424
  author: StoreAuthor!
2425
2425
  }
2426
- `,go=`"""
2426
+ `,Oo=`"""
2427
2427
  Whether a saved card is personally owned by the buyer or shared by their
2428
2428
  Organization/Contract. Resolved server-side by the Saved-cards service from
2429
2429
  the buyer's \`useAdHocCard\` role — never inferred client-side.
@@ -2487,7 +2487,7 @@ type SavedCardListResult {
2487
2487
  """
2488
2488
  list: [SavedCard!]
2489
2489
  }
2490
- `,mo=`"""
2490
+ `,Co=`"""
2491
2491
  Search Engine Optimization (SEO) tags data.
2492
2492
  """
2493
2493
  type StoreSeo {
@@ -2508,7 +2508,7 @@ type StoreSeo {
2508
2508
  """
2509
2509
  canonical: String!
2510
2510
  }
2511
- `,ho=`"""
2511
+ `,bo=`"""
2512
2512
  Currency information.
2513
2513
  """
2514
2514
  type StoreCurrency {
@@ -2701,6 +2701,9 @@ type StoreSession {
2701
2701
  type StoreB2B {
2702
2702
  customerId: String!
2703
2703
  isRepresentative: Boolean
2704
+ @deprecated(
2705
+ reason: "Always true when \`b2b\` is set: a B2B session is identified by \`unitId\` and \`customerId\`. Check that \`b2b\` is not null instead. Scheduled for removal in the next major."
2706
+ )
2704
2707
  unitName: String
2705
2708
  unitId: String
2706
2709
  firstName: String
@@ -2783,7 +2786,7 @@ input IStoreSession {
2783
2786
  """
2784
2787
  refreshAfter: String
2785
2788
  }
2786
- `,fo=`"""
2789
+ `,wo=`"""
2787
2790
  Shipping Simulation item input.
2788
2791
  """
2789
2792
  input IShippingItem {
@@ -3114,7 +3117,7 @@ type MessageFields {
3114
3117
  """
3115
3118
  skuName: String
3116
3119
  }
3117
- `,So=`type SkuVariants {
3120
+ `,Ao=`type SkuVariants {
3118
3121
  """
3119
3122
  SKU property values for the current SKU.
3120
3123
  """
@@ -3209,7 +3212,7 @@ Example:
3209
3212
  \`\`\`
3210
3213
  """
3211
3214
  scalar FormattedVariants
3212
- `,yo=`"""
3215
+ `,Po=`"""
3213
3216
  Status used to indicate a message type. For instance, a shopping cart informative or error message.
3214
3217
  """
3215
3218
  enum StoreStatus {
@@ -3217,7 +3220,7 @@ enum StoreStatus {
3217
3220
  WARNING
3218
3221
  ERROR
3219
3222
  }
3220
- `,Io=`scalar JSONObject
3223
+ `,Do=`scalar JSONObject
3221
3224
 
3222
3225
  type UserOrder {
3223
3226
  orderId: String
@@ -4041,4 +4044,4 @@ type UserOrderBudgetAllocationLinkedEntity {
4041
4044
  type: String
4042
4045
  id: String
4043
4046
  }
4044
- `,vo=Object.assign({"./address.graphql":Na,"./advertisement.graphql":Fa,"./aggregateOffer.graphql":La,"./aggregateRating.graphql":Ba,"./author.graphql":$a,"./brand.graphql":Ma,"./breadcrumb.graphql":za,"./cart.graphql":Va,"./collection.graphql":qa,"./deliveryPromisesBadge.graphql":xa,"./facet.graphql":ja,"./image.graphql":Wa,"./mutation.graphql":Ha,"./newsletter.graphql":Ga,"./objectOrString.graphql":Xa,"./offer.graphql":Ya,"./order.graphql":Ka,"./orderCommercialAuthorizaton.graphql":Ja,"./orderEntry.graphql":Qa,"./organization.graphql":Za,"./pageInfo.graphql":eo,"./password.graphql":no,"./person.graphql":to,"./pickupPoints.graphql":ro,"./product.graphql":io,"./productGroup.graphql":ao,"./profile.graphql":oo,"./propertyValue.graphql":so,"./query.graphql":co,"./quote.graphql":lo,"./recommendation.graphql":uo,"./review.graphql":po,"./savedCard.graphql":go,"./seo.graphql":mo,"./session.graphql":ho,"./shipping.graphql":fo,"./skuVariants.graphql":So,"./status.graphql":yo,"./userOrder.graphql":Io}),Oo=he.print(Object.values(vo).map(e=>he.parse(e)).reduce((e,n)=>Sn.mergeTypeDefs([e,n],{sort:!0}))),ut=Oo,Co=async e=>n=>(n.storage={channel:se.parse(e.channel),flags:e.flags??{},locale:e.locale,customSortMap:e.customSortMap??{},cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=mr(e,n),n.loaders=wr(e,n),n);function bo(){const e=Ra(),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,Ct(a,`${t}(${i})`)]));return n}function wo(e){const t=kn([En,Dn])(bo(),ut);return e&&he.isSchema(e)?yn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=Dn;exports.BadRequestError=k;exports.CacheControlDirective=En;exports.CardOrigin=In;exports.CommercialAuthorizationStatus=vn;exports.FastStoreError=q;exports.ForbiddenError=Q;exports.GraphqlVtexContextFactory=Co;exports.GraphqlVtexSchema=wo;exports.NotFoundError=$;exports.StoreCollectionType=On;exports.StoreFacetType=Cn;exports.StoreSort=bn;exports.StoreStatus=wn;exports.UnauthorizedError=re;exports.UserOrderInvoiceType=An;exports.getAuthCookie=B;exports.isBadRequestError=wt;exports.isFastStoreError=bt;exports.isForbiddenError=Un;exports.isNotFoundError=K;exports.isUnauthorizedError=At;exports.stringifyCacheControl=vt;exports.typeDefs=ut;exports.validateUserAuthentication=Pn;exports.withDirectives=kn;
4047
+ `,Eo=Object.assign({"./address.graphql":qa,"./advertisement.graphql":xa,"./aggregateOffer.graphql":ja,"./aggregateRating.graphql":Wa,"./author.graphql":Ha,"./brand.graphql":Ga,"./breadcrumb.graphql":Xa,"./cart.graphql":Ya,"./collection.graphql":Ka,"./deliveryPromisesBadge.graphql":Ja,"./facet.graphql":Qa,"./image.graphql":Za,"./mutation.graphql":eo,"./newsletter.graphql":no,"./objectOrString.graphql":to,"./offer.graphql":ro,"./order.graphql":io,"./orderCommercialAuthorizaton.graphql":ao,"./orderEntry.graphql":oo,"./organization.graphql":so,"./pageInfo.graphql":co,"./password.graphql":lo,"./person.graphql":uo,"./pickupPoints.graphql":po,"./product.graphql":go,"./productGroup.graphql":mo,"./profile.graphql":ho,"./propertyValue.graphql":fo,"./query.graphql":So,"./quote.graphql":yo,"./recommendation.graphql":Io,"./review.graphql":vo,"./savedCard.graphql":Oo,"./seo.graphql":Co,"./session.graphql":bo,"./shipping.graphql":wo,"./skuVariants.graphql":Ao,"./status.graphql":Po,"./userOrder.graphql":Do}),ko=me.print(Object.values(Eo).map(e=>me.parse(e)).reduce((e,n)=>In.mergeTypeDefs([e,n],{sort:!0}))),gt=ko,To=async e=>n=>(n.storage={channel:ce.parse(e.channel),flags:e.flags??{},locale:e.locale,customSortMap:e.customSortMap??{},cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=Sr(e,n),n.loaders=Dr(e,n),n);function _o(){const e=Va(),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 Uo(e){const t=_n([Tn,kn])(_o(),gt);return e&&me.isSchema(e)?vn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=kn;exports.BadRequestError=k;exports.CacheControlDirective=Tn;exports.CardOrigin=On;exports.CommercialAuthorizationStatus=Cn;exports.FastStoreError=j;exports.ForbiddenError=Z;exports.GraphqlVtexContextFactory=To;exports.GraphqlVtexSchema=Uo;exports.NotFoundError=L;exports.StoreCollectionType=bn;exports.StoreFacetType=wn;exports.StoreSort=An;exports.StoreStatus=Pn;exports.UnauthorizedError=ie;exports.UserOrderInvoiceType=Dn;exports.getAuthCookie=$;exports.isBadRequestError=Dt;exports.isFastStoreError=Pt;exports.isForbiddenError=Nn;exports.isNotFoundError=x;exports.isUnauthorizedError=Et;exports.stringifyCacheControl=bt;exports.typeDefs=gt;exports.validateUserAuthentication=En;exports.withDirectives=_n;