@warp-drive/legacy 5.8.0-alpha.9 → 5.8.0-beta.1

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