@faststore/api 4.5.0-dev.3 → 4.5.0-dev.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +95 -44
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/index.mjs +1088 -837
- package/dist/es/index.mjs.map +1 -1
- package/dist/src/__generated__/schema.d.ts +44 -3
- package/dist/src/__generated__/schema.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/catalog/index.d.ts +34 -0
- package/dist/src/platforms/vtex/clients/catalog/index.d.ts.map +1 -0
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts +6 -0
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/commerce/types/ByLinkId.d.ts +45 -0
- package/dist/src/platforms/vtex/clients/commerce/types/ByLinkId.d.ts.map +1 -0
- package/dist/src/platforms/vtex/clients/index.d.ts +8 -0
- package/dist/src/platforms/vtex/clients/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/search/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/index.d.ts +12 -13
- package/dist/src/platforms/vtex/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/loaders/collection.d.ts +32 -3
- package/dist/src/platforms/vtex/loaders/collection.d.ts.map +1 -1
- package/dist/src/platforms/vtex/loaders/index.d.ts +2 -2
- package/dist/src/platforms/vtex/loaders/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/collection.d.ts +20 -2
- package/dist/src/platforms/vtex/resolvers/collection.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/getOrderEntryOperation.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/index.d.ts +3 -13
- package/dist/src/platforms/vtex/resolvers/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/product.d.ts +13 -1
- package/dist/src/platforms/vtex/resolvers/product.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/query.d.ts +8 -17
- package/dist/src/platforms/vtex/resolvers/query.d.ts.map +1 -1
- package/dist/src/platforms/vtex/utils/localization.d.ts +28 -0
- package/dist/src/platforms/vtex/utils/localization.d.ts.map +1 -0
- package/package.json +3 -3
- package/src/__generated__/schema.ts +46 -3
- package/src/platforms/vtex/clients/catalog/index.ts +52 -0
- package/src/platforms/vtex/clients/commerce/index.ts +71 -0
- package/src/platforms/vtex/clients/commerce/types/ByLinkId.ts +46 -0
- package/src/platforms/vtex/clients/index.ts +3 -0
- package/src/platforms/vtex/clients/search/index.ts +16 -4
- package/src/platforms/vtex/index.ts +17 -2
- package/src/platforms/vtex/loaders/collection.ts +99 -25
- package/src/platforms/vtex/loaders/index.ts +2 -1
- package/src/platforms/vtex/resolvers/collection.ts +173 -66
- package/src/platforms/vtex/resolvers/product.ts +160 -11
- package/src/platforms/vtex/resolvers/query.ts +148 -56
- package/src/platforms/vtex/typeDefs/collection.graphql +33 -1
- package/src/platforms/vtex/typeDefs/product.graphql +19 -0
- package/src/platforms/vtex/utils/localization.ts +45 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const He=require("@graphql-tools/merge"),Xe=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),te=require("graphql"),Z=require("cookie"),Rn=require("isomorphic-unfetch"),Oe=require("p-limit"),oe=require("dataloader"),kn=require("sanitize-html"),Ce=require("fast-deep-equal"),Fn=require("node:crypto");var Ye=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(Ye||{}),Je=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(Je||{}),Ke=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(Ke||{}),Qe=(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))(Qe||{}),Ze=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(Ze||{}),en=(e=>(e.Input="Input",e.Output="Output",e))(en||{});const Nn=()=>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}},Ln=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new K("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new K("Authentication required"):r===403?new q("You are not allowed to access this resource"):new K("Authentication required")}},Bn="auth",nn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Bn)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Ln(o),r?.(i,a,o,s))}return n}})},Mn="cacheControl",$n=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},De=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,zn=(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=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Mn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,l,p)=>(l.cacheControl={sMaxAge:De(l.cacheControl?.sMaxAge,r),staleWhileRevalidate:De(l.cacheControl?.staleWhileRevalidate,i),scope:zn(l.cacheControl?.scope,a)},o?.(s,c,l,p))}return n}})},rn=e=>(n,t)=>{const r=He.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,Xe.makeExecutableSchema({typeDefs:r,resolvers:n}))},le="@faststore/api",de="4.5.0-dev.2",Ae={name:le,version:de},xn=(e,n)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,a);const o=L.OTELAPI.trace.getTracer(le,de),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=o.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":de,"@faststore_package_name":le,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return e(t,r,i,a);try{const l=e(t,r,i,a);return l instanceof Promise?l.then(p=>(c.end(),p)):(c.end(),l)}catch(l){throw c.end(),console.error(`Error when executing resolver: ${n}`,l),l}})};class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class E extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class K extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class q extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class B extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const qn=e=>e?.name==="FastStoreError",Vn=e=>e?.extensions?.type==="BadRequestError",jn=e=>e?.extensions?.type==="UnauthorizedError",an=e=>e?.extensions?.type==="ForbiddenError",be=e=>e?.extensions?.type==="NotFoundError",Wn=`${Ae.name}@${Ae.version}`,I=async(e,n,t)=>{const r=await Rn(e,{...n,headers:{...n?.headers??{},"User-Agent":Wn}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new E(i);case 401:throw new K(i);case 403:throw new q(i);case 404:throw new B(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},on=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),c=a.substring(o+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},Gn=/^([^=]+)=([^;]*)/,Hn=(e,n)=>{const t=n.match(Gn);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},Xn=(e,n)=>{n.getSetCookie().forEach(t=>Hn(e,t))},Yn=e=>n=>Xn(e,n),ue=e=>{if(!e.headers?.cookie)return null;const n=on(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Jn(r,i,a),n)},sn=e=>function(t){const r=ue(e);return r?{...t,cookie:r}:t},x=(e,n)=>{const t=on(e);return Z.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Jn=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Q(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const Kn="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},Qn=/^\d{4}-\d{2}-\d{2}$/,Zn=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function et({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&&!Qn.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!Zn.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function nt({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(l=>c.append("status",l)),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 tt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=Yn(i),s=sn(i),c=Nn(),l=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",p=r&&r.map(d=>d+".").find(d=>l.includes(d))||"",u=l.replace(p,""),h=`${a}/api/recommend-bff/v2`,S=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${Kn}`}),b=(d={})=>{const g=x(ue(i)??"",e);return s({...d,"X-FORWARDED-HOST":u,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:d=>I(`${a}/api/catalog_system/pub/saleschannel/${d}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(d=3)=>I(`${a}/api/catalog_system/pub/category/tree/${d}`,void 0,{storeCookies:o})},portal:{pagetype:d=>I(`${a}/api/catalog_system/pub/portal/pagetype/${d}`,void 0,{storeCookies:o})},products:{crossselling:({type:d,productId:g,groupByProduct:m=!0})=>{const y=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${d}/${g}?${y}`,void 0,{storeCookies:o})}}},checkout:{simulation:(d,{salesChannel:g}=i.storage.channel)=>{const m=new URLSearchParams({sc:g}),y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:y,body:JSON.stringify(d)},{storeCookies:o})},shippingData:({id:d,index:g,deliveryMode:m,selectedAddresses:y},C)=>{const w=C?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,v={logisticsInfo:Array.from({length:g},(f,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:y,clearAddressIfPostalCodeNotFound:t},P=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/shippingData`,{...X,headers:P,body:JSON.stringify(v)},{storeCookies:o})},marketingData:({id:d,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:d,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},orderForm:({id:d,refreshOutdatedData:g=!0,channel:m=i.storage.channel})=>{const{salesChannel:y}=m,C=s({"content-type":"application/json","X-FORWARDED-HOST":u}),w=new URLSearchParams({sc:y});d&&w.set("refreshOutdatedData",g.toString());const v=`${a}/api/checkout/pub/orderForm${d?`/${d}`:""}?${w.toString()}`;return I(v,{...X,headers:C,...d?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/messages/clear`,{...X,headers:g,body:"{}"})},updateOrderFormItems:({id:d,orderItems:g,allowOutdatedData:m="paymentData",salesChannel:y=i.storage.channel.salesChannel,shouldSplitItem:C=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:y}),v=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/items?${w}`,{headers:v,body:JSON.stringify({orderItems:g,noSplitItem:!C}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:d,appId:g,key:m,value:y})=>{const C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/customData/${g}/${m}`,{headers:C,body:JSON.stringify({value:y}),method:"PUT"})},region:async({postalCode:d,geoCoordinates:g,country:m,salesChannel:y})=>{const C=new URLSearchParams({country:m,sc:y??""});d?C.append("postalCode",d):C.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${C.toString()}`,v=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(w,{headers:v},{storeCookies:o})},address:async({postalCode:d,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/postal-code/${g}/${d}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:d,customerEmail:g,reason:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orders/${d}/user-cancel-request`,{method:"POST",headers:y,body:JSON.stringify({customerEmail:g,reason:m})},{})},pickupPoints:({geoCoordinates:d})=>{if(!d)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:d})},{storeCookies:o})}},session:d=>{const g=new URLSearchParams(d);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),y=Z.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${g.toString()}`,{method:y?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:d=>I(`${a}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...d,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async d=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/profile-system/pvt/profiles/${d}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders/${d}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:d,status:g,dateInitial:m,dateFinal:y,text:C,clientEmail:w,perPage:v,pendingMyApproval:P})=>{const f=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(y){const A=new Date(y).setHours(23,59,59,999);y=new Date(A).toISOString()}C&&f.append("text",C),g&&g.length>0&&f.append("status",g.filter(Boolean).join(",")),m&&y?f.append("creation_date",`creationDate:[${m} TO ${y}]`):m?f.append("creation_date",`creationDate:[${m} TO *]`):y&&f.append("creation_date",`creationDate:[* TO ${y}]`),w&&f.append("clientEmail",w),d&&f.append("page",d.toString()),v&&f.append("per_page",v.toString()),P&&f.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders?${f.toString()}`,{method:"GET",headers:D},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/${e}/commercial-authorizations/order/${d}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:d,dimensionId:g,ruleId:m,approved:y})=>{const C=s({"content-type":"application/json","X-FORWARDED-HOST":u}),P={params:{ruleId:m,dimensionId:g,score:y?100:0}};return I(`${a}/${e}/commercial-authorizations/${d}/callback`,{method:"POST",headers:C,body:JSON.stringify(P)},{storeCookies:o})}},units:{getUnitByUserId:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/users/${d}`,{method:"GET",headers:g},{})},getUserByEmail:({email:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/pvt/users/${d}`,{method:"GET",headers:g},{})},getUserRoles:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/storefront/users/${d}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:d})=>{if(!d)throw new E("Missing contractId to fetch CL fields.");const g=b({Accept:"application/json","content-type":"application/json"});return I(`${a}/api/dataentities/CL/documents/${d}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:d})=>{if(!d)throw new E("Missing userId to fetch shopper name.");const g=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),m=d.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${d})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:d=>{et(d);const g=nt(d),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u}),g=x(ue(i)??"",e);return I(`${a}/api/vtexid/credential/validate`,{headers:d,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:d,fileName:g,mimeType:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),C=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
2
|
-
`,P=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",f=g.replaceAll(/[\r\n"]/g,"_"),D=[`--${C}`,`Content-Disposition: form-data; name="file"; filename="${f}"`,`Content-Type: ${P}`,"",""].join(w),A=`${w}--${C}--${w}`,U=Buffer.from(D),O=Buffer.from(A),T=new Uint8Array(U.byteLength+d.byteLength+O.byteLength);let _=0;return T.set(U,_),_+=U.byteLength,T.set(d,_),_+=d.byteLength,T.set(O,_),I(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...y,"content-type":`multipart/form-data; boundary=${C}`},body:T.buffer},{})},startOperation:({objectKey:d,orderFormId:g,sessionToken:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),C=JSON.stringify({objectKey:d,orderFormId:g,operation:"CreateCart",...m?{sessionToken:m}:{}});return I(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:y,body:C},{})},getOperation:({operationId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/order-entry/operation/${d}?an=${e}`,{method:"GET",headers:g},{})},createOrderForm:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:d,body:"{}"},{})},getOrderFormItems:({orderFormId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}`,{method:"GET",headers:g},{})}},recommendation:{recommendations:({campaignVrn:d,userId:g,products:m=[],salesChannel:y,locale:C})=>{const w=new URLSearchParams({an:e,campaignVrn:d});return g&&w.append("userId",g),m.length>0&&w.append("products",m.join(",")),y&&w.append("salesChannel",y),C&&w.append("locale",C),I(`${h}/recommendations?${w.toString()}`,{headers:S},{storeCookies:o})},startRecommendationSession:()=>{const d=new URLSearchParams({an:e});return I(`${h}/users/start-session?${d.toString()}`,{method:"POST",headers:S},{storeCookies:o})}}}},pe="fuzzy",ge="operator",me="pickupPoint",Pe="shipping",Ee="delivery-options",rt="in-stock",it="trade-policy",at="region-id",ot=new Set([it,at,pe,ge,me]),st=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),ct=new Set(["productClusterIds"]),Ue=e=>encodeURI(decodeURI(e)),lt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),dt=/^pickup-in-point-(.+)$/;function cn(e){if(!e)return{};try{const t=Z.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function ut(e){const n={},t={},r=[];for(const i of e.split(";")){const a=i.indexOf("=");if(a<0)continue;const o=i.slice(0,a),s=i.slice(a+1);!o||!s||(st.has(o)?n[o]=s:ct.has(o)?t[o]=s:r.push({key:o,value:s}))}return{shipping:n,queryParams:t,extraFacets:r}}function pt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,queryParams:r,extraFacets:i}=ut(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0,productClusterIds:r.productClusterIds},extraFacets:i}}function ln(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],["productClusterId",n.productClusterIds]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function dn(e){return dt.exec(e)?.[1]}function gt(e){const n=e.find(r=>r.key==="shipping"),t=n?dn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function mt(e,n){const t=gt(n);return t===void 0?e:{...e,pickupPoint:t}}function ht(e){return e.map(n=>n.key!=="shipping"||dn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function ft(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),ht(t)}function St(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}${Ue(r)}/${lt(Ue(i)).replaceAll(/ |%20/g,"-")}/`},"")}const yt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),It=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function vt(e,n){const{segmentParams:t,extraFacets:r}=pt(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 Ot(e,n){const t=e.filter(({key:c})=>!ot.has(c)),r=e.find(({key:c,value:l})=>c===Pe&&l!=="all-delivery-methods")??null,i=e.find(({key:c,value:l})=>c===Ee&&l!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===Pe),s=a.some(({key:c})=>c===Ee);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),ft(a,n)}function Ct(e,n){const t=e.find(({key:a})=>a===pe)??null,r=e.find(({key:a})=>a===ge)??null,i=e.find(({key:a})=>a===me)??null;t&&yt(t)&&n.append(pe,t.value),r&&It(r)&&n.append(ge,r.value),i&&n.append(me,i.value)}function Te(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:l,sponsoredCount:p,hideUnavailableItems:u,allowRedirect:h=!1}=e,S=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const g=a*o,m=o===0?g:g+o-1;S.append("from",g.toString()),S.append("to",m.toString())}i&&S.append("query",i),r.includeSort&&s&&S.append("sort",s);const b=mt(t.segmentParams,c);if(ln(S,b??t.segmentParams),Ct(c,S),l&&S.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const g=c.find(({key:y})=>y===rt),m=g?g.value:u?.toString()??n.hideUnavailableItems.toString();S.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&S.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&S.append("showSponsored",n.showSponsored.toString()),p!==void 0&&S.append("sponsoredCount",p.toString()),h!==void 0&&S.append("allowRedirect",h.toString());const d=St(Ot(c,t.extraFacets));return{params:S,path:d}}function bt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return ln(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=vt(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Te(i,r,a,{includePagination:!0,includeSort:!0});return Y(s,o)}case"catalog-count":{const{params:o,path:s}=Te(i,r,a,{includePagination:!1,includeSort:!1});return Y(s,o)}case"products":{const o=bt(i,a.segmentParams);return Y("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const wt=10;function Dt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function At(e){const n=cn(e.headers?.cookie);return e.storage.locale||n.cultureInfo||""}const Pt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=sn(o),l=cn(o.headers?.cookie),p=()=>({salesChannel:o.storage.channel.salesChannel,regionId:Dt(o),locale:At(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",h=a&&a.map(f=>f+".").find(f=>u.includes(f))||"",S=u.replace(h,""),b=c({"content-type":"application/json","X-FORWARDED-HOST":S}),d=({type:f,...D})=>{const A=f==="facets"?"facets":"product-search",U=J({endpoint:A,segment:l,defaults:p(),args:D});return I(`${s}/api/intelligent-search/v1/${A}/${U.path}?${U.params.toString()}`,{headers:b})},g=f=>d({...f,type:"product_search"}),m=({field:f,value:D,hideUnavailableItems:A,showInvisibleItems:U})=>{const O=J({endpoint:"products",segment:l,defaults:p(),args:{field:f,value:D,hideUnavailableItems:A,showInvisibleItems:U}});return I(`${s}/api/intelligent-search/v1/products?${O.params.toString()}`,{headers:b})};return{facets:f=>d({...f,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:f,values:D,showInvisibleItems:A,hideUnavailableItems:U})=>{const O=Oe(wt);return(await Promise.all(D.map(_=>O(async()=>{try{return await m({field:f,value:_,hideUnavailableItems:U,showInvisibleItems:A})}catch{return null}})))).filter(_=>_!==null)},suggestedTerms:f=>{const D=J({endpoint:"search-suggestions",segment:l,defaults:p(),args:{query:f.query}});return I(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:b})},topSearches:()=>{const f=J({endpoint:"top-searches",segment:l,defaults:p()});return I(`${s}/api/intelligent-search/v1/top-searches?${f.params.toString()}`,{headers:b})},productCount:f=>{const D=J({endpoint:"catalog-count",segment:l,defaults:p(),args:f});return I(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:b})}}},Et=(e,n)=>{const t=Pt(e,n),r=tt(e,n);return{search:t,commerce:r}},Ut=20,Tt=new Set(["brand","category","department","subcategory","collection","cluster"]),V=e=>typeof e.pageType=="string"&&Tt.has(e.pageType.toLowerCase()),_t=(e,n)=>{const t=Oe(Ut),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await n.commerce.catalog.portal.pagetype(a);if(V(o))return o;throw new B(`Catalog returned ${o.pageType} for slug: ${a}. This usually happens when there is more than one category with the same name in the same category tree level.`)})));return new oe(r,{batch:!1})},Rt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new oe(t)},kt=1,Ft=(e,n)=>{const t=Oe(kt),r=async a=>{const o=a.reduce((u,{items:h})=>[...u,h],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),l=c.items.reduce((u,h)=>{const S=h.requestIndex;return typeof S=="number"&&S<u.length&&(u[S]=h),u},Array(s.length).fill(null)),p=o.reduce((u,h)=>[...u,h.length+u[u.length-1]],[0]);return o.map((u,h)=>({...c,items:l.slice(p[h],p[h+1]).filter(S=>!!S)}))},i=async a=>t(r,a);return new oe(i,{maxBatchSize:50})},Nt=(e,n)=>kn(e,n);function Lt(e){return{...e,description:e.description?Nt(e.description):e.description}}const N=(e,n)=>({...e,isVariantOf:Lt(n)}),Bt=({flags:e},n)=>{const t=async r=>{const i=r.map(p=>p.split("-")[0]),a=r.some(p=>p.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((p,u)=>{for(const h of u.items)p[h.itemId]=N(h,u);return p},{}),c=i.map(p=>s[p]),l=i.filter(p=>!s[p]);if(l.length>0)throw new B(`Search API did not found the following skus: ${l.join(",")}`);return c};return new oe(t,{maxBatchSize:99})},Mt=(e,{clients:n})=>{const t=Bt(e,n),r=Ft(e,n),i=_t(e,n),a=Rt(e,n);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},M=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,$t=e=>e.Price??0,_e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",un=(e,n)=>M(e)&&!M(n)?-1:!M(e)&&M(n)?1:j(e)-j(n),zt=e=>e==="available",$=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},xt=(e,n={includeTaxes:!1})=>{const t=e.filter(M),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?$(i,r?.Tax,r?.product?.unitMultiplier):i},Re=(e,n={includeTaxes:!1})=>{const[t]=e.filter(M),r=t?j(t):0;return n.includeTaxes?$(r,t?.Tax,t?.product?.unitMultiplier):r},qt={highPrice:e=>xt(e),lowPrice:e=>Re(e),lowPriceWithTaxes:e=>Re(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},Vt={ratingValue:()=>5,reviewCount:()=>0},ke="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",jt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",Wt=e=>{let n=e.slice(0);for(let t=0;t<ke.length;t++)n=n.replace(new RegExp(ke.charAt(t),"g"),jt.charAt(t));return n},Gt=e=>e.replace(/[·/_,:]/,"-");function pn(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return Gt(Wt(t)).toLowerCase()}const ne=e=>e.type==="brand"||V(e)&&e.pageType.toLowerCase()==="brand",he=e=>V(e)&&e.pageType.toLowerCase()==="collection",ce=e=>ne(e)||he(e)?pn(e.name):V(e)?new URL(`https://${e.url}`).pathname.slice(1).toLowerCase():new URL(e.url).pathname.slice(1).toLowerCase(),gn={id:({id:e})=>e.toString(),slug:e=>ce(e),seo:e=>ne(e)||V(e)?{title:e.title??e.name,description:e.metaTagDescription}:{title:e.Title,description:e.MetaTagDescription},type:e=>ne(e)?"Brand":V(e)?e.pageType:e.level===0?"Department":"Category",meta:e=>{const n=ce(e);return ne(e)?{selectedFacets:[{key:"brand",value:n}]}:he(e)?{selectedFacets:[{key:"productclusterids",value:e.id}]}:{selectedFacets:n.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,a=ce(e).split("/").filter(c=>!!c),o=a.map((c,l)=>a.slice(0,l+1).join("/")),s=await Promise.all(o.map(async c=>{const l=await r.load(c);return{slug:c,...l}}));return{itemListElement:s.map((c,l)=>({item:he(c)?`/${c.slug}`:new URL(`https://${c.url}`).pathname.toLowerCase(),name:c.name,position:l+1})),numberOfItems:s.length}}},mn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Fe=({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}}},Ne=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},Ht=e=>typeof mn[e]=="string",Xt=e=>{const n=e?.filter(t=>Ht(t.key));if(Array.isArray(n)&&n.length>1)throw new E(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},Yt=e=>e?.find(n=>n.key==="slug")?.value??null,Jt=e=>e?.find(n=>n.key==="id")?.value??null,Le=e=>e?.find(n=>n.key==="locale")?.value??null,Be=e=>e?.find(n=>n.key==="channel")?.value??null,fe=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},Kt={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Qt={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},Zt={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ne(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=fe(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=Ne(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=fe(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},er={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},nr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new E("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 tr(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 rr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=hn(r);return{isPendingForOtherAuthorizer:!i&&tr(r),ruleForAuthorization:i}},ir=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new E("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},ar=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},or=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),sr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new E("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 E("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new E("Invalid Base64 fileContent");const p=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:p,fileName:i,mimeType:a})};class re{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const Se=(e,n)=>{e.storage.channel=re.parse(n)},ye=(e,n)=>{e.storage.locale=n},fn=e=>Fn.createHash("md5").update(e).digest("hex"),ee={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Sn(e){return{name:e.name,value:e.content,valueReference:ee.attachment}}function cr(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:ee.attribute,visible:e.visible}}}function yn(e){return fn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const lr=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]},dr=(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},In=(e,n)=>{if(!ur(n))return{updateShipping:!1,addressChanged:!1};if(!hr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(pr(t,n.postalCode)||gr(t,n.geoCoordinates)||mr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return fr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},ur=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,pr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,gr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),mr=(e,n)=>typeof n=="string"&&e?.addressType!==n,hr=e=>e.items.length!==0,fr=(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 l=t&&o!==t,p=r&&s!==r;return c?.some(u=>l&&u.deliveryChannel===t||p&&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(h=>h?.startDateUtc===i&&h?.endDateUtc===a))})},vn=e=>e.valueReference===ee.attachment,Ie=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(vn).map(yn).join("-")].filter(Boolean).join("::"),ie=(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(Sn)},index:n}),Sr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(vn)??[]).map(n=>({name:n.name,content:n.value}))}),Me=e=>e.reduce((n,t)=>{const r=Ie(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),yr=(e,n)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=n.items.map(ie).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Ce(r,i);return a&&o};function On(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Cn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const $e=e=>{const n=e.items.reduce((t,r,i)=>{const a=Cn(e.items,r.id)||On(e.items,r.id)?`${Ie(ie(r))}::${i}`:Ie(ie(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}})}},ze=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),bn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return fn(JSON.stringify({sessionId:n?.id??"",items:t}))},xe=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:bn(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 nn=require("@graphql-tools/merge"),tn=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),ae=require("graphql"),Mn=require("isomorphic-unfetch"),te=require("cookie"),Ee=require("p-limit"),ue=require("dataloader"),zn=require("sanitize-html"),Ue=require("fast-deep-equal"),qn=require("node:crypto");var rn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(rn||{}),on=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(on||{}),an=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(an||{}),sn=(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))(sn||{}),cn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(cn||{}),ln=(e=>(e.Input="Input",e.Output="Output",e))(ln||{});const Vn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new x("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},xn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Q("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Q("Authentication required"):r===403?new x("You are not allowed to access this resource"):new Q("Authentication required")}},jn="auth",dn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,jn)?.[0]){const r=n.resolve;n.resolve=async(i,o,a,s)=>(await xn(a),r?.(i,o,a,s))}return n}})},Wn="cacheControl",Gn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},ke=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,Hn=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,un={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Wn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:o}=t,a=n.resolve;n.resolve=(s,c,l,p)=>(l.cacheControl={sMaxAge:ke(l.cacheControl?.sMaxAge,r),staleWhileRevalidate:ke(l.cacheControl?.staleWhileRevalidate,i),scope:Hn(l.cacheControl?.scope,o)},a?.(s,c,l,p))}return n}})},pn=e=>(n,t)=>{const r=nn.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:o})=>o?.(i)??i,tn.makeExecutableSchema({typeDefs:r,resolvers:n}))},me="@faststore/api",he="4.5.0-dev.3",_e={name:me,version:he},Xn=(e,n)=>(t,r,i,o)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,o);const a=L.OTELAPI.trace.getTracer(me,he),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=a.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":he,"@faststore_package_name":me,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return e(t,r,i,o);try{const l=e(t,r,i,o);return l instanceof Promise?l.then(p=>(c.end(),p)):(c.end(),l)}catch(l){throw c.end(),console.error(`Error when executing resolver: ${n}`,l),l}})};class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class E extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Q extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class B extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Yn=e=>e?.name==="FastStoreError",Jn=e=>e?.extensions?.type==="BadRequestError",Kn=e=>e?.extensions?.type==="UnauthorizedError",gn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",Qn=`${_e.name}@${_e.version}`,I=async(e,n,t)=>{const r=await Mn(e,{...n,headers:{...n?.headers??{},"User-Agent":Qn}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new E(i);case 401:throw new Q(i);case 403:throw new x(i);case 404:throw new B(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},Zn=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>I(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},mn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const o=i.trim();if(o){const a=o.indexOf("=");if(a>0){const s=o.substring(0,a),c=o.substring(a+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},et=/^([^=]+)=([^;]*)/,nt=(e,n)=>{const t=n.match(et);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},tt=(e,n)=>{n.getSetCookie().forEach(t=>nt(e,t))},rt=e=>n=>tt(e,n),fe=e=>{if(!e.headers?.cookie)return null;const n=mn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:o}])=>it(r,i,o),n)},hn=e=>function(t){const r=fe(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=mn(e);return te.parse(t)[`VtexIdclientAutCookie_${n}`]||""},it=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Z(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const ot="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},at=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,st=/^\d{4}-\d{2}-\d{2}$/,ct=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function lt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",o],["expiresAtTo",a]])if(c&&!st.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!ct.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function dt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(l=>c.append("status",l)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),o&&c.append("expiresAtFrom",o),a&&c.append("expiresAtTo",a),s?.trim()&&c.append("label",s.trim()),c}const ut=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const o=`https://${e}.${n}.com.br`,a=rt(i),s=hn(i),c=Vn(),l=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",p=r&&r.map(d=>d+".").find(d=>l.includes(d))||"",u=l.replace(p,""),h=`${o}/api/recommend-bff/v2`,f=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${ot}`}),v=(d={})=>{const g=V(fe(i)??"",e);return s({...d,"X-FORWARDED-HOST":u,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:d=>I(`${o}/api/catalog_system/pub/saleschannel/${d}`,void 0,{storeCookies:a}),brand:{list:()=>I(`${o}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:a})},category:{tree:(d=3)=>I(`${o}/api/catalog_system/pub/category/tree/${d}`,void 0,{storeCookies:a})},portal:{pagetype:d=>I(`${o}/api/catalog_system/pub/portal/pagetype/${d}`,void 0,{storeCookies:a})},byLinkId:{category:async(d,g)=>{try{return await I(`${o}/api/catalog_system/pub/category/by-linkid/${at(d)}`,ge(g))}catch(m){if(q(m))return null;throw m}},brand:async(d,g)=>{try{return await I(`${o}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(d)}`,ge(g))}catch(m){if(q(m))return null;throw m}},collection:async(d,g)=>{try{return await I(`${o}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(d)}`,ge(g))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:d,productId:g,groupByProduct:m=!0})=>{const y=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return I(`${o}/api/catalog_system/pub/products/crossselling/${d}/${g}?${y}`,void 0,{storeCookies:a})}}},checkout:{simulation:(d,{salesChannel:g}=i.storage.channel)=>{const m=new URLSearchParams({sc:g}),y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:y,body:JSON.stringify(d)},{storeCookies:a})},shippingData:({id:d,index:g,deliveryMode:m,selectedAddresses:y},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:g},(S,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:y,clearAddressIfPostalCodeNotFound:t},P=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/shippingData`,{...X,headers:P,body:JSON.stringify(C)},{storeCookies:a})},marketingData:({id:d,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},clientPreferencesData:({id:d,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},orderForm:({id:d,refreshOutdatedData:g=!0,channel:m=i.storage.channel})=>{const{salesChannel:y}=m,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),w=new URLSearchParams({sc:y});d&&w.set("refreshOutdatedData",g.toString());const C=`${o}/api/checkout/pub/orderForm${d?`/${d}`:""}?${w.toString()}`;return I(C,{...X,headers:O,...d?{}:{body:"{}"}},{storeCookies:a})},clearOrderFormMessages:({id:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/messages/clear`,{...X,headers:g,body:"{}"})},updateOrderFormItems:({id:d,orderItems:g,allowOutdatedData:m="paymentData",salesChannel:y=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:y}),C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/items?${w}`,{headers:C,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:a})},setCustomData:({id:d,appId:g,key:m,value:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/customData/${g}/${m}`,{headers:O,body:JSON.stringify({value:y}),method:"PUT"})},region:async({postalCode:d,geoCoordinates:g,country:m,salesChannel:y})=>{const O=new URLSearchParams({country:m,sc:y??""});d?O.append("postalCode",d):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const w=`${o}/api/checkout/pub/regions/?${O.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(w,{headers:C},{storeCookies:a})},address:async({postalCode:d,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/postal-code/${g}/${d}`,{headers:m},{storeCookies:a})},cancelOrder:({orderId:d,customerEmail:g,reason:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orders/${d}/user-cancel-request`,{method:"POST",headers:y,body:JSON.stringify({customerEmail:g,reason:m})},{})},pickupPoints:({geoCoordinates:d})=>{if(!d)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:d})},{storeCookies:a})}},session:d=>{const g=new URLSearchParams(d);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),y=te.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${o}/api/sessions?${g.toString()}`,{method:y?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:a})},subscribeToNewsletter:d=>I(`${o}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...d,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:a}),profile:{addresses:async d=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/profile-system/pvt/profiles/${d}/addresses`,{headers:g},{storeCookies:a})}},oms:{userOrder:({orderId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders/${d}`,{method:"GET",headers:g},{storeCookies:a})},listUserOrders:({page:d,status:g,dateInitial:m,dateFinal:y,text:O,clientEmail:w,perPage:C,pendingMyApproval:P})=>{const S=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(y){const A=new Date(y).setHours(23,59,59,999);y=new Date(A).toISOString()}O&&S.append("text",O),g&&g.length>0&&S.append("status",g.filter(Boolean).join(",")),m&&y?S.append("creation_date",`creationDate:[${m} TO ${y}]`):m?S.append("creation_date",`creationDate:[${m} TO *]`):y&&S.append("creation_date",`creationDate:[* TO ${y}]`),w&&S.append("clientEmail",w),d&&S.append("page",d.toString()),C&&S.append("per_page",C.toString()),P&&S.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders?${S.toString()}`,{method:"GET",headers:D},{storeCookies:a})},getCommercialAuthorizationsByOrderId:({orderId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/${e}/commercial-authorizations/order/${d}`,{method:"GET",headers:g},{storeCookies:a})},processOrderAuthorization:async({orderAuthorizationId:d,dimensionId:g,ruleId:m,approved:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),P={params:{ruleId:m,dimensionId:g,score:y?100:0}};return I(`${o}/${e}/commercial-authorizations/${d}/callback`,{method:"POST",headers:O,body:JSON.stringify(P)},{storeCookies:a})}},units:{getUnitByUserId:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/users/${d}`,{method:"GET",headers:g},{})},getUserByEmail:({email:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/pvt/users/${d}`,{method:"GET",headers:g},{})},getUserRoles:({userId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/storefront/users/${d}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:d})=>{if(!d)throw new E("Missing contractId to fetch CL fields.");const g=v({Accept:"application/json","content-type":"application/json"});return I(`${o}/api/dataentities/CL/documents/${d}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:d})=>{if(!d)throw new E("Missing userId to fetch shopper name.");const g=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),m=d.replace(/-/g,"");return I(`${o}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${d})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:d=>{lt(d);const g=dt(d),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:a})}},vtexid:{validate:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u}),g=V(fe(i)??"",e);return I(`${o}/api/vtexid/credential/validate`,{headers:d,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:a})}},orderEntry:{uploadFile:({fileBuffer:d,fileName:g,mimeType:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
2
|
+
`,P=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",S=g.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${S}"`,`Content-Type: ${P}`,"",""].join(w),A=`${w}--${O}--${w}`,U=Buffer.from(D),b=Buffer.from(A),T=new Uint8Array(U.byteLength+d.byteLength+b.byteLength);let k=0;return T.set(U,k),k+=U.byteLength,T.set(d,k),k+=d.byteLength,T.set(b,k),I(`${o}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...y,"content-type":`multipart/form-data; boundary=${O}`},body:T.buffer},{})},startOperation:({objectKey:d,orderFormId:g,sessionToken:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=JSON.stringify({objectKey:d,orderFormId:g,operation:"CreateCart",...m?{sessionToken:m}:{}});return I(`${o}/api/order-entry/operation?an=${e}`,{method:"POST",headers:y,body:O},{})},getOperation:({operationId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/order-entry/operation/${d}?an=${e}`,{method:"GET",headers:g},{})},createOrderForm:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:d,body:"{}"},{})},getOrderFormItems:({orderFormId:d})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}`,{method:"GET",headers:g},{})}},recommendation:{recommendations:({campaignVrn:d,userId:g,products:m=[],salesChannel:y,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:d});return g&&w.append("userId",g),m.length>0&&w.append("products",m.join(",")),y&&w.append("salesChannel",y),O&&w.append("locale",O),I(`${h}/recommendations?${w.toString()}`,{headers:f},{storeCookies:a})},startRecommendationSession:()=>{const d=new URLSearchParams({an:e});return I(`${h}/users/start-session?${d.toString()}`,{method:"POST",headers:f},{storeCookies:a})}}}},ee=e=>e.discoveryConfig?.localization??{},ne=e=>ee(e).enabled===!0,pt=e=>Object.keys(ee(e).locales??{}),gt=e=>ee(e).defaultLocale,ie=e=>ne(e)&&e.storage.locale||void 0,Se="fuzzy",ye="operator",Ie="pickupPoint",Re="shipping",Fe="delivery-options",mt="in-stock",ht="trade-policy",ft="region-id",St=new Set([ht,ft,Se,ye,Ie]),yt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),It=new Set(["productClusterIds"]),Ne=e=>encodeURI(decodeURI(e)),vt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Ot=/^pickup-in-point-(.+)$/;function fn(e){if(!e)return{};try{const t=te.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function Ct(e){const n={},t={},r=[];for(const i of e.split(";")){const o=i.indexOf("=");if(o<0)continue;const a=i.slice(0,o),s=i.slice(o+1);!a||!s||(yt.has(a)?n[a]=s:It.has(a)?t[a]=s:r.push({key:a,value:s}))}return{shipping:n,queryParams:t,extraFacets:r}}function bt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,queryParams:r,extraFacets:i}=Ct(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,productClusterIds:r.productClusterIds},extraFacets:i}}function Sn(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],["productClusterId",n.productClusterIds]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function yn(e){return Ot.exec(e)?.[1]}function wt(e){const n=e.find(r=>r.key==="shipping"),t=n?yn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Dt(e,n){const t=wt(n);return t===void 0?e:{...e,pickupPoint:t}}function At(e){return e.map(n=>n.key!=="shipping"||yn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Pt(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")),At(t)}function Et(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ne(r)}/${vt(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Ut=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),Tt=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function kt(e,n){const{segmentParams:t,extraFacets:r}=bt(e??{}),i=n?.salesChannel??t.sc,o=n?.regionId??t.regionId,a=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...o?{regionId:o}:{},locale:a},extraFacets:r}}function _t(e,n){const t=e.filter(({key:c})=>!St.has(c)),r=e.find(({key:c,value:l})=>c===Re&&l!=="all-delivery-methods")??null,i=e.find(({key:c,value:l})=>c===Fe&&l!=="all-delivery-options")??null,o=[...t],a=o.some(({key:c})=>c===Re),s=o.some(({key:c})=>c===Fe);return r!==null&&!a&&o.push(r),i!==null&&!s&&o.push(i),Pt(o,n)}function Rt(e,n){const t=e.find(({key:o})=>o===Se)??null,r=e.find(({key:o})=>o===ye)??null,i=e.find(({key:o})=>o===Ie)??null;t&&Ut(t)&&n.append(Se,t.value),r&&Tt(r)&&n.append(ye,r.value),i&&n.append(Ie,i.value)}function Le(e,n,t,r){const{query:i="",page:o,count:a,sort:s,selectedFacets:c=[],showInvisibleItems:l,sponsoredCount:p,hideUnavailableItems:u,allowRedirect:h=!1}=e,f=new URLSearchParams;if(r.includePagination&&o!==void 0&&a!==void 0){const g=o*a,m=a===0?g:g+a-1;f.append("from",g.toString()),f.append("to",m.toString())}i&&f.append("query",i),r.includeSort&&s&&f.append("sort",s);const v=Dt(t.segmentParams,c);if(Sn(f,v??t.segmentParams),Rt(c,f),l&&f.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const g=c.find(({key:y})=>y===mt),m=g?g.value:u?.toString()??n.hideUnavailableItems.toString();f.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&f.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&f.append("showSponsored",n.showSponsored.toString()),p!==void 0&&f.append("sponsoredCount",p.toString()),h!==void 0&&f.append("allowRedirect",h.toString());const d=Et(_t(c,t.extraFacets));return{params:f,path:d}}function Ft(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:o}=e,a=new URLSearchParams({field:t??"",value:r??""});return Sn(a,n),i&&a.append("hideUnavailableItems","true"),o&&a.append("show-invisible-items","true"),a}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,o=kt(t,r);switch(n){case"product-search":case"facets":{const{params:a,path:s}=Le(i,r,o,{includePagination:!0,includeSort:!0});return Y(s,a)}case"catalog-count":{const{params:a,path:s}=Le(i,r,o,{includePagination:!1,includeSort:!1});return Y(s,a)}case"products":{const a=Ft(i,o.segmentParams);return Y("",a)}case"search-suggestions":{const a=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}case"top-searches":{const a=new URLSearchParams({locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}default:{const a=n;throw new Error(`Unknown intelligent-search endpoint: ${a}`)}}}const Nt=10;function Lt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Bt(e){const t=fn(e.headers?.cookie).cultureInfo||"";return ne(e)?e.storage.locale||t:t||e.storage.locale||""}const $t=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:o},a)=>{const s=`https://${e}.${n}.com.br`,c=hn(a),l=fn(a.headers?.cookie),p=()=>({salesChannel:a.storage.channel.salesChannel,regionId:Lt(a),locale:Bt(a),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(a.headers).get("x-forwarded-host")??a.headers?.host??"",h=o&&o.map(S=>S+".").find(S=>u.includes(S))||"",f=u.replace(h,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":f}),d=({type:S,...D})=>{const A=S==="facets"?"facets":"product-search",U=J({endpoint:A,segment:l,defaults:p(),args:D});return I(`${s}/api/intelligent-search/v1/${A}/${U.path}?${U.params.toString()}`,{headers:v})},g=S=>d({...S,type:"product_search"}),m=({field:S,value:D,hideUnavailableItems:A,showInvisibleItems:U})=>{const b=J({endpoint:"products",segment:l,defaults:p(),args:{field:S,value:D,hideUnavailableItems:A,showInvisibleItems:U}});return I(`${s}/api/intelligent-search/v1/products?${b.params.toString()}`,{headers:v})};return{facets:S=>d({...S,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:S,values:D,showInvisibleItems:A,hideUnavailableItems:U})=>{const b=Ee(Nt);return(await Promise.all(D.map(k=>b(async()=>{try{return await m({field:S,value:k,hideUnavailableItems:U,showInvisibleItems:A})}catch{return null}})))).filter(k=>k!==null)},suggestedTerms:S=>{const D=J({endpoint:"search-suggestions",segment:l,defaults:p(),args:{query:S.query}});return I(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const S=J({endpoint:"top-searches",segment:l,defaults:p()});return I(`${s}/api/intelligent-search/v1/top-searches?${S.params.toString()}`,{headers:v})},productCount:S=>{const D=J({endpoint:"catalog-count",segment:l,defaults:p(),args:S});return I(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},Mt=(e,n)=>{const t=$t(e,n),r=ut(e,n),i=Zn(e);return{search:t,commerce:r,catalog:i}},zt=20,qt=e=>e.entityType==="category",ve=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Vt=(e,n)=>{const t=Ee(zt),r=async i=>Promise.all(i.map(o=>t(async()=>{const a=o.slug.toLowerCase(),s=o.locale,c=await n.commerce.catalog.byLinkId.category(a,s);if(c)return{...c,entityType:"category",slug:a};const l=await n.commerce.catalog.byLinkId.brand(a,s);if(l)return{...l,entityType:"brand"};const p=await n.commerce.catalog.byLinkId.collection(a,s);if(p)return{...p,entityType:"collection"};throw new B(`No catalog entity found for slug: ${o.slug}. Cascade exhausted (category → brand → collection).`)})));return new ue(r,{batch:!1,cacheKeyFn:({slug:i,locale:o})=>`${i.toLowerCase()}::${o??""}`})},xt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ue(t)},jt=1,Wt=(e,n)=>{const t=Ee(jt),r=async o=>{const a=o.reduce((u,{items:h})=>[...u,h],[]),s=[...a.flat()],c=await n.commerce.checkout.simulation({country:o[0].country,postalCode:o[0].postalCode,items:s}),l=c.items.reduce((u,h)=>{const f=h.requestIndex;return typeof f=="number"&&f<u.length&&(u[f]=h),u},Array(s.length).fill(null)),p=a.reduce((u,h)=>[...u,h.length+u[u.length-1]],[0]);return a.map((u,h)=>({...c,items:l.slice(p[h],p[h+1]).filter(f=>!!f)}))},i=async o=>t(r,o);return new ue(i,{maxBatchSize:50})},Gt=(e,n)=>zn(e,n);function Ht(e){return{...e,description:e.description?Gt(e.description):e.description}}const N=(e,n)=>({...e,isVariantOf:Ht(n)}),Xt=({flags:e},n)=>{const t=async r=>{const i=r.map(p=>p.split("-")[0]),o=r.some(p=>p.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:o,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((p,u)=>{for(const h of u.items)p[h.itemId]=N(h,u);return p},{}),c=i.map(p=>s[p]),l=i.filter(p=>!s[p]);if(l.length>0)throw new B(`Search API did not found the following skus: ${l.join(",")}`);return c};return new ue(t,{maxBatchSize:99})},Yt=(e,n)=>{const{clients:t}=n,r=Xt(e,t),i=Wt(e,t),o=Vt(e,t),a=xt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:o,salesChannelLoader:a}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,Jt=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",In=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),Kt=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},Qt=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},Zt={highPrice:e=>Qt(e),lowPrice:e=>Me(e),lowPriceWithTaxes:e=>Me(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},er={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",nr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",tr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),nr.charAt(t));return n},rr=e=>e.replace(/[·/_,:]/,"-");function se(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return rr(tr(t)).toLowerCase()}const K=e=>qt(e)?e.slug:ve(e)?e.linkId:e.linkId??se(e.name),vn={id:({id:e})=>e.toString(),slug:e=>K(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ve(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=K(e);if(ve(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t),o=r.split("/").filter(Boolean),a=o.map((l,p)=>o.slice(0,p+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(a.map(l=>s.load({slug:l,locale:ie(t)})))).map((l,p)=>({key:`category-${p+1}`,value:i&&l.availableLinkIds?.[i]||l.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,o=K(e).split("/").filter(Boolean),a=o.map((c,l)=>o.slice(0,l+1).join("/")),s=await Promise.all(a.map(c=>r.load({slug:c,locale:ie(t)})));return{itemListElement:s.map((c,l)=>({item:`/${K(c)}`,name:c.name,position:l+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=ee(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const o=t.storage.locale,a=K(e),s=a.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,l=s.map((u,h)=>s.slice(0,h+1).join("/"));let p;try{p=await Promise.all(l.map(u=>c.load({slug:u,locale:ie(t)})))}catch(u){return console.warn("[otherLocales] failed to load collection entities:",u),null}return i.map(u=>{if(u===o)return{locale:u,slug:a};const h=[];for(const f of p){const v=f.availableLinkIds?.[u];if(!v)return null;h.push(v)}return h.length>0?{locale:u,slug:h.join("/")}:null}).filter(u=>u!==null)}},On={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ve=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ir=e=>typeof On[e]=="string",or=e=>{const n=e?.filter(t=>ir(t.key));if(Array.isArray(n)&&n.length>1)throw new E(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},ar=e=>e?.find(n=>n.key==="slug")?.value??null,sr=e=>e?.find(n=>n.key==="id")?.value??null,xe=e=>e?.find(n=>n.key==="locale")?.value??null,je=e=>e?.find(n=>n.key==="channel")?.value??null,Oe=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},cr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},lr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},dr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Oe(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??a,absolute:a}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Oe(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??a,absolute:a}}},ur={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},pr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new E("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function Cn(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 gr(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 mr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=Cn(r);return{isPendingForOtherAuthorizer:!i&&gr(r),ruleForAuthorization:i}},hr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new E("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},fr=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},Sr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),yr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:o}=n;if(!r||!i||!o)throw new E("Missing required fields: fileContent, fileName, mimeType");const a=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(a.length*3/4)>s)throw new E("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw new E("Invalid Base64 fileContent");const p=Buffer.from(a,"base64");return await t.orderEntry.uploadFile({fileBuffer:p,fileName:i,mimeType:o})};class ce{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const Ce=(e,n)=>{e.storage.channel=ce.parse(n)},be=(e,n)=>{e.storage.locale=n},bn=e=>qn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function wn(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Ir(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Dn(e){return bn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const vr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,o=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&o!==null?[o,i]:[]}return[r]},Or=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,o=e?.shippingData?.availableAddresses??[],a=e?.shippingData?.selectedAddresses??[];if(!t&&a.length>0)return[a[0]];if(t&&o.length>0)for(const s of o){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},An=(e,n)=>{if(!Cr(n))return{updateShipping:!1,addressChanged:!1};if(!Ar(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(br(t,n.postalCode)||wr(t,n.geoCoordinates)||Dr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Pr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Cr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,br=(e,n)=>typeof n=="string"&&e?.postalCode!==n,wr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Dr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Ar=e=>e.items.length!==0,Pr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:o}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:a,selectedSla:s,slas:c})=>{const l=t&&a!==t,p=r&&s!==r;return c?.some(u=>l&&u.deliveryChannel===t||p&&u.id===r?!0:i&&o&&u.deliveryChannel===t&&u.id===r&&(!u?.deliveryWindow||u?.deliveryWindow?.startDateUtc!==i||u?.deliveryWindow?.endDateUtc!==o)&&u.availableDeliveryWindows?.some(h=>h?.startDateUtc===i&&h?.endDateUtc===o))})},Pn=e=>e.valueReference===re.attachment,we=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Pn).map(Dn).join("-")].filter(Boolean).join("::"),le=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(wn)},index:n}),Er=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Pn)??[]).map(n=>({name:n.name,content:n.value}))}),We=e=>e.reduce((n,t)=>{const r=we(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Ur=(e,n)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=n.items.map(le).map(t),i=e.acceptedOffer.map(t),o=e.orderNumber===n.orderFormId,a=Ue(r,i);return o&&a};function En(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Un(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const o=Un(e.items,r.id)||En(e.items,r.id)?`${we(le(r))}::${i}`:we(le(r));return t[o]||(t[o]=[]),t[o].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((a,s)=>a+s.quantity,0),o=t.reduce((a,s)=>a+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:o/i}})}},He=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),Tn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return bn(JSON.stringify({sessionId:n?.id??"",items:t}))},Xe=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:Tn(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
3
3
|
Make sure to add the following custom app to the orderForm:
|
|
4
4
|
{"fields":["cartEtag"],"id":"faststore","major":1}.
|
|
5
|
-
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},
|
|
6
|
-
`),r}}const
|
|
7
|
-
`)}let _;o.seller&&(s||p)&&(_=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:p,country:c,salesChannel:S}))?.[0]?.sellers.find(se=>o.seller===se.id));const G={...n,currency:{code:D?.currencyCode?.value??n.currency.code,symbol:D?.currencySymbol?.value??n.currency.symbol},country:D?.countryCode?.value??c,channel:re.stringify({salesChannel:D?.channel?.value??o.salesChannel,regionId:U?.regionId?.value??o.regionId,seller:_?.id,hasOnlyDefaultSalesChannel:!D?.channel?.value}),b2b:y?{isRepresentative:y??!1,customerId:A?.customerId?.value??C??"",unitName:A?.unitName?.value??"",unitId:A?.unitId?.value??w??"",firstName:typeof f?.firstName?.value=="string"?f.firstName.value:"",lastName:typeof f?.lastName?.value=="string"?f.lastName.value:"",userName:`${typeof f?.firstName?.value=="string"?f.firstName.value:""} ${typeof f?.lastName?.value=="string"?f.lastName.value:""}`.trim(),userEmail:A?.storeUserEmail.value??"",savedPostalCode:O?.postalCode?.value??"",contractName:wn(T,P),organizationManager:f?.organizationManager?.value??!1}:null,marketingData:d,person:P?.id?{id:P.id?.value??"",email:P.email?.value??"",givenName:P.firstName?.value??"",familyName:P.lastName?.value??""}:null,geoCoordinates:p?.latitude&&p?.longitude&&p||null,city:l};return Ce(n,G)?null:G},_r={validateCart:Cr,validateSession:Tr,subscribeToNewsletter:or,cancelOrder:nr,processOrderAuthorization:rr,uploadFileToOrderEntry:sr,startOrderEntryOperation:ir,startRecommendationSession:ar};var ve;(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"})(ve||(ve={}));const Rr=e=>typeof e=="string"?Dn(e):null;function Dn(e){try{return JSON.parse(e)}catch{return e}}const kr=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Fr=new te.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Rr,serialize:kr,parseLiteral(e){return e.kind===ve.STRING?Dn(e.value):null}}),F=e=>"Price"in e&&"seller"in e&&"product"in e,k=e=>"skuName"in e,Nr={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>F(e)?e.PriceValidUntil??"":k(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>F(e)?_e(M(e)):k(e)?_e(zt(e.availability)):null,seller:(e,n,t)=>F(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:k(e)?{identifier:e.seller}:null,price:e=>F(e)?j(e):k(e)?e.sellingPrice/100:null,priceWithTaxes:e=>F(e)?$(j(e),e?.Tax,e.product.unitMultiplier):k(e)?$(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>F(e)?$t(e):k(e)?e.sellingPrice/100:null,listPrice:e=>F(e)?e.ListPrice??0:k(e)?e.listPrice/100:null,listPriceWithTaxes:e=>F(e)?$(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):k(e)?$(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>F(e)?e.product:k(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>F(e)?e.AvailableQuantity??0:k(e)?e.quantity:null,isGift:e=>k(e)?e.isGift??!1:null},Lr=({linkText:e})=>`/${e}/p`,Br=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Mr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},An=(e,n)=>`${e}-${n}`,$r=(e,n)=>`/${An(e,n)}/p`,zr=e=>Array.isArray(e)&&e.length>0?e:null;function Pn(e){return e.replace(/^\/+|\/+$/g,"")}const xr=(e,n)=>{const t=e.findIndex(r=>Pn(r).split("/").at(-1)===n);return t<0?0:t},qr={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>An(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Lr(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:({isVariantOf:{categories:e,productName:n,linkText:t,categoryId:r,categoriesIds:i},itemId:a})=>{const o=xr(i,r),s=e[o],c=Pn(s).split("/");return{itemListElement:[...c.map((l,p)=>{const u=`/${c.slice(0,p+1).map(pn).join("/")}/`;return{name:l,item:u,position:p+1}}),{name:n,item:$r(t,a),position:c.length+1}],numberOfItems:c.length}},image:({images:e},n)=>{const t=(zr(e)??[Mr]).map(({imageUrl:s,imageText:c,imageLabel:l})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:l}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const 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=>Br({offer:n.commertialOffer,seller:n,product:e})).sort(un),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:ee.specification}))),i=n.map(Sn),a=t.map(cr);return[...r,...i,...a]},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},Vr=new Set(["allSpecifications"]),jr={hasVariant:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!Vr.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:ee.specification}))))},Wr={propertyID:e=>e.propertyID||yn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},Gr=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Hr=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))},ae=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=fe(n,({offer:r},{offer:i})=>un(r,i));return t?t.sku:e[0]},Xr=e=>e!==""&&!Number.isNaN(Number(e)),Yr=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Jr=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!Yr.test(s))throw new E(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new E("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(S=>!S?.trim())))throw new E("Invalid products: must be an array of non-empty strings");const l=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:p,correlationId:u}=l;return{products:(l.products??[]).map(S=>{const b=ae(S.items);return b?N(b,S):null}).filter(S=>!!S),correlationId:u,campaign:p}},Ve={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:""},En="Invalid SkuId",Kr="Slug was set but the fetched sku does not satisfy the slug condition.",Qr=e=>be(e)||e instanceof Error&&(e.message===En||e.message.startsWith(Kr)),Zr={product:async(e,{locator:n},t)=>{const r=Be(n),i=Le(n),a=Jt(n),o=Yt(n);r&&Se(t,r),i&&ye(t,i);const{loaders:{skuLoader:s},clients:{commerce:c,search:l}}=t;try{const p=a??o?.split("-").pop()??"";if(!Xr(p))throw new Error(En);const u=await s.load(p);if(o&&u.isVariantOf.linkText&&!o.startsWith(u.isVariantOf.linkText))throw new Error(`Slug was set but the fetched sku does not satisfy the slug condition. slug: ${o}, linkText: ${u.isVariantOf.linkText}`);return u}catch(p){if(!Qr(p))throw p;if(o==null)throw new E("Missing slug or id");const u=await c.catalog.portal.pagetype(`${o}/p`);if(u.pageType!=="Product"||!u.id)throw new B(`No product found for slug ${o}`);const h=await l.fetchProduct({field:"id",value:String(u.id)}).catch(()=>null);if(!h)throw new B(`No product found for id ${u.id}`);const S=ae(h.items);return N(S,h)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load(n)},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Be(a),l=Le(a),p=Xt(a);c&&Se(s,c),l&&ye(s,l);const u=t?Number(t):0,h={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:Ve[r??"score_desc"]??Ve.score_desc,selectedFacets:a?.flatMap(Fe)??[],sponsoredCount:o??void 0};if(p){const d=(await s.clients.commerce.catalog.products.crossselling({type:mn[p.key],productId:p.value})).map(m=>m.productId).slice(0,n),g=s.clients.search.productsByIdentifier({field:"id",values:d}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:h,productSearchPromise:g}}const S=s.clients.search.products(h);return{searchArgs:h,productSearchPromise:S}},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(l=>N(l,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,l)=>({node:c,cursor:(a+l).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=>N(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=[],l=(h,S)=>{c.push({...h,level:S});for(const b of h.children)l(b,S+1)};for(const h of s)l(h,0);const u=[...o.filter(h=>h.isActive).map(h=>({...h,type:"brand"})),...c].filter(h=>!!gn.slug(h,null,r,null));return{pageInfo:{hasNextPage:u.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,u.length-a)-1).toString(),totalCount:u.length},edges:u.slice(a,a+n).map((h,S)=>({node:h,cursor:(a+S).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(Fe)??[],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:l,sellers:p}=c;return{id:l,sellers:p}},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 E("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new B(`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 be(r)?new B(`No order found for id ${n}. ${o}.`):an(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}},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[l]=await r.masterData.getShopperById({userId:c});if(l){const p=[l.firstName,l.lastName].filter(Boolean).join(" ");p&&o.set(c,p)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?o.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=Q(x(i?.cookie??"",r))?.userId??"",[c,l,p]=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=l?.[0],h=c?.namespaces.authentication??null,S=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:h?.storeUserEmail?.value??"",name:S,email:h?.storeUserEmail?.value??"",phone:u?.phone??"",role:p?.Roles?.map(b=>b.Name)??[],orgUnit:h?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=Q(x(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const l=c.namespaces.profile??null,p=await a.masterData.getContractById({contractId:l?.id?.value??""});return{name:wn(p,l)||"",email:l?.email?.value||"",id:l?.id?.value||""}}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 E("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:a}}=t,o=await a.session("").catch(()=>null),s=x(i?.cookie??"",r);let c=null;try{c=s?Q(s):null}catch{c=null}const l=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!l||l!==n)throw new q("You are not allowed to list contracts for this organization unit");const p=Dr(o?.namespaces.shopper),u=Pr(o)||c?.customerId?.trim()||"";return Er(p,u)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:Gr,orderFormItems:Hr,recommendations:Jr},ei={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},ni=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,ti={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(p=>{const u=ae(p.items);return u&&N(u,p)}).filter(p=>!!p),{searches:l}=o;return{terms:l.map(p=>({value:p.term,count:p.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=ae(r.items);return i&&N(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),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(l=>!a||!ni(l,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},ri={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},ii=["bd","d","h","m"],ai=e=>ii.includes(e),oi={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"}},Un=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=ai(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return oi[t][a].replace("#",n)??""},si={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Un(e.shippingEstimate):""},je="skuvariation";function We(e,n){const t=`${je}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===je);return i||e[0]}function ci(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,l)=>l.name===n?c:c+`-${l.name}-${l.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function Ge(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function li(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function di(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function ui(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>di(i.value,a.value));return n}function pi(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 l=We(a.images,n),p={src:l.imageUrl,alt:l.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(p):r[o.name]=[p];return}a.variations.forEach(c=>{const l=`${c.name}-${c.values[0]}`;if(i.has(l))return;i.add(l);const p=We(a.images,c.name),u={src:p.imageUrl,alt:p.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),ui(r)}const gi={activeVariations:e=>Ge(e.variations),allVariantsByName:e=>li(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>ci(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=Ge(e.variations)[t];return pi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf))},mi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},hi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((l,p)=>{const u=p?.selectedSla||"",h=p?.selectedDeliveryChannel||p?.deliveryChannel||"",S=p?.deliveryCompany||"",b=p?.deliveryWindow,d=p?.pickupStoreInfo,g=p?.shippingEstimate||"",m=p?.shippingEstimate?Un(p?.shippingEstimate):"",y=p?.shippingEstimateDate||"",C=p?.addressId||"",w=p?.itemIndex??0,v=t?.[w],P=v?.seller||"",f=`${u}|${h}|${S}|${P}|${g}|${y}|${C}|${b?.startDateUtc}|${b?.endDateUtc}`,D=i?.find(_=>_?.addressId===C),A=`${mi[h]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:U,taxPriceTags:O}=fi(v?.priceTags??[]),T=(v?.sellingPrice??0)*(v?.quantity??0)+(v?.tax??0)+(U??0);return l[f]||(l[f]={selectedSla:u,deliveryChannel:h,deliveryCompany:S,deliveryWindow:b,shippingEstimate:g,shippingEstimateDate:y,seller:P,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:d,quantityOfDifferentItems:0,total:0,items:[]}),l[f]&&(l[f].items?.push({id:v?.id||"",uniqueId:v?.uniqueId||"",name:v?.name||"",quantity:v?.quantity||0,price:v?.price||0,sellingPrice:v?.sellingPrice||0,imageUrl:v?.imageUrl||"",taxPriceTags:O??[],taxPriceTagsTotal:U??0,tax:v?.tax||0,total:T}),l[f].quantityOfDifferentItems=(l[f].quantityOfDifferentItems??0)+1,l[f].total=(l[f].total??0)+T),l},{}),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 fi(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 Si={StoreCollection:gn,StoreAggregateOffer:qt,StoreProduct:qr,StoreSeo:ri,StoreFacet:Kt,StoreFacetBoolean:Qt,StoreFacetRange:Zt,StoreFacetValueBoolean:er,StoreOffer:Nr,StoreAggregateRating:Vt,StoreReview:ei,StoreProductGroup:jr,StoreSearchResult:ti,StorePropertyValue:Wr,SkuVariants:gi,ShippingSLA:si,UserOrderResult:hi,ObjectOrString:Fr,Query:Zr,Mutation:_r},yi=()=>Si,Ii=`"""
|
|
5
|
+
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},Tr=(e,n)=>{const r=e.customData?.customApps.find(o=>o.id==="faststore")?.fields?.cartEtag;return r==null?!0:Tn(e,n)!==r},kr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Ye=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=An(e,n);if(r){const o=Or(e,n,i),s=o||vr(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},_r=(e,n)=>{if(!e)return"";const r=te.parse(e)[n];return r?r.split("=")[1]:""},Rr=async(e,{cart:{order:n},session:t},r)=>{const i=_r(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:o},loaders:{skuLoader:a}}=r,s=t?.channel,c=t?.locale;s&&Ce(r,s),c&&be(r,c);const l=await o.checkout.orderForm({id:i||void 0,channel:r.storage.channel}),p=l.orderFormId;l.messages.length!==0&&await kr(p,r);const u=te.parse(r?.headers?.cookie??"")?.vtex_session,h=Z(u),{acceptedOffer:f,shouldSplitItem:v}=n;if(Tr(l,h)){const b=await Xe(l,o,h).then(Ge);if(p)return He(b,a,v)}const g=We(f),m=We(l.items.map(le)),y=Array.from(m.entries()),O=Array.from(g.entries()),{itemsToAdd:w,itemsToUpdate:C}=O.reduce((b,[T,k])=>{const G=m.get(T);if(!G)return k.forEach(H=>b.itemsToAdd.push(H)),b;const[_,...Te]=G;if(Un(l.items,_.itemOffered.sku)||En(l.items,_.itemOffered.sku))return b.itemsToUpdate.push(_),b;const pe=k.reduce((H,$n)=>H+$n.quantity,0);return b.itemsToUpdate.push({..._,quantity:pe}),Te.forEach(H=>b.itemsToUpdate.push({...H,quantity:0})),b},{itemsToAdd:[],itemsToUpdate:[]}),P=y.filter(([b])=>!g.has(b)).flatMap(([,b])=>b.map(T=>({...T,quantity:0}))),S=[...w,...C,...P].map(Er),{updateShipping:D}=t?An(l,t):{updateShipping:!1};if(S.length===0&&!D)return null;let A;S.length>0?A=await o.checkout.updateOrderFormItems({id:l.orderFormId,orderItems:S,shouldSplitItem:v}).then(b=>Ye(b,t,r)):A=await Ye(l,t,r),A=await Promise.resolve(A).then(b=>{if(t?.marketingData){const T={...b.marketingData,...t.marketingData};return o.checkout.marketingData({id:l.orderFormId,marketingData:T})}return b}).then(b=>c&&b.clientPreferencesData?.locale!==c?o.checkout.clientPreferencesData({id:b.orderFormId,clientPreferencesData:{...b.clientPreferencesData,locale:c}}):b).then(b=>Xe(b,o,h)).then(Ge);const U=Ue(l.messages,A.messages);return Ur(n,A)&&U?null:He(A,a,v)},Fr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Nr=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"},Lr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Nr):[]},Br=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,$r=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Mr=(e,n="")=>{const t=n.trim();return e.filter(Br).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},kn=(e,n)=>{const t=Fr(e);return t||(n?.firstName?.value??"").trim()};async function zr(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}).
|
|
6
|
+
`),r}}const qr=async(e,{session:n,search:t},{clients:r,headers:i,account:o})=>{const a=ce.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let l=n.city??null,p=n.geoCoordinates??null;if((!l||!p)&&s!==""&&c!==""){const _=await zr(r,c,s);l=_.city,p=_.geoCoordinates}const h=new URLSearchParams(t);h.has("facets")&&h.delete("facets");const f=h.get("sc")??a.salesChannel;h.set("sc",f),s&&h.set("postalCode",s),c&&h.set("country",c),p&&h.set("geoCoordinates",`${p.longitude},${p.latitude}`),h.set("locale",n.locale);const{marketingData:v}=n,d={utmCampaign:h.get("utm_campaign")??v?.utmCampaign??"",utmMedium:h.get("utm_medium")??v?.utmMedium??"",utmSource:h.get("utm_source")??v?.utmSource??"",utmiCampaign:h.get("utmi_cp")??v?.utmiCampaign??"",utmiPage:h.get("utmi_p")??v?.utmiPage??"",utmiPart:h.get("utmi_pc")??v?.utmiPart??""},g=Z(V(i?.cookie??"",o));let m=!1;if(g)try{m=(await r.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(_){console.warn("JWT validation failed:",_),m=!1}const y=m?g?.isRepresentative:!1,O=m?g?.customerId:void 0,w=m?g?.unitId:void 0,C=await r.commerce.session(h.toString()).catch(()=>null),P=C?.namespaces.profile??null,S=C?.namespaces.shopper??null,D=C?.namespaces.store??null,A=C?.namespaces.authentication??null,U=C?.namespaces.checkout??null,b=C?.namespaces.public??null;let T=null;if(y&&P?.id?.value)try{T=await r.commerce.masterData.getContractById({contractId:P.id.value})}catch{console.error(`Error while getting contract data for profile ID (${P.id.value}).
|
|
7
|
+
`)}let k;a.seller&&(s||p)&&(k=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:p,country:c,salesChannel:f}))?.[0]?.sellers.find(pe=>a.seller===pe.id));const G={...n,currency:{code:D?.currencyCode?.value??n.currency.code,symbol:D?.currencySymbol?.value??n.currency.symbol},country:D?.countryCode?.value??c,channel:ce.stringify({salesChannel:D?.channel?.value??a.salesChannel,regionId:U?.regionId?.value??a.regionId,seller:k?.id,hasOnlyDefaultSalesChannel:!D?.channel?.value}),b2b:y?{isRepresentative:y??!1,customerId:A?.customerId?.value??O??"",unitName:A?.unitName?.value??"",unitId:A?.unitId?.value??w??"",firstName:typeof S?.firstName?.value=="string"?S.firstName.value:"",lastName:typeof S?.lastName?.value=="string"?S.lastName.value:"",userName:`${typeof S?.firstName?.value=="string"?S.firstName.value:""} ${typeof S?.lastName?.value=="string"?S.lastName.value:""}`.trim(),userEmail:A?.storeUserEmail.value??"",savedPostalCode:b?.postalCode?.value??"",contractName:kn(T,P),organizationManager:S?.organizationManager?.value??!1}:null,marketingData:d,person:P?.id?{id:P.id?.value??"",email:P.email?.value??"",givenName:P.firstName?.value??"",familyName:P.lastName?.value??""}:null,geoCoordinates:p?.latitude&&p?.longitude&&p||null,city:l};return Ue(n,G)?null:G},Vr={validateCart:Rr,validateSession:qr,subscribeToNewsletter:Sr,cancelOrder:pr,processOrderAuthorization:mr,uploadFileToOrderEntry:yr,startOrderEntryOperation:hr,startRecommendationSession:fr};var De;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(De||(De={}));const xr=e=>typeof e=="string"?_n(e):null;function _n(e){try{return JSON.parse(e)}catch{return e}}const jr=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Wr=new ae.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:xr,serialize:jr,parseLiteral(e){return e.kind===De.STRING?_n(e.value):null}}),F=e=>"Price"in e&&"seller"in e&&"product"in e,R=e=>"skuName"in e,Gr={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>F(e)?e.PriceValidUntil??"":R(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>F(e)?$e($(e)):R(e)?$e(Kt(e.availability)):null,seller:(e,n,t)=>F(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:R(e)?{identifier:e.seller}:null,price:e=>F(e)?j(e):R(e)?e.sellingPrice/100:null,priceWithTaxes:e=>F(e)?M(j(e),e?.Tax,e.product.unitMultiplier):R(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>F(e)?Jt(e):R(e)?e.sellingPrice/100:null,listPrice:e=>F(e)?e.ListPrice??0:R(e)?e.listPrice/100:null,listPriceWithTaxes:e=>F(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):R(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>F(e)?e.product:R(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>F(e)?e.AvailableQuantity??0:R(e)?e.quantity:null,isGift:e=>R(e)?e.isGift??!1:null},Hr=({linkText:e})=>`/${e}/p`,Xr=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Yr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,Je=(e,n)=>`/${oe(e,n)}/p`,Jr=e=>Array.isArray(e)&&e.length>0?e:null;function Ae(e){return e.replace(/^\/+|\/+$/g,"")}async function Pe(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,o=i.get(r);if(o)return o;const a=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,a),a}const Kr=(e,n)=>{const t=e.findIndex(r=>Ae(r).split("/").at(-1)===n);return t<0?0:t},Qr={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>oe(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Hr(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:o,categoryId:a,categoriesIds:s,productId:c},itemId:l}=e,p=Kr(s,a),u=r[p],h=Ae(u).split("/"),f=t.storage.locale;if(ne(t)&&f){const v=await Pe(t,c,f);if(v){const d=new Set(Ae(s[p]).split("/").filter(Boolean)),g=v.categories.filter(y=>d.has(y.id.toString())).sort((y,O)=>y.fullPath.split("/").length-O.fullPath.split("/").length);if(g.length===h.length)return{itemListElement:[...g.map((y,O)=>({name:y.name,item:`/${y.fullPathUriName}/`,position:O+1})),{name:i,item:Je(v.linkId,l),position:h.length+1}],numberOfItems:h.length}}}return{itemListElement:[...h.map((v,d)=>{const g=`/${h.slice(0,d+1).map(se).join("/")}/`;return{name:v,item:g,position:d+1}}),{name:i,item:Je(o,l),position:h.length+1}],numberOfItems:h.length}},image:({images:e},n)=>{const t=(Jr(e)??[Yr]).map(({imageUrl:s,imageText:c,imageLabel:l})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:l}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const o=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let a=o?t.filter(({keywords:s})=>s===r):t;return a=a.length===0?t:a,a.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>Xr({offer:n.commertialOffer,seller:n,product:e})).sort(In),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:a,values:s})=>s.map(c=>({name:a,value:c,valueReference:re.specification}))),i=n.map(wn),o=t.map(Ir);return[...r,...i,...o]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ne(t))return null;const r=pt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,o=e.itemId,a=t.storage.locale,s=gt(t),c=await Pe(t,i,a);if(!c?.availableLinkIds)return null;const{availableLinkIds:l}=c,{linkText:p}=e.isVariantOf;return r.map(u=>{if(u===s)return{locale:u,slug:oe(p,o)};const h=l[u];return h?{locale:u,slug:oe(h,o)}:null}).filter(u=>u!==null)}},Zr=new Set(["allSpecifications"]),ei={hasVariant:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!Zr.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},ni={propertyID:e=>e.propertyID||Dn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},de=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Oe(n,({offer:r},{offer:i})=>In(r,i));return t?t.sku:e[0]},Rn=e=>e!==""&&!Number.isNaN(Number(e)),ti=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,ri=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:o}}=i,{salesChannel:a}=i.storage.channel,s=n?.trim();if(!s||!ti.test(s))throw new E(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new E("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(f=>!f?.trim())))throw new E("Invalid products: must be an array of non-empty strings");const l=await o.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:a??void 0,locale:i.storage.locale}),{campaign:p,correlationId:u}=l;return{products:(l.products??[]).map(f=>{const v=de(f.items);return v?N(v,f):null}).filter(f=>!!f),correlationId:u,campaign:p}},Ke={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},ii=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing operationId");return t.orderEntry.getOperation({operationId:n})},oi=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function ai(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await Pe(e,t,r))?.linkId===i}const Fn="Invalid SkuId",Nn="Slug was set but the fetched sku does not satisfy the slug condition.",si=e=>q(e)||e instanceof Error&&(e.message===Fn||e.message.startsWith(Nn));async function ci(e,n,t,r){const{linkText:i,productId:o}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ne(e)&&r&&Rn(t.split("-").pop()??"")&&await ai(e,t,o,r)))throw new Error(`${Nn} slug: ${t}, linkText: ${i}`)}async function li(e,n){if(n==null)throw new E("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new B(`No product found for slug ${n}`);const o=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!o)throw new B(`No product found for id ${i.id}`);return N(de(o.items),o)}const di={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),o=sr(n),a=ar(n);r&&Ce(t,r),i&&be(t,i);const{loaders:{skuLoader:s}}=t;try{const c=o??a?.split("-").pop()??"";if(!Rn(c))throw new Error(Fn);const l=await s.load(c);return await ci(t,l,a,i),l}catch(c){if(!si(c))throw c;return li(t,a)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ie(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:o,sponsoredCount:a},s)=>{const c=je(o),l=xe(o),p=or(o);c&&Ce(s,c),l&&be(s,l);const u=t?Number(t):0,h={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:Ke[r??"score_desc"]??Ke.score_desc,selectedFacets:o?.flatMap(qe)??[],sponsoredCount:a??void 0};if(p){const d=(await s.clients.commerce.catalog.products.crossselling({type:On[p.key],productId:p.value})).map(m=>m.productId).slice(0,n),g=s.clients.search.productsByIdentifier({field:"id",values:d}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:h,productSearchPromise:g}}const f=s.clients.search.products(h);return{searchArgs:h,productSearchPromise:f}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,o=t?Number(t):0,a=await i.products({page:Math.ceil(o/n),count:n}),s=a.products.flatMap(c=>c.items.map(l=>N(l,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:a.pagination.after.length>0,hasPreviousPage:a.pagination.before.length>0,startCursor:"0",endCursor:a.recordsFiltered.toString(),totalCount:a.recordsFiltered},edges:s.map((c,l)=>({node:c,cursor:(o+l).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(o=>o.items.map(a=>N(a,o))).filter(o=>n.includes(o.itemId)&&o.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,o=t?Number(t):0,[a,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],l=(f,v)=>{c.push({id:f.id,name:f.name,fatherCategoryId:v,linkId:se(f.name),title:f.Title,description:null,metaTagDescription:f.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(f.url).pathname.slice(1).toLowerCase()});for(const d of f.children)l(d,f.id)};for(const f of s)l(f,null);const h=[...a.filter(f=>f.isActive).map(f=>({id:f.id,name:f.name,linkId:se(f.name),title:f.title,description:null,metaTagDescription:f.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(f=>!!vn.slug(f,null,r,null));return{pageInfo:{hasNextPage:h.length-o>n,hasPreviousPage:o>0,startCursor:"0",endCursor:(Math.min(n,h.length-o)-1).toString(),totalCount:h.length},edges:h.slice(o,o+n).map((f,v)=>({node:f,cursor:(o+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:o},clients:{commerce:a}}=i,[s,c]=await Promise.all([o.load({country:n,items:t,postalCode:r}),a.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},o)=>{const{clients:{commerce:a}}=o,c=(await a.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:l,sellers:p}=c;return{id:l,sellers:p}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function o(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:o(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new E("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new B(`No order found for id ${n}`);let o=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});o=Cn(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!o,ruleForAuthorization:o,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let o={};try{const s=JSON.parse(i);o=s.error||s}catch{o={message:i}}const a=o?.message||i;throw q(r)?new B(`No order found for id ${n}. ${a}.`):gn(r)?new x(`You are forbidden to interact with order with id ${n}. ${a}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(o=>({orderId:o.orderId,creationDate:o.creationDate,clientName:o.clientName,items:o.items,totalValue:o.totalValue,status:o.status,statusDescription:o.statusDescription,ShippingEstimatedDate:o.ShippingEstimatedDate,customFields:o.customFields,currencyCode:o.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),o=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],a=new Map;return await Promise.all(o.map(async c=>{try{const[l]=await r.masterData.getShopperById({userId:c});if(l){const p=[l.firstName,l.lastName].filter(Boolean).join(" ");p&&a.set(c,p)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?a.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,s=Z(V(i?.cookie??"",r))?.userId??"",[c,l,p]=await Promise.all([o.session("").catch(()=>null),s?o.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?o.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),u=l?.[0],h=c?.namespaces.authentication??null,f=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:h?.storeUserEmail?.value??"",name:f,email:h?.storeUserEmail?.value??"",phone:u?.phone??"",role:p?.Roles?.map(v=>v.Name)??[],orgUnit:h?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,a=Z(V(i?.cookie??"",r));if(!a?.userId)return null;if(a?.isRepresentative){const c=await o.session("").catch(()=>null);if(!c)return null;const l=c.namespaces.profile??null,p=await o.masterData.getContractById({contractId:l?.id?.value??""});return{name:kn(p,l)||"",email:l?.email?.value||"",id:l?.id?.value||""}}const s=await o.licenseManager.getUserById({userId:a?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new E("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:o}}=t,a=await o.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Z(s):null}catch{c=null}const l=a?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!l||l!==n)throw new x("You are not allowed to list contracts for this organization unit");const p=Lr(a?.namespaces.shopper),u=$r(a)||c?.customerId?.trim()||"";return Mr(p,u)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:ii,orderFormItems:oi,recommendations:ri},ui={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},pi=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,gi={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(u=>({value:u.term,count:u.count})),products:[]};const{productSearchPromise:o}=e,[a,s]=await Promise.all([r.suggestedTerms(i),o]),c=s.products.map(p=>{const u=de(p.items);return u&&N(u,p)}).filter(p=>!!p),{searches:l}=a;return{terms:l.map(p=>({value:p.term,count:p.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=de(r.items);return i&&N(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),o=!e.query,a=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(l=>!o||!pi(l,a,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},mi={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},hi=["bd","d","h","m"],fi=e=>hi.includes(e),Si={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"}},Ln=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=fi(t);if(!r||!i)return"";const o=Number(n)<2?Number(n):"other";return Si[t][o].replace("#",n)??""},yi={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Ln(e.shippingEstimate):""},Qe="skuvariation";function Ze(e,n){const t=`${Qe}${n}`.toLowerCase(),r=e.find(o=>o.imageLabel===t);if(r)return r;const i=e.find(o=>o.imageLabel===Qe);return i||e[0]}function Ii(e,n,t){const r={};return e.forEach(i=>{const o=i.variations;if(o.length===0)return;const a=`${n}-${o.find(c=>c.name===n)?.values[0]??""}`,s=o.reduce((c,l)=>l.name===n?c:c+`-${l.name}-${l.values[0]}`,a);r[s]=`${t}-${i.itemId}`}),r}function en(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function vi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Oi(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Ci(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,o)=>Oi(i.value,o.value));return n}function bi(e,n,t){const r={},i=new Set;return e.forEach(o=>{if(o.variations.length===0)return;const a=o.variations.find(c=>c.name===n);if(!(a?.values[0]===t)){const c=`${n}-${a?.values[0]}`;if(!a||i.has(c))return;i.add(c);const l=Ze(o.images,n),p={src:l.imageUrl,alt:l.imageLabel??"",label:`${n}: ${a.values[0]}`,value:a.values[0]};r[a.name]?r[a.name].push(p):r[a.name]=[p];return}o.variations.forEach(c=>{const l=`${c.name}-${c.values[0]}`;if(i.has(l))return;i.add(l);const p=Ze(o.images,c.name),u={src:p.imageUrl,alt:p.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),Ci(r)}const wi={activeVariations:e=>en(e.variations),allVariantsByName:e=>vi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>Ii(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=en(e.variations)[t];return bi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf))},Di={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Ai={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],o=r.reduce((l,p)=>{const u=p?.selectedSla||"",h=p?.selectedDeliveryChannel||p?.deliveryChannel||"",f=p?.deliveryCompany||"",v=p?.deliveryWindow,d=p?.pickupStoreInfo,g=p?.shippingEstimate||"",m=p?.shippingEstimate?Ln(p?.shippingEstimate):"",y=p?.shippingEstimateDate||"",O=p?.addressId||"",w=p?.itemIndex??0,C=t?.[w],P=C?.seller||"",S=`${u}|${h}|${f}|${P}|${g}|${y}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(k=>k?.addressId===O),A=`${Di[h]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:U,taxPriceTags:b}=Pi(C?.priceTags??[]),T=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(U??0);return l[S]||(l[S]={selectedSla:u,deliveryChannel:h,deliveryCompany:f,deliveryWindow:v,shippingEstimate:g,shippingEstimateDate:y,seller:P,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:d,quantityOfDifferentItems:0,total:0,items:[]}),l[S]&&(l[S].items?.push({id:C?.id||"",uniqueId:C?.uniqueId||"",name:C?.name||"",quantity:C?.quantity||0,price:C?.price||0,sellingPrice:C?.sellingPrice||0,imageUrl:C?.imageUrl||"",taxPriceTags:b??[],taxPriceTagsTotal:U??0,tax:C?.tax||0,total:T}),l[S].quantityOfDifferentItems=(l[S].quantityOfDifferentItems??0)+1,l[S].total=(l[S].total??0)+T),l},{}),a=Object.values(o),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||a?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:a,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",o=r?.linkedEntity?.id||"",a=`${i}|${o||""}`;return t[a]||(t[a]={type:i,id:o,fields:[]}),t[a].fields.push(...r?.fields||[]),t},{}))||[]}};function Pi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,o)=>i+(o.rawValue?o.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Ei={StoreCollection:vn,StoreAggregateOffer:Zt,StoreProduct:Qr,StoreSeo:mi,StoreFacet:cr,StoreFacetBoolean:lr,StoreFacetRange:dr,StoreFacetValueBoolean:ur,StoreOffer:Gr,StoreAggregateRating:er,StoreReview:ui,StoreProductGroup:ei,StoreSearchResult:gi,StorePropertyValue:ni,SkuVariants:wi,ShippingSLA:yi,UserOrderResult:Ai,ObjectOrString:Wr,Query:di,Mutation:Vr},Ui=()=>Ei,Ti=`"""
|
|
8
8
|
Address information.
|
|
9
9
|
"""
|
|
10
10
|
type Address {
|
|
@@ -49,7 +49,7 @@ type Address {
|
|
|
49
49
|
"""
|
|
50
50
|
geoCoordinates: [Float]
|
|
51
51
|
}
|
|
52
|
-
`,
|
|
52
|
+
`,ki=`"""
|
|
53
53
|
Advertisement information about a specific product in a campaign
|
|
54
54
|
"""
|
|
55
55
|
type Advertisement {
|
|
@@ -74,7 +74,7 @@ type Advertisement {
|
|
|
74
74
|
"""
|
|
75
75
|
adResponseId: String!
|
|
76
76
|
}
|
|
77
|
-
`,
|
|
77
|
+
`,_i=`"""
|
|
78
78
|
Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
|
|
79
79
|
"""
|
|
80
80
|
type StoreAggregateOffer {
|
|
@@ -103,7 +103,7 @@ type StoreAggregateOffer {
|
|
|
103
103
|
"""
|
|
104
104
|
offers: [StoreOffer!]!
|
|
105
105
|
}
|
|
106
|
-
`,
|
|
106
|
+
`,Ri=`"""
|
|
107
107
|
Average rating, based on multiple ratings or reviews.
|
|
108
108
|
"""
|
|
109
109
|
type StoreAggregateRating {
|
|
@@ -116,7 +116,7 @@ type StoreAggregateRating {
|
|
|
116
116
|
"""
|
|
117
117
|
reviewCount: Int!
|
|
118
118
|
}
|
|
119
|
-
`,
|
|
119
|
+
`,Fi=`"""
|
|
120
120
|
information about the author of a product review or rating.
|
|
121
121
|
"""
|
|
122
122
|
type StoreAuthor {
|
|
@@ -125,7 +125,7 @@ type StoreAuthor {
|
|
|
125
125
|
"""
|
|
126
126
|
name: String!
|
|
127
127
|
}
|
|
128
|
-
`,
|
|
128
|
+
`,Ni=`"""
|
|
129
129
|
Brand of a given product.
|
|
130
130
|
"""
|
|
131
131
|
type StoreBrand {
|
|
@@ -134,7 +134,7 @@ type StoreBrand {
|
|
|
134
134
|
"""
|
|
135
135
|
name: String!
|
|
136
136
|
}
|
|
137
|
-
`,
|
|
137
|
+
`,Li=`"""
|
|
138
138
|
Item of a list.
|
|
139
139
|
"""
|
|
140
140
|
type StoreListItem {
|
|
@@ -165,7 +165,7 @@ type StoreBreadcrumbList {
|
|
|
165
165
|
"""
|
|
166
166
|
numberOfItems: Int!
|
|
167
167
|
}
|
|
168
|
-
`,
|
|
168
|
+
`,Bi=`"""
|
|
169
169
|
Shopping cart message.
|
|
170
170
|
"""
|
|
171
171
|
type StoreCartMessage {
|
|
@@ -202,8 +202,11 @@ input IStoreCart {
|
|
|
202
202
|
"""
|
|
203
203
|
order: IStoreOrder!
|
|
204
204
|
}
|
|
205
|
-
|
|
206
|
-
Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand
|
|
205
|
+
`,$i=`"""
|
|
206
|
+
Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand\` or \`Collection\`.
|
|
207
|
+
|
|
208
|
+
\`SubCategory\` and \`Cluster\` are still declared for backward compatibility but are
|
|
209
|
+
deprecated and never returned.
|
|
207
210
|
"""
|
|
208
211
|
enum StoreCollectionType {
|
|
209
212
|
"""
|
|
@@ -216,16 +219,26 @@ enum StoreCollectionType {
|
|
|
216
219
|
Category
|
|
217
220
|
"""
|
|
218
221
|
Third level of product categorization.
|
|
222
|
+
|
|
223
|
+
Deprecated: never returned — third-level categories resolve as \`Category\`.
|
|
219
224
|
"""
|
|
220
225
|
SubCategory
|
|
226
|
+
@deprecated(
|
|
227
|
+
reason: "Never returned since the by-linkid migration: the category response only exposes \`fatherCategoryId\`, which distinguishes root from non-root but not tree depth, so third-level categories resolve as \`Category\`. Scheduled for removal in the next major."
|
|
228
|
+
)
|
|
221
229
|
"""
|
|
222
230
|
Product brand.
|
|
223
231
|
"""
|
|
224
232
|
Brand
|
|
225
233
|
"""
|
|
226
234
|
Product cluster.
|
|
235
|
+
|
|
236
|
+
Deprecated: never returned — clusters resolve as \`Collection\`.
|
|
227
237
|
"""
|
|
228
238
|
Cluster
|
|
239
|
+
@deprecated(
|
|
240
|
+
reason: "Never returned since the by-linkid migration: clusters and curated collections are both served by \`collection/by-linkid\`, whose response carries no discriminator between them, so both resolve as \`Collection\`. Scheduled for removal in the next major."
|
|
241
|
+
)
|
|
229
242
|
"""
|
|
230
243
|
Product collection.
|
|
231
244
|
"""
|
|
@@ -284,8 +297,27 @@ type StoreCollection {
|
|
|
284
297
|
Collection type.
|
|
285
298
|
"""
|
|
286
299
|
type: StoreCollectionType!
|
|
300
|
+
"""
|
|
301
|
+
Localized versions of this collection for all available locales.
|
|
302
|
+
Only populated when localization is enabled.
|
|
303
|
+
"""
|
|
304
|
+
otherLocales: [StoreCollectionLocale!]
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
"""
|
|
308
|
+
Localized collection data for a specific locale.
|
|
309
|
+
"""
|
|
310
|
+
type StoreCollectionLocale {
|
|
311
|
+
"""
|
|
312
|
+
Locale code (e.g. "pt-BR", "it-IT").
|
|
313
|
+
"""
|
|
314
|
+
locale: String!
|
|
315
|
+
"""
|
|
316
|
+
Localized collection slug (e.g. "vestuario/camisetas").
|
|
317
|
+
"""
|
|
318
|
+
slug: String!
|
|
287
319
|
}
|
|
288
|
-
`,
|
|
320
|
+
`,Mi=`"""
|
|
289
321
|
Delivery Promise badge.
|
|
290
322
|
"""
|
|
291
323
|
type DeliveryPromiseBadge {
|
|
@@ -294,7 +326,7 @@ type DeliveryPromiseBadge {
|
|
|
294
326
|
"""
|
|
295
327
|
typeName: String
|
|
296
328
|
}
|
|
297
|
-
`,
|
|
329
|
+
`,zi=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
|
|
298
330
|
|
|
299
331
|
"""
|
|
300
332
|
Search facet range information.
|
|
@@ -371,7 +403,7 @@ type StoreFacetValueBoolean {
|
|
|
371
403
|
"""
|
|
372
404
|
quantity: Int
|
|
373
405
|
}
|
|
374
|
-
`,
|
|
406
|
+
`,qi=`"""
|
|
375
407
|
Image.
|
|
376
408
|
"""
|
|
377
409
|
type StoreImage {
|
|
@@ -398,7 +430,7 @@ input IStoreImage {
|
|
|
398
430
|
"""
|
|
399
431
|
alternateName: String!
|
|
400
432
|
}
|
|
401
|
-
`,
|
|
433
|
+
`,Vi=`type Mutation {
|
|
402
434
|
"""
|
|
403
435
|
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\`.
|
|
404
436
|
"""
|
|
@@ -440,7 +472,7 @@ input IStoreImage {
|
|
|
440
472
|
"""
|
|
441
473
|
startRecommendationSession: Boolean!
|
|
442
474
|
}
|
|
443
|
-
`,
|
|
475
|
+
`,xi=`"""
|
|
444
476
|
Newsletter information.
|
|
445
477
|
"""
|
|
446
478
|
type PersonNewsletter {
|
|
@@ -463,8 +495,8 @@ input IPersonNewsletter {
|
|
|
463
495
|
"""
|
|
464
496
|
email: String!
|
|
465
497
|
}
|
|
466
|
-
`,
|
|
467
|
-
`,
|
|
498
|
+
`,ji=`scalar ObjectOrString
|
|
499
|
+
`,Wi=`"""
|
|
468
500
|
Offer information.
|
|
469
501
|
"""
|
|
470
502
|
type StoreOffer {
|
|
@@ -547,7 +579,7 @@ input IStoreOffer {
|
|
|
547
579
|
"""
|
|
548
580
|
quantity: Int!
|
|
549
581
|
}
|
|
550
|
-
`,
|
|
582
|
+
`,Gi=`"""
|
|
551
583
|
Information of a specific order.
|
|
552
584
|
"""
|
|
553
585
|
type StoreOrder {
|
|
@@ -582,7 +614,7 @@ input IStoreOrder {
|
|
|
582
614
|
"""
|
|
583
615
|
shouldSplitItem: Boolean
|
|
584
616
|
}
|
|
585
|
-
`,
|
|
617
|
+
`,Hi=`"""
|
|
586
618
|
Commercial Authorization response.
|
|
587
619
|
"""
|
|
588
620
|
type CommercialAuthorizationResponse {
|
|
@@ -981,7 +1013,7 @@ type ProcessOrderAuthorizationRule {
|
|
|
981
1013
|
"""
|
|
982
1014
|
rule: CommercialAuthorizationRule!
|
|
983
1015
|
}
|
|
984
|
-
`,
|
|
1016
|
+
`,Xi=`"""
|
|
985
1017
|
Input for uploading a file to the Order Entry Service.
|
|
986
1018
|
The file is transmitted as a Base64-encoded string so it can travel
|
|
987
1019
|
through the standard GraphQL JSON pipeline without multipart support.
|
|
@@ -1042,7 +1074,7 @@ type StoreOrderFormCartItem {
|
|
|
1042
1074
|
seller: String!
|
|
1043
1075
|
unitMultiplier: Float
|
|
1044
1076
|
}
|
|
1045
|
-
`,
|
|
1077
|
+
`,Yi=`"""
|
|
1046
1078
|
Organization.
|
|
1047
1079
|
"""
|
|
1048
1080
|
type StoreOrganization {
|
|
@@ -1079,7 +1111,7 @@ type StoreContract {
|
|
|
1079
1111
|
"""
|
|
1080
1112
|
isActive: Boolean!
|
|
1081
1113
|
}
|
|
1082
|
-
|
|
1114
|
+
`,Ji=`"""
|
|
1083
1115
|
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.
|
|
1084
1116
|
"""
|
|
1085
1117
|
type StorePageInfo {
|
|
@@ -1104,7 +1136,7 @@ type StorePageInfo {
|
|
|
1104
1136
|
"""
|
|
1105
1137
|
totalCount: Int!
|
|
1106
1138
|
}
|
|
1107
|
-
`,
|
|
1139
|
+
`,Ki=`"""
|
|
1108
1140
|
Input type for setting a new password.
|
|
1109
1141
|
"""
|
|
1110
1142
|
input ISetPassword {
|
|
@@ -1147,7 +1179,7 @@ type SetPasswordResponse {
|
|
|
1147
1179
|
"""
|
|
1148
1180
|
message: String
|
|
1149
1181
|
}
|
|
1150
|
-
`,
|
|
1182
|
+
`,Qi=`"""
|
|
1151
1183
|
Client profile data.
|
|
1152
1184
|
"""
|
|
1153
1185
|
type StorePerson {
|
|
@@ -1190,7 +1222,7 @@ input IStorePerson {
|
|
|
1190
1222
|
"""
|
|
1191
1223
|
familyName: String!
|
|
1192
1224
|
}
|
|
1193
|
-
`,
|
|
1225
|
+
`,Zi=`type PickupPointAddress {
|
|
1194
1226
|
"""
|
|
1195
1227
|
Address city.
|
|
1196
1228
|
"""
|
|
@@ -1269,7 +1301,7 @@ type PickupPoints {
|
|
|
1269
1301
|
"""
|
|
1270
1302
|
pickupPointsHash: String
|
|
1271
1303
|
}
|
|
1272
|
-
`,
|
|
1304
|
+
`,eo=`"""
|
|
1273
1305
|
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.
|
|
1274
1306
|
"""
|
|
1275
1307
|
type StoreProduct {
|
|
@@ -1365,6 +1397,25 @@ type StoreProduct {
|
|
|
1365
1397
|
Delivery Promise product's badge.
|
|
1366
1398
|
"""
|
|
1367
1399
|
deliveryPromiseBadges: [DeliveryPromiseBadge]
|
|
1400
|
+
"""
|
|
1401
|
+
Localized versions of this product for all available locales.
|
|
1402
|
+
Only populated when localization is enabled.
|
|
1403
|
+
"""
|
|
1404
|
+
otherLocales: [StoreProductLocale!]
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
"""
|
|
1408
|
+
Localized product data for a specific locale.
|
|
1409
|
+
"""
|
|
1410
|
+
type StoreProductLocale {
|
|
1411
|
+
"""
|
|
1412
|
+
Locale code (e.g. "pt-BR", "it-IT").
|
|
1413
|
+
"""
|
|
1414
|
+
locale: String!
|
|
1415
|
+
"""
|
|
1416
|
+
Localized product slug including the SKU ID suffix (e.g. "adidas-polo-uomo-65").
|
|
1417
|
+
"""
|
|
1418
|
+
slug: String!
|
|
1368
1419
|
}
|
|
1369
1420
|
|
|
1370
1421
|
type SkuSpecification {
|
|
@@ -1418,7 +1469,7 @@ input IStoreProduct {
|
|
|
1418
1469
|
"""
|
|
1419
1470
|
additionalProperty: [IStorePropertyValue!]
|
|
1420
1471
|
}
|
|
1421
|
-
`,
|
|
1472
|
+
`,no=`"""
|
|
1422
1473
|
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.
|
|
1423
1474
|
"""
|
|
1424
1475
|
type StoreProductGroup {
|
|
@@ -1445,7 +1496,7 @@ type StoreProductGroup {
|
|
|
1445
1496
|
"""
|
|
1446
1497
|
skuVariants: SkuVariants
|
|
1447
1498
|
}
|
|
1448
|
-
`,
|
|
1499
|
+
`,to=`type Profile {
|
|
1449
1500
|
"""
|
|
1450
1501
|
Collection of user's address
|
|
1451
1502
|
"""
|
|
@@ -1506,7 +1557,7 @@ type ProfileAddress {
|
|
|
1506
1557
|
"""
|
|
1507
1558
|
geoCoordinate: [Float]
|
|
1508
1559
|
}
|
|
1509
|
-
`,
|
|
1560
|
+
`,ro=`"""
|
|
1510
1561
|
Properties that can be associated with products and products groups.
|
|
1511
1562
|
"""
|
|
1512
1563
|
type StorePropertyValue {
|
|
@@ -1546,7 +1597,7 @@ input IStorePropertyValue {
|
|
|
1546
1597
|
"""
|
|
1547
1598
|
valueReference: ObjectOrString!
|
|
1548
1599
|
}
|
|
1549
|
-
`,
|
|
1600
|
+
`,io=`"""
|
|
1550
1601
|
Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
|
|
1551
1602
|
"""
|
|
1552
1603
|
type StoreProductEdge {
|
|
@@ -2176,7 +2227,7 @@ type StoreAccountProfile {
|
|
|
2176
2227
|
email: String
|
|
2177
2228
|
id: String
|
|
2178
2229
|
}
|
|
2179
|
-
`,
|
|
2230
|
+
`,oo=`"""
|
|
2180
2231
|
Summary of a quote returned in list results.
|
|
2181
2232
|
"""
|
|
2182
2233
|
type UserQuoteSummary {
|
|
@@ -2241,7 +2292,7 @@ type UserQuoteListPaging {
|
|
|
2241
2292
|
"""
|
|
2242
2293
|
perPage: Int!
|
|
2243
2294
|
}
|
|
2244
|
-
`,
|
|
2295
|
+
`,ao=`type RecommendationResponse {
|
|
2245
2296
|
products: [StoreProduct!]!
|
|
2246
2297
|
correlationId: String!
|
|
2247
2298
|
campaign: RecommendationCampaign!
|
|
@@ -2252,7 +2303,7 @@ type RecommendationCampaign {
|
|
|
2252
2303
|
title: String
|
|
2253
2304
|
type: String!
|
|
2254
2305
|
}
|
|
2255
|
-
`,
|
|
2306
|
+
`,so=`"""
|
|
2256
2307
|
Information of a given review rating.
|
|
2257
2308
|
"""
|
|
2258
2309
|
type StoreReviewRating {
|
|
@@ -2279,7 +2330,7 @@ type StoreReview {
|
|
|
2279
2330
|
"""
|
|
2280
2331
|
author: StoreAuthor!
|
|
2281
2332
|
}
|
|
2282
|
-
`,
|
|
2333
|
+
`,co=`"""
|
|
2283
2334
|
Search Engine Optimization (SEO) tags data.
|
|
2284
2335
|
"""
|
|
2285
2336
|
type StoreSeo {
|
|
@@ -2300,7 +2351,7 @@ type StoreSeo {
|
|
|
2300
2351
|
"""
|
|
2301
2352
|
canonical: String!
|
|
2302
2353
|
}
|
|
2303
|
-
`,
|
|
2354
|
+
`,lo=`"""
|
|
2304
2355
|
Currency information.
|
|
2305
2356
|
"""
|
|
2306
2357
|
type StoreCurrency {
|
|
@@ -2575,7 +2626,7 @@ input IStoreSession {
|
|
|
2575
2626
|
"""
|
|
2576
2627
|
refreshAfter: String
|
|
2577
2628
|
}
|
|
2578
|
-
`,
|
|
2629
|
+
`,uo=`"""
|
|
2579
2630
|
Shipping Simulation item input.
|
|
2580
2631
|
"""
|
|
2581
2632
|
input IShippingItem {
|
|
@@ -2906,7 +2957,7 @@ type MessageFields {
|
|
|
2906
2957
|
"""
|
|
2907
2958
|
skuName: String
|
|
2908
2959
|
}
|
|
2909
|
-
`,
|
|
2960
|
+
`,po=`type SkuVariants {
|
|
2910
2961
|
"""
|
|
2911
2962
|
SKU property values for the current SKU.
|
|
2912
2963
|
"""
|
|
@@ -3001,7 +3052,7 @@ Example:
|
|
|
3001
3052
|
\`\`\`
|
|
3002
3053
|
"""
|
|
3003
3054
|
scalar FormattedVariants
|
|
3004
|
-
`,
|
|
3055
|
+
`,go=`"""
|
|
3005
3056
|
Status used to indicate a message type. For instance, a shopping cart informative or error message.
|
|
3006
3057
|
"""
|
|
3007
3058
|
enum StoreStatus {
|
|
@@ -3009,7 +3060,7 @@ enum StoreStatus {
|
|
|
3009
3060
|
WARNING
|
|
3010
3061
|
ERROR
|
|
3011
3062
|
}
|
|
3012
|
-
`,
|
|
3063
|
+
`,mo=`scalar JSONObject
|
|
3013
3064
|
|
|
3014
3065
|
type UserOrder {
|
|
3015
3066
|
orderId: String
|
|
@@ -3833,4 +3884,4 @@ type UserOrderBudgetAllocationLinkedEntity {
|
|
|
3833
3884
|
type: String
|
|
3834
3885
|
id: String
|
|
3835
3886
|
}
|
|
3836
|
-
`,
|
|
3887
|
+
`,ho=Object.assign({"./address.graphql":Ti,"./advertisement.graphql":ki,"./aggregateOffer.graphql":_i,"./aggregateRating.graphql":Ri,"./author.graphql":Fi,"./brand.graphql":Ni,"./breadcrumb.graphql":Li,"./cart.graphql":Bi,"./collection.graphql":$i,"./deliveryPromisesBadge.graphql":Mi,"./facet.graphql":zi,"./image.graphql":qi,"./mutation.graphql":Vi,"./newsletter.graphql":xi,"./objectOrString.graphql":ji,"./offer.graphql":Wi,"./order.graphql":Gi,"./orderCommercialAuthorizaton.graphql":Hi,"./orderEntry.graphql":Xi,"./organization.graphql":Yi,"./pageInfo.graphql":Ji,"./password.graphql":Ki,"./person.graphql":Qi,"./pickupPoints.graphql":Zi,"./product.graphql":eo,"./productGroup.graphql":no,"./profile.graphql":to,"./propertyValue.graphql":ro,"./query.graphql":io,"./quote.graphql":oo,"./recommendation.graphql":ao,"./review.graphql":so,"./seo.graphql":co,"./session.graphql":lo,"./shipping.graphql":uo,"./skuVariants.graphql":po,"./status.graphql":go,"./userOrder.graphql":mo}),fo=ae.print(Object.values(ho).map(e=>ae.parse(e)).reduce((e,n)=>nn.mergeTypeDefs([e,n],{sort:!0}))),Bn=fo,So=async e=>L.OTELAPI.context.with(L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),e.OTEL),()=>n=>(n.storage={channel:ce.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.account=e.account,n.OTEL=e.OTEL,n.discoveryConfig=e.discoveryConfig,n.clients=Mt(e,n),n.loaders=Yt(e,n),n));function yo(){const e=Ui(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,o])=>typeof o!="function"?[i,o]:[i,Xn(o,`${t}(${i})`)]));return n}function Io(e){const t=pn([un,dn])(yo(),Bn);return e&&ae.isSchema(e)?tn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=dn;exports.BadRequestError=E;exports.CacheControlDirective=un;exports.CommercialAuthorizationStatus=rn;exports.FastStoreError=W;exports.ForbiddenError=x;exports.GraphqlVtexContextFactory=So;exports.GraphqlVtexSchema=Io;exports.NotFoundError=B;exports.StoreCollectionType=on;exports.StoreFacetType=an;exports.StoreSort=sn;exports.StoreStatus=cn;exports.UnauthorizedError=Q;exports.UserOrderInvoiceType=ln;exports.isBadRequestError=Jn;exports.isFastStoreError=Yn;exports.isForbiddenError=gn;exports.isNotFoundError=q;exports.isUnauthorizedError=Kn;exports.stringifyCacheControl=Gn;exports.typeDefs=Bn;exports.withDirectives=pn;
|