@faststore/api 2.1.83 → 2.1.98

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.
@@ -64,7 +64,6 @@ export declare const VtexCommerce: ({ account, environment, incrementAddress }:
64
64
  address: ({ postalCode, country, }: AddressInput) => Promise<Address>;
65
65
  };
66
66
  session: (search: string) => Promise<Session>;
67
- getSessionOrder: () => Promise<Session>;
68
67
  subscribeToNewsletter: (data: {
69
68
  name: string;
70
69
  email: string;
@@ -1 +1 @@
1
- export declare const fetchAPI: (info: RequestInfo, init?: RequestInit | undefined) => Promise<any>;
1
+ export declare const fetchAPI: (info: RequestInfo, init?: RequestInit | undefined, getHeaders?: ((headers: Headers) => void) | undefined) => Promise<any>;
@@ -57,7 +57,6 @@ export declare const getClients: (options: Options, ctx: Context) => {
57
57
  address: ({ postalCode, country, }: import("./commerce/types/Address").AddressInput) => Promise<import("./commerce/types/Address").Address>;
58
58
  };
59
59
  session: (search: string) => Promise<import("./commerce/types/Session").Session>;
60
- getSessionOrder: () => Promise<import("./commerce/types/Session").Session>;
61
60
  subscribeToNewsletter: (data: {
62
61
  name: string;
63
62
  email: string;
@@ -29,6 +29,7 @@ export interface Context {
29
29
  locale: string;
30
30
  flags: FeatureFlags;
31
31
  searchArgs?: Omit<SearchArgs, 'type'>;
32
+ cookies?: string | null;
32
33
  };
33
34
  headers: Record<string, string>;
34
35
  }
@@ -0,0 +1 @@
1
+ export default function getCookieByName(cookiename: string, source: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faststore/api",
3
- "version": "2.1.83",
3
+ "version": "2.1.98",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -56,5 +56,5 @@
56
56
  "@envelop/core": "^1 || ^2",
57
57
  "graphql": "^15.6.0"
58
58
  },
59
- "gitHead": "a55301974a0ab1894b32414d372091d956fbc17b"
59
+ "gitHead": "5b295774a676946af022c70fb0d04914d3bd3a44"
60
60
  }
@@ -15,11 +15,11 @@ import type {
15
15
  } from './types/Simulation'
16
16
  import type { Session } from './types/Session'
17
17
  import type { Channel } from '../../utils/channel'
18
- import { getCookie } from '../../utils/getCookies'
19
18
  import type { SalesChannel } from './types/SalesChannel'
20
19
  import { MasterDataResponse } from './types/Newsletter'
21
20
  import type { Address, AddressInput } from './types/Address'
22
21
  import { DeliveryMode, SelectedAddress } from './types/ShippingData'
22
+ import getCookieByName from '../../../../utils/get-cookie-by-name'
23
23
 
24
24
  type ValueOf<T> = T extends Record<string, infer K> ? K : never
25
25
 
@@ -30,6 +30,18 @@ const BASE_INIT = {
30
30
  },
31
31
  }
32
32
 
33
+ const setCheckoutOrderFormOwnershipCookie = (
34
+ headers: Headers,
35
+ ctx: Context
36
+ ) => {
37
+ if (headers) {
38
+ ctx.storage.cookies = `CheckoutOrderFormOwnership=${getCookieByName(
39
+ 'CheckoutOrderFormOwnership',
40
+ headers.get('set-cookie') ?? ''
41
+ )}`
42
+ }
43
+ }
44
+
33
45
  export const VtexCommerce = (
34
46
  { account, environment, incrementAddress }: Options,
35
47
  ctx: Context
@@ -131,8 +143,9 @@ export const VtexCommerce = (
131
143
  headers: {
132
144
  'content-type': 'application/json',
133
145
  cookie: ctx.headers.cookie,
134
- }
135
- }
146
+ },
147
+ },
148
+ (headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
136
149
  )
137
150
  },
138
151
 
@@ -153,7 +166,8 @@ export const VtexCommerce = (
153
166
 
154
167
  return fetchAPI(
155
168
  `${base}/api/checkout/pub/orderForm/${id}?${params.toString()}`,
156
- BASE_INIT
169
+ BASE_INIT,
170
+ (headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
157
171
  )
158
172
  },
159
173
  updateOrderFormItems: ({
@@ -183,7 +197,8 @@ export const VtexCommerce = (
183
197
  noSplitItem: !shouldSplitItem,
184
198
  }),
185
199
  method: 'PATCH',
186
- }
200
+ },
201
+ (headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
187
202
  )
188
203
  },
