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

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