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

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