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