@warp-drive-mirror/json-api 5.8.0-alpha.4 → 5.8.0-alpha.41

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.
@@ -0,0 +1,3350 @@
1
+ import { graphFor, peekGraph, isBelongsTo } from '@warp-drive-mirror/core/graph/-private';
2
+ import { logGroup, isResourceKey, assertPrivateCapabilities, isRequestKey } from '@warp-drive-mirror/core/store/-private';
3
+ import Fuse from 'fuse.js';
4
+ import jsonToAst from 'json-to-ast';
5
+
6
+ function validateDocumentFields(schema, jsonApiDoc) {
7
+ const {
8
+ data,
9
+ included
10
+ } = jsonApiDoc;
11
+ if (data === null) {
12
+ return;
13
+ }
14
+ if (typeof jsonApiDoc.data !== 'object') {
15
+ throw new Error(`Expected a resource object in the 'data' property in the document provided to the cache, but was ${typeof jsonApiDoc.data}`);
16
+ }
17
+ if (Array.isArray(data)) {
18
+ for (const resource of data) {
19
+ validateResourceFields(schema, resource, {
20
+ verifyIncluded: true,
21
+ included
22
+ });
23
+ }
24
+ } else {
25
+ validateResourceFields(schema, data, {
26
+ verifyIncluded: true,
27
+ included
28
+ });
29
+ }
30
+ if (included) {
31
+ for (const resource of included) {
32
+ validateResourceFields(schema, resource, {
33
+ verifyIncluded: false
34
+ });
35
+ }
36
+ }
37
+ }
38
+ function validateResourceFields(schema, resource, options) {
39
+ if (!resource.relationships) {
40
+ return;
41
+ }
42
+ const resourceType = resource.type;
43
+ const fields = schema.fields({
44
+ type: resource.type
45
+ });
46
+ for (const [type, relationshipDoc] of Object.entries(resource.relationships)) {
47
+ const field = fields.get(type);
48
+ if (!field) {
49
+ return;
50
+ }
51
+ switch (field.kind) {
52
+ case 'belongsTo':
53
+ {
54
+ if (field.options.linksMode) {
55
+ validateBelongsToLinksMode(resourceType, field, relationshipDoc, options);
56
+ }
57
+ break;
58
+ }
59
+ case 'hasMany':
60
+ {
61
+ if (field.options.linksMode) {
62
+ validateHasManyToLinksMode(resourceType, field);
63
+ }
64
+ break;
65
+ }
66
+ }
67
+ }
68
+ }
69
+ function validateBelongsToLinksMode(resourceType, field, relationshipDoc, options) {
70
+ if (field.options.async) {
71
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but async is not yet supported`);
72
+ }
73
+ if (!relationshipDoc.links?.related) {
74
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the related link is missing`);
75
+ }
76
+ const relationshipData = relationshipDoc.data;
77
+ if (Array.isArray(relationshipData)) {
78
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the relationship data for a belongsTo relationship is unexpectedly an array`);
79
+ }
80
+ // Explicitly allow `null`! Missing key or `undefined` are always invalid.
81
+ if (relationshipData === undefined) {
82
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the relationship data is undefined`);
83
+ }
84
+ if (relationshipData === null) {
85
+ return;
86
+ }
87
+ if (!options.verifyIncluded) {
88
+ return;
89
+ }
90
+ const includedDoc = options.included?.find(doc => doc.type === relationshipData.type && doc.id === relationshipData.id);
91
+ if (!includedDoc) {
92
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the related data is not included`);
93
+ }
94
+ }
95
+ function validateHasManyToLinksMode(resourceType, field, _relationshipDoc, _options) {
96
+ if (field.options.async) {
97
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but async hasMany is not yet supported`);
98
+ }
99
+ }
100
+
101
+ function inspectType(obj) {
102
+ if (obj === null) {
103
+ return 'null';
104
+ }
105
+ if (Array.isArray(obj)) {
106
+ return 'array';
107
+ }
108
+ if (typeof obj === 'object') {
109
+ const proto = Object.getPrototypeOf(obj);
110
+ if (proto === null) {
111
+ return 'object';
112
+ }
113
+ if (proto === Object.prototype) {
114
+ return 'object';
115
+ }
116
+ return `object (${proto.constructor?.name})`;
117
+ }
118
+ if (typeof obj === 'function') {
119
+ return 'function';
120
+ }
121
+ if (typeof obj === 'string') {
122
+ return 'string';
123
+ }
124
+ if (typeof obj === 'number') {
125
+ return 'number';
126
+ }
127
+ if (typeof obj === 'boolean') {
128
+ return 'boolean';
129
+ }
130
+ if (typeof obj === 'symbol') {
131
+ return 'symbol';
132
+ }
133
+ if (typeof obj === 'bigint') {
134
+ return 'bigint';
135
+ }
136
+ if (typeof obj === 'undefined') {
137
+ return 'undefined';
138
+ }
139
+ return 'unknown';
140
+ }
141
+ function isSimpleObject(obj) {
142
+ if (obj === null) {
143
+ return false;
144
+ }
145
+ if (Array.isArray(obj)) {
146
+ return false;
147
+ }
148
+ if (typeof obj !== 'object') {
149
+ return false;
150
+ }
151
+ const proto = Object.getPrototypeOf(obj);
152
+ if (proto === null) {
153
+ return true;
154
+ }
155
+ if (proto === Object.prototype) {
156
+ return true;
157
+ }
158
+ return false;
159
+ }
160
+ const RELATIONSHIP_FIELD_KINDS = ['belongsTo', 'hasMany', 'resource', 'collection'];
161
+ class Reporter {
162
+ capabilities;
163
+ contextDocument;
164
+ errors = [];
165
+ ast;
166
+ jsonStr;
167
+
168
+ // TODO @runspired make this configurable to consuming apps before
169
+ // activating by default
170
+ strict = {
171
+ linkage: true,
172
+ unknownType: true,
173
+ unknownAttribute: true,
174
+ unknownRelationship: true
175
+ };
176
+ constructor(capabilities, doc) {
177
+ this.capabilities = capabilities;
178
+ this.contextDocument = doc;
179
+ this.jsonStr = JSON.stringify(doc.content, null, 2);
180
+ this.ast = jsonToAst(this.jsonStr, {
181
+ loc: true
182
+ });
183
+ }
184
+ searchTypes(type) {
185
+ if (!this._typeFilter) {
186
+ const allTypes = this.schema.resourceTypes();
187
+ this._typeFilter = new Fuse(allTypes);
188
+ }
189
+ const result = this._typeFilter.search(type);
190
+ return result;
191
+ }
192
+ _fieldFilters = new Map();
193
+ searchFields(type, field) {
194
+ if (!this._fieldFilters.has(type)) {
195
+ const allFields = this.schema.fields({
196
+ type
197
+ });
198
+ const allCacheFields = this.schema.cacheFields?.({
199
+ type
200
+ }) ?? allFields;
201
+ const attrs = Array.from(allCacheFields.values()).filter(isRemoteField).map(v => v.name);
202
+ this._fieldFilters.set(type, new Fuse(attrs));
203
+ }
204
+ const result = this._fieldFilters.get(type).search(field);
205
+ return result;
206
+ }
207
+ get schema() {
208
+ return this.capabilities.schema;
209
+ }
210
+ getLocation(path, kind) {
211
+ if (path.length === 0) {
212
+ return this.ast.loc;
213
+ }
214
+ let priorNode = this.ast;
215
+ let node = this.ast;
216
+ for (const segment of path) {
217
+ //
218
+ // handle array paths
219
+ //
220
+ if (typeof segment === 'number') {
221
+ (test => {
222
+ if (!test) {
223
+ throw new Error(`Because the segment is a number, expected a node of type Array`);
224
+ }
225
+ })(node.type === 'Array');
226
+ if (node.children && node.children[segment]) {
227
+ priorNode = node;
228
+ const childNode = node.children[segment];
229
+ if (childNode.type === 'Object' || childNode.type === 'Array') {
230
+ node = childNode;
231
+ } else {
232
+ // set to the closest node we can find
233
+ return node.loc;
234
+ }
235
+ } else {
236
+ // set to the closest node we can find
237
+ // as we had no children
238
+ return priorNode.loc;
239
+ }
240
+
241
+ //
242
+ // handle object paths
243
+ //
244
+ } else {
245
+ (test => {
246
+ if (!test) {
247
+ throw new Error(`Because the segment is a string, expected a node of type Object`);
248
+ }
249
+ })(node.type === 'Object');
250
+ const child = node.children.find(childCandidate => {
251
+ if (childCandidate.type === 'Property') {
252
+ return childCandidate.key.type === 'Identifier' && childCandidate.key.value === segment;
253
+ }
254
+ return false;
255
+ });
256
+ if (child) {
257
+ if (child.value.type === 'Object' || child.value.type === 'Array') {
258
+ priorNode = node;
259
+ node = child.value;
260
+ } else {
261
+ // set to the closest node we can find
262
+ return kind === 'key' ? child.key.loc : child.value.loc;
263
+ }
264
+ } else {
265
+ // set to the closest node we can find
266
+ return priorNode.loc;
267
+ }
268
+ }
269
+ }
270
+ return node.loc;
271
+ }
272
+ error(path, message, kind = 'key') {
273
+ const loc = this.getLocation(path, kind);
274
+ this.errors.push({
275
+ path,
276
+ message,
277
+ loc,
278
+ type: 'error',
279
+ kind
280
+ });
281
+ }
282
+ warn(path, message, kind = 'key') {
283
+ const loc = this.getLocation(path, kind);
284
+ this.errors.push({
285
+ path,
286
+ message,
287
+ loc,
288
+ type: 'warning',
289
+ kind
290
+ });
291
+ }
292
+ info(path, message, kind = 'key') {
293
+ const loc = this.getLocation(path, kind);
294
+ this.errors.push({
295
+ path,
296
+ message,
297
+ loc,
298
+ type: 'info',
299
+ kind
300
+ });
301
+ }
302
+ hasExtension(extensionName) {
303
+ return REGISTERED_EXTENSIONS.has(extensionName);
304
+ }
305
+ getExtension(extensionName) {
306
+ return REGISTERED_EXTENSIONS.get(extensionName);
307
+ }
308
+ report(colorize = true) {
309
+ const lines = this.jsonStr.split('\n');
310
+
311
+ // sort the errors by line, then by column, then by type
312
+ const {
313
+ errors
314
+ } = this;
315
+ if (!errors.length) {
316
+ return;
317
+ }
318
+ errors.sort((a, b) => {
319
+ return a.loc.end.line < b.loc.end.line ? -1 : a.loc.end.column < b.loc.end.column ? -1 : compareType(a.type, b.type);
320
+ });
321
+
322
+ // store the errors in a map by line
323
+ const errorMap = new Map();
324
+ for (const error of errors) {
325
+ const line = error.loc.end.line;
326
+ if (!errorMap.has(line)) {
327
+ errorMap.set(line, []);
328
+ }
329
+ errorMap.get(line).push(error);
330
+ }
331
+
332
+ // splice the errors into the lines
333
+ const errorLines = [];
334
+ const colors = [];
335
+ const counts = {
336
+ error: 0,
337
+ warning: 0,
338
+ info: 0
339
+ };
340
+ const LINE_SIZE = String(lines.length).length;
341
+ for (let i = 0; i < lines.length; i++) {
342
+ const line = lines[i];
343
+ errorLines.push(colorize ? `${String(i + 1).padEnd(LINE_SIZE, ' ')} \t%c${line}%c` : `${String(i + 1).padEnd(LINE_SIZE, ' ')} \t${line}`);
344
+ colors.push(`color: grey; background-color: transparent;`,
345
+ // first color sets color
346
+ `color: inherit; background-color: transparent;` // second color resets the color profile
347
+ );
348
+ if (errorMap.has(i + 1)) {
349
+ const errorsForLine = errorMap.get(i + 1);
350
+ for (const error of errorsForLine) {
351
+ counts[error.type]++;
352
+ const {
353
+ loc,
354
+ message
355
+ } = error;
356
+ const start = loc.end.line === loc.start.line ? loc.start.column - 1 : loc.end.column - 1;
357
+ const end = loc.end.column - 1;
358
+ const symbol = error.type === 'error' ? '❌' : error.type === 'warning' ? '⚠️' : 'ℹ️';
359
+ const errorLine = colorize ? `${''.padStart(LINE_SIZE, ' ') + symbol}\t${' '.repeat(start)}%c^${'~'.repeat(end - start)} %c//%c ${message}%c` : `${''.padStart(LINE_SIZE, ' ') + symbol}\t${' '.repeat(start)}^${'~'.repeat(end - start)} // ${message}`;
360
+ errorLines.push(errorLine);
361
+ colors.push(error.type === 'error' ? 'color: red;' : error.type === 'warning' ? 'color: orange;' : 'color: blue;', 'color: grey;', error.type === 'error' ? 'color: red;' : error.type === 'warning' ? 'color: orange;' : 'color: blue;', 'color: inherit; background-color: transparent;' // reset color
362
+ );
363
+ }
364
+ }
365
+ }
366
+ const contextStr = `${counts.error} errors and ${counts.warning} warnings found in the {json:api} document returned by ${this.contextDocument.request?.method} ${this.contextDocument.request?.url}`;
367
+ const errorString = contextStr + `\n\n` + errorLines.join('\n');
368
+
369
+ // eslint-disable-next-line no-console, @typescript-eslint/no-unused-expressions
370
+ colorize ? console.log(errorString, ...colors) : console.log(errorString);
371
+ }
372
+ }
373
+
374
+ // we always want to sort errors first, then warnings, then info
375
+ function compareType(a, b) {
376
+ if (a === b) {
377
+ return 0;
378
+ }
379
+ if (a === 'error') {
380
+ return -1;
381
+ }
382
+ if (b === 'error') {
383
+ return 1;
384
+ }
385
+ if (a === 'warning') {
386
+ return -1;
387
+ }
388
+ if (b === 'warning') {
389
+ return 1;
390
+ }
391
+ return 0;
392
+ }
393
+ const REGISTERED_EXTENSIONS = new Map();
394
+ function isMetaDocument(doc) {
395
+ return !(doc instanceof Error) && doc.content && !('data' in doc.content) && !('included' in doc.content) && 'meta' in doc.content;
396
+ }
397
+ function isErrorDocument(doc) {
398
+ return doc instanceof Error;
399
+ }
400
+ function isPushedDocument(doc) {
401
+ return !!doc && typeof doc === 'object' && 'content' in doc && !('request' in doc) && !('response' in doc);
402
+ }
403
+ function logPotentialMatches(matches, kind) {
404
+ if (matches.length === 0) {
405
+ return '';
406
+ }
407
+ if (matches.length === 1) {
408
+ return ` Did you mean this available ${kind} "${matches[0].item}"?`;
409
+ }
410
+ const potentialMatches = matches.map(match => match.item).join('", "');
411
+ return ` Did you mean one of these available ${kind}s: "${potentialMatches}"?`;
412
+ }
413
+ function isRemoteField(v) {
414
+ return !(v.kind === '@local' || v.kind === 'alias' || v.kind === 'derived');
415
+ }
416
+ function getRemoteField(fields, key) {
417
+ const field = fields.get(key);
418
+ if (!field) {
419
+ return undefined;
420
+ }
421
+ if (!isRemoteField(field)) {
422
+ return undefined;
423
+ }
424
+ return field;
425
+ }
426
+
427
+ const VALID_TOP_LEVEL_MEMBERS = ['data', 'included', 'meta', 'jsonapi', 'links'];
428
+
429
+ /**
430
+ * Reports issues which violate the JSON:API spec for top-level members.
431
+ *
432
+ * Version: 1.1
433
+ * Section: 7.1
434
+ * Link: https://jsonapi.org/format/#document-top-level
435
+ *
436
+ * @internal
437
+ */
438
+ function validateTopLevelDocumentMembers(reporter, doc) {
439
+ const keys = Object.keys(doc);
440
+ for (const key of keys) {
441
+ if (!VALID_TOP_LEVEL_MEMBERS.includes(key)) {
442
+ if (key.includes(':')) {
443
+ // TODO @runspired expose the API to enable folks to add validation for their own extensions
444
+ const extensionName = key.split(':')[0];
445
+ if (reporter.hasExtension(extensionName)) {
446
+ const extension = reporter.getExtension(extensionName);
447
+ extension(reporter, [key]);
448
+ } else {
449
+ reporter.warn([key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {json:api} member`);
450
+ }
451
+ } else {
452
+ reporter.error([key], `Unrecognized top-level member. The data it provides is ignored as it is not a valid {json:api} member`);
453
+ }
454
+ }
455
+ }
456
+
457
+ // additional rules for top-level members
458
+ // ======================================
459
+
460
+ // 1. MUST have either `data`, `errors`, or `meta`
461
+ if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
462
+ reporter.error([], 'A {json:api} Document must contain one-of `data` `errors` or `meta`');
463
+ }
464
+
465
+ // 2. MUST NOT have both `data` and `errors`
466
+ if ('data' in doc && 'errors' in doc) {
467
+ reporter.error(['data'], 'A {json:api} Document MUST NOT contain both `data` and `errors` members');
468
+ }
469
+
470
+ // 3. MUST NOT have both `included` and `errors`
471
+ // while not explicitly stated in the spec, this is a logical extension of the above rule
472
+ // since `included` is only valid when `data` is present.
473
+ if ('included' in doc && 'errors' in doc) {
474
+ reporter.error(['included'], 'A {json:api} Document MUST NOT contain both `included` and `errors` members');
475
+ }
476
+
477
+ // 4. MUST NOT have `included` if `data` is not present
478
+ if ('included' in doc && !('data' in doc)) {
479
+ reporter.error(['included'], 'A {json:api} Document MUST NOT contain `included` if `data` is not present');
480
+ }
481
+
482
+ // 5. MUST NOT have `included` if `data` is null
483
+ // when strictly enforcing full linkage, we need to ensure that `included` is not present if `data` is null
484
+ // however, most APIs will ignore this rule for DELETE requests, so unless strict linkage is enabled, we will only warn
485
+ // about this issue.
486
+ if ('included' in doc && doc.data === null) {
487
+ const isMaybeDelete = reporter.contextDocument.request?.method?.toUpperCase() === 'DELETE' || reporter.contextDocument.request?.op === 'deleteRecord';
488
+ const method = !reporter.strict.linkage && isMaybeDelete ? 'warn' : 'error';
489
+ reporter[method](['included'], 'A {json:api} Document MUST NOT contain `included` if `data` is null');
490
+ }
491
+
492
+ // Simple Validation of Top-Level Members
493
+ // ==========================================
494
+ // 1. `data` MUST be a single resource object or an array of resource objects or `null`
495
+ if ('data' in doc) {
496
+ const dataMemberHasAppropriateForm = doc.data === null || Array.isArray(doc.data) || isSimpleObject(doc.data);
497
+ if (!dataMemberHasAppropriateForm) {
498
+ reporter.error(['data'], `The 'data' member MUST be a single resource object or an array of resource objects or null. Received data of type "${inspectType(doc.data)}"`);
499
+ }
500
+ }
501
+
502
+ // 2. `included` MUST be an array of resource objects
503
+ if ('included' in doc) {
504
+ if (!Array.isArray(doc.included)) {
505
+ reporter.error(['included'], `The 'included' member MUST be an array of resource objects. Received data of type "${inspectType(doc.included)}"`);
506
+ }
507
+ }
508
+
509
+ // 3. `meta` MUST be a simple object
510
+ if ('meta' in doc) {
511
+ if (!isSimpleObject(doc.meta)) {
512
+ reporter.error(['meta'], `The 'meta' member MUST be a simple object. Received data of type "${inspectType(doc.meta)}"`);
513
+ }
514
+ }
515
+
516
+ // 4. `jsonapi` MUST be a simple object
517
+ if ('jsonapi' in doc) {
518
+ if (!isSimpleObject(doc.jsonapi)) {
519
+ reporter.error(['jsonapi'], `The 'jsonapi' member MUST be a simple object. Received data of type "${inspectType(doc.jsonapi)}"`);
520
+ }
521
+ }
522
+
523
+ // 5. `links` MUST be a simple object
524
+ if ('links' in doc) {
525
+ if (!isSimpleObject(doc.links)) {
526
+ reporter.error(['links'], `The 'links' member MUST be a simple object. Received data of type "${inspectType(doc.links)}"`);
527
+ }
528
+ }
529
+
530
+ // 6. `errors` MUST be an array of error objects
531
+ if ('errors' in doc) {
532
+ if (!Array.isArray(doc.errors)) {
533
+ reporter.error(['errors'], `The 'errors' member MUST be an array of error objects. Received data of type "${inspectType(doc.errors)}"`);
534
+ }
535
+ }
536
+ }
537
+
538
+ const VALID_COLLECTION_LINKS = ['self', 'related', 'first', 'last', 'prev', 'next'];
539
+ const VALID_RESOURCE_RELATIONSHIP_LINKS = ['self', 'related'];
540
+ const VALID_RESOURCE_LINKS = ['self'];
541
+
542
+ /**
543
+ * Validates the links object in a top-level JSON API document or resource object
544
+ *
545
+ * Version: 1.1
546
+ *
547
+ * Section: 7.1 Top Level
548
+ * Link: https://jsonapi.org/format/#document-top-level
549
+ *
550
+ * Section: 7.2.3 Resource Objects
551
+ * Link: https://jsonapi.org/format/#document-resource-object-links
552
+ *
553
+ * Section: 7.2.2.2 Resource Relationships
554
+ * Link: https://jsonapi.org/format/#document-resource-object-relationships
555
+ *
556
+ * Section: 7.6 Document Links
557
+ * Link: https://jsonapi.org/format/#document-links
558
+ *
559
+ * @internal
560
+ */
561
+ function validateLinks(reporter, doc, type, path = ['links']) {
562
+ if (!('links' in doc)) {
563
+ return;
564
+ }
565
+ if (!isSimpleObject(doc.links)) {
566
+ // this is a violation but we report it when validating section 7.1
567
+ return;
568
+ }
569
+
570
+ // prettier-ignore
571
+ const VALID_TOP_LEVEL_LINKS = type === 'collection-document' || type === 'collection-relationship' ? VALID_COLLECTION_LINKS : type === 'resource-document' || type === 'resource-relationship' ? VALID_RESOURCE_RELATIONSHIP_LINKS : type === 'resource' ? VALID_RESOURCE_LINKS : [];
572
+ const links = doc.links;
573
+ const keys = Object.keys(links);
574
+ for (const key of keys) {
575
+ if (!VALID_TOP_LEVEL_LINKS.includes(key)) {
576
+ reporter.warn([...path, key], `Unrecognized top-level link. The data it provides may be ignored as it is not a valid {json:api} link for a ${type}`);
577
+ }
578
+ // links may be either a string or an object with an href property or null
579
+ if (links[key] === null) ; else if (typeof links[key] === 'string') {
580
+ if (links[key].length === 0) {
581
+ reporter.warn([...path, key], `Expected a non-empty string, but received an empty string`);
582
+ }
583
+ // valid, though we should potentially validate the URL here
584
+ } else if (isSimpleObject(links[key])) {
585
+ if ('href' in links[key]) {
586
+ const linksKeys = Object.keys(links[key]);
587
+ if (linksKeys.length > 1) {
588
+ reporter.warn([...path, key], `Expected the links object to only have an href property, but received unknown keys ${linksKeys.filter(k => k !== 'href').join(', ')}`);
589
+ }
590
+ if (typeof links[key].href !== 'string') {
591
+ reporter.error([...path, key, 'href'], `Expected a string value, but received ${inspectType(links[key].href)}`);
592
+ } else {
593
+ if (links[key].href.length === 0) {
594
+ reporter.warn([...path, key, 'href'], `Expected a non-empty string, but received an empty string`);
595
+ }
596
+ // valid, though we should potentially validate the URL here
597
+ }
598
+ } else {
599
+ const linksKeys = Object.keys(links[key]);
600
+ if (linksKeys.length > 0) {
601
+ reporter.error([...path, key], `Expected the links object to have an href property, but received only the unknown keys ${linksKeys.join(', ')}`);
602
+ } else {
603
+ reporter.error([...path, key], `Expected the links object to have an href property`);
604
+ }
605
+ }
606
+ } else {
607
+ // invalid
608
+ reporter.error([...path, key], `Expected a string, null, or an object with an href property for the link "${key}", but received ${inspectType(links[key])}`);
609
+ }
610
+ }
611
+ }
612
+
613
+ const SINGULAR_OPS = ['createRecord', 'updateRecord', 'deleteRecord', 'findRecord', 'queryRecord'];
614
+
615
+ /**
616
+ * Validates the resource objects in either the `data` or `included` members of
617
+ * JSON:API document.
618
+ *
619
+ * Version: 1.1
620
+ * Section: 7.2
621
+ * Link: https://jsonapi.org/format/#document-resource-objects
622
+ *
623
+ * @internal
624
+ */
625
+ function validateDocumentResources(reporter, doc) {
626
+ if ('data' in doc) {
627
+ // scan for common mistakes of single vs multiple resource objects
628
+ const op = reporter.contextDocument.request?.op;
629
+ if (op && SINGULAR_OPS.includes(op)) {
630
+ if (Array.isArray(doc.data)) {
631
+ reporter.error(['data'], `"${op}" requests expect a single resource object in the returned data, but received an array`);
632
+ }
633
+ }
634
+
635
+ // guard for a common mistake around deleteRecord
636
+ if (op === 'deleteRecord') {
637
+ if (doc.data !== null) {
638
+ reporter.warn(['data'], `"deleteRecord" requests expect the data member to be null, but received ${inspectType(doc.data)}. This can sometimes cause unexpected resurrection of the deleted record.`);
639
+ }
640
+ }
641
+ if (Array.isArray(doc.data)) {
642
+ doc.data.forEach((resource, index) => {
643
+ if (!isSimpleObject(resource)) {
644
+ reporter.error(['data', index], `Expected a resource object, but received ${inspectType(resource)}`);
645
+ } else {
646
+ validateResourceObject(reporter, resource, ['data', index]);
647
+ }
648
+ });
649
+ } else if (doc.data !== null) {
650
+ if (!isSimpleObject(doc.data)) {
651
+ reporter.error(['data'], `Expected a resource object, but received ${inspectType(doc.data)}`);
652
+ } else {
653
+ validateResourceObject(reporter, doc.data, ['data']);
654
+ }
655
+ }
656
+ }
657
+ if ('included' in doc && Array.isArray(doc.included)) {
658
+ doc.included.forEach((resource, index) => {
659
+ if (!isSimpleObject(resource)) {
660
+ reporter.error(['included', index], `Expected a resource object, but received ${inspectType(resource)}`);
661
+ } else {
662
+ validateResourceObject(reporter, resource, ['included', index]);
663
+ }
664
+ });
665
+ }
666
+ }
667
+ function validateResourceObject(reporter, resource, path) {
668
+ validateTopLevelResourceShape(reporter, resource, path);
669
+ }
670
+ const VALID_TOP_LEVEL_RESOURCE_KEYS = ['lid', 'id', 'type', 'attributes', 'relationships', 'meta', 'links'];
671
+ function validateTopLevelResourceShape(reporter, resource, path) {
672
+ // a resource MUST have a string type
673
+ if (!('type' in resource)) {
674
+ reporter.error([...path, 'type'], `Expected a ResourceObject to have a type property`);
675
+ } else if (typeof resource.type !== 'string') {
676
+ reporter.error([...path, 'type'], `Expected a string value for the type property, but received ${inspectType(resource.type)}`, 'value');
677
+ } else if (resource.type.length === 0) {
678
+ reporter.error([...path, 'type'], `Expected a non-empty string value for the type property, but received an empty string`, 'value');
679
+ } else if (!reporter.schema.hasResource({
680
+ type: resource.type
681
+ })) {
682
+ const method = reporter.strict.unknownType ? 'error' : 'warn';
683
+ const potentialTypes = reporter.searchTypes(resource.type);
684
+ reporter[method]([...path, 'type'], `Expected a schema to be available for the ResourceType "${resource.type}" but none was found.${logPotentialMatches(potentialTypes, 'ResourceType')}`, 'value');
685
+ }
686
+
687
+ // a resource MUST have a string ID
688
+ if (!('id' in resource)) {
689
+ reporter.error([...path, 'id'], `Expected a ResourceObject to have an id property`);
690
+ } else if (typeof resource.id !== 'string') {
691
+ reporter.error([...path, 'id'], `Expected a string value for the id property, but received ${inspectType(resource.id)}`, 'value');
692
+ } else if (resource.id.length === 0) {
693
+ reporter.error([...path, 'id'], `Expected a non-empty string value for the id property, but received an empty string`, 'value');
694
+ }
695
+
696
+ // a resource MAY have a lid property
697
+ if ('lid' in resource && typeof resource.lid !== 'string') {
698
+ reporter.error([...path, 'lid'], `Expected a string value for the lid property, but received ${inspectType(resource.lid)}`, 'value');
699
+ }
700
+
701
+ // a resource MAY have a meta property
702
+ if ('meta' in resource && !isSimpleObject(resource.meta)) {
703
+ reporter.error([...path, 'meta'], `Expected a simple object for the meta property, but received ${inspectType(resource.meta)}`, 'value');
704
+ }
705
+
706
+ // a resource MAY have a links property
707
+ if ('links' in resource && !isSimpleObject(resource.links)) {
708
+ reporter.error([...path, 'links'], `Expected a simple object for the links property, but received ${inspectType(resource.links)}`, 'value');
709
+ } else if ('links' in resource) {
710
+ validateLinks(reporter, resource, 'resource', [...path, 'links']);
711
+ }
712
+ const hasAttributes = 'attributes' in resource && isSimpleObject(resource.attributes);
713
+ const hasRelationships = 'relationships' in resource && isSimpleObject(resource.relationships);
714
+
715
+ // We expect at least one of attributes or relationships to be present
716
+ if (!hasAttributes && !hasRelationships) {
717
+ reporter.warn(path, `Expected a ResourceObject to have either attributes or relationships`);
718
+ }
719
+
720
+ // we expect at least one of attributes or relationships to be non-empty
721
+ const attributesLength = hasAttributes ? Object.keys(resource.attributes).length : 0;
722
+ const relationshipsLength = hasRelationships ? Object.keys(resource.relationships).length : 0;
723
+ if ((hasAttributes || hasRelationships) && attributesLength === 0 && relationshipsLength === 0) {
724
+ reporter.warn([...path, hasAttributes ? 'attributes' : hasRelationships ? 'relationships' : 'attributes'], `Expected a ResourceObject to have either non-empty attributes or non-empty relationships`);
725
+ }
726
+
727
+ // check for unknown keys on the resource object
728
+ const keys = Object.keys(resource);
729
+ for (const key of keys) {
730
+ if (!VALID_TOP_LEVEL_RESOURCE_KEYS.includes(key)) {
731
+ // check for extension keys
732
+ if (key.includes(':')) {
733
+ const extensionName = key.split(':')[0];
734
+ if (reporter.hasExtension(extensionName)) {
735
+ const extension = reporter.getExtension(extensionName);
736
+ extension(reporter, [...path, key]);
737
+ } else {
738
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {json:api} ResourceObject member`);
739
+ }
740
+ } else {
741
+ // check if this is an attribute or relationship
742
+ let didYouMean = ' Likely this field should have been inside of either "attributes" or "relationships"';
743
+ const type = 'type' in resource ? resource.type : undefined;
744
+ if (type && reporter.schema.hasResource({
745
+ type
746
+ })) {
747
+ const fields = reporter.schema.fields({
748
+ type
749
+ });
750
+ const field = getRemoteField(fields, key);
751
+ if (field) {
752
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(field.kind);
753
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely a ${field.kind} and belongs inside of ${isRelationship ? 'relationships' : 'attributes'}, e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${key}": { ... } }`;
754
+ } else {
755
+ const fieldMatches = reporter.searchFields(type, key);
756
+ if (fieldMatches.length === 1) {
757
+ const matchedField = fields.get(fieldMatches[0].item);
758
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(matchedField.kind);
759
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely a ${matchedField.kind} and belongs inside of ${isRelationship ? 'relationships' : 'attributes'}, e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${matchedField.name}": { ... } }`;
760
+ } else if (fieldMatches.length > 1) {
761
+ const matchedField = fields.get(fieldMatches[0].item);
762
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(matchedField.kind);
763
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely one of "${fieldMatches.map(v => v.item).join('", "')}" and belongs inside of either "attributes" or "relationships", e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${matchedField.name}": { ... } }`;
764
+ }
765
+ }
766
+ }
767
+ reporter.error([...path, key], `Unrecognized ResourceObject member. The data it provides is ignored as it is not a valid {json:api} ResourceObject member.${didYouMean}`);
768
+ }
769
+ }
770
+ }
771
+
772
+ // if we have a schema, validate the individual attributes and relationships
773
+ const type = 'type' in resource ? resource.type : undefined;
774
+ if (type && reporter.schema.hasResource({
775
+ type
776
+ })) {
777
+ if ('attributes' in resource) {
778
+ validateResourceAttributes(reporter, type, resource.attributes, [...path, 'attributes']);
779
+ }
780
+ if ('relationships' in resource) {
781
+ validateResourceRelationships(reporter, type, resource.relationships, [...path, 'relationships']);
782
+ }
783
+ }
784
+ }
785
+ function validateResourceAttributes(reporter, type, resource, path) {
786
+ const fields = reporter.schema.fields({
787
+ type
788
+ });
789
+ const cacheFields = reporter.schema.cacheFields?.({
790
+ type
791
+ }) ?? fields;
792
+ for (const [key] of Object.entries(resource)) {
793
+ const field = getRemoteField(cacheFields, key);
794
+ const actualField = cacheFields.get(key);
795
+ if (!field && actualField) {
796
+ reporter.warn([...path, key], `Expected the ${actualField.kind} field "${key}" to not have its own data in the ResourceObject's attributes. Likely this field should either not be returned in this payload or the field definition should be updated in the schema.`);
797
+ } else if (!field) {
798
+ if (key.includes(':')) {
799
+ const extensionName = key.split(':')[0];
800
+ if (reporter.hasExtension(extensionName)) {
801
+ const extension = reporter.getExtension(extensionName);
802
+ extension(reporter, [...path, key]);
803
+ } else {
804
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {json:api} ResourceObject member`);
805
+ }
806
+ } else {
807
+ const method = reporter.strict.unknownAttribute ? 'error' : 'warn';
808
+
809
+ // TODO @runspired when we check for fuzzy matches we can adjust the message to say
810
+ // whether the expected field is an attribute or a relationship
811
+ const potentialFields = reporter.searchFields(type, key);
812
+ reporter[method]([...path, key], `Unrecognized attribute. The data it provides is ignored as it is not part of the ResourceSchema for "${type}".${logPotentialMatches(potentialFields, 'field')}`);
813
+ }
814
+ } else if (field && RELATIONSHIP_FIELD_KINDS.includes(field.kind)) {
815
+ reporter.error([...path, key], `Expected the "${key}" field to be in "relationships" as it has kind "${field.kind}", but received data for it in "attributes".`);
816
+ }
817
+ }
818
+
819
+ // TODO @runspired we should also deep-validate the field value
820
+ // TODO @runspired we should validate that field values are valid JSON and not instances
821
+ }
822
+ function validateResourceRelationships(reporter, type, resource, path) {
823
+ const schema = reporter.schema.fields({
824
+ type
825
+ });
826
+ for (const [key] of Object.entries(resource)) {
827
+ const field = getRemoteField(schema, key);
828
+ const actualField = schema.get(key);
829
+ if (!field && actualField) {
830
+ reporter.warn([...path, key], `Expected the ${actualField.kind} field "${key}" to not have its own data in the ResourceObject's relationships. Likely this field should either not be returned in this payload or the field definition should be updated in the schema.`);
831
+ } else if (!field) {
832
+ if (key.includes(':')) {
833
+ const extensionName = key.split(':')[0];
834
+ if (reporter.hasExtension(extensionName)) {
835
+ const extension = reporter.getExtension(extensionName);
836
+ extension(reporter, [...path, key]);
837
+ } else {
838
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {json:api} ResourceObject member`);
839
+ }
840
+ } else {
841
+ const method = reporter.strict.unknownRelationship ? 'error' : 'warn';
842
+
843
+ // TODO @runspired when we check for fuzzy matches we can adjust the message to say
844
+ // whether the expected field is an attribute or a relationship
845
+ const potentialFields = reporter.searchFields(type, key);
846
+ reporter[method]([...path, key], `Unrecognized relationship. The data it provides is ignored as it is not part of the ResourceSchema for "${type}".${logPotentialMatches(potentialFields, 'field')}`);
847
+ }
848
+ } else if (field && !RELATIONSHIP_FIELD_KINDS.includes(field.kind)) {
849
+ reporter.error([...path, key], `Expected the "${key}" field to be in "attributes" as it has kind "${field.kind}", but received data for it in "relationships".`);
850
+ }
851
+ }
852
+
853
+ // TODO @runspired we should also deep-validate the relationship payload
854
+ // TODO @runspired we should validate linksMode requirements for both Polaris and Legacy modes
855
+ // TODO @runspired we should warn if the discovered resource-type in a relationship is the abstract
856
+ // type instead of the concrete type.
857
+ }
858
+
859
+ function validateDocument(capabilities, doc) {
860
+ (test => {
861
+ if (!test) {
862
+ throw new Error(`Expected a JSON:API Document as the content provided to the cache, received ${typeof doc.content}`);
863
+ }
864
+ })(doc instanceof Error || typeof doc.content === 'object' && doc.content !== null);
865
+ if (isErrorDocument(doc)) {
866
+ return; // return validateErrorDocument(reporter, doc);
867
+ } else if (isMetaDocument(doc)) {
868
+ return; // return validateMetaDocument(reporter, doc);
869
+ } else if (isPushedDocument(doc)) {
870
+ return; // return validatePushedDocument(reporter, doc);
871
+ }
872
+ const reporter = new Reporter(capabilities, doc);
873
+ return validateResourceDocument(reporter, doc);
874
+ }
875
+
876
+ // function validateErrorDocument(reporter: Reporter, doc: StructuredErrorDocument) {}
877
+
878
+ // function validateMetaDocument(reporter: Reporter, doc: StructuredDataDocument<ResourceMetaDocument>) {}
879
+
880
+ // function validatePushedDocument(reporter: Reporter, doc: StructuredDataDocument<ResourceDocument>) {}
881
+
882
+ function validateResourceDocument(reporter, doc) {
883
+ validateTopLevelDocumentMembers(reporter, doc.content);
884
+ validateLinks(reporter, doc.content, 'data' in doc.content && Array.isArray(doc.content?.data) ? 'collection-document' : 'resource-document');
885
+ validateDocumentResources(reporter, doc.content);
886
+
887
+ // TODO @runspired - validateMeta on document
888
+ // TODO @runspired - validateMeta on resource
889
+ // TODO @runspired - validateMeta on resource relationships
890
+ // TODO @runspired - validate no-meta on resource identifiers
891
+ //
892
+ // ---------------------------------
893
+ // super-strict-mode
894
+ //
895
+ // TODO @runspired - validate that all referenced resource identifiers are present in the document (full linkage)
896
+ // TODO @runspired - validate that all included resources have a path back to `data` (full linkage)
897
+ //
898
+ // ---------------------------------
899
+ // nice-to-haves
900
+ //
901
+ // TODO @runspired - validate links objects more thoroughly for spec props we don't use
902
+ // TODO @runspired - validate request includes are in fact included
903
+ // TODO @runspired - validate request fields are in fact present
904
+ // TODO @runspired - MAYBE validate request sort is in fact sorted? (useful for catching Mocking bugs)
905
+ // TODO @runspired - MAYBE validate request pagination is in fact paginated? (useful for catching Mocking bugs)
906
+
907
+ reporter.report();
908
+ }
909
+
910
+ /*
911
+ These are the runtime implementations for the javascript macros that have
912
+ runtime implementations.
913
+
914
+ Not every macro has a runtime implementation, some only make sense in the
915
+ build and always run there.
916
+
917
+ Even when we have runtime implementations, we are still careful to emit static
918
+ errors during the build wherever possible, and runtime errors when necessary,
919
+ so that you're not surprised when you switch from runtime-mode to compile-time
920
+ mode.
921
+ */
922
+
923
+
924
+ // This is here as a compile target for `getConfig` and `getOwnConfig` when
925
+ // we're in runtime mode. This is not public API to call from your own code.
926
+ function config(packageRoot) {
927
+ return runtimeConfig.packages[packageRoot];
928
+ }
929
+ function getGlobalConfig() {
930
+ return runtimeConfig.global;
931
+ }
932
+ const runtimeConfig = initializeRuntimeMacrosConfig();
933
+
934
+ // this exists to be targeted by our babel plugin
935
+ function initializeRuntimeMacrosConfig() {
936
+ return {
937
+ "packages": {},
938
+ "global": {
939
+ "@embroider/macros": {
940
+ "isTesting": false
941
+ },
942
+ "WarpDrive": {
943
+ "debug": {
944
+ "DEBUG_RELATIONSHIP_NOTIFICATIONS": false,
945
+ "LOG_CACHE": false,
946
+ "LOG_CACHE_POLICY": false,
947
+ "LOG_GRAPH": false,
948
+ "LOG_IDENTIFIERS": false,
949
+ "LOG_INSTANCE_CACHE": false,
950
+ "LOG_METRIC_COUNTS": false,
951
+ "LOG_MUTATIONS": false,
952
+ "LOG_NOTIFICATIONS": false,
953
+ "LOG_OPERATIONS": false,
954
+ "LOG_PAYLOADS": false,
955
+ "LOG_REACT_SIGNAL_INTEGRATION": false,
956
+ "LOG_REQUESTS": false,
957
+ "LOG_REQUEST_STATUS": false,
958
+ "__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS": false
959
+ },
960
+ "polyfillUUID": false,
961
+ "includeDataAdapter": true,
962
+ "compatWith": "99.0",
963
+ "deprecations": {
964
+ "DEPRECATE_CATCH_ALL": false,
965
+ "DEPRECATE_COMPUTED_CHAINS": false,
966
+ "DEPRECATE_EMBER_INFLECTOR": false,
967
+ "DEPRECATE_LEGACY_IMPORTS": false,
968
+ "DEPRECATE_MANY_ARRAY_DUPLICATES": false,
969
+ "DEPRECATE_NON_STRICT_ID": false,
970
+ "DEPRECATE_NON_STRICT_TYPES": false,
971
+ "DEPRECATE_NON_UNIQUE_PAYLOADS": false,
972
+ "DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE": false,
973
+ "DEPRECATE_STORE_EXTENDS_EMBER_OBJECT": false,
974
+ "DEPRECATE_TRACKING_PACKAGE": false,
975
+ "DISABLE_7X_DEPRECATIONS": false,
976
+ "ENABLE_LEGACY_REQUEST_METHODS": false,
977
+ "ENABLE_LEGACY_SCHEMA_SERVICE": false
978
+ },
979
+ "features": {
980
+ "ENFORCE_STRICT_RESOURCE_FINALIZATION": false,
981
+ "JSON_API_CACHE_VALIDATION_ERRORS": false,
982
+ "SAMPLE_FEATURE_FLAG": null
983
+ },
984
+ "activeLogging": {
985
+ "DEBUG_RELATIONSHIP_NOTIFICATIONS": true,
986
+ "LOG_CACHE": true,
987
+ "LOG_CACHE_POLICY": true,
988
+ "LOG_GRAPH": true,
989
+ "LOG_IDENTIFIERS": true,
990
+ "LOG_INSTANCE_CACHE": true,
991
+ "LOG_METRIC_COUNTS": true,
992
+ "LOG_MUTATIONS": true,
993
+ "LOG_NOTIFICATIONS": true,
994
+ "LOG_OPERATIONS": true,
995
+ "LOG_PAYLOADS": true,
996
+ "LOG_REACT_SIGNAL_INTEGRATION": true,
997
+ "LOG_REQUESTS": true,
998
+ "LOG_REQUEST_STATUS": true,
999
+ "__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS": true
1000
+ },
1001
+ "env": {
1002
+ "TESTING": true,
1003
+ "PRODUCTION": false,
1004
+ "DEBUG": true,
1005
+ "IS_RECORDING": false,
1006
+ "IS_CI": true,
1007
+ "SHOULD_RECORD": false
1008
+ }
1009
+ }
1010
+ }
1011
+ };
1012
+ }
1013
+ function updaterMethods() {
1014
+ return {
1015
+ config,
1016
+ getGlobalConfig,
1017
+ setConfig(packageRoot, value) {
1018
+ runtimeConfig.packages[packageRoot] = value;
1019
+ },
1020
+ setGlobalConfig(key, value) {
1021
+ runtimeConfig.global[key] = value;
1022
+ }
1023
+ };
1024
+ }
1025
+
1026
+ // this is how runtime config can get injected at boot. I'm not sure yet if this
1027
+ // should be public API, but we certainly need it internally to set things like
1028
+ // the global fastboot.isRunning.
1029
+ //
1030
+ // consumers of this API push a function onto
1031
+ // window._embroider_macros_runtime_config. The function is given four methods
1032
+ // which allow it to read and write the per-package and global configs. The
1033
+ // reason for allowing both read & write is that merging strategies are up to
1034
+ // each consumers -- read first, then merge, then write.
1035
+ //
1036
+ // For an example user of this API, see where we generate
1037
+ // embroider_macros_fastboot_init.js' in @embroider/core.
1038
+ let updaters = typeof window !== 'undefined' ? window._embroider_macros_runtime_config : undefined;
1039
+ if (updaters) {
1040
+ let methods = updaterMethods();
1041
+ for (let updater of updaters) {
1042
+ updater(methods);
1043
+ }
1044
+ }
1045
+
1046
+ function isImplicit(relationship) {
1047
+ return relationship.definition.isImplicit;
1048
+ }
1049
+ const EMPTY_ITERATOR = {
1050
+ iterator() {
1051
+ return {
1052
+ next() {
1053
+ return {
1054
+ done: true,
1055
+ value: undefined
1056
+ };
1057
+ }
1058
+ };
1059
+ }
1060
+ };
1061
+ function makeCache() {
1062
+ return {
1063
+ id: null,
1064
+ remoteAttrs: null,
1065
+ localAttrs: null,
1066
+ defaultAttrs: null,
1067
+ inflightAttrs: null,
1068
+ changes: null,
1069
+ errors: null,
1070
+ isNew: false,
1071
+ isDeleted: false,
1072
+ isDeletionCommitted: false
1073
+ };
1074
+ }
1075
+
1076
+ /**
1077
+ * ```ts
1078
+ * import { JSONAPICache } from '@warp-drive-mirror/json-api';
1079
+ * ```
1080
+ *
1081
+ * A {@link Cache} implementation tuned for [{json:api}](https://jsonapi.org/)
1082
+ *
1083
+ * @categoryDescription Cache Management
1084
+ * APIs for primary cache management functionality
1085
+ * @categoryDescription Cache Forking
1086
+ * APIs that support Cache Forking
1087
+ * @categoryDescription SSR Support
1088
+ * APIs that support SSR functionality
1089
+ * @categoryDescription Resource Lifecycle
1090
+ * APIs that support management of resource data
1091
+ * @categoryDescription Resource Data
1092
+ * APIs that support granular field level management of resource data
1093
+ * @categoryDescription Resource State
1094
+ * APIs that support managing Resource states
1095
+ *
1096
+ * @public
1097
+ */
1098
+ class JSONAPICache {
1099
+ /**
1100
+ * The Cache Version that this implementation implements.
1101
+ *
1102
+ * @public
1103
+ */
1104
+
1105
+ /** @internal */
1106
+
1107
+ /** @internal */
1108
+
1109
+ /** @internal */
1110
+
1111
+ /** @internal */
1112
+
1113
+ /** @internal */
1114
+
1115
+ constructor(capabilities) {
1116
+ this.version = '2';
1117
+ this._capabilities = capabilities;
1118
+ this.__cache = new Map();
1119
+ this.__graph = graphFor(capabilities);
1120
+ this.__destroyedCache = new Map();
1121
+ this.__documents = new Map();
1122
+ }
1123
+
1124
+ ////////// ================ //////////
1125
+ ////////// Cache Management //////////
1126
+ ////////// ================ //////////
1127
+
1128
+ /**
1129
+ * Cache the response to a request
1130
+ *
1131
+ * Implements `Cache.put`.
1132
+ *
1133
+ * Expects a StructuredDocument whose `content` member is a JsonApiDocument.
1134
+ *
1135
+ * ```js
1136
+ * cache.put({
1137
+ * request: { url: 'https://api.example.com/v1/user/1' },
1138
+ * content: {
1139
+ * data: {
1140
+ * type: 'user',
1141
+ * id: '1',
1142
+ * attributes: {
1143
+ * name: 'Chris'
1144
+ * }
1145
+ * }
1146
+ * }
1147
+ * })
1148
+ * ```
1149
+ *
1150
+ * > **Note**
1151
+ * > The nested `content` and `data` members are not a mistake. This is because
1152
+ * > there are two separate concepts involved here, the `StructuredDocument` which contains
1153
+ * > the context of a given Request that has been issued with the returned contents as its
1154
+ * > `content` property, and a `JSON:API Document` which is the json contents returned by
1155
+ * > this endpoint and which uses its `data` property to signify which resources are the
1156
+ * > primary resources associated with the request.
1157
+ *
1158
+ * StructuredDocument's with urls will be cached as full documents with
1159
+ * associated resource membership order and contents preserved but linked
1160
+ * into the cache.
1161
+ *
1162
+ * @category Cache Management
1163
+ * @public
1164
+ */
1165
+
1166
+ put(doc) {
1167
+ {
1168
+ validateDocument(this._capabilities, doc);
1169
+ }
1170
+ if (isErrorDocument(doc)) {
1171
+ return this._putDocument(doc, undefined, undefined);
1172
+ } else if (isMetaDocument(doc)) {
1173
+ return this._putDocument(doc, undefined, undefined);
1174
+ }
1175
+ const jsonApiDoc = doc.content;
1176
+ const included = jsonApiDoc.included;
1177
+ let i, length;
1178
+ const {
1179
+ cacheKeyManager
1180
+ } = this._capabilities;
1181
+ {
1182
+ validateDocumentFields(this._capabilities.schema, jsonApiDoc);
1183
+ }
1184
+ {
1185
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1186
+ const Counts = new Map();
1187
+ let totalCount = 0;
1188
+ if (included) {
1189
+ for (i = 0, length = included.length; i < length; i++) {
1190
+ const type = included[i].type;
1191
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1192
+ totalCount++;
1193
+ }
1194
+ }
1195
+ if (Array.isArray(jsonApiDoc.data)) {
1196
+ for (i = 0, length = jsonApiDoc.data.length; i < length; i++) {
1197
+ const type = jsonApiDoc.data[i].type;
1198
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1199
+ totalCount++;
1200
+ }
1201
+ } else if (jsonApiDoc.data) {
1202
+ const type = jsonApiDoc.data.type;
1203
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1204
+ totalCount++;
1205
+ }
1206
+ logGroup('cache', 'put', '<@document>', doc.content?.lid || doc.request?.url || 'unknown-request', `(${totalCount}) records`, '');
1207
+ let str = `\tContent Counts:`;
1208
+ Counts.forEach((count, type) => {
1209
+ str += `\n\t\t${type}: ${count} record${count > 1 ? 's' : ''}`;
1210
+ });
1211
+ if (Counts.size === 0) {
1212
+ str += `\t(empty)`;
1213
+ }
1214
+ // eslint-disable-next-line no-console
1215
+ console.log(str);
1216
+ // eslint-disable-next-line no-console
1217
+ console.log({
1218
+ lid: doc.content?.lid,
1219
+ content: structuredClone(doc.content),
1220
+ // we may need a specialized copy here
1221
+ request: doc.request,
1222
+ // structuredClone(doc.request),
1223
+ response: doc.response // structuredClone(doc.response),
1224
+ });
1225
+ // eslint-disable-next-line no-console
1226
+ console.groupEnd();
1227
+ }
1228
+ }
1229
+ if (included) {
1230
+ for (i = 0, length = included.length; i < length; i++) {
1231
+ included[i] = putOne(this, cacheKeyManager, included[i]);
1232
+ }
1233
+ }
1234
+ if (Array.isArray(jsonApiDoc.data)) {
1235
+ length = jsonApiDoc.data.length;
1236
+ const identifiers = [];
1237
+ for (i = 0; i < length; i++) {
1238
+ identifiers.push(putOne(this, cacheKeyManager, jsonApiDoc.data[i]));
1239
+ }
1240
+ return this._putDocument(doc, identifiers, included);
1241
+ }
1242
+ if (jsonApiDoc.data === null) {
1243
+ return this._putDocument(doc, null, included);
1244
+ }
1245
+ const identifier = putOne(this, cacheKeyManager, jsonApiDoc.data);
1246
+ return this._putDocument(doc, identifier, included);
1247
+ }
1248
+
1249
+ /** @internal */
1250
+
1251
+ /** @internal */
1252
+
1253
+ /** @internal */
1254
+
1255
+ /** @internal */
1256
+
1257
+ /** @internal */
1258
+ _putDocument(doc, data, included) {
1259
+ // @ts-expect-error narrowing within is just horrible in TS :/
1260
+ const resourceDocument = isErrorDocument(doc) ? fromStructuredError(doc) : fromBaseDocument(doc);
1261
+ if (data !== undefined) {
1262
+ resourceDocument.data = data;
1263
+ }
1264
+ if (included !== undefined) {
1265
+ (test => {
1266
+ if (!test) {
1267
+ throw new Error(`There should not be included data on an Error document`);
1268
+ }
1269
+ })(!isErrorDocument(doc));
1270
+ (test => {
1271
+ if (!test) {
1272
+ throw new Error(`There should not be included data on a Meta document`);
1273
+ }
1274
+ })(!isMetaDocument(doc));
1275
+ resourceDocument.included = included;
1276
+ }
1277
+ const request = doc.request;
1278
+ const identifier = request ? this._capabilities.cacheKeyManager.getOrCreateDocumentIdentifier(request) : null;
1279
+ if (identifier) {
1280
+ resourceDocument.lid = identifier.lid;
1281
+
1282
+ // @ts-expect-error
1283
+ doc.content = resourceDocument;
1284
+ const hasExisting = this.__documents.has(identifier.lid);
1285
+ this.__documents.set(identifier.lid, doc);
1286
+ this._capabilities.notifyChange(identifier, hasExisting ? 'updated' : 'added', null);
1287
+ }
1288
+ if (doc.request?.op === 'findHasMany') {
1289
+ const parentIdentifier = doc.request.options?.identifier;
1290
+ const parentField = doc.request.options?.field;
1291
+ (test => {
1292
+ if (!test) {
1293
+ throw new Error(`Expected a hasMany field`);
1294
+ }
1295
+ })(parentField?.kind === 'hasMany');
1296
+ (test => {
1297
+ if (!test) {
1298
+ throw new Error(`Expected a parent identifier for a findHasMany request`);
1299
+ }
1300
+ })(parentIdentifier && isResourceKey(parentIdentifier));
1301
+ if (parentField && parentIdentifier) {
1302
+ this.__graph.push({
1303
+ op: 'updateRelationship',
1304
+ record: parentIdentifier,
1305
+ field: parentField.name,
1306
+ value: resourceDocument
1307
+ });
1308
+ }
1309
+ }
1310
+ return resourceDocument;
1311
+ }
1312
+
1313
+ /**
1314
+ * Update the "remote" or "canonical" (persisted) state of the Cache
1315
+ * by merging new information into the existing state.
1316
+ *
1317
+ * @category Cache Management
1318
+ * @public
1319
+ * @param op the operation or list of operations to perform
1320
+ */
1321
+ patch(op) {
1322
+ if (Array.isArray(op)) {
1323
+ {
1324
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1325
+ logGroup('cache', 'patch', '<BATCH>', String(op.length) + ' operations', '', '');
1326
+ }
1327
+ }
1328
+ assertPrivateCapabilities(this._capabilities);
1329
+ this._capabilities._store._join(() => {
1330
+ for (const operation of op) {
1331
+ patchCache(this, operation);
1332
+ }
1333
+ });
1334
+ {
1335
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1336
+ // eslint-disable-next-line no-console
1337
+ console.groupEnd();
1338
+ }
1339
+ }
1340
+ } else {
1341
+ patchCache(this, op);
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * Update the "local" or "current" (unpersisted) state of the Cache
1347
+ *
1348
+ * @category Cache Management
1349
+ * @public
1350
+ */
1351
+ mutate(mutation) {
1352
+ {
1353
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1354
+ logGroup('cache', 'mutate', mutation.record.type, mutation.record.lid, mutation.field, mutation.op);
1355
+ try {
1356
+ const _data = JSON.parse(JSON.stringify(mutation));
1357
+ // eslint-disable-next-line no-console
1358
+ console.log(_data);
1359
+ } catch {
1360
+ // eslint-disable-next-line no-console
1361
+ console.log(mutation);
1362
+ }
1363
+ }
1364
+ }
1365
+ this.__graph.update(mutation, false);
1366
+ {
1367
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1368
+ // eslint-disable-next-line no-console
1369
+ console.groupEnd();
1370
+ }
1371
+ }
1372
+ }
1373
+
1374
+ /**
1375
+ * Peek resource data from the Cache.
1376
+ *
1377
+ * In development, if the return value
1378
+ * is JSON the return value
1379
+ * will be deep-cloned and deep-frozen
1380
+ * to prevent mutation thereby enforcing cache
1381
+ * Immutability.
1382
+ *
1383
+ * This form of peek is useful for implementations
1384
+ * that want to feed raw-data from cache to the UI
1385
+ * or which want to interact with a blob of data
1386
+ * directly from the presentation cache.
1387
+ *
1388
+ * An implementation might want to do this because
1389
+ * de-referencing records which read from their own
1390
+ * blob is generally safer because the record does
1391
+ * not require retainining connections to the Store
1392
+ * and Cache to present data on a per-field basis.
1393
+ *
1394
+ * This generally takes the place of `getAttr` as
1395
+ * an API and may even take the place of `getRelationship`
1396
+ * depending on implementation specifics, though this
1397
+ * latter usage is less recommended due to the advantages
1398
+ * of the Graph handling necessary entanglements and
1399
+ * notifications for relational data.
1400
+ *
1401
+ * :::warning
1402
+ * It is not recommended to use the return value as
1403
+ * a serialized representation of the resource both
1404
+ * due to it containing local mutations and because
1405
+ * it may contain additional fields not recognized
1406
+ * by the {json:api} API implementation such as `lid` and
1407
+ * the various internal WarpDrive bookkeeping fields.
1408
+ * :::
1409
+ *
1410
+ * @category Cache Management
1411
+ * @public
1412
+ */
1413
+
1414
+ peek(identifier) {
1415
+ if (isResourceKey(identifier)) {
1416
+ const peeked = this.__safePeek(identifier, false);
1417
+ if (!peeked) {
1418
+ return null;
1419
+ }
1420
+ const {
1421
+ type,
1422
+ id,
1423
+ lid
1424
+ } = identifier;
1425
+ const attributes = structuredClone(Object.assign({}, peeked.remoteAttrs, peeked.inflightAttrs, peeked.localAttrs));
1426
+ const relationships = {};
1427
+ const rels = this.__graph.identifiers.get(identifier);
1428
+ if (rels) {
1429
+ Object.keys(rels).forEach(key => {
1430
+ const rel = rels[key];
1431
+ if (rel.definition.isImplicit) {
1432
+ return;
1433
+ } else {
1434
+ relationships[key] = this.__graph.getData(identifier, key);
1435
+ }
1436
+ });
1437
+ }
1438
+ assertPrivateCapabilities(this._capabilities);
1439
+ const store = this._capabilities._store;
1440
+ const attrs = getCacheFields(this, identifier);
1441
+ attrs.forEach((attr, key) => {
1442
+ if (key in attributes && attributes[key] !== undefined) {
1443
+ return;
1444
+ }
1445
+ const defaultValue = getDefaultValue(attr, identifier, store);
1446
+ if (defaultValue !== undefined) {
1447
+ attributes[key] = defaultValue;
1448
+ }
1449
+ });
1450
+ return {
1451
+ type,
1452
+ id,
1453
+ lid,
1454
+ attributes,
1455
+ relationships
1456
+ };
1457
+ }
1458
+ const document = this.peekRequest(identifier);
1459
+ if (document) {
1460
+ if ('content' in document) return document.content;
1461
+ }
1462
+ return null;
1463
+ }
1464
+
1465
+ /**
1466
+ * Peek the remote resource data from the Cache.
1467
+ *
1468
+ * @category Cache Management
1469
+ * @public
1470
+ */
1471
+
1472
+ peekRemoteState(identifier) {
1473
+ if (isResourceKey(identifier)) {
1474
+ const peeked = this.__safePeek(identifier, false);
1475
+ if (!peeked) {
1476
+ return null;
1477
+ }
1478
+ const {
1479
+ type,
1480
+ id,
1481
+ lid
1482
+ } = identifier;
1483
+ const attributes = structuredClone(peeked.remoteAttrs);
1484
+ const relationships = {};
1485
+ const rels = this.__graph.identifiers.get(identifier);
1486
+ if (rels) {
1487
+ Object.keys(rels).forEach(key => {
1488
+ const rel = rels[key];
1489
+ if (rel.definition.isImplicit) {
1490
+ return;
1491
+ } else {
1492
+ relationships[key] = structuredClone(this.__graph.getData(identifier, key));
1493
+ }
1494
+ });
1495
+ }
1496
+ assertPrivateCapabilities(this._capabilities);
1497
+ const store = this._capabilities._store;
1498
+ const attrs = getCacheFields(this, identifier);
1499
+ attrs.forEach((attr, key) => {
1500
+ if (key in attributes && attributes[key] !== undefined) {
1501
+ return;
1502
+ }
1503
+ const defaultValue = getDefaultValue(attr, identifier, store);
1504
+ if (defaultValue !== undefined) {
1505
+ attributes[key] = defaultValue;
1506
+ }
1507
+ });
1508
+ return {
1509
+ type,
1510
+ id,
1511
+ lid,
1512
+ attributes,
1513
+ relationships
1514
+ };
1515
+ }
1516
+ const document = this.peekRequest(identifier);
1517
+ if (document) {
1518
+ if ('content' in document) return document.content;
1519
+ }
1520
+ return null;
1521
+ }
1522
+
1523
+ /**
1524
+ * Peek the Cache for the existing request data associated with
1525
+ * a cacheable request.
1526
+ *
1527
+ * This is effectively the reverse of `put` for a request in
1528
+ * that it will return the the request, response, and content
1529
+ * whereas `peek` will return just the `content`.
1530
+ *
1531
+ * @category Cache Management
1532
+ * @public
1533
+ */
1534
+ peekRequest(identifier) {
1535
+ return this.__documents.get(identifier.lid) || null;
1536
+ }
1537
+
1538
+ /**
1539
+ * Push resource data from a remote source into the cache for this identifier
1540
+ *
1541
+ * @category Cache Management
1542
+ * @public
1543
+ * @return if `calculateChanges` is true then calculated key changes should be returned
1544
+ */
1545
+ upsert(identifier, data, calculateChanges) {
1546
+ assertPrivateCapabilities(this._capabilities);
1547
+ const store = this._capabilities._store;
1548
+ if (!store._cbs) {
1549
+ let result = undefined;
1550
+ store._run(() => {
1551
+ result = cacheUpsert(this, identifier, data, calculateChanges);
1552
+ });
1553
+ return result;
1554
+ }
1555
+ return cacheUpsert(this, identifier, data, calculateChanges);
1556
+ }
1557
+
1558
+ ////////// ============= //////////
1559
+ ////////// Cache Forking //////////
1560
+ ////////// ============= //////////
1561
+
1562
+ /**
1563
+ * Create a fork of the cache from the current state.
1564
+ *
1565
+ * Applications should typically not call this method themselves,
1566
+ * preferring instead to fork at the Store level, which will
1567
+ * utilize this method to fork the cache.
1568
+ *
1569
+ * @category Cache Forking
1570
+ * @private
1571
+ */
1572
+ fork() {
1573
+ throw new Error(`Not Implemented`);
1574
+ }
1575
+
1576
+ /**
1577
+ * Merge a fork back into a parent Cache.
1578
+ *
1579
+ * Applications should typically not call this method themselves,
1580
+ * preferring instead to merge at the Store level, which will
1581
+ * utilize this method to merge the caches.
1582
+ *
1583
+ * @category Cache Forking
1584
+ * @private
1585
+ */
1586
+ merge(_cache) {
1587
+ throw new Error(`Not Implemented`);
1588
+ }
1589
+
1590
+ /**
1591
+ * Generate the list of changes applied to all
1592
+ * record in the store.
1593
+ *
1594
+ * Each individual resource or document that has
1595
+ * been mutated should be described as an individual
1596
+ * `Change` entry in the returned array.
1597
+ *
1598
+ * A `Change` is described by an object containing up to
1599
+ * three properties: (1) the `identifier` of the entity that
1600
+ * changed; (2) the `op` code of that change being one of
1601
+ * `upsert` or `remove`, and if the op is `upsert` a `patch`
1602
+ * containing the data to merge into the cache for the given
1603
+ * entity.
1604
+ *
1605
+ * This `patch` is opaque to the Store but should be understood
1606
+ * by the Cache and may expect to be utilized by an Adapter
1607
+ * when generating data during a `save` operation.
1608
+ *
1609
+ * It is generally recommended that the `patch` contain only
1610
+ * the updated state, ignoring fields that are unchanged
1611
+ *
1612
+ * ```ts
1613
+ * interface Change {
1614
+ * identifier: ResourceKey | RequestKey;
1615
+ * op: 'upsert' | 'remove';
1616
+ * patch?: unknown;
1617
+ * }
1618
+ * ```
1619
+ *
1620
+ * @category Cache Forking
1621
+ * @private
1622
+ */
1623
+ diff() {
1624
+ throw new Error(`Not Implemented`);
1625
+ }
1626
+
1627
+ ////////// =========== //////////
1628
+ ////////// SSR Support //////////
1629
+ ////////// =========== //////////
1630
+
1631
+ /**
1632
+ * Serialize the entire contents of the Cache into a Stream
1633
+ * which may be fed back into a new instance of the same Cache
1634
+ * via `cache.hydrate`.
1635
+ *
1636
+ * @category SSR Support
1637
+ * @private
1638
+ */
1639
+ dump() {
1640
+ throw new Error(`Not Implemented`);
1641
+ }
1642
+
1643
+ /**
1644
+ * hydrate a Cache from a Stream with content previously serialized
1645
+ * from another instance of the same Cache, resolving when hydration
1646
+ * is complete.
1647
+ *
1648
+ * This method should expect to be called both in the context of restoring
1649
+ * the Cache during application rehydration after SSR **AND** at unknown
1650
+ * times during the lifetime of an already booted application when it is
1651
+ * desired to bulk-load additional information into the cache. This latter
1652
+ * behavior supports optimizing pre/fetching of data for route transitions
1653
+ * via data-only SSR modes.
1654
+ *
1655
+ * @category SSR Support
1656
+ * @private
1657
+ */
1658
+ hydrate(stream) {
1659
+ throw new Error('Not Implemented');
1660
+ }
1661
+
1662
+ ////////// ================== //////////
1663
+ ////////// Resource Lifecycle //////////
1664
+ ////////// ================== //////////
1665
+
1666
+ /**
1667
+ * [LIFECYCLE] Signal to the cache that a new record has been instantiated on the client
1668
+ *
1669
+ * It returns properties from options that should be set on the record during the create
1670
+ * process. This return value behavior is deprecated.
1671
+ *
1672
+ * @category Resource Lifecycle
1673
+ * @public
1674
+ */
1675
+ clientDidCreate(identifier, options) {
1676
+ {
1677
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1678
+ try {
1679
+ const _data = options ? JSON.parse(JSON.stringify(options)) : options;
1680
+ // eslint-disable-next-line no-console
1681
+ console.log(`WarpDrive | Mutation - clientDidCreate ${identifier.lid}`, _data);
1682
+ } catch {
1683
+ // eslint-disable-next-line no-console
1684
+ console.log(`WarpDrive | Mutation - clientDidCreate ${identifier.lid}`, options);
1685
+ }
1686
+ }
1687
+ }
1688
+ const cached = this._createCache(identifier);
1689
+ cached.isNew = true;
1690
+ const createOptions = {};
1691
+ if (options !== undefined) {
1692
+ const fields = getCacheFields(this, identifier);
1693
+ const graph = this.__graph;
1694
+ const propertyNames = Object.keys(options);
1695
+ for (let i = 0; i < propertyNames.length; i++) {
1696
+ const name = propertyNames[i];
1697
+ const propertyValue = options[name];
1698
+ if (name === 'id') {
1699
+ continue;
1700
+ }
1701
+ const fieldType = fields.get(name);
1702
+ const kind = fieldType !== undefined ? 'kind' in fieldType ? fieldType.kind : 'attribute' : null;
1703
+ let relationship;
1704
+ switch (kind) {
1705
+ case 'attribute':
1706
+ this.setAttr(identifier, name, propertyValue);
1707
+ createOptions[name] = propertyValue;
1708
+ break;
1709
+ case 'belongsTo':
1710
+ this.mutate({
1711
+ op: 'replaceRelatedRecord',
1712
+ field: name,
1713
+ record: identifier,
1714
+ value: propertyValue
1715
+ });
1716
+ relationship = graph.get(identifier, name);
1717
+ relationship.state.hasReceivedData = true;
1718
+ relationship.state.isEmpty = false;
1719
+ break;
1720
+ case 'hasMany':
1721
+ this.mutate({
1722
+ op: 'replaceRelatedRecords',
1723
+ field: name,
1724
+ record: identifier,
1725
+ value: propertyValue
1726
+ });
1727
+ relationship = graph.get(identifier, name);
1728
+ relationship.state.hasReceivedData = true;
1729
+ relationship.state.isEmpty = false;
1730
+ break;
1731
+ default:
1732
+ // reflect back (pass-thru) unknown properties
1733
+ createOptions[name] = propertyValue;
1734
+ }
1735
+ }
1736
+ }
1737
+ this._capabilities.notifyChange(identifier, 'added', null);
1738
+ return createOptions;
1739
+ }
1740
+
1741
+ /**
1742
+ * [LIFECYCLE] Signals to the cache that a resource
1743
+ * will be part of a save transaction.
1744
+ *
1745
+ * @category Resource Lifecycle
1746
+ * @public
1747
+ */
1748
+ willCommit(identifier, _context) {
1749
+ if (Array.isArray(identifier)) {
1750
+ for (const key of identifier) {
1751
+ willCommit(this, key);
1752
+ }
1753
+ } else {
1754
+ willCommit(this, identifier);
1755
+ }
1756
+ }
1757
+
1758
+ /**
1759
+ * [LIFECYCLE] Signals to the cache that a resource
1760
+ * was successfully updated as part of a save transaction.
1761
+ *
1762
+ * @category Resource Lifecycle
1763
+ * @public
1764
+ */
1765
+
1766
+ didCommit(committedIdentifier, result) {
1767
+ const payload = result ? result.content : null;
1768
+ const operation = result?.request?.op ?? null;
1769
+ const data = payload && payload.data;
1770
+ {
1771
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1772
+ try {
1773
+ const payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
1774
+ // eslint-disable-next-line no-console
1775
+ console.log(`WarpDrive | Payload - ${operation}`, payloadCopy);
1776
+ } catch {
1777
+ // eslint-disable-next-line no-console
1778
+ console.log(`WarpDrive | Payload - ${operation}`, payload);
1779
+ }
1780
+ }
1781
+ }
1782
+ const responseIsCollection = Array.isArray(data);
1783
+ const hasMultipleIdentifiers = Array.isArray(committedIdentifier) && committedIdentifier.length > 1;
1784
+ if (Array.isArray(committedIdentifier)) {
1785
+ // if we get back an array of primary data, we treat each
1786
+ // entry as a separate commit for each identifier
1787
+ (test => {
1788
+ if (!test) {
1789
+ throw new Error(`Expected the array of primary data to match the array of committed identifiers`);
1790
+ }
1791
+ })(!hasMultipleIdentifiers || !responseIsCollection || data.length === committedIdentifier.length);
1792
+ if (responseIsCollection) {
1793
+ for (let i = 0; i < committedIdentifier.length; i++) {
1794
+ const identifier = committedIdentifier[i];
1795
+ didCommit(this, identifier, data[i] ?? null, operation);
1796
+ }
1797
+ // but if we get back no data or a single entry, we apply
1798
+ // the change back to the original identifier
1799
+ } else {
1800
+ for (let i = 0; i < committedIdentifier.length; i++) {
1801
+ const identifier = committedIdentifier[i];
1802
+ didCommit(this, identifier, i === 0 ? data : null, operation);
1803
+ }
1804
+ }
1805
+ } else {
1806
+ didCommit(this, committedIdentifier, data, operation);
1807
+ }
1808
+ const included = payload && payload.included;
1809
+ const {
1810
+ cacheKeyManager
1811
+ } = this._capabilities;
1812
+ if (included) {
1813
+ for (let i = 0, length = included.length; i < length; i++) {
1814
+ putOne(this, cacheKeyManager, included[i]);
1815
+ }
1816
+ }
1817
+ return hasMultipleIdentifiers && responseIsCollection ? {
1818
+ data: committedIdentifier
1819
+ } : {
1820
+ data: Array.isArray(committedIdentifier) ? committedIdentifier[0] : committedIdentifier
1821
+ };
1822
+ }
1823
+
1824
+ /**
1825
+ * [LIFECYCLE] Signals to the cache that a resource
1826
+ * was update via a save transaction failed.
1827
+ *
1828
+ * @category Resource Lifecycle
1829
+ * @public
1830
+ */
1831
+ commitWasRejected(identifier, errors) {
1832
+ if (Array.isArray(identifier)) {
1833
+ for (let i = 0; i < identifier.length; i++) {
1834
+ commitDidError(this, identifier[i], errors && i === 0 ? errors : null);
1835
+ }
1836
+ return;
1837
+ }
1838
+ return commitDidError(this, identifier, errors || null);
1839
+ }
1840
+
1841
+ /**
1842
+ * [LIFECYCLE] Signals to the cache that all data for a resource
1843
+ * should be cleared.
1844
+ *
1845
+ * This method is a candidate to become a mutation
1846
+ *
1847
+ * @category Resource Lifecycle
1848
+ * @public
1849
+ */
1850
+ unloadRecord(identifier) {
1851
+ const storeWrapper = this._capabilities;
1852
+ // TODO this is necessary because
1853
+ // we maintain memebership inside InstanceCache
1854
+ // for peekAll, so even though we haven't created
1855
+ // any data we think this exists.
1856
+ // TODO can we eliminate that membership now?
1857
+ if (!this.__cache.has(identifier)) {
1858
+ // the graph may still need to unload identity
1859
+ peekGraph(storeWrapper)?.unload(identifier);
1860
+ return;
1861
+ }
1862
+ const removeFromRecordArray = !this.isDeletionCommitted(identifier);
1863
+ let removed = false;
1864
+ const cached = this.__peek(identifier, false);
1865
+ if (cached.isNew || cached.isDeletionCommitted) {
1866
+ peekGraph(storeWrapper)?.push({
1867
+ op: 'deleteRecord',
1868
+ record: identifier,
1869
+ isNew: cached.isNew
1870
+ });
1871
+ } else {
1872
+ peekGraph(storeWrapper)?.unload(identifier);
1873
+ }
1874
+
1875
+ // effectively clearing these is ensuring that
1876
+ // we report as `isEmpty` during teardown.
1877
+ cached.localAttrs = null;
1878
+ cached.remoteAttrs = null;
1879
+ cached.defaultAttrs = null;
1880
+ cached.inflightAttrs = null;
1881
+ const relatedIdentifiers = _allRelatedIdentifiers(storeWrapper, identifier);
1882
+ if (areAllModelsUnloaded(storeWrapper, relatedIdentifiers)) {
1883
+ for (let i = 0; i < relatedIdentifiers.length; ++i) {
1884
+ const relatedIdentifier = relatedIdentifiers[i];
1885
+ storeWrapper.notifyChange(relatedIdentifier, 'removed', null);
1886
+ removed = true;
1887
+ storeWrapper.disconnectRecord(relatedIdentifier);
1888
+ }
1889
+ }
1890
+ this.__cache.delete(identifier);
1891
+ this.__destroyedCache.set(identifier, cached);
1892
+
1893
+ /*
1894
+ * The destroy cache is a hack to prevent applications
1895
+ * from blowing up during teardown. Accessing state
1896
+ * on a destroyed record is not safe, but historically
1897
+ * was possible due to a combination of teardown timing
1898
+ * and retention of cached state directly on the
1899
+ * record itself.
1900
+ *
1901
+ * Once we have deprecated accessing state on a destroyed
1902
+ * instance we may remove this. The timing isn't a huge deal
1903
+ * as momentarily retaining the objects outside the bounds
1904
+ * of a test won't cause issues.
1905
+ */
1906
+ if (this.__destroyedCache.size === 1) {
1907
+ // TODO do we still need this?
1908
+ setTimeout(() => {
1909
+ this.__destroyedCache.clear();
1910
+ }, 100);
1911
+ }
1912
+ if (!removed && removeFromRecordArray) {
1913
+ storeWrapper.notifyChange(identifier, 'removed', null);
1914
+ }
1915
+ }
1916
+
1917
+ ////////// ============= //////////
1918
+ ////////// Resource Data //////////
1919
+ ////////// ============= //////////
1920
+
1921
+ /**
1922
+ * Retrieve the data for an attribute from the cache
1923
+ * with local mutations applied.
1924
+ *
1925
+ * @category Resource Data
1926
+ * @public
1927
+ */
1928
+ getAttr(identifier, attr) {
1929
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
1930
+ if (Array.isArray(attr) && attr.length === 1) {
1931
+ attr = attr[0];
1932
+ }
1933
+ if (isSimplePath) {
1934
+ const attribute = attr;
1935
+ const cached = this.__peek(identifier, true);
1936
+ (test => {
1937
+ if (!test) {
1938
+ throw new Error(`Cannot retrieve attributes for identifier ${String(identifier)} as it is not present in the cache`);
1939
+ }
1940
+ })(cached);
1941
+
1942
+ // in Prod we try to recover when accessing something that
1943
+ // doesn't exist
1944
+ if (!cached) {
1945
+ return undefined;
1946
+ }
1947
+ if (cached.localAttrs && attribute in cached.localAttrs) {
1948
+ return cached.localAttrs[attribute];
1949
+ } else if (cached.inflightAttrs && attribute in cached.inflightAttrs) {
1950
+ return cached.inflightAttrs[attribute];
1951
+ } else if (cached.remoteAttrs && attribute in cached.remoteAttrs) {
1952
+ return cached.remoteAttrs[attribute];
1953
+ } else if (cached.defaultAttrs && attribute in cached.defaultAttrs) {
1954
+ return cached.defaultAttrs[attribute];
1955
+ } else {
1956
+ const attrSchema = getCacheFields(this, identifier).get(attribute);
1957
+ assertPrivateCapabilities(this._capabilities);
1958
+ const defaultValue = getDefaultValue(attrSchema, identifier, this._capabilities._store);
1959
+ if (schemaHasLegacyDefaultValueFn(attrSchema)) {
1960
+ cached.defaultAttrs = cached.defaultAttrs || Object.create(null);
1961
+ cached.defaultAttrs[attribute] = defaultValue;
1962
+ }
1963
+ return defaultValue;
1964
+ }
1965
+ }
1966
+
1967
+ // TODO @runspired consider whether we need a defaultValue cache in ReactiveResource
1968
+ // like we do for the simple case above.
1969
+ const path = attr;
1970
+ const cached = this.__peek(identifier, true);
1971
+ const basePath = path[0];
1972
+ let current = cached.localAttrs && basePath in cached.localAttrs ? cached.localAttrs[basePath] : undefined;
1973
+ if (current === undefined) {
1974
+ current = cached.inflightAttrs && basePath in cached.inflightAttrs ? cached.inflightAttrs[basePath] : undefined;
1975
+ }
1976
+ if (current === undefined) {
1977
+ current = cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
1978
+ }
1979
+ if (current === undefined) {
1980
+ return undefined;
1981
+ }
1982
+ for (let i = 1; i < path.length; i++) {
1983
+ current = current[path[i]];
1984
+ if (current === undefined) {
1985
+ return undefined;
1986
+ }
1987
+ }
1988
+ return current;
1989
+ }
1990
+
1991
+ /**
1992
+ * Retrieve the remote data for an attribute from the cache
1993
+ *
1994
+ * @category Resource Data
1995
+ * @public
1996
+ */
1997
+ getRemoteAttr(identifier, attr) {
1998
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
1999
+ if (Array.isArray(attr) && attr.length === 1) {
2000
+ attr = attr[0];
2001
+ }
2002
+ if (isSimplePath) {
2003
+ const attribute = attr;
2004
+ const cached = this.__peek(identifier, true);
2005
+ (test => {
2006
+ if (!test) {
2007
+ throw new Error(`Cannot retrieve remote attributes for identifier ${String(identifier)} as it is not present in the cache`);
2008
+ }
2009
+ })(cached);
2010
+
2011
+ // in Prod we try to recover when accessing something that
2012
+ // doesn't exist
2013
+ if (!cached) {
2014
+ return undefined;
2015
+ }
2016
+ if (cached.remoteAttrs && attribute in cached.remoteAttrs) {
2017
+ return cached.remoteAttrs[attribute];
2018
+
2019
+ // we still show defaultValues in the case of a remoteAttr access
2020
+ } else if (cached.defaultAttrs && attribute in cached.defaultAttrs) {
2021
+ return cached.defaultAttrs[attribute];
2022
+ } else {
2023
+ const attrSchema = getCacheFields(this, identifier).get(attribute);
2024
+ assertPrivateCapabilities(this._capabilities);
2025
+ const defaultValue = getDefaultValue(attrSchema, identifier, this._capabilities._store);
2026
+ if (schemaHasLegacyDefaultValueFn(attrSchema)) {
2027
+ cached.defaultAttrs = cached.defaultAttrs || Object.create(null);
2028
+ cached.defaultAttrs[attribute] = defaultValue;
2029
+ }
2030
+ return defaultValue;
2031
+ }
2032
+ }
2033
+
2034
+ // TODO @runspired consider whether we need a defaultValue cache in ReactiveResource
2035
+ // like we do for the simple case above.
2036
+ const path = attr;
2037
+ const cached = this.__peek(identifier, true);
2038
+ const basePath = path[0];
2039
+ let current = cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
2040
+ if (current === undefined) {
2041
+ return undefined;
2042
+ }
2043
+ for (let i = 1; i < path.length; i++) {
2044
+ current = current[path[i]];
2045
+ if (current === undefined) {
2046
+ return undefined;
2047
+ }
2048
+ }
2049
+ return current;
2050
+ }
2051
+
2052
+ /**
2053
+ * Mutate the data for an attribute in the cache
2054
+ *
2055
+ * This method is a candidate to become a mutation
2056
+ *
2057
+ * @category Resource Data
2058
+ * @public
2059
+ */
2060
+ setAttr(identifier, attr, value) {
2061
+ // this assert works to ensure we have a non-empty string and/or a non-empty array
2062
+ (test => {
2063
+ if (!test) {
2064
+ throw new Error('setAttr must receive at least one attribute path');
2065
+ }
2066
+ })(attr.length > 0);
2067
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
2068
+ if (Array.isArray(attr) && attr.length === 1) {
2069
+ attr = attr[0];
2070
+ }
2071
+ if (isSimplePath) {
2072
+ const cached = this.__peek(identifier, false);
2073
+ const currentAttr = attr;
2074
+ const existing = cached.inflightAttrs && currentAttr in cached.inflightAttrs ? cached.inflightAttrs[currentAttr] : cached.remoteAttrs && currentAttr in cached.remoteAttrs ? cached.remoteAttrs[currentAttr] : undefined;
2075
+ if (existing !== value) {
2076
+ cached.localAttrs = cached.localAttrs || Object.create(null);
2077
+ cached.localAttrs[currentAttr] = value;
2078
+ cached.changes = cached.changes || Object.create(null);
2079
+ cached.changes[currentAttr] = [existing, value];
2080
+ } else if (cached.localAttrs) {
2081
+ delete cached.localAttrs[currentAttr];
2082
+ delete cached.changes[currentAttr];
2083
+ }
2084
+ if (cached.defaultAttrs && currentAttr in cached.defaultAttrs) {
2085
+ delete cached.defaultAttrs[currentAttr];
2086
+ }
2087
+ this._capabilities.notifyChange(identifier, 'attributes', currentAttr);
2088
+ return;
2089
+ }
2090
+
2091
+ // get current value from local else inflight else remote
2092
+ // structuredClone current if not local (or always?)
2093
+ // traverse path, update value at path
2094
+ // notify change at first link in path.
2095
+ // second pass optimization is change notifyChange signature to take an array path
2096
+
2097
+ // guaranteed that we have path of at least 2 in length
2098
+ const path = attr;
2099
+ const cached = this.__peek(identifier, false);
2100
+
2101
+ // get existing cache record for base path
2102
+ const basePath = path[0];
2103
+ const existing = cached.inflightAttrs && basePath in cached.inflightAttrs ? cached.inflightAttrs[basePath] : cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
2104
+ let existingAttr;
2105
+ if (existing) {
2106
+ existingAttr = existing[path[1]];
2107
+ for (let i = 2; i < path.length; i++) {
2108
+ // the specific change we're making is at path[length - 1]
2109
+ existingAttr = existingAttr[path[i]];
2110
+ }
2111
+ }
2112
+ if (existingAttr !== value) {
2113
+ cached.localAttrs = cached.localAttrs || Object.create(null);
2114
+ cached.localAttrs[basePath] = cached.localAttrs[basePath] || structuredClone(existing);
2115
+ cached.changes = cached.changes || Object.create(null);
2116
+ let currentLocal = cached.localAttrs[basePath];
2117
+ let nextLink = 1;
2118
+ while (nextLink < path.length - 1) {
2119
+ currentLocal = currentLocal[path[nextLink++]];
2120
+ }
2121
+ currentLocal[path[nextLink]] = value;
2122
+ cached.changes[basePath] = [existing, cached.localAttrs[basePath]];
2123
+
2124
+ // since we initiaize the value as basePath as a clone of the value at the remote basePath
2125
+ // then in theory we can use JSON.stringify to compare the two values as key insertion order
2126
+ // ought to be consistent.
2127
+ // we try/catch this because users have a habit of doing "Bad Things"TM wherein the cache contains
2128
+ // stateful values that are not JSON serializable correctly such as Dates.
2129
+ // in the case that we error, we fallback to not removing the local value
2130
+ // so that any changes we don't understand are preserved. Thse objects would then sometimes
2131
+ // appear to be dirty unnecessarily, and for folks that open an issue we can guide them
2132
+ // to make their cache data less stateful.
2133
+ } else if (cached.localAttrs) {
2134
+ try {
2135
+ if (!existing) {
2136
+ return;
2137
+ }
2138
+ const existingStr = JSON.stringify(existing);
2139
+ const newStr = JSON.stringify(cached.localAttrs[basePath]);
2140
+ if (existingStr !== newStr) {
2141
+ delete cached.localAttrs[basePath];
2142
+ delete cached.changes[basePath];
2143
+ }
2144
+ } catch {
2145
+ // noop
2146
+ }
2147
+ }
2148
+ this._capabilities.notifyChange(identifier, 'attributes', basePath);
2149
+ }
2150
+
2151
+ /**
2152
+ * Query the cache for the changed attributes of a resource.
2153
+ *
2154
+ * @category Resource Data
2155
+ * @public
2156
+ * @return `{ '<field>': ['<old>', '<new>'] }`
2157
+ */
2158
+ changedAttrs(identifier) {
2159
+ const cached = this.__peek(identifier, false);
2160
+ (test => {
2161
+ if (!test) {
2162
+ throw new Error(`Cannot retrieve changed attributes for identifier ${String(identifier)} as it is not present in the cache`);
2163
+ }
2164
+ })(cached);
2165
+
2166
+ // in Prod we try to recover when accessing something that
2167
+ // doesn't exist
2168
+ if (!cached) {
2169
+ return Object.create(null);
2170
+ }
2171
+
2172
+ // TODO freeze in dev
2173
+ return cached.changes || Object.create(null);
2174
+ }
2175
+
2176
+ /**
2177
+ * Query the cache for whether any mutated attributes exist
2178
+ *
2179
+ * @category Resource Data
2180
+ * @public
2181
+ */
2182
+ hasChangedAttrs(identifier) {
2183
+ const cached = this.__peek(identifier, true);
2184
+ (test => {
2185
+ if (!test) {
2186
+ throw new Error(`Cannot retrieve changed attributes for identifier ${String(identifier)} as it is not present in the cache`);
2187
+ }
2188
+ })(cached);
2189
+
2190
+ // in Prod we try to recover when accessing something that
2191
+ // doesn't exist
2192
+ if (!cached) {
2193
+ return false;
2194
+ }
2195
+ return cached.inflightAttrs !== null && Object.keys(cached.inflightAttrs).length > 0 || cached.localAttrs !== null && Object.keys(cached.localAttrs).length > 0;
2196
+ }
2197
+
2198
+ /**
2199
+ * Tell the cache to discard any uncommitted mutations to attributes
2200
+ *
2201
+ * This method is a candidate to become a mutation
2202
+ *
2203
+ * @category Resource Data
2204
+ * @public
2205
+ * @return the names of fields that were restored
2206
+ */
2207
+ rollbackAttrs(identifier) {
2208
+ const cached = this.__peek(identifier, false);
2209
+ let dirtyKeys;
2210
+ cached.isDeleted = false;
2211
+ if (cached.localAttrs !== null) {
2212
+ dirtyKeys = Object.keys(cached.localAttrs);
2213
+ cached.localAttrs = null;
2214
+ cached.changes = null;
2215
+ }
2216
+ if (cached.isNew) {
2217
+ // > Note: Graph removal handled by unloadRecord
2218
+ cached.isDeletionCommitted = true;
2219
+ cached.isDeleted = true;
2220
+ cached.isNew = false;
2221
+ }
2222
+ cached.inflightAttrs = null;
2223
+ cached.defaultAttrs = null;
2224
+ if (cached.errors) {
2225
+ cached.errors = null;
2226
+ this._capabilities.notifyChange(identifier, 'errors', null);
2227
+ }
2228
+ this._capabilities.notifyChange(identifier, 'state', null);
2229
+ if (dirtyKeys && dirtyKeys.length) {
2230
+ notifyAttributes(this._capabilities, identifier, new Set(dirtyKeys));
2231
+ }
2232
+ return dirtyKeys || [];
2233
+ }
2234
+
2235
+ /**
2236
+ * Query the cache for the changes to relationships of a resource.
2237
+ *
2238
+ * Returns a map of relationship names to RelationshipDiff objects.
2239
+ *
2240
+ * ```ts
2241
+ * type RelationshipDiff =
2242
+ | {
2243
+ kind: 'collection';
2244
+ remoteState: ResourceKey[];
2245
+ additions: Set<ResourceKey>;
2246
+ removals: Set<ResourceKey>;
2247
+ localState: ResourceKey[];
2248
+ reordered: boolean;
2249
+ }
2250
+ | {
2251
+ kind: 'resource';
2252
+ remoteState: ResourceKey | null;
2253
+ localState: ResourceKey | null;
2254
+ };
2255
+ ```
2256
+ *
2257
+ * @category Resource Data
2258
+ * @public
2259
+ */
2260
+ changedRelationships(identifier) {
2261
+ return this.__graph.getChanged(identifier);
2262
+ }
2263
+
2264
+ /**
2265
+ * Query the cache for whether any mutated relationships exist
2266
+ *
2267
+ * @category Resource Data
2268
+ * @public
2269
+ */
2270
+ hasChangedRelationships(identifier) {
2271
+ return this.__graph.hasChanged(identifier);
2272
+ }
2273
+
2274
+ /**
2275
+ * Tell the cache to discard any uncommitted mutations to relationships.
2276
+ *
2277
+ * This will also discard the change on any appropriate inverses.
2278
+ *
2279
+ * This method is a candidate to become a mutation
2280
+ *
2281
+ * @category Resource Data
2282
+ * @public
2283
+ * @return the names of relationships that were restored
2284
+ */
2285
+ rollbackRelationships(identifier) {
2286
+ assertPrivateCapabilities(this._capabilities);
2287
+ let result;
2288
+ this._capabilities._store._join(() => {
2289
+ result = this.__graph.rollback(identifier);
2290
+ });
2291
+ return result;
2292
+ }
2293
+
2294
+ /**
2295
+ * Query the cache for the current state of a relationship property
2296
+ *
2297
+ * @category Resource Data
2298
+ * @public
2299
+ * @return resource relationship object
2300
+ */
2301
+ getRelationship(identifier, field) {
2302
+ return this.__graph.getData(identifier, field);
2303
+ }
2304
+
2305
+ /**
2306
+ * Query the cache for the remote state of a relationship property
2307
+ *
2308
+ * @category Resource Data
2309
+ * @public
2310
+ * @return resource relationship object
2311
+ */
2312
+ getRemoteRelationship(identifier, field) {
2313
+ return this.__graph.getRemoteData(identifier, field);
2314
+ }
2315
+
2316
+ ////////// ============== //////////
2317
+ ////////// Resource State //////////
2318
+ ////////// ============== //////////
2319
+
2320
+ /**
2321
+ * Update the cache state for the given resource to be marked
2322
+ * as locally deleted, or remove such a mark.
2323
+ *
2324
+ * This method is a candidate to become a mutation
2325
+ *
2326
+ * @category Resource State
2327
+ * @public
2328
+ */
2329
+ setIsDeleted(identifier, isDeleted) {
2330
+ const cached = this.__peek(identifier, false);
2331
+ cached.isDeleted = isDeleted;
2332
+ // > Note: Graph removal for isNew handled by unloadRecord
2333
+ this._capabilities.notifyChange(identifier, 'state', null);
2334
+ }
2335
+
2336
+ /**
2337
+ * Query the cache for any validation errors applicable to the given resource.
2338
+ *
2339
+ * @category Resource State
2340
+ * @public
2341
+ */
2342
+ getErrors(identifier) {
2343
+ return this.__peek(identifier, true).errors || [];
2344
+ }
2345
+
2346
+ /**
2347
+ * Query the cache for whether a given resource has any available data
2348
+ *
2349
+ * @category Resource State
2350
+ * @public
2351
+ */
2352
+ isEmpty(identifier) {
2353
+ const cached = this.__safePeek(identifier, true);
2354
+ return cached ? cached.remoteAttrs === null && cached.inflightAttrs === null && cached.localAttrs === null : true;
2355
+ }
2356
+
2357
+ /**
2358
+ * Query the cache for whether a given resource was created locally and not
2359
+ * yet persisted.
2360
+ *
2361
+ * @category Resource State
2362
+ * @public
2363
+ */
2364
+ isNew(identifier) {
2365
+ // TODO can we assert here?
2366
+ return this.__safePeek(identifier, true)?.isNew || false;
2367
+ }
2368
+
2369
+ /**
2370
+ * Query the cache for whether a given resource is marked as deleted (but not
2371
+ * necessarily persisted yet).
2372
+ *
2373
+ * @category Resource State
2374
+ * @public
2375
+ */
2376
+ isDeleted(identifier) {
2377
+ // TODO can we assert here?
2378
+ return this.__safePeek(identifier, true)?.isDeleted || false;
2379
+ }
2380
+
2381
+ /**
2382
+ * Query the cache for whether a given resource has been deleted and that deletion
2383
+ * has also been persisted.
2384
+ *
2385
+ * @category Resource State
2386
+ * @public
2387
+ */
2388
+ isDeletionCommitted(identifier) {
2389
+ // TODO can we assert here?
2390
+ return this.__safePeek(identifier, true)?.isDeletionCommitted || false;
2391
+ }
2392
+
2393
+ /**
2394
+ * Private method used to populate an entry for the identifier
2395
+ *
2396
+ * @internal
2397
+ */
2398
+ _createCache(identifier) {
2399
+ (test => {
2400
+ if (!test) {
2401
+ throw new Error(`Expected no resource data to yet exist in the cache`);
2402
+ }
2403
+ })(!this.__cache.has(identifier));
2404
+ const cache = makeCache();
2405
+ this.__cache.set(identifier, cache);
2406
+ return cache;
2407
+ }
2408
+
2409
+ /**
2410
+ * Peek whether we have cached resource data matching the identifier
2411
+ * without asserting if the resource data is missing.
2412
+ *
2413
+ * @internal
2414
+ */
2415
+ __safePeek(identifier, allowDestroyed) {
2416
+ let resource = this.__cache.get(identifier);
2417
+ if (!resource && allowDestroyed) {
2418
+ resource = this.__destroyedCache.get(identifier);
2419
+ }
2420
+ return resource;
2421
+ }
2422
+
2423
+ /**
2424
+ * Peek whether we have cached resource data matching the identifier
2425
+ * Asserts if the resource data is missing.
2426
+ *
2427
+ * @internal
2428
+ */
2429
+ __peek(identifier, allowDestroyed) {
2430
+ const resource = this.__safePeek(identifier, allowDestroyed);
2431
+ (test => {
2432
+ if (!test) {
2433
+ throw new Error(`Expected Cache to have a resource entry for the identifier ${String(identifier)} but none was found`);
2434
+ }
2435
+ })(resource);
2436
+ return resource;
2437
+ }
2438
+ }
2439
+ function addResourceToDocument(cache, op) {
2440
+ (test => {
2441
+ if (!test) {
2442
+ throw new Error(`Expected field to be either 'data' or 'included'`);
2443
+ }
2444
+ })(op.field === 'data' || op.field === 'included');
2445
+ const doc = cache.__documents.get(op.record.lid);
2446
+ (test => {
2447
+ if (!test) {
2448
+ throw new Error(`Expected to have a cached document on which to perform the add operation`);
2449
+ }
2450
+ })(doc);
2451
+ (test => {
2452
+ if (!test) {
2453
+ throw new Error(`Expected to have content on the document`);
2454
+ }
2455
+ })(doc.content);
2456
+ const {
2457
+ content
2458
+ } = doc;
2459
+ if (op.field === 'data') {
2460
+ let shouldNotify = false;
2461
+ (test => {
2462
+ if (!test) {
2463
+ throw new Error(`Expected to have a data property on the document`);
2464
+ }
2465
+ })('data' in content);
2466
+
2467
+ // if data is not an array, we set the data property directly
2468
+ if (!Array.isArray(content.data)) {
2469
+ (test => {
2470
+ if (!test) {
2471
+ throw new Error(`Expected to have a single record as the operation value`);
2472
+ }
2473
+ })(op.value && !Array.isArray(op.value));
2474
+ shouldNotify = content.data !== op.value;
2475
+ if (shouldNotify) content.data = op.value;
2476
+ (test => {
2477
+ if (!test) {
2478
+ throw new Error(`The value '${op.value.lid}' cannot be added from the data of document '${op.record.lid}' as it is already the current value '${content.data ? content.data.lid : '<null>'}'`);
2479
+ }
2480
+ })(shouldNotify);
2481
+ } else {
2482
+ (test => {
2483
+ if (!test) {
2484
+ throw new Error(`Expected to have a non-null operation value`);
2485
+ }
2486
+ })(op.value);
2487
+ if (Array.isArray(op.value)) {
2488
+ if (op.index !== undefined) {
2489
+ // for collections, because we allow duplicates we are always changed.
2490
+ shouldNotify = true;
2491
+ content.data.splice(op.index, 0, ...op.value);
2492
+ } else {
2493
+ // for collections, because we allow duplicates we are always changed.
2494
+ shouldNotify = true;
2495
+ content.data.push(...op.value);
2496
+ }
2497
+ } else {
2498
+ if (op.index !== undefined) {
2499
+ // for collections, because we allow duplicates we are always changed.
2500
+ shouldNotify = true;
2501
+ content.data.splice(op.index, 0, op.value);
2502
+ } else {
2503
+ // for collections, because we allow duplicates we are always changed.
2504
+ shouldNotify = true;
2505
+ content.data.push(op.value);
2506
+ }
2507
+ }
2508
+ }
2509
+
2510
+ // notify
2511
+ if (shouldNotify) cache._capabilities.notifyChange(op.record, 'updated', null);
2512
+ return;
2513
+ }
2514
+ content.included = content.included || [];
2515
+ (test => {
2516
+ if (!test) {
2517
+ throw new Error(`Expected to have a non-null operation value`);
2518
+ }
2519
+ })(op.value);
2520
+ if (Array.isArray(op.value)) {
2521
+ // included is not allowed to have duplicates, so we do a dirty check here
2522
+ (test => {
2523
+ if (!test) {
2524
+ throw new Error(`included should not contain duplicate members`);
2525
+ }
2526
+ })(new Set([...content.included, ...op.value]).size === content.included.length + op.value.length);
2527
+ content.included = content.included.concat(op.value);
2528
+ } else {
2529
+ // included is not allowed to have duplicates, so we do a dirty check here
2530
+ (test => {
2531
+ if (!test) {
2532
+ throw new Error(`included should not contain duplicate members`);
2533
+ }
2534
+ })(content.included.includes(op.value) === false);
2535
+ content.included.push(op.value);
2536
+ }
2537
+
2538
+ // we don't notify in the included case because this is not reactively
2539
+ // exposed. We should possibly consider doing so though for subscribers
2540
+ }
2541
+ function removeResourceFromDocument(cache, op) {
2542
+ (test => {
2543
+ if (!test) {
2544
+ throw new Error(`Expected field to be either 'data' or 'included'`);
2545
+ }
2546
+ })(op.field === 'data' || op.field === 'included');
2547
+ const doc = cache.__documents.get(op.record.lid);
2548
+ (test => {
2549
+ if (!test) {
2550
+ throw new Error(`Expected to have a cached document on which to perform the remove operation`);
2551
+ }
2552
+ })(doc);
2553
+ (test => {
2554
+ if (!test) {
2555
+ throw new Error(`Expected to have content on the document`);
2556
+ }
2557
+ })(doc.content);
2558
+ const {
2559
+ content
2560
+ } = doc;
2561
+ if (op.field === 'data') {
2562
+ let shouldNotify = false;
2563
+ (test => {
2564
+ if (!test) {
2565
+ throw new Error(`Expected to have a data property on the document`);
2566
+ }
2567
+ })('data' in content);
2568
+
2569
+ // if data is not an array, we set the data property directly
2570
+ if (!Array.isArray(content.data)) {
2571
+ (test => {
2572
+ if (!test) {
2573
+ throw new Error(`Expected to have a single record as the operation value`);
2574
+ }
2575
+ })(op.value && !Array.isArray(op.value));
2576
+ shouldNotify = content.data === op.value;
2577
+ // we only remove the value if it was our existing value
2578
+ if (shouldNotify) content.data = null;
2579
+ (test => {
2580
+ if (!test) {
2581
+ throw new Error(`The value '${op.value.lid}' cannot be removed from the data of document '${op.record.lid}' as it is not the current value '${content.data ? content.data.lid : '<null>'}'`);
2582
+ }
2583
+ })(shouldNotify);
2584
+ } else {
2585
+ (test => {
2586
+ if (!test) {
2587
+ throw new Error(`Expected to have a non-null operation value`);
2588
+ }
2589
+ })(op.value);
2590
+ const toRemove = Array.isArray(op.value) ? op.value : [op.value];
2591
+ for (let i = 0; i < toRemove.length; i++) {
2592
+ const value = toRemove[i];
2593
+ if (op.index !== undefined) {
2594
+ // in production we want to recover gracefully
2595
+ // so we fallback to first-index-of
2596
+ const index = op.index < content.data.length && content.data[op.index] === value ? op.index : content.data.indexOf(value);
2597
+ (test => {
2598
+ if (!test) {
2599
+ throw new Error(`Mismatched Index: Expected index '${op.index}' to contain the value '${value.lid}' but that value is at index '${index}'`);
2600
+ }
2601
+ })(op.index < content.data.length && content.data[op.index] === value);
2602
+ if (index !== -1) {
2603
+ // we remove the first occurrence of the value
2604
+ shouldNotify = true;
2605
+ content.data.splice(index, 1);
2606
+ }
2607
+ } else {
2608
+ // we remove the first occurrence of the value
2609
+ const index = content.data.indexOf(value);
2610
+ if (index !== -1) {
2611
+ shouldNotify = true;
2612
+ content.data.splice(index, 1);
2613
+ }
2614
+ }
2615
+ }
2616
+ }
2617
+
2618
+ // notify
2619
+ if (shouldNotify) cache._capabilities.notifyChange(op.record, 'updated', null);
2620
+ } else {
2621
+ content.included = content.included || [];
2622
+ (test => {
2623
+ if (!test) {
2624
+ throw new Error(`Expected to have a non-null operation value`);
2625
+ }
2626
+ })(op.value);
2627
+ const toRemove = Array.isArray(op.value) ? op.value : [op.value];
2628
+ for (const identifier of toRemove) {
2629
+ (test => {
2630
+ if (!test) {
2631
+ throw new Error(`attempted to remove a value from included that was not present in the included array`);
2632
+ }
2633
+ })(content.included.includes(identifier));
2634
+ const index = content.included.indexOf(identifier);
2635
+ (test => {
2636
+ if (!test) {
2637
+ throw new Error(`The value '${identifier.lid}' cannot be removed from the included of document '${op.record.lid}' as it is not present`);
2638
+ }
2639
+ })(index !== -1);
2640
+ if (index !== -1) {
2641
+ content.included.splice(index, 1);
2642
+ }
2643
+ }
2644
+
2645
+ // we don't notify in the included case because this is not reactively
2646
+ // exposed. We should possibly consider doing so though for subscribers
2647
+ }
2648
+ }
2649
+ function areAllModelsUnloaded(wrapper, identifiers) {
2650
+ for (let i = 0; i < identifiers.length; ++i) {
2651
+ const identifier = identifiers[i];
2652
+ if (wrapper.hasRecord(identifier)) {
2653
+ return false;
2654
+ }
2655
+ }
2656
+ return true;
2657
+ }
2658
+ function getLocalState(rel) {
2659
+ if (isBelongsTo(rel)) {
2660
+ return rel.localState ? [rel.localState] : [];
2661
+ }
2662
+ return rel.additions ? [...rel.additions] : [];
2663
+ }
2664
+ function getRemoteState(rel) {
2665
+ if (isBelongsTo(rel)) {
2666
+ return rel.remoteState ? [rel.remoteState] : [];
2667
+ }
2668
+ return rel.remoteState;
2669
+ }
2670
+ function schemaHasLegacyDefaultValueFn(schema) {
2671
+ if (!schema) return false;
2672
+ return hasLegacyDefaultValueFn(schema.options);
2673
+ }
2674
+ function hasLegacyDefaultValueFn(options) {
2675
+ return !!options && typeof options.defaultValue === 'function';
2676
+ }
2677
+ function getDefaultValue(schema, identifier, store) {
2678
+ const options = schema?.options;
2679
+ if (!schema || !options && !schema.type) {
2680
+ return;
2681
+ }
2682
+ if (schema.kind !== 'attribute' && schema.kind !== 'field') {
2683
+ return;
2684
+ }
2685
+
2686
+ // legacy support for defaultValues that are functions
2687
+ if (hasLegacyDefaultValueFn(options)) {
2688
+ // If anyone opens an issue for args not working right, we'll restore + deprecate it via a Proxy
2689
+ // that lazily instantiates the record. We don't want to provide any args here
2690
+ // because in a non @ember-data-mirror/model world they don't make sense.
2691
+ return options.defaultValue();
2692
+ // legacy support for defaultValues that are primitives
2693
+ } else if (options && 'defaultValue' in options) {
2694
+ const defaultValue = options.defaultValue;
2695
+ (test => {
2696
+ if (!test) {
2697
+ throw new Error(`Non primitive defaultValues are not supported because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.`);
2698
+ }
2699
+ })(typeof defaultValue !== 'object' || defaultValue === null);
2700
+ return defaultValue;
2701
+
2702
+ // new style transforms
2703
+ } else if (schema.kind !== 'attribute' && schema.type) {
2704
+ const transform = store.schema.transformation(schema);
2705
+ if (transform?.defaultValue) {
2706
+ return transform.defaultValue(options || null, identifier);
2707
+ }
2708
+ }
2709
+ }
2710
+ function notifyAttributes(storeWrapper, identifier, keys) {
2711
+ if (!keys) {
2712
+ storeWrapper.notifyChange(identifier, 'attributes', null);
2713
+ return;
2714
+ }
2715
+ for (const key of keys) {
2716
+ storeWrapper.notifyChange(identifier, 'attributes', key);
2717
+ }
2718
+ }
2719
+
2720
+ /*
2721
+ TODO @deprecate IGOR DAVID
2722
+ There seems to be a potential bug here, where we will return keys that are not
2723
+ in the schema
2724
+ */
2725
+ function calculateChangedKeys(cached, updates, fields) {
2726
+ const changedKeys = new Set();
2727
+ const keys = Object.keys(updates);
2728
+ const length = keys.length;
2729
+ const localAttrs = cached.localAttrs;
2730
+ const original = Object.assign(Object.create(null), cached.remoteAttrs, cached.inflightAttrs);
2731
+ for (let i = 0; i < length; i++) {
2732
+ const key = keys[i];
2733
+ if (!fields.has(key)) {
2734
+ continue;
2735
+ }
2736
+ const value = updates[key];
2737
+
2738
+ // A value in localAttrs means the user has a local change to
2739
+ // this attribute. We never override this value when merging
2740
+ // updates from the backend so we should not sent a change
2741
+ // notification if the server value differs from the original.
2742
+ if (localAttrs && localAttrs[key] !== undefined) {
2743
+ continue;
2744
+ }
2745
+ if (original[key] !== value) {
2746
+ changedKeys.add(key);
2747
+ }
2748
+ }
2749
+ return changedKeys;
2750
+ }
2751
+ function cacheIsEmpty(cached) {
2752
+ return !cached || cached.remoteAttrs === null && cached.inflightAttrs === null && cached.localAttrs === null;
2753
+ }
2754
+ function _isEmpty(peeked) {
2755
+ if (!peeked) {
2756
+ return true;
2757
+ }
2758
+ const isNew = peeked.isNew;
2759
+ const isDeleted = peeked.isDeleted;
2760
+ const isEmpty = cacheIsEmpty(peeked);
2761
+ return (!isNew || isDeleted) && isEmpty;
2762
+ }
2763
+ function recordIsLoaded(cached, filterDeleted = false) {
2764
+ if (!cached) {
2765
+ return false;
2766
+ }
2767
+ const isNew = cached.isNew;
2768
+ const isEmpty = cacheIsEmpty(cached);
2769
+
2770
+ // if we are new we must consider ourselves loaded
2771
+ if (isNew) {
2772
+ return !cached.isDeleted;
2773
+ }
2774
+ // even if we have a past request, if we are now empty we are not loaded
2775
+ // typically this is true after an unloadRecord call
2776
+
2777
+ // if we are not empty, not new && we have a fulfilled request then we are loaded
2778
+ // we should consider allowing for something to be loaded that is simply "not empty".
2779
+ // which is how RecordState currently handles this case; however, RecordState is buggy
2780
+ // in that it does not account for unloading.
2781
+ return filterDeleted && cached.isDeletionCommitted ? false : !isEmpty;
2782
+ }
2783
+ function _isLoading(peeked, capabilities, identifier) {
2784
+ assertPrivateCapabilities(capabilities);
2785
+ // TODO refactor things such that the cache is not required to know
2786
+ // about isLoading
2787
+ const req = capabilities._store.getRequestStateService();
2788
+ // const fulfilled = req.getLastRequestForRecord(identifier);
2789
+ const isLoaded = recordIsLoaded(peeked);
2790
+ return !isLoaded &&
2791
+ // fulfilled === null &&
2792
+ req.getPendingRequestsForRecord(identifier).some(r => r.type === 'query');
2793
+ }
2794
+ function setupRelationships(graph, fields, identifier, data) {
2795
+ for (const name in data.relationships) {
2796
+ const relationshipData = data.relationships[name];
2797
+ const field = fields.get(name);
2798
+ // TODO consider asserting if the relationship is not in the schema
2799
+ // we intentionally ignore relationships that are not in the schema
2800
+ if (!relationshipData || !field || !isRelationship(field)) continue;
2801
+ graph.push({
2802
+ op: 'updateRelationship',
2803
+ record: identifier,
2804
+ field: name,
2805
+ value: relationshipData
2806
+ });
2807
+ }
2808
+ }
2809
+ function isRelationship(field) {
2810
+ const {
2811
+ kind
2812
+ } = field;
2813
+ return kind === 'hasMany' || kind === 'belongsTo' || kind === 'resource' || kind === 'collection';
2814
+ }
2815
+ function patchLocalAttributes(cached, changedRemoteKeys) {
2816
+ const {
2817
+ localAttrs,
2818
+ remoteAttrs,
2819
+ inflightAttrs,
2820
+ defaultAttrs,
2821
+ changes
2822
+ } = cached;
2823
+ if (!localAttrs) {
2824
+ cached.changes = null;
2825
+ return false;
2826
+ }
2827
+ let hasAppliedPatch = false;
2828
+ const mutatedKeys = Object.keys(localAttrs);
2829
+ for (let i = 0, length = mutatedKeys.length; i < length; i++) {
2830
+ const attr = mutatedKeys[i];
2831
+ const existing = inflightAttrs && attr in inflightAttrs ? inflightAttrs[attr] : remoteAttrs && attr in remoteAttrs ? remoteAttrs[attr] : undefined;
2832
+ if (existing === localAttrs[attr]) {
2833
+ hasAppliedPatch = true;
2834
+
2835
+ // if the local change is committed, then
2836
+ // the remoteKeyChange is no longer relevant
2837
+ changedRemoteKeys?.delete(attr);
2838
+ delete localAttrs[attr];
2839
+ delete changes[attr];
2840
+ }
2841
+ if (defaultAttrs && attr in defaultAttrs) {
2842
+ delete defaultAttrs[attr];
2843
+ }
2844
+ }
2845
+ return hasAppliedPatch;
2846
+ }
2847
+ function putOne(cache, identifiers, resource) {
2848
+ (test => {
2849
+ if (!test) {
2850
+ throw new Error(`You must include an 'id' for the resource data ${resource.type}`);
2851
+ }
2852
+ })(resource.id !== null && resource.id !== undefined && resource.id !== '');
2853
+ (test => {
2854
+ if (!test) {
2855
+ throw new Error(`Missing Resource Type: received resource data with a type '${resource.type}' but no schema could be found with that name.`);
2856
+ }
2857
+ })(cache._capabilities.schema.hasResource(resource));
2858
+ let identifier = identifiers.peekResourceKey(resource);
2859
+ if (identifier) {
2860
+ identifier = identifiers.updateRecordIdentifier(identifier, resource);
2861
+ } else {
2862
+ identifier = identifiers.getOrCreateRecordIdentifier(resource);
2863
+ }
2864
+ cache.upsert(identifier, resource, cache._capabilities.hasRecord(identifier));
2865
+ // even if the identifier was not "existing" before, it is now
2866
+ return identifier;
2867
+ }
2868
+
2869
+ /*
2870
+ Iterates over the set of internal models reachable from `this` across exactly one
2871
+ relationship.
2872
+ */
2873
+ function _directlyRelatedIdentifiersIterable(storeWrapper, originating) {
2874
+ const graph = peekGraph(storeWrapper);
2875
+ const initializedRelationships = graph?.identifiers.get(originating);
2876
+ if (!initializedRelationships) {
2877
+ return EMPTY_ITERATOR;
2878
+ }
2879
+ const initializedRelationshipsArr = [];
2880
+ Object.keys(initializedRelationships).forEach(key => {
2881
+ const rel = initializedRelationships[key];
2882
+ if (rel && !isImplicit(rel)) {
2883
+ initializedRelationshipsArr.push(rel);
2884
+ }
2885
+ });
2886
+ let i = 0;
2887
+ let j = 0;
2888
+ let k = 0;
2889
+ const findNext = () => {
2890
+ while (i < initializedRelationshipsArr.length) {
2891
+ while (j < 2) {
2892
+ const relatedIdentifiers = j === 0 ? getLocalState(initializedRelationshipsArr[i]) : getRemoteState(initializedRelationshipsArr[i]);
2893
+ while (k < relatedIdentifiers.length) {
2894
+ const relatedIdentifier = relatedIdentifiers[k++];
2895
+ if (relatedIdentifier !== null) {
2896
+ return relatedIdentifier;
2897
+ }
2898
+ }
2899
+ k = 0;
2900
+ j++;
2901
+ }
2902
+ j = 0;
2903
+ i++;
2904
+ }
2905
+ return undefined;
2906
+ };
2907
+ return {
2908
+ iterator() {
2909
+ return {
2910
+ next: () => {
2911
+ const value = findNext();
2912
+ return {
2913
+ value,
2914
+ done: value === undefined
2915
+ };
2916
+ }
2917
+ };
2918
+ }
2919
+ };
2920
+ }
2921
+
2922
+ /*
2923
+ Computes the set of Identifiers reachable from this Identifier.
2924
+
2925
+ Reachability is determined over the relationship graph (ie a graph where
2926
+ nodes are identifiers and edges are belongs to or has many
2927
+ relationships).
2928
+
2929
+ Returns an array including `this` and all identifiers reachable
2930
+ from `this.identifier`.
2931
+ */
2932
+ function _allRelatedIdentifiers(storeWrapper, originating) {
2933
+ const array = [];
2934
+ const queue = [];
2935
+ const seen = new Set();
2936
+ queue.push(originating);
2937
+ while (queue.length > 0) {
2938
+ const identifier = queue.shift();
2939
+ array.push(identifier);
2940
+ seen.add(identifier);
2941
+ const iterator = _directlyRelatedIdentifiersIterable(storeWrapper, originating).iterator();
2942
+ for (let obj = iterator.next(); !obj.done; obj = iterator.next()) {
2943
+ const relatedIdentifier = obj.value;
2944
+ if (relatedIdentifier && !seen.has(relatedIdentifier)) {
2945
+ seen.add(relatedIdentifier);
2946
+ queue.push(relatedIdentifier);
2947
+ }
2948
+ }
2949
+ }
2950
+ return array;
2951
+ }
2952
+ function fromBaseDocument(doc) {
2953
+ const resourceDocument = {};
2954
+ const jsonApiDoc = doc.content;
2955
+ if (jsonApiDoc) {
2956
+ copyLinksAndMeta(resourceDocument, jsonApiDoc);
2957
+ }
2958
+ return resourceDocument;
2959
+ }
2960
+ function fromStructuredError(doc) {
2961
+ const errorDoc = {};
2962
+ if (doc.content) {
2963
+ copyLinksAndMeta(errorDoc, doc.content);
2964
+ if ('errors' in doc.content) {
2965
+ errorDoc.errors = doc.content.errors;
2966
+ } else if (typeof doc.error === 'object' && 'errors' in doc.error) {
2967
+ errorDoc.errors = doc.error.errors;
2968
+ } else {
2969
+ errorDoc.errors = [{
2970
+ title: doc.message
2971
+ }];
2972
+ }
2973
+ }
2974
+ return errorDoc;
2975
+ }
2976
+ function copyLinksAndMeta(target, source) {
2977
+ if ('links' in source) {
2978
+ target.links = source.links;
2979
+ }
2980
+ if ('meta' in source) {
2981
+ target.meta = source.meta;
2982
+ }
2983
+ }
2984
+ function cacheUpsert(cache, identifier, data, calculateChanges) {
2985
+ let changedKeys;
2986
+ const peeked = cache.__safePeek(identifier, false);
2987
+ const existed = !!peeked;
2988
+ const cached = peeked || cache._createCache(identifier);
2989
+ const isLoading = /*#__NOINLINE__*/_isLoading(peeked, cache._capabilities, identifier) || !recordIsLoaded(peeked);
2990
+ const isUpdate = /*#__NOINLINE__*/!_isEmpty(peeked) && !isLoading;
2991
+ {
2992
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
2993
+ logGroup('cache', 'upsert', identifier.type, identifier.lid, existed ? 'merged' : 'inserted', calculateChanges ? 'has-subscription' : '');
2994
+ try {
2995
+ const _data = JSON.parse(JSON.stringify(data));
2996
+
2997
+ // eslint-disable-next-line no-console
2998
+ console.log(_data);
2999
+ } catch {
3000
+ // eslint-disable-next-line no-console
3001
+ console.log(data);
3002
+ }
3003
+ }
3004
+ }
3005
+ if (cached.isNew) {
3006
+ cached.isNew = false;
3007
+ cache._capabilities.notifyChange(identifier, 'identity', null);
3008
+ cache._capabilities.notifyChange(identifier, 'state', null);
3009
+ }
3010
+ const fields = getCacheFields(cache, identifier);
3011
+
3012
+ // if no cache entry existed, no record exists / property has been accessed
3013
+ // and thus we do not need to notify changes to any properties.
3014
+ if (calculateChanges && existed && data.attributes) {
3015
+ changedKeys = calculateChangedKeys(cached, data.attributes, fields);
3016
+ }
3017
+ cached.remoteAttrs = Object.assign(cached.remoteAttrs || Object.create(null), data.attributes);
3018
+ if (cached.localAttrs) {
3019
+ if (patchLocalAttributes(cached, changedKeys)) {
3020
+ cache._capabilities.notifyChange(identifier, 'state', null);
3021
+ }
3022
+ }
3023
+ if (!isUpdate) {
3024
+ cache._capabilities.notifyChange(identifier, 'added', null);
3025
+ }
3026
+ if (data.id) {
3027
+ cached.id = data.id;
3028
+ }
3029
+ if (data.relationships) {
3030
+ setupRelationships(cache.__graph, fields, identifier, data);
3031
+ }
3032
+ if (changedKeys?.size) {
3033
+ notifyAttributes(cache._capabilities, identifier, changedKeys);
3034
+ }
3035
+ {
3036
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3037
+ // eslint-disable-next-line no-console
3038
+ console.groupEnd();
3039
+ }
3040
+ }
3041
+ return changedKeys?.size ? Array.from(changedKeys) : undefined;
3042
+ }
3043
+ function patchCache(Cache, op) {
3044
+ const isRecord = isResourceKey(op.record);
3045
+ const isDocument = !isRecord && isRequestKey(op.record);
3046
+ (test => {
3047
+ if (!test) {
3048
+ throw new Error(`Expected Cache.patch op.record to be a record or document identifier`);
3049
+ }
3050
+ })(isRecord || isDocument);
3051
+ {
3052
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3053
+ logGroup('cache', 'patch', isRecord ? op.record.type : '<@document>', op.record.lid, op.op, 'field' in op ? op.field : op.op === 'mergeIdentifiers' ? op.value.lid : '');
3054
+ try {
3055
+ const _data = JSON.parse(JSON.stringify(op));
3056
+ // eslint-disable-next-line no-console
3057
+ console.log(_data);
3058
+ } catch {
3059
+ // eslint-disable-next-line no-console
3060
+ console.log(op);
3061
+ }
3062
+ }
3063
+ }
3064
+ switch (op.op) {
3065
+ case 'mergeIdentifiers':
3066
+ {
3067
+ const cache = Cache.__cache.get(op.record);
3068
+ if (cache) {
3069
+ Cache.__cache.set(op.value, cache);
3070
+ Cache.__cache.delete(op.record);
3071
+ }
3072
+ Cache.__graph.update(op, true);
3073
+ break;
3074
+ }
3075
+ case 'update':
3076
+ {
3077
+ if (isRecord) {
3078
+ if ('field' in op) {
3079
+ const field = getCacheFields(Cache, op.record).get(op.field);
3080
+ (test => {
3081
+ if (!test) {
3082
+ throw new Error(`Expected ${op.field} to be a field on ${op.record.type}`);
3083
+ }
3084
+ })(field);
3085
+ if (isRelationship(field)) {
3086
+ Cache.__graph.push(op);
3087
+ } else {
3088
+ Cache.upsert(op.record, {
3089
+ type: op.record.type,
3090
+ id: op.record.id,
3091
+ attributes: {
3092
+ [op.field]: op.value
3093
+ }
3094
+ }, Cache._capabilities.hasRecord(op.record));
3095
+ }
3096
+ } else {
3097
+ Cache.upsert(op.record, op.value, Cache._capabilities.hasRecord(op.record));
3098
+ }
3099
+ } else {
3100
+ (test => {
3101
+ {
3102
+ throw new Error(`Update operations on documents is not supported`);
3103
+ }
3104
+ })();
3105
+ }
3106
+ break;
3107
+ }
3108
+ case 'add':
3109
+ {
3110
+ if (isRecord) {
3111
+ if ('field' in op) {
3112
+ Cache.__graph.push(op);
3113
+ } else {
3114
+ Cache.upsert(op.record, op.value, Cache._capabilities.hasRecord(op.record));
3115
+ }
3116
+ } else {
3117
+ (test => {
3118
+ if (!test) {
3119
+ throw new Error(`Expected a field in the add operation`);
3120
+ }
3121
+ })('field' in op);
3122
+ addResourceToDocument(Cache, op);
3123
+ }
3124
+ break;
3125
+ }
3126
+ case 'remove':
3127
+ {
3128
+ if (isRecord) {
3129
+ if ('field' in op) {
3130
+ Cache.__graph.push(op);
3131
+ } else {
3132
+ const cached = Cache.__safePeek(op.record, false);
3133
+ if (cached) {
3134
+ cached.isDeleted = true;
3135
+ cached.isDeletionCommitted = true;
3136
+ Cache.unloadRecord(op.record);
3137
+ } else {
3138
+ peekGraph(Cache._capabilities)?.push({
3139
+ op: 'deleteRecord',
3140
+ record: op.record,
3141
+ isNew: false
3142
+ });
3143
+ }
3144
+ }
3145
+ } else {
3146
+ if ('field' in op) {
3147
+ (test => {
3148
+ if (!test) {
3149
+ throw new Error(`Expected a field in the remove operation`);
3150
+ }
3151
+ })('field' in op);
3152
+ removeResourceFromDocument(Cache, op);
3153
+ } else {
3154
+ // TODO @runspired teardown associated state ... notify subscribers etc.
3155
+ // This likely means that the instance cache needs to handle
3156
+ // holding onto reactive documents instead of the CacheHandler
3157
+ // and use a subscription to remove them.
3158
+ // Cache.__documents.delete(op.record.lid);
3159
+ (test => {
3160
+ {
3161
+ throw new Error(`Removing documents from the cache is not yet supported`);
3162
+ }
3163
+ })();
3164
+ }
3165
+ }
3166
+ break;
3167
+ }
3168
+ default:
3169
+ (test => {
3170
+ {
3171
+ throw new Error(`Unhandled cache.patch operation ${op.op}`);
3172
+ }
3173
+ })();
3174
+ }
3175
+ {
3176
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3177
+ // eslint-disable-next-line no-console
3178
+ console.groupEnd();
3179
+ }
3180
+ }
3181
+ }
3182
+ function getCacheFields(cache, identifier) {
3183
+ if (cache._capabilities.schema.cacheFields) {
3184
+ const result = cache._capabilities.schema.cacheFields(identifier);
3185
+ if (result) {
3186
+ return result;
3187
+ }
3188
+ }
3189
+
3190
+ // the model schema service cannot process fields that are not cache fields
3191
+ return cache._capabilities.schema.fields(identifier);
3192
+ }
3193
+ function commitDidError(cache, identifier, errors) {
3194
+ const cached = cache.__peek(identifier, false);
3195
+ if (cached.inflightAttrs) {
3196
+ const keys = Object.keys(cached.inflightAttrs);
3197
+ if (keys.length > 0) {
3198
+ const attrs = cached.localAttrs = cached.localAttrs || Object.create(null);
3199
+ for (let i = 0; i < keys.length; i++) {
3200
+ if (attrs[keys[i]] === undefined) {
3201
+ attrs[keys[i]] = cached.inflightAttrs[keys[i]];
3202
+ }
3203
+ }
3204
+ }
3205
+ cached.inflightAttrs = null;
3206
+ }
3207
+ if (errors) {
3208
+ cached.errors = errors;
3209
+ }
3210
+ cache._capabilities.notifyChange(identifier, 'errors', null);
3211
+ }
3212
+ function didCommit(cache, committedIdentifier, data, op) {
3213
+ if (!data) {
3214
+ (test => {
3215
+ if (!test) {
3216
+ throw new Error(`Your ${committedIdentifier.type} record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.`);
3217
+ }
3218
+ })(committedIdentifier.id);
3219
+ }
3220
+ const {
3221
+ cacheKeyManager
3222
+ } = cache._capabilities;
3223
+ const existingId = committedIdentifier.id;
3224
+ const identifier = op !== 'deleteRecord' && data ? cacheKeyManager.updateRecordIdentifier(committedIdentifier, data) : committedIdentifier;
3225
+ const cached = cache.__peek(identifier, false);
3226
+ if (cached.isDeleted || op === 'deleteRecord') {
3227
+ cache.__graph.push({
3228
+ op: 'deleteRecord',
3229
+ record: identifier,
3230
+ isNew: false
3231
+ });
3232
+ cached.isDeleted = true;
3233
+ cached.isDeletionCommitted = true;
3234
+ cache._capabilities.notifyChange(identifier, 'removed', null);
3235
+ // TODO @runspired should we early exit here?
3236
+ }
3237
+ {
3238
+ if (cached.isNew && !identifier.id && (typeof data?.id !== 'string' || data.id.length > 0)) {
3239
+ const error = new Error(`Expected an id ${String(identifier)} in response ${JSON.stringify(data)}`);
3240
+ //@ts-expect-error
3241
+ error.isAdapterError = true;
3242
+ //@ts-expect-error
3243
+ error.code = 'InvalidError';
3244
+ throw error;
3245
+ }
3246
+ }
3247
+ const fields = getCacheFields(cache, identifier);
3248
+ cached.isNew = false;
3249
+ let newCanonicalAttributes;
3250
+ if (data) {
3251
+ if (data.id && !cached.id) {
3252
+ cached.id = data.id;
3253
+ }
3254
+ if (identifier === committedIdentifier && identifier.id !== existingId) {
3255
+ cache._capabilities.notifyChange(identifier, 'identity', null);
3256
+ }
3257
+ (test => {
3258
+ if (!test) {
3259
+ throw new Error(`Expected the ID received for the primary '${identifier.type}' resource being saved to match the current id '${cached.id}' but received '${identifier.id}'.`);
3260
+ }
3261
+ })(identifier.id === cached.id);
3262
+ if (data.relationships) {
3263
+ {
3264
+ {
3265
+ // assert against bad API behavior where a belongsTo relationship
3266
+ // is saved but the return payload indicates a different final state.
3267
+ fields.forEach((field, name) => {
3268
+ if (field.kind === 'belongsTo') {
3269
+ const relationshipData = data.relationships[name]?.data;
3270
+ if (relationshipData !== undefined) {
3271
+ const inFlightData = cached.inflightRelationships?.[name];
3272
+ if (!inFlightData || !('data' in inFlightData)) {
3273
+ return;
3274
+ }
3275
+ const actualData = relationshipData ? cache._capabilities.cacheKeyManager.getOrCreateRecordIdentifier(relationshipData) : null;
3276
+ (test => {
3277
+ if (!test) {
3278
+ throw new Error(`Expected the resource relationship '<${identifier.type}>.${name}' on ${identifier.lid} to be saved as ${inFlightData.data ? inFlightData.data.lid : '<null>'} but it was saved as ${actualData ? actualData.lid : '<null>'}`);
3279
+ }
3280
+ })(inFlightData.data === actualData);
3281
+ }
3282
+ }
3283
+ });
3284
+ cached.inflightRelationships = null;
3285
+ }
3286
+ }
3287
+ setupRelationships(cache.__graph, fields, identifier, data);
3288
+ }
3289
+ newCanonicalAttributes = data.attributes;
3290
+ }
3291
+ const changedKeys = newCanonicalAttributes && calculateChangedKeys(cached, newCanonicalAttributes, fields);
3292
+ cached.remoteAttrs = Object.assign(cached.remoteAttrs || Object.create(null), cached.inflightAttrs, newCanonicalAttributes);
3293
+ cached.inflightAttrs = null;
3294
+ patchLocalAttributes(cached, changedKeys);
3295
+ if (cached.errors) {
3296
+ cached.errors = null;
3297
+ cache._capabilities.notifyChange(identifier, 'errors', null);
3298
+ }
3299
+ if (changedKeys?.size) notifyAttributes(cache._capabilities, identifier, changedKeys);
3300
+ cache._capabilities.notifyChange(identifier, 'state', null);
3301
+ }
3302
+ function willCommit(cache, identifier) {
3303
+ const cached = cache.__peek(identifier, false);
3304
+
3305
+ /*
3306
+ if we have multiple saves in flight at once then
3307
+ we have information loss no matter what. This
3308
+ attempts to lose the least information.
3309
+ If we were to clear inflightAttrs, previous requests
3310
+ would not be able to use it during their didCommit.
3311
+ If we upsert inflightattrs, previous requests incorrectly
3312
+ see more recent inflight changes as part of their own and
3313
+ will incorrectly mark the new state as the correct remote state.
3314
+ We choose this latter behavior to avoid accidentally removing
3315
+ earlier changes.
3316
+ If apps do not want this behavior they can either
3317
+ - chain save requests serially vs allowing concurrent saves
3318
+ - move to using a request handler that caches the inflight state
3319
+ on a per-request basis
3320
+ - change their save requests to only send a "PATCH" instead of a "PUT"
3321
+ so that only latest changes are involved in each request, and then also
3322
+ ensure that the API or their handler reflects only those changes back
3323
+ for upsert into the cache.
3324
+ */
3325
+ if (cached.inflightAttrs) {
3326
+ if (cached.localAttrs) {
3327
+ Object.assign(cached.inflightAttrs, cached.localAttrs);
3328
+ }
3329
+ } else {
3330
+ cached.inflightAttrs = cached.localAttrs;
3331
+ }
3332
+ cached.localAttrs = null;
3333
+ {
3334
+ {
3335
+ // save off info about saved relationships
3336
+ const fields = getCacheFields(cache, identifier);
3337
+ fields.forEach((schema, name) => {
3338
+ if (schema.kind === 'belongsTo') {
3339
+ if (cache.__graph._isDirty(identifier, name)) {
3340
+ const relationshipData = cache.__graph.getData(identifier, name);
3341
+ const inFlight = cached.inflightRelationships = cached.inflightRelationships || Object.create(null);
3342
+ inFlight[name] = relationshipData;
3343
+ }
3344
+ }
3345
+ });
3346
+ }
3347
+ }
3348
+ }
3349
+
3350
+ export { JSONAPICache };