@prezly/theme-kit-core 10.9.3 → 10.10.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.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.allStories = void 0;
6
+ exports.allStories = exports.DEFAULT_NEGATIVE_TTL = void 0;
7
7
  exports.createClient = createClient;
8
8
  exports.story = exports.stories = exports.galleries = void 0;
9
9
  var _sdk = require("@prezly/sdk");
@@ -16,6 +16,12 @@ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol"
16
16
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
17
17
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
18
18
  function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
19
+ /**
20
+ * Not-found results are cached only briefly: long enough to absorb repeated
21
+ * requests for the same missing slug, short enough that a story published
22
+ * without a cache version change appears within a minute.
23
+ */
24
+ var DEFAULT_NEGATIVE_TTL = exports.DEFAULT_NEGATIVE_TTL = 60;
19
25
  var stories;
20
26
  var allStories;
21
27
  var story;
@@ -290,6 +296,7 @@ function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
290
296
  }
291
297
  };
292
298
  if (cache) {
299
+ var _cache$negativeTtl;
293
300
  if (cache.scope !== undefined && !cache.scope) {
294
301
  throw new Error('Content cache scope must not be empty.');
295
302
  }
@@ -297,7 +304,7 @@ function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
297
304
  // A single schema prefix keeps old readers away from scoped envelopes.
298
305
  // Scope/version changes overwrite the same keys rather than adding namespaces.
299
306
  var storage = cache.scope === undefined ? cache.storage : cache.storage.namespace('scoped-v1');
300
- injectCache(client, storage.namespace(namespace), cache.latestVersion, cache.scope, namespace, UNCACHED_METHODS, telemetry);
307
+ injectCache(client, storage.namespace(namespace), cache.latestVersion, cache.scope, namespace, UNCACHED_METHODS, telemetry, (_cache$negativeTtl = cache.negativeTtl) !== null && _cache$negativeTtl !== void 0 ? _cache$negativeTtl : DEFAULT_NEGATIVE_TTL);
301
308
  } else if (telemetry) {
302
309
  var _loop2 = function _loop2() {
303
310
  if (UNCACHED_METHODS.includes(methodName)) return 1; // continue
@@ -320,9 +327,21 @@ function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
320
327
  }
321
328
  return client;
322
329
  }
