@ember-data/request-utils 5.6.0-beta.0 → 5.6.0-beta.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.
Files changed (30) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/deprecation-support.js +9 -8
  3. package/dist/handlers.js +1 -147
  4. package/dist/index.js +7 -936
  5. package/dist/string.js +1 -2
  6. package/package.json +5 -17
  7. package/unstable-preview-types/deprecation-support.d.ts +2 -2
  8. package/unstable-preview-types/handlers.d.ts +8 -9
  9. package/unstable-preview-types/index.d.ts +10 -685
  10. package/unstable-preview-types/string.d.ts +13 -15
  11. package/dist/deprecation-support.js.map +0 -1
  12. package/dist/handlers.js.map +0 -1
  13. package/dist/index.js.map +0 -1
  14. package/dist/inflect-CwI_k2it.js +0 -305
  15. package/dist/inflect-CwI_k2it.js.map +0 -1
  16. package/dist/string.js.map +0 -1
  17. package/dist/transform-1PDozfHr.js +0 -192
  18. package/dist/transform-1PDozfHr.js.map +0 -1
  19. package/unstable-preview-types/-private/handlers/auto-compress.d.ts +0 -168
  20. package/unstable-preview-types/-private/handlers/auto-compress.d.ts.map +0 -1
  21. package/unstable-preview-types/-private/string/inflect.d.ts +0 -140
  22. package/unstable-preview-types/-private/string/inflect.d.ts.map +0 -1
  23. package/unstable-preview-types/-private/string/inflections.d.ts +0 -12
  24. package/unstable-preview-types/-private/string/inflections.d.ts.map +0 -1
  25. package/unstable-preview-types/-private/string/transform.d.ts +0 -117
  26. package/unstable-preview-types/-private/string/transform.d.ts.map +0 -1
  27. package/unstable-preview-types/deprecation-support.d.ts.map +0 -1
  28. package/unstable-preview-types/handlers.d.ts.map +0 -1
  29. package/unstable-preview-types/index.d.ts.map +0 -1
  30. package/unstable-preview-types/string.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { deprecate } from '@ember/debug';
2
- import { getOrSetGlobal } from '@warp-drive/core-types/-private';
3
- import { L as LRUCache } from "./transform-1PDozfHr.js";
4
- import { macroCondition, getGlobalConfig } from '@embroider/macros';
2
+ import { DefaultCachePolicy } from '@warp-drive/core/store';
3
+ export { DefaultCachePolicy as CachePolicy, parseCacheControl } from '@warp-drive/core/store';
4
+ export * from '@warp-drive/utilities';
5
5
 
6
6
  /**
7
7
  * Simple utility function to assist in url building,
@@ -38,941 +38,11 @@ import { macroCondition, getGlobalConfig } from '@embroider/macros';
38
38
  * // Note: options will also include other request options like headers, method, etc.
39
39
  * ```
40
40
  *
41
- * @module @ember-data/request-utils
42
- * @main @ember-data/request-utils
41
+ * @module
43
42
  * @public
44
43
  */
45
- // prevents the final constructed object from needing to add
46
- // host and namespace which are provided by the final consuming
47
- // class to the prototype which can result in overwrite errors
48
- const CONFIG = getOrSetGlobal('CONFIG', {
49
- host: '',
50
- namespace: ''
51
- });
52
44
 
