@ember-data/request-utils 5.4.0-alpha.13 → 5.4.0-alpha.131

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.
package/dist/index.js ADDED
@@ -0,0 +1,775 @@
1
+ import { deprecate } from '@ember/debug';
2
+ import { macroCondition, getGlobalConfig } from '@embroider/macros';
3
+
4
+ /**
5
+ * Simple utility function to assist in url building,
6
+ * query params, and other common request operations.
7
+ *
8
+ * These primitives may be used directly or composed
9
+ * by request builders to provide a consistent interface
10
+ * for building requests.
11
+ *
12
+ * For instance:
13
+ *
14
+ * ```ts
15
+ * import { buildBaseURL, buildQueryParams } from '@ember-data/request-utils';
16
+ *
17
+ * const baseURL = buildBaseURL({
18
+ * host: 'https://api.example.com',
19
+ * namespace: 'api/v1',
20
+ * resourcePath: 'emberDevelopers',
21
+ * op: 'query',
22
+ * identifier: { type: 'ember-developer' }
23
+ * });
24
+ * const url = `${baseURL}?${buildQueryParams({ name: 'Chris', include:['pets'] })}`;
25
+ * // => 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris'
26
+ * ```
27
+ *
28
+ * This is useful, but not as useful as the REST request builder for query which is sugar
29
+ * over this (and more!):
30
+ *
31
+ * ```ts
32
+ * import { query } from '@ember-data/rest/request';
33
+ *
34
+ * const options = query('ember-developer', { name: 'Chris', include:['pets'] });
35
+ * // => { url: 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris' }
36
+ * // Note: options will also include other request options like headers, method, etc.
37
+ * ```
38
+ *
39
+ * @module @ember-data/request-utils
40
+ * @main @ember-data/request-utils
41
+ * @public
42
+ */
43
+ // prevents the final constructed object from needing to add
44
+ // host and namespace which are provided by the final consuming
45
+ // class to the prototype which can result in overwrite errors
46
+ const CONFIG = {
47
+ host: '',
48
+ namespace: ''
49
+ };
50
+
51
+ /**
52
+ * Sets the global configuration for `buildBaseURL`
53
+ * for host and namespace values for the application.
54
+ *
55
+ * These values may still be overridden by passing
56
+ * them to buildBaseURL directly.
57
+ *
58
+ * This method may be called as many times as needed.
59
+ * host values of `''` or `'/'` are equivalent.
60
+ *
61
+ * Except for the value of `/` as host, host should not
62
+ * end with `/`.
63
+ *
64
+ * namespace should not start or end with a `/`.
65
+ *
66
+ * ```ts
67
+ * type BuildURLConfig = {
68
+ * host: string;
69
+ * namespace: string'
70
+ * }
71
+ * ```
72
+ *
73
+ * Example:
74
+ *
75
+ * ```ts
76
+ * import { setBuildURLConfig } from '@ember-data/request-utils';
77
+ *
78
+ * setBuildURLConfig({
79
+ * host: 'https://api.example.com',
80
+ * namespace: 'api/v1'
81
+ * });
82
+ * ```
83
+ *
84
+ * @method setBuildURLConfig
85
+ * @static
86
+ * @public
87
+ * @for @ember-data/request-utils
88
+ * @param {BuildURLConfig} config
89
+ * @return void
90
+ */
91
+ function setBuildURLConfig(config) {
92
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
93
+ if (!test) {
94
+ throw new Error(`setBuildURLConfig: You must pass a config object`);
95
+ }
96
+ })(config) : {};
97
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
98
+ if (!test) {
99
+ throw new Error(`setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`);
100
+ }
101
+ })('host' in config || 'namespace' in config) : {};
102
+ CONFIG.host = config.host || '';
103
+ CONFIG.namespace = config.namespace || '';
104
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
105
+ if (!test) {
106
+ throw new Error(`buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`);
107
+ }
108
+ })(CONFIG.host === '/' || !CONFIG.host.endsWith('/')) : {};
109
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
110
+ if (!test) {
111
+ throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`);
112
+ }
113
+ })(!CONFIG.namespace.startsWith('/')) : {};
114
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
115
+ if (!test) {
116
+ throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`);
117
+ }
118
+ })(!CONFIG.namespace.endsWith('/')) : {};
119
+ }
120
+ const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
121
+ function isOperationWithPrimaryRecord(options) {
122
+ return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
123
+ }
124
+ function hasResourcePath(options) {
125
+ return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;
126
+ }
127
+ function resourcePathForType(options) {
128
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
129
+ if (!test) {
130
+ throw new Error(`resourcePathForType: You must pass a valid op as part of options`);
131
+ }
132
+ })('op' in options && typeof options.op === 'string') : {};
133
+ return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
134
+ }
135
+
136
+ /**
137
+ * Builds a URL for a request based on the provided options.
138
+ * Does not include support for building query params (see `buildQueryParams`)
139
+ * so that it may be composed cleanly with other query-params strategies.
140
+ *
141
+ * Usage:
142
+ *
143
+ * ```ts
144
+ * import { buildBaseURL } from '@ember-data/request-utils';
145
+ *
146
+ * const url = buildBaseURL({
147
+ * host: 'https://api.example.com',
148
+ * namespace: 'api/v1',
149
+ * resourcePath: 'emberDevelopers',
150
+ * op: 'query',
151
+ * identifier: { type: 'ember-developer' }
152
+ * });
153
+ *
154
+ * // => 'https://api.example.com/api/v1/emberDevelopers'
155
+ * ```
156
+ *
157
+ * On the surface this may seem like a lot of work to do something simple, but
158
+ * it is designed to be composable with other utilities and interfaces that the
159
+ * average product engineer will never need to see or use.
160
+ *
161
+ * A few notes:
162
+ *
163
+ * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
164
+ * - `host` and `namespace` are optional, but if they are not provided, the values globally
165
+ * configured via `setBuildURLConfig` will be used.
166
+ * - `op` is required and must be one of the following:
167
+ * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
168
+ * - Depending on the value of `op`, `identifier` or `identifiers` will be required.
169
+ *
170
+ * @method buildBaseURL
171
+ * @static
172
+ * @public
173
+ * @for @ember-data/request-utils
174
+ * @param urlOptions
175
+ * @return string
176
+ */
177
+ function buildBaseURL(urlOptions) {
178
+ const options = Object.assign({
179
+ host: CONFIG.host,
180
+ namespace: CONFIG.namespace
181
+ }, urlOptions);
182
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
183
+ if (!test) {
184
+ throw new Error(`buildBaseURL: You must pass \`op\` as part of options`);
185
+ }
186
+ })(hasResourcePath(options) || typeof options.op === 'string' && options.op.length > 0) : {};
187
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
188
+ if (!test) {
189
+ throw new Error(`buildBaseURL: You must pass \`identifier\` as part of options`);
190
+ }
191
+ })(hasResourcePath(options) || options.op === 'findMany' || options.identifier && typeof options.identifier === 'object') : {};
192
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
193
+ if (!test) {
194
+ throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
195
+ }
196
+ })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object')) : {};
197
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
198
+ if (!test) {
199
+ throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`);
200
+ }
201
+ })(hasResourcePath(options) || !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0) : {};
202
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
203
+ if (!test) {
204
+ throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
205
+ }
206
+ })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0)) : {};
207
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
208
+ if (!test) {
209
+ throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`);
210
+ }
211
+ })(hasResourcePath(options) || options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0) : {};
212
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
213
+ if (!test) {
214
+ throw new Error(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`);
215
+ }
216
+ })(hasResourcePath(options) || options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0) : {};
217
+
218
+ // prettier-ignore
219
+ const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
220
+ const resourcePath = options.resourcePath || resourcePathForType(options);
221
+ const {
222
+ host,
223
+ namespace
224
+ } = options;
225
+ const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
226
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
227
+ if (!test) {
228
+ 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('","')}".`);
229
+ }
230
+ })(hasResourcePath(options) || ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op)) : {};
231
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
232
+ if (!test) {
233
+ throw new Error(`buildBaseURL: host must NOT end with '/', received '${host}'`);
234
+ }
235
+ })(host === '/' || !host.endsWith('/')) : {};
236
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
237
+ if (!test) {
238
+ throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`);
239
+ }
240
+ })(!namespace.startsWith('/')) : {};
241
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
242
+ if (!test) {
243
+ throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`);
244
+ }
245
+ })(!namespace.endsWith('/')) : {};
246
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
247
+ if (!test) {
248
+ throw new Error(`buildBaseURL: resourcePath must NOT start with '/', received '${resourcePath}'`);
249
+ }
250
+ })(!resourcePath.startsWith('/')) : {};
251
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
252
+ if (!test) {
253
+ throw new Error(`buildBaseURL: resourcePath must NOT end with '/', received '${resourcePath}'`);
254
+ }
255
+ })(!resourcePath.endsWith('/')) : {};
256
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
257
+ if (!test) {
258
+ throw new Error(`buildBaseURL: fieldPath must NOT start with '/', received '${fieldPath}'`);
259
+ }
260
+ })(!fieldPath.startsWith('/')) : {};
261
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
262
+ if (!test) {
263
+ throw new Error(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`);
264
+ }
265
+ })(!fieldPath.endsWith('/')) : {};
266
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
267
+ if (!test) {
268
+ throw new Error(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`);
269
+ }
270
+ })(!idPath.startsWith('/')) : {};
271
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
272
+ if (!test) {
273
+ throw new Error(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`);
274
+ }
275
+ })(!idPath.endsWith('/')) : {};
276
+ const hasHost = host !== '' && host !== '/';
277
+ const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
278
+ return hasHost ? url : `/${url}`;
279
+ }
280
+ const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
281
+ arrayFormat: 'comma'
282
+ };
283
+ function handleInclude(include) {
284
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
285
+ if (!test) {
286
+ throw new Error(`Expected include to be a string or array, got ${typeof include}`);
287
+ }
288
+ })(typeof include === 'string' || Array.isArray(include)) : {};
289
+ return typeof include === 'string' ? include.split(',') : include;
290
+ }
291
+
292
+ /**
293
+ * filter out keys of an object that have falsy values or point to empty arrays
294
+ * returning a new object with only those keys that have truthy values / non-empty arrays
295
+ *
296
+ * @method filterEmpty
297
+ * @static
298
+ * @public
299
+ * @for @ember-data/request-utils
300
+ * @param {Record<string, Serializable>} source object to filter keys with empty values from
301
+ * @return {Record<string, Serializable>} A new object with the keys that contained empty values removed
302
+ */
303
+ function filterEmpty(source) {
304
+ const result = {};
305
+ for (const key in source) {
306
+ const value = source[key];
307
+ // Allow `0` and `false` but filter falsy values that indicate "empty"
308
+ if (value !== undefined && value !== null && value !== '') {
309
+ if (!Array.isArray(value) || value.length > 0) {
310
+ result[key] = source[key];
311
+ }
312
+ }
313
+ }
314
+ return result;
315
+ }
316
+
317
+ /**
318
+ * Sorts query params by both key and value returning a new URLSearchParams
319
+ * object with the keys inserted in sorted order.
320
+ *
321
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
322
+ *
323
+ * Options:
324
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
325
+ *
326
+ * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
327
+ * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
328
+ * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
329
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
330
+ *
331
+ * @method sortQueryParams
332
+ * @static
333
+ * @public
334
+ * @for @ember-data/request-utils
335
+ * @param {URLSearchParams | object} params
336
+ * @param {object} options
337
+ * @return {URLSearchParams} A URLSearchParams with keys inserted in sorted order
338
+ */
339
+ function sortQueryParams(params, options) {
340
+ const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
341
+ const paramsIsObject = !(params instanceof URLSearchParams);
342
+ const urlParams = new URLSearchParams();
343
+ const dictionaryParams = paramsIsObject ? params : {};
344
+ if (!paramsIsObject) {
345
+ params.forEach((value, key) => {
346
+ const hasExisting = key in dictionaryParams;
347
+ if (!hasExisting) {
348
+ dictionaryParams[key] = value;
349
+ } else {
350
+ const existingValue = dictionaryParams[key];
351
+ if (Array.isArray(existingValue)) {
352
+ existingValue.push(value);
353
+ } else {
354
+ dictionaryParams[key] = [existingValue, value];
355
+ }
356
+ }
357
+ });
358
+ }
359
+ if ('include' in dictionaryParams) {
360
+ dictionaryParams.include = handleInclude(dictionaryParams.include);
361
+ }
362
+ const sortedKeys = Object.keys(dictionaryParams).sort();
363
+ sortedKeys.forEach(key => {
364
+ const value = dictionaryParams[key];
365
+ if (Array.isArray(value)) {
366
+ value.sort();
367
+ switch (opts.arrayFormat) {
368
+ case 'indices':
369
+ value.forEach((v, i) => {
370
+ urlParams.append(`${key}[${i}]`, String(v));
371
+ });
372
+ return;
373
+ case 'bracket':
374
+ value.forEach(v => {
375
+ urlParams.append(`${key}[]`, String(v));
376
+ });
377
+ return;
378
+ case 'repeat':
379
+ value.forEach(v => {
380
+ urlParams.append(key, String(v));
381
+ });
382
+ return;
383
+ case 'comma':
384
+ default:
385
+ urlParams.append(key, value.join(','));
386
+ return;
387
+ }
388
+ } else {
389
+ urlParams.append(key, String(value));
390
+ }
391
+ });
392
+ return urlParams;
393
+ }
394
+
395
+ /**
396
+ * Sorts query params by both key and value, returning a query params string
397
+ *
398
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
399
+ *
400
+ * Options:
401
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
402
+ *
403
+ * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
404
+ * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
405
+ * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
406
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
407
+ *
408
+ * @method buildQueryParams
409
+ * @static
410
+ * @public
411
+ * @for @ember-data/request-utils
412
+ * @param {URLSearchParams | object} params
413
+ * @param {object} [options]
414
+ * @return {string} A sorted query params string without the leading `?`
415
+ */
416
+ function buildQueryParams(params, options) {
417
+ return sortQueryParams(params, options).toString();
418
+ }
419
+ const NUMERIC_KEYS = new Set(['max-age', 's-maxage', 'stale-if-error', 'stale-while-revalidate']);
420
+
421
+ /**
422
+ * Parses a string Cache-Control header value into an object with the following structure:
423
+ *
424
+ * ```ts
425
+ * interface CacheControlValue {
426
+ * immutable?: boolean;
427
+ * 'max-age'?: number;
428
+ * 'must-revalidate'?: boolean;
429
+ * 'must-understand'?: boolean;
430
+ * 'no-cache'?: boolean;
431
+ * 'no-store'?: boolean;
432
+ * 'no-transform'?: boolean;
433
+ * 'only-if-cached'?: boolean;
434
+ * private?: boolean;
435
+ * 'proxy-revalidate'?: boolean;
436
+ * public?: boolean;
437
+ * 's-maxage'?: number;
438
+ * 'stale-if-error'?: number;
439
+ * 'stale-while-revalidate'?: number;
440
+ * }
441
+ * ```
442
+ * @method parseCacheControl
443
+ * @static
444
+ * @public
445
+ * @for @ember-data/request-utils
446
+ * @param {string} header
447
+ * @return {CacheControlValue}
448
+ */
449
+ function parseCacheControl(header) {
450
+ let key = '';
451
+ let value = '';
452
+ let isParsingKey = true;
453
+ const cacheControlValue = {};
454
+ function parseCacheControlValue(stringToParse) {
455
+ const parsedValue = Number.parseInt(stringToParse);
456
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
457
+ if (!test) {
458
+ throw new Error(`Invalid Cache-Control value, expected a number but got - ${stringToParse}`);
459
+ }
460
+ })(!Number.isNaN(parsedValue)) : {};
461
+ return parsedValue;
462
+ }
463
+ for (let i = 0; i < header.length; i++) {
464
+ const char = header.charAt(i);
465
+ if (char === ',') {
466
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
467
+ if (!test) {
468
+ throw new Error(`Invalid Cache-Control value, expected a value`);
469
+ }
470
+ })(!isParsingKey || !NUMERIC_KEYS.has(key)) : {};
471
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
472
+ if (!test) {
473
+ throw new Error(`Invalid Cache-Control value, expected a value after "=" but got ","`);
474
+ }
475
+ })(i === 0 || header.charAt(i - 1) !== '=') : {};
476
+ isParsingKey = true;
477
+ // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
478
+ cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
479
+ key = '';
480
+ value = '';
481
+ continue;
482
+ } else if (char === '=') {
483
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
484
+ if (!test) {
485
+ throw new Error(`Invalid Cache-Control value, expected a value after "="`);
486
+ }
487
+ })(i + 1 !== header.length) : {};
488
+ isParsingKey = false;
489
+ } else if (char === ' ' || char === `\t` || char === `\n`) {
490
+ continue;
491
+ } else if (isParsingKey) {
492
+ key += char;
493
+ } else {
494
+ value += char;
495
+ }
496
+ if (i === header.length - 1) {
497
+ // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
498
+ cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
499
+ }
500
+ }
501
+ return cacheControlValue;
502
+ }
503
+ function isStale(headers, expirationTime) {
504
+ // const age = headers.get('age');
505
+ // const cacheControl = parseCacheControl(headers.get('cache-control') || '');
506
+ // const expires = headers.get('expires');
507
+ // const lastModified = headers.get('last-modified');
508
+ const date = headers.get('date');
509
+ if (!date) {
510
+ return true;
511
+ }
512
+ const time = new Date(date).getTime();
513
+ const now = Date.now();
514
+ const deadline = time + expirationTime;
515
+ const result = now > deadline;
516
+ return result;
517
+ }
518
+ /**
519
+ * A basic CachePolicy that can be added to the Store service.
520
+ *
521
+ * Determines staleness based on time since the request was last received from the API
522
+ * using the `date` header.
523
+ *
524
+ * Invalidates any request for which `cacheOptions.types` was provided when a createRecord
525
+ * request for that type is successful.
526
+ *
527
+ * For this to work, the `createRecord` request must include the `cacheOptions.types` array
528
+ * with the types that should be invalidated, or its request should specify the identifiers
529
+ * of the records that are being created via `records`. Providing both is valid.
530
+ *
531
+ * > [!NOTE]
532
+ * > only requests that had specified `cacheOptions.types` and occurred prior to the
533
+ * > createRecord request will be invalidated. This means that a given request should always
534
+ * > specify the types that would invalidate it to opt into this behavior. Abstracting this
535
+ * > behavior via builders is recommended to ensure consistency.
536
+ *
537
+ * This allows the Store's CacheHandler to determine if a request is expired and
538
+ * should be refetched upon next request.
539
+ *
540
+ * The `Fetch` handler provided by `@ember-data/request/fetch` will automatically
541
+ * add the `date` header to responses if it is not present.
542
+ *
543
+ * > [!NOTE]
544
+ * > Date headers do not have millisecond precision, so expiration times should
545
+ * > generally be larger than 1000ms.
546
+ *
547
+ * Usage:
548
+ *
549
+ * ```ts
550
+ * import { CachePolicy } from '@ember-data/request-utils';
551
+ * import DataStore from '@ember-data/store';
552
+ *
553
+ * // ...
554
+ *
555
+ * export class Store extends DataStore {
556
+ * constructor(args) {
557
+ * super(args);
558
+ * this.lifetimes = new CachePolicy({ apiCacheSoftExpires: 30_000, apiCacheHardExpires: 60_000 });
559
+ * }
560
+ * }
561
+ * ```
562
+ *
563
+ * @class CachePolicy
564
+ * @public
565
+ * @module @ember-data/request-utils
566
+ */
567
+ class CachePolicy {
568
+ _getStore(store) {
569
+ let set = this._stores.get(store);
570
+ if (!set) {
571
+ set = {
572
+ invalidated: new Set(),
573
+ types: new Map()
574
+ };
575
+ this._stores.set(store, set);
576
+ }
577
+ return set;
578
+ }
579
+ constructor(config) {
580
+ this._stores = new WeakMap();
581
+ const _config = arguments.length === 1 ? config : arguments[1];
582
+ deprecate(`Passing a Store to the CachePolicy is deprecated, please pass only a config instead.`, arguments.length === 1, {
583
+ id: 'ember-data:request-utils:lifetimes-service-store-arg',
584
+ since: {
585
+ enabled: '5.4',
586
+ available: '4.13'
587
+ },
588
+ for: '@ember-data/request-utils',
589
+ until: '6.0'
590
+ });
591
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
592
+ if (!test) {
593
+ throw new Error(`You must pass a config to the CachePolicy`);
594
+ }
595
+ })(_config) : {};
596
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
597
+ if (!test) {
598
+ throw new Error(`You must pass a apiCacheSoftExpires to the CachePolicy`);
599
+ }
600
+ })(typeof _config.apiCacheSoftExpires === 'number') : {};
601
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
602
+ if (!test) {
603
+ throw new Error(`You must pass a apiCacheHardExpires to the CachePolicy`);
604
+ }
605
+ })(typeof _config.apiCacheHardExpires === 'number') : {};
606
+ this.config = _config;
607
+ }
608
+
609
+ /**
610
+ * Invalidate a request by its identifier for a given store instance.
611
+ *
612
+ * While the store argument may seem redundant, the CachePolicy
613
+ * is designed to be shared across multiple stores / forks
614
+ * of the store.
615
+ *
616
+ * ```ts
617
+ * store.lifetimes.invalidateRequest(store, identifier);
618
+ * ```
619
+ *
620
+ * @method invalidateRequest
621
+ * @public
622
+ * @param {StableDocumentIdentifier} identifier
623
+ * @param {Store} store
624
+ */
625
+ invalidateRequest(identifier, store) {
626
+ this._getStore(store).invalidated.add(identifier);
627
+ }
628
+
629
+ /**
630
+ * Invalidate all requests associated to a specific type
631
+ * for a given store instance.
632
+ *
633
+ * While the store argument may seem redundant, the CachePolicy
634
+ * is designed to be shared across multiple stores / forks
635
+ * of the store.
636
+ *
637
+ * This invalidation is done automatically when using this service
638
+ * for both the CacheHandler and the LegacyNetworkHandler.
639
+ *
640
+ * ```ts
641
+ * store.lifetimes.invalidateRequestsForType(store, 'person');
642
+ * ```
643
+ *
644
+ * @method invalidateRequestsForType
645
+ * @public
646
+ * @param {string} type
647
+ * @param {Store} store
648
+ */
649
+ invalidateRequestsForType(type, store) {
650
+ const storeCache = this._getStore(store);
651
+ const set = storeCache.types.get(type);
652
+ const notifications = store.notifications;
653
+ if (set) {
654
+ // TODO batch notifications
655
+ set.forEach(id => {
656
+ storeCache.invalidated.add(id);
657
+ notifications.notify(id, 'invalidated');
658
+ });
659
+ }
660
+ }
661
+
662
+ /**
663
+ * Invoked when a request has been fulfilled from the configured request handlers.
664
+ * This is invoked by the CacheHandler for both foreground and background requests
665
+ * once the cache has been updated.
666
+ *
667
+ * Note, this is invoked by the CacheHandler regardless of whether
668
+ * the request has a cache-key.
669
+ *
670
+ * This method should not be invoked directly by consumers.
671
+ *
672
+ * @method didRequest
673
+ * @public
674
+ * @param {ImmutableRequestInfo} request
675
+ * @param {ImmutableResponse} response
676
+ * @param {Store} store
677
+ * @param {StableDocumentIdentifier | null} identifier
678
+ * @return {void}
679
+ */
680
+ didRequest(request, response, identifier, store) {
681
+ // if this is a successful createRecord request, invalidate the cacheKey for the type
682
+ if (request.op === 'createRecord') {
683
+ const statusNumber = response?.status ?? 0;
684
+ if (statusNumber >= 200 && statusNumber < 400) {
685
+ const types = new Set(request.records?.map(r => r.type));
686
+ const additionalTypes = request.cacheOptions?.types;
687
+ additionalTypes?.forEach(type => {
688
+ types.add(type);
689
+ });
690
+ types.forEach(type => {
691
+ this.invalidateRequestsForType(type, store);
692
+ });
693
+ }
694
+
695
+ // add this document's cacheKey to a map for all associated types
696
+ // it is recommended to only use this for queries
697
+ } else if (identifier && request.cacheOptions?.types?.length) {
698
+ const storeCache = this._getStore(store);
699
+ request.cacheOptions?.types.forEach(type => {
700
+ const set = storeCache.types.get(type);
701
+ if (set) {
702
+ set.add(identifier);
703
+ storeCache.invalidated.delete(identifier);
704
+ } else {
705
+ storeCache.types.set(type, new Set([identifier]));
706
+ }
707
+ });
708
+ }
709
+ }
710
+
711
+ /**
712
+ * Invoked to determine if the request may be fulfilled from cache
713
+ * if possible.
714
+ *
715
+ * Note, this is only invoked by the CacheHandler if the request has
716
+ * a cache-key.
717
+ *
718
+ * If no cache entry is found or the entry is hard expired,
719
+ * the request will be fulfilled from the configured request handlers
720
+ * and the cache will be updated before returning the response.
721
+ *
722
+ * @method isHardExpired
723
+ * @public
724
+ * @param {StableDocumentIdentifier} identifier
725
+ * @param {Store} store
726
+ * @return {boolean} true if the request is considered hard expired
727
+ */
728
+ isHardExpired(identifier, store) {
729
+ // if we are explicitly invalidated, we are hard expired
730
+ const storeCache = this._getStore(store);
731
+ if (storeCache.invalidated.has(identifier)) {
732
+ return true;
733
+ }
734
+ const cache = store.cache;
735
+ const cached = cache.peekRequest(identifier);
736
+ return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheHardExpires);
737
+ }
738
+
739
+ /**
740
+ * Invoked if `isHardExpired` is false to determine if the request
741
+ * should be update behind the scenes if cache data is already available.
742
+ *
743
+ * Note, this is only invoked by the CacheHandler if the request has
744
+ * a cache-key.
745
+ *
746
+ * If true, the request will be fulfilled from cache while a backgrounded
747
+ * request is made to update the cache via the configured request handlers.
748
+ *
749
+ * @method isSoftExpired
750
+ * @public
751
+ * @param {StableDocumentIdentifier} identifier
752
+ * @param {Store} store
753
+ * @return {boolean} true if the request is considered soft expired
754
+ */
755
+ isSoftExpired(identifier, store) {
756
+ const cache = store.cache;
757
+ const cached = cache.peekRequest(identifier);
758
+ return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheSoftExpires);
759
+ }
760
+ }
761
+ class LifetimesService extends CachePolicy {
762
+ constructor(config) {
763
+ deprecate(`\`import { LifetimesService } from '@ember-data/request-utils';\` is deprecated, please use \`import { CachePolicy } from '@ember-data/request-utils';\` instead.`, false, {
764
+ id: 'ember-data:deprecate-lifetimes-service-import',
765
+ since: {
766
+ enabled: '5.4',
767
+ available: '4.13'
768
+ },
769
+ for: 'ember-data',
770
+ until: '6.0'
771
+ });
772
+ super(config);
773
+ }
774
+ }
775
+ export { CachePolicy, LifetimesService, buildBaseURL, buildQueryParams, filterEmpty, parseCacheControl, setBuildURLConfig, sortQueryParams };