330
+ function readScopedValue(stored, scope) {
331
+ if ((stored === null || stored === void 0 ? void 0 : stored.scope) !== scope) return undefined;
332
+ if (stored.value === null) {
333
+ var fresh = typeof stored.expires === 'number' && stored.expires > Date.now() / 1000;
334
+ return fresh ? null : undefined;
335
+ }
336
+ return stored.value;
337
+ }
323
338
  function injectCache(client, cache, latestVersion, scope, namespace) {
324
339
  var uncachedMethods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
325
340
  var telemetry = arguments.length > 6 ? arguments[6] : undefined;
341
+ var negativeTtl = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : DEFAULT_NEGATIVE_TTL;
342
+ if (!Number.isInteger(negativeTtl) || negativeTtl < 1) {
343
+ throw new RangeError('The negative cache TTL must be a positive integer number of seconds.');
344
+ }
326
345
  // An opaque SDK client does not expose its credentials/source. Callers without
327
346
  // an explicit scope keep request-local sharing; the Next.js adapter supplies one.
328
347
  var requests = scope === undefined ? new _RequestCoalescer.RequestCoalescer() : _RequestCoalescer.sharedContentRequests;
@@ -348,10 +367,12 @@ function injectCache(client, cache, latestVersion, scope, namespace) {
348
367
  var _stored = telemetry ? yield cache.get(cacheKey, latestVersion, source => {
349
368
  layer = source === 'memory' || source === 'redis' ? source : 'custom';
350
369
  }) : yield cache.get(cacheKey, latestVersion);
351
- var cached = scope === undefined ? _stored : (_stored === null || _stored === void 0 ? void 0 : _stored.scope) === scope ? _stored.value : undefined;
352
- // Preserve existing negative-cache semantics until null results
353
- // have a deliberately short TTL and correct error classification.
354
- if (cached) {
370
+ // Only an absent entry is a miss: a stored `false` or `0` is a valid
371
+ // result. A stored `null` (not found) is a hit only inside its own
372
+ // deadline, which lives in the scoped envelope. Unscoped clients
373
+ // cannot carry that deadline and keep treating null as a miss.
374
+ var cached = scope === undefined ? _stored === null ? undefined : _stored : readScopedValue(_stored, scope);
375
+ if (cached !== undefined) {
355
376
  (0, _telemetry.emit)(telemetry, {
356
377
  type: 'cache_hit',
357
378
  operation,
@@ -374,13 +395,27 @@ function injectCache(client, cache, latestVersion, scope, namespace) {
374
395
  operation
375
396
  });
376
397
  var value = yield observeOrigin(() => uncachedFn(...args), telemetry, operation);
377
- var stored = scope === undefined ? value : {
398
+ // `null` means the API answered 403/404/410 for this lookup. Keep it
399
+ // only briefly, with the deadline in the envelope and a matching
400
+ // layer hint. Errors (401, 429, 5xx, transport) throw above and are
401
+ // never stored. `undefined` results are not stored either.
402
+ var negative = value === null && scope !== undefined;
403
+ var stored = scope === undefined ? value : negative ? {
404
+ scope,
405
+ value,
406
+ // Fractional seconds: flooring would shorten a 1-second
407
+ // retention to almost nothing.
408
+ expires: Date.now() / 1000 + negativeTtl
409
+ } : {
378
410
  scope,
379
411
  value
380
412
  };
413
+ var options = negative ? {
414
+ ttl: negativeTtl
415
+ } : undefined;
381
416
  // Observe synchronous and asynchronous write failures without holding
382
417
  // up a successful response or leaving an unhandled rejection.
383
- var cacheWrite = Promise.resolve().then(() => cache.set(cacheKey, stored, latestVersion)).catch(() => {
418
+ var cacheWrite = value === undefined || value === null && scope === undefined ? undefined : Promise.resolve().then(() => cache.set(cacheKey, stored, latestVersion, options)).catch(() => {
384
419
  (0, _telemetry.emit)(telemetry, {
385
420
  type: 'cache_error',
386
421
  operation,
@@ -10,8 +10,20 @@ export interface Options {
10
10
  latestVersion: UnixTimestampInSeconds;
11
11
  /** Stable source/authorization identity. Enables cross-client request sharing. */
12
12
  scope?: string;
13
+ /**
14
+ * Retention in seconds for `null` results, i.e. content the API reported as
15
+ * not found, gone or forbidden. Defaults to `DEFAULT_NEGATIVE_TTL`.
16
+ * A cache version change still invalidates them immediately.
17
+ */
18
+ negativeTtl?: number;
13
19
  };
14
20
  }
21
+ /**
22
+ * Not-found results are cached only briefly: long enough to absorb repeated
23
+ * requests for the same missing slug, short enough that a story published
24
+ * without a cache version change appears within a minute.
25
+ */
26
+ export declare const DEFAULT_NEGATIVE_TTL = 60;
15
27
  export declare namespace stories {
16
28
  interface SearchParams {
17
29
  search?: string;
@@ -8,6 +8,12 @@ function _asyncToGenerator(n) { return function () { var t = this, e = arguments
8
8
  import { ApiError, Category, NewsroomGallery, SortOrder, Stories, Story } from '@prezly/sdk';
9
9
  import { RequestCoalescer, sharedContentRequests } from "./RequestCoalescer.mjs";
10
10
  import { CONTENT_OPERATIONS, emit, elapsedSeconds, telemetryNow } from "./telemetry.mjs";
11
+ /**
12
+ * Not-found results are cached only briefly: long enough to absorb repeated
13
+ * requests for the same missing slug, short enough that a story published
14
+ * without a cache version change appears within a minute.
15
+ */
16
+ export var DEFAULT_NEGATIVE_TTL = 60;
11
17
  export var stories;
12
18
  export var allStories;
13
19
  export var story;
@@ -282,6 +288,7 @@ export function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
282
288
  }
283
289
  };
284
290
  if (cache) {
291
+ var _cache$negativeTtl;
285
292
  if (cache.scope !== undefined && !cache.scope) {
286
293
  throw new Error('Content cache scope must not be empty.');
287
294
  }
@@ -289,7 +296,7 @@ export function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
289
296
  // A single schema prefix keeps old readers away from scoped envelopes.
290
297
  // Scope/version changes overwrite the same keys rather than adding namespaces.
291
298
  var storage = cache.scope === undefined ? cache.storage : cache.storage.namespace('scoped-v1');
292
- injectCache(client, storage.namespace(namespace), cache.latestVersion, cache.scope, namespace, UNCACHED_METHODS, telemetry);
299
+ injectCache(client, storage.namespace(namespace), cache.latestVersion, cache.scope, namespace, UNCACHED_METHODS, telemetry, (_cache$negativeTtl = cache.negativeTtl) !== null && _cache$negativeTtl !== void 0 ? _cache$negativeTtl : DEFAULT_NEGATIVE_TTL);
293
300
  } else if (telemetry) {
294
301
  var _loop2 = function _loop2() {
295
302
  if (UNCACHED_METHODS.includes(methodName)) return 1; // continue
@@ -312,9 +319,21 @@ export function createClient(prezly, newsroomUuid, newsroomThemeUuid) {
312
319
  }
313
320
  return client;
314
321
  }
322
+ function readScopedValue(stored, scope) {
323
+ if ((stored === null || stored === void 0 ? void 0 : stored.scope) !== scope) return undefined;
324
+ if (stored.value === null) {
325
+ var fresh = typeof stored.expires === 'number' && stored.expires > Date.now() / 1000;
326
+ return fresh ? null : undefined;
327
+ }
328
+ return stored.value;
329
+ }
315
330
  function injectCache(client, cache, latestVersion, scope, namespace) {
316
331
  var uncachedMethods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
317
332
  var telemetry = arguments.length > 6 ? arguments[6] : undefined;
333
+ var negativeTtl = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : DEFAULT_NEGATIVE_TTL;
334
+ if (!Number.isInteger(negativeTtl) || negativeTtl < 1) {
335
+ throw new RangeError('The negative cache TTL must be a positive integer number of seconds.');
336
+ }
318
337
  // An opaque SDK client does not expose its credentials/source. Callers without
319
338
  // an explicit scope keep request-local sharing; the Next.js adapter supplies one.
320
339
  var requests = scope === undefined ? new RequestCoalescer() : sharedContentRequests;
@@ -340,10 +359,12 @@ function injectCache(client, cache, latestVersion, scope, namespace) {
340
359
  var _stored = telemetry ? yield cache.get(cacheKey, latestVersion, source => {
341
360
  layer = source === 'memory' || source === 'redis' ? source : 'custom';
342
361
  }) : yield cache.get(cacheKey, latestVersion);
343
- var cached = scope === undefined ? _stored : (_stored === null || _stored === void 0 ? void 0 : _stored.scope) === scope ? _stored.value : undefined;
344
- // Preserve existing negative-cache semantics until null results
345
- // have a deliberately short TTL and correct error classification.
346
- if (cached) {
362
+ // Only an absent entry is a miss: a stored `false` or `0` is a valid
363
+ // result. A stored `null` (not found) is a hit only inside its own
364
+ // deadline, which lives in the scoped envelope. Unscoped clients
365
+ // cannot carry that deadline and keep treating null as a miss.
366
+ var cached = scope === undefined ? _stored === null ? undefined : _stored : readScopedValue(_stored, scope);
367
+ if (cached !== undefined) {
347
368
  emit(telemetry, {
348
369
  type: 'cache_hit',
349
370
  operation,
@@ -366,13 +387,27 @@ function injectCache(client, cache, latestVersion, scope, namespace) {
366
387
  operation
367
388
  });
368
389
  var value = yield observeOrigin(() => uncachedFn(...args), telemetry, operation);
369
- var stored = scope === undefined ? value : {
390
+ // `null` means the API answered 403/404/410 for this lookup. Keep it
391
+ // only briefly, with the deadline in the envelope and a matching
392
+ // layer hint. Errors (401, 429, 5xx, transport) throw above and are
393
+ // never stored. `undefined` results are not stored either.
394
+ var negative = value === null && scope !== undefined;
395
+ var stored = scope === undefined ? value : negative ? {
396
+ scope,
397
+ value,
398
+ // Fractional seconds: flooring would shorten a 1-second
399
+ // retention to almost nothing.
400
+ expires: Date.now() / 1000 + negativeTtl
401
+ } : {
370
402
  scope,
371
403
  value
372
404
  };
405
+ var options = negative ? {
406
+ ttl: negativeTtl
407
+ } : undefined;
373
408
  // Observe synchronous and asynchronous write failures without holding
374
409
  // up a successful response or leaving an unhandled rejection.
375
- var cacheWrite = Promise.resolve().then(() => cache.set(cacheKey, stored, latestVersion)).catch(() => {
410
+ var cacheWrite = value === undefined || value === null && scope === undefined ? undefined : Promise.resolve().then(() => cache.set(cacheKey, stored, latestVersion, options)).catch(() => {
376
411
  emit(telemetry, {
377
412
  type: 'cache_error',
378
413
  operation,
@@ -2,6 +2,12 @@
2
2
 
3
3
  var _sdk = require("@prezly/sdk");
4
4
  var _ContentDelivery = require("./ContentDelivery.cjs");
5
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
6
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
7
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
8
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
9
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
10
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
5
11
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
6
12
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
7
13
  function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
@@ -16,13 +22,14 @@ function memory() {
16
22
  return entry && entry.version >= version ? entry.value : undefined;
17
23
  });
18
24
  var _set = jest.fn(/*#__PURE__*/function () {
19
- var _ref = _asyncToGenerator(function* (key, value, version) {
25
+ var _ref = _asyncToGenerator(function* (key, value, version, options) {
20
26
  entries.set(key, {
21
27
  value,
22
- version
28
+ version,
29
+ ttl: options === null || options === void 0 ? void 0 : options.ttl
23
30
  });
24
31
  });
25
- return function (_x, _x2, _x3) {
32
+ return function (_x, _x2, _x3, _x4) {
26
33
  return _ref.apply(this, arguments);
27
34
  };
28
35
  }());
@@ -30,7 +37,7 @@ function memory() {
30
37
  var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
31
38
  return {
32
39
  get: (key, version) => _get(prefix + key, version),
33
- set: (key, value, version) => _set(prefix + key, value, version),
40
+ set: (key, value, version, options) => _set(prefix + key, value, version, options),
34
41
  namespace: name => storage("".concat(prefix).concat(name, ":"))
35
42
  };
36
43
  }
@@ -56,7 +63,7 @@ function api() {
56
63
  stories: [offset]
57
64
  };
58
65
  });
59
- return function (_x4) {
66
+ return function (_x5) {
60
67
  return _ref4.apply(this, arguments);
61
68
  };
62
69
  }());
@@ -281,4 +288,361 @@ describe('ContentDelivery request sharing', () => {
281
288
  jest.useRealTimers();
282
289
  }
283
290
  }));
291
+ });
292
+ function apiError(status) {
293
+ return new _sdk.ApiError({
294
+ payload: {
295
+ code: status,
296
+ message: 'x'
297
+ },
298
+ status,
299
+ statusText: 'x',
300
+ headers: {}
301
+ });
302
+ }
303
+ function storyApi(outcomes) {
304
+ var queue = [...outcomes];
305
+ var getBySlug = jest.fn(/*#__PURE__*/function () {
306
+ var _ref11 = _asyncToGenerator(function* (slug) {
307
+ var _queue$shift;
308
+ var outcome = (_queue$shift = queue.shift()) !== null && _queue$shift !== void 0 ? _queue$shift : 'story';
309
+ if (outcome === 'story') return {
310
+ slug,
311
+ uuid: "uuid-".concat(slug)
312
+ };
313
+ throw apiError(outcome);
314
+ });
315
+ return function (_x6) {
316
+ return _ref11.apply(this, arguments);
317
+ };
318
+ }());
319
+ return {
320
+ getBySlug,
321
+ client: {
322
+ stories: {
323
+ getBySlug
324
+ }
325
+ }
326
+ };
327
+ }
328
+ describe('ContentDelivery negative caching', () => {
329
+ it('reuses a cached null story across clients and stores it with the negative TTL', /*#__PURE__*/_asyncToGenerator(function* () {
330
+ var storage = memory();
331
+ var sdk = storyApi([404]);
332
+ var cache = {
333
+ storage: storage.storage,
334
+ latestVersion: 1,
335
+ scope: identity()
336
+ };
337
+ var first = (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
338
+ cache
339
+ });
340
+ expect(yield first.story({
341
+ slug: 'missing'
342
+ })).toBeNull();
343
+ yield flush();
344
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
345
+ cache
346
+ }).story({
347
+ slug: 'missing'
348
+ })).toBeNull();
349
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(1);
350
+ var _storage$entries$valu = storage.entries.values(),
351
+ _storage$entries$valu2 = _slicedToArray(_storage$entries$valu, 1),
352
+ entry = _storage$entries$valu2[0];
353
+ expect(entry.ttl).toBe(_ContentDelivery.DEFAULT_NEGATIVE_TTL);
354
+ expect(entry.value).toEqual({
355
+ scope: cache.scope,
356
+ value: null,
357
+ expires: expect.any(Number)
358
+ });
359
+ expect(entry.value.expires).toBeGreaterThan(Date.now() / 1000);
360
+ expect(entry.value.expires).toBeLessThanOrEqual(Date.now() / 1000 + _ContentDelivery.DEFAULT_NEGATIVE_TTL);
361
+ }));
362
+ it('treats a null written by a cache that ignores the ttl hint as a miss once its deadline passes', /*#__PURE__*/_asyncToGenerator(function* () {
363
+ jest.useFakeTimers();
364
+ try {
365
+ var storage = memory();
366
+ var sdk = storyApi([404, 'story']);
367
+ var cache = {
368
+ storage: storage.storage,
369
+ latestVersion: 1,
370
+ scope: identity(),
371
+ negativeTtl: 30
372
+ };
373
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
374
+ cache
375
+ }).story({
376
+ slug: 's'
377
+ })).toBeNull();
378
+ yield jest.advanceTimersByTimeAsync(0);
379
+ jest.advanceTimersByTime(29000);
380
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
381
+ cache
382
+ }).story({
383
+ slug: 's'
384
+ })).toBeNull();
385
+ yield jest.advanceTimersByTimeAsync(0);
386
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(1);
387
+ jest.advanceTimersByTime(2000);
388
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
389
+ cache
390
+ }).story({
391
+ slug: 's'
392
+ })).toMatchObject({
393
+ slug: 's'
394
+ });
395
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(2);
396
+ } finally {
397
+ jest.useRealTimers();
398
+ }
399
+ }));
400
+ it('treats a legacy null envelope without a deadline as a miss and replaces it', /*#__PURE__*/_asyncToGenerator(function* () {
401
+ var storage = memory();
402
+ var sdk = storyApi(['story']);
403
+ var scope = identity();
404
+ var cache = {
405
+ storage: storage.storage,
406
+ latestVersion: 1,
407
+ scope
408
+ };
409
+ var client = (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
410
+ cache
411
+ });
412
+ yield client.story({
413
+ slug: 'legacy'
414
+ });
415
+ yield flush();
416
+ var _storage$entries$keys = storage.entries.keys(),
417
+ _storage$entries$keys2 = _slicedToArray(_storage$entries$keys, 1),
418
+ key = _storage$entries$keys2[0];
419
+ storage.entries.set(key, {
420
+ value: {
421
+ scope,
422
+ value: null
423
+ },
424
+ version: 1
425
+ });
426
+ expect(yield client.story({
427
+ slug: 'legacy'
428
+ })).toMatchObject({
429
+ slug: 'legacy'
430
+ });
431
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(2);
432
+ }));
433
+ it('does not store null for clients without a scope', /*#__PURE__*/_asyncToGenerator(function* () {
434
+ var storage = memory();
435
+ var sdk = storyApi([404, 404]);
436
+ var cache = {
437
+ storage: storage.storage,
438
+ latestVersion: 1
439
+ };
440
+ var client = (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
441
+ cache
442
+ });
443
+ expect(yield client.story({
444
+ slug: 's'
445
+ })).toBeNull();
446
+ yield flush();
447
+ expect(storage.set).not.toHaveBeenCalled();
448
+ expect(yield client.story({
449
+ slug: 's'
450
+ })).toBeNull();
451
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(2);
452
+ }));
453
+ it.each([403, 410])('keeps a %s result only for the configured negative TTL', /*#__PURE__*/function () {
454
+ var _ref16 = _asyncToGenerator(function* (status) {
455
+ var storage = memory();
456
+ var sdk = storyApi([status]);
457
+ var cache = {
458
+ storage: storage.storage,
459
+ latestVersion: 1,
460
+ scope: identity(),
461
+ negativeTtl: 5
462
+ };
463
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
464
+ cache
465
+ }).story({
466
+ slug: 's'
467
+ })).toBeNull();
468
+ yield flush();
469
+ expect([...storage.entries.values()][0].ttl).toBe(5);
470
+ });
471
+ return function (_x7) {
472
+ return _ref16.apply(this, arguments);
473
+ };
474
+ }());
475
+ it('stores found stories without a short TTL', /*#__PURE__*/_asyncToGenerator(function* () {
476
+ var storage = memory();
477
+ var sdk = storyApi(['story']);
478
+ var cache = {
479
+ storage: storage.storage,
480
+ latestVersion: 1,
481
+ scope: identity()
482
+ };
483
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
484
+ cache
485
+ }).story({
486
+ slug: 's'
487
+ })).toMatchObject({
488
+ slug: 's'
489
+ });
490
+ yield flush();
491
+ expect([...storage.entries.values()][0].ttl).toBeUndefined();
492
+ }));
493
+ it('serves published content after a cache version change', /*#__PURE__*/_asyncToGenerator(function* () {
494
+ var storage = memory();
495
+ var sdk = storyApi([404, 'story']);
496
+ var cache = {
497
+ storage: storage.storage,
498
+ latestVersion: 1,
499
+ scope: identity()
500
+ };
501
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
502
+ cache
503
+ }).story({
504
+ slug: 's'
505
+ })).toBeNull();
506
+ yield flush();
507
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
508
+ cache: _objectSpread(_objectSpread({}, cache), {}, {
509
+ latestVersion: 2
510
+ })
511
+ }).story({
512
+ slug: 's'
513
+ })).toMatchObject({
514
+ slug: 's'
515
+ });
516
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(2);
517
+ }));
518
+ it.each([401, 429, 500, 503])('does not store a %s failure and retries the next lookup', /*#__PURE__*/function () {
519
+ var _ref19 = _asyncToGenerator(function* (status) {
520
+ var storage = memory();
521
+ var sdk = storyApi([status, 'story']);
522
+ var cache = {
523
+ storage: storage.storage,
524
+ latestVersion: 1,
525
+ scope: identity()
526
+ };
527
+ var client = (0, _ContentDelivery.createClient)(sdk.client, 'room', undefined, {
528
+ cache
529
+ });
530
+ yield expect(client.story({
531
+ slug: 's'
532
+ })).rejects.toMatchObject({
533
+ status
534
+ });
535
+ yield flush();
536
+ expect(storage.set).not.toHaveBeenCalled();
537
+ expect(yield client.story({
538
+ slug: 's'
539
+ })).toMatchObject({
540
+ slug: 's'
541
+ });
542
+ });
543
+ return function (_x8) {
544
+ return _ref19.apply(this, arguments);
545
+ };
546
+ }());
547
+ it('does not store a transport failure', /*#__PURE__*/_asyncToGenerator(function* () {
548
+ var storage = memory();
549
+ var getBySlug = jest.fn(/*#__PURE__*/_asyncToGenerator(function* () {
550
+ throw new TypeError('fetch failed');
551
+ }));
552
+ var client = {
553
+ stories: {
554
+ getBySlug
555
+ }
556
+ };
557
+ var cache = {
558
+ storage: storage.storage,
559
+ latestVersion: 1,
560
+ scope: identity()
561
+ };
562
+ yield expect((0, _ContentDelivery.createClient)(client, 'room', undefined, {
563
+ cache
564
+ }).story({
565
+ slug: 's'
566
+ })).rejects.toThrow('fetch failed');
567
+ yield flush();
568
+ expect(storage.set).not.toHaveBeenCalled();
569
+ }));
570
+ it('isolates not-found results per newsroom', /*#__PURE__*/_asyncToGenerator(function* () {
571
+ var storage = memory();
572
+ var sdk = storyApi([404, 'story']);
573
+ var cache = {
574
+ storage: storage.storage,
575
+ latestVersion: 1,
576
+ scope: identity()
577
+ };
578
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room-a', undefined, {
579
+ cache
580
+ }).story({
581
+ slug: 's'
582
+ })).toBeNull();
583
+ yield flush();
584
+ expect(yield (0, _ContentDelivery.createClient)(sdk.client, 'room-b', undefined, {
585
+ cache
586
+ }).story({
587
+ slug: 's'
588
+ })).toMatchObject({
589
+ slug: 's'
590
+ });
591
+ expect(sdk.getBySlug).toHaveBeenCalledTimes(2);
592
+ expect(storage.entries.size).toBe(2);
593
+ }));
594
+ it.each([false, 0, ''])('treats a cached %p as a hit', /*#__PURE__*/function () {
595
+ var _ref23 = _asyncToGenerator(function* (value) {
596
+ var storage = memory();
597
+ var get = jest.fn(/*#__PURE__*/_asyncToGenerator(function* () {
598
+ return value;
599
+ }));
600
+ var client = {
601
+ newsrooms: {
602
+ get
603
+ }
604
+ };
605
+ var cache = {
606
+ storage: storage.storage,
607
+ latestVersion: 1,
608
+ scope: identity()
609
+ };
610
+ expect(yield (0, _ContentDelivery.createClient)(client, 'room', undefined, {
611
+ cache
612
+ }).newsroom()).toBe(value);
613
+ yield flush();
614
+ expect(yield (0, _ContentDelivery.createClient)(client, 'room', undefined, {
615
+ cache
616
+ }).newsroom()).toBe(value);
617
+ expect(get).toHaveBeenCalledTimes(1);
618
+ expect([...storage.entries.values()][0].ttl).toBeUndefined();
619
+ });
620
+ return function (_x9) {
621
+ return _ref23.apply(this, arguments);
622
+ };
623
+ }());
624
+ it('does not store undefined results', /*#__PURE__*/_asyncToGenerator(function* () {
625
+ var storage = memory();
626
+ var cache = {
627
+ storage: storage.storage,
628
+ latestVersion: 1,
629
+ scope: identity()
630
+ };
631
+ expect(yield (0, _ContentDelivery.createClient)(api().client, 'room', undefined, {
632
+ cache
633
+ }).theme()).toBeUndefined();
634
+ yield flush();
635
+ expect(storage.set).not.toHaveBeenCalled();
636
+ }));
637
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])('rejects a negative TTL of %p', negativeTtl => {
638
+ var cache = {
639
+ storage: memory().storage,
640
+ latestVersion: 1,
641
+ scope: identity(),
642
+ negativeTtl
643
+ };
644
+ expect(() => (0, _ContentDelivery.createClient)(api().client, 'room', undefined, {
645
+ cache
646
+ })).toThrow(RangeError);
647
+ });
284
648
  });