53
- /**
54
- * Sets the global configuration for `buildBaseURL`
55
- * for host and namespace values for the application.
56
- *
57
- * These values may still be overridden by passing
58
- * them to buildBaseURL directly.
59
- *
60
- * This method may be called as many times as needed.
61
- * host values of `''` or `'/'` are equivalent.
62
- *
63
- * Except for the value of `/` as host, host should not
64
- * end with `/`.
65
- *
66
- * namespace should not start or end with a `/`.
67
- *
68
- * ```ts
69
- * type BuildURLConfig = {
70
- * host: string;
71
- * namespace: string'
72
- * }
73
- * ```
74
- *
75
- * Example:
76
- *
77
- * ```ts
78
- * import { setBuildURLConfig } from '@ember-data/request-utils';
79
- *
80
- * setBuildURLConfig({
81
- * host: 'https://api.example.com',
82
- * namespace: 'api/v1'
83
- * });
84
- * ```
85
- *
86
- * @method setBuildURLConfig
87
- * @static
88
- * @public
89
- * @for @ember-data/request-utils
90
- * @param {BuildURLConfig} config
91
- * @return void
92
- */
93
- function setBuildURLConfig(config) {
94
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
95
- if (!test) {
96
- throw new Error(`setBuildURLConfig: You must pass a config object`);
97
- }
98
- })(config) : {};
99
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
100
- if (!test) {
101
- throw new Error(`setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`);
102
- }
103
- })('host' in config || 'namespace' in config) : {};
104
- CONFIG.host = config.host || '';
105
- CONFIG.namespace = config.namespace || '';
106
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
107
- if (!test) {
108
- throw new Error(`buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`);
109
- }
110
- })(CONFIG.host === '/' || !CONFIG.host.endsWith('/')) : {};
111
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
112
- if (!test) {
113
- throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`);
114
- }
115
- })(!CONFIG.namespace.startsWith('/')) : {};
116
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
117
- if (!test) {
118
- throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`);
119
- }
120
- })(!CONFIG.namespace.endsWith('/')) : {};
121
- }
122
- const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
123
- function isOperationWithPrimaryRecord(options) {
124
- return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
125
- }
126
- function hasResourcePath(options) {
127
- return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;
128
- }
129
- function resourcePathForType(options) {
130
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
131
- if (!test) {
132
- throw new Error(`resourcePathForType: You must pass a valid op as part of options`);
133
- }
134
- })('op' in options && typeof options.op === 'string') : {};
135
- return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
136
- }
137
-
138
- /**
139
- * Builds a URL for a request based on the provided options.
140
- * Does not include support for building query params (see `buildQueryParams`)
141
- * so that it may be composed cleanly with other query-params strategies.
142
- *
143
- * Usage:
144
- *
145
- * ```ts
146
- * import { buildBaseURL } from '@ember-data/request-utils';
147
- *
148
- * const url = buildBaseURL({
149
- * host: 'https://api.example.com',
150
- * namespace: 'api/v1',
151
- * resourcePath: 'emberDevelopers',
152
- * op: 'query',
153
- * identifier: { type: 'ember-developer' }
154
- * });
155
- *
156
- * // => 'https://api.example.com/api/v1/emberDevelopers'
157
- * ```
158
- *
159
- * On the surface this may seem like a lot of work to do something simple, but
160
- * it is designed to be composable with other utilities and interfaces that the
161
- * average product engineer will never need to see or use.
162
- *
163
- * A few notes:
164
- *
165
- * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
166
- * - `host` and `namespace` are optional, but if they are not provided, the values globally
167
- * configured via `setBuildURLConfig` will be used.
168
- * - `op` is required and must be one of the following:
169
- * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
170
- * - Depending on the value of `op`, `identifier` or `identifiers` will be required.
171
- *
172
- * @method buildBaseURL
173
- * @static
174
- * @public
175
- * @for @ember-data/request-utils
176
- * @param urlOptions
177
- * @return string
178
- */
179
- function buildBaseURL(urlOptions) {
180
- const options = Object.assign({
181
- host: CONFIG.host,
182
- namespace: CONFIG.namespace
183
- }, urlOptions);
184
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
185
- if (!test) {
186
- throw new Error(`buildBaseURL: You must pass \`op\` as part of options`);
187
- }
188
- })(hasResourcePath(options) || typeof options.op === 'string' && options.op.length > 0) : {};
189
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
190
- if (!test) {
191
- throw new Error(`buildBaseURL: You must pass \`identifier\` as part of options`);
192
- }
193
- })(hasResourcePath(options) || options.op === 'findMany' || options.identifier && typeof options.identifier === 'object') : {};
194
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
195
- if (!test) {
196
- throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
197
- }
198
- })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object')) : {};
199
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
200
- if (!test) {
201
- throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`);
202
- }
203
- })(hasResourcePath(options) || !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0) : {};
204
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
205
- if (!test) {
206
- throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
207
- }
208
- })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0)) : {};
209
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
210
- if (!test) {
211
- throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`);
212
- }
213
- })(hasResourcePath(options) || options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0) : {};
214
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
215
- if (!test) {
216
- throw new Error(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`);
217
- }
218
- })(hasResourcePath(options) || options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0) : {};
219
-
220
- // prettier-ignore
221
- const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
222
- const resourcePath = options.resourcePath || resourcePathForType(options);
223
- const {
224
- host,
225
- namespace
226
- } = options;
227
- const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
228
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
229
- if (!test) {
230
- throw new Error(`buildBaseURL: You tried to build a url for a ${String('op' in options ? options.op + ' ' : '')}request to ${resourcePath} but resourcePath must be set or op must be one of "${['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord', 'createRecord', 'query', 'findMany'].join('","')}".`);
231
- }
232
- })(hasResourcePath(options) || ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op)) : {};
233
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
234
- if (!test) {
235
- throw new Error(`buildBaseURL: host must NOT end with '/', received '${host}'`);
236
- }
237
- })(host === '/' || !host.endsWith('/')) : {};
238
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
239
- if (!test) {
240
- throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`);
241
- }
242
- })(!namespace.startsWith('/')) : {};
243
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
244
- if (!test) {
245
- throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`);
246
- }
247
- })(!namespace.endsWith('/')) : {};
248
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
249
- if (!test) {
250
- throw new Error(`buildBaseURL: resourcePath must NOT start with '/', received '${resourcePath}'`);
251
- }
252
- })(!resourcePath.startsWith('/')) : {};
253
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
254
- if (!test) {
255
- throw new Error(`buildBaseURL: resourcePath must NOT end with '/', received '${resourcePath}'`);
256
- }
257
- })(!resourcePath.endsWith('/')) : {};
258
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
259
- if (!test) {
260
- throw new Error(`buildBaseURL: fieldPath must NOT start with '/', received '${fieldPath}'`);
261
- }
262
- })(!fieldPath.startsWith('/')) : {};
263
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
264
- if (!test) {
265
- throw new Error(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`);
266
- }
267
- })(!fieldPath.endsWith('/')) : {};
268
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
269
- if (!test) {
270
- throw new Error(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`);
271
- }
272
- })(!idPath.startsWith('/')) : {};
273
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
274
- if (!test) {
275
- throw new Error(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`);
276
- }
277
- })(!idPath.endsWith('/')) : {};
278
- const hasHost = host !== '' && host !== '/';
279
- const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
280
- return hasHost ? url : `/${url}`;
281
- }
282
- const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
283
- arrayFormat: 'comma'
284
- };
285
- function handleInclude(include) {
286
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
287
- if (!test) {
288
- throw new Error(`Expected include to be a string or array, got ${typeof include}`);
289
- }
290
- })(typeof include === 'string' || Array.isArray(include)) : {};
291
- return typeof include === 'string' ? include.split(',') : include;
292
- }
293
-
294
- /**
295
- * filter out keys of an object that have falsy values or point to empty arrays
296
- * returning a new object with only those keys that have truthy values / non-empty arrays
297
- *
298
- * @method filterEmpty
299
- * @static
300
- * @public
301
- * @for @ember-data/request-utils
302
- * @param {Record<string, Serializable>} source object to filter keys with empty values from
303
- * @return {Record<string, Serializable>} A new object with the keys that contained empty values removed
304
- */
305
- function filterEmpty(source) {
306
- const result = {};
307
- for (const key in source) {
308
- const value = source[key];
309
- // Allow `0` and `false` but filter falsy values that indicate "empty"
310
- if (value !== undefined && value !== null && value !== '') {
311
- if (!Array.isArray(value) || value.length > 0) {
312
- result[key] = source[key];
313
- }
314
- }
315
- }
316
- return result;
317
- }
318
-
319
- /**
320
- * Sorts query params by both key and value returning a new URLSearchParams
321
- * object with the keys inserted in sorted order.
322
- *
323
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
324
- *
325
- * Options:
326
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
327
- *
328
- * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
329
- * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
330
- * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
331
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
332
- *
333
- * @method sortQueryParams
334
- * @static
335
- * @public
336
- * @for @ember-data/request-utils
337
- * @param {URLSearchParams | object} params
338
- * @param {Object} options
339
- * @return {URLSearchParams} A URLSearchParams with keys inserted in sorted order
340
- */
341
- function sortQueryParams(params, options) {
342
- const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
343
- const paramsIsObject = !(params instanceof URLSearchParams);
344
- const urlParams = new URLSearchParams();
345
- const dictionaryParams = paramsIsObject ? params : {};
346
- if (!paramsIsObject) {
347
- params.forEach((value, key) => {
348
- const hasExisting = key in dictionaryParams;
349
- if (!hasExisting) {
350
- dictionaryParams[key] = value;
351
- } else {
352
- const existingValue = dictionaryParams[key];
353
- if (Array.isArray(existingValue)) {
354
- existingValue.push(value);
355
- } else {
356
- dictionaryParams[key] = [existingValue, value];
357
- }
358
- }
359
- });
360
- }
361
- if ('include' in dictionaryParams) {
362
- dictionaryParams.include = handleInclude(dictionaryParams.include);
363
- }
364
- const sortedKeys = Object.keys(dictionaryParams).sort();
365
- sortedKeys.forEach(key => {
366
- const value = dictionaryParams[key];
367
- if (Array.isArray(value)) {
368
- value.sort();
369
- switch (opts.arrayFormat) {
370
- case 'indices':
371
- value.forEach((v, i) => {
372
- urlParams.append(`${key}[${i}]`, String(v));
373
- });
374
- return;
375
- case 'bracket':
376
- value.forEach(v => {
377
- urlParams.append(`${key}[]`, String(v));
378
- });
379
- return;
380
- case 'repeat':
381
- value.forEach(v => {
382
- urlParams.append(key, String(v));
383
- });
384
- return;
385
- case 'comma':
386
- default:
387
- urlParams.append(key, value.join(','));
388
- return;
389
- }
390
- } else {
391
- urlParams.append(key, String(value));
392
- }
393
- });
394
- return urlParams;
395
- }
396
-
397
- /**
398
- * Sorts query params by both key and value, returning a query params string
399
- *
400
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
401
- *
402
- * Options:
403
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
404
- *
405
- * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
406
- * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
407
- * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
408
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
409
- *
410
- * @method buildQueryParams
411
- * @static
412
- * @public
413
- * @for @ember-data/request-utils
414
- * @param {URLSearchParams | Object} params
415
- * @param {Object} [options]
416
- * @return {String} A sorted query params string without the leading `?`
417
- */
418
- function buildQueryParams(params, options) {
419
- return sortQueryParams(params, options).toString();
420
- }
421
- const NUMERIC_KEYS = new Set(['max-age', 's-maxage', 'stale-if-error', 'stale-while-revalidate']);
422
-
423
- /**
424
- * Parses a string Cache-Control header value into an object with the following structure:
425
- *
426
- * ```ts
427
- * interface CacheControlValue {
428
- * immutable?: boolean;
429
- * 'max-age'?: number;
430
- * 'must-revalidate'?: boolean;
431
- * 'must-understand'?: boolean;
432
- * 'no-cache'?: boolean;
433
- * 'no-store'?: boolean;
434
- * 'no-transform'?: boolean;
435
- * 'only-if-cached'?: boolean;
436
- * private?: boolean;
437
- * 'proxy-revalidate'?: boolean;
438
- * public?: boolean;
439
- * 's-maxage'?: number;
440
- * 'stale-if-error'?: number;
441
- * 'stale-while-revalidate'?: number;
442
- * }
443
- * ```
444
- * @method parseCacheControl
445
- * @static
446
- * @public
447
- * @for @ember-data/request-utils
448
- * @param {String} header
449
- * @return {CacheControlValue}
450
- */
451
- function parseCacheControl(header) {
452
- return CACHE_CONTROL_CACHE.get(header);
453
- }
454
- const CACHE_CONTROL_CACHE = new LRUCache(header => {
455
- let key = '';
456
- let value = '';
457
- let isParsingKey = true;
458
- const cacheControlValue = {};
459
- for (let i = 0; i < header.length; i++) {
460
- const char = header.charAt(i);
461
- if (char === ',') {
462
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
463
- if (!test) {
464
- throw new Error(`Invalid Cache-Control value, expected a value`);
465
- }
466
- })(!isParsingKey || !NUMERIC_KEYS.has(key)) : {};
467
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
468
- if (!test) {
469
- throw new Error(`Invalid Cache-Control value, expected a value after "=" but got ","`);
470
- }
471
- })(i === 0 || header.charAt(i - 1) !== '=') : {};
472
- isParsingKey = true;
473
- // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
474
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
475
- key = '';
476
- value = '';
477
- continue;
478
- } else if (char === '=') {
479
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
480
- if (!test) {
481
- throw new Error(`Invalid Cache-Control value, expected a value after "="`);
482
- }
483
- })(i + 1 !== header.length) : {};
484
- isParsingKey = false;
485
- } else if (char === ' ' || char === `\t` || char === `\n`) {
486
- continue;
487
- } else if (isParsingKey) {
488
- key += char;
489
- } else {
490
- value += char;
491
- }
492
- if (i === header.length - 1) {
493
- // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
494
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
495
- }
496
- }
497
- return cacheControlValue;
498
- }, 200);
499
- function parseCacheControlValue(stringToParse) {
500
- const parsedValue = Number.parseInt(stringToParse);
501
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
502
- if (!test) {
503
- throw new Error(`Invalid Cache-Control value, expected a number but got - ${stringToParse}`);
504
- }
505
- })(!Number.isNaN(parsedValue)) : {};
506
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
507
- if (!test) {
508
- throw new Error(`Invalid Cache-Control value, expected a number greater than 0 but got - ${stringToParse}`);
509
- }
510
- })(parsedValue >= 0) : {};
511
- if (Number.isNaN(parsedValue) || parsedValue < 0) {
512
- return 0;
513
- }
514
- return parsedValue;
515
- }
516
- function isExpired(identifier, request, config) {
517
- const {
518
- constraints
519
- } = config;
520
- if (constraints?.isExpired) {
521
- const result = constraints.isExpired(request);
522
- if (result !== null) {
523
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
524
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
525
- // eslint-disable-next-line no-console
526
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because constraints.isExpired returned ${result}`);
527
- }
528
- }
529
- return result;
530
- }
531
- }
532
- const {
533
- headers
534
- } = request.response;
535
- if (!headers) {
536
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
537
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
538
- // eslint-disable-next-line no-console
539
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no headers were provided`);
540
- }
541
- }
542
-
543
- // if we have no headers then both the headers based expiration
544
- // and the time based expiration will be considered expired
545
- return true;
546
- }
547
-
548
- // check for X-WarpDrive-Expires
549
- const now = Date.now();
550
- const date = headers.get('Date');
551
- if (constraints?.headers) {
552
- if (constraints.headers['X-WarpDrive-Expires']) {
553
- const xWarpDriveExpires = headers.get('X-WarpDrive-Expires');
554
- if (xWarpDriveExpires) {
555
- const expirationTime = new Date(xWarpDriveExpires).getTime();
556
- const result = now >= expirationTime;
557
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
558
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
559
- // eslint-disable-next-line no-console
560
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by X-WarpDrive-Expires header is ${result ? 'in the past' : 'in the future'}`);
561
- }
562
- }
563
- return result;
564
- }
565
- }
566
-
567
- // check for Cache-Control
568
- if (constraints.headers['Cache-Control']) {
569
- const cacheControl = headers.get('Cache-Control');
570
- const age = headers.get('Age');
571
- if (cacheControl && age && date) {
572
- const cacheControlValue = parseCacheControl(cacheControl);
573
-
574
- // max-age and s-maxage are stored in
575
- const maxAge = cacheControlValue['max-age'] || cacheControlValue['s-maxage'];
576
- if (maxAge) {
577
- // age is stored in seconds
578
- const ageValue = parseInt(age, 10);
579
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
580
- if (!test) {
581
- throw new Error(`Invalid Cache-Control value, expected a number but got - ${age}`);
582
- }
583
- })(!Number.isNaN(ageValue)) : {};
584
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
585
- if (!test) {
586
- throw new Error(`Invalid Cache-Control value, expected a number greater than 0 but got - ${age}`);
587
- }
588
- })(ageValue >= 0) : {};
589
- if (!Number.isNaN(ageValue) && ageValue >= 0) {
590
- const dateValue = new Date(date).getTime();
591
- const expirationTime = dateValue + (maxAge - ageValue) * 1000;
592
- const result = now >= expirationTime;
593
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
594
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
595
- // eslint-disable-next-line no-console
596
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by Cache-Control header is ${result ? 'in the past' : 'in the future'}`);
597
- }
598
- }
599
- return result;
600
- }
601
- }
602
- }
603
- }
604
-
605
- // check for Expires
606
- if (constraints.headers.Expires) {
607
- const expires = headers.get('Expires');
608
- if (expires) {
609
- const expirationTime = new Date(expires).getTime();
610
- const result = now >= expirationTime;
611
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
612
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
613
- // eslint-disable-next-line no-console
614
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by Expires header is ${result ? 'in the past' : 'in the future'}`);
615
- }
616
- }
617
- return result;
618
- }
619
- }
620
- }
621
-
622
- // check for Date
623
- if (!date) {
624
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
625
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
626
- // eslint-disable-next-line no-console
627
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no Date header was provided`);
628
- }
629
- }
630
- return true;
631
- }
632
- let expirationTime = config.apiCacheHardExpires;
633
- if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
634
- if (!config.disableTestOptimization) {
635
- expirationTime = config.apiCacheSoftExpires;
636
- }
637
- }
638
- const time = new Date(date).getTime();
639
- const deadline = time + expirationTime;
640
- const result = now >= deadline;
641
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
642
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
643
- // eslint-disable-next-line no-console
644
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the apiCacheHardExpires time since the response's Date header is ${result ? 'in the past' : 'in the future'}`);
645
- }
646
- }
647
- return result;
648
- }
649
-
650
- /**
651
- * The configuration options for the CachePolicy
652
- * provided by `@ember-data/request-utils`.
653
- *
654
- * ```ts
655
- * import { CachePolicy } from '@ember-data/request-utils';
656
- *
657
- * new CachePolicy({
658
- * // ... PolicyConfig Settings ... //
659
- * });
660
- * ```
661
- *
662
- * @typedoc
663
- */
664
-
665
- /**
666
- * A basic CachePolicy that can be added to the Store service.
667
- *
668
- * Determines staleness based on time since the request was last received from the API
669
- * using the `date` header.
670
- *
671
- * Determines expiration based on configured constraints as well as a time based
672
- * expiration strategy based on the `date` header.
673
- *
674
- * In order expiration is determined by:
675
- *
676
- * - Is explicitly invalidated
677
- * - ↳ (if null) isExpired function <IF Constraint Active>
678
- * - ↳ (if null) X-WarpDrive-Expires header <IF Constraint Active>
679
- * - ↳ (if null) Cache-Control header <IF Constraint Active>
680
- * - ↳ (if null) Expires header <IF Constraint Active>
681
- * - ↳ (if null) Date header + apiCacheHardExpires < current time
682
- *
683
- * Invalidates any request for which `cacheOptions.types` was provided when a createRecord
684
- * request for that type is successful.
685
- *
686
- * For this to work, the `createRecord` request must include the `cacheOptions.types` array
687
- * with the types that should be invalidated, or its request should specify the identifiers
688
- * of the records that are being created via `records`. Providing both is valid.
689
- *
690
- * > [!NOTE]
691
- * > only requests that had specified `cacheOptions.types` and occurred prior to the
692
- * > createRecord request will be invalidated. This means that a given request should always
693
- * > specify the types that would invalidate it to opt into this behavior. Abstracting this
694
- * > behavior via builders is recommended to ensure consistency.
695
- *
696
- * This allows the Store's CacheHandler to determine if a request is expired and
697
- * should be refetched upon next request.
698
- *
699
- * The `Fetch` handler provided by `@ember-data/request/fetch` will automatically
700
- * add the `date` header to responses if it is not present.
701
- *
702
- * > [!NOTE]
703
- * > Date headers do not have millisecond precision, so expiration times should
704
- * > generally be larger than 1000ms.
705
- *
706
- * Usage:
707
- *
708
- * ```ts
709
- * import { CachePolicy } from '@ember-data/request-utils';
710
- * import DataStore from '@ember-data/store';
711
- *
712
- * // ...
713
- *
714
- * export class Store extends DataStore {
715
- * constructor(args) {
716
- * super(args);
717
- * this.lifetimes = new CachePolicy({ apiCacheSoftExpires: 30_000, apiCacheHardExpires: 60_000 });
718
- * }
719
- * }
720
- * ```
721
- *
722
- * In Testing environments, the `apiCacheSoftExpires` will always be `false`
723
- * and `apiCacheHardExpires` will use the `apiCacheSoftExpires` value.
724
- *
725
- * This helps reduce flakiness and produce predictably rendered results in test suites.
726
- *
727
- * Requests that specifically set `cacheOptions.backgroundReload = true` will
728
- * still be background reloaded in tests.
729
- *
730
- * This behavior can be opted out of by setting `disableTestOptimization = true`
731
- * in the policy config.
732
- *
733
- * @class CachePolicy
734
- * @public
735
- * @module @ember-data/request-utils
736
- */
737
- class CachePolicy {
738
- _getStore(store) {
739
- let set = this._stores.get(store);
740
- if (!set) {
741
- set = {
742
- invalidated: new Set(),
743
- types: new Map()
744
- };
745
- this._stores.set(store, set);
746
- }
747
- return set;
748
- }
749
- constructor(config) {
750
- this._stores = new WeakMap();
751
- const _config = arguments.length === 1 ? config : arguments[1];
752
- deprecate(`Passing a Store to the CachePolicy is deprecated, please pass only a config instead.`, arguments.length === 1, {
753
- id: 'ember-data:request-utils:lifetimes-service-store-arg',
754
- since: {
755
- enabled: '5.4',
756
- available: '4.13'
757
- },
758
- for: '@ember-data/request-utils',
759
- until: '6.0'
760
- });
761
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
762
- if (!test) {
763
- throw new Error(`You must pass a config to the CachePolicy`);
764
- }
765
- })(_config) : {};
766
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
767
- if (!test) {
768
- throw new Error(`You must pass a apiCacheSoftExpires to the CachePolicy`);
769
- }
770
- })(typeof _config.apiCacheSoftExpires === 'number') : {};
771
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
772
- if (!test) {
773
- throw new Error(`You must pass a apiCacheHardExpires to the CachePolicy`);
774
- }
775
- })(typeof _config.apiCacheHardExpires === 'number') : {};
776
- this.config = _config;
777
- }
778
-
779
- /**
780
- * Invalidate a request by its identifier for a given store instance.
781
- *
782
- * While the store argument may seem redundant, the CachePolicy
783
- * is designed to be shared across multiple stores / forks
784
- * of the store.
785
- *
786
- * ```ts
787
- * store.lifetimes.invalidateRequest(store, identifier);
788
- * ```
789
- *
790
- * @method invalidateRequest
791
- * @public
792
- * @param {StableDocumentIdentifier} identifier
793
- * @param {Store} store
794
- */
795
- invalidateRequest(identifier, store) {
796
- this._getStore(store).invalidated.add(identifier);
797
- }
798
-
799
- /**
800
- * Invalidate all requests associated to a specific type
801
- * for a given store instance.
802
- *
803
- * While the store argument may seem redundant, the CachePolicy
804
- * is designed to be shared across multiple stores / forks
805
- * of the store.
806
- *
807
- * This invalidation is done automatically when using this service
808
- * for both the CacheHandler and the LegacyNetworkHandler.
809
- *
810
- * ```ts
811
- * store.lifetimes.invalidateRequestsForType(store, 'person');
812
- * ```
813
- *
814
- * @method invalidateRequestsForType
815
- * @public
816
- * @param {String} type
817
- * @param {Store} store
818
- */
819
- invalidateRequestsForType(type, store) {
820
- const storeCache = this._getStore(store);
821
- const set = storeCache.types.get(type);
822
- const notifications = store.notifications;
823
- if (set) {
824
- // TODO batch notifications
825
- set.forEach(id => {
826
- storeCache.invalidated.add(id);
827
- notifications.notify(id, 'invalidated');
828
- });
829
- }
830
- }
831
-
832
- /**
833
- * Invoked when a request has been fulfilled from the configured request handlers.
834
- * This is invoked by the CacheHandler for both foreground and background requests
835
- * once the cache has been updated.
836
- *
837
- * Note, this is invoked by the CacheHandler regardless of whether
838
- * the request has a cache-key.
839
- *
840
- * This method should not be invoked directly by consumers.
841
- *
842
- * @method didRequest
843
- * @public
844
- * @param {ImmutableRequestInfo} request
845
- * @param {ImmutableResponse} response
846
- * @param {Store} store
847
- * @param {StableDocumentIdentifier | null} identifier
848
- * @return {void}
849
- */
850
- didRequest(request, response, identifier, store) {
851
- // if this is a successful createRecord request, invalidate the cacheKey for the type
852
- if (request.op === 'createRecord') {
853
- const statusNumber = response?.status ?? 0;
854
- if (statusNumber >= 200 && statusNumber < 400) {
855
- const types = new Set(request.records?.map(r => r.type));
856
- const additionalTypes = request.cacheOptions?.types;
857
- additionalTypes?.forEach(type => {
858
- types.add(type);
859
- });
860
- types.forEach(type => {
861
- this.invalidateRequestsForType(type, store);
862
- });
863
- }
864
-
865
- // add this document's cacheKey to a map for all associated types
866
- // it is recommended to only use this for queries
867
- } else if (identifier && request.cacheOptions?.types?.length) {
868
- const storeCache = this._getStore(store);
869
- request.cacheOptions?.types.forEach(type => {
870
- const set = storeCache.types.get(type);
871
- if (set) {
872
- set.add(identifier);
873
- storeCache.invalidated.delete(identifier);
874
- } else {
875
- storeCache.types.set(type, new Set([identifier]));
876
- }
877
- });
878
- }
879
- }
880
-
881
- /**
882
- * Invoked to determine if the request may be fulfilled from cache
883
- * if possible.
884
- *
885
- * Note, this is only invoked by the CacheHandler if the request has
886
- * a cache-key.
887
- *
888
- * If no cache entry is found or the entry is hard expired,
889
- * the request will be fulfilled from the configured request handlers
890
- * and the cache will be updated before returning the response.
891
- *
892
- * @method isHardExpired
893
- * @public
894
- * @param {StableDocumentIdentifier} identifier
895
- * @param {Store} store
896
- * @return {Boolean} true if the request is considered hard expired
897
- */
898
- isHardExpired(identifier, store) {
899
- // if we are explicitly invalidated, we are hard expired
900
- const storeCache = this._getStore(store);
901
- if (storeCache.invalidated.has(identifier)) {
902
- return true;
903
- }
904
- const cache = store.cache;
905
- const cached = cache.peekRequest(identifier);
906
- if (!cached?.response) {
907
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
908
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
909
- // eslint-disable-next-line no-console
910
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no cache entry was found`);
911
- }
912
- }
913
- return true;
914
- }
915
- return isExpired(identifier, cached, this.config);
916
- }
917
-
918
- /**
919
- * Invoked if `isHardExpired` is false to determine if the request
920
- * should be update behind the scenes if cache data is already available.
921
- *
922
- * Note, this is only invoked by the CacheHandler if the request has
923
- * a cache-key.
924
- *
925
- * If true, the request will be fulfilled from cache while a backgrounded
926
- * request is made to update the cache via the configured request handlers.
927
- *
928
- * @method isSoftExpired
929
- * @public
930
- * @param {StableDocumentIdentifier} identifier
931
- * @param {Store} store
932
- * @return {Boolean} true if the request is considered soft expired
933
- */
934
- isSoftExpired(identifier, store) {
935
- if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
936
- if (!this.config.disableTestOptimization) {
937
- return false;
938
- }
939
- }
940
- const cache = store.cache;
941
- const cached = cache.peekRequest(identifier);
942
- if (cached?.response) {
943
- const date = cached.response.headers.get('date');
944
- if (!date) {
945
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
946
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
947
- // eslint-disable-next-line no-console
948
- console.log(`CachePolicy: ${identifier.lid} is STALE because no date header was found`);
949
- }
950
- }
951
- return true;
952
- } else {
953
- const time = new Date(date).getTime();
954
- const now = Date.now();
955
- const deadline = time + this.config.apiCacheSoftExpires;
956
- const result = now >= deadline;
957
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
958
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
959
- // eslint-disable-next-line no-console
960
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'STALE' : 'NOT stale'}. Expiration time: ${deadline}, now: ${now}`);
961
- }
962
- }
963
- return result;
964
- }
965
- }
966
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
967
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
968
- // eslint-disable-next-line no-console
969
- console.log(`CachePolicy: ${identifier.lid} is STALE because no cache entry was found`);
970
- }
971
- }
972
- return true;
973
- }
974
- }
975
- class LifetimesService extends CachePolicy {
45
+ class LifetimesService extends DefaultCachePolicy {
976
46
  constructor(config) {
977
47
  deprecate(`\`import { LifetimesService } from '@ember-data/request-utils';\` is deprecated, please use \`import { CachePolicy } from '@ember-data/request-utils';\` instead.`, false, {
978
48
  id: 'ember-data:deprecate-lifetimes-service-import',
@@ -986,4 +56,5 @@ class LifetimesService extends CachePolicy {
986
56
  super(config);
987
57
  }
988
58
  }
989
- export { CachePolicy, LifetimesService, buildBaseURL, buildQueryParams, filterEmpty, parseCacheControl, setBuildURLConfig, sortQueryParams };
59
+
60
+ export { LifetimesService };