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