@warp-drive/legacy 5.6.0-alpha.11

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