189
204
  setCustomData: ({
@@ -203,7 +218,8 @@ export const VtexCommerce = (
203
218
  ...BASE_INIT,
204
219
  body: JSON.stringify({ value }),
205
220
  method: 'PUT',
206
- }
221
+ },
222
+ (headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
207
223
  )
208
224
  },
209
225
  region: async ({
@@ -243,35 +259,18 @@ export const VtexCommerce = (
243
259
  'items',
244
260
  'profile.id,profile.email,profile.firstName,profile.lastName,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol'
245
261
  )
246
- if (getCookie('vtex_session', ctx.headers.cookie)) {
247
- // cookie set
248
- return fetchAPI(`${base}/api/sessions?${params.toString()}`, {
249
- method: 'GET',
250
- headers: {
251
- 'content-type': 'application/json',
252
- cookie: ctx.headers.cookie,
253
- },
254
- })
255
- } else {
256
- // cookie unset -> create session
257
- return fetchAPI(`${base}/api/sessions?${params.toString()}`, {
262
+ return fetchAPI(
263
+ `${base}/api/sessions?${params.toString()}`,
264
+ {
258
265
  method: 'POST',
259
266
  headers: {
260
267
  'content-type': 'application/json',
261
268
  cookie: ctx.headers.cookie,
262
269
  },
263
270
  body: '{}',
264
- })
265
- }
266
- },
267
- getSessionOrder: (): Promise<Session> => {
268
- return fetchAPI(`${base}/api/sessions?items=public.orderFormId`, {
269
- method: 'GET',
270
- headers: {
271
- 'content-type': 'application/json',
272
- cookie: ctx.headers.cookie,
273
271
  },
274
- })
272
+ (headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
273
+ )
275
274
  },
276
275
  subscribeToNewsletter: (data: {
277
276
  name: string
@@ -3,7 +3,11 @@ import packageJson from '../../../../package.json'
3
3
 
4
4
  const USER_AGENT = `${packageJson.name}@${packageJson.version}`
5
5
 
6
- export const fetchAPI = async (info: RequestInfo, init?: RequestInit) => {
6
+ export const fetchAPI = async (
7
+ info: RequestInfo,
8
+ init?: RequestInit,
9
+ getHeaders?: (headers: Headers) => void
10
+ ) => {
7
11
  const response = await fetch(info, {
8
12
  ...init,
9
13
  headers: {
@@ -13,6 +17,10 @@ export const fetchAPI = async (info: RequestInfo, init?: RequestInit) => {
13
17
  })
14
18
 
15
19
  if (response.ok) {
20
+ if (getHeaders) {
21
+ getHeaders(response.headers)
22
+ }
23
+
16
24
  return response.status !== 204 ? response.json() : undefined
17
25
  }
18
26
 
@@ -35,7 +35,7 @@ export interface Options {
35
35
  channel: string
36
36
  locale: string
37
37
  hideUnavailableItems: boolean
38
- incrementAddress: boolean,
38
+ incrementAddress: boolean
39
39
  flags?: FeatureFlags
40
40
  }
41
41
 
@@ -57,6 +57,7 @@ export interface Context {
57
57
  locale: string
58
58
  flags: FeatureFlags
59
59
  searchArgs?: Omit<SearchArgs, 'type'>
60
+ cookies?: string | null
60
61
  }
61
62
  headers: Record<string, string>
62
63
  }
@@ -92,16 +93,16 @@ const Resolvers = {
92
93
 
93
94
  export const getContextFactory =
94
95
  (options: Options) =>
95
- (ctx: any): Context => {
96
- ctx.storage = {
97
- channel: ChannelMarshal.parse(options.channel),
98
- flags: options.flags ?? {},
99
- locale: options.locale,
100
- }
101
- ctx.clients = getClients(options, ctx)
102
- ctx.loaders = getLoaders(options, ctx)
103
-
104
- return ctx
96
+ (ctx: any): Context => {
97
+ ctx.storage = {
98
+ channel: ChannelMarshal.parse(options.channel),
99
+ flags: options.flags ?? {},
100
+ locale: options.locale,
105
101
  }
102
+ ctx.clients = getClients(options, ctx)
103
+ ctx.loaders = getLoaders(options, ctx)
104
+
105
+ return ctx
106
+ }
106
107
 
107
108
  export const getResolvers = (_: Options) => Resolvers
@@ -1,7 +1,6 @@
1
1
  import deepEquals from 'fast-deep-equal'
2
2
 
3
3
  import { mutateChannelContext, mutateLocaleContext } from '../utils/contex'
4
- import { getCookie } from '../utils/getCookies'
5
4
  import { md5 } from '../utils/md5'
6
5
  import {
7
6
  attachmentToPropertyValue,
@@ -130,7 +129,8 @@ const joinItems = (form: OrderForm) => {
130
129
  const totalPrice = items.reduce(
131
130
  (acc, i) =>
132
131
  acc +
133
- (i?.priceDefinition?.total ?? (i?.quantity ?? 0) * (i?.sellingPrice ?? 0)),
132
+ (i?.priceDefinition?.total ??
133
+ (i?.quantity ?? 0) * (i?.sellingPrice ?? 0)),
134
134
  0
135
135
  )
136
136
 
@@ -207,19 +207,6 @@ const isOrderFormStale = (form: OrderForm) => {
207
207
  return newEtag !== oldEtag
208
208
  }
209
209
 
210
- async function getOrderNumberFromSession(
211
- headers: Record<string, string> = {},
212
- commerce: Context['clients']['commerce']
213
- ) {
214
- const cookieSession = getCookie('vtex_session', headers.cookie)
215
-
216
- if (cookieSession) {
217
- const { namespaces } = await commerce.getSessionOrder()
218
- return namespaces.public?.orderFormId?.value ?? undefined
219
- }
220
- return
221
- }
222
-
223
210
  // Returns the regionalized orderForm
224
211
  const getOrderForm = async (id: string, { clients: { commerce } }: Context) => {
225
212
  return commerce.checkout.orderForm({
@@ -303,15 +290,10 @@ export const validateCart = async (
303
290
  { cart: { order }, session }: MutationValidateCartArgs,
304
291
  ctx: Context
305
292
  ) => {
306
- const {
307
- orderNumber: orderNumberFromCart,
308
- acceptedOffer,
309
- shouldSplitItem,
310
- } = order
293
+ const { orderNumber, acceptedOffer, shouldSplitItem } = order
311
294
  const {
312
295
  clients: { commerce },
313
296
  loaders: { skuLoader },
314
- headers,
315
297
  } = ctx
316
298
 
317
299
  const channel = session?.channel
@@ -325,25 +307,10 @@ export const validateCart = async (
325
307
  mutateLocaleContext(ctx, locale)
326
308
  }
327
309
 
328
- const orderNumberFromSession = await getOrderNumberFromSession(
329
- headers,
330
- commerce
331
- )
332
- const orderNumber = orderNumberFromSession ?? orderNumberFromCart ?? ''
333
-
334
310
  // Step1: Get OrderForm from VTEX Commerce
335
311
  const orderForm = await getOrderForm(orderNumber, ctx)
336
312
 
337
- // Step1.1: Checks if the orderForm id has changed. There are three cases for this:
338
- // Social Selling: the vtex_session cookie contains a new orderForm id with Social Selling data
339
- // My Orders: the customer clicks on reordering through generating a new cart and when returning to the faststore, this information needs to be returned by vtex_session cookie.
340
- // New session: a new user enters the website and has no orderForm attributed to it (has no relation to the vtex_session cookie).
341
- // In all cases, the origin orderForm should replace the copy that's in the browser
342
- if (orderForm.orderFormId != orderNumberFromCart) {
343
- return orderFormToCart(orderForm, skuLoader)
344
- }
345
-
346
- // Step1.2: Check if another system changed the orderForm with this orderNumber
313
+ // Step1.5: Check if another system changed the orderForm with this orderNumber
347
314
  // If so, this means the user interacted with this cart elsewhere and expects
348
315
  // to see this new cart state instead of what's stored on the user's browser.
349
316
  const isStale = isOrderFormStale(orderForm)
@@ -424,6 +391,7 @@ export const validateCart = async (
424
391
  if (equals(order, updatedOrderForm)) {
425
392
  return null
426
393
  }
394
+
427
395
  // Step6: There were changes, convert orderForm to StoreCart
428
396
  return orderFormToCart(updatedOrderForm, skuLoader)
429
397
  }
@@ -0,0 +1,6 @@
1
+ export default function getCookieByName(cookiename: string, source: string) {
2
+ var cookiestring = RegExp(cookiename + '=[^;]+').exec(source)
3
+ return decodeURIComponent(
4
+ !!cookiestring ? cookiestring.toString().replace(/^[^=]+./, '') : ''
5
+ )
6
+ }
@@ -1 +0,0 @@
1
- export declare const getCookie: (name: string, cookie: string) => string;
@@ -1,8 +0,0 @@
1
- export const getCookie = (name: string, cookie: string): string => {
2
- const value = `; ${cookie}`
3
- const parts = value.split(`; ${name}=`)
4
- if (parts.length === 2) {
5
- return parts?.pop()?.split(';').shift() ?? ''
6
- }
7
- return ''
8
- }