@warp-drive-mirror/utilities 5.8.0-alpha.9 → 5.8.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 (72) hide show
  1. package/README.md +14 -26
  2. package/declarations/-private/active-record/find-record.d.ts +5 -6
  3. package/declarations/-private/active-record/query.d.ts +2 -2
  4. package/declarations/-private/active-record/save-record.d.ts +2 -2
  5. package/declarations/-private/json-api/find-record.d.ts +37 -18
  6. package/declarations/-private/json-api/query.d.ts +3 -6
  7. package/declarations/-private/json-api/save-record.d.ts +45 -10
  8. package/declarations/-private/json-api/serialize.d.ts +15 -1
  9. package/declarations/-private/rest/find-record.d.ts +5 -8
  10. package/declarations/-private/rest/query.d.ts +2 -2
  11. package/declarations/-private/rest/save-record.d.ts +2 -2
  12. package/dist/active-record.js +2 -0
  13. package/dist/json-api.js +94 -26
  14. package/dist/rest.js +2 -2
  15. package/dist/string.js +428 -1
  16. package/dist/unpkg/dev/-private.js +7 -0
  17. package/dist/unpkg/dev/active-record.js +394 -0
  18. package/dist/unpkg/dev/builder-utils-Donkk-BZ.js +22 -0
  19. package/dist/unpkg/dev/derivations.js +30 -0
  20. package/dist/unpkg/dev/handlers.js +316 -0
  21. package/dist/unpkg/dev/index.js +362 -0
  22. package/dist/unpkg/dev/inflect-BEv8WqY1.js +343 -0
  23. package/dist/unpkg/dev/json-api.js +740 -0
  24. package/dist/unpkg/dev/rest.js +392 -0
  25. package/dist/unpkg/dev/string.js +1 -0
  26. package/dist/unpkg/dev-deprecated/-private.js +7 -0
  27. package/dist/unpkg/dev-deprecated/active-record.js +394 -0
  28. package/dist/unpkg/dev-deprecated/builder-utils-Donkk-BZ.js +22 -0
  29. package/dist/unpkg/dev-deprecated/derivations.js +30 -0
  30. package/dist/unpkg/dev-deprecated/handlers.js +316 -0
  31. package/dist/unpkg/dev-deprecated/index.js +362 -0
  32. package/dist/unpkg/dev-deprecated/inflect-BEv8WqY1.js +343 -0
  33. package/dist/unpkg/dev-deprecated/json-api.js +740 -0
  34. package/dist/unpkg/dev-deprecated/rest.js +392 -0
  35. package/dist/unpkg/dev-deprecated/string.js +1 -0
  36. package/dist/unpkg/prod/-private.js +7 -0
  37. package/dist/unpkg/prod/active-record.js +366 -0
  38. package/dist/unpkg/prod/builder-utils-Donkk-BZ.js +22 -0
  39. package/dist/unpkg/prod/derivations.js +30 -0
  40. package/dist/unpkg/prod/handlers.js +305 -0
  41. package/dist/unpkg/prod/index.js +239 -0
  42. package/dist/unpkg/prod/inflect-Dh9dyEYx.js +333 -0
  43. package/dist/unpkg/prod/json-api.js +702 -0
  44. package/dist/unpkg/prod/rest.js +364 -0
  45. package/dist/unpkg/prod/string.js +1 -0
  46. package/dist/unpkg/prod-deprecated/-private.js +7 -0
  47. package/dist/unpkg/prod-deprecated/active-record.js +366 -0
  48. package/dist/unpkg/prod-deprecated/builder-utils-Donkk-BZ.js +22 -0
  49. package/dist/unpkg/prod-deprecated/derivations.js +30 -0
  50. package/dist/unpkg/prod-deprecated/handlers.js +305 -0
  51. package/dist/unpkg/prod-deprecated/index.js +239 -0
  52. package/dist/unpkg/prod-deprecated/inflect-Dh9dyEYx.js +333 -0
  53. package/dist/unpkg/prod-deprecated/json-api.js +702 -0
  54. package/dist/unpkg/prod-deprecated/rest.js +364 -0
  55. package/dist/unpkg/prod-deprecated/string.js +1 -0
  56. package/logos/README.md +2 -2
  57. package/logos/logo-yellow-slab.svg +1 -0
  58. package/logos/word-mark-black.svg +1 -0
  59. package/logos/word-mark-white.svg +1 -0
  60. package/package.json +12 -4
  61. package/logos/NCC-1701-a-blue.svg +0 -4
  62. package/logos/NCC-1701-a-gold.svg +0 -4
  63. package/logos/NCC-1701-a-gold_100.svg +0 -1
  64. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  65. package/logos/NCC-1701-a.svg +0 -4
  66. package/logos/docs-badge.svg +0 -2
  67. package/logos/ember-data-logo-dark.svg +0 -12
  68. package/logos/ember-data-logo-light.svg +0 -12
  69. package/logos/social1.png +0 -0
  70. package/logos/social2.png +0 -0
  71. package/logos/warp-drive-logo-dark.svg +0 -4
  72. package/logos/warp-drive-logo-gold.svg +0 -4
