@sitecore-feaas/clientside 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/build/dom/stylesheet.js +11 -12
  2. package/build/dom/stylesheet.js.map +1 -1
  3. package/build/fetch.js +25 -1
  4. package/build/fetch.js.map +1 -1
  5. package/build/utils/settings.js +1 -1
  6. package/build/utils/settings.js.map +1 -1
  7. package/dist/browser/headless.cjs +4 -4
  8. package/dist/browser/headless.cjs.map +3 -3
  9. package/dist/browser/headless.esm.js +3 -3
  10. package/dist/browser/headless.esm.js.map +1 -1
  11. package/dist/browser/index.cjs +4 -4
  12. package/dist/browser/index.cjs.map +3 -3
  13. package/dist/browser/index.esm.js +4 -4
  14. package/dist/browser/index.esm.js.map +1 -1
  15. package/dist/browser/react.cjs +4 -4
  16. package/dist/browser/react.cjs.map +3 -3
  17. package/dist/browser/react.esm.js +3 -3
  18. package/dist/browser/react.esm.js.map +1 -1
  19. package/dist/node/headless.cjs +4 -4
  20. package/dist/node/headless.cjs.map +3 -3
  21. package/dist/node/headless.esm.js +3 -3
  22. package/dist/node/headless.esm.js.map +3 -3
  23. package/dist/node/index.cjs +4 -4
  24. package/dist/node/index.cjs.map +3 -3
  25. package/dist/node/index.esm.js +4 -4
  26. package/dist/node/index.esm.js.map +3 -3
  27. package/dist/node/react.cjs +4 -4
  28. package/dist/node/react.cjs.map +3 -3
  29. package/dist/node/react.esm.js +3 -3
  30. package/dist/node/react.esm.js.map +3 -3
  31. package/headless.cjs +4 -4
  32. package/headless.cjs.map +3 -3
  33. package/headless.js +4 -4
  34. package/headless.js.map +3 -3
  35. package/package.json +1 -1
  36. package/react.cjs +4 -4
  37. package/react.cjs.map +3 -3
  38. package/react.js +4 -4
  39. package/react.js.map +3 -3
  40. package/src/dom/stylesheet.ts +17 -15
  41. package/src/fetch.ts +25 -1
  42. package/src/utils/settings.ts +1 -1
  43. package/test/FEAASComponent.test.tsx +117 -20
  44. package/test/FEAASStylesheet.test.tsx +13 -11
  45. package/test/datasettings.test.ts +92 -0
  46. package/types/dom/stylesheet.d.ts +1 -1
  47. package/types/dom/stylesheet.d.ts.map +1 -1
  48. package/types/fetch.d.ts +24 -0
  49. package/types/fetch.d.ts.map +1 -1
@@ -17,23 +17,25 @@ export function renderStylesheetPromise(props: FEAASCDNStylesheetProps, styleshe
17
17
  }).then(() => stylesheet)
18
18
  }
19
19
 
20
+ const validatedStylesheets = new WeakSet<HTMLStyleElement | HTMLLinkElement>()
20
21
  export function loadStylesheet(props: FEAASCDNStylesheetProps, callback?: ValidatableStylesheetCallback) {
21
- var foundStylesheet = findStylesheet(props) as HTMLStyleElement
22
- if (!foundStylesheet) {
23
- var createdStylesheet = createStylesheet(props)
24
- } else {
25
- if (foundStylesheet.tagName == 'LINK') {
26
- callback(null, 'initial')
27
- return Promise.resolve(foundStylesheet)
28
- }
22
+ var foundStylesheet: HTMLStyleElement | HTMLLinkElement
23
+ var writableStylesheet: HTMLStyleElement
24
+
25
+ if (foundStylesheet && validatedStylesheets.has(foundStylesheet)) {
26
+ return Promise.resolve(foundStylesheet)
29
27
  }
30
28
 
31
29
  return fetchAndRevalidateStylesheet(props, (cssText, phase) => {
32
- if (createdStylesheet) {
33
- createdStylesheet.textContent = cssText
30
+ foundStylesheet ||= findStylesheet(props)
31
+ // dont need to write stylesheet for cached state if we already found a stylesheet
32
+ if (!(phase == 'initial' && foundStylesheet)) {
33
+ writableStylesheet ||=
34
+ !foundStylesheet || foundStylesheet.tagName == 'LINK' ? createStylesheet(props) : foundStylesheet
35
+ writableStylesheet.textContent = cssText
34
36
  }
35
37
  callback?.(cssText, phase)
36
- }).then(() => foundStylesheet || createdStylesheet)
38
+ }).then(() => foundStylesheet || writableStylesheet)
37
39
  }
