@warp-drive/legacy 5.8.0-alpha.4 → 5.8.0-alpha.40

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