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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +14 -27
  2. package/declarations/adapter/error.d.ts +7 -7
  3. package/declarations/adapter/json-api.d.ts +2 -2
  4. package/declarations/adapter/rest.d.ts +21 -104
  5. package/declarations/adapter.d.ts +2 -2
  6. package/declarations/compat/builders/find-all.d.ts +6 -6
  7. package/declarations/compat/builders/find-record.d.ts +8 -8
  8. package/declarations/compat/builders/query.d.ts +12 -12
  9. package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts +16 -24
  10. package/declarations/compat/utils.d.ts +13 -13
  11. package/declarations/compat.d.ts +31 -5
  12. package/declarations/index.d.ts +25 -8
  13. package/declarations/model/-private/legacy-relationships-support.d.ts +2 -2
  14. package/declarations/model/-private/model.d.ts +10 -51
  15. package/declarations/model/-private/promise-many-array.d.ts +0 -18
  16. package/declarations/model/-private/references/belongs-to.d.ts +18 -28
  17. package/declarations/model/-private/references/has-many.d.ts +13 -15
  18. package/declarations/model/migration-support.d.ts +42 -19
  19. package/declarations/model-fragments/extensions/fragment-array.d.ts +16 -0
  20. package/declarations/model-fragments/extensions/fragment.d.ts +15 -0
  21. package/declarations/model-fragments/hooks/model-for.d.ts +20 -0
  22. package/declarations/model-fragments/index.d.ts +5 -0
  23. package/declarations/model-fragments/instance-initializers/fragment-extensions.d.ts +9 -0
  24. package/declarations/model-fragments/utilities/with-array-defaults.d.ts +15 -0
  25. package/declarations/model-fragments/utilities/with-fragment-array-defaults.d.ts +20 -0
  26. package/declarations/model-fragments/utilities/with-fragment-defaults.d.ts +19 -0
  27. package/declarations/model-fragments/utilities/with-legacy.d.ts +3 -0
  28. package/declarations/model-fragments.d.ts +9 -0
  29. package/declarations/model.d.ts +2 -2
  30. package/declarations/serializer/-private/embedded-records-mixin.d.ts +1 -1
  31. package/declarations/serializer/json-api.d.ts +7 -6
  32. package/declarations/serializer/json.d.ts +3 -3
  33. package/declarations/serializer.d.ts +5 -6
  34. package/dist/{-private-B1pSSN52.js → -private-BG3bMiKp.js} +2 -1
  35. package/dist/adapter/-private.js +1 -1
  36. package/dist/adapter/error.js +9 -9
  37. package/dist/adapter/json-api.js +1 -1
  38. package/dist/adapter/rest.js +33 -117
  39. package/dist/adapter.js +2 -2
  40. package/dist/compat/-private.js +1 -1
  41. package/dist/compat/builders.js +26 -26
  42. package/dist/compat/utils.js +13 -14
  43. package/dist/compat.js +28 -8
  44. package/dist/{errors-COviC59J.js → errors-Cz5KrzBk.js} +113 -120
  45. package/dist/{hooks-Bp8SIQBU.js → hooks-D6diaM34.js} +1 -1
  46. package/dist/index.js +25 -8
  47. package/dist/{json-ksWOHRfq.js → json-ChdEfB0X.js} +12 -27
  48. package/dist/model/-private.js +1 -1
  49. package/dist/model/migration-support.js +55 -25
  50. package/dist/model-for-CqXsIKws.js +221 -0
  51. package/dist/model-fragments.js +76 -0
  52. package/dist/model.js +3 -3
  53. package/dist/{schema-provider-JlCneqZH.js → schema-provider-DJCV_6AF.js} +44 -87
  54. package/dist/{serialize-into-hash-BnYvPex3.js → serialize-into-hash-DPZYoF-i.js} +1 -1
  55. package/dist/serializer/json-api.js +18 -45
  56. package/dist/serializer/json.js +1 -1
  57. package/dist/serializer/rest.js +10 -10
  58. package/dist/serializer.js +5 -6
  59. package/dist/store.js +2 -1
  60. package/dist/unpkg/dev/-private-DtjBbEgy.js +1206 -0
  61. package/dist/unpkg/dev/adapter/-private.js +1 -0
  62. package/dist/unpkg/dev/adapter/error.js +335 -0
  63. package/dist/unpkg/dev/adapter/json-api.js +271 -0
  64. package/dist/unpkg/dev/adapter/rest.js +1171 -0
  65. package/dist/unpkg/dev/adapter.js +1252 -0
  66. package/dist/unpkg/dev/compat/-private.js +1 -0
  67. package/dist/unpkg/dev/compat/builders.js +275 -0
  68. package/dist/unpkg/dev/compat/extensions.js +242 -0
  69. package/dist/unpkg/dev/compat/utils.js +223 -0
  70. package/dist/unpkg/dev/compat.js +1147 -0
  71. package/dist/unpkg/dev/errors-DmGGJr3T.js +2562 -0
  72. package/dist/unpkg/dev/hooks-CkYiE6Ud.js +73 -0
  73. package/dist/unpkg/dev/index.js +197 -0
  74. package/dist/unpkg/dev/json-Cu1LNgmQ.js +1256 -0
  75. package/dist/unpkg/dev/model/-private.js +1 -0
  76. package/dist/unpkg/dev/model/migration-support.js +553 -0
  77. package/dist/unpkg/dev/model-for-CqXsIKws.js +221 -0
  78. package/dist/unpkg/dev/model-fragments.js +76 -0
  79. package/dist/unpkg/dev/model.js +678 -0
  80. package/dist/unpkg/dev/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  81. package/dist/unpkg/dev/schema-provider-DDVYxmUV.js +2186 -0
  82. package/dist/unpkg/dev/serialize-into-hash-B2xDbuo5.js +259 -0
  83. package/dist/unpkg/dev/serializer/json-api.js +649 -0
  84. package/dist/unpkg/dev/serializer/json.js +4 -0
  85. package/dist/unpkg/dev/serializer/rest.js +1242 -0
  86. package/dist/unpkg/dev/serializer/transform.js +278 -0
  87. package/dist/unpkg/dev/serializer.js +248 -0
  88. package/dist/unpkg/dev/store.js +637 -0
  89. package/dist/unpkg/dev/util-DvanW33H.js +20 -0
  90. package/dist/unpkg/dev/utils-BhvS1iTS.js +8 -0
  91. package/dist/unpkg/dev-deprecated/-private-DtjBbEgy.js +1206 -0
  92. package/dist/unpkg/dev-deprecated/adapter/-private.js +1 -0
  93. package/dist/unpkg/dev-deprecated/adapter/error.js +335 -0
  94. package/dist/unpkg/dev-deprecated/adapter/json-api.js +271 -0
  95. package/dist/unpkg/dev-deprecated/adapter/rest.js +1171 -0
  96. package/dist/unpkg/dev-deprecated/adapter.js +1252 -0
  97. package/dist/unpkg/dev-deprecated/compat/-private.js +1 -0
  98. package/dist/unpkg/dev-deprecated/compat/builders.js +275 -0
  99. package/dist/unpkg/dev-deprecated/compat/extensions.js +242 -0
  100. package/dist/unpkg/dev-deprecated/compat/utils.js +223 -0
  101. package/dist/unpkg/dev-deprecated/compat.js +1147 -0
  102. package/dist/unpkg/dev-deprecated/errors-Spt6ubMd.js +2565 -0
  103. package/dist/unpkg/dev-deprecated/hooks-DOXegvhL.js +73 -0
  104. package/dist/unpkg/dev-deprecated/index.js +196 -0
  105. package/dist/unpkg/dev-deprecated/json-Cu1LNgmQ.js +1256 -0
  106. package/dist/unpkg/dev-deprecated/model/-private.js +1 -0
  107. package/dist/unpkg/dev-deprecated/model/migration-support.js +570 -0
  108. package/dist/unpkg/dev-deprecated/model-for-CqXsIKws.js +221 -0
  109. package/dist/unpkg/dev-deprecated/model-fragments.js +76 -0
  110. package/dist/unpkg/dev-deprecated/model.js +682 -0
  111. package/dist/unpkg/dev-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  112. package/dist/unpkg/dev-deprecated/schema-provider-BP6_8N-V.js +2211 -0
  113. package/dist/unpkg/dev-deprecated/serialize-into-hash-B2xDbuo5.js +259 -0
  114. package/dist/unpkg/dev-deprecated/serializer/json-api.js +649 -0
  115. package/dist/unpkg/dev-deprecated/serializer/json.js +4 -0
  116. package/dist/unpkg/dev-deprecated/serializer/rest.js +1242 -0
  117. package/dist/unpkg/dev-deprecated/serializer/transform.js +278 -0
  118. package/dist/unpkg/dev-deprecated/serializer.js +248 -0
  119. package/dist/unpkg/dev-deprecated/store.js +637 -0
  120. package/dist/unpkg/dev-deprecated/util-CWr5WQOT.js +24 -0
  121. package/dist/unpkg/dev-deprecated/utils-C9PJehtL.js +12 -0
  122. package/dist/unpkg/prod/-private-BdyZaGEh.js +971 -0
  123. package/dist/unpkg/prod/adapter/-private.js +1 -0
  124. package/dist/unpkg/prod/adapter/error.js +330 -0
  125. package/dist/unpkg/prod/adapter/json-api.js +266 -0
  126. package/dist/unpkg/prod/adapter/rest.js +1134 -0
  127. package/dist/unpkg/prod/adapter.js +1219 -0
  128. package/dist/unpkg/prod/compat/-private.js +1 -0
  129. package/dist/unpkg/prod/compat/builders.js +210 -0
  130. package/dist/unpkg/prod/compat/extensions.js +232 -0
  131. package/dist/unpkg/prod/compat/utils.js +218 -0
  132. package/dist/unpkg/prod/compat.js +727 -0
  133. package/dist/unpkg/prod/errors-BGVFCBmi.js +2314 -0
  134. package/dist/unpkg/prod/hooks-BztVA_x0.js +41 -0
  135. package/dist/unpkg/prod/index.js +151 -0
  136. package/dist/unpkg/prod/json-BWrZ5546.js +1243 -0
  137. package/dist/unpkg/prod/model/-private.js +1 -0
  138. package/dist/unpkg/prod/model/migration-support.js +546 -0
  139. package/dist/unpkg/prod/model-for-CqXsIKws.js +221 -0
  140. package/dist/unpkg/prod/model-fragments.js +76 -0
  141. package/dist/unpkg/prod/model.js +593 -0
  142. package/dist/unpkg/prod/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  143. package/dist/unpkg/prod/schema-provider-DJtD_8jZ.js +1861 -0
  144. package/dist/unpkg/prod/serialize-into-hash-DGlzQteF.js +215 -0
  145. package/dist/unpkg/prod/serializer/json-api.js +592 -0
  146. package/dist/unpkg/prod/serializer/json.js +4 -0
  147. package/dist/unpkg/prod/serializer/rest.js +1210 -0
  148. package/dist/unpkg/prod/serializer/transform.js +278 -0
  149. package/dist/unpkg/prod/serializer.js +248 -0
  150. package/dist/unpkg/prod/store.js +505 -0
  151. package/dist/unpkg/prod/util-DvanW33H.js +20 -0
  152. package/dist/unpkg/prod/utils-BhvS1iTS.js +8 -0
  153. package/dist/unpkg/prod-deprecated/-private-BdyZaGEh.js +971 -0
  154. package/dist/unpkg/prod-deprecated/adapter/-private.js +1 -0
  155. package/dist/unpkg/prod-deprecated/adapter/error.js +330 -0
  156. package/dist/unpkg/prod-deprecated/adapter/json-api.js +266 -0
  157. package/dist/unpkg/prod-deprecated/adapter/rest.js +1134 -0
  158. package/dist/unpkg/prod-deprecated/adapter.js +1219 -0
  159. package/dist/unpkg/prod-deprecated/compat/-private.js +1 -0
  160. package/dist/unpkg/prod-deprecated/compat/builders.js +210 -0
  161. package/dist/unpkg/prod-deprecated/compat/extensions.js +232 -0
  162. package/dist/unpkg/prod-deprecated/compat/utils.js +218 -0
  163. package/dist/unpkg/prod-deprecated/compat.js +727 -0
  164. package/dist/unpkg/prod-deprecated/errors-CdDaK81x.js +2317 -0
  165. package/dist/unpkg/prod-deprecated/hooks-yId87yyG.js +41 -0
  166. package/dist/unpkg/prod-deprecated/index.js +150 -0
  167. package/dist/unpkg/prod-deprecated/json-BWrZ5546.js +1243 -0
  168. package/dist/unpkg/prod-deprecated/model/-private.js +1 -0
  169. package/dist/unpkg/prod-deprecated/model/migration-support.js +563 -0
  170. package/dist/unpkg/prod-deprecated/model-for-CqXsIKws.js +221 -0
  171. package/dist/unpkg/prod-deprecated/model-fragments.js +76 -0
  172. package/dist/unpkg/prod-deprecated/model.js +596 -0
  173. package/dist/unpkg/prod-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  174. package/dist/unpkg/prod-deprecated/schema-provider-CjX55uSY.js +1904 -0
  175. package/dist/unpkg/prod-deprecated/serialize-into-hash-DGlzQteF.js +215 -0
  176. package/dist/unpkg/prod-deprecated/serializer/json-api.js +592 -0
  177. package/dist/unpkg/prod-deprecated/serializer/json.js +4 -0
  178. package/dist/unpkg/prod-deprecated/serializer/rest.js +1210 -0
  179. package/dist/unpkg/prod-deprecated/serializer/transform.js +278 -0
  180. package/dist/unpkg/prod-deprecated/serializer.js +248 -0
  181. package/dist/unpkg/prod-deprecated/store.js +505 -0
  182. package/dist/unpkg/prod-deprecated/util-B6cn-i93.js +23 -0
  183. package/dist/unpkg/prod-deprecated/utils-BUWwQwCh.js +11 -0
  184. package/logos/README.md +2 -2
  185. package/logos/logo-yellow-slab.svg +1 -0
  186. package/logos/word-mark-black.svg +1 -0
  187. package/logos/word-mark-white.svg +1 -0
  188. package/package.json +14 -6
  189. package/logos/NCC-1701-a-blue.svg +0 -4
  190. package/logos/NCC-1701-a-gold.svg +0 -4
  191. package/logos/NCC-1701-a-gold_100.svg +0 -1
  192. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  193. package/logos/NCC-1701-a.svg +0 -4
  194. package/logos/docs-badge.svg +0 -2
  195. package/logos/ember-data-logo-dark.svg +0 -12
  196. package/logos/ember-data-logo-light.svg +0 -12
  197. package/logos/social1.png +0 -0
  198. package/logos/social2.png +0 -0
  199. package/logos/warp-drive-logo-dark.svg +0 -4
  200. package/logos/warp-drive-logo-gold.svg +0 -4