@@ -0,0 +1,702 @@
1
+ import { setBuildURLConfig as setBuildURLConfig$1, buildBaseURL, buildQueryParams } from './index.js';
2
+ import { p as pluralize } from "./inflect-Dh9dyEYx.js";
3
+ import { e as extractCacheOptions, c as copyForwardUrlOptions } from "./builder-utils-Donkk-BZ.js";
4
+ import { recordIdentifierFor } from '@warp-drive-mirror/core';
5
+ const JsonApiAccept = 'application/vnd.api+json';
6
+ const DEFAULT_CONFIG = {
7
+ host: '',
8
+ namespace: ''
9
+ };
10
+ let ACCEPT_HEADER_VALUE = 'application/vnd.api+json';
11
+
12
+ /**
13
+ * Allows setting extensions and profiles to be used in the `Accept` header.
14
+ *
15
+ * Extensions and profiles are keyed by their namespace with the value being
16
+ * their URI.
17
+ *
18
+ * Example:
19
+ *
20
+ * ```ts
21
+ * setBuildURLConfig({
22
+ * extensions: {
23
+ * atomic: 'https://jsonapi.org/ext/atomic'
24
+ * },
25
+ * profiles: {
26
+ * pagination: 'https://jsonapi.org/profiles/ethanresnick/cursor-pagination'
27
+ * }
28
+ * });
29
+ * ```
30
+ *
31
+ * This also sets the global configuration for `buildBaseURL`
32
+ * for host and namespace values for the global coniguration
33
+ * done via `import { setBuildURLConfig } from '@warp-drive-mirror/utilities';`
34
+ *
35
+ * These values may still be overridden by passing
36
+ * them to buildBaseURL directly.
37
+ *
38
+ * This method may be called as many times as needed
39
+ *
40
+ * ```ts
41
+ * type BuildURLConfig = {
42
+ * host: string;
43
+ * namespace: string'
44
+ * }
45
+ * ```
46
+ *
47
+ * @public
48
+ * @param {BuildURLConfig} config
49
+ * @return {void}
50
+ */
51
+ function setBuildURLConfig(config) {
52
+ Object.assign({}, DEFAULT_CONFIG, config);
53
+ if (config.profiles || config.extensions) {
54
+ let accept = JsonApiAccept;
55
+ if (config.profiles) {
56
+ const profiles = Object.values(config.profiles);
57
+ if (profiles.length) {
58
+ accept += ';profile="' + profiles.join(' ') + '"';
59
+ }
60
+ }
61
+ if (config.extensions) {
62
+ const extensions = Object.values(config.extensions);
63
+ if (extensions.length) {
64
+ accept += ';ext=' + extensions.join(' ');
65
+ }
66
+ }
67
+ ACCEPT_HEADER_VALUE = accept;
68
+ }
69
+ setBuildURLConfig$1(config);
70
+ }
71
+
72
+ /**
73
+ * Builds request options to fetch a single resource by a known id or identifier
74
+ * configured for the url and header expectations of most JSON:API APIs.
75
+ *
76
+ * :::tabs
77
+ *
78
+ * == Basic Usage
79
+ *
80
+ * ```ts
81
+ * import { findRecord } from '@warp-drive-mirror/utilities/json-api';
82
+ * import type { Person } from '#/data/types';
83
+ *
84
+ * const result = await store.request(
85
+ * findRecord<Person>('person', '1')
86
+ * );
87
+ * ```
88
+ *
89
+ * == With Options
90
+ *
91
+ * ```ts
92
+ * import { findRecord } from '@warp-drive-mirror/utilities/json-api';
93
+ * import type { Person } from '#/data/types';
94
+ *
95
+ * const data = await store.request(
96
+ * findRecord<Person>(
97
+ * 'person', '1',
98
+ * { include: ['pets', 'friends'] }
99
+ * )
100
+ * );
101
+ * ```
102
+ *
103
+ * == With an Identifier
104
+ *
105
+ * ```ts
106
+ * import { findRecord } from '@warp-drive-mirror/utilities/json-api';
107
+ * import type { Person } from '#/data/types';
108
+ *
109
+ * const data = await store.request(
110
+ * findRecord<Person>(
111
+ * { type: 'person', id: '1' },
112
+ * { include: ['pets', 'friends'] }
113
+ * )
114
+ * );
115
+ * ```
116
+ *
117
+ * :::
118
+ *
119
+ * **Supplying Options to Modify the Request Behavior**
120
+ *
121
+ * The following options are supported:
122
+ *
123
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
124
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
125
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
126
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
127
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
128
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
129
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
130
+ * defaulting to `false` if none is configured.
131
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
132
+ *
133
+ * ```ts
134
+ * import { findRecord } from '@warp-drive-mirror/utilities/json-api';
135
+ *
136
+ * const data = await store.request(
137
+ * findRecord(
138
+ * 'person', '1',
139
+ * { include: ['pets', 'friends'] },
140
+ * { namespace: 'api/v2' }
141
+ * )
142
+ * );
143
+ * ```
144
+ *
145
+ * @public
146
+ */
147
+
148
+ function findRecord(arg1, arg2, arg3) {
149
+ const identifier = typeof arg1 === 'string' ? {
150
+ type: arg1,
151
+ id: arg2
152
+ } : arg1;
153
+ const options = (typeof arg1 === 'string' ? arg3 : arg2) || {};
154
+ const cacheOptions = extractCacheOptions(options);
155
+ const urlOptions = {
156
+ identifier,
157
+ op: 'findRecord',
158
+ resourcePath: pluralize(identifier.type)
159
+ };
160
+ copyForwardUrlOptions(urlOptions, options);
161
+ const url = buildBaseURL(urlOptions);
162
+ const headers = new Headers();
163
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
164
+ return {
165
+ url: options.include?.length ? `${url}?${buildQueryParams({
166
+ include: options.include
167
+ }, options.urlParamsSettings)}` : url,
168
+ method: 'GET',
169
+ headers,
170
+ cacheOptions,
171
+ op: 'findRecord',
172
+ records: [identifier]
173
+ };
174
+ }
175
+
176
+ /** @deprecated use {@link ReactiveDataDocument} */
177
+
178
+ /**
179
+ * Builds request options to query for resources, usually by a primary
180
+ * type, configured for the url and header expectations of most JSON:API APIs.
181
+ *
182
+ * The key difference between this and `postQuery` is that this method will send the query
183
+ * as query params in the url of a "GET" request instead of as the JSON body of a "POST"
184
+ * request.
185
+ *
186
+ * **Basic Usage**
187
+ *
188
+ * ```ts
189
+ * import { query } from '@warp-drive-mirror/utilities/json-api';
190
+ *
191
+ * const data = await store.request(query('person'));
192
+ * ```
193
+ *
194
+ * **With Query Params**
195
+ *
196
+ * ```ts
197
+ * import { query } from '@warp-drive-mirror/utilities/json-api';
198
+ *
199
+ * const options = query('person', { include: ['pets', 'friends'] });
200
+ * const data = await store.request(options);
201
+ * ```
202
+ *
203
+ * **Supplying Options to Modify the Request Behavior**
204
+ *
205
+ * The following options are supported:
206
+ *
207
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
208
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
209
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
210
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
211
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
212
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
213
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
214
+ * defaulting to `false` if none is configured.
215
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
216
+ *
217
+ * ```ts
218
+ * import { query } from '@warp-drive-mirror/utilities/json-api';
219
+ *
220
+ * const options = query('person', { include: ['pets', 'friends'] }, { reload: true });
221
+ * const data = await store.request(options);
222
+ * ```
223
+ *
224
+ * @public
225
+ */
226
+
227
+ function query(type,
228
+ // eslint-disable-next-line @typescript-eslint/no-shadow
229
+ query = {}, options = {}) {
230
+ const cacheOptions = extractCacheOptions(options);
231
+ const urlOptions = {
232
+ identifier: {
233
+ type
234
+ },
235
+ op: 'query',
236
+ resourcePath: pluralize(type)
237
+ };
238
+ copyForwardUrlOptions(urlOptions, options);
239
+ const url = buildBaseURL(urlOptions);
240
+ const headers = new Headers();
241
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
242
+ const queryString = buildQueryParams(query, options.urlParamsSettings);
243
+ return {
244
+ url: queryString ? `${url}?${queryString}` : url,
245
+ method: 'GET',
246
+ headers,
247
+ cacheOptions,
248
+ op: 'query'
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Builds request options to query for resources, usually by a primary
254
+ * type, configured for the url and header expectations of most JSON:API APIs.
255
+ *
256
+ * The key difference between this and `query` is that this method will send the query
257
+ * as the JSON body of a "POST" request instead of as query params in the url of a "GET"
258
+ * request.
259
+ *
260
+ * A CacheKey is generated from the url and query params, and used to cache the response
261
+ * in the store.
262
+ *
263
+ * ```ts
264
+ * import { postQuery } from '@warp-drive-mirror/utilities/json-api';
265
+ *
266
+ * const options = postQuery('person', { include: ['pets', 'friends'] });
267
+ * const data = await store.request(options);
268
+ * ```
269
+ *
270
+ * **Supplying Options to Modify the Request Behavior**
271
+ *
272
+ * The following options are supported:
273
+ *
274
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
275
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
276
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
277
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
278
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
279
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
280
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
281
+ * defaulting to `false` if none is configured.
282
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
283
+ *
284
+ * ```ts
285
+ * import { postQuery } from '@warp-drive-mirror/utilities/json-api';
286
+ *
287
+ * const options = postQuery('person', { include: ['pets', 'friends'] }, { reload: true });
288
+ * const data = await store.request(options);
289
+ * ```
290
+ *
291
+ * @public
292
+ * @param identifier
293
+ * @param query
294
+ * @param options
295
+ */
296
+
297
+ function postQuery(type,
298
+ // eslint-disable-next-line @typescript-eslint/no-shadow
299
+ query = {}, options = {}) {
300
+ const cacheOptions = extractCacheOptions(options);
301
+ const urlOptions = {
302
+ identifier: {
303
+ type
304
+ },
305
+ op: 'query',
306
+ resourcePath: options.resourcePath ?? pluralize(type)
307
+ };
308
+ copyForwardUrlOptions(urlOptions, options);
309
+ const url = buildBaseURL(urlOptions);
310
+ const headers = new Headers();
311
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
312
+ const queryData = structuredClone(query);
313
+ cacheOptions.key = cacheOptions.key ?? `${url}?${buildQueryParams(queryData, options.urlParamsSettings)}`;
314
+ return {
315
+ url,
316
+ method: 'POST',
317
+ body: JSON.stringify(query),
318
+ headers,
319
+ cacheOptions: cacheOptions,
320
+ op: 'query'
321
+ };
322
+ }
323
+
324
+ /**
325
+ * :::warning ⚠️ **These Mutation Builders DO NOT Set The Request Body**
326
+ * While this may come as a surprise, the app providing the body ensures that only
327
+ * desired and correctly formatted data is sent with the request.
328
+ * :::
329
+ *
330
+ * Builds request options to delete record for resources,
331
+ * configured for the url, method and header expectations of most JSON:API APIs.
332
+ *
333
+ * **Basic Usage**
334
+ *
335
+ * ```ts
336
+ * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';
337
+ *
338
+ * const person = store.peekRecord('person', '1');
339
+ *
340
+ * // mark record as deleted
341
+ * store.deleteRecord(person);
342
+ *
343
+ * // persist deletion
344
+ * const data = await store.request(deleteRecord(person));
345
+ * ```
346
+ *
347
+ * **Supplying Options to Modify the Request Behavior**
348
+ *
349
+ * The following options are supported:
350
+ *
351
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
352
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
353
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
354
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
355
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
356
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
357
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
358
+ * defaulting to `false` if none is configured.
359
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
360
+ *
361
+ * ```ts
362
+ * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';
363
+ *
364
+ * const person = store.peekRecord('person', '1');
365
+ *
366
+ * // mark record as deleted
367
+ * store.deleteRecord(person);
368
+ *
369
+ * // persist deletion
370
+ * const options = deleteRecord(person, { namespace: 'api/v1' });
371
+ * const data = await store.request(options);
372
+ * ```
373
+ *
374
+ * @public
375
+ * @param record
376
+ * @param options
377
+ */
378
+
379
+ function deleteRecord(record, options = {}) {
380
+ const identifier = recordIdentifierFor(record);
381
+ const urlOptions = {
382
+ identifier: identifier,
383
+ op: 'deleteRecord',
384
+ resourcePath: pluralize(identifier.type)
385
+ };
386
+ copyForwardUrlOptions(urlOptions, options);
387
+ const url = buildBaseURL(urlOptions);
388
+ const headers = new Headers();
389
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
390
+ return {
391
+ url,
392
+ method: 'DELETE',
393
+ headers,
394
+ op: 'deleteRecord',
395
+ data: {
396
+ record: identifier
397
+ },
398
+ records: [identifier]
399
+ };
400
+ }
401
+
402
+ /**
403
+ * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**
404
+ * While this may come as a surprise, the app providing the body ensures that only
405
+ * desired and correctly formatted data is sent with the request.
406
+ * :::
407
+ *
408
+ * Builds request options to create new record for resources,
409
+ * configured for the url, method and header expectations of most JSON:API APIs.
410
+ *
411
+ * **Basic Usage**
412
+ *
413
+ * ```ts
414
+ * import { cacheKeyFor } from '@warp-drive-mirror/core';
415
+ * import { createRecord } from '@warp-drive-mirror/utilities/json-api';
416
+ * import type { Person } from '#/data/types';
417
+ *
418
+ * const person = store.createRecord<Person>('person', { name: 'Ted' });
419
+ * const init = createRecord(person);
420
+ * init.body = JSON.stringify(
421
+ * {
422
+ * // it's likely you will want to transform this data
423
+ * // somewhat
424
+ * data: store.cache.peek(cacheKeyFor(person))
425
+ * }
426
+ * );
427
+ * const data = await store.request(init);
428
+ * ```
429
+ *
430
+ * **Supplying Options to Modify the Request Behavior**
431
+ *
432
+ * The following options are supported:
433
+ *
434
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
435
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
436
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
437
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
438
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
439
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
440
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
441
+ * defaulting to `false` if none is configured.
442
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
443
+ *
444
+ * ```ts
445
+ * import { createRecord } from '@warp-drive-mirror/utilities/json-api';
446
+ *
447
+ * const person = store.createRecord('person', { name: 'Ted' });
448
+ * const options = createRecord(person, { namespace: 'api/v1' });
449
+ * const data = await store.request(options);
450
+ * ```
451
+ *
452
+ * @public
453
+ * @param record
454
+ * @param options
455
+ */
456
+
457
+ function createRecord(record, options = {}) {
458
+ const identifier = recordIdentifierFor(record);
459
+ const urlOptions = {
460
+ identifier: identifier,
461
+ op: 'createRecord',
462
+ resourcePath: pluralize(identifier.type)
463
+ };
464
+ copyForwardUrlOptions(urlOptions, options);
465
+ const url = buildBaseURL(urlOptions);
466
+ const headers = new Headers();
467
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
468
+ return {
469
+ url,
470
+ method: 'POST',
471
+ headers,
472
+ op: 'createRecord',
473
+ data: {
474
+ record: identifier
475
+ },
476
+ records: [identifier]
477
+ };
478
+ }
479
+
480
+ /**
481
+ * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**
482
+ * While this may come as a surprise, the app providing the body ensures that only
483
+ * desired and correctly formatted data is sent with the request.
484
+ * :::
485
+ *
486
+ * Builds request options to update existing record for resources,
487
+ * configured for the url, method and header expectations of most JSON:API APIs.
488
+ *
489
+ * **Example Usage**
490
+ *
491
+ * ```ts
492
+ * import { cacheKeyFor } from '@warp-drive-mirror/core';
493
+ * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';
494
+ * import type { EditablePerson } from '#/data/types';
495
+ *
496
+ * const mutable = await checkout<EditablePerson>(person);
497
+ * mutable.name = 'Chris';
498
+ * const init = updateRecord(mutable);
499
+ *
500
+ * init.body = JSON.stringify(
501
+ * // it's likely you will want to transform this data
502
+ * // somewhat, or serialize only specific properties instead
503
+ * serializePatch(store.cache, cacheKeyFor(mutable))
504
+ * );
505
+ * const data = await store.request(init);
506
+ * ```
507
+ *
508
+ *
509
+ * **Supplying Options to Modify the Request Behavior**
510
+ *
511
+ * The following options are supported:
512
+ *
513
+ * - `patch` - Allows caller to specify whether to use a PATCH request instead of a PUT request, defaults to `false`.
514
+ * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.
515
+ * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.
516
+ * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type
517
+ * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this
518
+ * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.
519
+ * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the
520
+ * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,
521
+ * defaulting to `false` if none is configured.
522
+ * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)
523
+ *
524
+ * ```ts
525
+ * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';
526
+ *
527
+ * const person = store.peekRecord('person', '1');
528
+ * person.name = 'Chris';
529
+ * const options = updateRecord(person, { patch: true });
530
+ * const data = await store.request(options);
531
+ * ```
532
+ *
533
+ * @public
534
+ * @param record
535
+ * @param options
536
+ */
537
+
538
+ function updateRecord(record, options = {}) {
539
+ const identifier = recordIdentifierFor(record);
540
+ const urlOptions = {
541
+ identifier: identifier,
542
+ op: 'updateRecord',
543
+ resourcePath: pluralize(identifier.type)
544
+ };
545
+ copyForwardUrlOptions(urlOptions, options);
546
+ const url = buildBaseURL(urlOptions);
547
+ const headers = new Headers();
548
+ headers.append('Accept', ACCEPT_HEADER_VALUE);
549
+ return {
550
+ url,
551
+ method: options.patch ? 'PATCH' : 'PUT',
552
+ headers,
553
+ op: 'updateRecord',
554
+ data: {
555
+ record: identifier
556
+ },
557
+ records: [identifier]
558
+ };
559
+ }
560
+
561
+ /**
562
+ * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**
563
+ *
564
+ * While this may come as a surprise, they are intended to serialize cache state for more
565
+ * generalized usage. {json:api} has a large variance in acceptable shapes, and only your
566
+ * app can ensure that the body is correctly formatted and contains all necessary data.
567
+ * :::
568
+ *
569
+ * Serializes the current state of a resource or array of resources for use with POST or PUT requests.
570
+ *
571
+ * @public
572
+ * @param {Cache} cache}
573
+ * @param {ResourceKey} identifier
574
+ * @return {Object} An object with a `data` property containing the serialized resource patch
575
+ */
576
+
577
+ function serializeResources(cache, identifiers) {
578
+ return {
579
+ data: Array.isArray(identifiers) ? identifiers.map(identifier => _serializeResource(cache, identifier)) : _serializeResource(cache, identifiers)
580
+ };
581
+ }
582
+ function fixRef({
583
+ id,
584
+ lid,
585
+ type
586
+ }) {
587
+ if (id !== null) {
588
+ return {
589
+ id,
590
+ type
591
+ };
592
+ }
593
+ return {
594
+ id,
595
+ lid,
596
+ type
597
+ };
598
+ }
599
+ function fixRelData(rel) {
600
+ if (Array.isArray(rel)) {
601
+ return rel.map(ref => fixRef(ref));
602
+ } else if (typeof rel === 'object' && rel !== null) {
603
+ return fixRef(rel);
604
+ }
605
+ return null;
606
+ }
607
+ function _serializeResource(cache, identifier) {
608
+ const {
609
+ id,
610
+ lid,
611
+ type
612
+ } = identifier;
613
+ // peek gives us everything we want, but since its referentially the same data
614
+ // as is in the cache we clone it to avoid any accidental mutations
615
+ const record = structuredClone(cache.peek(identifier));
616
+
617
+ // remove lid from anything that has an ID and slice any relationship arrays
618
+ if (record.id !== null) {
619
+ delete record.lid;
620
+ }
621
+ if (record.relationships) {
622
+ for (const key of Object.keys(record.relationships)) {
623
+ const relationship = record.relationships[key];
624
+ if (Array.isArray(relationship.data)) {
625
+ relationship.data = relationship.data.map(ref => fixRef(ref));
626
+ } else if (typeof relationship.data === 'object' && relationship.data !== null) {
627
+ relationship.data = fixRef(relationship.data);
628
+ } else if (Object.keys(relationship ?? {}).length === 0) {
629
+ delete record.relationships[key];
630
+ }
631
+ }
632
+ }
633
+ return record;
634
+ }
635
+
636
+ /**
637
+ * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**
638
+ *
639
+ * While this may come as a surprise, they are intended to serialize cache state for more
640
+ * generalized usage. {json:api} has a large variance in acceptable shapes, and only your
641
+ * app can ensure that the body is correctly formatted and contains all necessary data.
642
+ * :::
643
+ *
644
+ * Serializes changes to a resource. Useful for use with building bodies for PATCH requests.
645
+ *
646
+ * Only attributes which are changed are serialized.
647
+ * Only relationships which are changed are serialized.
648
+ *
649
+ * Collection relationships serialize the collection as a whole.
650
+ *
651
+ * If you would like to serialize updates to a collection more granularly
652
+ * (for instance, as operations) request the diff from the store and
653
+ * serialize as desired:
654
+ *
655
+ * ```ts
656
+ * const relationshipDiffMap = cache.changedRelationships(identifier);
657
+ * ```
658
+ *
659
+ * @public
660
+ * @param {Cache} cache}
661
+ * @param {ResourceKey} identifier
662
+ * @return {Object} An object with a `data` property containing the serialized resource patch
663
+ */
664
+ function serializePatch(cache, identifier) {
665
+ const {
666
+ id,
667
+ lid,
668
+ type
669
+ } = identifier;
670
+ const data = id === null ? {
671
+ type,
672
+ lid,
673
+ id
674
+ } : {
675
+ type,
676
+ id
677
+ };
678
+ if (cache.hasChangedAttrs(identifier)) {
679
+ const attrsChanges = cache.changedAttrs(identifier);
680
+ const attributes = {};
681
+ Object.keys(attrsChanges).forEach(key => {
682
+ const change = attrsChanges[key];
683
+ const newVal = change[1];
684
+ attributes[key] = newVal === undefined ? null : structuredClone(newVal);
685
+ });
686
+ data.attributes = attributes;
687
+ }
688
+ const changedRelationships = cache.changedRelationships(identifier);
689
+ if (changedRelationships.size) {
690
+ const relationships = {};
691
+ changedRelationships.forEach((diff, key) => {
692
+ relationships[key] = {
693
+ data: fixRelData(diff.localState)
694
+ };
695
+ });
696
+ data.relationships = relationships;
697
+ }
698
+ return {
699
+ data
700
+ };
701
+ }
702
+ export { createRecord, deleteRecord, findRecord, postQuery, query, serializePatch, serializeResources, setBuildURLConfig, updateRecord };