@ember-data/model 5.6.0-alpha.2 → 5.6.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/-private.js +1 -2
  2. package/dist/-private.js.map +1 -1
  3. package/dist/{model-Dkk-TZlL.js → errors-DsUSZ9m8.js} +41 -2335
  4. package/dist/errors-DsUSZ9m8.js.map +1 -0
  5. package/dist/{hooks-o1U_cEA3.js → hooks-rXIjX2-H.js} +1 -2
  6. package/dist/{hooks-o1U_cEA3.js.map → hooks-rXIjX2-H.js.map} +1 -1
  7. package/dist/hooks.js +2 -2
  8. package/dist/index.js +667 -5
  9. package/dist/index.js.map +1 -1
  10. package/dist/migration-support.js +7 -14
  11. package/dist/migration-support.js.map +1 -1
  12. package/dist/schema-provider-B6-5uzxP.js +2229 -0
  13. package/dist/schema-provider-B6-5uzxP.js.map +1 -0
  14. package/package.json +16 -19
  15. package/unstable-preview-types/-private/attr.d.ts +4 -12
  16. package/unstable-preview-types/-private/attr.d.ts.map +1 -1
  17. package/unstable-preview-types/-private/belongs-to.d.ts +0 -6
  18. package/unstable-preview-types/-private/belongs-to.d.ts.map +1 -1
  19. package/unstable-preview-types/-private/errors.d.ts +4 -15
  20. package/unstable-preview-types/-private/errors.d.ts.map +1 -1
  21. package/unstable-preview-types/-private/has-many.d.ts +0 -3
  22. package/unstable-preview-types/-private/has-many.d.ts.map +1 -1
  23. package/unstable-preview-types/-private/model.d.ts +531 -562
  24. package/unstable-preview-types/-private/model.d.ts.map +1 -1
  25. package/unstable-preview-types/-private/promise-belongs-to.d.ts +0 -4
  26. package/unstable-preview-types/-private/promise-belongs-to.d.ts.map +1 -1
  27. package/unstable-preview-types/-private/promise-many-array.d.ts +3 -11
  28. package/unstable-preview-types/-private/promise-many-array.d.ts.map +1 -1
  29. package/unstable-preview-types/-private/references/belongs-to.d.ts +3 -12
  30. package/unstable-preview-types/-private/references/belongs-to.d.ts.map +1 -1
  31. package/unstable-preview-types/-private/references/has-many.d.ts +7 -19
  32. package/unstable-preview-types/-private/references/has-many.d.ts.map +1 -1
  33. package/unstable-preview-types/-private/type-utils.d.ts +0 -5
  34. package/unstable-preview-types/-private/type-utils.d.ts.map +1 -1
  35. package/unstable-preview-types/-private.d.ts +0 -4
  36. package/unstable-preview-types/-private.d.ts.map +1 -1
  37. package/unstable-preview-types/index.d.ts +23 -20
  38. package/unstable-preview-types/index.d.ts.map +1 -1
  39. package/unstable-preview-types/migration-support.d.ts +4 -10
  40. package/unstable-preview-types/migration-support.d.ts.map +1 -1
  41. package/dist/has-many-BXU96bZ9.js +0 -682
  42. package/dist/has-many-BXU96bZ9.js.map +0 -1
  43. package/dist/model-Dkk-TZlL.js.map +0 -1
  44. package/dist/schema-provider-DyG6fJXt.js +0 -259
  45. package/dist/schema-provider-DyG6fJXt.js.map +0 -1