38
40
 
39
41
  export function loadStylesheetAllowStale(props: FEAASCDNStylesheetProps) {
@@ -43,10 +45,10 @@ export function loadStylesheetAllowStale(props: FEAASCDNStylesheetProps) {
43
45
  }
44
46
 
45
47
  export function findStylesheet(props: FEAASCDNStylesheetProps) {
46
- return (
47
- document.head.querySelector(`style[data-href="${getStylesheetURL(props)}"]`) ||
48
- document.querySelector(`link[rel="stylesheet"][href="${getStylesheetURL(props)}"]`)
49
- )
48
+ return (document.head.querySelector(`style[data-href="${getStylesheetURL(props)}"]`) ||
49
+ document.querySelector(`link[rel="stylesheet"][href="${getStylesheetURL(props)}"]`)) as
50
+ | HTMLStyleElement
51
+ | HTMLLinkElement
50
52
  }
51
53
 
52
54
  export function createStylesheet(props: FEAASCDNStylesheetProps) {
package/src/fetch.ts CHANGED
@@ -68,6 +68,22 @@ export function getFetchCache(url: Parameters<typeof fetch>[0], dontCreate = fal
68
68
 
69
69
  export class InvalidResponse extends Error {}
70
70
 
71
+ /**
72
+ * Executes a fetch request optionally validating and handling the response. Using callback function it's possible to
73
+ * observe successful response twice: Cached version first, and up-to-date later.
74
+ *
75
+ * @param {Object} request - An object containing request parameters.
76
+ * @param {string} request.url - The URL to fetch.
77
+ * @param {Object} request.options - Fetch request options.
78
+ * @param {Function} [request.validator] - Function to validate the response. Should return `false` if
79
+ * validation fails.
80
+ * @param {Function} [request.callback] - Function to execute after fetching. Receives the response,
81
+ * phase, and cache status.
82
+ * @param {Object} [request.cache] - Cache object to store or retrieve cached data.
83
+ * @param {ValidatableRequestPhase} [phase='initial'] - The phase of the request, defaults to 'initial'.
84
+ * @returns {Promise<Object>} A promise that resolves to an object containing request details and the response.
85
+ * @throws {Error} Throws an error if the fetch fails or if the response is not valid according to the validator.
86
+ */
71
87
  export async function fetchWithCacheAwareness(
72
88
  { url, options, validator, callback, cache }: ValidatableRequest,
73
89
  phase: ValidatableRequestPhase = 'initial'
@@ -107,6 +123,14 @@ export async function fetchWithCacheAwareness(
107
123
  }
108
124
  }
109
125
 
126
+ /**
127
+ * Validates cache of previousl fetch If the resource is cached and there is a newer version available, it will be
128
+ * re-fetched.
129
+ *
130
+ * @param request - The request object containing the URL, cache information, options, validator, and response of
131
+ * initial request.
132
+ * @returns A promise that resolves to the request object.
133
+ */
110
134
  export async function fetchToValidateCache(
111
135
  request: ValidatableRequest & Required<Pick<ValidatableRequest, 'response'>>
112
136
  ) {
@@ -129,7 +153,7 @@ export async function fetchToValidateCache(
129
153
 
130
154
  // there's a newer version of the file that we may fetch
131
155
  if (head.headers.get('last-modified') != response.headers.get('last-modified')) {
132
- // otherwise the new resource has to be re-fetched
156
+ // the new resource has to be re-fetched
133
157
  return fetchBypassingCache(request)
134
158
  }
135
159
  }
@@ -52,7 +52,7 @@ export function clean(settings: any) {
52
52
  * @returns {boolean} - True if the data is of type DataSettings, false otherwise.
53
53
  */
54
54
  export const isDataSettings = (data: any): data is DataSettings => {
55
- if (typeof data.url != 'string') return false
55
+ if (!data || typeof data.url != 'string') return false
56
56
 
57
57
  for (var property in data) {
58
58
  if (
@@ -25,7 +25,7 @@ describe('Components', () => {
25
25
  const spy = vi.spyOn(global, 'fetch')
26
26
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
27
27
  if (url.match('CDN/components/L/C/V/R')) {
28
- return new Response('TODAY', {
28
+ return new Response('FRESH', {
29
29
  headers: {
30
30
  date: now.toUTCString(),
31
31
  'last-modified': earlier.toUTCString()
@@ -43,7 +43,7 @@ describe('Components', () => {
43
43
  await expect(component.whenRendered).resolves.toEqual(component)
44
44
  expect(spy).toHaveBeenCalledTimes(1)
45
45
 
46
- expect(component.innerHTML).toContain('TODAY')
46
+ expect(component.innerHTML).toContain('FRESH')
47
47
  })
48
48
 
49
49
  describe('fetch control', () => {
@@ -116,7 +116,7 @@ describe('Components', () => {
116
116
  const spy = vi.spyOn(global, 'fetch')
117
117
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
118
118
  if (url.match('CDN/components/L/C/V/R')) {
119
- return new Response('TODAY', {
119
+ return new Response('FRESH', {
120
120
  headers: {
121
121
  date: now.toUTCString(),
122
122
  'last-modified': earlier.toUTCString()
@@ -139,7 +139,7 @@ describe('Components', () => {
139
139
 
140
140
  await expect(component.whenRendered).resolves.toEqual(component)
141
141
  expect(spy).toHaveBeenCalledTimes(2)
142
- expect(component.innerHTML).toBe('TODAY')
142
+ expect(component.innerHTML).toBe('FRESH')
143
143
  expect(document.head.querySelectorAll('style').length).toEqual(1)
144
144
  })
145
145
  it('should make data/css requests when fetch="stylesheet data"', async () => {
@@ -208,7 +208,7 @@ describe('Components', () => {
208
208
  const spy = vi.spyOn(global, 'fetch')
209
209
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
210
210
  if (url.match('http://a/components/b/c/d/1.html')) {
211
- return new Response('TODAY', {
211
+ return new Response('FRESH', {
212
212
  headers: {
213
213
  date: now.toUTCString(),
214
214
  'last-modified': earlier.toUTCString()
@@ -226,7 +226,7 @@ describe('Components', () => {
226
226
  expect(spy).toHaveBeenCalledTimes(1)
227
227
 
228
228
  expect(component.outerHTML).toBe(
229
- `<feaas-component fetch="template data" src="http://a/components/b/c/d/1.html" cdn="http://a" library="b" component="c" version="d" revision="1" class="-feaas">TODAY</feaas-component>`
229
+ `<feaas-component fetch="template data" src="http://a/components/b/c/d/1.html" cdn="http://a" library="b" component="c" version="d" revision="1" class="-feaas">FRESH</feaas-component>`
230
230
  )
231
231
  })
232
232
 
@@ -234,7 +234,7 @@ describe('Components', () => {
234
234
  const spy = vi.spyOn(global, 'fetch')
235
235
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
236
236
  if (url.match('http://a/components/b/c/d/1.html')) {
237
- return new Response('TODAY', {
237
+ return new Response('FRESH', {
238
238
  headers: {
239
239
  date: now.toUTCString(),
240
240
  'last-modified': earlier.toUTCString()
@@ -260,16 +260,63 @@ describe('Components', () => {
260
260
  expect(document.head.querySelectorAll('style')[1].getAttribute('data-href')).toBe('http://a/styles/b/staged.css')
261
261
  })
262
262
 
263
- it('should render component if stylesheet is statically embedded as link', async () => {
263
+ it('should validate stylesheet when included as link before rendering component', async () => {
264
264
  const spy = vi.spyOn(global, 'fetch')
265
265
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
266
266
  if (url.match('http://a/components/b/c/d/1.html')) {
267
- return new Response('TODAY', {
267
+ return new Response('FRESH', {
268
268
  headers: {
269
269
  date: now.toUTCString(),
270
270
  'last-modified': earlier.toUTCString()
271
271
  }
272
272
  })
273
+ } else if (url.match('.css')) {
274
+ return new Response('FRESH', {
275
+ headers: {
276
+ date: /*String(options?.method).toLowerCase() == 'head' ? */ now.toUTCString(),
277
+ 'last-modified': earlier.toUTCString()
278
+ }
279
+ })
280
+ }
281
+ })
282
+
283
+ document.body.innerHTML =
284
+ '<feaas-component src="http://a/components/b/c/d/1.html"></feaas-component><link rel="stylesheet" href="http://a/styles/b/published.css" />'
285
+
286
+ const component = document.body.firstElementChild as FEAASComponent
287
+ await expect(component.whenRendered).resolves.toEqual(component)
288
+ expect(spy).toHaveBeenCalledTimes(2)
289
+ expect(document.head.querySelectorAll('style').length).toBe(0)
290
+ })
291
+
292
+ it('should validate and re-write stylesheet when included as link before rendering component', async () => {
293
+ const spy = vi.spyOn(global, 'fetch')
294
+ spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
295
+ if (url.match('http://a/components/b/c/d/1.html')) {
296
+ return new Response('FRESH', {
297
+ headers: {
298
+ date: now.toUTCString(),
299
+ 'last-modified': earlier.toUTCString()
300
+ }
301
+ })
302
+ } else if (url.match('.css')) {
303
+ if (!options?.cache) {
304
+ // respond with cached css
305
+ return new Response('CACHED', {
306
+ headers: {
307
+ date: earliest.toUTCString(),
308
+ 'last-modified': earliest.toUTCString()
309
+ }
310
+ })
311
+ } else {
312
+ // respond with up to date
313
+ return new Response('CACHED', {
314
+ headers: {
315
+ date: now.toUTCString(),
316
+ 'last-modified': earliest.toUTCString()
317
+ }
318
+ })
319
+ }
273
320
  }
274
321
  })
275
322
 
@@ -278,15 +325,65 @@ describe('Components', () => {
278
325
 
279
326
  const component = document.body.firstElementChild as FEAASComponent
280
327
  await expect(component.whenRendered).resolves.toEqual(component)
328
+ expect(spy).toHaveBeenCalledTimes(3)
329
+ // render with stale stylesheet
330
+ expect(document.head.querySelectorAll('style').length).toBe(0)
331
+ await new Promise((r) => setTimeout(r, 50))
332
+ expect(spy).toHaveBeenCalledTimes(3)
281
333
  expect(document.head.querySelectorAll('style').length).toBe(0)
282
334
  })
283
335
 
336
+ it('should validate and re-write stylesheet when included as link before rendering component', async () => {
337
+ const spy = vi.spyOn(global, 'fetch')
338
+ spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
339
+ if (url.match('http://a/components/b/c/d/1.html')) {
340
+ return new Response('FRESH', {
341
+ headers: {
342
+ date: now.toUTCString(),
343
+ 'last-modified': earlier.toUTCString()
344
+ }
345
+ })
346
+ } else if (url.match('.css')) {
347
+ if (!options?.cache) {
348
+ // respond with cached css
349
+ return new Response('CACHED', {
350
+ headers: {
351
+ date: earliest.toUTCString(),
352
+ 'last-modified': earliest.toUTCString()
353
+ }
354
+ })
355
+ } else {
356
+ if (String(options?.method).toLowerCase() == 'head') await new Promise((r) => setTimeout(r, 50))
357
+ // respond with up to date
358
+ return new Response('FRESH', {
359
+ headers: {
360
+ date: now.toUTCString(),
361
+ 'last-modified': now.toUTCString()
362
+ }
363
+ })
364
+ }
365
+ }
366
+ })
367
+
368
+ document.body.innerHTML =
369
+ '<feaas-component src="http://a/components/b/c/d/1.html"></feaas-component><link rel="stylesheet" href="http://a/styles/b/published.css" />'
370
+
371
+ const component = document.body.firstElementChild as FEAASComponent
372
+ await expect(component.whenRendered).resolves.toEqual(component)
373
+ expect(spy).toHaveBeenCalledTimes(3)
374
+ // render with stale stylesheet
375
+ expect(document.head.querySelectorAll('style').length).toBe(0)
376
+ await new Promise((r) => setTimeout(r, 100))
377
+ expect(spy).toHaveBeenCalledTimes(4)
378
+ expect(document.head.querySelectorAll('style').length).toBe(1)
379
+ })
380
+
284
381
  it('should revalidate cached component response', async () => {
285
382
  const spy = vi.spyOn(global, 'fetch')
286
383
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
287
384
  if (url.match('CDN/components/L/C/V/R') && options.method != 'HEAD') {
288
385
  // 1. Here's cached component
289
- return new Response('TODAY', {
386
+ return new Response('CACHED', {
290
387
  headers: {
291
388
  date: earlier.toUTCString(),
292
389
  'last-modified': earlier.toUTCString()
@@ -311,7 +408,7 @@ describe('Components', () => {
311
408
  await expect(component.whenRendered).resolves.toEqual(component)
312
409
  expect(spy).toHaveBeenCalledTimes(2)
313
410
 
314
- expect(component.innerHTML).toContain('TODAY')
411
+ expect(component.innerHTML).toContain('CACHED')
315
412
  })
316
413
 
317
414
  it('should reload component while using stale cache', async () => {
@@ -335,7 +432,7 @@ describe('Components', () => {
335
432
  })
336
433
  } else {
337
434
  // Up to date version
338
- return new Response('TODAY', {
435
+ return new Response('FRESH', {
339
436
  headers: {
340
437
  date: now.toUTCString(),
341
438
  'last-modified': earlier.toUTCString()
@@ -356,7 +453,7 @@ describe('Components', () => {
356
453
  // whenLoaded only fires when ensures that up-to-date version is loaded
357
454
  await expect(component.whenLoaded).resolves.toBeTruthy()
358
455
  expect(spy).toHaveBeenCalledTimes(3)
359
- expect(component.innerHTML).toContain('TODAY')
456
+ expect(component.innerHTML).toContain('FRESH')
360
457
  })
361
458
 
362
459
  it('should re-fetch component when attributes change', async () => {
@@ -418,7 +515,7 @@ describe('Components', () => {
418
515
  })
419
516
  } else {
420
517
  await new Promise((resolve) => setTimeout(resolve, 200))
421
- return new Response('TODAY {}', {
518
+ return new Response('FRESH {}', {
422
519
  headers: {
423
520
  date: now.toUTCString(),
424
521
  'last-modified': earlier.toUTCString()
@@ -445,7 +542,7 @@ describe('Components', () => {
445
542
  } else {
446
543
  // Latest
447
544
  await new Promise((resolve) => setTimeout(resolve, 100))
448
- return new Response('TODAY', {
545
+ return new Response('FRESH', {
449
546
  headers: {
450
547
  date: now.toUTCString(),
451
548
  'last-modified': earlier.toUTCString()
@@ -459,20 +556,20 @@ describe('Components', () => {
459
556
  const component = document.body.firstElementChild as FEAASComponent
460
557
  expect(document.head.querySelector('style')).toBeNull()
461
558
  await new Promise((resolve) => setTimeout(resolve, 50))
462
- const stylesheet = document.head.querySelector('style') as HTMLStyleElement
463
- expect(stylesheet.innerHTML).toEqual('')
559
+ expect(document.head.querySelector('style')).toBeNull()
464
560
  expect(component.innerHTML).toEqual('')
465
561
  // Component will rendered with stale cached stylesheet
466
562
  await expect(component.whenRendered).resolves.toEqual(component)
563
+ const stylesheet = document.head.querySelector('style') as HTMLStyleElement
467
564
  expect(stylesheet.innerHTML).toEqual('YESTERDAY {}')
468
565
  expect(component.innerHTML).toEqual('YESTERDAY')
469
566
  // Component will update itself with stale cached stylesheet
470
- await expect(component.whenLoaded).resolves.toEqual('TODAY')
567
+ await expect(component.whenLoaded).resolves.toEqual('FRESH')
471
568
  expect(stylesheet.innerHTML).toEqual('YESTERDAY {}')
472
- expect(component.innerHTML).toEqual('TODAY')
569
+ expect(component.innerHTML).toEqual('FRESH')
473
570
  await new Promise((resolve) => setTimeout(resolve, 200))
474
571
  // Stylesheet will update later
475
- expect(stylesheet.innerHTML).toEqual('TODAY {}')
572
+ expect(stylesheet.innerHTML).toEqual('FRESH {}')
476
573
  })
477
574
 
478
575
  it('render without data', () => {
@@ -29,7 +29,7 @@ describe('Stylesheet', () => {
29
29
  it('should load stylesheet (cold cache)', async () => {
30
30
  const spy = vi.spyOn(global, 'fetch')
31
31
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
32
- return new Response('TODAY {}', {
32
+ return new Response('FRESH {}', {
33
33
  headers: {
34
34
  date: now.toUTCString(),
35
35
  'last-modified': earlier.toUTCString()
@@ -44,13 +44,13 @@ describe('Stylesheet', () => {
44
44
  await expect(stylesheet.whenRendered).resolves.toEqual(stylesheet)
45
45
  expect(spy).toHaveBeenCalledTimes(1)
46
46
 
47
- expect(document.head.querySelector('style').textContent).toContain('TODAY')
47
+ expect(document.head.querySelector('style').textContent).toContain('FRESH')
48
48
  })
49
49
  it('should load stylesheet with minimum parameters(cold cache)', async () => {
50
50
  const spy = vi.spyOn(global, 'fetch')
51
51
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
52
52
  if (url.match(DEFAULT_CDN_URL + '/styles/L/published.css'))
53
- return new Response('TODAY {}', {
53
+ return new Response('FRESH {}', {
54
54
  headers: {
55
55
  date: now.toUTCString(),
56
56
  'last-modified': earlier.toUTCString()
@@ -65,14 +65,14 @@ describe('Stylesheet', () => {
65
65
  await expect(stylesheet.whenRendered).resolves.toEqual(stylesheet)
66
66
  expect(spy).toHaveBeenCalledTimes(1)
67
67
 
68
- expect(document.head.querySelector('style').textContent).toContain('TODAY')
68
+ expect(document.head.querySelector('style').textContent).toContain('FRESH')
69
69
  })
70
70
 
71
71
  it('should invalidate stylesheet cache', async () => {
72
72
  const spy = vi.spyOn(global, 'fetch')
73
73
  spy.mockImplementation(async (url: string, options: Parameters<typeof fetch>[1] = {}) => {
74
74
  if (url.match('CDN/styles/L/published.css') && options?.method != 'HEAD') {
75
- return new Response('TODAY {}', {
75
+ return new Response('FRESH {}', {
76
76
  headers: {
77
77
  date: earlier.toUTCString(),
78
78
  'last-modified': earlier.toUTCString()
@@ -95,7 +95,7 @@ describe('Stylesheet', () => {
95
95
  await expect(stylesheet.whenRendered).resolves.toEqual(stylesheet)
96
96
  expect(spy).toHaveBeenCalledTimes(2)
97
97
 
98
- expect(document.head.querySelector('style').textContent).toContain('TODAY')
98
+ expect(document.head.querySelector('style').textContent).toContain('FRESH')
99
99
  })
100
100
  it('should update stylesheet while using stale cache', async () => {
101
101
  const spy = vi.spyOn(global, 'fetch')
@@ -117,7 +117,7 @@ describe('Stylesheet', () => {
117
117
  }
118
118
  })
119
119
  } else {
120
- return new Response('TODAY {}', {
120
+ return new Response('FRESH {}', {
121
121
  headers: {
122
122
  date: now.toUTCString(),
123
123
  'last-modified': earlier.toUTCString()
@@ -137,7 +137,7 @@ describe('Stylesheet', () => {
137
137
  // whenLoaded only fires when ensures that up-to-date version is loaded
138
138
  await expect(stylesheet.whenLoaded).resolves.toBeTruthy()
139
139
  expect(spy).toHaveBeenCalledTimes(3)
140
- expect(document.head.querySelector('style').textContent).toContain('TODAY {}')
140
+ expect(document.head.querySelector('style').textContent).toContain('FRESH {}')
141
141
  })
142
142
 
143
143
  it('should load stylesheet statically', async () => {
@@ -160,7 +160,7 @@ describe('Stylesheet', () => {
160
160
  }
161
161
  })
162
162
  } else {
163
- return new Response('TODAY {}', {
163
+ return new Response('FRESH {}', {
164
164
  headers: {
165
165
  date: now.toUTCString(),
166
166
  'last-modified': earlier.toUTCString()
@@ -175,7 +175,9 @@ describe('Stylesheet', () => {
175
175
  library: 'L',
176
176
  revision: 'published'
177
177
  }).then((r) => r.textContent)
178
- ).resolves.toEqual('TODAY {}')
179
- await expect(loadStylesheet(`http://CDN/L/published.css`).then((r) => r.textContent)).resolves.toEqual('TODAY {}')
178
+ ).resolves.toEqual('FRESH {}')
179
+ await expect(loadStylesheet(`http://CDN/L/published.css`).then((r) => r.textContent)).resolves.toEqual('FRESH {}')
180
180
  })
181
+
182
+ it('should ')
181
183
  })
@@ -118,6 +118,98 @@ describe('DataSettings', () => {
118
118
  ])
119
119
  })
120
120
  })
121
+ describe('.isDataSettings', () => {
122
+ it('should return true if data has all the required properties', () => {
123
+ const data = {
124
+ url: 'https://example.com',
125
+ method: 'GET',
126
+ headers: { 'Content-Type': 'application/json' }
127
+ }
128
+
129
+ expect(DataSettings.isDataSettings(data)).toBe(true)
130
+ })
131
+
132
+ it('should return false if data does not have the "url" property', () => {
133
+ const data = {
134
+ method: 'GET',
135
+ headers: { 'Content-Type': 'application/json' }
136
+ }
137
+
138
+ expect(DataSettings.isDataSettings(data)).toBe(false)
139
+ })
140
+
141
+ it('should return false if data has an additional property apart from the allowed ones', () => {
142
+ const data = {
143
+ url: 'https://example.com',
144
+ method: 'GET',
145
+ headers: { 'Content-Type': 'application/json' },
146
+ invalidProperty: 'invalid'
147
+ }
148
+
149
+ expect(DataSettings.isDataSettings(data)).toBe(false)
150
+ })
151
+
152
+ it('should return false if "jsonpath" property is not a string', () => {
153
+ const data = {
154
+ url: 'https://example.com',
155
+ method: 'GET',
156
+ headers: { 'Content-Type': 'application/json' },
157
+ jsonpath: { invalid: 'value' }
158
+ }
159
+
160
+ expect(DataSettings.isDataSettings(data)).toBe(false)
161
+ })
162
+ })
163
+ describe('.hasDataSettings', () => {
164
+ it('should return false if data is falsy', () => {
165
+ expect(DataSettings.hasDataSettings(null)).toBe(false)
166
+ expect(DataSettings.hasDataSettings(undefined)).toBe(false)
167
+ expect(DataSettings.hasDataSettings({ test: null })).toBe(false)
168
+ expect(DataSettings.hasDataSettings({ test: undefined })).toBe(false)
169
+ })
170
+ it('should return true for simple case', () => {
171
+ expect(DataSettings.hasDataSettings({ test: { url: 'a' } })).toBe(true)
172
+ expect(DataSettings.hasDataSettings({ url: 'a' })).toBe(true)
173
+ })
174
+
175
+ it('should return true if data has a valid DataSettings object', () => {
176
+ const data = {
177
+ url: 'https://example.com',
178
+ method: 'GET',
179
+ headers: { 'Content-Type': 'application/json' }
180
+ }
181
+
182
+ expect(DataSettings.hasDataSettings(data)).toBe(true)
183
+ expect(DataSettings.hasDataSettings({ a: data })).toBe(true)
184
+ })
185
+
186
+ it('should return true if any property in data is a valid DataSettings object', () => {
187
+ const data = {
188
+ url: 'https://example.com',
189
+ method: 'GET',
190
+ headers: { 'Content-Type': 'application/json' },
191
+ nestedData: {
192
+ url: 'https://example.com/nested',
193
+ method: 'POST',
194
+ headers: { 'Content-Type': 'application/json' }
195
+ }
196
+ }
197
+
198
+ expect(DataSettings.hasDataSettings(data)).toBe(true)
199
+ })
200
+
201
+ it('should return false if all properties in data are invalid', () => {
202
+ const data = {
203
+ property1: 'value1',
204
+ property2: { invalid: 'object' },
205
+ property3: false
206
+ }
207
+
208
+ expect(DataSettings.hasDataSettings(data)).toBe(false)
209
+ })
210
+
211
+ // Add more test cases to cover other scenarios
212
+ })
121
213
  describe('.fetch', () => {
122
214
  it('fetches when passed data object', async () => {
123
215
  const result = await DataSettings.fetch({ hello: 'world' })
@@ -3,6 +3,6 @@ export declare function renderStylesheet(props: FEAASCDNStylesheetProps, style?:
3
3
  export declare function renderStylesheetPromise(props: FEAASCDNStylesheetProps, stylesheet?: HTMLStyleElement): Promise<HTMLStyleElement>;
4
4
  export declare function loadStylesheet(props: FEAASCDNStylesheetProps, callback?: ValidatableStylesheetCallback): Promise<HTMLStyleElement>;
5
5
  export declare function loadStylesheetAllowStale(props: FEAASCDNStylesheetProps): Promise<unknown>;
6
- export declare function findStylesheet(props: FEAASCDNStylesheetProps): Element;
6
+ export declare function findStylesheet(props: FEAASCDNStylesheetProps): HTMLLinkElement | HTMLStyleElement;
7
7
  export declare function createStylesheet(props: FEAASCDNStylesheetProps): HTMLStyleElement;
8
8
  //# sourceMappingURL=stylesheet.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stylesheet.d.ts","sourceRoot":"","sources":["../../src/dom/stylesheet.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAElB,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,uBAAuB,EAAE,KAAK,CAAC,EAAE,gBAAgB,oBAGxF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,uBAAuB,EAAE,UAAU,CAAC,EAAE,gBAAgB,6BAKpG;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,uBAAuB,EAAE,QAAQ,CAAC,EAAE,6BAA6B,6BAiBtG;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,uBAAuB,oBAItE;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,uBAAuB,WAK5D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,uBAAuB,oBAM9D"}
1
+ {"version":3,"file":"stylesheet.d.ts","sourceRoot":"","sources":["../../src/dom/stylesheet.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAElB,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,uBAAuB,EAAE,KAAK,CAAC,EAAE,gBAAgB,oBAGxF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,uBAAuB,EAAE,UAAU,CAAC,EAAE,gBAAgB,6BAKpG;AAGD,wBAAgB,cAAc,CAAC,KAAK,EAAE,uBAAuB,EAAE,QAAQ,CAAC,EAAE,6BAA6B,6BAkBtG;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,uBAAuB,oBAItE;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,uBAAuB,sCAK5D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,uBAAuB,oBAM9D"}
package/types/fetch.d.ts CHANGED
@@ -36,6 +36,22 @@ export declare function fetchAndRevalidate(url: ValidatableRequest['url'], optio
36
36
  export declare function getFetchCache(url: Parameters<typeof fetch>[0], dontCreate?: boolean): FetchCacheRequest;
37
37
  export declare class InvalidResponse extends Error {
38
38
  }
39
+ /**
40
+ * Executes a fetch request optionally validating and handling the response. Using callback function it's possible to
41
+ * observe successful response twice: Cached version first, and up-to-date later.
42
+ *
43
+ * @param {Object} request - An object containing request parameters.
44
+ * @param {string} request.url - The URL to fetch.
45
+ * @param {Object} request.options - Fetch request options.
46
+ * @param {Function} [request.validator] - Function to validate the response. Should return `false` if
47
+ * validation fails.
48
+ * @param {Function} [request.callback] - Function to execute after fetching. Receives the response,
49
+ * phase, and cache status.
50
+ * @param {Object} [request.cache] - Cache object to store or retrieve cached data.
51
+ * @param {ValidatableRequestPhase} [phase='initial'] - The phase of the request, defaults to 'initial'.
52
+ * @returns {Promise<Object>} A promise that resolves to an object containing request details and the response.
53
+ * @throws {Error} Throws an error if the fetch fails or if the response is not valid according to the validator.
54
+ */
39
55
  export declare function fetchWithCacheAwareness({ url, options, validator, callback, cache }: ValidatableRequest, phase?: ValidatableRequestPhase): Promise<{
40
56
  url: RequestInfo | URL;
41
57
  options: RequestInit;
@@ -45,6 +61,14 @@ export declare function fetchWithCacheAwareness({ url, options, validator, callb
45
61
  callback: (response: Response, status: "initial" | "check" | "updated", isCached: boolean) => any;
46
62
  cache: FetchCache;
47
63
  }>;
64
+ /**
65
+ * Validates cache of previousl fetch If the resource is cached and there is a newer version available, it will be
66
+ * re-fetched.
67
+ *
68
+ * @param request - The request object containing the URL, cache information, options, validator, and response of
69
+ * initial request.
70
+ * @returns A promise that resolves to the request object.
71
+ */
48
72
  export declare function fetchToValidateCache(request: ValidatableRequest & Required<Pick<ValidatableRequest, 'response'>>): Promise<ValidatableRequest & Required<Pick<ValidatableRequest, "response">>>;
49
73
  export declare function fetchBypassingCache(request: ValidatableRequest): Promise<{
50
74
  url: RequestInfo | URL;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAEtD;;;;;;;;;;;GAWG;AACH,QAAA,MAAM,MAAM,0CAA2C,CAAA;AACvD,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;AAC7D,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAA;AAC1D,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;IAChC,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;IACrC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,KAAK,OAAO,CAAA;IAC9D,QAAQ,CAAC,EAAE,CAAC,QA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