@@ -0,0 +1,2562 @@
1
+ import { Context } from '@warp-drive/core/reactive/-private';
2
+ import { memoized, defineSignal, defineNonEnumerableSignal, notifyInternalSignal } from '@warp-drive/core/signals/-leaked';
3
+ import { assertPrivateStore, isResourceKey, recordIdentifierFor, isPrivateStore, storeFor, fastPush, createLegacyManyArray } from '@warp-drive/core/store/-private';
4
+ import { getOrSetGlobal } from '@warp-drive/core/types/-private';
5
+ import { EnableHydration } from '@warp-drive/core/types/request';
6
+ import { u as upgradeStore } from "./-private-DtjBbEgy.js";
7
+ import { computed, get } from '@ember/object';
8
+ import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
9
+ import ObjectProxy from '@ember/object/proxy';
10
+ import { d as decorateMethodV2, a as decorateFieldV2, i as initializeDeferredDecorator } from "./runtime-BPCpkOf1-BKOwiRJp.js";
11
+ import { A } from '@ember/array';
12
+ import ArrayProxy from '@ember/array/proxy';
13
+ import { mapBy, not } from '@ember/object/computed';
14
+ const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);
15
+ const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
16
+
17
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-extraneous-class
18
+
19
+ const Extended = PromiseObject;
20
+
21
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
22
+
23
+ /**
24
+ A PromiseBelongsTo is a PromiseObject that also proxies certain method calls
25
+ to the underlying belongsTo model.
26
+ Right now we proxy:
27
+ * `reload()`
28
+ @class PromiseBelongsTo
29
+ @private
30
+ */
31
+ class PromiseBelongsTo extends Extended {
32
+ get id() {
33
+ const {
34
+ key,
35
+ legacySupport
36
+ } = this._belongsToState;
37
+ const ref = legacySupport.referenceFor('belongsTo', key);
38
+ return ref.id();
39
+ }
40
+
41
+ // we don't proxy meta because we would need to proxy it to the relationship state container
42
+ // however, meta on relationships does not trigger change notifications.
43
+ // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()`
44
+ static {
45
+ decorateMethodV2(this.prototype, "id", [memoized]);
46
+ }
47
+ get meta() {
48
+ // eslint-disable-next-line no-constant-condition
49
+ {
50
+ (test => {
51
+ {
52
+ throw new Error('You attempted to access meta on the promise for the async belongsTo relationship ' + `${this._belongsToState.modelName}:${this._belongsToState.key}'.` + '\nUse `record.belongsTo(relationshipName).meta()` instead.');
53
+ }
54
+ })();
55
+ }
56
+ return;
57
+ }
58
+ static {
59
+ decorateMethodV2(this.prototype, "meta", [computed()]);
60
+ }
61
+ async reload(options) {
62
+ (test => {
63
+ if (!test) {
64
+ throw new Error('You are trying to reload an async belongsTo before it has been created');
65
+ }
66
+ })(this.content !== undefined);
67
+ const {
68
+ key,
69
+ legacySupport
70
+ } = this._belongsToState;
71
+ await legacySupport.reloadBelongsTo(key, options);
72
+ return this;
73
+ }
74
+ }
75
+ PromiseBelongsTo.prototype[LegacyPromiseProxy] = true;
76
+
77
+ /**
78
+ This class is returned as the result of accessing an async hasMany relationship
79
+ on an instance of a Model extending from `@ember-data/model`.
80
+
81
+ A PromiseManyArray is an iterable proxy that allows templates to consume related
82
+ ManyArrays and update once their contents are no longer pending.
83
+
84
+ In your JS code you should resolve the promise first.
85
+
86
+ ```js
87
+ const comments = await post.comments;
88
+ ```
89
+
90
+ @public
91
+ */
92
+ class PromiseManyArray {
93
+ constructor(promise, content) {
94
+ this._update(promise, content);
95
+ this.isDestroyed = false;
96
+ this[LegacyPromiseProxy] = true;
97
+ }
98
+
99
+ /**
100
+ * Retrieve the length of the content
101
+ * @public
102
+ */
103
+ get length() {
104
+ // shouldn't be needed, but ends up being needed
105
+ // for computed chains even in 4.x
106
+
107
+ return this.content ? this.content.length : 0;
108
+ }
109
+
110
+ // this will error if someone tries to call
111
+ // A(identifierArray) since it is not configurable
112
+ // which is preferrable to the `meta` override we used
113
+ // before which required importing all of Ember
114
+ static {
115
+ decorateMethodV2(this.prototype, "length", [memoized]);
116
+ }
117
+ get '[]'() {
118
+ // ember-source < 3.23 (e.g. 3.20 lts)
119
+ // requires that the tag `'[]'` be notified
120
+ // on the ArrayProxy in order for `{{#each}}`
121
+ // to recompute. We entangle content.
122
+ return this.content?.length && this.content;
123
+ }
124
+
125
+ /**
126
+ * Iterate the proxied content. Called by the glimmer iterator in #each
127
+ * We do not guarantee that forEach will always be available. This
128
+ * may eventually be made to use Symbol.Iterator once glimmer supports it.
129
+ *
130
+ * @param cb
131
+ * @return
132
+ * @private
133
+ */
134
+ static {
135
+ decorateMethodV2(this.prototype, '[]', [memoized]);
136
+ }
137
+ forEach(cb) {
138
+ if (this.content && this.length) {
139
+ this.content.forEach(cb);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Reload the relationship
145
+ * @public
146
+ */
147
+ reload(options) {
148
+ (test => {
149
+ if (!test) {
150
+ throw new Error('You are trying to reload an async manyArray before it has been created');
151
+ }
152
+ })(this.content);
153
+ void this.content.reload(options);
154
+ return this;
155
+ }
156
+
157
+ //---- Properties/Methods from the PromiseProxyMixin that we will keep as our API
158
+
159
+ /**
160
+ * Whether the loading promise is still pending
161
+ *
162
+ * @public
163
+ */
164
+
165
+ /**
166
+ * Whether the loading promise rejected
167
+ *
168
+ * @public
169
+ */
170
+
171
+ /**
172
+ * Whether the loading promise succeeded
173
+ *
174
+ * @public
175
+ */
176
+
177
+ /**
178
+ * Whether the loading promise completed (resolved or rejected)
179
+ *
180
+ * @public
181
+ */
182
+
183
+ /**
184
+ * chain this promise
185
+ *
186
+ * @public
187
+ */
188
+ then(success, rejected) {
189
+ return this.promise.then(success, rejected);
190
+ }
191
+
192
+ /**
193
+ * catch errors thrown by this promise
194
+ * @public
195
+ */
196
+ catch(cb) {
197
+ return this.promise.catch(cb);
198
+ }
199
+
200
+ /**
201
+ * run cleanup after this promise completes
202
+ *
203
+ * @public
204
+ */
205
+ finally(cb) {
206
+ return this.promise.finally(cb);
207
+ }
208
+
209
+ //---- Methods on EmberObject that we should keep
210
+
211
+ destroy() {
212
+ this.isDestroyed = true;
213
+ this.content = null;
214
+ this.promise = null;
215
+ }
216
+
217
+ //---- Methods/Properties on ManyArray that we own and proxy to
218
+
219
+ /**
220
+ * Retrieve the links for this relationship
221
+ * @public
222
+ */
223
+ get links() {
224
+ return this.content ? this.content.links : undefined;
225
+ }
226
+
227
+ /**
228
+ * Retrieve the meta for this relationship
229
+ * @public
230
+ */
231
+ static {
232
+ decorateMethodV2(this.prototype, "links", [memoized]);
233
+ }
234
+ get meta() {
235
+ return this.content ? this.content.meta : undefined;
236
+ }
237
+
238
+ //---- Our own stuff
239
+
240
+ /** @internal */
241
+ static {
242
+ decorateMethodV2(this.prototype, "meta", [memoized]);
243
+ }
244
+ _update(promise, content) {
245
+ if (content !== undefined) {
246
+ this.content = content;
247
+ }
248
+ this.promise = tapPromise(this, promise);
249
+ }
250
+ static create({
251
+ promise,
252
+ content
253
+ }) {
254
+ return new this(promise, content);
255
+ }
256
+ }
257
+ defineSignal(PromiseManyArray.prototype, 'content', null);
258
+ defineSignal(PromiseManyArray.prototype, 'isPending', false);
259
+ defineSignal(PromiseManyArray.prototype, 'isRejected', false);
260
+ defineSignal(PromiseManyArray.prototype, 'isFulfilled', false);
261
+ defineSignal(PromiseManyArray.prototype, 'isSettled', false);
262
+ function tapPromise(proxy, promise) {
263
+ proxy.isPending = true;
264
+ proxy.isSettled = false;
265
+ proxy.isFulfilled = false;
266
+ proxy.isRejected = false;
267
+ return Promise.resolve(promise).then(content => {
268
+ proxy.isPending = false;
269
+ proxy.isFulfilled = true;
270
+ proxy.isSettled = true;
271
+ proxy.content = content;
272
+ return content;
273
+ }, error => {
274
+ proxy.isPending = false;
275
+ proxy.isFulfilled = false;
276
+ proxy.isRejected = true;
277
+ proxy.isSettled = true;
278
+ throw error;
279
+ });
280
+ }
281
+
282
+ /*
283
+ Assert that `addedRecord` has a valid type so it can be added to the
284
+ relationship of the `record`.
285
+
286
+ The assert basically checks if the `addedRecord` can be added to the
287
+ relationship (specified via `relationshipMeta`) of the `record`.
288
+
289
+ This utility should only be used internally, as both record parameters must
290
+ be stable record identifiers and the `relationshipMeta` needs to be the meta
291
+ information about the relationship, retrieved via
292
+ `record.relationshipFor(key)`.
293
+ */
294
+ let assertPolymorphicType;
295
+ {
296
+ // eslint-disable-next-line @typescript-eslint/no-shadow
297
+ assertPolymorphicType = function assertPolymorphicType(parentIdentifier, parentDefinition, addedIdentifier, store) {
298
+ if (parentDefinition.inverseIsImplicit) {
299
+ return;
300
+ }
301
+ if (parentDefinition.isPolymorphic) {
302
+ const meta = store.schema.fields(addedIdentifier)?.get(parentDefinition.inverseKey);
303
+ if (meta) {
304
+ (test => {
305
+ if (!test) {
306
+ throw new Error(`Expected the schema for the field ${parentDefinition.inverseKey} on ${addedIdentifier.type} to be for a legacy relationship`);
307
+ }
308
+ })(meta.kind === 'belongsTo' || meta.kind === 'hasMany');
309
+ (test => {
310
+ if (!test) {
311
+ throw new Error(`The schema for the relationship '${parentDefinition.inverseKey}' on '${addedIdentifier.type}' type does not implement '${parentDefinition.type}' and thus cannot be assigned to the '${parentDefinition.key}' relationship in '${parentIdentifier.type}'. The definition should specify 'as: "${parentDefinition.type}"' in options.`);
312
+ }
313
+ })(meta?.options?.as === parentDefinition.type);
314
+ }
315
+ }
316
+ };
317
+ }
318
+ function isResourceIdentiferWithRelatedLinks$1(value) {
319
+ return Boolean(value && value.links && value.links.related);
320
+ }
321
+ /**
322
+ A `HasManyReference` is a low-level API that allows access
323
+ and manipulation of a hasMany relationship.
324
+
325
+ It is especially useful when you're dealing with `async` relationships
326
+ from `@warp-drive/legacy/model` as it allows synchronous access to
327
+ the relationship data if loaded, as well as APIs for loading, reloading
328
+ the data or accessing available information without triggering a load.
329
+
330
+ It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
331
+ that need to be loaded/reloaded with more precise timing than marking the
332
+ relationship as `async` and relying on autofetch would have allowed.
333
+
334
+ However,keep in mind that marking a relationship as `async: false` will introduce
335
+ bugs into your application if the data is not always guaranteed to be available
336
+ by the time the relationship is accessed. Ergo, it is recommended when using this
337
+ approach to utilize `links` for unloaded relationship state instead of identifiers.
338
+
339
+ Reference APIs are entangled with the relationship's underlying state,
340
+ thus any getters or cached properties that utilize these will properly
341
+ invalidate if the relationship state changes.
342
+
343
+ References are "stable", meaning that multiple calls to retrieve the reference
344
+ for a given relationship will always return the same HasManyReference.
345
+
346
+ @class HasManyReference
347
+ @public
348
+ */
349
+ class HasManyReference {
350
+ /**
351
+ * The field name on the parent record for this has-many relationship.
352
+ *
353
+ * @property key
354
+ * @type {String}
355
+ * @public
356
+ */
357
+
358
+ /**
359
+ * The type of resource this relationship will contain.
360
+ *
361
+ * @property type
362
+ * @type {String}
363
+ * @public
364
+ */
365
+
366
+ // unsubscribe tokens given to us by the notification manager
367
+ ___token;
368
+ ___identifier;
369
+ ___relatedTokenMap;
370
+ constructor(store, graph, parentIdentifier, hasManyRelationship, key) {
371
+ this.graph = graph;
372
+ this.key = key;
373
+ this.hasManyRelationship = hasManyRelationship;
374
+ this.type = hasManyRelationship.definition.type;
375
+ this.store = store;
376
+ this.___identifier = parentIdentifier;
377
+ this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
378
+ if (bucket === 'relationships' && notifiedKey === key) {
379
+ this._ref++;
380
+ }
381
+ });
382
+ this.___relatedTokenMap = new Map();
383
+ // TODO inverse
384
+ }
385
+
386
+ /**
387
+ * This method should never be called by user code.
388
+ *
389
+ * @internal
390
+ */
391
+ destroy() {
392
+ this.store.notifications.unsubscribe(this.___token);
393
+ this.___relatedTokenMap.forEach(token => {
394
+ this.store.notifications.unsubscribe(token);
395
+ });
396
+ this.___relatedTokenMap.clear();
397
+ }
398
+
399
+ /**
400
+ * An array of identifiers for the records that this reference refers to.
401
+ *
402
+ * @property identifiers
403
+ * @type {ResourceKey[]}
404
+ * @public
405
+ */
406
+ get identifiers() {
407
+ ensureRefCanSubscribe(this);
408
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
409
+ this._ref;
410
+ const resource = this._resource();
411
+ const map = this.___relatedTokenMap;
412
+ this.___relatedTokenMap = new Map();
413
+ if (resource && resource.data) {
414
+ return resource.data.map(resourceIdentifier => {
415
+ const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resourceIdentifier);
416
+ let token = map.get(identifier);
417
+ if (token) {
418
+ map.delete(identifier);
419
+ } else {
420
+ token = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
421
+ if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
422
+ this._ref++;
423
+ }
424
+ });
425
+ }
426
+ this.___relatedTokenMap.set(identifier, token);
427
+ return identifier;
428
+ });
429
+ }
430
+ map.forEach(token => {
431
+ this.store.notifications.unsubscribe(token);
432
+ });
433
+ map.clear();
434
+ return [];
435
+ }
436
+ static {
437
+ decorateMethodV2(this.prototype, "identifiers", [memoized]);
438
+ }
439
+ _resource() {
440
+ const cache = this.store.cache;
441
+ return cache.getRelationship(this.___identifier, this.key);
442
+ }
443
+
444
+ /**
445
+ This returns a string that represents how the reference will be
446
+ looked up when it is loaded. If the relationship has a link it will
447
+ use the "link" otherwise it defaults to "id".
448
+ Example
449
+ ```js [app/models/post.js]
450
+ import { Model, hasMany } from '@warp-drive/legacy/model';
451
+ export default class PostModel extends Model {
452
+ @hasMany('comment', { async: true, inverse: null }) comments;
453
+ }
454
+ ```
455
+ ```javascript
456
+ let post = store.push({
457
+ data: {
458
+ type: 'post',
459
+ id: 1,
460
+ relationships: {
461
+ comments: {
462
+ data: [{ type: 'comment', id: 1 }]
463
+ }
464
+ }
465
+ }
466
+ });
467
+ let commentsRef = post.hasMany('comments');
468
+ // get the identifier of the reference
469
+ if (commentsRef.remoteType() === "ids") {
470
+ let ids = commentsRef.ids();
471
+ } else if (commentsRef.remoteType() === "link") {
472
+ let link = commentsRef.link();
473
+ }
474
+ ```
475
+ @public
476
+ @return The name of the remote type. This should either be `link` or `ids`
477
+ */
478
+ remoteType() {
479
+ const value = this._resource();
480
+ if (value && value.links && value.links.related) {
481
+ return 'link';
482
+ }
483
+ return 'ids';
484
+ }
485
+
486
+ /**
487
+ `ids()` returns an array of the record IDs in this relationship.
488
+ Example
489
+ ```js [app/models/post.js]
490
+ import { Model, hasMany } from '@warp-drive/legacy/model';
491
+ export default class PostModel extends Model {
492
+ @hasMany('comment', { async: true, inverse: null }) comments;
493
+ }
494
+ ```
495
+ ```javascript
496
+ let post = store.push({
497
+ data: {
498
+ type: 'post',
499
+ id: 1,
500
+ relationships: {
501
+ comments: {
502
+ data: [{ type: 'comment', id: 1 }]
503
+ }
504
+ }
505
+ }
506
+ });
507
+ let commentsRef = post.hasMany('comments');
508
+ commentsRef.ids(); // ['1']
509
+ ```
510
+ @public
511
+ @return The ids in this has-many relationship
512
+ */
513
+ ids() {
514
+ return this.identifiers.map(identifier => identifier.id);
515
+ }
516
+
517
+ /**
518
+ The link WarpDrive will use to fetch or reload this belongs-to
519
+ relationship. By default it uses only the "related" resource linkage.
520
+ Example
521
+ ```javascript
522
+ // models/blog.js
523
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
524
+ export default Model.extend({
525
+ user: belongsTo('user', { async: true, inverse: null })
526
+ });
527
+ let blog = store.push({
528
+ data: {
529
+ type: 'blog',
530
+ id: 1,
531
+ relationships: {
532
+ user: {
533
+ links: {
534
+ related: '/articles/1/author'
535
+ }
536
+ }
537
+ }
538
+ }
539
+ });
540
+ let userRef = blog.belongsTo('user');
541
+ // get the identifier of the reference
542
+ if (userRef.remoteType() === "link") {
543
+ let link = userRef.link();
544
+ }
545
+ ```
546
+ @public
547
+ @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
548
+ */
549
+ link() {
550
+ const resource = this._resource();
551
+ if (isResourceIdentiferWithRelatedLinks$1(resource)) {
552
+ if (resource.links) {
553
+ const related = resource.links.related;
554
+ return !related || typeof related === 'string' ? related : related.href;
555
+ }
556
+ }
557
+ return null;
558
+ }
559
+
560
+ /**
561
+ * any links that have been received for this relationship
562
+ *
563
+ * @public
564
+ * @return
565
+ */
566
+ links() {
567
+ const resource = this._resource();
568
+ return resource && resource.links ? resource.links : null;
569
+ }
570
+
571
+ /**
572
+ The meta data for the has-many relationship.
573
+ Example
574
+ ```javascript
575
+ // models/blog.js
576
+ import { Model, hasMany } from '@warp-drive/legacy/model';
577
+ export default Model.extend({
578
+ users: hasMany('user', { async: true, inverse: null })
579
+ });
580
+ let blog = store.push({
581
+ data: {
582
+ type: 'blog',
583
+ id: 1,
584
+ relationships: {
585
+ users: {
586
+ links: {
587
+ related: {
588
+ href: '/articles/1/authors'
589
+ },
590
+ },
591
+ meta: {
592
+ lastUpdated: 1458014400000
593
+ }
594
+ }
595
+ }
596
+ }
597
+ });
598
+ let usersRef = blog.hasMany('user');
599
+ usersRef.meta() // { lastUpdated: 1458014400000 }
600
+ ```
601
+ @public
602
+ @return The meta information for the belongs-to relationship.
603
+ */
604
+ meta() {
605
+ let meta = null;
606
+ const resource = this._resource();
607
+ if (resource && resource.meta && typeof resource.meta === 'object') {
608
+ meta = resource.meta;
609
+ }
610
+ return meta;
611
+ }
612
+
613
+ /**
614
+ `push` can be used to update the data in the relationship and WarpDrive
615
+ will treat the new data as the canonical value of this relationship on
616
+ the backend. An empty array will signify the canonical value should be
617
+ empty.
618
+ Example model
619
+ ```js [app/models/post.js]
620
+ import { Model, hasMany } from '@warp-drive/legacy/model';
621
+ export default class PostModel extends Model {
622
+ @hasMany('comment', { async: true, inverse: null }) comments;
623
+ }
624
+ ```
625
+ Setup some initial state, note we haven't loaded the comments yet:
626
+ ```js
627
+ const post = store.push({
628
+ data: {
629
+ type: 'post',
630
+ id: '1',
631
+ relationships: {
632
+ comments: {
633
+ data: [{ type: 'comment', id: '1' }]
634
+ }
635
+ }
636
+ }
637
+ });
638
+ const commentsRef = post.hasMany('comments');
639
+ commentsRef.ids(); // ['1']
640
+ ```
641
+ Update the state using `push`, note we can do this even without
642
+ having loaded these comments yet by providing resource identifiers.
643
+ Both full resources and resource identifiers are supported.
644
+ ```js
645
+ await commentsRef.push({
646
+ data: [
647
+ { type: 'comment', id: '2' },
648
+ { type: 'comment', id: '3' },
649
+ ]
650
+ });
651
+ commentsRef.ids(); // ['2', '3']
652
+ ```
653
+ For convenience, you can also pass in an array of resources or resource identifiers
654
+ without wrapping them in the `data` property:
655
+ ```js
656
+ await commentsRef.push([
657
+ { type: 'comment', id: '4' },
658
+ { type: 'comment', id: '5' },
659
+ ]);
660
+ commentsRef.ids(); // ['4', '5']
661
+ ```
662
+ When using the `data` property, you may also include other resource data via included,
663
+ as well as provide new links and meta to the relationship.
664
+ ```js
665
+ await commentsRef.push({
666
+ links: {
667
+ related: '/posts/1/comments'
668
+ },
669
+ meta: {
670
+ total: 2
671
+ },
672
+ data: [
673
+ { type: 'comment', id: '4' },
674
+ { type: 'comment', id: '5' },
675
+ ],
676
+ included: [
677
+ { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
678
+ ]
679
+ });
680
+ ```
681
+ By default, the store will attempt to fetch any unloaded records before resolving
682
+ the returned promise with the ManyArray.
683
+ Alternatively, pass `true` as the second argument to avoid fetching unloaded records
684
+ and instead the promise will resolve with void without attempting to fetch. This is
685
+ particularly useful if you want to update the state of the relationship without
686
+ forcing the load of all of the associated records.
687
+ @public
688
+ @param doc a JSONAPI document object describing the new value of this relationship.
689
+ @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
690
+ */
691
+ async push(doc, skipFetch) {
692
+ const {
693
+ store
694
+ } = this;
695
+ const dataDoc = Array.isArray(doc) ? {
696
+ data: doc
697
+ } : doc;
698
+ const isResourceData = Array.isArray(dataDoc.data) && dataDoc.data.length > 0 && isMaybeResource(dataDoc.data[0]);
699
+
700
+ // enforce that one of links, meta or data is present
701
+ (test => {
702
+ if (!test) {
703
+ throw new Error(`You must provide at least one of 'links', 'meta' or 'data' when calling hasManyReference.push`);
704
+ }
705
+ })('links' in dataDoc || 'meta' in dataDoc || 'data' in dataDoc);
706
+ const identifiers = !Array.isArray(dataDoc.data) ? [] : isResourceData ? store._push(dataDoc, true) : dataDoc.data.map(i => store.cacheKeyManager.getOrCreateRecordIdentifier(i));
707
+ const {
708
+ identifier
709
+ } = this.hasManyRelationship;
710
+ {
711
+ const relationshipMeta = this.hasManyRelationship.definition;
712
+ identifiers.forEach(added => {
713
+ assertPolymorphicType(identifier, relationshipMeta, added, store);
714
+ });
715
+ }
716
+ const newData = {};
717
+ // only set data if it was passed in
718
+ if (Array.isArray(dataDoc.data)) {
719
+ newData.data = identifiers;
720
+ }
721
+ if ('links' in dataDoc) {
722
+ newData.links = dataDoc.links;
723
+ }
724
+ if ('meta' in dataDoc) {
725
+ newData.meta = dataDoc.meta;
726
+ }
727
+ assertPrivateStore(store);
728
+ store._join(() => {
729
+ this.graph.push({
730
+ op: 'updateRelationship',
731
+ record: identifier,
732
+ field: this.key,
733
+ value: newData
734
+ });
735
+ });
736
+ if (!skipFetch) return this.load();
737
+ }
738
+ _isLoaded() {
739
+ const hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
740
+ if (!hasRelationshipDataProperty) {
741
+ return false;
742
+ }
743
+ const relationship = this.graph.getData(this.hasManyRelationship.identifier, this.key);
744
+ return relationship.data ? relationship.data.every(identifier => {
745
+ assertPrivateStore(this.store);
746
+ return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
747
+ }) : false;
748
+ }
749
+
750
+ /**
751
+ `value()` synchronously returns the current value of the has-many
752
+ relationship. Unlike `record.relationshipName`, calling
753
+ `value()` on a reference does not trigger a fetch if the async
754
+ relationship is not yet loaded. If the relationship is not loaded
755
+ it will always return `null`.
756
+ Example
757
+ ```js [app/models/post.js]
758
+ import { Model, hasMany } from '@warp-drive/legacy/model';
759
+ export default class PostModel extends Model {
760
+ @hasMany('comment', { async: true, inverse: null }) comments;
761
+ }
762
+ ```
763
+ ```javascript
764
+ let post = store.push({
765
+ data: {
766
+ type: 'post',
767
+ id: 1,
768
+ relationships: {
769
+ comments: {
770
+ data: [{ type: 'comment', id: 1 }]
771
+ }
772
+ }
773
+ }
774
+ });
775
+ let commentsRef = post.hasMany('comments');
776
+ post.comments.then(function(comments) {
777
+ commentsRef.value() === comments
778
+ })
779
+ ```
780
+ @public
781
+ */
782
+ value() {
783
+ const support = LEGACY_SUPPORT.get(this.___identifier);
784
+ if (!ensureRefCanSubscribe(this)) {
785
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
786
+ this._ref;
787
+ return null;
788
+ }
789
+ return support.getManyArray(this.key);
790
+ }
791
+
792
+ /**
793
+ Loads the relationship if it is not already loaded. If the
794
+ relationship is already loaded this method does not trigger a new
795
+ load. This causes a request to the specified
796
+ relationship link or reloads all items currently in the relationship.
797
+ Example
798
+ ```js [app/models/post.js]
799
+ import { Model, hasMany } from '@warp-drive/legacy/model';
800
+ export default class PostModel extends Model {
801
+ @hasMany('comment', { async: true, inverse: null }) comments;
802
+ }
803
+ ```
804
+ ```javascript
805
+ let post = store.push({
806
+ data: {
807
+ type: 'post',
808
+ id: 1,
809
+ relationships: {
810
+ comments: {
811
+ data: [{ type: 'comment', id: 1 }]
812
+ }
813
+ }
814
+ }
815
+ });
816
+ let commentsRef = post.hasMany('comments');
817
+ commentsRef.load().then(function(comments) {
818
+ //...
819
+ });
820
+ ```
821
+ You may also pass in an options object whose properties will be
822
+ fed forward. This enables you to pass `adapterOptions` into the
823
+ request given to the adapter via the reference.
824
+ Example
825
+ ```javascript
826
+ commentsRef.load({ adapterOptions: { isPrivate: true } })
827
+ .then(function(comments) {
828
+ //...
829
+ });
830
+ ```
831
+ ```js [app/adapters/comment.js]
832
+ export default ApplicationAdapter.extend({
833
+ findMany(store, type, id, snapshots) {
834
+ // In the adapter you will have access to adapterOptions.
835
+ let adapterOptions = snapshots[0].adapterOptions;
836
+ }
837
+ });
838
+ ```
839
+ @public
840
+ @param options the options to pass in.
841
+ @return a promise that resolves with the ManyArray in
842
+ this has-many relationship.
843
+ */
844
+ async load(options) {
845
+ const support = LEGACY_SUPPORT.get(this.___identifier);
846
+ const fetchSyncRel = !this.hasManyRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
847
+ return fetchSyncRel ? support.reloadHasMany(this.key, options) :
848
+ // we cast to fix the return type since typescript and eslint don't understand async functions
849
+ // properly
850
+ support.getHasMany(this.key, options);
851
+ }
852
+
853
+ /**
854
+ Reloads this has-many relationship. This causes a request to the specified
855
+ relationship link or reloads all items currently in the relationship.
856
+ Example
857
+ ```js [app/models/post.js]
858
+ import { Model, hasMany } from '@warp-drive/legacy/model';
859
+ export default class PostModel extends Model {
860
+ @hasMany('comment', { async: true, inverse: null }) comments;
861
+ }
862
+ ```
863
+ ```javascript
864
+ let post = store.push({
865
+ data: {
866
+ type: 'post',
867
+ id: 1,
868
+ relationships: {
869
+ comments: {
870
+ data: [{ type: 'comment', id: 1 }]
871
+ }
872
+ }
873
+ }
874
+ });
875
+ let commentsRef = post.hasMany('comments');
876
+ commentsRef.reload().then(function(comments) {
877
+ //...
878
+ });
879
+ ```
880
+ You may also pass in an options object whose properties will be
881
+ fed forward. This enables you to pass `adapterOptions` into the
882
+ request given to the adapter via the reference. A full example
883
+ can be found in the `load` method.
884
+ Example
885
+ ```javascript
886
+ commentsRef.reload({ adapterOptions: { isPrivate: true } })
887
+ ```
888
+ @public
889
+ @param options the options to pass in.
890
+ @return a promise that resolves with the ManyArray in this has-many relationship.
891
+ */
892
+ reload(options) {
893
+ const support = LEGACY_SUPPORT.get(this.___identifier);
894
+ return support.reloadHasMany(this.key, options);
895
+ }
896
+ }
897
+ defineNonEnumerableSignal(HasManyReference.prototype, '_ref', 0);
898
+ function isMaybeResource(object) {
899
+ const keys = Object.keys(object).filter(k => k !== 'id' && k !== 'type' && k !== 'lid');
900
+ return keys.length > 0;
901
+ }
902
+ function ensureRefCanSubscribe(rel) {
903
+ const loaded = rel._isLoaded();
904
+ if (!loaded) {
905
+ // subscribe to changes
906
+ // for when we are not loaded yet
907
+ //
908
+ // because the graph optimizes the case where a relationship has never been subscribed,
909
+ // we force accessed to be true here. When we make the graph public we should create a
910
+ // subscribe/unsubscribe API
911
+ const edge = rel.graph.get(rel.___identifier, rel.key);
912
+ (test => {
913
+ if (!test) {
914
+ throw new Error(`Expected a hasMany relationship for ${rel.___identifier.type}:${rel.key}`);
915
+ }
916
+ })('accessed' in edge);
917
+ edge.accessed = true;
918
+ return false;
919
+ }
920
+ return true;
921
+ }
922
+ function isResourceIdentiferWithRelatedLinks(value) {
923
+ return Boolean(value && value.links && value.links.related);
924
+ }
925
+
926
+ /**
927
+ A `BelongsToReference` is a low-level API that allows access
928
+ and manipulation of a belongsTo relationship.
929
+
930
+ It is especially useful when you're dealing with `async` relationships
931
+ from `@warp-drive/legacy/model` as it allows synchronous access to
932
+ the relationship data if loaded, as well as APIs for loading, reloading
933
+ the data or accessing available information without triggering a load.
934
+
935
+ It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
936
+ that need to be loaded/reloaded with more precise timing than marking the
937
+ relationship as `async` and relying on autofetch would have allowed.
938
+
939
+ However,keep in mind that marking a relationship as `async: false` will introduce
940
+ bugs into your application if the data is not always guaranteed to be available
941
+ by the time the relationship is accessed. Ergo, it is recommended when using this
942
+ approach to utilize `links` for unloaded relationship state instead of identifiers.
943
+
944
+ Reference APIs are entangled with the relationship's underlying state,
945
+ thus any getters or cached properties that utilize these will properly
946
+ invalidate if the relationship state changes.
947
+
948
+ References are "stable", meaning that multiple calls to retrieve the reference
949
+ for a given relationship will always return the same HasManyReference.
950
+
951
+ @public
952
+ */
953
+ class BelongsToReference {
954
+ /**
955
+ * The field name on the parent record for this has-many relationship.
956
+ *
957
+ */
958
+
959
+ /**
960
+ * The type of resource this relationship will contain.
961
+ *
962
+ */
963
+
964
+ // unsubscribe tokens given to us by the notification manager
965
+
966
+ constructor(store, graph, parentIdentifier, belongsToRelationship, key) {
967
+ this.graph = graph;
968
+ this.key = key;
969
+ this.belongsToRelationship = belongsToRelationship;
970
+ this.type = belongsToRelationship.definition.type;
971
+ this.store = store;
972
+ this.___identifier = parentIdentifier;
973
+ this.___relatedToken = null;
974
+ this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
975
+ if (bucket === 'relationships' && notifiedKey === key) {
976
+ this._ref++;
977
+ }
978
+ });
979
+
980
+ // TODO inverse
981
+ }
982
+ destroy() {
983
+ // TODO @feature we need the notification manager often enough
984
+ // we should potentially just expose it fully public
985
+ this.store.notifications.unsubscribe(this.___token);
986
+ this.___token = null;
987
+ if (this.___relatedToken) {
988
+ this.store.notifications.unsubscribe(this.___relatedToken);
989
+ this.___relatedToken = null;
990
+ }
991
+ }
992
+
993
+ /**
994
+ * The identifier of the record that this reference refers to.
995
+ * `null` if no related record is known.
996
+ *
997
+ */
998
+ get identifier() {
999
+ if (this.___relatedToken) {
1000
+ this.store.notifications.unsubscribe(this.___relatedToken);
1001
+ this.___relatedToken = null;
1002
+ }
1003
+ const resource = this._resource();
1004
+ if (resource && resource.data) {
1005
+ const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resource.data);
1006
+ this.___relatedToken = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
1007
+ if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
1008
+ this._ref++;
1009
+ }
1010
+ });
1011
+ return identifier;
1012
+ }
1013
+ return null;
1014
+ }
1015
+
1016
+ /**
1017
+ The `id` of the record that this reference refers to. Together, the
1018
+ `type()` and `id()` methods form a composite key for the identity
1019
+ map. This can be used to access the id of an async relationship
1020
+ without triggering a fetch that would normally happen if you
1021
+ attempted to use `record.relationship.id`.
1022
+ Example
1023
+ ```javascript
1024
+ // models/blog.js
1025
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1026
+ export default class BlogModel extends Model {
1027
+ @belongsTo('user', { async: true, inverse: null }) user;
1028
+ }
1029
+ let blog = store.push({
1030
+ data: {
1031
+ type: 'blog',
1032
+ id: 1,
1033
+ relationships: {
1034
+ user: {
1035
+ data: { type: 'user', id: 1 }
1036
+ }
1037
+ }
1038
+ }
1039
+ });
1040
+ let userRef = blog.belongsTo('user');
1041
+ // get the identifier of the reference
1042
+ if (userRef.remoteType() === "id") {
1043
+ let id = userRef.id();
1044
+ }
1045
+ ```
1046
+ @public
1047
+ @return The id of the record in this belongsTo relationship.
1048
+ */
1049
+ static {
1050
+ decorateMethodV2(this.prototype, "identifier", [memoized]);
1051
+ }
1052
+ id() {
1053
+ return this.identifier?.id || null;
1054
+ }
1055
+
1056
+ /**
1057
+ The link WarpDrive will use to fetch or reload this belongs-to
1058
+ relationship. By default it uses only the "related" resource linkage.
1059
+ Example
1060
+ ```javascript
1061
+ // models/blog.js
1062
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1063
+ export default Model.extend({
1064
+ user: belongsTo('user', { async: true, inverse: null })
1065
+ });
1066
+ let blog = store.push({
1067
+ data: {
1068
+ type: 'blog',
1069
+ id: 1,
1070
+ relationships: {
1071
+ user: {
1072
+ links: {
1073
+ related: '/articles/1/author'
1074
+ }
1075
+ }
1076
+ }
1077
+ }
1078
+ });
1079
+ let userRef = blog.belongsTo('user');
1080
+ // get the identifier of the reference
1081
+ if (userRef.remoteType() === "link") {
1082
+ let link = userRef.link();
1083
+ }
1084
+ ```
1085
+ @public
1086
+ @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
1087
+ */
1088
+ link() {
1089
+ const resource = this._resource();
1090
+ if (isResourceIdentiferWithRelatedLinks(resource)) {
1091
+ if (resource.links) {
1092
+ const related = resource.links.related;
1093
+ return !related || typeof related === 'string' ? related : related.href;
1094
+ }
1095
+ }
1096
+ return null;
1097
+ }
1098
+
1099
+ /**
1100
+ * any links that have been received for this relationship
1101
+ *
1102
+ * @public
1103
+ * @return
1104
+ */
1105
+ links() {
1106
+ const resource = this._resource();
1107
+ return resource && resource.links ? resource.links : null;
1108
+ }
1109
+
1110
+ /**
1111
+ The meta data for the belongs-to relationship.
1112
+ Example
1113
+ ```javascript
1114
+ // models/blog.js
1115
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1116
+ export default Model.extend({
1117
+ user: belongsTo('user', { async: true, inverse: null })
1118
+ });
1119
+ let blog = store.push({
1120
+ data: {
1121
+ type: 'blog',
1122
+ id: 1,
1123
+ relationships: {
1124
+ user: {
1125
+ links: {
1126
+ related: {
1127
+ href: '/articles/1/author'
1128
+ },
1129
+ },
1130
+ meta: {
1131
+ lastUpdated: 1458014400000
1132
+ }
1133
+ }
1134
+ }
1135
+ }
1136
+ });
1137
+ let userRef = blog.belongsTo('user');
1138
+ userRef.meta() // { lastUpdated: 1458014400000 }
1139
+ ```
1140
+ @public
1141
+ @return The meta information for the belongs-to relationship.
1142
+ */
1143
+ meta() {
1144
+ let meta = null;
1145
+ const resource = this._resource();
1146
+ if (resource && resource.meta && typeof resource.meta === 'object') {
1147
+ meta = resource.meta;
1148
+ }
1149
+ return meta;
1150
+ }
1151
+ _resource() {
1152
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1153
+ this._ref; // subscribe
1154
+ const cache = this.store.cache;
1155
+ return cache.getRelationship(this.___identifier, this.key);
1156
+ }
1157
+
1158
+ /**
1159
+ This returns a string that represents how the reference will be
1160
+ looked up when it is loaded. If the relationship has a link it will
1161
+ use the "link" otherwise it defaults to "id".
1162
+ Example
1163
+ ```js [app/models/post.js]
1164
+ import Model, { hasMany } from '@warp-drive/legacy/model';
1165
+ export default class PostModel extends Model {
1166
+ @hasMany('comment', { async: true, inverse: null }) comments;
1167
+ }
1168
+ ```
1169
+ ```javascript
1170
+ let post = store.push({
1171
+ data: {
1172
+ type: 'post',
1173
+ id: 1,
1174
+ relationships: {
1175
+ comments: {
1176
+ data: [{ type: 'comment', id: 1 }]
1177
+ }
1178
+ }
1179
+ }
1180
+ });
1181
+ let commentsRef = post.hasMany('comments');
1182
+ // get the identifier of the reference
1183
+ if (commentsRef.remoteType() === "ids") {
1184
+ let ids = commentsRef.ids();
1185
+ } else if (commentsRef.remoteType() === "link") {
1186
+ let link = commentsRef.link();
1187
+ }
1188
+ ```
1189
+ @public
1190
+ @return The name of the remote type. This should either be `link` or `id`
1191
+ */
1192
+ remoteType() {
1193
+ const value = this._resource();
1194
+ if (isResourceIdentiferWithRelatedLinks(value)) {
1195
+ return 'link';
1196
+ }
1197
+ return 'id';
1198
+ }
1199
+
1200
+ /**
1201
+ `push` can be used to update the data in the relationship and WarpDrive
1202
+ will treat the new data as the canonical value of this relationship on
1203
+ the backend. A value of `null` (e.g. `{ data: null }`) can be passed to
1204
+ clear the relationship.
1205
+ Example model
1206
+ ```js [app/models/blog.js]
1207
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1208
+ export default class BlogModel extends Model {
1209
+ @belongsTo('user', { async: true, inverse: null }) user;
1210
+ }
1211
+ ```
1212
+ Setup some initial state, note we haven't loaded the user yet:
1213
+ ```js
1214
+ const blog = store.push({
1215
+ data: {
1216
+ type: 'blog',
1217
+ id: '1',
1218
+ relationships: {
1219
+ user: {
1220
+ data: { type: 'user', id: '1' }
1221
+ }
1222
+ }
1223
+ }
1224
+ });
1225
+ const userRef = blog.belongsTo('user');
1226
+ userRef.id(); // '1'
1227
+ ```
1228
+ Update the state using `push`, note we can do this even without
1229
+ having loaded the user yet by providing a resource-identifier.
1230
+ Both full a resource and a resource-identifier are supported.
1231
+ ```js
1232
+ await userRef.push({
1233
+ data: {
1234
+ type: 'user',
1235
+ id: '2',
1236
+ }
1237
+ });
1238
+ userRef.id(); // '2'
1239
+ ```
1240
+ You may also pass in links and meta fore the relationship, and sideload
1241
+ additional resources that might be required.
1242
+ ```js
1243
+ await userRef.push({
1244
+ data: {
1245
+ type: 'user',
1246
+ id: '2',
1247
+ },
1248
+ links: {
1249
+ related: '/articles/1/author'
1250
+ },
1251
+ meta: {
1252
+ lastUpdated: Date.now()
1253
+ },
1254
+ included: [
1255
+ {
1256
+ type: 'user-preview',
1257
+ id: '2',
1258
+ attributes: {
1259
+ username: '@runspired'
1260
+ }
1261
+ }
1262
+ ]
1263
+ });
1264
+ ```
1265
+ By default, the store will attempt to fetch the record if it is not loaded or its
1266
+ resource data is not included in the call to `push` before resolving the returned
1267
+ promise with the new state..
1268
+ Alternatively, pass `true` as the second argument to avoid fetching unloaded records
1269
+ and instead the promise will resolve with void without attempting to fetch. This is
1270
+ particularly useful if you want to update the state of the relationship without
1271
+ forcing the load of all of the associated record.
1272
+ @public
1273
+ @param doc a JSONAPI document object describing the new value of this relationship.
1274
+ @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
1275
+ @return a promise that resolves with the record in this belongs-to relationship after the push has completed.
1276
+ */
1277
+ async push(doc, skipFetch) {
1278
+ const {
1279
+ store
1280
+ } = this;
1281
+ const isResourceData = doc.data && isMaybeResource(doc.data);
1282
+ const added = isResourceData ? store._push(doc, true) : doc.data ? store.cacheKeyManager.getOrCreateRecordIdentifier(doc.data) : null;
1283
+ const {
1284
+ identifier
1285
+ } = this.belongsToRelationship;
1286
+ {
1287
+ if (added) {
1288
+ assertPolymorphicType(identifier, this.belongsToRelationship.definition, added, store);
1289
+ }
1290
+ }
1291
+ const newData = {};
1292
+
1293
+ // only set data if it was passed in
1294
+ if (doc.data || doc.data === null) {
1295
+ newData.data = added;
1296
+ }
1297
+ if ('links' in doc) {
1298
+ newData.links = doc.links;
1299
+ }
1300
+ if ('meta' in doc) {
1301
+ newData.meta = doc.meta;
1302
+ }
1303
+ assertPrivateStore(store);
1304
+ store._join(() => {
1305
+ this.graph.push({
1306
+ op: 'updateRelationship',
1307
+ record: identifier,
1308
+ field: this.key,
1309
+ value: newData
1310
+ });
1311
+ });
1312
+ if (!skipFetch) return this.load();
1313
+ }
1314
+
1315
+ /**
1316
+ `value()` synchronously returns the current value of the belongs-to
1317
+ relationship. Unlike `record.relationshipName`, calling
1318
+ `value()` on a reference does not trigger a fetch if the async
1319
+ relationship is not yet loaded. If the relationship is not loaded
1320
+ it will always return `null`.
1321
+ Example
1322
+ ```javascript
1323
+ // models/blog.js
1324
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1325
+ export default class BlogModel extends Model {
1326
+ @belongsTo('user', { async: true, inverse: null }) user;
1327
+ }
1328
+ let blog = store.push({
1329
+ data: {
1330
+ type: 'blog',
1331
+ id: 1,
1332
+ relationships: {
1333
+ user: {
1334
+ data: { type: 'user', id: 1 }
1335
+ }
1336
+ }
1337
+ }
1338
+ });
1339
+ let userRef = blog.belongsTo('user');
1340
+ userRef.value(); // null
1341
+ // provide data for reference
1342
+ userRef.push({
1343
+ data: {
1344
+ type: 'user',
1345
+ id: 1,
1346
+ attributes: {
1347
+ username: "@user"
1348
+ }
1349
+ }
1350
+ }).then(function(user) {
1351
+ userRef.value(); // user
1352
+ });
1353
+ ```
1354
+ @public
1355
+ @return the record in this relationship
1356
+ */
1357
+ value() {
1358
+ const resource = this._resource();
1359
+ return resource && resource.data ? this.store.peekRecord(resource.data) : null;
1360
+ }
1361
+
1362
+ /**
1363
+ Loads a record in a belongs-to relationship if it is not already
1364
+ loaded. If the relationship is already loaded this method does not
1365
+ trigger a new load.
1366
+ Example
1367
+ ```javascript
1368
+ // models/blog.js
1369
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1370
+ export default class BlogModel extends Model {
1371
+ @belongsTo('user', { async: true, inverse: null }) user;
1372
+ }
1373
+ let blog = store.push({
1374
+ data: {
1375
+ type: 'blog',
1376
+ id: 1,
1377
+ relationships: {
1378
+ user: {
1379
+ data: { type: 'user', id: 1 }
1380
+ }
1381
+ }
1382
+ }
1383
+ });
1384
+ let userRef = blog.belongsTo('user');
1385
+ userRef.value(); // null
1386
+ userRef.load().then(function(user) {
1387
+ userRef.value() === user
1388
+ });
1389
+ ```
1390
+ You may also pass in an options object whose properties will be
1391
+ fed forward. This enables you to pass `adapterOptions` into the
1392
+ request given to the adapter via the reference.
1393
+ Example
1394
+ ```javascript
1395
+ userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
1396
+ userRef.value() === user;
1397
+ });
1398
+ ```
1399
+ ```js [app/adapters/user.js]
1400
+ import Adapter from '@warp-drive/legacy/adapter';
1401
+ export default class UserAdapter extends Adapter {
1402
+ findRecord(store, type, id, snapshot) {
1403
+ // In the adapter you will have access to adapterOptions.
1404
+ let adapterOptions = snapshot.adapterOptions;
1405
+ }
1406
+ });
1407
+ ```
1408
+ @public
1409
+ @param options the options to pass in.
1410
+ @return a promise that resolves with the record in this belongs-to relationship.
1411
+ */
1412
+ async load(options) {
1413
+ const support = LEGACY_SUPPORT.get(this.___identifier);
1414
+ const fetchSyncRel = !this.belongsToRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
1415
+ return fetchSyncRel ? support.reloadBelongsTo(this.key, options).then(() => this.value()) :
1416
+ // we cast to fix the return type since typescript and eslint don't understand async functions
1417
+ // properly
1418
+ support.getBelongsTo(this.key, options);
1419
+ }
1420
+
1421
+ /**
1422
+ Triggers a reload of the value in this relationship. If the
1423
+ remoteType is `"link"` WarpDrive will use the relationship link to
1424
+ reload the relationship. Otherwise it will reload the record by its
1425
+ id.
1426
+ Example
1427
+ ```javascript
1428
+ // models/blog.js
1429
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1430
+ export default class BlogModel extends Model {
1431
+ @belongsTo('user', { async: true, inverse: null }) user;
1432
+ }
1433
+ let blog = store.push({
1434
+ data: {
1435
+ type: 'blog',
1436
+ id: 1,
1437
+ relationships: {
1438
+ user: {
1439
+ data: { type: 'user', id: 1 }
1440
+ }
1441
+ }
1442
+ }
1443
+ });
1444
+ let userRef = blog.belongsTo('user');
1445
+ userRef.reload().then(function(user) {
1446
+ userRef.value() === user
1447
+ });
1448
+ ```
1449
+ You may also pass in an options object whose properties will be
1450
+ fed forward. This enables you to pass `adapterOptions` into the
1451
+ request given to the adapter via the reference. A full example
1452
+ can be found in the `load` method.
1453
+ Example
1454
+ ```javascript
1455
+ userRef.reload({ adapterOptions: { isPrivate: true } })
1456
+ ```
1457
+ @public
1458
+ @param options the options to pass in.
1459
+ @return a promise that resolves with the record in this belongs-to relationship after the reload has completed.
1460
+ */
1461
+ reload(options) {
1462
+ const support = LEGACY_SUPPORT.get(this.___identifier);
1463
+ return support.reloadBelongsTo(this.key, options).then(() => this.value());
1464
+ }
1465
+ }
1466
+ defineNonEnumerableSignal(BelongsToReference.prototype, '_ref', 0);
1467
+ const LEGACY_SUPPORT = getOrSetGlobal('LEGACY_SUPPORT', new Map());
1468
+ function lookupLegacySupport(record) {
1469
+ const identifier = recordIdentifierFor(record);
1470
+ (test => {
1471
+ if (!test) {
1472
+ throw new Error(`Expected a record`);
1473
+ }
1474
+ })(identifier);
1475
+ let support = LEGACY_SUPPORT.get(identifier);
1476
+ if (!support) {
1477
+ (test => {
1478
+ if (!test) {
1479
+ throw new Error(`Memory Leak Detected`);
1480
+ }
1481
+ })(!record.isDestroyed && !record.isDestroying);
1482
+ support = new LegacySupport(record, identifier);
1483
+ LEGACY_SUPPORT.set(identifier, support);
1484
+ }
1485
+ return support;
1486
+ }
1487
+
1488
+ /**
1489
+ * @hideconstructor
1490
+ */
1491
+ class LegacySupport {
1492
+ /** @internal */
1493
+
1494
+ /** @internal */
1495
+
1496
+ /** @internal */
1497
+
1498
+ /** @internal */
1499
+
1500
+ /** @internal */
1501
+
1502
+ /** @internal */
1503
+
1504
+ /** @internal */
1505
+
1506
+ /** @internal */
1507
+
1508
+ /** @internal */
1509
+
1510
+ /** @internal */
1511
+
1512
+ /** @internal */
1513
+
1514
+ constructor(record, identifier) {
1515
+ this.record = record;
1516
+ this.store = isPrivateStore(storeFor(record, false));
1517
+ this.identifier = identifier;
1518
+ this.cache = this.store.cache;
1519
+ if (this.store._graph) {
1520
+ this.graph = this.store._graph;
1521
+ }
1522
+ this._manyArrayCache = Object.create(null);
1523
+ this._relationshipPromisesCache = Object.create(null);
1524
+ this._relationshipProxyCache = Object.create(null);
1525
+ this._pending = Object.create(null);
1526
+ this.references = Object.create(null);
1527
+ }
1528
+
1529
+ /** @private */
1530
+ _syncArray(array) {
1531
+ // It’s possible the parent side of the relationship may have been destroyed by this point
1532
+ if (this.isDestroyed || this.isDestroying) {
1533
+ return;
1534
+ }
1535
+ const currentState = array[Context].source;
1536
+ const identifier = this.identifier;
1537
+ const [identifiers, jsonApi] = this._getCurrentState(identifier, array.key);
1538
+ if (jsonApi.meta) {
1539
+ array.meta = jsonApi.meta;
1540
+ }
1541
+ if (jsonApi.links) {
1542
+ array.links = jsonApi.links;
1543
+ }
1544
+ currentState.length = 0;
1545
+ fastPush(currentState, identifiers);
1546
+ }
1547
+ mutate(mutation) {
1548
+ this.cache.mutate(mutation);
1549
+ }
1550
+ _findBelongsTo(key, resource, relationship, options) {
1551
+ const name = getRealFieldName(this, key);
1552
+
1553
+ // TODO @runspired follow up if parent isNew then we should not be attempting load here
1554
+ // TODO @runspired follow up on whether this should be in the relationship requests cache
1555
+ return this._findBelongsToByJsonApiResource(resource, this.identifier, relationship, options).then(identifier => handleCompletedRelationshipRequest(this, name, relationship, identifier), e => handleCompletedRelationshipRequest(this, name, relationship, null, e));
1556
+ }
1557
+ reloadBelongsTo(key, options) {
1558
+ const loadingPromise = this._relationshipPromisesCache[key];
1559
+ if (loadingPromise) {
1560
+ return loadingPromise;
1561
+ }
1562
+ const name = getRealFieldName(this, key);
1563
+ const resource = this.store.cache.getRelationship(this.identifier, name);
1564
+ const relationship = this.graph.get(this.identifier, name);
1565
+ (test => {
1566
+ if (!test) {
1567
+ throw new Error(`Expected ${key === name ? name : `${key} (source: ${name})`} to be a belongs-to relationship`);
1568
+ }
1569
+ })(isBelongsTo(relationship));
1570
+ relationship.state.hasFailedLoadAttempt = false;
1571
+ relationship.state.shouldForceReload = true;
1572
+ const promise = this._findBelongsTo(name, resource, relationship, options);
1573
+ if (this._relationshipProxyCache[name]) {
1574
+ // @ts-expect-error
1575
+ return this._updatePromiseProxyFor('belongsTo', name, {
1576
+ promise
1577
+ });
1578
+ }
1579
+ return promise;
1580
+ }
1581
+ getBelongsTo(key, options) {
1582
+ const {
1583
+ identifier
1584
+ } = this;
1585
+ const name = getRealFieldName(this, key);
1586
+ const resource = this.store.cache.getRelationship(this.identifier, name);
1587
+ const relatedIdentifier = resource && resource.data ? resource.data : null;
1588
+ (test => {
1589
+ if (!test) {
1590
+ throw new Error(`Expected a stable identifier`);
1591
+ }
1592
+ })(!relatedIdentifier || isResourceKey(relatedIdentifier));
1593
+ const store = this.store;
1594
+ const relationship = this.graph.get(this.identifier, name);
1595
+ (test => {
1596
+ if (!test) {
1597
+ throw new Error(`Expected ${key === name ? name : `${key} (source: ${name})`} to be a belongs-to relationship`);
1598
+ }
1599
+ })(isBelongsTo(relationship));
1600
+ const isAsync = relationship.definition.isAsync;
1601
+ const _belongsToState = {
1602
+ key,
1603
+ store,
1604
+ legacySupport: this,
1605
+ modelName: relationship.definition.type
1606
+ };
1607
+ if (isAsync) {
1608
+ if (relationship.state.hasFailedLoadAttempt) {
1609
+ return this._relationshipProxyCache[name];
1610
+ }
1611
+ const promise = this._findBelongsTo(name, resource, relationship, options);
1612
+ const isLoaded = relatedIdentifier && store._instanceCache.recordIsLoaded(relatedIdentifier);
1613
+ return this._updatePromiseProxyFor('belongsTo', name, {
1614
+ promise,
1615
+ content: isLoaded ? store._instanceCache.getRecord(relatedIdentifier) : null,
1616
+ _belongsToState
1617
+ });
1618
+ } else {
1619
+ if (relatedIdentifier === null) {
1620
+ return null;
1621
+ } else {
1622
+ (test => {
1623
+ if (!test) {
1624
+ throw new Error(`You looked up the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${identifier.type}' with id ${identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\`belongsTo(<type>, { async: true, inverse: <inverse> })\`)`);
1625
+ }
1626
+ })(store._instanceCache.recordIsLoaded(relatedIdentifier, true));
1627
+ return store._instanceCache.getRecord(relatedIdentifier);
1628
+ }
1629
+ }
1630
+ }
1631
+ setDirtyBelongsTo(key, value) {
1632
+ const name = getRealFieldName(this, key);
1633
+ return this.cache.mutate({
1634
+ op: 'replaceRelatedRecord',
1635
+ record: this.identifier,
1636
+ field: name,
1637
+ value: extractIdentifierFromRecord(value)
1638
+ },
1639
+ // @ts-expect-error
1640
+ true);
1641
+ }
1642
+ _getCurrentState(identifier, field) {
1643
+ const jsonApi = this.cache.getRelationship(identifier, field);
1644
+ const cache = this.store._instanceCache;
1645
+ const identifiers = [];
1646
+ if (jsonApi.data) {
1647
+ for (let i = 0; i < jsonApi.data.length; i++) {
1648
+ const relatedIdentifier = jsonApi.data[i];
1649
+ (test => {
1650
+ if (!test) {
1651
+ throw new Error(`Expected a stable identifier`);
1652
+ }
1653
+ })(isResourceKey(relatedIdentifier));
1654
+ if (cache.recordIsLoaded(relatedIdentifier, true)) {
1655
+ identifiers.push(relatedIdentifier);
1656
+ }
1657
+ }
1658
+ }
1659
+ return [identifiers, jsonApi];
1660
+ }
1661
+ getManyArray(key, definition) {
1662
+ const name = getRealFieldName(this, key);
1663
+ if (this.graph) {
1664
+ let manyArray = this._manyArrayCache[name];
1665
+ if (!definition) {
1666
+ definition = this.graph.get(this.identifier, name).definition;
1667
+ }
1668
+ if (!manyArray) {
1669
+ const [identifiers, doc] = this._getCurrentState(this.identifier, name);
1670
+ const field = getField(this, name);
1671
+ manyArray = createLegacyManyArray({
1672
+ store: this.store,
1673
+ // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
1674
+ manager: this,
1675
+ source: identifiers,
1676
+ type: definition.type,
1677
+ isLoaded: !definition.isAsync,
1678
+ editable: true,
1679
+ isAsync: definition.isAsync,
1680
+ isPolymorphic: definition.isPolymorphic,
1681
+ field: field,
1682
+ identifier: this.identifier,
1683
+ links: doc.links || null,
1684
+ meta: doc.meta || null
1685
+ });
1686
+ this._manyArrayCache[name] = manyArray;
1687
+ }
1688
+ return manyArray;
1689
+ }
1690
+ (test => {
1691
+ {
1692
+ throw new Error('hasMany only works with the JSONAPICache');
1693
+ }
1694
+ })();
1695
+ }
1696
+ fetchAsyncHasMany(key, relationship, manyArray, options) {
1697
+ const name = getRealFieldName(this, key);
1698
+ if (this.graph) {
1699
+ let loadingPromise = this._relationshipPromisesCache[name];
1700
+ if (loadingPromise) {
1701
+ return loadingPromise;
1702
+ }
1703
+ const jsonApi = this.cache.getRelationship(this.identifier, name);
1704
+ const promise = this._findHasManyByJsonApiResource(jsonApi, this.identifier, relationship, options);
1705
+ if (!promise) {
1706
+ manyArray.isLoaded = true;
1707
+ return Promise.resolve(manyArray);
1708
+ }
1709
+ loadingPromise = promise.then(() => handleCompletedRelationshipRequest(this, name, relationship, manyArray), e => handleCompletedRelationshipRequest(this, name, relationship, manyArray, e));
1710
+ this._relationshipPromisesCache[name] = loadingPromise;
1711
+ return loadingPromise;
1712
+ }
1713
+ (test => {
1714
+ {
1715
+ throw new Error('hasMany only works with the JSONAPICache');
1716
+ }
1717
+ })();
1718
+ }
1719
+ reloadHasMany(key, options) {
1720
+ const name = getRealFieldName(this, key);
1721
+ if (this.graph) {
1722
+ const loadingPromise = this._relationshipPromisesCache[name];
1723
+ if (loadingPromise) {
1724
+ return loadingPromise;
1725
+ }
1726
+ const relationship = this.graph.get(this.identifier, name);
1727
+ const {
1728
+ definition,
1729
+ state
1730
+ } = relationship;
1731
+ state.hasFailedLoadAttempt = false;
1732
+ state.shouldForceReload = true;
1733
+ const manyArray = this.getManyArray(name, definition);
1734
+ const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1735
+ if (this._relationshipProxyCache[name]) {
1736
+ return this._updatePromiseProxyFor('hasMany', name, {
1737
+ promise
1738
+ });
1739
+ }
1740
+ return promise;
1741
+ }
1742
+ (test => {
1743
+ {
1744
+ throw new Error(`hasMany only works with the JSONAPICache`);
1745
+ }
1746
+ })();
1747
+ }
1748
+ getHasMany(key, options) {
1749
+ const name = getRealFieldName(this, key);
1750
+ if (this.graph) {
1751
+ const relationship = this.graph.get(this.identifier, name);
1752
+ const {
1753
+ definition,
1754
+ state
1755
+ } = relationship;
1756
+ const manyArray = this.getManyArray(name, definition);
1757
+ if (definition.isAsync) {
1758
+ if (state.hasFailedLoadAttempt) {
1759
+ return this._relationshipProxyCache[name];
1760
+ }
1761
+ const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1762
+ return this._updatePromiseProxyFor('hasMany', name, {
1763
+ promise,
1764
+ content: manyArray
1765
+ });
1766
+ } else {
1767
+ (test => {
1768
+ if (!test) {
1769
+ throw new Error(`You looked up the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${this.identifier.type}' with id ${this.identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async ('hasMany(<type>, { async: true, inverse: <inverse> })')`);
1770
+ }
1771
+ })(!anyUnloaded(this.store, relationship));
1772
+ return manyArray;
1773
+ }
1774
+ }
1775
+ (test => {
1776
+ {
1777
+ throw new Error(`hasMany only works with the JSONAPICache`);
1778
+ }
1779
+ })();
1780
+ }
1781
+ _updatePromiseProxyFor(kind, key, args) {
1782
+ let promiseProxy = this._relationshipProxyCache[key];
1783
+ if (kind === 'hasMany') {
1784
+ const {
1785
+ promise,
1786
+ content
1787
+ } = args;
1788
+ if (promiseProxy) {
1789
+ (test => {
1790
+ if (!test) {
1791
+ throw new Error(`Expected a PromiseManyArray`);
1792
+ }
1793
+ })('_update' in promiseProxy);
1794
+ promiseProxy._update(promise, content);
1795
+ } else {
1796
+ promiseProxy = this._relationshipProxyCache[key] = new PromiseManyArray(promise, content);
1797
+ }
1798
+ return promiseProxy;
1799
+ }
1800
+ if (promiseProxy) {
1801
+ const {
1802
+ promise,
1803
+ content
1804
+ } = args;
1805
+ (test => {
1806
+ if (!test) {
1807
+ throw new Error(`Expected a PromiseBelongsTo`);
1808
+ }
1809
+ })('_belongsToState' in promiseProxy);
1810
+ if (content !== undefined) {
1811
+ promiseProxy.set('content', content);
1812
+ }
1813
+ void promiseProxy.set('promise', promise);
1814
+ } else {
1815
+ promiseProxy = PromiseBelongsTo.create(args);
1816
+ this._relationshipProxyCache[key] = promiseProxy;
1817
+ }
1818
+ return promiseProxy;
1819
+ }
1820
+ referenceFor(kind, key) {
1821
+ const name = getRealFieldName(this, key);
1822
+ let reference = this.references[name];
1823
+ if (!reference) {
1824
+ if (!this.graph) {
1825
+ // TODO @runspired while this feels odd, it is not a regression in capability because we do
1826
+ // not today support references pulling from RecordDatas other than our own
1827
+ // because of the intimate API access involved. This is something we will need to redesign.
1828
+ (test => {
1829
+ {
1830
+ throw new Error(`snapshot.belongsTo only supported when using the JSONAPICache`);
1831
+ }
1832
+ })();
1833
+ }
1834
+ const {
1835
+ graph,
1836
+ identifier
1837
+ } = this;
1838
+ const relationship = graph.get(identifier, name);
1839
+ {
1840
+ if (kind) {
1841
+ const modelName = identifier.type;
1842
+ const actualRelationshipKind = relationship.definition.kind;
1843
+ (test => {
1844
+ if (!test) {
1845
+ throw new Error(`You tried to get the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${modelName}' via record.${kind}('${key}'), but the relationship is of kind '${actualRelationshipKind}'. Use record.${actualRelationshipKind}('${key}') instead.`);
1846
+ }
1847
+ })(actualRelationshipKind === kind);
1848
+ }
1849
+ }
1850
+ const relationshipKind = relationship.definition.kind;
1851
+ if (relationshipKind === 'belongsTo') {
1852
+ reference = new BelongsToReference(this.store, graph, identifier, relationship, key);
1853
+ } else if (relationshipKind === 'hasMany') {
1854
+ reference = new HasManyReference(this.store, graph, identifier, relationship, key);
1855
+ }
1856
+ this.references[name] = reference;
1857
+ }
1858
+ return reference;
1859
+ }
1860
+ _findHasManyByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1861
+ if (this.graph) {
1862
+ if (!resource) {
1863
+ return;
1864
+ }
1865
+ const {
1866
+ definition,
1867
+ state
1868
+ } = relationship;
1869
+ upgradeStore(this.store);
1870
+ const adapter = this.store.adapterFor?.(definition.type);
1871
+ const {
1872
+ isStale,
1873
+ hasDematerializedInverse,
1874
+ hasReceivedData,
1875
+ isEmpty,
1876
+ shouldForceReload
1877
+ } = state;
1878
+ const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1879
+ const identifiers = resource.data;
1880
+ const shouldFindViaLink = resource.links && resource.links.related && (typeof adapter?.findHasMany === 'function' || typeof identifiers === 'undefined') && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1881
+ const field = this.store.schema.fields({
1882
+ type: definition.inverseType
1883
+ }).get(definition.key);
1884
+ (test => {
1885
+ if (!test) {
1886
+ throw new Error(`Expected a hasMany field definition for ${definition.inverseType}.${definition.key}`);
1887
+ }
1888
+ })(field && field.kind === 'hasMany');
1889
+ const request = {
1890
+ useLink: shouldFindViaLink,
1891
+ field,
1892
+ links: resource.links,
1893
+ meta: resource.meta,
1894
+ options,
1895
+ record: parentIdentifier
1896
+ };
1897
+
1898
+ // fetch via link
1899
+ if (shouldFindViaLink) {
1900
+ (test => {
1901
+ if (!test) {
1902
+ throw new Error(`Expected collection to be an array`);
1903
+ }
1904
+ })(!identifiers || Array.isArray(identifiers));
1905
+ (test => {
1906
+ if (!test) {
1907
+ throw new Error(`Expected stable identifiers`);
1908
+ }
1909
+ })(!identifiers || identifiers.every(isResourceKey));
1910
+ const req = field.options.linksMode ? {
1911
+ url: getRelatedLink(resource),
1912
+ op: 'findHasMany',
1913
+ method: 'GET',
1914
+ records: identifiers || [],
1915
+ data: request,
1916
+ [EnableHydration]: false
1917
+ } : {
1918
+ op: 'findHasMany',
1919
+ records: identifiers || [],
1920
+ data: request,
1921
+ cacheOptions: {
1922
+ [Symbol.for('wd:skip-cache')]: true
1923
+ }
1924
+ };
1925
+ return this.store.request(req);
1926
+ }
1927
+ const preferLocalCache = hasReceivedData && !isEmpty;
1928
+ const hasLocalPartialData = hasDematerializedInverse || isEmpty && Array.isArray(identifiers) && identifiers.length > 0;
1929
+ const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
1930
+ if (attemptLocalCache && allInverseRecordsAreLoaded) {
1931
+ return;
1932
+ }
1933
+ const hasData = hasReceivedData && !isEmpty;
1934
+ if (attemptLocalCache || hasData || hasLocalPartialData) {
1935
+ (test => {
1936
+ if (!test) {
1937
+ throw new Error(`Expected collection to be an array`);
1938
+ }
1939
+ })(Array.isArray(identifiers));
1940
+ (test => {
1941
+ if (!test) {
1942
+ throw new Error(`Expected stable identifiers`);
1943
+ }
1944
+ })(identifiers.every(isResourceKey));
1945
+ options.reload = options.reload || !attemptLocalCache || undefined;
1946
+ return this.store.request({
1947
+ op: 'findHasMany',
1948
+ records: identifiers,
1949
+ data: request,
1950
+ cacheOptions: {
1951
+ [Symbol.for('wd:skip-cache')]: true
1952
+ }
1953
+ });
1954
+ }
1955
+
1956
+ // we were explicitly told we have no data and no links.
1957
+ // TODO if the relationshipIsStale, should we hit the adapter anyway?
1958
+ return;
1959
+ }
1960
+ (test => {
1961
+ {
1962
+ throw new Error(`hasMany only works with the JSONAPICache`);
1963
+ }
1964
+ })();
1965
+ }
1966
+ _findBelongsToByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1967
+ if (!resource) {
1968
+ return Promise.resolve(null);
1969
+ }
1970
+ const key = relationship.definition.key;
1971
+ const name = getRealFieldName(this, key);
1972
+
1973
+ // interleaved promises mean that we MUST cache this here
1974
+ // in order to prevent infinite re-render if the request
1975
+ // fails.
1976
+ if (this._pending[name]) {
1977
+ return this._pending[name];
1978
+ }
1979
+ const identifier = resource.data ? resource.data : null;
1980
+ (test => {
1981
+ if (!test) {
1982
+ throw new Error(`Expected a stable identifier`);
1983
+ }
1984
+ })(!identifier || isResourceKey(identifier));
1985
+ const {
1986
+ isStale,
1987
+ hasDematerializedInverse,
1988
+ hasReceivedData,
1989
+ isEmpty,
1990
+ shouldForceReload
1991
+ } = relationship.state;
1992
+ const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1993
+ const shouldFindViaLink = resource.links?.related && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1994
+ const field = this.store.schema.fields(this.identifier).get(relationship.definition.key);
1995
+ (test => {
1996
+ if (!test) {
1997
+ throw new Error(`Attempted to access a belongsTo relationship but no definition exists for it`);
1998
+ }
1999
+ })(field && field.kind === 'belongsTo');
2000
+ const request = {
2001
+ useLink: shouldFindViaLink,
2002
+ field,
2003
+ links: resource.links,
2004
+ meta: resource.meta,
2005
+ options,
2006
+ record: parentIdentifier
2007
+ };
2008
+
2009
+ // fetch via link
2010
+ if (shouldFindViaLink) {
2011
+ const req = field.options.linksMode ? {
2012
+ url: getRelatedLink(resource),
2013
+ op: 'findBelongsTo',
2014
+ method: 'GET',
2015
+ records: identifier ? [identifier] : [],
2016
+ data: request,
2017
+ [EnableHydration]: false
2018
+ } : {
2019
+ op: 'findBelongsTo',
2020
+ records: identifier ? [identifier] : [],
2021
+ data: request,
2022
+ cacheOptions: {
2023
+ [Symbol.for('wd:skip-cache')]: true
2024
+ }
2025
+ };
2026
+ const future = this.store.request(req);
2027
+ this._pending[name] = future.then(doc => field.options.linksMode ? doc.content.data : doc.content).finally(() => {
2028
+ this._pending[name] = undefined;
2029
+ });
2030
+ return this._pending[name];
2031
+ }
2032
+ const preferLocalCache = hasReceivedData && allInverseRecordsAreLoaded && !isEmpty;
2033
+ const hasLocalPartialData = hasDematerializedInverse || isEmpty && resource.data;
2034
+ // null is explicit empty, undefined is "we don't know anything"
2035
+ const localDataIsEmpty = !identifier;
2036
+ const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
2037
+
2038
+ // we dont need to fetch and are empty
2039
+ if (attemptLocalCache && localDataIsEmpty) {
2040
+ return Promise.resolve(null);
2041
+ }
2042
+
2043
+ // we dont need to fetch because we are local state
2044
+ const resourceIsLocal = identifier?.id === null;
2045
+ if (attemptLocalCache && allInverseRecordsAreLoaded || resourceIsLocal) {
2046
+ return Promise.resolve(identifier);
2047
+ }
2048
+
2049
+ // we may need to fetch
2050
+ if (identifier) {
2051
+ (test => {
2052
+ if (!test) {
2053
+ throw new Error(`Cannot fetch belongs-to relationship with no information`);
2054
+ }
2055
+ })(identifier);
2056
+ options.reload = options.reload || !attemptLocalCache || undefined;
2057
+ this._pending[name] = this.store.request({
2058
+ op: 'findBelongsTo',
2059
+ records: [identifier],
2060
+ data: request,
2061
+ cacheOptions: {
2062
+ [Symbol.for('wd:skip-cache')]: true
2063
+ }
2064
+ }).then(doc => doc.content).finally(() => {
2065
+ this._pending[name] = undefined;
2066
+ });
2067
+ return this._pending[name];
2068
+ }
2069
+
2070
+ // we were explicitly told we have no data and no links.
2071
+ // TODO if the relationshipIsStale, should we hit the adapter anyway?
2072
+ return Promise.resolve(null);
2073
+ }
2074
+ destroy() {
2075
+ this.isDestroying = true;
2076
+ let cache = this._manyArrayCache;
2077
+ this._manyArrayCache = Object.create(null);
2078
+ Object.keys(cache).forEach(key => {
2079
+ cache[key].destroy();
2080
+ });
2081
+ cache = this._relationshipProxyCache;
2082
+ this._relationshipProxyCache = Object.create(null);
2083
+ Object.keys(cache).forEach(key => {
2084
+ const proxy = cache[key];
2085
+ if (proxy.destroy) {
2086
+ proxy.destroy();
2087
+ }
2088
+ });
2089
+ cache = this.references;
2090
+ this.references = Object.create(null);
2091
+ Object.keys(cache).forEach(key => {
2092
+ cache[key].destroy();
2093
+ });
2094
+ this.isDestroyed = true;
2095
+ }
2096
+ }
2097
+ function getRelatedLink(resource) {
2098
+ const related = resource.links?.related;
2099
+ (test => {
2100
+ if (!test) {
2101
+ throw new Error(`Expected a related link`);
2102
+ }
2103
+ })(related);
2104
+ return typeof related === 'object' ? related.href : related;
2105
+ }
2106
+ function handleCompletedRelationshipRequest(recordExt, key, relationship, value, error) {
2107
+ delete recordExt._relationshipPromisesCache[key];
2108
+ relationship.state.shouldForceReload = false;
2109
+ const isHasMany = relationship.definition.kind === 'hasMany';
2110
+ if (isHasMany) {
2111
+ // we don't notify the record property here to avoid refetch
2112
+ // only the many array
2113
+ notifyInternalSignal(value[Context].signal);
2114
+ }
2115
+ if (error) {
2116
+ relationship.state.hasFailedLoadAttempt = true;
2117
+ const proxy = recordExt._relationshipProxyCache[key];
2118
+ // belongsTo relationships are sometimes unloaded
2119
+ // when a load fails, in this case we need
2120
+ // to make sure that we aren't proxying
2121
+ // to destroyed content
2122
+ // for the sync belongsTo reload case there will be no proxy
2123
+ // for the async reload case there will be no proxy if the ui
2124
+ // has never been accessed
2125
+ if (proxy && !isHasMany) {
2126
+ // @ts-expect-error unsure why this is not resolving the boolean but async belongsTo is weird
2127
+ if (proxy.content && proxy.content.isDestroying) {
2128
+ proxy.set('content', null);
2129
+ }
2130
+ recordExt.store.notifications._flush();
2131
+ }
2132
+ throw error;
2133
+ }
2134
+ if (isHasMany) {
2135
+ value.isLoaded = true;
2136
+ } else {
2137
+ recordExt.store.notifications._flush();
2138
+ }
2139
+ relationship.state.hasFailedLoadAttempt = false;
2140
+ // only set to not stale if no error is thrown
2141
+ relationship.state.isStale = false;
2142
+ return isHasMany || !value ? value : recordExt.store.peekRecord(value);
2143
+ }
2144
+ function extractIdentifierFromRecord(record) {
2145
+ if (!record) {
2146
+ return null;
2147
+ }
2148
+ return recordIdentifierFor(record);
2149
+ }
2150
+ function anyUnloaded(store, relationship) {
2151
+ assertPrivateStore(store);
2152
+ const graph = store._graph;
2153
+ (test => {
2154
+ if (!test) {
2155
+ throw new Error(`Expected a Graph instance to be available`);
2156
+ }
2157
+ })(graph);
2158
+ const relationshipData = graph.getData(relationship.identifier, relationship.definition.key);
2159
+ const state = relationshipData.data;
2160
+ const cache = store._instanceCache;
2161
+ const unloaded = state?.find(s => {
2162
+ const isLoaded = cache.recordIsLoaded(s, true);
2163
+ return !isLoaded;
2164
+ });
2165
+ return unloaded || false;
2166
+ }
2167
+ function areAllInverseRecordsLoaded(store, resource) {
2168
+ assertPrivateStore(store);
2169
+ const instanceCache = store._instanceCache;
2170
+ const identifiers = resource.data;
2171
+ if (Array.isArray(identifiers)) {
2172
+ (test => {
2173
+ if (!test) {
2174
+ throw new Error(`Expected stable identifiers`);
2175
+ }
2176
+ })(identifiers.every(isResourceKey));
2177
+ // treat as collection
2178
+ // check for unloaded records
2179
+ return identifiers.every(identifier => instanceCache.recordIsLoaded(identifier));
2180
+ }
2181
+
2182
+ // treat as single resource
2183
+ if (!identifiers) return true;
2184
+ (test => {
2185
+ if (!test) {
2186
+ throw new Error(`Expected stable identifiers`);
2187
+ }
2188
+ })(isResourceKey(identifiers));
2189
+ return instanceCache.recordIsLoaded(identifiers);
2190
+ }
2191
+ function isBelongsTo(relationship) {
2192
+ return relationship.definition.kind === 'belongsTo';
2193
+ }
2194
+ function getField(context, key) {
2195
+ const {
2196
+ identifier,
2197
+ store
2198
+ } = context;
2199
+ return store.schema.fields(identifier).get(key) ?? store.schema.cacheFields?.(identifier).get(key);
2200
+ }
2201
+ function getRealFieldName(context, key) {
2202
+ const field = getField(context, key);
2203
+ return field ? field.sourceKey ?? field.name : key;
2204
+ }
2205
+
2206
+ // we force the type here to our own construct because mixin and extend patterns
2207
+ // lose generic signatures. We also do this because we need to Omit `clear` from
2208
+ // the type of ArrayProxy as we override it's signature.
2209
+ const ArrayProxyWithCustomOverrides = ArrayProxy;
2210
+
2211
+ /**
2212
+ Holds validation errors for a given record, organized by attribute names.
2213
+
2214
+ This class is not directly instantiable.
2215
+
2216
+ Every `Model` has an `errors` property that is an instance of
2217
+ `Errors`. This can be used to display validation error
2218
+ messages returned from the server when a `record.save()` rejects.
2219
+
2220
+ For Example, if you had a `User` model that looked like this:
2221
+
2222
+ ```js [app/models/user.js]
2223
+ import { Model, attr } from '@warp-drive/legacy/model';
2224
+
2225
+ export default class UserModel extends Model {
2226
+ @attr('string') username;
2227
+ @attr('string') email;
2228
+ }
2229
+ ```
2230
+ And you attempted to save a record that did not validate on the backend:
2231
+
2232
+ ```javascript
2233
+ let user = store.createRecord('user', {
2234
+ username: 'tomster',
2235
+ email: 'invalidEmail'
2236
+ });
2237
+ user.save();
2238
+ ```
2239
+
2240
+ Your backend would be expected to return an error response that described
2241
+ the problem, so that error messages can be generated on the app.
2242
+
2243
+ API responses will be translated into instances of `Errors` differently,
2244
+ depending on the specific combination of adapter and serializer used. You
2245
+ may want to check the documentation or the source code of the libraries
2246
+ that you are using, to know how they expect errors to be communicated.
2247
+
2248
+ Errors can be displayed to the user by accessing their property name
2249
+ to get an array of all the error objects for that property. Each
2250
+ error object is a JavaScript object with two keys:
2251
+
2252
+ - `message` A string containing the error message from the backend
2253
+ - `attribute` The name of the property associated with this error message
2254
+
2255
+ ```handlebars
2256
+ <label>Username: <Input @value={{@model.username}} /> </label>
2257
+ {{#each @model.errors.username as |error|}}
2258
+ <div class="error">
2259
+ {{error.message}}
2260
+ </div>
2261
+ {{/each}}
2262
+
2263
+ <label>Email: <Input @value={{@model.email}} /> </label>
2264
+ {{#each @model.errors.email as |error|}}
2265
+ <div class="error">
2266
+ {{error.message}}
2267
+ </div>
2268
+ {{/each}}
2269
+ ```
2270
+
2271
+ You can also access the special `messages` property on the error
2272
+ object to get an array of all the error strings.
2273
+
2274
+ ```handlebars
2275
+ {{#each @model.errors.messages as |message|}}
2276
+ <div class="error">
2277
+ {{message}}
2278
+ </div>
2279
+ {{/each}}
2280
+ ```
2281
+
2282
+ @class Errors
2283
+ @public
2284
+ */
2285
+ class Errors extends ArrayProxyWithCustomOverrides {
2286
+ /**
2287
+ @property errorsByAttributeName
2288
+ @type {MapWithDefault}
2289
+ @private
2290
+ */
2291
+ get errorsByAttributeName() {
2292
+ return new Map();
2293
+ }
2294
+
2295
+ /**
2296
+ Returns errors for a given attribute
2297
+ ```javascript
2298
+ let user = store.createRecord('user', {
2299
+ username: 'tomster',
2300
+ email: 'invalidEmail'
2301
+ });
2302
+ user.save().catch(function(){
2303
+ user.errors.errorsFor('email'); // returns:
2304
+ // [{attribute: "email", message: "Doesn't look like a valid email."}]
2305
+ });
2306
+ ```
2307
+ @public
2308
+ @param {String} attribute
2309
+ @return {Array}
2310
+ */
2311
+ static {
2312
+ decorateMethodV2(this.prototype, "errorsByAttributeName", [computed()]);
2313
+ }
2314
+ errorsFor(attribute) {
2315
+ const map = this.errorsByAttributeName;
2316
+ let errors = map.get(attribute);
2317
+ if (errors === undefined) {
2318
+ errors = A();
2319
+ map.set(attribute, errors);
2320
+ }
2321
+
2322
+ // Errors may be a native array with extensions turned on. Since we access
2323
+ // the array via a method, and not a computed or using `Ember.get`, it does
2324
+ // not entangle properly with autotracking, so we entangle manually by
2325
+ // getting the `[]` property.
2326
+ get(errors, '[]');
2327
+ return errors;
2328
+ }
2329
+
2330
+ /**
2331
+ An array containing all of the error messages for this
2332
+ record. This is useful for displaying all errors to the user.
2333
+ ```handlebars
2334
+ {{#each @model.errors.messages as |message|}}
2335
+ <div class="error">
2336
+ {{message}}
2337
+ </div>
2338
+ {{/each}}
2339
+ ```
2340
+ @property messages
2341
+ @public
2342
+ @type {Array}
2343
+ */
2344
+ static {
2345
+ decorateFieldV2(this.prototype, "messages", [mapBy('content', 'message')]);
2346
+ }
2347
+ #messages = (initializeDeferredDecorator(this, "messages"), void 0);
2348
+ /**
2349
+ @property content
2350
+ @type {Array}
2351
+ @private
2352
+ */
2353
+ get content() {
2354
+ return A();
2355
+ }
2356
+
2357
+ /**
2358
+ @private
2359
+ */
2360
+ static {
2361
+ decorateMethodV2(this.prototype, "content", [computed()]);
2362
+ }
2363
+ unknownProperty(attribute) {
2364
+ const errors = this.errorsFor(attribute);
2365
+ if (errors.length === 0) {
2366
+ return undefined;
2367
+ }
2368
+ return errors;
2369
+ }
2370
+
2371
+ /**
2372
+ Total number of errors.
2373
+ @property length
2374
+ @type {Number}
2375
+ @public
2376
+ @readonly
2377
+ */
2378
+
2379
+ /**
2380
+ `true` if we have no errors.
2381
+ @property isEmpty
2382
+ @type {Boolean}
2383
+ @public
2384
+ @readonly
2385
+ */
2386
+ static {
2387
+ decorateFieldV2(this.prototype, "isEmpty", [not('length')]);
2388
+ }
2389
+ #isEmpty = (initializeDeferredDecorator(this, "isEmpty"), void 0);
2390
+ /**
2391
+ Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
2392
+ the record and transition the record into an `invalid` state.
2393
+ Example
2394
+ ```javascript
2395
+ let errors = user.errors;
2396
+ // add multiple errors
2397
+ errors.add('password', [
2398
+ 'Must be at least 12 characters',
2399
+ 'Must contain at least one symbol',
2400
+ 'Cannot contain your name'
2401
+ ]);
2402
+ errors.errorsFor('password');
2403
+ // =>
2404
+ // [
2405
+ // { attribute: 'password', message: 'Must be at least 12 characters' },
2406
+ // { attribute: 'password', message: 'Must contain at least one symbol' },
2407
+ // { attribute: 'password', message: 'Cannot contain your name' },
2408
+ // ]
2409
+ // add a single error
2410
+ errors.add('username', 'This field is required');
2411
+ errors.errorsFor('username');
2412
+ // =>
2413
+ // [
2414
+ // { attribute: 'username', message: 'This field is required' },
2415
+ // ]
2416
+ ```
2417
+ @public
2418
+ @param {String} attribute - the property name of an attribute or relationship
2419
+ @param {string[]|string} messages - an error message or array of error messages for the attribute
2420
+ */
2421
+ add(attribute, messages) {
2422
+ const errors = this._findOrCreateMessages(attribute, messages);
2423
+ this.addObjects(errors);
2424
+ this.errorsFor(attribute).addObjects(errors);
2425
+ this.__record.currentState.notify('isValid');
2426
+ this.notifyPropertyChange(attribute);
2427
+ }
2428
+
2429
+ /**
2430
+ @private
2431
+ */
2432
+ _findOrCreateMessages(attribute, messages) {
2433
+ const errors = this.errorsFor(attribute);
2434
+ const messagesArray = Array.isArray(messages) ? messages : [messages];
2435
+ const _messages = new Array(messagesArray.length);
2436
+ for (let i = 0; i < messagesArray.length; i++) {
2437
+ const message = messagesArray[i];
2438
+ const err = errors.findBy('message', message);
2439
+ if (err) {
2440
+ _messages[i] = err;
2441
+ } else {
2442
+ _messages[i] = {
2443
+ attribute: attribute,
2444
+ message
2445
+ };
2446
+ }
2447
+ }
2448
+ return _messages;
2449
+ }
2450
+
2451
+ /**
2452
+ Manually removes all errors for a given member from the record.
2453
+ This will transition the record into a `valid` state, and
2454
+ triggers the `becameValid` event and lifecycle method.
2455
+ Example:
2456
+ ```javascript
2457
+ let errors = user.errors;
2458
+ errors.add('phone', ['error-1', 'error-2']);
2459
+ errors.errorsFor('phone');
2460
+ // =>
2461
+ // [
2462
+ // { attribute: 'phone', message: 'error-1' },
2463
+ // { attribute: 'phone', message: 'error-2' },
2464
+ // ]
2465
+ errors.remove('phone');
2466
+ errors.errorsFor('phone');
2467
+ // => undefined
2468
+ ```
2469
+ @public
2470
+ @param {String} member - the property name of an attribute or relationship
2471
+ */
2472
+ remove(attribute) {
2473
+ if (this.isEmpty) {
2474
+ return;
2475
+ }
2476
+ const content = this.rejectBy('attribute', attribute);
2477
+ this.content.setObjects(content);
2478
+
2479
+ // Although errorsByAttributeName.delete is technically enough to sync errors state, we also
2480
+ // must mutate the array as well for autotracking
2481
+ const errors = this.errorsFor(attribute);
2482
+ for (let i = 0; i < errors.length; i++) {
2483
+ if (errors[i].attribute === attribute) {
2484
+ // .replace from Ember.NativeArray is necessary. JS splice will not work.
2485
+ errors.replace(i, 1);
2486
+ }
2487
+ }
2488
+ this.errorsByAttributeName.delete(attribute);
2489
+ this.__record.currentState.notify('isValid');
2490
+ this.notifyPropertyChange(attribute);
2491
+ this.notifyPropertyChange('length');
2492
+ }
2493
+
2494
+ /**
2495
+ Manually clears all errors for the record.
2496
+ This will transition the record into a `valid` state, and
2497
+ will trigger the `becameValid` event and lifecycle method.
2498
+ Example:
2499
+ ```javascript
2500
+ let errors = user.errors;
2501
+ errors.add('username', ['error-a']);
2502
+ errors.add('phone', ['error-1', 'error-2']);
2503
+ errors.errorsFor('username');
2504
+ // =>
2505
+ // [
2506
+ // { attribute: 'username', message: 'error-a' },
2507
+ // ]
2508
+ errors.errorsFor('phone');
2509
+ // =>
2510
+ // [
2511
+ // { attribute: 'phone', message: 'error-1' },
2512
+ // { attribute: 'phone', message: 'error-2' },
2513
+ // ]
2514
+ errors.clear();
2515
+ errors.errorsFor('username');
2516
+ // => undefined
2517
+ errors.errorsFor('phone');
2518
+ // => undefined
2519
+ errors.messages
2520
+ // => []
2521
+ ```
2522
+ @public
2523
+ */
2524
+ clear() {
2525
+ if (this.isEmpty) {
2526
+ return;
2527
+ }
2528
+ const errorsByAttributeName = this.errorsByAttributeName;
2529
+ const attributes = [];
2530
+ errorsByAttributeName.forEach(function (_, attribute) {
2531
+ attributes.push(attribute);
2532
+ });
2533
+ errorsByAttributeName.clear();
2534
+ attributes.forEach(attribute => {
2535
+ this.notifyPropertyChange(attribute);
2536
+ });
2537
+ this.__record.currentState.notify('isValid');
2538
+ super.clear();
2539
+ }
2540
+
2541
+ /**
2542
+ Checks if there are error messages for the given attribute.
2543
+ ```js [app/controllers/user/edit.js]
2544
+ export default class UserEditController extends Controller {
2545
+ @action
2546
+ save(user) {
2547
+ if (user.errors.has('email')) {
2548
+ return alert('Please update your email before attempting to save.');
2549
+ }
2550
+ user.save();
2551
+ }
2552
+ }
2553
+ ```
2554
+ @public
2555
+ @param {String} attribute
2556
+ @return {Boolean} true if there some errors on given attribute
2557
+ */
2558
+ has(attribute) {
2559
+ return this.errorsFor(attribute).length > 0;
2560
+ }
2561
+ }
2562
+ export { Errors as E, LEGACY_SUPPORT as L, PromiseBelongsTo as P, PromiseManyArray as a, lookupLegacySupport as l };