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

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