@@ -0,0 +1,2229 @@
1
+ import { getOwner } from '@ember/application';
2
+ import { deprecate } from '@ember/debug';
3
+ import EmberObject from '@ember/object';
4
+ import { recordIdentifierFor, storeFor } from '@ember-data/store';
5
+ import { peekCache, notifyInternalSignal, peekInternalSignal, withSignalStore, ARRAY_SIGNAL, recordIdentifierFor as recordIdentifierFor$1, gate, memoized, defineSignal, coerceId, entangleSignal } from '@ember-data/store/-private';
6
+ import { RecordStore } from '@warp-drive/core-types/symbols';
7
+ import { l as lookupLegacySupport, L as LEGACY_SUPPORT, d as decorateMethodV2, E as Errors } from "./errors-DsUSZ9m8.js";
8
+ import { macroCondition, getGlobalConfig, importSync } from '@embroider/macros';
9
+ import { upgradeStore } from '@ember-data/legacy-compat/-private';
10
+ import { cacheFor } from '@ember/object/internals';
11
+ import { dasherize } from '@ember-data/request-utils/string';
12
+ function isElementDescriptor(args) {
13
+ const [maybeTarget, maybeKey, maybeDesc] = args;
14
+ return (
15
+ // Ensure we have the right number of args
16
+ args.length === 3 && (
17
+ // Make sure the target is a class or object (prototype)
18
+ typeof maybeTarget === 'function' || typeof maybeTarget === 'object' && maybeTarget !== null) &&
19
+ // Make sure the key is a string
20
+ typeof maybeKey === 'string' && (
21
+ // Make sure the descriptor is the right shape
22
+ typeof maybeDesc === 'object' && maybeDesc !== null && 'enumerable' in maybeDesc && 'configurable' in maybeDesc ||
23
+ // TS compatibility
24
+ maybeDesc === undefined)
25
+ );
26
+ }
27
+ function normalizeModelName(type) {
28
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_NON_STRICT_TYPES)) {
29
+ const result = dasherize(type);
30
+ deprecate(`The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`, result === type, {
31
+ id: 'ember-data:deprecate-non-strict-types',
32
+ until: '6.0',
33
+ for: 'ember-data',
34
+ since: {
35
+ available: '4.13',
36
+ enabled: '5.3'
37
+ }
38
+ });
39
+ return result;
40
+ }
41
+ return type;
42
+ }
43
+ function rollbackAttributes() {
44
+ const {
45
+ currentState
46
+ } = this;
47
+ const {
48
+ isNew
49
+ } = currentState;
50
+ this[RecordStore]._join(() => {
51
+ peekCache(this).rollbackAttrs(recordIdentifierFor(this));
52
+ this.errors.clear();
53
+ currentState.cleanErrorRequests();
54
+ if (isNew) {
55
+ this.unloadRecord();
56
+ }
57
+ });
58
+ }
59
+ function unloadRecord() {
60
+ if (this.currentState.isNew && (this.isDestroyed || this.isDestroying)) {
61
+ return;
62
+ }
63
+ this[RecordStore].unloadRecord(this);
64
+ }
65
+ function belongsTo(prop) {
66
+ return lookupLegacySupport(this).referenceFor('belongsTo', prop);
67
+ }
68
+ function hasMany(prop) {
69
+ return lookupLegacySupport(this).referenceFor('hasMany', prop);
70
+ }
71
+ function reload(options = {}) {
72
+ options.isReloading = true;
73
+ options.reload = true;
74
+ const identifier = recordIdentifierFor(this);
75
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
76
+ if (!test) {
77
+ throw new Error(`You cannot reload a record without an ID`);
78
+ }
79
+ })(identifier.id) : {};
80
+ this.isReloading = true;
81
+ const promise = this[RecordStore].request({
82
+ op: 'findRecord',
83
+ data: {
84
+ options,
85
+ record: identifier
86
+ },
87
+ cacheOptions: {
88
+ [Symbol.for('wd:skip-cache')]: true
89
+ }
90
+ }).then(() => this).finally(() => {
91
+ this.isReloading = false;
92
+ });
93
+ return promise;
94
+ }
95
+ function changedAttributes() {
96
+ return peekCache(this).changedAttrs(recordIdentifierFor(this));
97
+ }
98
+ function serialize(options) {
99
+ upgradeStore(this[RecordStore]);
100
+ return this[RecordStore].serializeRecord(this, options);
101
+ }
102
+ function deleteRecord() {
103
+ // ensure we've populated currentState prior to deleting a new record
104
+ if (this.currentState) {
105
+ this[RecordStore].deleteRecord(this);
106
+ }
107
+ }
108
+ function save(options) {
109
+ let promise;
110
+ if (this.currentState.isNew && this.currentState.isDeleted) {
111
+ promise = Promise.resolve(this);
112
+ } else {
113
+ this.errors.clear();
114
+ promise = this[RecordStore].saveRecord(this, options);
115
+ }
116
+ return promise;
117
+ }
118
+ function destroyRecord(options) {
119
+ const {
120
+ isNew
121
+ } = this.currentState;
122
+ this.deleteRecord();
123
+ if (isNew) {
124
+ return Promise.resolve(this);
125
+ }
126
+ return this.save(options).then(_ => {
127
+ this.unloadRecord();
128
+ return this;
129
+ });
130
+ }
131
+ function createSnapshot() {
132
+ const store = this[RecordStore];
133
+ upgradeStore(store);
134
+ if (!store._fetchManager) {
135
+ const FetchManager = importSync('@ember-data/legacy-compat/-private').FetchManager;
136
+ store._fetchManager = new FetchManager(store);
137
+ }
138
+
139
+ // @ts-expect-error Typescript isn't able to curry narrowed args that are divorced from each other.
140
+ return store._fetchManager.createSnapshot(recordIdentifierFor(this));
141
+ }
142
+ function notifyChanges(identifier, value, key, record, store) {
143
+ switch (value) {
144
+ case 'added':
145
+ case 'attributes':
146
+ if (key) {
147
+ notifyAttribute(store, identifier, key, record);
148
+ } else {
149
+ record.eachAttribute(name => {
150
+ notifyAttribute(store, identifier, name, record);
151
+ });
152
+ }
153
+ break;
154
+ case 'relationships':
155
+ if (key) {
156
+ const meta = record.constructor.relationshipsByName.get(key);
157
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
158
+ if (!test) {
159
+ throw new Error(`Expected to find a relationship for ${key} on ${identifier.type}`);
160
+ }
161
+ })(meta) : {};
162
+ notifyRelationship(identifier, key, record, meta);
163
+ } else {
164
+ record.eachRelationship((name, meta) => {
165
+ notifyRelationship(identifier, name, record, meta);
166
+ });
167
+ }
168
+ break;
169
+ case 'identity':
170
+ notifyInternalSignal(peekInternalSignal(withSignalStore(record), 'id'));
171
+ break;
172
+ }
173
+ }
174
+ function notifyRelationship(identifier, key, record, meta) {
175
+ if (meta.kind === 'belongsTo') {
176
+ record.notifyPropertyChange(key);
177
+ } else if (meta.kind === 'hasMany') {
178
+ const support = LEGACY_SUPPORT.get(identifier);
179
+ const manyArray = support && support._manyArrayCache[key];
180
+ const hasPromise = support && support._relationshipPromisesCache[key];
181
+ if (manyArray && hasPromise) {
182
+ // do nothing, we will notify the ManyArray directly
183
+ // once the fetch has completed.
184
+ return;
185
+ }
186
+ if (manyArray) {
187
+ notifyInternalSignal(manyArray[ARRAY_SIGNAL]);
188
+
189
+ //We need to notifyPropertyChange in the adding case because we need to make sure
190
+ //we fetch the newly added record in case it is unloaded
191
+ //TODO(Igor): Consider whether we could do this only if the record state is unloaded
192
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
193
+ if (!test) {
194
+ throw new Error(`Expected options to exist on relationship meta`);
195
+ }
196
+ })(meta.options) : {};
197
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
198
+ if (!test) {
199
+ throw new Error(`Expected async to exist on relationship meta options`);
200
+ }
201
+ })('async' in meta.options) : {};
202
+ if (meta.options.async) {
203
+ record.notifyPropertyChange(key);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ function notifyAttribute(store, identifier, key, record) {
209
+ const currentValue = cacheFor(record, key);
210
+ const cache = store.cache;
211
+ if (currentValue !== cache.getAttr(identifier, key)) {
212
+ record.notifyPropertyChange(key);
213
+ }
214
+ }
215
+ const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
216
+ const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
217
+ const PRIMARY_ATTRIBUTE_KEY = 'base';
218
+ function isInvalidError(error) {
219
+ return !!error && error instanceof Error && 'isAdapterError' in error && error.isAdapterError === true && 'code' in error && error.code === 'InvalidError';
220
+ }
221
+
222
+ /**
223
+ Historically EmberData managed a state machine
224
+ for each record, the localState for which
225
+ was reflected onto Model.
226
+
227
+ This implements the flags and stateName for backwards compat
228
+ with the state tree that used to be possible (listed below).
229
+
230
+ stateName and dirtyType are candidates for deprecation.
231
+
232
+ root
233
+ empty
234
+ deleted // hidden from stateName
235
+ preloaded // hidden from stateName
236
+
237
+ loading
238
+ empty // hidden from stateName
239
+ preloaded // hidden from stateName
240
+
241
+ loaded
242
+ saved
243
+ updated
244
+ uncommitted
245
+ invalid
246
+ inFlight
247
+ created
248
+ uncommitted
249
+ invalid
250
+ inFlight
251
+
252
+ deleted
253
+ saved
254
+ new // hidden from stateName
255
+ uncommitted
256
+ invalid
257
+ inFlight
258
+
259
+ @internal
260
+ */
261
+ class RecordState {
262
+ constructor(record) {
263
+ const store = storeFor(record);
264
+ const identity = recordIdentifierFor$1(record);
265
+ this.identifier = identity;
266
+ this.record = record;
267
+ this.cache = store.cache;
268
+ this.pendingCount = 0;
269
+ this.fulfilledCount = 0;
270
+ this.rejectedCount = 0;
271
+ this._errorRequests = [];
272
+ this._lastError = null;
273
+ const requests = store.getRequestStateService();
274
+ const notifications = store.notifications;
275
+ const handleRequest = req => {
276
+ if (req.type === 'mutation') {
277
+ switch (req.state) {
278
+ case 'pending':
279
+ this.isSaving = true;
280
+ break;
281
+ case 'rejected':
282
+ this.isSaving = false;
283
+ this._lastError = req;
284
+ if (!(req.response && isInvalidError(req.response.data))) {
285
+ this._errorRequests.push(req);
286
+ }
287
+ notifyErrorsStateChanged(this);
288
+ break;
289
+ case 'fulfilled':
290
+ this._errorRequests = [];
291
+ this._lastError = null;
292
+ this.isSaving = false;
293
+ this.notify('isDirty');
294
+ notifyErrorsStateChanged(this);
295
+ break;
296
+ }
297
+ } else {
298
+ switch (req.state) {
299
+ case 'pending':
300
+ this.pendingCount++;
301
+ this.notify('isLoading');
302
+ break;
303
+ case 'rejected':
304
+ this.pendingCount--;
305
+ this._lastError = req;
306
+ if (!(req.response && isInvalidError(req.response.data))) {
307
+ this._errorRequests.push(req);
308
+ }
309
+ this.notify('isLoading');
310
+ notifyErrorsStateChanged(this);
311
+ break;
312
+ case 'fulfilled':
313
+ this.pendingCount--;
314
+ this.fulfilledCount++;
315
+ this.notify('isLoading');
316
+ this.notify('isDirty');
317
+ notifyErrorsStateChanged(this);
318
+ this._errorRequests = [];
319
+ this._lastError = null;
320
+ break;
321
+ }
322
+ }
323
+ };
324
+ requests.subscribeForRecord(identity, handleRequest);
325
+
326
+ // we instantiate lazily
327
+ // so we grab anything we don't have yet
328
+ const lastRequest = requests.getLastRequestForRecord(identity);
329
+ if (lastRequest) {
330
+ handleRequest(lastRequest);
331
+ }
332
+ this.handler = notifications.subscribe(identity, (identifier, type, key) => {
333
+ switch (type) {
334
+ case 'state':
335
+ this.notify('isSaved');
336
+ this.notify('isNew');
337
+ this.notify('isDeleted');
338
+ this.notify('isDirty');
339
+ break;
340
+ case 'attributes':
341
+ this.notify('isEmpty');
342
+ this.notify('isDirty');
343
+ break;
344
+ case 'errors':
345
+ this.updateInvalidErrors(this.record.errors);
346
+ this.notify('isValid');
347
+ break;
348
+ }
349
+ });
350
+ }
351
+ destroy() {
352
+ storeFor(this.record).notifications.unsubscribe(this.handler);
353
+ }
354
+ notify(key) {
355
+ const signals = withSignalStore(this);
356
+ const signal = peekInternalSignal(signals, key);
357
+ if (signal) {
358
+ notifyInternalSignal(signal);
359
+ }
360
+ }
361
+ updateInvalidErrors(errors) {
362
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
363
+ if (!test) {
364
+ throw new Error(`Expected the Cache instance for ${this.identifier.lid} to implement getErrors(identifier)`);
365
+ }
366
+ })(typeof this.cache.getErrors === 'function') : {};
367
+ const jsonApiErrors = this.cache.getErrors(this.identifier);
368
+ errors.clear();
369
+ for (let i = 0; i < jsonApiErrors.length; i++) {
370
+ const error = jsonApiErrors[i];
371
+ if (error.source && error.source.pointer) {
372
+ const keyMatch = error.source.pointer.match(SOURCE_POINTER_REGEXP);
373
+ let key;
374
+ if (keyMatch) {
375
+ key = keyMatch[2];
376
+ } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
377
+ key = PRIMARY_ATTRIBUTE_KEY;
378
+ }
379
+ if (key) {
380
+ const errMsg = error.detail || error.title;
381
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
382
+ if (!test) {
383
+ throw new Error(`Expected field error to have a detail or title to use as the message`);
384
+ }
385
+ })(errMsg) : {};
386
+ errors.add(key, errMsg);
387
+ }
388
+ }
389
+ }
390
+ }
391
+ cleanErrorRequests() {
392
+ this.notify('isValid');
393
+ this.notify('isError');
394
+ this.notify('adapterError');
395
+ this._errorRequests = [];
396
+ this._lastError = null;
397
+ }
398
+ get isLoading() {
399
+ return !this.isLoaded && this.pendingCount > 0 && this.fulfilledCount === 0;
400
+ }
401
+ static {
402
+ decorateMethodV2(this.prototype, "isLoading", [gate]);
403
+ }
404
+ get isLoaded() {
405
+ if (this.isNew) {
406
+ return true;
407
+ }
408
+ return this.fulfilledCount > 0 || !this.isEmpty;
409
+ }
410
+ static {
411
+ decorateMethodV2(this.prototype, "isLoaded", [gate]);
412
+ }
413
+ get isSaved() {
414
+ const rd = this.cache;
415
+ if (this.isDeleted) {
416
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
417
+ if (!test) {
418
+ throw new Error(`Expected Cache to implement isDeletionCommitted()`);
419
+ }
420
+ })(typeof rd.isDeletionCommitted === 'function') : {};
421
+ return rd.isDeletionCommitted(this.identifier);
422
+ }
423
+ if (this.isNew || this.isEmpty || !this.isValid || this.isDirty || this.isLoading) {
424
+ return false;
425
+ }
426
+ return true;
427
+ }
428
+ static {
429
+ decorateMethodV2(this.prototype, "isSaved", [gate]);
430
+ }
431
+ get isEmpty() {
432
+ const rd = this.cache;
433
+ // TODO this is not actually an RFC'd concept. Determine the
434
+ // correct heuristic to replace this with.
435
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
436
+ if (!test) {
437
+ throw new Error(`Expected Cache to implement isEmpty()`);
438
+ }
439
+ })(typeof rd.isEmpty === 'function') : {};
440
+ return !this.isNew && rd.isEmpty(this.identifier);
441
+ }
442
+ static {
443
+ decorateMethodV2(this.prototype, "isEmpty", [gate]);
444
+ }
445
+ get isNew() {
446
+ const rd = this.cache;
447
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
448
+ if (!test) {
449
+ throw new Error(`Expected Cache to implement isNew()`);
450
+ }
451
+ })(typeof rd.isNew === 'function') : {};
452
+ return rd.isNew(this.identifier);
453
+ }
454
+ static {
455
+ decorateMethodV2(this.prototype, "isNew", [gate]);
456
+ }
457
+ get isDeleted() {
458
+ const rd = this.cache;
459
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
460
+ if (!test) {
461
+ throw new Error(`Expected Cache to implement isDeleted()`);
462
+ }
463
+ })(typeof rd.isDeleted === 'function') : {};
464
+ return rd.isDeleted(this.identifier);
465
+ }
466
+ static {
467
+ decorateMethodV2(this.prototype, "isDeleted", [gate]);
468
+ }
469
+ get isValid() {
470
+ return this.record.errors.length === 0;
471
+ }
472
+ static {
473
+ decorateMethodV2(this.prototype, "isValid", [gate]);
474
+ }
475
+ get isDirty() {
476
+ const rd = this.cache;
477
+ if (this.isEmpty || rd.isDeletionCommitted(this.identifier) || this.isDeleted && this.isNew) {
478
+ return false;
479
+ }
480
+ return this.isDeleted || this.isNew || rd.hasChangedAttrs(this.identifier);
481
+ }
482
+ static {
483
+ decorateMethodV2(this.prototype, "isDirty", [gate]);
484
+ }
485
+ get isError() {
486
+ const errorReq = this._errorRequests[this._errorRequests.length - 1];
487
+ if (!errorReq) {
488
+ return false;
489
+ } else {
490
+ return true;
491
+ }
492
+ }
493
+ static {
494
+ decorateMethodV2(this.prototype, "isError", [gate]);
495
+ }
496
+ get adapterError() {
497
+ const request = this._lastError;
498
+ if (!request) {
499
+ return null;
500
+ }
501
+ return request.state === 'rejected' && request.response.data;
502
+ }
503
+ static {
504
+ decorateMethodV2(this.prototype, "adapterError", [gate]);
505
+ }
506
+ get isPreloaded() {
507
+ return !this.isEmpty && this.isLoading;
508
+ }
509
+ static {
510
+ decorateMethodV2(this.prototype, "isPreloaded", [memoized]);
511
+ }
512
+ get stateName() {
513
+ // we might be empty while loading so check this first
514
+ if (this.isLoading) {
515
+ return 'root.loading';
516
+
517
+ // got nothing yet or were unloaded
518
+ } else if (this.isEmpty) {
519
+ return 'root.empty';
520
+
521
+ // deleted substates
522
+ } else if (this.isDeleted) {
523
+ if (this.isSaving) {
524
+ return 'root.deleted.inFlight';
525
+ } else if (this.isSaved) {
526
+ // TODO ensure isSaved isn't true from previous requests
527
+ return 'root.deleted.saved';
528
+ } else if (!this.isValid) {
529
+ return 'root.deleted.invalid';
530
+ } else {
531
+ return 'root.deleted.uncommitted';
532
+ }
533
+
534
+ // loaded.created substates
535
+ } else if (this.isNew) {
536
+ if (this.isSaving) {
537
+ return 'root.loaded.created.inFlight';
538
+ } else if (!this.isValid) {
539
+ return 'root.loaded.created.invalid';
540
+ }
541
+ return 'root.loaded.created.uncommitted';
542
+
543
+ // loaded.updated substates
544
+ } else if (this.isSaving) {
545
+ return 'root.loaded.updated.inFlight';
546
+ } else if (!this.isValid) {
547
+ return 'root.loaded.updated.invalid';
548
+ } else if (this.isDirty) {
549
+ return 'root.loaded.updated.uncommitted';
550
+
551
+ // if nothing remains, we are loaded saved!
552
+ } else {
553
+ return 'root.loaded.saved';
554
+ }
555
+ }
556
+ static {
557
+ decorateMethodV2(this.prototype, "stateName", [memoized]);
558
+ }
559
+ get dirtyType() {
560
+ // we might be empty while loading so check this first
561
+ if (this.isLoading || this.isEmpty) {
562
+ return '';
563
+
564
+ // deleted substates
565
+ } else if (this.isDirty && this.isDeleted) {
566
+ return 'deleted';
567
+
568
+ // loaded.created substates
569
+ } else if (this.isNew) {
570
+ return 'created';
571
+
572
+ // loaded.updated substates
573
+ } else if (this.isSaving || !this.isValid || this.isDirty) {
574
+ return 'updated';
575
+
576
+ // if nothing remains, we are loaded saved!
577
+ } else {
578
+ return '';
579
+ }
580
+ }
581
+ static {
582
+ decorateMethodV2(this.prototype, "dirtyType", [memoized]);
583
+ }
584
+ }
585
+ defineSignal(RecordState.prototype, 'isSaving', false);
586
+ function notifyErrorsStateChanged(state) {
587
+ state.notify('isValid');
588
+ state.notify('isError');
589
+ state.notify('adapterError');
590
+ }
591
+
592
+ /*
593
+ * This decorator allows us to lazily compute
594
+ * an expensive getter on first-access and thereafter
595
+ * never recompute it.
596
+ */
597
+ function computeOnce(target, propertyName, desc) {
598
+ const cache = new WeakMap();
599
+ // eslint-disable-next-line @typescript-eslint/unbound-method
600
+ const getter = desc.get;
601
+ desc.get = function () {
602
+ let meta = cache.get(this);
603
+ if (!meta) {
604
+ meta = {
605
+ hasComputed: false,
606
+ value: undefined
607
+ };
608
+ cache.set(this, meta);
609
+ }
610
+ if (!meta.hasComputed) {
611
+ meta.value = getter.call(this);
612
+ meta.hasComputed = true;
613
+ }
614
+ return meta.value;
615
+ };
616
+ return desc;
617
+ }
618
+
619
+ /**
620
+ * @noInheritDoc
621
+ */
622
+
623
+ /**
624
+ * Base class from which Models can be defined.
625
+ *
626
+ * ::: code-group
627
+ *
628
+ * ```js [app/models/user.js]
629
+ * import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
630
+ *
631
+ * export default class User extends Model {
632
+ * @attr name;
633
+ * @attr('number') age;
634
+ * @hasMany('post', { async: true, inverse: null }) posts;
635
+ * @belongsTo('group', { async: false, inverse: 'users' }) group;
636
+ * }
637
+ * ```
638
+ *
639
+ * ```ts [app/models/user.ts]
640
+ * import Model, { attr, belongsTo, hasMany, type AsyncHasMany } from '@ember-data/model';
641
+ * import type { NumberTransform } from '@ember-data/serializer/transform';
642
+ * import type Group from './group';
643
+ * import type Post from './post';
644
+ *
645
+ * export default class User extends Model {
646
+ * @attr declare name: string;
647
+ *
648
+ * @attr<NumberTransform>('number')
649
+ * declare age: number;
650
+ *
651
+ * @hasMany('post', { async: true, inverse: null })
652
+ * declare posts: AsyncHasMany<Post>;
653
+ *
654
+ * @belongsTo('group', { async: false, inverse: 'users' })
655
+ * declare group: Group | null;
656
+ * }
657
+ * ```
658
+ *
659
+ * :::
660
+ *
661
+ * Models both define the schema for a resource type and provide
662
+ * the class to use as the reactive object for data of resource
663
+ * of that type.
664
+ *
665
+ * @noInheritDoc
666
+ */
667
+ class Model extends EmberObject {
668
+ // set during create by the store
669
+ /**
670
+ * The store service instance which created this record instance
671
+ */
672
+
673
+ /** @internal */
674
+
675
+ /** @internal */
676
+
677
+ /** @internal */
678
+
679
+ /** @internal */
680
+ init(options) {
681
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
682
+ if (!options?._secretInit && !options?._createProps) {
683
+ throw new Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
684
+ }
685
+ }
686
+ const createProps = options._createProps;
687
+ const _secretInit = options._secretInit;
688
+ options._createProps = null;
689
+ options._secretInit = null;
690
+ const store = this.store = _secretInit.store;
691
+ super.init(options);
692
+ this[RecordStore] = store;
693
+ const identity = _secretInit.identifier;
694
+ _secretInit.cb(this, _secretInit.cache, identity, _secretInit.store);
695
+ this.___recordState = macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? new RecordState(this) : null;
696
+ this.setProperties(createProps);
697
+ const notifications = store.notifications;
698
+ this.___private_notifications = notifications.subscribe(identity, (identifier, type, field) => {
699
+ notifyChanges(identifier, type, field, this, store);
700
+ });
701
+ }
702
+
703
+ /** @internal */
704
+ // @ts-expect-error destroy should not return a value, but ember's types force it to
705
+ destroy() {
706
+ const identifier = recordIdentifierFor(this);
707
+ this.___recordState?.destroy();
708
+ const store = storeFor(this);
709
+ store.notifications.unsubscribe(this.___private_notifications);
710
+ LEGACY_SUPPORT.get(this)?.destroy();
711
+ LEGACY_SUPPORT.delete(this);
712
+ LEGACY_SUPPORT.delete(identifier);
713
+ super.destroy();
714
+ }
715
+
716
+ /**
717
+ If this property is `true` the record is in the `empty`
718
+ state. Empty is the first state all records enter after they have
719
+ been created. Most records created by the store will quickly
720
+ transition to the `loading` state if data needs to be fetched from
721
+ the server or the `created` state if the record is created on the
722
+ client. A record can also enter the empty state if the adapter is
723
+ unable to locate the record.
724
+ @property isEmpty
725
+ @public
726
+ @readonly
727
+ */
728
+ get isEmpty() {
729
+ return this.currentState.isEmpty;
730
+ }
731
+
732
+ /**
733
+ If this property is `true` the record is in the `loading` state. A
734
+ record enters this state when the store asks the adapter for its
735
+ data. It remains in this state until the adapter provides the
736
+ requested data.
737
+ @property isLoading
738
+ @public
739
+ @readonly
740
+ */
741
+ static {
742
+ decorateMethodV2(this.prototype, "isEmpty", [memoized]);
743
+ }
744
+ get isLoading() {
745
+ return this.currentState.isLoading;
746
+ }
747
+
748
+ /**
749
+ If this property is `true` the record is in the `loaded` state. A
750
+ record enters this state when its data is populated. Most of a
751
+ record's lifecycle is spent inside substates of the `loaded`
752
+ state.
753
+ Example
754
+ ```javascript
755
+ let record = store.createRecord('model');
756
+ record.isLoaded; // true
757
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
758
+ model.isLoaded;
759
+ ```
760
+ @property isLoaded
761
+ @public
762
+ @readonly
763
+ */
764
+ static {
765
+ decorateMethodV2(this.prototype, "isLoading", [memoized]);
766
+ }
767
+ get isLoaded() {
768
+ return this.currentState.isLoaded;
769
+ }
770
+
771
+ /**
772
+ If this property is `true` the record is in the `dirty` state. The
773
+ record has local changes that have not yet been saved by the
774
+ adapter. This includes records that have been created (but not yet
775
+ saved) or deleted.
776
+ Example
777
+ ```javascript
778
+ let record = store.createRecord('model');
779
+ record.hasDirtyAttributes; // true
780
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
781
+ model.hasDirtyAttributes; // false
782
+ model.foo = 'some value';
783
+ model.hasDirtyAttributes; // true
784
+ ```
785
+ @since 1.13.0
786
+ @property hasDirtyAttributes
787
+ @public
788
+ @readonly
789
+ */
790
+ static {
791
+ decorateMethodV2(this.prototype, "isLoaded", [memoized]);
792
+ }
793
+ get hasDirtyAttributes() {
794
+ return this.currentState.isDirty;
795
+ }
796
+
797
+ /**
798
+ If this property is `true` the record is in the `saving` state. A
799
+ record enters the saving state when `save` is called, but the
800
+ adapter has not yet acknowledged that the changes have been
801
+ persisted to the backend.
802
+ Example
803
+ ```javascript
804
+ let record = store.createRecord('model');
805
+ record.isSaving; // false
806
+ let promise = record.save();
807
+ record.isSaving; // true
808
+ promise.then(function() {
809
+ record.isSaving; // false
810
+ });
811
+ ```
812
+ @property isSaving
813
+ @public
814
+ @readonly
815
+ */
816
+ static {
817
+ decorateMethodV2(this.prototype, "hasDirtyAttributes", [memoized]);
818
+ }
819
+ get isSaving() {
820
+ return this.currentState.isSaving;
821
+ }
822
+
823
+ /**
824
+ If this property is `true` the record is in the `deleted` state
825
+ and has been marked for deletion. When `isDeleted` is true and
826
+ `hasDirtyAttributes` is true, the record is deleted locally but the deletion
827
+ was not yet persisted. When `isSaving` is true, the change is
828
+ in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
829
+ change has persisted.
830
+ Example
831
+ ```javascript
832
+ let record = store.createRecord('model');
833
+ record.isDeleted; // false
834
+ record.deleteRecord();
835
+ // Locally deleted
836
+ record.isDeleted; // true
837
+ record.hasDirtyAttributes; // true
838
+ record.isSaving; // false
839
+ // Persisting the deletion
840
+ let promise = record.save();
841
+ record.isDeleted; // true
842
+ record.isSaving; // true
843
+ // Deletion Persisted
844
+ promise.then(function() {
845
+ record.isDeleted; // true
846
+ record.isSaving; // false
847
+ record.hasDirtyAttributes; // false
848
+ });
849
+ ```
850
+ @property isDeleted
851
+ @public
852
+ @readonly
853
+ */
854
+ static {
855
+ decorateMethodV2(this.prototype, "isSaving", [memoized]);
856
+ }
857
+ get isDeleted() {
858
+ return this.currentState.isDeleted;
859
+ }
860
+
861
+ /**
862
+ If this property is `true` the record is in the `new` state. A
863
+ record will be in the `new` state when it has been created on the
864
+ client and the adapter has not yet report that it was successfully
865
+ saved.
866
+ Example
867
+ ```javascript
868
+ let record = store.createRecord('model');
869
+ record.isNew; // true
870
+ record.save().then(function(model) {
871
+ model.isNew; // false
872
+ });
873
+ ```
874
+ @property isNew
875
+ @public
876
+ @readonly
877
+ */
878
+ static {
879
+ decorateMethodV2(this.prototype, "isDeleted", [memoized]);
880
+ }
881
+ get isNew() {
882
+ return this.currentState.isNew;
883
+ }
884
+
885
+ /**
886
+ If this property is `true` the record is in the `valid` state.
887
+ A record will be in the `valid` state when the adapter did not report any
888
+ server-side validation failures.
889
+ @property isValid
890
+ @public
891
+ @readonly
892
+ */
893
+ static {
894
+ decorateMethodV2(this.prototype, "isNew", [memoized]);
895
+ }
896
+ get isValid() {
897
+ return this.currentState.isValid;
898
+ }
899
+
900
+ /**
901
+ If the record is in the dirty state this property will report what
902
+ kind of change has caused it to move into the dirty
903
+ state. Possible values are:
904
+ - `created` The record has been created by the client and not yet saved to the adapter.
905
+ - `updated` The record has been updated by the client and not yet saved to the adapter.
906
+ - `deleted` The record has been deleted by the client and not yet saved to the adapter.
907
+ Example
908
+ ```javascript
909
+ let record = store.createRecord('model');
910
+ record.dirtyType; // 'created'
911
+ ```
912
+ @property dirtyType
913
+ @public
914
+ @readonly
915
+ */
916
+ static {
917
+ decorateMethodV2(this.prototype, "isValid", [memoized]);
918
+ }
919
+ get dirtyType() {
920
+ return this.currentState.dirtyType;
921
+ }
922
+
923
+ /**
924
+ If `true` the adapter reported that it was unable to save local
925
+ changes to the backend for any reason other than a server-side
926
+ validation error.
927
+ Example
928
+ ```javascript
929
+ record.isError; // false
930
+ record.set('foo', 'valid value');
931
+ record.save().then(null, function() {
932
+ record.isError; // true
933
+ });
934
+ ```
935
+ @property isError
936
+ @public
937
+ @readonly
938
+ */
939
+ static {
940
+ decorateMethodV2(this.prototype, "dirtyType", [memoized]);
941
+ }
942
+ get isError() {
943
+ return this.currentState.isError;
944
+ }
945
+ static {
946
+ decorateMethodV2(this.prototype, "isError", [memoized]);
947
+ }
948
+ set isError(v) {
949
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
950
+ throw new Error(`isError is not directly settable`);
951
+ }
952
+ }
953
+
954
+ /**
955
+ If `true` the store is attempting to reload the record from the adapter.
956
+ Example
957
+ ```javascript
958
+ record.isReloading; // false
959
+ record.reload();
960
+ record.isReloading; // true
961
+ ```
962
+ @property isReloading
963
+ @public
964
+ @readonly
965
+ */
966
+
967
+ /**
968
+ All ember models have an id property. This is an identifier
969
+ managed by an external source. These are always coerced to be
970
+ strings before being used internally. Note when declaring the
971
+ attributes for a model it is an error to declare an id
972
+ attribute.
973
+ ```javascript
974
+ let record = store.createRecord('model');
975
+ record.id; // null
976
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
977
+ model.id; // '1'
978
+ ```
979
+ @property id
980
+ @public
981
+ */
982
+ get id() {
983
+ // this guard exists, because some dev-only deprecation code
984
+ // (addListener via validatePropertyInjections) invokes toString before the
985
+ // object is real.
986
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
987
+ try {
988
+ return recordIdentifierFor(this).id;
989
+ } catch {
990
+ return null;
991
+ }
992
+ }
993
+ return recordIdentifierFor(this).id;
994
+ }
995
+ static {
996
+ decorateMethodV2(this.prototype, "id", [gate]);
997
+ }
998
+ set id(id) {
999
+ const normalizedId = coerceId(id);
1000
+ const identifier = recordIdentifierFor(this);
1001
+ const didChange = normalizedId !== identifier.id;
1002
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1003
+ if (!test) {
1004
+ throw new Error(`Cannot set ${identifier.type} record's id to ${id}, because id is already ${identifier.id}`);
1005
+ }
1006
+ })(!didChange || identifier.id === null) : {};
1007
+ if (normalizedId !== null && didChange) {
1008
+ this.store._instanceCache.setRecordId(identifier, normalizedId);
1009
+ this.store.notifications.notify(identifier, 'identity');
1010
+ }
1011
+ }
1012
+ toString() {
1013
+ return `<model::${this.constructor.modelName}:${this.id}>`;
1014
+ }
1015
+
1016
+ /**
1017
+ @property currentState
1018
+ @private
1019
+ */
1020
+ // TODO we can probably make this a computeOnce
1021
+ // we likely do not need to notify the currentState root anymore
1022
+ get currentState() {
1023
+ // descriptors are called with the wrong `this` context during mergeMixins
1024
+ // when using legacy/classic ember classes. Basically: lazy in prod and eager in dev.
1025
+ // so we do this to try to steer folks to the nicer "dont user currentState"
1026
+ // error.
1027
+ if (macroCondition(!getGlobalConfig().WarpDrive.env.DEBUG)) {
1028
+ if (!this.___recordState) {
1029
+ this.___recordState = new RecordState(this);
1030
+ }
1031
+ }
1032
+ return this.___recordState;
1033
+ }
1034
+ static {
1035
+ decorateMethodV2(this.prototype, "currentState", [gate]);
1036
+ }
1037
+ set currentState(_v) {
1038
+ throw new Error('cannot set currentState');
1039
+ }
1040
+
1041
+ /**
1042
+ The store service instance which created this record instance
1043
+ @property store
1044
+ @public
1045
+ */
1046
+
1047
+ /**
1048
+ When the record is in the `invalid` state this object will contain
1049
+ any errors returned by the adapter. When present the errors hash
1050
+ contains keys corresponding to the invalid property names
1051
+ and values which are arrays of Javascript objects with two keys:
1052
+ - `message` A string containing the error message from the backend
1053
+ - `attribute` The name of the property associated with this error message
1054
+ ```javascript
1055
+ record.errors.length; // 0
1056
+ record.set('foo', 'invalid value');
1057
+ record.save().catch(function() {
1058
+ record.errors.foo;
1059
+ // [{message: 'foo should be a number.', attribute: 'foo'}]
1060
+ });
1061
+ ```
1062
+ The `errors` property is useful for displaying error messages to
1063
+ the user.
1064
+ ```handlebars
1065
+ <label>Username: <Input @value={{@model.username}} /> </label>
1066
+ {{#each @model.errors.username as |error|}}
1067
+ <div class="error">
1068
+ {{error.message}}
1069
+ </div>
1070
+ {{/each}}
1071
+ <label>Email: <Input @value={{@model.email}} /> </label>
1072
+ {{#each @model.errors.email as |error|}}
1073
+ <div class="error">
1074
+ {{error.message}}
1075
+ </div>
1076
+ {{/each}}
1077
+ ```
1078
+ You can also access the special `messages` property on the error
1079
+ object to get an array of all the error strings.
1080
+ ```handlebars
1081
+ {{#each @model.errors.messages as |message|}}
1082
+ <div class="error">
1083
+ {{message}}
1084
+ </div>
1085
+ {{/each}}
1086
+ ```
1087
+ @property errors
1088
+ @public
1089
+ */
1090
+ get errors() {
1091
+ const errors = Errors.create({
1092
+ __record: this
1093
+ });
1094
+ this.currentState.updateInvalidErrors(errors);
1095
+ return errors;
1096
+ }
1097
+
1098
+ /**
1099
+ This property holds the `AdapterError` object with which
1100
+ last adapter operation was rejected.
1101
+ @property adapterError
1102
+ @public
1103
+ */
1104
+ static {
1105
+ decorateMethodV2(this.prototype, "errors", [computeOnce]);
1106
+ }
1107
+ get adapterError() {
1108
+ return this.currentState.adapterError;
1109
+ }
1110
+ static {
1111
+ decorateMethodV2(this.prototype, "adapterError", [memoized]);
1112
+ }
1113
+ set adapterError(v) {
1114
+ throw new Error(`adapterError is not directly settable`);
1115
+ }
1116
+
1117
+ /*
1118
+ We hook the default implementation to ensure
1119
+ our tagged properties are properly notified
1120
+ as well. We still super for everything because
1121
+ sync observers require a direct call occuring
1122
+ to trigger their flush. We wouldn't need to
1123
+ super in 4.0+ where sync observers are removed.
1124
+ */
1125
+ // @ts-expect-error no return is necessary, but Ember's types are forcing it
1126
+ notifyPropertyChange(prop) {
1127
+ const signals = withSignalStore(this);
1128
+ entangleSignal(signals, this, prop, undefined);
1129
+ super.notifyPropertyChange(prop);
1130
+ }
1131
+
1132
+ /** @internal */
1133
+ attr() {
1134
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1135
+ {
1136
+ throw new Error('The `attr` method is not available on Model, a Snapshot was probably expected. Are you passing a Model instead of a Snapshot to your serializer?');
1137
+ }
1138
+ })() : {};
1139
+ }
1140
+
1141
+ /**
1142
+ Given a callback, iterates over each of the relationships in the model,
1143
+ invoking the callback with the name of each relationship and its relationship
1144
+ descriptor.
1145
+ The callback method you provide should have the following signature (all
1146
+ parameters are optional):
1147
+ ```javascript
1148
+ function(name, descriptor);
1149
+ ```
1150
+ - `name` the name of the current property in the iteration
1151
+ - `descriptor` the meta object that describes this relationship
1152
+ The relationship descriptor argument is an object with the following properties.
1153
+ - **name** <span class="type">String</span> the name of this relationship on the Model
1154
+ - **kind** <span class="type">String</span> "hasMany" or "belongsTo"
1155
+ - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
1156
+ - **parentType** <span class="type">Model</span> the type of the Model that owns this relationship
1157
+ - **type** <span class="type">String</span> the type name of the related Model
1158
+ Note that in addition to a callback, you can also pass an optional target
1159
+ object that will be set as `this` on the context.
1160
+ Example
1161
+ ```js [app/serializers/application.js]
1162
+ import JSONSerializer from '@ember-data/serializer/json';
1163
+ export default class ApplicationSerializer extends JSONSerializer {
1164
+ serialize(record, options) {
1165
+ let json = {};
1166
+ record.eachRelationship(function(name, descriptor) {
1167
+ if (descriptor.kind === 'hasMany') {
1168
+ let serializedHasManyName = name.toUpperCase() + '_IDS';
1169
+ json[serializedHasManyName] = record.get(name).map(r => r.id);
1170
+ }
1171
+ });
1172
+ return json;
1173
+ }
1174
+ }
1175
+ ```
1176
+ @public
1177
+ @param {Function} callback the callback to invoke
1178
+ @param {any} binding the value to which the callback's `this` should be bound
1179
+ */
1180
+ eachRelationship(callback, binding) {
1181
+ this.constructor.eachRelationship(callback, binding);
1182
+ }
1183
+ relationshipFor(name) {
1184
+ return this.constructor.relationshipsByName.get(name);
1185
+ }
1186
+ inverseFor(name) {
1187
+ return this.constructor.inverseFor(name, storeFor(this));
1188
+ }
1189
+ eachAttribute(callback, binding) {
1190
+ this.constructor.eachAttribute(callback, binding);
1191
+ }
1192
+
1193
+ /**
1194
+ * @internal
1195
+ */
1196
+ static isModel = true;
1197
+
1198
+ /**
1199
+ Represents the model's class name as a string. This can be used to look up the model's class name through
1200
+ `Store`'s modelFor method.
1201
+ `modelName` is generated for you by EmberData. It will be a lowercased, dasherized string.
1202
+ For example:
1203
+ ```javascript
1204
+ store.modelFor('post').modelName; // 'post'
1205
+ store.modelFor('blog-post').modelName; // 'blog-post'
1206
+ ```
1207
+ The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
1208
+ keys to underscore (instead of dasherized), you might use the following code:
1209
+ ```javascript
1210
+ import RESTSerializer from '@ember-data/serializer/rest';
1211
+ import { underscore } from '<app-name>/utils/string-utils';
1212
+ export default const PostSerializer = RESTSerializer.extend({
1213
+ payloadKeyFromModelName(modelName) {
1214
+ return underscore(modelName);
1215
+ }
1216
+ });
1217
+ ```
1218
+ @property modelName
1219
+ @public
1220
+ @readonly
1221
+ */
1222
+ static modelName = null;
1223
+
1224
+ /*
1225
+ These class methods below provide relationship
1226
+ introspection abilities about relationships.
1227
+ A note about the computed properties contained here:
1228
+ **These properties are effectively sealed once called for the first time.**
1229
+ To avoid repeatedly doing expensive iteration over a model's fields, these
1230
+ values are computed once and then cached for the remainder of the runtime of
1231
+ your application.
1232
+ If your application needs to modify a class after its initial definition
1233
+ (for example, using `reopen()` to add additional attributes), make sure you
1234
+ do it before using your model with the store, which uses these properties
1235
+ extensively.
1236
+ */
1237
+
1238
+ /**
1239
+ For a given relationship name, returns the model type of the relationship.
1240
+ For example, if you define a model like this:
1241
+ ```js [app/models/post.js]
1242
+ import Model, { hasMany } from '@ember-data/model';
1243
+ export default class PostModel extends Model {
1244
+ @hasMany('comment') comments;
1245
+ }
1246
+ ```
1247
+ Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`.
1248
+ @public
1249
+ @param {String} name the name of the relationship
1250
+ @param {store} store an instance of Store
1251
+ @return {Model} the type of the relationship, or undefined
1252
+ */
1253
+ static typeForRelationship(name, store) {
1254
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1255
+ if (!test) {
1256
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1257
+ }
1258
+ })(this.modelName) : {};
1259
+ const relationship = this.relationshipsByName.get(name);
1260
+ return relationship && store.modelFor(relationship.type);
1261
+ }
1262
+ static get inverseMap() {
1263
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1264
+ if (!test) {
1265
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1266
+ }
1267
+ })(this.modelName) : {};
1268
+ return Object.create(null);
1269
+ }
1270
+
1271
+ /**
1272
+ Find the relationship which is the inverse of the one asked for.
1273
+ For example, if you define models like this:
1274
+ ```js [app/models/post.js]
1275
+ import Model, { hasMany } from '@ember-data/model';
1276
+ export default class PostModel extends Model {
1277
+ @hasMany('message') comments;
1278
+ }
1279
+ ```
1280
+ ```js [app/models/message.js]
1281
+ import Model, { belongsTo } from '@ember-data/model';
1282
+ export default class MessageModel extends Model {
1283
+ @belongsTo('post') owner;
1284
+ }
1285
+ ```
1286
+ ``` js
1287
+ store.modelFor('post').inverseFor('comments', store) // { type: 'message', name: 'owner', kind: 'belongsTo' }
1288
+ store.modelFor('message').inverseFor('owner', store) // { type: 'post', name: 'comments', kind: 'hasMany' }
1289
+ ```
1290
+ @public
1291
+ @param {String} name the name of the relationship
1292
+ @param {Store} store
1293
+ @return {Object} the inverse relationship, or null
1294
+ */
1295
+ static {
1296
+ decorateMethodV2(this, "inverseMap", [computeOnce]);
1297
+ }
1298
+ static inverseFor(name, store) {
1299
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1300
+ if (!test) {
1301
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1302
+ }
1303
+ })(this.modelName) : {};
1304
+ const inverseMap = this.inverseMap;
1305
+ if (inverseMap[name]) {
1306
+ return inverseMap[name];
1307
+ } else {
1308
+ const inverse = this._findInverseFor(name, store);
1309
+ inverseMap[name] = inverse;
1310
+ return inverse;
1311
+ }
1312
+ }
1313
+
1314
+ //Calculate the inverse, ignoring the cache
1315
+ static _findInverseFor(name, store) {
1316
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1317
+ if (!test) {
1318
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1319
+ }
1320
+ })(this.modelName) : {};
1321
+ const relationship = this.relationshipsByName.get(name);
1322
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1323
+ if (!test) {
1324
+ throw new Error(`No relationship named '${name}' on '${this.modelName}' exists.`);
1325
+ }
1326
+ })(relationship) : {};
1327
+ if (!relationship) {
1328
+ return null;
1329
+ }
1330
+ const {
1331
+ options
1332
+ } = relationship;
1333
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1334
+ if (!test) {
1335
+ throw new Error(`Expected the relationship ${name} on ${this.modelName} to define an inverse.`);
1336
+ }
1337
+ })(options.inverse === null || typeof options.inverse === 'string' && options.inverse.length > 0) : {};
1338
+ if (options.inverse === null) {
1339
+ return null;
1340
+ }
1341
+ const schemaExists = store.schema.hasResource(relationship);
1342
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1343
+ if (!test) {
1344
+ throw new Error(`No associated schema found for '${relationship.type}' while calculating the inverse of ${name} on ${this.modelName}`);
1345
+ }
1346
+ })(schemaExists) : {};
1347
+ if (!schemaExists) {
1348
+ return null;
1349
+ }
1350
+ const inverseField = store.schema.fields(relationship).get(options.inverse);
1351
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1352
+ if (!test) {
1353
+ throw new Error(`No inverse relationship found for '${name}' on '${this.modelName}'`);
1354
+ }
1355
+ })(inverseField && (inverseField.kind === 'belongsTo' || inverseField.kind === 'hasMany')) : {};
1356
+ return inverseField || null;
1357
+ }
1358
+
1359
+ /**
1360
+ The model's relationships as a map, keyed on the type of the
1361
+ relationship. The value of each entry is an array containing a descriptor
1362
+ for each relationship with that type, describing the name of the relationship
1363
+ as well as the type.
1364
+ For example, given the following model definition:
1365
+ ```js [app/models/blog.js]
1366
+ import Model, { belongsTo, hasMany } from '@ember-data/model';
1367
+ export default class BlogModel extends Model {
1368
+ @hasMany('user') users;
1369
+ @belongsTo('user') owner;
1370
+ @hasMany('post') posts;
1371
+ }
1372
+ ```
1373
+ This computed property would return a map describing these
1374
+ relationships, like this:
1375
+ ```javascript
1376
+ import Blog from 'app/models/blog';
1377
+ import User from 'app/models/user';
1378
+ import Post from 'app/models/post';
1379
+ let relationships = Blog.relationships;
1380
+ relationships.user;
1381
+ //=> [ { name: 'users', kind: 'hasMany' },
1382
+ // { name: 'owner', kind: 'belongsTo' } ]
1383
+ relationships.post;
1384
+ //=> [ { name: 'posts', kind: 'hasMany' } ]
1385
+ ```
1386
+ @property relationships
1387
+ @public
1388
+ @readonly
1389
+ */
1390
+
1391
+ static get relationships() {
1392
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1393
+ if (!test) {
1394
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1395
+ }
1396
+ })(this.modelName) : {};
1397
+ const map = new Map();
1398
+ const relationshipsByName = this.relationshipsByName;
1399
+
1400
+ // Loop through each computed property on the class
1401
+ relationshipsByName.forEach(desc => {
1402
+ const {
1403
+ type
1404
+ } = desc;
1405
+ if (!map.has(type)) {
1406
+ map.set(type, []);
1407
+ }
1408
+ map.get(type).push(desc);
1409
+ });
1410
+ return map;
1411
+ }
1412
+
1413
+ /**
1414
+ A hash containing lists of the model's relationships, grouped
1415
+ by the relationship kind. For example, given a model with this
1416
+ definition:
1417
+ ```js [app/models/blog.js]
1418
+ import Model, { belongsTo, hasMany } from '@ember-data/model';
1419
+ export default class BlogModel extends Model {
1420
+ @hasMany('user') users;
1421
+ @belongsTo('user') owner;
1422
+ @hasMany('post') posts;
1423
+ }
1424
+ ```
1425
+ This property would contain the following:
1426
+ ```javascript
1427
+ import Blog from 'app/models/blog';
1428
+ let relationshipNames = Blog.relationshipNames;
1429
+ relationshipNames.hasMany;
1430
+ //=> ['users', 'posts']
1431
+ relationshipNames.belongsTo;
1432
+ //=> ['owner']
1433
+ ```
1434
+ @property relationshipNames
1435
+ @public
1436
+ @readonly
1437
+ */
1438
+ static {
1439
+ decorateMethodV2(this, "relationships", [computeOnce]);
1440
+ }
1441
+ static get relationshipNames() {
1442
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1443
+ if (!test) {
1444
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1445
+ }
1446
+ })(this.modelName) : {};
1447
+ const names = {
1448
+ hasMany: [],
1449
+ belongsTo: []
1450
+ };
1451
+ this.eachComputedProperty((name, meta) => {
1452
+ if (isRelationshipSchema(meta)) {
1453
+ names[meta.kind].push(name);
1454
+ }
1455
+ });
1456
+ return names;
1457
+ }
1458
+
1459
+ /**
1460
+ An array of types directly related to a model. Each type will be
1461
+ included once, regardless of the number of relationships it has with
1462
+ the model.
1463
+ For example, given a model with this definition:
1464
+ ```js [app/models/blog.js]
1465
+ import Model, { belongsTo, hasMany } from '@ember-data/model';
1466
+ export default class BlogModel extends Model {
1467
+ @hasMany('user') users;
1468
+ @belongsTo('user') owner;
1469
+ @hasMany('post') posts;
1470
+ }
1471
+ ```
1472
+ This property would contain the following:
1473
+ ```javascript
1474
+ import Blog from 'app/models/blog';
1475
+ let relatedTypes = Blog.relatedTypes');
1476
+ //=> ['user', 'post']
1477
+ ```
1478
+ @property relatedTypes
1479
+ @public
1480
+ @readonly
1481
+ */
1482
+ static {
1483
+ decorateMethodV2(this, "relationshipNames", [computeOnce]);
1484
+ }
1485
+ static get relatedTypes() {
1486
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1487
+ if (!test) {
1488
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1489
+ }
1490
+ })(this.modelName) : {};
1491
+ const types = [];
1492
+ const rels = this.relationshipsObject;
1493
+ const relationships = Object.keys(rels);
1494
+
1495
+ // create an array of the unique types involved
1496
+ // in relationships
1497
+ for (let i = 0; i < relationships.length; i++) {
1498
+ const name = relationships[i];
1499
+ const meta = rels[name];
1500
+ const modelName = meta.type;
1501
+ if (!types.includes(modelName)) {
1502
+ types.push(modelName);
1503
+ }
1504
+ }
1505
+ return types;
1506
+ }
1507
+
1508
+ /**
1509
+ A map whose keys are the relationships of a model and whose values are
1510
+ relationship descriptors.
1511
+ For example, given a model with this
1512
+ definition:
1513
+ ```js [app/models/blog.js]
1514
+ import Model, { belongsTo, hasMany } from '@ember-data/model';
1515
+ export default class BlogModel extends Model {
1516
+ @hasMany('user') users;
1517
+ @belongsTo('user') owner;
1518
+ @hasMany('post') posts;
1519
+ }
1520
+ ```
1521
+ This property would contain the following:
1522
+ ```javascript
1523
+ import Blog from 'app/models/blog';
1524
+ let relationshipsByName = Blog.relationshipsByName;
1525
+ relationshipsByName.users;
1526
+ //=> { name: 'users', kind: 'hasMany', type: 'user', options: Object }
1527
+ relationshipsByName.owner;
1528
+ //=> { name: 'owner', kind: 'belongsTo', type: 'user', options: Object }
1529
+ ```
1530
+ @property relationshipsByName
1531
+ @public
1532
+ @readonly
1533
+ */
1534
+ static {
1535
+ decorateMethodV2(this, "relatedTypes", [computeOnce]);
1536
+ }
1537
+ static get relationshipsByName() {
1538
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1539
+ if (!test) {
1540
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1541
+ }
1542
+ })(this.modelName) : {};
1543
+ const map = new Map();
1544
+ const rels = this.relationshipsObject;
1545
+ const relationships = Object.keys(rels);
1546
+ for (let i = 0; i < relationships.length; i++) {
1547
+ const name = relationships[i];
1548
+ const value = rels[name];
1549
+ map.set(value.name, value);
1550
+ }
1551
+ return map;
1552
+ }
1553
+ static {
1554
+ decorateMethodV2(this, "relationshipsByName", [computeOnce]);
1555
+ }
1556
+ static get relationshipsObject() {
1557
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1558
+ if (!test) {
1559
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1560
+ }
1561
+ })(this.modelName) : {};
1562
+ const relationships = Object.create(null);
1563
+ const modelName = this.modelName;
1564
+ this.eachComputedProperty((name, meta) => {
1565
+ if (!isRelationshipSchema(meta)) {
1566
+ return;
1567
+ }
1568
+ // TODO deprecate key being here
1569
+ meta.key = name;
1570
+ meta.name = name;
1571
+ relationships[name] = meta;
1572
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1573
+ if (!test) {
1574
+ throw new Error(`Expected options in meta`);
1575
+ }
1576
+ })(meta.options && typeof meta.options === 'object') : {};
1577
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1578
+ if (!test) {
1579
+ throw new Error(`You should not specify both options.as and options.inverse as null on ${modelName}.${meta.name}, as if there is no inverse field there is no abstract type to conform to. You may have intended for this relationship to be polymorphic, or you may have mistakenly set inverse to null.`);
1580
+ }
1581
+ })(!(meta.options.inverse === null && meta.options.as?.length)) : {};
1582
+ });
1583
+ return relationships;
1584
+ }
1585
+
1586
+ /**
1587
+ A map whose keys are the fields of the model and whose values are strings
1588
+ describing the kind of the field. A model's fields are the union of all of its
1589
+ attributes and relationships.
1590
+ For example:
1591
+ ```js [app/models/blog.js]
1592
+ import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
1593
+ export default class BlogModel extends Model {
1594
+ @hasMany('user') users;
1595
+ @belongsTo('user') owner;
1596
+ @hasMany('post') posts;
1597
+ @attr('string') title;
1598
+ }
1599
+ ```
1600
+ ```js
1601
+ import Blog from 'app/models/blog'
1602
+ let fields = Blog.fields;
1603
+ fields.forEach(function(kind, field) {
1604
+ // do thing
1605
+ });
1606
+ // prints:
1607
+ // users, hasMany
1608
+ // owner, belongsTo
1609
+ // posts, hasMany
1610
+ // title, attribute
1611
+ ```
1612
+ @property fields
1613
+ @public
1614
+ @readonly
1615
+ */
1616
+ static {
1617
+ decorateMethodV2(this, "relationshipsObject", [computeOnce]);
1618
+ }
1619
+ static get fields() {
1620
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1621
+ if (!test) {
1622
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1623
+ }
1624
+ })(this.modelName) : {};
1625
+ const map = new Map();
1626
+ this.eachComputedProperty((name, meta) => {
1627
+ if (isRelationshipSchema(meta)) {
1628
+ map.set(name, meta.kind);
1629
+ } else if (isAttributeSchema(meta)) {
1630
+ map.set(name, 'attribute');
1631
+ }
1632
+ });
1633
+ return map;
1634
+ }
1635
+
1636
+ /**
1637
+ Given a callback, iterates over each of the relationships in the model,
1638
+ invoking the callback with the name of each relationship and its relationship
1639
+ descriptor.
1640
+ @public
1641
+ @param {Function} callback the callback to invoke
1642
+ @param {any} binding the value to which the callback's `this` should be bound
1643
+ */
1644
+ static {
1645
+ decorateMethodV2(this, "fields", [computeOnce]);
1646
+ }
1647
+ static eachRelationship(callback, binding) {
1648
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1649
+ if (!test) {
1650
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1651
+ }
1652
+ })(this.modelName) : {};
1653
+ this.relationshipsByName.forEach((relationship, name) => {
1654
+ callback.call(binding, name, relationship);
1655
+ });
1656
+ }
1657
+
1658
+ /**
1659
+ Given a callback, iterates over each of the types related to a model,
1660
+ invoking the callback with the related type's class. Each type will be
1661
+ returned just once, regardless of how many different relationships it has
1662
+ with a model.
1663
+ @public
1664
+ @param {Function} callback the callback to invoke
1665
+ @param {any} binding the value to which the callback's `this` should be bound
1666
+ */
1667
+ static eachRelatedType(callback, binding) {
1668
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1669
+ if (!test) {
1670
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1671
+ }
1672
+ })(this.modelName) : {};
1673
+ const relationshipTypes = this.relatedTypes;
1674
+ for (let i = 0; i < relationshipTypes.length; i++) {
1675
+ const type = relationshipTypes[i];
1676
+ callback.call(binding, type);
1677
+ }
1678
+ }
1679
+
1680
+ /**
1681
+ *
1682
+ * @private
1683
+ * @deprecated
1684
+ */
1685
+ static determineRelationshipType(knownSide, store) {
1686
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1687
+ if (!test) {
1688
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1689
+ }
1690
+ })(this.modelName) : {};
1691
+ const knownKey = knownSide.name;
1692
+ const knownKind = knownSide.kind;
1693
+ const inverse = this.inverseFor(knownKey, store);
1694
+ // let key;
1695
+
1696
+ if (!inverse) {
1697
+ return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
1698
+ }
1699
+
1700
+ // key = inverse.name;
1701
+ const otherKind = inverse.kind;
1702
+ if (otherKind === 'belongsTo') {
1703
+ return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
1704
+ } else {
1705
+ return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
1706
+ }
1707
+ }
1708
+
1709
+ /**
1710
+ A map whose keys are the attributes of the model (properties
1711
+ described by attr) and whose values are the meta object for the
1712
+ property.
1713
+ Example
1714
+ ```js [app/models/person.js]
1715
+ import Model, { attr } from '@ember-data/model';
1716
+ export default class PersonModel extends Model {
1717
+ @attr('string') firstName;
1718
+ @attr('string') lastName;
1719
+ @attr('date') birthday;
1720
+ }
1721
+ ```
1722
+ ```javascript
1723
+ import Person from 'app/models/person'
1724
+ let attributes = Person.attributes
1725
+ attributes.forEach(function(meta, name) {
1726
+ // do thing
1727
+ });
1728
+ // prints:
1729
+ // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
1730
+ // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
1731
+ // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
1732
+ ```
1733
+ @property attributes
1734
+ @public
1735
+ @readonly
1736
+ */
1737
+ static get attributes() {
1738
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1739
+ if (!test) {
1740
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1741
+ }
1742
+ })(this.modelName) : {};
1743
+ const map = new Map();
1744
+ this.eachComputedProperty((name, meta) => {
1745
+ if (isAttributeSchema(meta)) {
1746
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1747
+ if (!test) {
1748
+ throw new Error("You may not set 'id' as an attribute on your model. Please remove any lines that look like: `id: attr('<type>')` from " + this.toString());
1749
+ }
1750
+ })(name !== 'id') : {};
1751
+
1752
+ // TODO deprecate key being here
1753
+ meta.key = name;
1754
+ meta.name = name;
1755
+ map.set(name, meta);
1756
+ }
1757
+ });
1758
+ return map;
1759
+ }
1760
+
1761
+ /**
1762
+ A map whose keys are the attributes of the model (properties
1763
+ described by attr) and whose values are type of transformation
1764
+ applied to each attribute. This map does not include any
1765
+ attributes that do not have an transformation type.
1766
+ Example
1767
+ ```js [app/models/person.js]
1768
+ import Model, { attr } from '@ember-data/model';
1769
+ export default class PersonModel extends Model {
1770
+ @attr firstName;
1771
+ @attr('string') lastName;
1772
+ @attr('date') birthday;
1773
+ }
1774
+ ```
1775
+ ```javascript
1776
+ import Person from 'app/models/person';
1777
+ let transformedAttributes = Person.transformedAttributes
1778
+ transformedAttributes.forEach(function(field, type) {
1779
+ // do thing
1780
+ });
1781
+ // prints:
1782
+ // lastName string
1783
+ // birthday date
1784
+ ```
1785
+ @property transformedAttributes
1786
+ @public
1787
+ @readonly
1788
+ */
1789
+ static {
1790
+ decorateMethodV2(this, "attributes", [computeOnce]);
1791
+ }
1792
+ static get transformedAttributes() {
1793
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1794
+ if (!test) {
1795
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1796
+ }
1797
+ })(this.modelName) : {};
1798
+ const map = new Map();
1799
+ this.eachAttribute((name, meta) => {
1800
+ if (meta.type) {
1801
+ map.set(name, meta.type);
1802
+ }
1803
+ });
1804
+ return map;
1805
+ }
1806
+
1807
+ /**
1808
+ Iterates through the attributes of the model, calling the passed function on each
1809
+ attribute.
1810
+ The callback method you provide should have the following signature (all
1811
+ parameters are optional):
1812
+ ```javascript
1813
+ function(name, meta);
1814
+ ```
1815
+ - `name` the name of the current property in the iteration
1816
+ - `meta` the meta object for the attribute property in the iteration
1817
+ Note that in addition to a callback, you can also pass an optional target
1818
+ object that will be set as `this` on the context.
1819
+ Example
1820
+ ```javascript
1821
+ import Model, { attr } from '@ember-data/model';
1822
+ class PersonModel extends Model {
1823
+ @attr('string') firstName;
1824
+ @attr('string') lastName;
1825
+ @attr('date') birthday;
1826
+ }
1827
+ PersonModel.eachAttribute(function(name, meta) {
1828
+ // do thing
1829
+ });
1830
+ // prints:
1831
+ // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
1832
+ // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
1833
+ // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
1834
+ ```
1835
+ @public
1836
+ @param {Function} callback The callback to execute
1837
+ @param {Object} [binding] the value to which the callback's `this` should be bound
1838
+ */
1839
+ static {
1840
+ decorateMethodV2(this, "transformedAttributes", [computeOnce]);
1841
+ }
1842
+ static eachAttribute(callback, binding) {
1843
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1844
+ if (!test) {
1845
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1846
+ }
1847
+ })(this.modelName) : {};
1848
+ this.attributes.forEach((meta, name) => {
1849
+ callback.call(binding, name, meta);
1850
+ });
1851
+ }
1852
+
1853
+ /**
1854
+ Iterates through the transformedAttributes of the model, calling
1855
+ the passed function on each attribute. Note the callback will not be
1856
+ called for any attributes that do not have an transformation type.
1857
+ The callback method you provide should have the following signature (all
1858
+ parameters are optional):
1859
+ ```javascript
1860
+ function(name, type);
1861
+ ```
1862
+ - `name` the name of the current property in the iteration
1863
+ - `type` a string containing the name of the type of transformed
1864
+ applied to the attribute
1865
+ Note that in addition to a callback, you can also pass an optional target
1866
+ object that will be set as `this` on the context.
1867
+ Example
1868
+ ```javascript
1869
+ import Model, { attr } from '@ember-data/model';
1870
+ let Person = Model.extend({
1871
+ firstName: attr(),
1872
+ lastName: attr('string'),
1873
+ birthday: attr('date')
1874
+ });
1875
+ Person.eachTransformedAttribute(function(name, type) {
1876
+ // do thing
1877
+ });
1878
+ // prints:
1879
+ // lastName string
1880
+ // birthday date
1881
+ ```
1882
+ @public
1883
+ @param {Function} callback The callback to execute
1884
+ @param {Object} [binding] the value to which the callback's `this` should be bound
1885
+ */
1886
+ static eachTransformedAttribute(callback, binding) {
1887
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1888
+ if (!test) {
1889
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1890
+ }
1891
+ })(this.modelName) : {};
1892
+ this.transformedAttributes.forEach((type, name) => {
1893
+ callback.call(binding, name, type);
1894
+ });
1895
+ }
1896
+
1897
+ /**
1898
+ Returns the name of the model class.
1899
+ @public
1900
+ */
1901
+ static toString() {
1902
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1903
+ if (!test) {
1904
+ throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
1905
+ }
1906
+ })(this.modelName) : {};
1907
+ return `model:${this.modelName}`;
1908
+ }
1909
+ }
1910
+
1911
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1912
+ Model.prototype.save = save;
1913
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1914
+ Model.prototype.destroyRecord = destroyRecord;
1915
+ Model.prototype.unloadRecord = unloadRecord;
1916
+ Model.prototype.hasMany = hasMany;
1917
+ Model.prototype.belongsTo = belongsTo;
1918
+ Model.prototype.serialize = serialize;
1919
+ Model.prototype._createSnapshot = createSnapshot;
1920
+ Model.prototype.deleteRecord = deleteRecord;
1921
+ Model.prototype.changedAttributes = changedAttributes;
1922
+ Model.prototype.rollbackAttributes = rollbackAttributes;
1923
+ Model.prototype.reload = reload;
1924
+ defineSignal(Model.prototype, 'isReloading', false);
1925
+
1926
+ // this is required to prevent `init` from passing
1927
+ // the values initialized during create to `setUnknownProperty`
1928
+ Model.prototype._createProps = null;
1929
+ Model.prototype._secretInit = null;
1930
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1931
+ const lookupDescriptor = function lookupDescriptor(obj, keyName) {
1932
+ let current = obj;
1933
+ do {
1934
+ const descriptor = Object.getOwnPropertyDescriptor(current, keyName);
1935
+ if (descriptor !== undefined) {
1936
+ return descriptor;
1937
+ }
1938
+ current = Object.getPrototypeOf(current);
1939
+ } while (current !== null);
1940
+ return null;
1941
+ };
1942
+
1943
+ // eslint-disable-next-line @typescript-eslint/unbound-method
1944
+ const init = Model.prototype.init;
1945
+ Model.prototype.init = function (createArgs) {
1946
+ init.call(this, createArgs);
1947
+ const ourDescriptor = lookupDescriptor(Model.prototype, 'currentState');
1948
+ const theirDescriptor = lookupDescriptor(this, 'currentState');
1949
+ if (!ourDescriptor || !theirDescriptor) {
1950
+ throw new Error(`Unable to determine if 'currentState' is a reserved property name on instances of classes extending Model. Please ensure that 'currentState' is not defined as a property on ${this.constructor.toString()}`);
1951
+ }
1952
+ const realState = this.___recordState;
1953
+ if (ourDescriptor.get !== theirDescriptor.get || realState !== this.currentState) {
1954
+ throw new Error(`'currentState' is a reserved property name on instances of classes extending Model. Please choose a different property name for ${this.constructor.toString()}`);
1955
+ }
1956
+ const ID_DESCRIPTOR = lookupDescriptor(Model.prototype, 'id');
1957
+ const idDesc = lookupDescriptor(this, 'id');
1958
+ if (!ID_DESCRIPTOR || !idDesc) {
1959
+ throw new Error(`Unable to determine if 'id' is a reserved property name on instances of classes extending Model. Please ensure that 'id' is not defined as a property on ${this.constructor.toString()}`);
1960
+ }
1961
+ if (idDesc.get !== ID_DESCRIPTOR.get) {
1962
+ throw new Error(`You may not set 'id' as an attribute on your model. Please remove any lines that look like: \`id: attr('<type>')\` from ${this.constructor.toString()}`);
1963
+ }
1964
+ };
1965
+ delete Model.reopen;
1966
+ delete Model.reopenClass;
1967
+ }
1968
+ function isRelationshipSchema(meta) {
1969
+ const hasKind = typeof meta === 'object' && meta !== null && 'kind' in meta && 'options' in meta;
1970
+ return hasKind && (meta.kind === 'hasMany' || meta.kind === 'belongsTo');
1971
+ }
1972
+ function isAttributeSchema(meta) {
1973
+ return typeof meta === 'object' && meta !== null && 'kind' in meta && meta.kind === 'attribute';
1974
+ }
1975
+
1976
+ /*
1977
+ In case someone defined a relationship to a mixin, for example:
1978
+ ```ts
1979
+ class CommentModel extends Model {
1980
+ @belongsTo('commentable', { polymorphic: true }) owner;
1981
+ }
1982
+
1983
+ let Commentable = Mixin.create({
1984
+ @hasMany('comment') comments;
1985
+ });
1986
+ ```
1987
+ we want to look up a Commentable class which has all the necessary
1988
+ relationship meta data. Thus, we look up the mixin and create a mock
1989
+ Model, so we can access the relationship CPs of the mixin (`comments`)
1990
+ in this case
1991
+ */
1992
+ function modelForMixin(store, normalizedModelName) {
1993
+ const owner = getOwner(store);
1994
+ const MaybeMixin = owner.factoryFor(`mixin:${normalizedModelName}`);
1995
+ const mixin = MaybeMixin && MaybeMixin.class;
1996
+ if (mixin) {
1997
+ const ModelForMixin = Model.extend(mixin);
1998
+ ModelForMixin.__isMixin = true;
1999
+ ModelForMixin.__mixin = mixin;
2000
+ //Cache the class as a model
2001
+ owner.register(`model:${normalizedModelName}`, ModelForMixin);
2002
+ }
2003
+ return owner.factoryFor(`model:${normalizedModelName}`);
2004
+ }
2005
+ class ModelSchemaProvider {
2006
+ constructor(store) {
2007
+ this.store = store;
2008
+ this._schemas = new Map();
2009
+ this._typeMisses = new Set();
2010
+ }
2011
+ resourceTypes() {
2012
+ return Array.from(this._schemas.keys());
2013
+ }
2014
+ hasTrait(type) {
2015
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2016
+ {
2017
+ throw new Error(`hasTrait is not available with @ember-data/model's SchemaService`);
2018
+ }
2019
+ })() : {};
2020
+ return false;
2021
+ }
2022
+ resourceHasTrait(resource, trait) {
2023
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2024
+ {
2025
+ throw new Error(`resourceHasTrait is not available with @ember-data/model's SchemaService`);
2026
+ }
2027
+ })() : {};
2028
+ return false;
2029
+ }
2030
+ transformation(field) {
2031
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2032
+ {
2033
+ throw new Error(`transformation is not available with @ember-data/model's SchemaService`);
2034
+ }
2035
+ })() : {};
2036
+ }
2037
+ derivation(field) {
2038
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2039
+ {
2040
+ throw new Error(`derivation is not available with @ember-data/model's SchemaService`);
2041
+ }
2042
+ })() : {};
2043
+ }
2044
+ hashFn(field) {
2045
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2046
+ {
2047
+ throw new Error(`hashFn is not available with @ember-data/model's SchemaService`);
2048
+ }
2049
+ })() : {};
2050
+ }
2051
+ resource(resource) {
2052
+ const type = normalizeModelName(resource.type);
2053
+ if (!this._schemas.has(type)) {
2054
+ this._loadModelSchema(type);
2055
+ }
2056
+ return this._schemas.get(type).schema;
2057
+ }
2058
+ registerResources(schemas) {
2059
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2060
+ {
2061
+ throw new Error(`registerResources is not available with @ember-data/model's SchemaService`);
2062
+ }
2063
+ })() : {};
2064
+ }
2065
+ registerResource(schema) {
2066
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2067
+ {
2068
+ throw new Error(`registerResource is not available with @ember-data/model's SchemaService`);
2069
+ }
2070
+ })() : {};
2071
+ }
2072
+ registerTransformation(transform) {
2073
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2074
+ {
2075
+ throw new Error(`registerTransformation is not available with @ember-data/model's SchemaService`);
2076
+ }
2077
+ })() : {};
2078
+ }
2079
+ registerDerivation(derivation) {
2080
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2081
+ {
2082
+ throw new Error(`registerDerivation is not available with @ember-data/model's SchemaService`);
2083
+ }
2084
+ })() : {};
2085
+ }
2086
+ registerHashFn(hashFn) {
2087
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2088
+ {
2089
+ throw new Error(`registerHashFn is not available with @ember-data/model's SchemaService`);
2090
+ }
2091
+ })() : {};
2092
+ }
2093
+ _loadModelSchema(type) {
2094
+ const modelClass = this.store.modelFor(type);
2095
+ const attributeMap = modelClass.attributes;
2096
+ const attributes = Object.create(null);
2097
+ attributeMap.forEach((meta, name) => attributes[name] = meta);
2098
+ const relationships = modelClass.relationshipsObject || null;
2099
+ const fields = new Map();
2100
+ for (const attr of Object.values(attributes)) {
2101
+ fields.set(attr.name, attr);
2102
+ }
2103
+ for (const rel of Object.values(relationships)) {
2104
+ fields.set(rel.name, rel);
2105
+ }
2106
+ const schema = {
2107
+ legacy: true,
2108
+ identity: {
2109
+ name: 'id',
2110
+ kind: '@id'
2111
+ },
2112
+ type,
2113
+ fields: Array.from(fields.values())
2114
+ };
2115
+ const internalSchema = {
2116
+ schema,
2117
+ attributes,
2118
+ relationships,
2119
+ fields
2120
+ };
2121
+ this._schemas.set(type, internalSchema);
2122
+ return internalSchema;
2123
+ }
2124
+ fields(resource) {
2125
+ const type = normalizeModelName(resource.type);
2126
+ if (!this._schemas.has(type)) {
2127
+ this._loadModelSchema(type);
2128
+ }
2129
+ return this._schemas.get(type).fields;
2130
+ }
2131
+ hasResource(resource) {
2132
+ const type = normalizeModelName(resource.type);
2133
+ if (this._schemas.has(type)) {
2134
+ return true;
2135
+ }
2136
+ if (this._typeMisses.has(type)) {
2137
+ return false;
2138
+ }
2139
+ const factory = getModelFactory(this.store, type);
2140
+ const exists = factory !== null;
2141
+ if (!exists) {
2142
+ this._typeMisses.add(type);
2143
+ return false;
2144
+ }
2145
+ return true;
2146
+ }
2147
+ }
2148
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.ENABLE_LEGACY_SCHEMA_SERVICE)) {
2149
+ ModelSchemaProvider.prototype.doesTypeExist = function (type) {
2150
+ deprecate(`Use \`schema.hasResource({ type })\` instead of \`schema.doesTypeExist(type)\``, false, {
2151
+ id: 'ember-data:schema-service-updates',
2152
+ until: '6.0',
2153
+ for: 'ember-data',
2154
+ since: {
2155
+ available: '4.13',
2156
+ enabled: '5.4'
2157
+ }
2158
+ });
2159
+ return this.hasResource({
2160
+ type
2161
+ });
2162
+ };
2163
+ ModelSchemaProvider.prototype.attributesDefinitionFor = function (resource) {
2164
+ deprecate(`Use \`schema.fields({ type })\` instead of \`schema.attributesDefinitionFor({ type })\``, false, {
2165
+ id: 'ember-data:schema-service-updates',
2166
+ until: '6.0',
2167
+ for: 'ember-data',
2168
+ since: {
2169
+ available: '4.13',
2170
+ enabled: '5.4'
2171
+ }
2172
+ });
2173
+ const type = normalizeModelName(resource.type);
2174
+ if (!this._schemas.has(type)) {
2175
+ this._loadModelSchema(type);
2176
+ }
2177
+ return this._schemas.get(type).attributes;
2178
+ };
2179
+ ModelSchemaProvider.prototype.relationshipsDefinitionFor = function (resource) {
2180
+ deprecate(`Use \`schema.fields({ type })\` instead of \`schema.relationshipsDefinitionFor({ type })\``, false, {
2181
+ id: 'ember-data:schema-service-updates',
2182
+ until: '6.0',
2183
+ for: 'ember-data',
2184
+ since: {
2185
+ available: '4.13',
2186
+ enabled: '5.4'
2187
+ }
2188
+ });
2189
+ const type = normalizeModelName(resource.type);
2190
+ if (!this._schemas.has(type)) {
2191
+ this._loadModelSchema(type);
2192
+ }
2193
+ return this._schemas.get(type).relationships;
2194
+ };
2195
+ }
2196
+ function buildSchema(store) {
2197
+ return new ModelSchemaProvider(store);
2198
+ }
2199
+ function getModelFactory(store, type) {
2200
+ if (!store._modelFactoryCache) {
2201
+ store._modelFactoryCache = Object.create(null);
2202
+ }
2203
+ const cache = store._modelFactoryCache;
2204
+ let factory = cache[type];
2205
+ if (!factory) {
2206
+ const owner = getOwner(store);
2207
+ factory = owner.factoryFor(`model:${type}`);
2208
+ if (!factory) {
2209
+ //Support looking up mixins as base types for polymorphic relationships
2210
+ factory = modelForMixin(store, type);
2211
+ }
2212
+ if (!factory) {
2213
+ // we don't cache misses in case someone wants to register a missing model
2214
+ return null;
2215
+ }
2216
+ const klass = factory.class;
2217
+ if (klass.isModel) {
2218
+ const hasOwnModelNameSet = klass.modelName && Object.prototype.hasOwnProperty.call(klass, 'modelName');
2219
+ if (!hasOwnModelNameSet) {
2220
+ Object.defineProperty(klass, 'modelName', {
2221
+ value: type
2222
+ });
2223
+ }
2224
+ }
2225
+ cache[type] = factory;
2226
+ }
2227
+ return factory;
2228
+ }
2229
+ export { Model as M, RecordState as R, save as a, buildSchema as b, reload as c, destroyRecord as d, deleteRecord as e, changedAttributes as f, getModelFactory as g, hasMany as h, belongsTo as i, createSnapshot as j, isElementDescriptor as k, ModelSchemaProvider as l, normalizeModelName as n, rollbackAttributes as r, serialize as s, unloadRecord as u };