@faststore/core 4.11.2 → 4.11.3-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -60,6 +60,10 @@ const entryData: Record<string, Record<string, unknown>> = {
60
60
  settings: { template: { value: '/outra' } },
61
61
  sections: [{ name: 'Other' }],
62
62
  },
63
+ camisetas: {
64
+ settings: { template: { value: '/camisetas/' } },
65
+ sections: [{ name: 'Camisetas PDP' }],
66
+ },
63
67
  }
64
68
 
65
69
  const toEntry = (id: string): ContentEntry => ({
@@ -74,15 +78,49 @@ const toEntry = (id: string): ContentEntry => ({
74
78
  slug: id,
75
79
  })
76
80
 
81
+ const toEntryWithContent = (id: string) => ({
82
+ ...toEntry(id),
83
+ content: { ...entryData[id] },
84
+ })
85
+
86
+ const toPage = (pages: string[][], scroll?: string) => {
87
+ const index = scroll ? Number(scroll) : 0
88
+ return {
89
+ ids: pages[index],
90
+ scroll: index + 1 < pages.length ? String(index + 1) : null,
91
+ }
92
+ }
93
+
94
+ // The single widening cast below is intentional: the object literal is still
95
+ // structurally checked against the product type, so a typo in a fixture key
96
+ // fails the typecheck instead of being accepted silently (unlike
97
+ // `as unknown as ...`).
98
+ const toProduct = (...breadcrumb: string[]) =>
99
+ ({
100
+ breadcrumbList: {
101
+ itemListElement: breadcrumb.map((item, index) => ({
102
+ item,
103
+ name: item,
104
+ position: index + 1,
105
+ })),
106
+ },
107
+ }) as Parameters<ContentService['getPdpContent']>[0]
108
+
77
109
  function createFakeClientCP(pages: string[][]) {
78
110
  return {
79
111
  listEntries: vi.fn(async (_params: EntryPathParams, scroll?: string) => {
80
- const index = scroll ? Number(scroll) : 0
81
- return {
82
- entries: pages[index].map(toEntry),
83
- scroll: index + 1 < pages.length ? String(index + 1) : null,
84
- }
112
+ const page = toPage(pages, scroll)
113
+ return { entries: page.ids.map(toEntry), scroll: page.scroll }
85
114
  }),
115
+ listEntriesWithContent: vi.fn(
116
+ async (_params: EntryPathParams, scroll?: string) => {
117
+ const page = toPage(pages, scroll)
118
+ return {
119
+ entries: page.ids.map(toEntryWithContent),
120
+ scroll: page.scroll,
121
+ }
122
+ }
123
+ ),
86
124
  getEntry: vi.fn(async ({ entryId }: EntryPathParams) => ({
87
125
  ...entryData[entryId as string],
88
126
  createdBy: 'payload@example.com',
@@ -235,7 +273,7 @@ describe('ContentService', () => {
235
273
  expect(listedPage).not.toHaveProperty('storeId')
236
274
  })
237
275
 
238
- it('shares one list and entry fetch across concurrent PLPs with different slugs', async () => {
276
+ it('shares one listEntriesWithContent fetch across concurrent PLPs with different slugs', async () => {
239
277
  const { service, clientCP } = createServiceWithClient()
240
278
 
241
279
  const [collectionPage, otherPage, unknownPage] = await Promise.all([
@@ -244,8 +282,9 @@ describe('ContentService', () => {
244
282
  service.getPlpContent({ slug: 'nao-existe' }, []),
245
283
  ])
246
284
 
247
- expect(clientCP.listEntries).toHaveBeenCalledTimes(1)
248
- expect(clientCP.getEntry).toHaveBeenCalledTimes(3)
285
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
286
+ expect(clientCP.listEntries).not.toHaveBeenCalled()
287
+ expect(clientCP.getEntry).not.toHaveBeenCalled()
249
288
  expect(collectionPage.sections).toEqual([{ name: 'Collection' }])
250
289
  expect(otherPage.sections).toEqual([{ name: 'Other' }])
251
290
  expect(unknownPage.sections).toEqual([{ name: 'Generic' }])
@@ -257,8 +296,8 @@ describe('ContentService', () => {
257
296
  await service.getPlpContent({ slug: 'colecao' }, [])
258
297
  await service.getPlpContent({ slug: 'outra' }, [])
259
298
 
260
- expect(clientCP.listEntries).toHaveBeenCalledTimes(1)
261
- expect(clientCP.getEntry).toHaveBeenCalledTimes(3)
299
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
300
+ expect(clientCP.getEntry).not.toHaveBeenCalled()
262
301
  })
263
302
 
264
303
  it('still prefers a direct slug match over the cached list', async () => {
@@ -271,7 +310,7 @@ describe('ContentService', () => {
271
310
  const page = await service.getPlpContent({ slug: 'colecao' }, [])
272
311
 
273
312
  expect(page.sections).toEqual([{ name: 'Direct' }])
274
- expect(clientCP.listEntries).toHaveBeenCalledTimes(1)
313
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
275
314
  })
276
315
 
277
316
  it('consumes every scroll page once', async () => {
@@ -287,9 +326,9 @@ describe('ContentService', () => {
287
326
  ])
288
327
  const { data } = await service.getMultipleContent({ contentType: 'plp' })
289
328
 
290
- expect(clientCP.listEntries).toHaveBeenCalledTimes(3)
329
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(3)
291
330
  expect(
292
- clientCP.listEntries.mock.calls.map(([, scroll]) => scroll)
331
+ clientCP.listEntriesWithContent.mock.calls.map(([, scroll]) => scroll)
293
332
  ).toEqual([undefined, '1', '2'])
294
333
  expect(data.map((entry) => entry.id)).toEqual([
295
334
  'generic',
@@ -305,9 +344,11 @@ describe('ContentService', () => {
305
344
  await service.getMultipleContent({ contentType: 'pdp' })
306
345
  await service.getMultipleContent({ contentType: 'pdp' })
307
346
 
308
- expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
347
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(2)
309
348
  expect(
310
- clientCP.listEntries.mock.calls.map(([params]) => params.contentType)
349
+ clientCP.listEntriesWithContent.mock.calls.map(
350
+ ([params]) => params.contentType
351
+ )
311
352
  ).toEqual(['plp', 'pdp'])
312
353
  })
313
354
 
@@ -318,9 +359,11 @@ describe('ContentService', () => {
318
359
  await service.getMultipleContent({ contentType: 'plp', locale: 'en-US' })
319
360
  await service.getMultipleContent({ contentType: 'plp', locale: 'pt-BR' })
320
361
 
321
- expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
362
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(2)
322
363
  expect(
323
- clientCP.listEntries.mock.calls.map(([params]) => params.locale)
364
+ clientCP.listEntriesWithContent.mock.calls.map(
365
+ ([params]) => params.locale
366
+ )
324
367
  ).toEqual(['pt-BR', 'en-US'])
325
368
  })
326
369
 
@@ -340,22 +383,23 @@ describe('ContentService', () => {
340
383
  await service.getMultipleContent(previewParams)
341
384
  await service.getMultipleContent({ contentType: 'plp' })
342
385
 
343
- expect(clientCP.listEntries).toHaveBeenCalledTimes(3)
344
- expect(clientCP.getEntry).toHaveBeenCalledTimes(3)
386
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
387
+ expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
388
+ expect(clientCP.getEntry).not.toHaveBeenCalled()
345
389
  expect(clientCP.previewEntryById).toHaveBeenCalledTimes(6)
346
390
  })
347
391
 
348
392
  it('does not cache failures', async () => {
349
393
  const { service, clientCP } = createServiceWithClient()
350
394
  const error = new Error('Request failed with status code 500')
351
- clientCP.listEntries.mockRejectedValueOnce(error)
395
+ clientCP.listEntriesWithContent.mockRejectedValueOnce(error)
352
396
 
353
397
  await expect(
354
398
  service.getMultipleContent({ contentType: 'plp' })
355
399
  ).rejects.toBe(error)
356
400
  const { data } = await service.getMultipleContent({ contentType: 'plp' })
357
401
 
358
- expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
402
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(2)
359
403
  expect(data).toHaveLength(3)
360
404
  })
361
405
 
@@ -363,7 +407,7 @@ describe('ContentService', () => {
363
407
  vi.useFakeTimers()
364
408
  const { service, clientCP } = createServiceWithClient()
365
409
  let rejectFirst: (err: Error) => void = () => {}
366
- clientCP.listEntries.mockImplementationOnce(
410
+ clientCP.listEntriesWithContent.mockImplementationOnce(
367
411
  () =>
368
412
  new Promise((_, reject) => {
369
413
  rejectFirst = reject
@@ -379,7 +423,7 @@ describe('ContentService', () => {
379
423
  await firstResult
380
424
  await service.getMultipleContent({ contentType: 'plp' })
381
425
 
382
- expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
426
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(2)
383
427
  })
384
428
 
385
429
  it('fetches the list again after the TTL', async () => {
@@ -389,11 +433,103 @@ describe('ContentService', () => {
389
433
  await service.getMultipleContent({ contentType: 'plp' })
390
434
  vi.advanceTimersByTime(FIVE_MINUTES - 1)
391
435
  await service.getMultipleContent({ contentType: 'plp' })
392
- expect(clientCP.listEntries).toHaveBeenCalledTimes(1)
436
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
393
437
 
394
438
  vi.advanceTimersByTime(1)
395
439
  await service.getMultipleContent({ contentType: 'plp' })
396
- expect(clientCP.listEntries).toHaveBeenCalledTimes(2)
440
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(2)
441
+ })
442
+
443
+ it('merges the entry metadata with its inline content', async () => {
444
+ const { service, clientCP } = createServiceWithClient([['collection']])
445
+
446
+ const { data } = await service.getMultipleContent({ contentType: 'plp' })
447
+
448
+ expect(data).toEqual([
449
+ {
450
+ id: 'collection',
451
+ name: 'collection',
452
+ settings: { template: { value: '/colecao' } },
453
+ sections: [{ name: 'Collection' }],
454
+ },
455
+ ])
456
+ expect(clientCP.getEntry).not.toHaveBeenCalled()
457
+ })
458
+
459
+ it('warns without naming one list method when the pagination cap is hit', async () => {
460
+ // 26 pages exceed the MAX_PAGES cap of 25, so the service stops
461
+ // paginating and warns.
462
+ const pages = Array.from({ length: 26 }, (_, index) => [`entry-${index}`])
463
+ const { service, clientCP } = createServiceWithClient(pages)
464
+
465
+ const { data } = await service.getMultipleContent({
466
+ contentType: 'plp',
467
+ })
468
+
469
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(25)
470
+ expect(data).toHaveLength(25)
471
+ expect(console.warn).toHaveBeenCalledWith(
472
+ expect.stringContaining('pagination hit MAX_PAGES cap'),
473
+ expect.anything()
474
+ )
475
+ expect(console.warn).not.toHaveBeenCalledWith(
476
+ expect.stringContaining('listEntries pagination'),
477
+ expect.anything()
478
+ )
479
+ })
480
+
481
+ describe('PDP', () => {
482
+ it('skips the product slug lookup and matches a template from the list', async () => {
483
+ const { service, clientCP } = createServiceWithClient([
484
+ ['generic', 'camisetas'],
485
+ ])
486
+
487
+ const page = await service.getPdpContent(
488
+ toProduct('/camisetas/', '/camiseta-azul-123/p'),
489
+ { slug: 'camiseta-azul-123' }
490
+ )
491
+
492
+ expect(clientCP.getEntryBySlug).not.toHaveBeenCalled()
493
+ expect(clientCP.listEntriesWithContent).toHaveBeenCalledTimes(1)
494
+ expect(page.sections).toEqual([{ name: 'Camisetas PDP' }])
495
+ })
496
+
497
+ it('still fetches the previewed entry by id', async () => {
498
+ const { service, clientCP } = createServiceWithClient()
499
+
500
+ const page = await service.getPdpContent(
501
+ toProduct('/camiseta-azul-123/p'),
502
+ {
503
+ slug: 'camiseta-azul-123',
504
+ previewData: {
505
+ contentType: 'pdp',
506
+ documentId: 'collection',
507
+ versionId: 'version-1',
508
+ },
509
+ }
510
+ )
511
+
512
+ expect(clientCP.previewEntryById).toHaveBeenCalledWith(
513
+ expect.objectContaining({ entryId: 'collection', contentType: 'pdp' })
514
+ )
515
+ expect(clientCP.listEntriesWithContent).not.toHaveBeenCalled()
516
+ expect(page.sections).toEqual([{ name: 'Collection' }])
517
+ })
518
+
519
+ it('still fetches an explicit documentId directly', async () => {
520
+ const { service, clientCP } = createServiceWithClient()
521
+
522
+ const page = await service.getPdpContent(
523
+ toProduct('/camiseta-azul-123/p'),
524
+ { slug: 'camiseta-azul-123', documentId: 'other' }
525
+ )
526
+
527
+ expect(clientCP.getEntry).toHaveBeenCalledWith(
528
+ expect.objectContaining({ entryId: 'other', contentType: 'pdp' })
529
+ )
530
+ expect(clientCP.listEntriesWithContent).not.toHaveBeenCalled()
531
+ expect(page.sections).toEqual([{ name: 'Other' }])
532
+ })
397
533
  })
398
534
  })
399
535
 
@@ -0,0 +1,89 @@
1
+ import { stringifyCacheControl } from '@faststore/api'
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
3
+
4
+ import { execute } from '../../src/server'
5
+
6
+ const probeResolvers = vi.hoisted(() => ({
7
+ Query: {
8
+ probeAuth: vi.fn(() => 'auth-ok'),
9
+ probeCache: vi.fn(() => 'cache-ok'),
10
+ },
11
+ }))
12
+
13
+ const fetchMock = vi.hoisted(() => vi.fn())
14
+
15
+ vi.mock('../../src/customizations/src/graphql/thirdParty/resolvers', () => ({
16
+ default: probeResolvers,
17
+ }))
18
+
19
+ vi.mock('isomorphic-unfetch', () => ({
20
+ default: (...args: unknown[]) => fetchMock(...args),
21
+ }))
22
+
23
+ vi.mock('@graphql-tools/load-files', () => ({
24
+ loadFilesSync: () => [
25
+ /* GraphQL */ `
26
+ extend type Query {
27
+ probeAuth: String @auth
28
+ probeCache: String
29
+ @cacheControl(scope: "private", sMaxAge: 7, staleWhileRevalidate: 11)
30
+ }
31
+ `,
32
+ ],
33
+ }))
34
+
35
+ const operation = (operationName: string, query: string) => ({
36
+ variables: {},
37
+ query,
38
+ operation: {
39
+ __meta__: { operationName, operationHash: operationName },
40
+ },
41
+ })
42
+
43
+ describe('store directives through the core server', () => {
44
+ beforeEach(() => {
45
+ probeResolvers.Query.probeAuth.mockClear()
46
+ probeResolvers.Query.probeCache.mockClear()
47
+ fetchMock.mockReset()
48
+ fetchMock.mockResolvedValue({
49
+ ok: false,
50
+ status: 401,
51
+ statusText: 'Unauthorized',
52
+ headers: new Headers(),
53
+ text: async () => 'unauthorized',
54
+ json: async () => ({}),
55
+ })
56
+ })
57
+
58
+ it('applies @cacheControl from a store field to the response extensions', async () => {
59
+ const result = await execute(
60
+ operation('ProbeCacheQuery', 'query ProbeCacheQuery { probeCache }')
61
+ )
62
+
63
+ expect(result.errors).toBeUndefined()
64
+ expect(result.data).toEqual({ probeCache: 'cache-ok' })
65
+ expect(result.extensions.cacheControl).toEqual({
66
+ scope: 'private',
67
+ sMaxAge: 7,
68
+ staleWhileRevalidate: 11,
69
+ })
70
+ expect(
71
+ stringifyCacheControl(result.extensions.cacheControl ?? {}, false)
72
+ ).toBe('private, s-maxage=7, stale-while-revalidate=11')
73
+ })
74
+
75
+ it('applies @auth from a store field and validates the session once', async () => {
76
+ const result = await execute(
77
+ operation('ProbeAuthQuery', 'query ProbeAuthQuery { probeAuth }')
78
+ )
79
+
80
+ expect(result.data).toEqual({ probeAuth: null })
81
+ expect(result.errors?.length).toBeGreaterThan(0)
82
+ expect(probeResolvers.Query.probeAuth).not.toHaveBeenCalled()
83
+ expect(
84
+ fetchMock.mock.calls.filter(([url]) =>
85
+ String(url).includes('/api/vtexid/credential/validate')
86
+ )
87
+ ).toHaveLength(1)
88
+ })
89
+ })
@@ -0,0 +1,73 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import defaultConfig from '../../discovery.config.default'
3
+ import { mergeDiscoveryConfig } from '../../src/utils/mergeDiscoveryConfig'
4
+
5
+ describe('mergeDiscoveryConfig', () => {
6
+ describe('api.subDomainPrefix', () => {
7
+ it('keeps the default when the store does not set it', () => {
8
+ const config = mergeDiscoveryConfig(defaultConfig, {
9
+ api: { storeId: 'store' },
10
+ })
11
+
12
+ expect(config.api.subDomainPrefix).toEqual(['www'])
13
+ })
14
+
15
+ it('lets the store clear the prefixes with an empty array', () => {
16
+ const config = mergeDiscoveryConfig(defaultConfig, {
17
+ api: { subDomainPrefix: [] },
18
+ })
19
+
20
+ expect(config.api.subDomainPrefix).toEqual([])
21
+ })
22
+
23
+ it('keeps appending non-empty arrays to the default', () => {
24
+ const config = mergeDiscoveryConfig(defaultConfig, {
25
+ api: { subDomainPrefix: ['shop'] },
26
+ })
27
+
28
+ expect(config.api.subDomainPrefix).toEqual(['www', 'shop'])
29
+ })
30
+
31
+ it('applies to every merge in the chain', () => {
32
+ const storeConfig = mergeDiscoveryConfig(defaultConfig, {
33
+ api: { subDomainPrefix: ['shop'] },
34
+ })
35
+ const config = mergeDiscoveryConfig(storeConfig, {
36
+ api: { subDomainPrefix: [] },
37
+ })
38
+
39
+ expect(config.api.subDomainPrefix).toEqual([])
40
+ })
41
+ })
42
+
43
+ it('keeps merging the other api fields', () => {
44
+ const config = mergeDiscoveryConfig(defaultConfig, {
45
+ api: { storeId: 'store', subDomainPrefix: [] },
46
+ })
47
+
48
+ expect(config.api.storeId).toBe('store')
49
+ expect(config.api.environment).toBe(defaultConfig.api.environment)
50
+ })
51
+
52
+ it('keeps concatenating the other arrays', () => {
53
+ const config = mergeDiscoveryConfig({ list: ['a'] }, { list: [] })
54
+
55
+ expect(config.list).toEqual(['a'])
56
+ })
57
+
58
+ it('only clears subDomainPrefix under api', () => {
59
+ const config = mergeDiscoveryConfig(
60
+ { api: { subDomainPrefix: ['www'] }, other: { subDomainPrefix: ['a'] } },
61
+ { api: { subDomainPrefix: [] }, other: { subDomainPrefix: [] } }
62
+ )
63
+
64
+ expect(config.api.subDomainPrefix).toEqual([])
65
+ expect(config.other.subDomainPrefix).toEqual(['a'])
66
+ })
67
+
68
+ it('does not mutate the default config', () => {
69
+ mergeDiscoveryConfig(defaultConfig, { api: { subDomainPrefix: [] } })
70
+
71
+ expect(defaultConfig.api.subDomainPrefix).toEqual(['www'])
72
+ })
73
+ })
@@ -0,0 +1,49 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { getSubDomainPrefixWarning } from '../../src/utils/subDomainPrefixWarning'
3
+
4
+ describe('getSubDomainPrefixWarning', () => {
5
+ const store = (
6
+ subDomainPrefix: string[] | undefined,
7
+ secureSubdomain: string,
8
+ storeUrl = 'https://www.store.com'
9
+ ) => ({ storeUrl, secureSubdomain, api: { subDomainPrefix } })
10
+
11
+ it('warns when the prefixes are cleared and checkout is on another host', () => {
12
+ expect(
13
+ getSubDomainPrefixWarning(store([], 'https://secure.store.com'))
14
+ ).toContain('secure.store.com')
15
+ })
16
+
17
+ it('does not warn when checkout is on the storefront host', () => {
18
+ expect(
19
+ getSubDomainPrefixWarning(store([], 'https://www.store.com'))
20
+ ).toBeUndefined()
21
+ })
22
+
23
+ it('does not warn when the store keeps any prefix', () => {
24
+ expect(
25
+ getSubDomainPrefixWarning(store(['www'], 'https://secure.store.com'))
26
+ ).toBeUndefined()
27
+ expect(
28
+ getSubDomainPrefixWarning(store(undefined, 'https://secure.store.com'))
29
+ ).toBeUndefined()
30
+ })
31
+
32
+ it('does not warn when secureSubdomain is not set', () => {
33
+ expect(getSubDomainPrefixWarning(store([], ''))).toBeUndefined()
34
+ })
35
+
36
+ it('warns when secureSubdomain is not a valid URL', () => {
37
+ expect(getSubDomainPrefixWarning(store([], 'secure.store.com'))).toContain(
38
+ 'secureSubdomain could not be parsed'
39
+ )
40
+ })
41
+
42
+ it('warns when storeUrl is not a valid URL', () => {
43
+ expect(
44
+ getSubDomainPrefixWarning(
45
+ store([], 'https://secure.store.com', 'www.store.com')
46
+ )
47
+ ).toContain('storeUrl could not be parsed')
48
+ })
49
+ })