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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/README.md +22 -38
  2. package/declarations/configure.d.ts +1 -1
  3. package/declarations/graph/-private/-edge-definition.d.ts +12 -2
  4. package/declarations/index.d.ts +14 -9
  5. package/declarations/reactive/-private/default-mode.d.ts +1 -1
  6. package/declarations/reactive/-private/fields/extension.d.ts +1 -1
  7. package/declarations/reactive/-private/fields/managed-array.d.ts +2 -2
  8. package/declarations/reactive/-private/fields/managed-object.d.ts +1 -1
  9. package/declarations/reactive/-private/record.d.ts +10 -1
  10. package/declarations/reactive/-private.d.ts +1 -0
  11. package/declarations/reactive.d.ts +11 -7
  12. package/declarations/request/-private/types.d.ts +1 -1
  13. package/declarations/signals/-leaked.d.ts +2 -0
  14. package/declarations/signals/-private.d.ts +6 -0
  15. package/declarations/{store/-private/new-core-tmp → signals}/promise-state.d.ts +1 -1
  16. package/declarations/{store/-private/new-core-tmp → signals}/request-state.d.ts +6 -6
  17. package/declarations/{store/-private/new-core-tmp → signals}/request-subscription.d.ts +4 -4
  18. package/declarations/store/-private/cache-handler/types.d.ts +2 -16
  19. package/declarations/store/-private/caches/instance-cache.d.ts +1 -1
  20. package/declarations/store/-private/managers/cache-manager.d.ts +1 -14
  21. package/declarations/store/-private/managers/notification-manager.d.ts +1 -1
  22. package/declarations/store/-private/record-arrays/legacy-many-array.d.ts +1 -1
  23. package/declarations/store/-private/record-arrays/resource-array.d.ts +1 -1
  24. package/declarations/store/-private/store-service.d.ts +2 -2
  25. package/declarations/store/-private.d.ts +0 -6
  26. package/declarations/store/deprecated/-private.d.ts +2 -2
  27. package/declarations/store/deprecated/store.d.ts +1 -1
  28. package/declarations/store.d.ts +1 -0
  29. package/declarations/types/cache.d.ts +2 -2
  30. package/declarations/types/record.d.ts +132 -0
  31. package/declarations/types/request.d.ts +22 -8
  32. package/declarations/types/schema/fields.d.ts +26 -13
  33. package/declarations/types/schema/schema-service.d.ts +4 -4
  34. package/declarations/types/spec/document.d.ts +34 -0
  35. package/dist/configure-DPUFCemT.js +1940 -0
  36. package/dist/configure.js +2 -1
  37. package/dist/{request-oqoLC9rz.js → future-BKkJJkj7.js} +1 -48
  38. package/dist/graph/-private.js +15 -5
  39. package/dist/{index-B1cSRj-N.js → index-CQP2NSqg.js} +63 -1812
  40. package/dist/index.js +5 -5
  41. package/dist/reactive/-private.js +1 -1
  42. package/dist/reactive.js +4 -129
  43. package/dist/request.js +49 -1
  44. package/dist/signals/-leaked.js +1 -0
  45. package/dist/store/-private.js +1 -2
  46. package/dist/symbols-3C1OkYtZ.js +39 -0
  47. package/dist/types/-private.js +1 -1
  48. package/dist/types/record.js +127 -0
  49. package/dist/types/request.js +11 -7
  50. package/dist/unpkg/dev/-leaked-Co0EI6Go.js +1939 -0
  51. package/dist/unpkg/dev/build-config/babel-macros.js +1 -0
  52. package/dist/unpkg/dev/build-config/canary-features.js +1 -0
  53. package/dist/unpkg/dev/build-config/debugging.js +1 -0
  54. package/dist/unpkg/dev/build-config/deprecations.js +1 -0
  55. package/dist/unpkg/dev/build-config/env.js +1 -0
  56. package/dist/unpkg/dev/build-config/macros.js +1 -0
  57. package/dist/unpkg/dev/build-config.js +1 -0
  58. package/dist/unpkg/dev/configure.js +1 -0
  59. package/dist/unpkg/dev/future-DFfOzSoe.js +672 -0
  60. package/dist/unpkg/dev/graph/-private.js +3132 -0
  61. package/dist/unpkg/dev/index-BzcBOnw9.js +9392 -0
  62. package/dist/unpkg/dev/index.js +6 -0
  63. package/dist/unpkg/dev/reactive/-private.js +1 -0
  64. package/dist/unpkg/dev/reactive.js +3 -0
  65. package/dist/unpkg/dev/request.js +49 -0
  66. package/dist/unpkg/dev/runtime-E1M51_-O.js +135 -0
  67. package/dist/unpkg/dev/signals/-leaked.js +1 -0
  68. package/dist/unpkg/dev/store/-private.js +55 -0
  69. package/dist/unpkg/dev/store.js +558 -0
  70. package/dist/unpkg/dev/types/-private.js +69 -0
  71. package/dist/unpkg/dev/types/cache/aliases.js +0 -0
  72. package/dist/unpkg/dev/types/cache/change.js +0 -0
  73. package/dist/unpkg/dev/types/cache/mutations.js +0 -0
  74. package/dist/unpkg/dev/types/cache/operations.js +0 -0
  75. package/dist/unpkg/dev/types/cache/relationship.js +0 -0
  76. package/dist/unpkg/dev/types/cache.js +0 -0
  77. package/dist/unpkg/dev/types/graph.js +0 -0
  78. package/dist/unpkg/dev/types/identifier.js +61 -0
  79. package/dist/unpkg/dev/types/json/raw.js +0 -0
  80. package/dist/unpkg/dev/types/params.js +0 -0
  81. package/dist/unpkg/dev/types/record.js +191 -0
  82. package/dist/unpkg/dev/types/request.js +77 -0
  83. package/dist/unpkg/dev/types/runtime.js +34 -0
  84. package/dist/unpkg/dev/types/schema/concepts.js +0 -0
  85. package/dist/unpkg/dev/types/schema/fields.js +505 -0
  86. package/dist/unpkg/dev/types/schema/fields.type-test.js +0 -0
  87. package/dist/unpkg/dev/types/schema/schema-service.js +0 -0
  88. package/dist/unpkg/dev/types/spec/document.js +0 -0
  89. package/dist/unpkg/dev/types/spec/error.js +0 -0
  90. package/dist/unpkg/dev/types/spec/json-api-raw.js +0 -0
  91. package/dist/unpkg/dev/types/symbols.js +84 -0
  92. package/dist/unpkg/dev/types/utils.js +0 -0
  93. package/dist/unpkg/dev/types.js +0 -0
  94. package/dist/unpkg/dev/utils/string.js +91 -0
  95. package/dist/unpkg/dev-deprecated/-leaked-DjMeRqdU.js +1939 -0
  96. package/dist/unpkg/dev-deprecated/-private-3C1OkYtZ.js +39 -0
  97. package/dist/unpkg/dev-deprecated/build-config/babel-macros.js +1 -0
  98. package/dist/unpkg/dev-deprecated/build-config/canary-features.js +1 -0
  99. package/dist/unpkg/dev-deprecated/build-config/debugging.js +1 -0
  100. package/dist/unpkg/dev-deprecated/build-config/deprecations.js +1 -0
  101. package/dist/unpkg/dev-deprecated/build-config/env.js +1 -0
  102. package/dist/unpkg/dev-deprecated/build-config/macros.js +1 -0
  103. package/dist/unpkg/dev-deprecated/build-config.js +1 -0
  104. package/dist/unpkg/dev-deprecated/configure.js +1 -0
  105. package/dist/unpkg/dev-deprecated/future-DFfOzSoe.js +672 -0
  106. package/dist/unpkg/dev-deprecated/graph/-private.js +3327 -0
  107. package/dist/unpkg/dev-deprecated/index-6TnTv-WG.js +10007 -0
  108. package/dist/unpkg/dev-deprecated/index.js +5 -0
  109. package/dist/unpkg/dev-deprecated/reactive/-private.js +1 -0
  110. package/dist/unpkg/dev-deprecated/reactive.js +3 -0
  111. package/dist/unpkg/dev-deprecated/request.js +49 -0
  112. package/dist/unpkg/dev-deprecated/runtime-DAu5b0IR.js +135 -0
  113. package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -0
  114. package/dist/unpkg/dev-deprecated/store/-private.js +1 -0
  115. package/dist/unpkg/dev-deprecated/store.js +558 -0
  116. package/dist/unpkg/dev-deprecated/types/-private.js +69 -0
  117. package/dist/unpkg/dev-deprecated/types/cache/aliases.js +0 -0
  118. package/dist/unpkg/dev-deprecated/types/cache/change.js +0 -0
  119. package/dist/unpkg/dev-deprecated/types/cache/mutations.js +0 -0
  120. package/dist/unpkg/dev-deprecated/types/cache/operations.js +0 -0
  121. package/dist/unpkg/dev-deprecated/types/cache/relationship.js +0 -0
  122. package/dist/unpkg/dev-deprecated/types/cache.js +0 -0
  123. package/dist/unpkg/dev-deprecated/types/graph.js +0 -0
  124. package/dist/unpkg/dev-deprecated/types/identifier.js +61 -0
  125. package/dist/unpkg/dev-deprecated/types/json/raw.js +0 -0
  126. package/dist/unpkg/dev-deprecated/types/params.js +0 -0
  127. package/dist/unpkg/dev-deprecated/types/record.js +191 -0
  128. package/dist/unpkg/dev-deprecated/types/request.js +77 -0
  129. package/dist/unpkg/dev-deprecated/types/runtime.js +34 -0
  130. package/dist/unpkg/dev-deprecated/types/schema/concepts.js +0 -0
  131. package/dist/unpkg/dev-deprecated/types/schema/fields.js +505 -0
  132. package/dist/unpkg/dev-deprecated/types/schema/fields.type-test.js +0 -0
  133. package/dist/unpkg/dev-deprecated/types/schema/schema-service.js +0 -0
  134. package/dist/unpkg/dev-deprecated/types/spec/document.js +0 -0
  135. package/dist/unpkg/dev-deprecated/types/spec/error.js +0 -0
  136. package/dist/unpkg/dev-deprecated/types/spec/json-api-raw.js +0 -0
  137. package/dist/unpkg/dev-deprecated/types/symbols.js +84 -0
  138. package/dist/unpkg/dev-deprecated/types/utils.js +0 -0
  139. package/dist/unpkg/dev-deprecated/types.js +0 -0
  140. package/dist/unpkg/dev-deprecated/utils/string.js +91 -0
  141. package/dist/unpkg/prod/-leaked-DUONXQDB.js +1676 -0
  142. package/dist/unpkg/prod/-private-sql1_mdx.js +39 -0
  143. package/dist/unpkg/prod/build-config/babel-macros.js +1 -0
  144. package/dist/unpkg/prod/build-config/canary-features.js +1 -0
  145. package/dist/unpkg/prod/build-config/debugging.js +1 -0
  146. package/dist/unpkg/prod/build-config/deprecations.js +1 -0
  147. package/dist/unpkg/prod/build-config/env.js +1 -0
  148. package/dist/unpkg/prod/build-config/macros.js +1 -0
  149. package/dist/unpkg/prod/build-config.js +1 -0
  150. package/dist/unpkg/prod/configure.js +2 -0
  151. package/dist/unpkg/prod/graph/-private.js +2235 -0
  152. package/dist/unpkg/prod/handler-EU_8ncB2.js +1619 -0
  153. package/dist/unpkg/prod/index.js +483 -0
  154. package/dist/unpkg/prod/promise-cache-DIT8Ypjq.js +19 -0
  155. package/dist/unpkg/prod/reactive/-private.js +1 -0
  156. package/dist/unpkg/prod/reactive.js +30 -0
  157. package/dist/unpkg/prod/request-BrJSCG6r.js +421 -0
  158. package/dist/unpkg/prod/request.js +2 -0
  159. package/dist/unpkg/prod/schema-BSkHyoWz.js +5219 -0
  160. package/dist/unpkg/prod/signals/-leaked.js +1 -0
  161. package/dist/unpkg/prod/store/-private.js +126 -0
  162. package/dist/unpkg/prod/store.js +437 -0
  163. package/dist/unpkg/prod/types/-private.js +49 -0
  164. package/dist/unpkg/prod/types/cache/aliases.js +0 -0
  165. package/dist/unpkg/prod/types/cache/change.js +0 -0
  166. package/dist/unpkg/prod/types/cache/mutations.js +0 -0
  167. package/dist/unpkg/prod/types/cache/operations.js +0 -0
  168. package/dist/unpkg/prod/types/cache/relationship.js +0 -0
  169. package/dist/unpkg/prod/types/cache.js +0 -0
  170. package/dist/unpkg/prod/types/graph.js +0 -0
  171. package/dist/unpkg/prod/types/identifier.js +61 -0
  172. package/dist/unpkg/prod/types/json/raw.js +0 -0
  173. package/dist/unpkg/prod/types/params.js +0 -0
  174. package/dist/unpkg/prod/types/record.js +191 -0
  175. package/dist/unpkg/prod/types/request.js +77 -0
  176. package/dist/unpkg/prod/types/runtime.js +34 -0
  177. package/dist/unpkg/prod/types/schema/concepts.js +0 -0
  178. package/dist/unpkg/prod/types/schema/fields.js +505 -0
  179. package/dist/unpkg/prod/types/schema/fields.type-test.js +0 -0
  180. package/dist/unpkg/prod/types/schema/schema-service.js +0 -0
  181. package/dist/unpkg/prod/types/spec/document.js +0 -0
  182. package/dist/unpkg/prod/types/spec/error.js +0 -0
  183. package/dist/unpkg/prod/types/spec/json-api-raw.js +0 -0
  184. package/dist/unpkg/prod/types/symbols.js +84 -0
  185. package/dist/unpkg/prod/types/utils.js +0 -0
  186. package/dist/unpkg/prod/types.js +0 -0
  187. package/dist/unpkg/prod/utils/string.js +72 -0
  188. package/dist/unpkg/prod-deprecated/-leaked-DRNv9VIX.js +1676 -0
  189. package/dist/unpkg/prod-deprecated/-private-3C1OkYtZ.js +39 -0
  190. package/dist/unpkg/prod-deprecated/build-config/babel-macros.js +1 -0
  191. package/dist/unpkg/prod-deprecated/build-config/canary-features.js +1 -0
  192. package/dist/unpkg/prod-deprecated/build-config/debugging.js +1 -0
  193. package/dist/unpkg/prod-deprecated/build-config/deprecations.js +1 -0
  194. package/dist/unpkg/prod-deprecated/build-config/env.js +1 -0
  195. package/dist/unpkg/prod-deprecated/build-config/macros.js +1 -0
  196. package/dist/unpkg/prod-deprecated/build-config.js +1 -0
  197. package/dist/unpkg/prod-deprecated/configure.js +2 -0
  198. package/dist/unpkg/prod-deprecated/graph/-private.js +2408 -0
  199. package/dist/unpkg/prod-deprecated/handler-CCIu4sQ3.js +334 -0
  200. package/dist/unpkg/prod-deprecated/hooks-Dv4Np0MY.js +26 -0
  201. package/dist/unpkg/prod-deprecated/index.js +483 -0
  202. package/dist/unpkg/prod-deprecated/promise-cache-DIT8Ypjq.js +19 -0
  203. package/dist/unpkg/prod-deprecated/reactive/-private.js +1 -0
  204. package/dist/unpkg/prod-deprecated/reactive.js +5 -0
  205. package/dist/unpkg/prod-deprecated/request-BrJSCG6r.js +421 -0
  206. package/dist/unpkg/prod-deprecated/request.js +2 -0
  207. package/dist/unpkg/prod-deprecated/schema-CJcjHv0E.js +6939 -0
  208. package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -0
  209. package/dist/unpkg/prod-deprecated/store/-private.js +88 -0
  210. package/dist/unpkg/prod-deprecated/store.js +437 -0
  211. package/dist/unpkg/prod-deprecated/types/-private.js +49 -0
  212. package/dist/unpkg/prod-deprecated/types/cache/aliases.js +0 -0
  213. package/dist/unpkg/prod-deprecated/types/cache/change.js +0 -0
  214. package/dist/unpkg/prod-deprecated/types/cache/mutations.js +0 -0
  215. package/dist/unpkg/prod-deprecated/types/cache/operations.js +0 -0
  216. package/dist/unpkg/prod-deprecated/types/cache/relationship.js +0 -0
  217. package/dist/unpkg/prod-deprecated/types/cache.js +0 -0
  218. package/dist/unpkg/prod-deprecated/types/graph.js +0 -0
  219. package/dist/unpkg/prod-deprecated/types/identifier.js +61 -0
  220. package/dist/unpkg/prod-deprecated/types/json/raw.js +0 -0
  221. package/dist/unpkg/prod-deprecated/types/params.js +0 -0
  222. package/dist/unpkg/prod-deprecated/types/record.js +191 -0
  223. package/dist/unpkg/prod-deprecated/types/request.js +77 -0
  224. package/dist/unpkg/prod-deprecated/types/runtime.js +34 -0
  225. package/dist/unpkg/prod-deprecated/types/schema/concepts.js +0 -0
  226. package/dist/unpkg/prod-deprecated/types/schema/fields.js +505 -0
  227. package/dist/unpkg/prod-deprecated/types/schema/fields.type-test.js +0 -0
  228. package/dist/unpkg/prod-deprecated/types/schema/schema-service.js +0 -0
  229. package/dist/unpkg/prod-deprecated/types/spec/document.js +0 -0
  230. package/dist/unpkg/prod-deprecated/types/spec/error.js +0 -0
  231. package/dist/unpkg/prod-deprecated/types/spec/json-api-raw.js +0 -0
  232. package/dist/unpkg/prod-deprecated/types/symbols.js +84 -0
  233. package/dist/unpkg/prod-deprecated/types/utils.js +0 -0
  234. package/dist/unpkg/prod-deprecated/types.js +0 -0
  235. package/dist/unpkg/prod-deprecated/utils/string.js +72 -0
  236. package/logos/README.md +2 -2
  237. package/logos/logo-yellow-slab.svg +1 -0
  238. package/logos/word-mark-black.svg +1 -0
  239. package/logos/word-mark-white.svg +1 -0
  240. package/package.json +11 -3
  241. package/declarations/store/-private/new-core-tmp/expensive-subscription.d.ts +0 -24
  242. package/dist/configure-C3x8YXzL.js +0 -181
  243. package/logos/NCC-1701-a-blue.svg +0 -4
  244. package/logos/NCC-1701-a-gold.svg +0 -4
  245. package/logos/NCC-1701-a-gold_100.svg +0 -1
  246. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  247. package/logos/NCC-1701-a.svg +0 -4
  248. package/logos/docs-badge.svg +0 -2
  249. package/logos/ember-data-logo-dark.svg +0 -12
  250. package/logos/ember-data-logo-light.svg +0 -12
  251. package/logos/social1.png +0 -0
  252. package/logos/social2.png +0 -0
  253. package/logos/warp-drive-logo-dark.svg +0 -4
  254. package/logos/warp-drive-logo-gold.svg +0 -4
  255. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/configure.d.ts +0 -0
  256. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/internal.d.ts +0 -0
  257. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/signal.d.ts +0 -0
  258. /package/dist/{symbols-sql1_mdx.js → unpkg/dev/-private-sql1_mdx.js} +0 -0
@@ -0,0 +1,3327 @@
1
+ import { g as getGlobalConfig } from "../runtime-DAu5b0IR.js";
2
+ import { getOrSetGlobal, peekTransient, setTransient } from '../types/-private.js';
3
+
4
+ // Used by the store to normalize IDs entering the store. Despite the fact
5
+ // that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`),
6
+ // it is important that internally we use strings, since IDs may be serialized
7
+ // and lose type information. For example, Ember's router may put a record's
8
+ // ID into the URL, and if we later try to deserialize that URL and find the
9
+ // corresponding record, we will not know if it is a string or a number.
10
+ function coerceId(id) {
11
+ {
12
+ let normalized;
13
+ if (id === null || id === undefined || id === '') {
14
+ normalized = null;
15
+ } else {
16
+ normalized = String(id);
17
+ }
18
+ !(normalized === id) && console.warn(`The resource id '<${typeof id}> ${String(id)} ' is not normalized. Update your application code to use '${JSON.stringify(normalized)}' instead.`);
19
+ return normalized;
20
+ }
21
+ }
22
+ function getStore(wrapper) {
23
+ (test => {
24
+ if (!test) {
25
+ throw new Error(`expected a private _store property`);
26
+ }
27
+ })('_store' in wrapper);
28
+ return wrapper._store;
29
+ }
30
+ function expandingGet(cache, key1, key2) {
31
+ const mainCache = cache[key1] = cache[key1] || Object.create(null);
32
+ return mainCache[key2];
33
+ }
34
+ function expandingSet(cache, key1, key2, value) {
35
+ const mainCache = cache[key1] = cache[key1] || Object.create(null);
36
+ mainCache[key2] = value;
37
+ }
38
+ function assertValidRelationshipPayload(graph, op) {
39
+ const relationship = graph.get(op.record, op.field);
40
+ (test => {
41
+ if (!test) {
42
+ throw new Error(`Cannot update an implicit relationship`);
43
+ }
44
+ })(isHasMany(relationship) || isBelongsTo(relationship));
45
+ const payload = op.value;
46
+ const {
47
+ definition,
48
+ identifier,
49
+ state
50
+ } = relationship;
51
+ const {
52
+ type
53
+ } = identifier;
54
+ const {
55
+ field
56
+ } = op;
57
+ const {
58
+ isAsync,
59
+ kind
60
+ } = definition;
61
+ if (payload.links) {
62
+ console.warn(`You pushed a record of type '${type}' with a relationship '${field}' configured as 'async: false'. You've included a link but no primary data, this may be an error in your payload. WarpDrive will treat this relationship as known-to-be-empty.`, isAsync || !!payload.data || state.hasReceivedData, {
63
+ id: 'ds.store.push-link-for-sync-relationship'
64
+ });
65
+ } else if (payload.data) {
66
+ if (kind === 'belongsTo') {
67
+ (test => {
68
+ if (!test) {
69
+ throw new Error(`A ${type} record was pushed into the store with the value of ${field} being ${inspect(payload.data)}, but ${field} is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.`);
70
+ }
71
+ })(!Array.isArray(payload.data));
72
+ assertRelationshipData(getStore(graph.store), identifier, payload.data, definition);
73
+ } else if (kind === 'hasMany') {
74
+ (test => {
75
+ if (!test) {
76
+ throw new Error(`A ${type} record was pushed into the store with the value of ${field} being '${inspect(payload.data)}', but ${field} is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.`);
77
+ }
78
+ })(Array.isArray(payload.data));
79
+ if (Array.isArray(payload.data)) {
80
+ for (let i = 0; i < payload.data.length; i++) {
81
+ assertRelationshipData(getStore(graph.store), identifier, payload.data[i], definition);
82
+ }
83
+ }
84
+ }
85
+ }
86
+ }
87
+ function inspect(value) {
88
+ const type = typeof value;
89
+ if (value === null) {
90
+ return 'null';
91
+ }
92
+ if (type !== 'object') {
93
+ return type;
94
+ }
95
+ if (Array.isArray(value)) {
96
+ return 'Array';
97
+ }
98
+ if (value instanceof Date) {
99
+ return 'Date';
100
+ }
101
+ if (value instanceof RegExp) {
102
+ return 'RegExp';
103
+ }
104
+ if (value instanceof Map) {
105
+ return 'Map';
106
+ }
107
+ if (value instanceof Set) {
108
+ return 'Set';
109
+ }
110
+ return 'object';
111
+ }
112
+ function checkIfNew(store, resourceKey) {
113
+ if (!resourceKey.id) {
114
+ return true;
115
+ }
116
+ return store.cache.isNew(resourceKey);
117
+ }
118
+ function isBelongsTo(relationship) {
119
+ return relationship.definition.kind === 'belongsTo';
120
+ }
121
+ function isImplicit(relationship) {
122
+ return relationship.definition.isImplicit;
123
+ }
124
+ function isHasMany(relationship) {
125
+ return relationship.definition.kind === 'hasMany';
126
+ }
127
+ function forAllRelatedIdentifiers(rel, cb) {
128
+ if (isBelongsTo(rel)) {
129
+ if (rel.remoteState) {
130
+ cb(rel.remoteState);
131
+ }
132
+ if (rel.localState && rel.localState !== rel.remoteState) {
133
+ cb(rel.localState);
134
+ }
135
+ } else if (isHasMany(rel)) {
136
+ // TODO
137
+ // rel.remoteMembers.forEach(cb);
138
+ // might be simpler if performance is not a concern
139
+ for (let i = 0; i < rel.remoteState.length; i++) {
140
+ const inverseIdentifier = rel.remoteState[i];
141
+ cb(inverseIdentifier);
142
+ }
143
+ rel.additions?.forEach(cb);
144
+ } else {
145
+ rel.localMembers.forEach(cb);
146
+ rel.remoteMembers.forEach(inverseIdentifier => {
147
+ if (!rel.localMembers.has(inverseIdentifier)) {
148
+ cb(inverseIdentifier);
149
+ }
150
+ });
151
+ }
152
+ }
153
+
154
+ /*
155
+ Removes the given identifier from BOTH remote AND local state.
156
+
157
+ This method is useful when either a deletion or a rollback on a new record
158
+ needs to entirely purge itself from an inverse relationship.
159
+ */
160
+ function removeIdentifierCompletelyFromRelationship(graph, relationship, value, silenceNotifications) {
161
+ if (isBelongsTo(relationship)) {
162
+ if (relationship.remoteState === value) {
163
+ relationship.remoteState = null;
164
+ }
165
+ if (relationship.localState === value) {
166
+ relationship.localState = null;
167
+ // This allows dematerialized inverses to be rematerialized
168
+ // we shouldn't be notifying here though, figure out where
169
+ // a notification was missed elsewhere.
170
+ {
171
+ notifyChange(graph, relationship);
172
+ }
173
+ }
174
+ } else if (isHasMany(relationship)) {
175
+ relationship.remoteMembers.delete(value);
176
+ relationship.additions?.delete(value);
177
+ const wasInRemovals = relationship.removals?.delete(value);
178
+ const canonicalIndex = relationship.remoteState.indexOf(value);
179
+ if (canonicalIndex !== -1) {
180
+ relationship.remoteState.splice(canonicalIndex, 1);
181
+ }
182
+ if (!wasInRemovals) {
183
+ const currentIndex = relationship.localState?.indexOf(value);
184
+ if (currentIndex !== -1 && currentIndex !== undefined) {
185
+ relationship.localState.splice(currentIndex, 1);
186
+ // This allows dematerialized inverses to be rematerialized
187
+ // we shouldn't be notifying here though, figure out where
188
+ // a notification was missed elsewhere.
189
+ {
190
+ notifyChange(graph, relationship);
191
+ }
192
+ }
193
+ }
194
+ } else {
195
+ relationship.remoteMembers.delete(value);
196
+ relationship.localMembers.delete(value);
197
+ }
198
+ }
199
+ function notifyChange(graph, relationship) {
200
+ if (!relationship.accessed) {
201
+ return;
202
+ }
203
+ const resourceKey = relationship.identifier;
204
+ const key = relationship.definition.key;
205
+ if (resourceKey === graph._removing) {
206
+ {
207
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
208
+ // eslint-disable-next-line no-console
209
+ console.log(`Graph: ignoring relationship change for removed identifier ${String(resourceKey)} ${key}`);
210
+ }
211
+ }
212
+ return;
213
+ }
214
+ {
215
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
216
+ // eslint-disable-next-line no-console
217
+ console.log(`Graph: notifying relationship change for ${String(resourceKey)} ${key}`);
218
+ }
219
+ }
220
+ graph.store.notifyChange(resourceKey, 'relationships', key);
221
+ }
222
+ function assertRelationshipData(store, resourceKey, data, meta) {
223
+ (test => {
224
+ if (!test) {
225
+ throw new Error(`A ${resourceKey.type} record was pushed into the store with the value of ${meta.key} being '${JSON.stringify(data)}', but ${meta.key} is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.`);
226
+ }
227
+ })(!Array.isArray(data));
228
+ (test => {
229
+ if (!test) {
230
+ throw new Error(`Encountered a relationship identifier without a type for the ${meta.kind} relationship '${meta.key}' on <${resourceKey.type}:${String(resourceKey.id)}>, expected an identifier with type '${meta.type}' but found\n\n'${JSON.stringify(data, null, 2)}'\n\nPlease check your serializer and make sure it is serializing the relationship payload into a JSON API format.`);
231
+ }
232
+ })(data === null || 'type' in data && typeof data.type === 'string' && data.type.length);
233
+ (test => {
234
+ if (!test) {
235
+ throw new Error(`Encountered a relationship identifier without an id for the ${meta.kind} relationship '${meta.key}' on <${resourceKey.type}:${String(resourceKey.id)}>, expected an identifier but found\n\n'${JSON.stringify(data, null, 2)}'\n\nPlease check your serializer and make sure it is serializing the relationship payload into a JSON API format.`);
236
+ }
237
+ })(data === null || !!coerceId(data.id));
238
+ if (data?.type === meta.type) {
239
+ (test => {
240
+ if (!test) {
241
+ throw new Error(`Missing Schema: Encountered a relationship identifier { type: '${data.type}', id: '${String(data.id)}' } for the '${resourceKey.type}.${meta.key}' ${meta.kind} relationship on <${resourceKey.type}:${String(resourceKey.id)}>, but no schema exists for that type.`);
242
+ }
243
+ })(store.schema.hasResource(data));
244
+ } else {
245
+ (test => {
246
+ if (!test) {
247
+ throw new Error(`Missing Schema: Encountered a relationship identifier with type '${data.type}' for the ${meta.kind} relationship '${meta.key}' on <${resourceKey.type}:${String(resourceKey.id)}>, Expected an identifier with type '${meta.type}'. No schema was found for '${data.type}'.`);
248
+ }
249
+ })(data === null || !data.type || store.schema.hasResource(data));
250
+ }
251
+ }
252
+ const RELATIONSHIP_KINDS = ['belongsTo', 'hasMany', 'resource', 'collection'];
253
+ function isLegacyField(field) {
254
+ return field.kind === 'belongsTo' || field.kind === 'hasMany';
255
+ }
256
+ function isRelationshipField(field) {
257
+ return RELATIONSHIP_KINDS.includes(field.kind);
258
+ }
259
+ function temporaryConvertToLegacy(field) {
260
+ return {
261
+ kind: field.kind === 'resource' ? 'belongsTo' : 'hasMany',
262
+ name: field.name,
263
+ type: field.type,
264
+ options: Object.assign({}, {
265
+ async: false,
266
+ inverse: null,
267
+ resetOnRemoteUpdate: false
268
+ }, field.options)
269
+ };
270
+ }
271
+
272
+ /**
273
+ *
274
+ * Given RHS (Right Hand Side)
275
+ *
276
+ * ```ts
277
+ * class User extends Model {
278
+ * @hasMany('animal', { async: false, inverse: 'owner' }) pets;
279
+ * }
280
+ * ```
281
+ *
282
+ * Given LHS (Left Hand Side)
283
+ *
284
+ * ```ts
285
+ * class Animal extends Model {
286
+ * @belongsTo('user', { async: false, inverse: 'pets' }) owner;
287
+ * }
288
+ * ```
289
+ *
290
+ * The UpgradedMeta for the RHS would be:
291
+ *
292
+ * ```ts
293
+ * {
294
+ * kind: 'hasMany',
295
+ * key: 'pets',
296
+ * type: 'animal',
297
+ * isAsync: false,
298
+ * isImplicit: false,
299
+ * isCollection: true,
300
+ * isPolymorphic: false,
301
+ * inverseKind: 'belongsTo',
302
+ * inverseKey: 'owner',
303
+ * inverseType: 'user',
304
+ * inverseIsAsync: false,
305
+ * inverseIsImplicit: false,
306
+ * inverseIsCollection: false,
307
+ * inverseIsPolymorphic: false,
308
+ * }
309
+ * ```
310
+ *
311
+ * The UpgradeMeta for the LHS would be:
312
+ *
313
+ * ```ts
314
+ * {
315
+ * kind: 'belongsTo',
316
+ * key: 'owner',
317
+ * type: 'user',
318
+ * isAsync: false,
319
+ * isImplicit: false,
320
+ * isCollection: false,
321
+ * isPolymorphic: false,
322
+ * inverseKind: 'hasMany',
323
+ * inverseKey: 'pets',
324
+ * inverseType: 'animal',
325
+ * inverseIsAsync: false,
326
+ * inverseIsImplicit: false,
327
+ * inverseIsCollection: true,
328
+ * inverseIsPolymorphic: false,
329
+ * }
330
+ * ```
331
+ *
332
+ * @private
333
+ */
334
+
335
+ const BOOL_LATER = null;
336
+ const STR_LATER = '';
337
+ const IMPLICIT_KEY_RAND = Date.now();
338
+ function implicitKeyFor(type, key) {
339
+ return `implicit-${type}:${key}${IMPLICIT_KEY_RAND}`;
340
+ }
341
+ function syncMeta(definition, inverseDefinition) {
342
+ definition.inverseKind = inverseDefinition.kind;
343
+ definition.inverseKey = inverseDefinition.key;
344
+ definition.inverseName = inverseDefinition.name;
345
+ definition.inverseType = inverseDefinition.type;
346
+ definition.inverseIsAsync = inverseDefinition.isAsync;
347
+ definition.inverseIsCollection = inverseDefinition.isCollection;
348
+ definition.inverseIsPolymorphic = inverseDefinition.isPolymorphic;
349
+ definition.inverseIsImplicit = inverseDefinition.isImplicit;
350
+ definition.inverseIsLinksMode = inverseDefinition.isLinksMode;
351
+ const resetOnRemoteUpdate = definition.resetOnRemoteUpdate === false || inverseDefinition.resetOnRemoteUpdate === false ? false : true;
352
+ definition.resetOnRemoteUpdate = resetOnRemoteUpdate;
353
+ inverseDefinition.resetOnRemoteUpdate = resetOnRemoteUpdate;
354
+ }
355
+ function upgradeMeta(meta) {
356
+ if (!isLegacyField(meta)) {
357
+ meta = temporaryConvertToLegacy(meta);
358
+ }
359
+ const niceMeta = {};
360
+ const options = meta.options;
361
+ niceMeta.kind = meta.kind;
362
+ niceMeta.key = meta.sourceKey ?? meta.name;
363
+ niceMeta.name = meta.name;
364
+ niceMeta.type = meta.type;
365
+ (test => {
366
+ if (!test) {
367
+ throw new Error(`Expected relationship definition to specify async`);
368
+ }
369
+ })(typeof options?.async === 'boolean');
370
+ niceMeta.isAsync = options.async;
371
+ niceMeta.isImplicit = false;
372
+ niceMeta.isCollection = meta.kind === 'hasMany';
373
+ niceMeta.isPolymorphic = options && !!options.polymorphic;
374
+ niceMeta.isLinksMode = options.linksMode ?? false;
375
+ niceMeta.inverseKey = options && options.inverse || STR_LATER;
376
+ niceMeta.inverseName = options && options.inverse || STR_LATER;
377
+ niceMeta.inverseType = STR_LATER;
378
+ niceMeta.inverseIsAsync = BOOL_LATER;
379
+ niceMeta.inverseIsImplicit = options && options.inverse === null || BOOL_LATER;
380
+ niceMeta.inverseIsCollection = BOOL_LATER;
381
+ niceMeta.inverseIsLinksMode = BOOL_LATER;
382
+
383
+ // prettier-ignore
384
+ niceMeta.resetOnRemoteUpdate = !isLegacyField(meta) ? false : meta.options?.linksMode ? false : meta.options?.resetOnRemoteUpdate === false ? false : true;
385
+ return niceMeta;
386
+ }
387
+ function assertConfiguration(info, type, key) {
388
+ {
389
+ const isSelfReferential = info.isSelfReferential;
390
+ if (isSelfReferential) {
391
+ return true;
392
+ }
393
+ const _isRHS = key === info.rhs_relationshipName && (type === info.rhs_baseModelName ||
394
+ // base or non-polymorphic
395
+ // if the other side is polymorphic then we need to scan our modelNames
396
+ info.lhs_isPolymorphic && info.rhs_modelNames.includes(type)); // polymorphic
397
+ const _isLHS = key === info.lhs_relationshipName && (type === info.lhs_baseModelName ||
398
+ // base or non-polymorphic
399
+ // if the other side is polymorphic then we need to scan our modelNames
400
+ info.rhs_isPolymorphic && info.lhs_modelNames.includes(type)); // polymorphic;
401
+
402
+ if (!_isRHS && !_isLHS) {
403
+ /*
404
+ this occurs when we are likely polymorphic but not configured to be polymorphic
405
+ most often due to extending a class that has a relationship definition on it.
406
+ e.g.
407
+ ```ts
408
+ class Pet extends Model {
409
+ @belongsTo('human', { async: false, inverse: 'pet' }) owner;
410
+ }
411
+ class Human extends Model {
412
+ @belongsTo('pet', { async: false, inverse: 'owner' }) pet;
413
+ }
414
+ class Farmer extends Human {}
415
+ ```
416
+ In the above case, the following would trigger this error:
417
+ ```ts
418
+ let pet = store.createRecord('pet');
419
+ let farmer = store.createRecord('farmer');
420
+ farmer.pet = pet; // error
421
+ ```
422
+ The correct way to fix this is to specify the polymorphic option on Pet
423
+ and to specify the abstract type 'human' on the Human base class.
424
+ ```ts
425
+ class Pet extends Model {
426
+ @belongsTo('human', { async: false, inverse: 'pet', polymorphic: true }) owner;
427
+ }
428
+ class Human extends Model {
429
+ @belongsTo('pet', { async: false, inverse: 'owner', as: 'human' }) pet;
430
+ }
431
+ class Farmer extends Human {}
432
+ ```
433
+ Alternatively both Human and Farmer could declare the relationship, because relationship
434
+ definitions are "structural".
435
+ ```ts
436
+ class Pet extends Model {
437
+ @belongsTo('human', { async: false, inverse: 'pet', polymorphic: true }) owner;
438
+ }
439
+ class Human extends Model {
440
+ @belongsTo('pet', { async: false, inverse: 'owner', as: 'human' }) pet;
441
+ }
442
+ class Farmer extends Model {
443
+ @belongsTo('pet', { async: false, inverse: 'owner', as: 'human' }) pet;
444
+ }
445
+ ```
446
+ */
447
+ if (key === info.lhs_relationshipName && info.lhs_modelNames.includes(type)) {
448
+ // parentIdentifier, parentDefinition, addedIdentifier, store
449
+ assertInheritedSchema(info.lhs_definition, type);
450
+ } else if (key === info.rhs_relationshipName && info.rhs_modelNames.includes(type)) {
451
+ assertInheritedSchema(info.lhs_definition, type);
452
+ }
453
+ // OPEN AN ISSUE :: we would like to improve our errors but need to understand what corner case got us here
454
+ throw new Error(`PLEASE OPEN AN ISSUE :: Found a relationship that is neither the LHS nor RHS of the same edge. This is not supported. Please report this to the WarpDrive team.`);
455
+ }
456
+ if (_isRHS && _isLHS) {
457
+ // not sure how we get here but it's probably the result of some form of inheritance
458
+ // without having specified polymorphism correctly leading to it not being self-referential
459
+ // OPEN AN ISSUE :: we would like to improve our errors but need to understand what corner case got us here
460
+ throw new Error(`PLEASE OPEN AN ISSUE :: Found a relationship that is both the LHS and RHS of the same edge but is not self-referential. This is not supported. Please report this to the WarpDrive team.`);
461
+ }
462
+ }
463
+ }
464
+ function isLHS(info, type, key) {
465
+ const isSelfReferential = info.isSelfReferential;
466
+ const isRelationship = key === info.lhs_relationshipName;
467
+ {
468
+ assertConfiguration(info, type, key);
469
+ }
470
+ if (isRelationship === true) {
471
+ return isSelfReferential === true ||
472
+ // itself
473
+ type === info.lhs_baseModelName ||
474
+ // base or non-polymorphic
475
+ // if the other side is polymorphic then we need to scan our modelNames
476
+ info.rhs_isPolymorphic && info.lhs_modelNames.includes(type) // polymorphic
477
+ ;
478
+ }
479
+ return false;
480
+ }
481
+ function upgradeDefinition(graph, key, propertyName, isImplicit = false) {
482
+ const cache = graph._definitionCache;
483
+ const storeWrapper = graph.store;
484
+ const polymorphicLookup = graph._potentialPolymorphicTypes;
485
+ const {
486
+ type
487
+ } = key;
488
+ let cached = /*#__NOINLINE__*/expandingGet(cache, type, propertyName);
489
+
490
+ // CASE: We have a cached resolution (null if no relationship exists)
491
+ if (cached !== undefined) {
492
+ return cached;
493
+ }
494
+ (test => {
495
+ if (!test) {
496
+ throw new Error(`Expected to find relationship definition in the cache for the implicit relationship ${propertyName}`);
497
+ }
498
+ })(!isImplicit);
499
+ const relationships = storeWrapper.schema.fields(key);
500
+ const relationshipsBySourceKey = storeWrapper.schema.cacheFields?.(key) ?? relationships;
501
+ (test => {
502
+ if (!test) {
503
+ throw new Error(`Expected to have a relationship definition for ${type} but none was found.`);
504
+ }
505
+ })(relationships);
506
+ const meta = relationshipsBySourceKey.get(propertyName);
507
+ if (!meta) {
508
+ // TODO potentially we should just be permissive here since this is an implicit relationship
509
+ // and not require the lookup table to be populated
510
+ if (polymorphicLookup[type]) {
511
+ const altTypes = Object.keys(polymorphicLookup[type]);
512
+ for (let i = 0; i < altTypes.length; i++) {
513
+ const _cached = expandingGet(cache, altTypes[i], propertyName);
514
+ if (_cached) {
515
+ /*#__NOINLINE__*/expandingSet(cache, type, propertyName, _cached);
516
+ _cached.rhs_modelNames.push(type);
517
+ return _cached;
518
+ }
519
+ }
520
+ }
521
+
522
+ // CASE: We don't have a relationship at all
523
+ // we should only hit this in prod
524
+ (test => {
525
+ if (!test) {
526
+ throw new Error(`Expected a relationship schema for '${type}.${propertyName}', but no relationship schema was found.`);
527
+ }
528
+ })(meta);
529
+ cache[type][propertyName] = null;
530
+ return null;
531
+ }
532
+ (test => {
533
+ if (!test) {
534
+ throw new Error(`Expected ${propertyName} to be a relationship`);
535
+ }
536
+ })(isRelationshipField(meta));
537
+ const definition = /*#__NOINLINE__*/upgradeMeta(meta);
538
+ let inverseDefinition;
539
+ let inverseKey;
540
+ const inverseType = definition.type;
541
+
542
+ // CASE: Inverse is explicitly null
543
+ if (definition.inverseKey === null) {
544
+ // TODO probably dont need this assertion if polymorphic
545
+ (test => {
546
+ if (!test) {
547
+ throw new Error(`Expected the inverse model to exist`);
548
+ }
549
+ })(getStore(storeWrapper).modelFor(inverseType));
550
+ inverseDefinition = null;
551
+ } else {
552
+ inverseKey = /*#__NOINLINE__*/inverseForRelationship(getStore(storeWrapper), key, propertyName);
553
+
554
+ // CASE: If we are polymorphic, and we declared an inverse that is non-null
555
+ // we must assume that the lack of inverseKey means that there is no
556
+ // concrete type as the baseType, so we must construct and artificial
557
+ // placeholder
558
+ if (!inverseKey && definition.isPolymorphic && definition.inverseKey) {
559
+ inverseDefinition = {
560
+ kind: 'belongsTo',
561
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
562
+ key: definition.inverseKey,
563
+ name: definition.inverseName,
564
+ type: type,
565
+ isAsync: false,
566
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
567
+ isImplicit: false,
568
+ isCollection: false,
569
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
570
+ isPolymorphic: false
571
+ }; // the rest of the fields are populated by syncMeta
572
+
573
+ // CASE: Inverse resolves to null
574
+ } else if (!inverseKey) {
575
+ inverseDefinition = null;
576
+ } else {
577
+ // CASE: We have an explicit inverse or were able to resolve one
578
+ // for the inverse we use "name" for lookup not "sourceKey"
579
+ const inverseDefinitions = storeWrapper.schema.fields({
580
+ type: inverseType
581
+ });
582
+ (test => {
583
+ if (!test) {
584
+ throw new Error(`Expected to have a relationship definition for ${inverseType} but none was found.`);
585
+ }
586
+ })(inverseDefinitions);
587
+ const metaFromInverse = inverseDefinitions.get(inverseKey);
588
+ (test => {
589
+ if (!test) {
590
+ throw new Error(`Expected a relationship schema for '${inverseType}.${inverseKey}' to match the inverse of '${type}.${propertyName}', but no relationship schema was found.`);
591
+ }
592
+ })(metaFromInverse);
593
+ (test => {
594
+ if (!test) {
595
+ throw new Error(`Expected ${inverseKey} to be a relationship`);
596
+ }
597
+ })(isRelationshipField(metaFromInverse));
598
+ inverseDefinition = upgradeMeta(metaFromInverse);
599
+ }
600
+ }
601
+
602
+ // CASE: We have no inverse
603
+ if (!inverseDefinition) {
604
+ // polish off meta
605
+ inverseKey = /*#__NOINLINE__*/implicitKeyFor(type, propertyName);
606
+ inverseDefinition = {
607
+ kind: 'implicit',
608
+ key: inverseKey,
609
+ type: type,
610
+ isAsync: false,
611
+ isImplicit: true,
612
+ isCollection: true,
613
+ // with implicits any number of records could point at us
614
+ isPolymorphic: false
615
+ }; // the rest of the fields are populated by syncMeta
616
+
617
+ syncMeta(definition, inverseDefinition);
618
+ syncMeta(inverseDefinition, definition);
619
+ const info = {
620
+ lhs_key: `${type}:${propertyName}`,
621
+ lhs_modelNames: [type],
622
+ lhs_baseModelName: type,
623
+ lhs_relationshipName: propertyName,
624
+ lhs_definition: definition,
625
+ lhs_isPolymorphic: definition.isPolymorphic,
626
+ rhs_key: inverseDefinition.key,
627
+ rhs_modelNames: [inverseType],
628
+ rhs_baseModelName: inverseType,
629
+ rhs_relationshipName: inverseDefinition.key,
630
+ rhs_definition: inverseDefinition,
631
+ rhs_isPolymorphic: false,
632
+ hasInverse: false,
633
+ isSelfReferential: type === inverseType,
634
+ // this could be wrong if we are self-referential but also polymorphic
635
+ isReflexive: false // we can't be reflexive if we don't define an inverse
636
+ };
637
+ expandingSet(cache, inverseType, inverseKey, info);
638
+ expandingSet(cache, type, propertyName, info);
639
+ return info;
640
+ }
641
+
642
+ // CASE: We do have an inverse
643
+ const baseType = inverseDefinition.type;
644
+
645
+ // TODO we want to assert this but this breaks all of our shoddily written tests
646
+ /*
647
+ if (DEBUG) {
648
+ let inverseDoubleCheck = inverseFor(inverseRelationshipName, store);
649
+ assert(`The ${inverseBaseModelName}:${inverseRelationshipName} relationship declares 'inverse: null', but it was resolved as the inverse for ${baseModelName}:${relationshipName}.`, inverseDoubleCheck);
650
+ }
651
+ */
652
+ // CASE: We may have already discovered the inverse for the baseModelName
653
+ // CASE: We have already discovered the inverse
654
+ (test => {
655
+ if (!test) {
656
+ throw new Error(`We should have determined an inverseKey by now, open an issue if this is hit`);
657
+ }
658
+ })(typeof inverseKey === 'string' && inverseKey.length > 0);
659
+ cached = expandingGet(cache, baseType, propertyName) || expandingGet(cache, inverseType, inverseKey);
660
+ if (cached) {
661
+ // TODO this assert can be removed if the above assert is enabled
662
+ (test => {
663
+ if (!test) {
664
+ throw new Error(`The ${inverseType}:${inverseKey} relationship declares 'inverse: null', but it was resolved as the inverse for ${type}:${propertyName}.`);
665
+ }
666
+ })(cached.hasInverse !== false);
667
+ const _isLHS = cached.lhs_baseModelName === baseType;
668
+ const modelNames = _isLHS ? cached.lhs_modelNames : cached.rhs_modelNames;
669
+ // make this lookup easier in the future by caching the key
670
+ modelNames.push(type);
671
+ expandingSet(cache, type, propertyName, cached);
672
+ return cached;
673
+ }
674
+
675
+ // this is our first time so polish off the metas
676
+ syncMeta(definition, inverseDefinition);
677
+ syncMeta(inverseDefinition, definition);
678
+ const lhs_modelNames = [type];
679
+ if (type !== baseType) {
680
+ lhs_modelNames.push(baseType);
681
+ }
682
+ const isSelfReferential = baseType === inverseType;
683
+ const info = {
684
+ lhs_key: `${baseType}:${propertyName}`,
685
+ lhs_modelNames,
686
+ lhs_baseModelName: baseType,
687
+ lhs_relationshipName: propertyName,
688
+ lhs_definition: definition,
689
+ lhs_isPolymorphic: definition.isPolymorphic,
690
+ rhs_key: `${inverseType}:${inverseKey}`,
691
+ rhs_modelNames: [inverseType],
692
+ rhs_baseModelName: inverseType,
693
+ rhs_relationshipName: inverseKey,
694
+ rhs_definition: inverseDefinition,
695
+ rhs_isPolymorphic: inverseDefinition.isPolymorphic,
696
+ hasInverse: true,
697
+ isSelfReferential,
698
+ isReflexive: isSelfReferential && propertyName === inverseKey
699
+ };
700
+
701
+ // Create entries for the baseModelName as well as modelName to speed up
702
+ // inverse lookups
703
+ expandingSet(cache, baseType, propertyName, info);
704
+ expandingSet(cache, type, propertyName, info);
705
+
706
+ // Greedily populate the inverse
707
+ expandingSet(cache, inverseType, inverseKey, info);
708
+ return info;
709
+ }
710
+ function inverseForRelationship(store, resourceKey, key) {
711
+ const fields = store.schema.fields(resourceKey);
712
+ const definition = fields.get(key);
713
+ if (!definition) {
714
+ return null;
715
+ }
716
+ (test => {
717
+ if (!test) {
718
+ throw new Error(`Expected ${key} to be a relationship`);
719
+ }
720
+ })(isRelationshipField(definition));
721
+ (test => {
722
+ if (!test) {
723
+ throw new Error(`Expected the relationship defintion to specify the inverse type or null.`);
724
+ }
725
+ })(definition.options?.inverse === null || typeof definition.options?.inverse === 'string' && definition.options.inverse.length > 0);
726
+ return definition.options.inverse;
727
+ }
728
+
729
+ /* eslint-disable @typescript-eslint/no-shadow */
730
+
731
+ /*
732
+ Assert that `addedRecord` has a valid type so it can be added to the
733
+ relationship of the `record`.
734
+
735
+ The assert basically checks if the `addedRecord` can be added to the
736
+ relationship (specified via `relationshipMeta`) of the `record`.
737
+
738
+ This utility should only be used internally, as both record parameters must
739
+ be ResourceKeys and the `relationshipMeta` needs to be the meta
740
+ information about the relationship, retrieved via
741
+ `record.relationshipFor(key)`.
742
+ */
743
+ let assertPolymorphicType;
744
+ let assertInheritedSchema;
745
+ {
746
+ function validateSchema(definition, meta) {
747
+ const errors = new Map();
748
+ if (definition.inverseKey !== meta.name) {
749
+ errors.set('name', ` <---- should be '${definition.inverseKey}'`);
750
+ }
751
+ if (definition.inverseType !== meta.type) {
752
+ errors.set('type', ` <---- should be '${definition.inverseType}'`);
753
+ }
754
+ if (definition.inverseKind !== meta.kind) {
755
+ errors.set('type', ` <---- should be '${definition.inverseKind}'`);
756
+ }
757
+ if (definition.inverseIsAsync !== meta.options.async) {
758
+ errors.set('async', ` <---- should be ${definition.inverseIsAsync}`);
759
+ }
760
+ if (definition.inverseIsPolymorphic && definition.inverseIsPolymorphic !== meta.options.polymorphic) {
761
+ errors.set('polymorphic', ` <---- should be ${definition.inverseIsPolymorphic}`);
762
+ }
763
+ if (definition.key !== meta.options.inverse) {
764
+ errors.set('inverse', ` <---- should be '${definition.key}'`);
765
+ }
766
+ if (definition.type !== meta.options.as) {
767
+ errors.set('as', ` <---- should be '${definition.type}'`);
768
+ }
769
+ return errors;
770
+ }
771
+ function expectedSchema(definition) {
772
+ return printSchema({
773
+ name: definition.inverseKey,
774
+ type: definition.inverseType,
775
+ kind: definition.inverseKind,
776
+ options: {
777
+ as: definition.type,
778
+ async: definition.inverseIsAsync,
779
+ polymorphic: definition.inverseIsPolymorphic || false,
780
+ inverse: definition.key
781
+ }
782
+ });
783
+ }
784
+ function printSchema(config, errors) {
785
+ return `
786
+
787
+ \`\`\`
788
+ {
789
+ ${config.name}: {
790
+ name: '${config.name}',${errors?.get('name') || ''}
791
+ type: '${config.type}',${errors?.get('type') || ''}
792
+ kind: '${config.kind}',${errors?.get('kind') || ''}
793
+ options: {
794
+ as: '${config.options.as}',${errors?.get('as') || ''}
795
+ async: ${config.options.async},${errors?.get('async') || ''}
796
+ polymorphic: ${config.options.polymorphic},${errors?.get('polymorphic') || ''}
797
+ inverse: '${config.options.inverse}'${errors?.get('inverse') || ''}
798
+ }
799
+ }
800
+ }
801
+ \`\`\`
802
+
803
+ `;
804
+ }
805
+ function metaFrom(definition) {
806
+ return {
807
+ name: definition.key,
808
+ type: definition.type,
809
+ kind: definition.kind,
810
+ options: {
811
+ async: definition.isAsync,
812
+ polymorphic: definition.isPolymorphic,
813
+ inverse: definition.inverseKey
814
+ }
815
+ };
816
+ }
817
+ function inverseMetaFrom(definition) {
818
+ return {
819
+ name: definition.inverseKey,
820
+ type: definition.inverseType,
821
+ kind: definition.inverseKind,
822
+ options: {
823
+ as: definition.isPolymorphic ? definition.type : undefined,
824
+ async: definition.inverseIsAsync,
825
+ polymorphic: definition.inverseIsPolymorphic,
826
+ inverse: definition.key
827
+ }
828
+ };
829
+ }
830
+ function inverseDefinition(definition) {
831
+ return {
832
+ key: definition.inverseKey,
833
+ name: definition.inverseName,
834
+ type: definition.inverseType,
835
+ kind: definition.inverseKind,
836
+ isAsync: definition.inverseIsAsync,
837
+ isPolymorphic: true,
838
+ isLinksMode: definition.isLinksMode,
839
+ isCollection: definition.inverseIsCollection,
840
+ isImplicit: definition.inverseIsImplicit,
841
+ inverseKey: definition.key,
842
+ inverseName: definition.name,
843
+ inverseType: definition.type,
844
+ inverseKind: definition.kind,
845
+ inverseIsAsync: definition.isAsync,
846
+ inverseIsPolymorphic: definition.isPolymorphic,
847
+ inverseIsLinksMode: definition.inverseIsLinksMode,
848
+ inverseIsImplicit: definition.isImplicit,
849
+ inverseIsCollection: definition.isCollection,
850
+ resetOnRemoteUpdate: definition.resetOnRemoteUpdate
851
+ };
852
+ }
853
+ function definitionWithPolymorphic(definition) {
854
+ return Object.assign({}, definition, {
855
+ inverseIsPolymorphic: true
856
+ });
857
+ }
858
+ assertInheritedSchema = function assertInheritedSchema(definition, type) {
859
+ const meta1 = metaFrom(definition);
860
+ const meta2 = inverseMetaFrom(definition);
861
+ const errors1 = validateSchema(inverseDefinition(definition), meta1);
862
+ const errors2 = validateSchema(definitionWithPolymorphic(definition), meta2);
863
+ if (errors2.size === 0 && errors1.size > 0) {
864
+ throw new Error(`The schema for the relationship '${type}.${definition.key}' is not configured to satisfy '${definition.inverseType}' and thus cannot utilize the '${definition.inverseType}.${definition.key}' relationship to connect with '${definition.type}.${definition.inverseKey}'\n\nIf using this relationship in a polymorphic manner is desired, the relationships schema definition for '${type}' should include:${printSchema(meta1, errors1)}`);
865
+ } else if (errors1.size > 0) {
866
+ throw new Error(`The schema for the relationship '${type}.${definition.key}' is not configured to satisfy '${definition.inverseType}' and thus cannot utilize the '${definition.inverseType}.${definition.key}' relationship to connect with '${definition.type}.${definition.inverseKey}'\n\nIf using this relationship in a polymorphic manner is desired, the relationships schema definition for '${type}' should include:${printSchema(meta1, errors1)} and the relationships schema definition for '${definition.type}' should include:${printSchema(meta2, errors2)}`);
867
+ } else if (errors2.size > 0) {
868
+ throw new Error(`The schema for the relationship '${type}.${definition.key}' satisfies '${definition.inverseType}' but cannot utilize the '${definition.inverseType}.${definition.key}' relationship to connect with '${definition.type}.${definition.inverseKey}' because that relationship is not polymorphic.\n\nIf using this relationship in a polymorphic manner is desired, the relationships schema definition for '${definition.type}' should include:${printSchema(meta2, errors2)}`);
869
+ }
870
+ };
871
+ assertPolymorphicType = function assertPolymorphicType(parentIdentifier, parentDefinition, addedIdentifier, store) {
872
+ if (parentDefinition.inverseIsImplicit) {
873
+ return;
874
+ }
875
+ if (parentDefinition.isPolymorphic) {
876
+ let meta = store.schema.fields(addedIdentifier).get(parentDefinition.inverseKey);
877
+ (test => {
878
+ if (!test) {
879
+ throw new Error(`No '${parentDefinition.inverseKey}' field exists on '${addedIdentifier.type}'. To use this type in the polymorphic relationship '${parentDefinition.inverseType}.${parentDefinition.key}' the relationships schema definition for ${addedIdentifier.type} should include:${expectedSchema(parentDefinition)}`);
880
+ }
881
+ })(meta);
882
+ (test => {
883
+ if (!test) {
884
+ throw new Error(`Expected the field ${parentDefinition.inverseKey} to be a relationship`);
885
+ }
886
+ })(meta && isRelationshipField(meta));
887
+ meta = isLegacyField(meta) ? meta : temporaryConvertToLegacy(meta);
888
+ (test => {
889
+ if (!test) {
890
+ throw new Error(`You should not specify both options.as and options.inverse as null on ${addedIdentifier.type}.${parentDefinition.inverseKey}, as if there is no inverse field there is no abstract type to conform to. You may have intended for this relationship to be polymorphic, or you may have mistakenly set inverse to null.`);
891
+ }
892
+ })(!(meta.options.inverse === null && meta?.options.as?.length));
893
+ const errors = validateSchema(parentDefinition, meta);
894
+ (test => {
895
+ if (!test) {
896
+ throw new Error(`The schema for the relationship '${parentDefinition.inverseKey}' on '${addedIdentifier.type}' type does not correctly implement '${parentDefinition.type}' and thus cannot be assigned to the '${parentDefinition.key}' relationship in '${parentIdentifier.type}'. If using this record in this polymorphic relationship is desired, correct the errors in the schema shown below:${printSchema(meta, errors)}`);
897
+ }
898
+ })(errors.size === 0);
899
+ } else if (addedIdentifier.type !== parentDefinition.type) {
900
+ // if we are not polymorphic
901
+ // then the addedIdentifier.type must be the same as the parentDefinition.type
902
+ let meta = store.schema.fields(addedIdentifier).get(parentDefinition.inverseKey);
903
+ (test => {
904
+ if (!test) {
905
+ throw new Error(`Expected the field ${parentDefinition.inverseKey} to be a relationship`);
906
+ }
907
+ })(!meta || isRelationshipField(meta));
908
+ meta = meta && (isLegacyField(meta) ? meta : temporaryConvertToLegacy(meta));
909
+ if (meta?.options.as === parentDefinition.type) {
910
+ // inverse is likely polymorphic but missing the polymorphic flag
911
+ let meta = store.schema.fields({
912
+ type: parentDefinition.inverseType
913
+ }).get(parentDefinition.key);
914
+ (test => {
915
+ if (!test) {
916
+ throw new Error(`Expected the field ${parentDefinition.key} to be a relationship`);
917
+ }
918
+ })(meta && isRelationshipField(meta));
919
+ meta = isLegacyField(meta) ? meta : temporaryConvertToLegacy(meta);
920
+ const errors = validateSchema(definitionWithPolymorphic(inverseDefinition(parentDefinition)), meta);
921
+ (test => {
922
+ {
923
+ throw new Error(`The '<${addedIdentifier.type}>.${parentDefinition.inverseKey}' relationship cannot be used polymorphically because '<${parentDefinition.inverseType}>.${parentDefinition.key} is not a polymorphic relationship. To use this relationship in a polymorphic manner, fix the following schema issues on the relationships schema for '${parentDefinition.inverseType}':${printSchema(meta, errors)}`);
924
+ }
925
+ })();
926
+ } else {
927
+ (test => {
928
+ {
929
+ throw new Error(`The '${addedIdentifier.type}' type does not implement '${parentDefinition.type}' and thus cannot be assigned to the '${parentDefinition.key}' relationship in '${parentIdentifier.type}'. If this relationship should be polymorphic, mark ${parentDefinition.inverseType}.${parentDefinition.key} as \`polymorphic: true\` and ${addedIdentifier.type}.${parentDefinition.inverseKey} as implementing it via \`as: '${parentDefinition.type}'\`.`);
930
+ }
931
+ })();
932
+ }
933
+ }
934
+ };
935
+ }
936
+ function count(label) {
937
+ // @ts-expect-error
938
+ // eslint-disable-next-line
939
+ globalThis.__WarpDriveMetricCountData[label] = (globalThis.__WarpDriveMetricCountData[label] || 0) + 1;
940
+ }
941
+
942
+ /*
943
+ case many:1
944
+ ========
945
+ In a bi-directional graph with Many:1 edges, adding a value
946
+ results in up-to 3 discrete value transitions, while removing
947
+ a value is only 2 transitions.
948
+
949
+ For adding C to A
950
+ If: A <<-> B, C <->> D is the initial state,
951
+ and: B <->> A <<-> C, D is the final state
952
+
953
+ then we would undergo the following transitions.
954
+
955
+ add C to A
956
+ remove C from D
957
+ add A to C
958
+
959
+ For removing B from A
960
+ If: A <<-> B, C <->> D is the initial state,
961
+ and: A, B, C <->> D is the final state
962
+
963
+ then we would undergo the following transitions.
964
+
965
+ remove B from A
966
+ remove A from B
967
+
968
+ case many:many
969
+ ===========
970
+ In a bi-directional graph with Many:Many edges, adding or
971
+ removing a value requires only 2 value transitions.
972
+
973
+ For Adding
974
+ If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
975
+ And: D<<->>C<<->>A<<->>B is the final state
976
+
977
+ Then we would undergo two transitions.
978
+
979
+ add C to A.
980
+ add A to C
981
+
982
+ For Removing
983
+ If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
984
+ And: A, B, C<<->>D is the final state
985
+
986
+ Then we would undergo two transitions.
987
+
988
+ remove B from A
989
+ remove A from B
990
+
991
+ case many:?
992
+ ========
993
+ In a uni-directional graph with Many:? edges (modeled in WarpDrive with `inverse:null`) with
994
+ artificial (implicit) inverses, replacing a value results in 2 discrete value transitions.
995
+ This is because a Many:? relationship is effectively Many:Many.
996
+ */
997
+ function replaceRelatedRecords(graph, op, isRemote) {
998
+ if (isRemote) {
999
+ replaceRelatedRecordsRemote(graph, op, isRemote);
1000
+ } else {
1001
+ replaceRelatedRecordsLocal(graph, op, isRemote);
1002
+ }
1003
+ }
1004
+ function replaceRelatedRecordsLocal(graph, op, isRemote) {
1005
+ const resourceKeys = op.value;
1006
+ const relationship = graph.get(op.record, op.field);
1007
+ (test => {
1008
+ if (!test) {
1009
+ throw new Error(`expected hasMany relationship`);
1010
+ }
1011
+ })(isHasMany(relationship));
1012
+ relationship.state.hasReceivedData = true;
1013
+ const {
1014
+ additions,
1015
+ removals
1016
+ } = relationship;
1017
+ const {
1018
+ inverseKey,
1019
+ type
1020
+ } = relationship.definition;
1021
+ const {
1022
+ record
1023
+ } = op;
1024
+ const wasDirty = relationship.isDirty;
1025
+ let localBecameDirty = false;
1026
+ {
1027
+ if (getGlobalConfig().WarpDrive.debug.LOG_METRIC_COUNTS || globalThis.getWarpDriveRuntimeConfig().debug.LOG_METRIC_COUNTS) {
1028
+ count(`replaceRelatedRecordsLocal ${'type' in record ? record.type : '<document>'} ${op.field}`);
1029
+ }
1030
+ }
1031
+ const onAdd = resourceKey => {
1032
+ // Since we are diffing against the remote state, we check
1033
+ // if our previous local state did not contain this ResourceKey
1034
+ const removalsHas = removals?.has(resourceKey);
1035
+ if (removalsHas || !additions?.has(resourceKey)) {
1036
+ if (type !== resourceKey.type) {
1037
+ {
1038
+ assertPolymorphicType(relationship.identifier, relationship.definition, resourceKey, graph.store);
1039
+ }
1040
+ graph.registerPolymorphicType(type, resourceKey.type);
1041
+ }
1042
+
1043
+ // we've added a record locally that wasn't in the local state before
1044
+ localBecameDirty = true;
1045
+ addToInverse(graph, resourceKey, inverseKey, op.record, isRemote);
1046
+ if (removalsHas) {
1047
+ removals.delete(resourceKey);
1048
+ }
1049
+ }
1050
+ };
1051
+ const onRemove = resourceKey => {
1052
+ // Since we are diffing against the remote state, we check
1053
+ // if our previous local state had contained this ResourceKey
1054
+ const additionsHas = additions?.has(resourceKey);
1055
+ if (additionsHas || !removals?.has(resourceKey)) {
1056
+ // we've removed a record locally that was in the local state before
1057
+ localBecameDirty = true;
1058
+ removeFromInverse(graph, resourceKey, inverseKey, record, isRemote);
1059
+ if (additionsHas) {
1060
+ additions.delete(resourceKey);
1061
+ }
1062
+ }
1063
+ };
1064
+ const diff = diffCollection(resourceKeys, relationship, onAdd, onRemove);
1065
+
1066
+ // any additions no longer in the local state
1067
+ // also need to be removed from the inverse
1068
+ if (additions && additions.size > 0) {
1069
+ additions.forEach(resourceKey => {
1070
+ if (!diff.add.has(resourceKey)) {
1071
+ localBecameDirty = true;
1072
+ onRemove(resourceKey);
1073
+ }
1074
+ });
1075
+ }
1076
+
1077
+ // any removals no longer in the local state
1078
+ // also need to be added back to the inverse
1079
+ if (removals && removals.size > 0) {
1080
+ removals.forEach(resourceKey => {
1081
+ if (!diff.del.has(resourceKey)) {
1082
+ localBecameDirty = true;
1083
+ onAdd(resourceKey);
1084
+ }
1085
+ });
1086
+ }
1087
+ const becameDirty = diff.changed || localBecameDirty;
1088
+ relationship.additions = diff.add;
1089
+ relationship.removals = diff.del;
1090
+ relationship.localState = diff.finalState;
1091
+
1092
+ // we only notify if the localState changed and were not already dirty before
1093
+ // because if we were already dirty then we have already notified
1094
+ if (becameDirty && !wasDirty) {
1095
+ notifyChange(graph, relationship);
1096
+ }
1097
+ }
1098
+ function replaceRelatedRecordsRemote(graph, op, isRemote) {
1099
+ const resourceKeys = op.value;
1100
+ const relationship = graph.get(op.record, op.field);
1101
+ {
1102
+ if (getGlobalConfig().WarpDrive.debug.LOG_METRIC_COUNTS || globalThis.getWarpDriveRuntimeConfig().debug.LOG_METRIC_COUNTS) {
1103
+ count(`replaceRelatedRecordsRemote ${'type' in op.record ? op.record.type : '<document>'} ${op.field}`);
1104
+ }
1105
+ }
1106
+ (test => {
1107
+ if (!test) {
1108
+ throw new Error(`You can only '${op.op}' on a hasMany relationship. ${op.record.type}.${op.field} is a ${relationship.definition.kind}`);
1109
+ }
1110
+ })(isHasMany(relationship));
1111
+ if (isRemote) {
1112
+ graph._addToTransaction(relationship);
1113
+ }
1114
+ const wasDirty = relationship.isDirty;
1115
+ // if this is our first time receiving data
1116
+ // we need to mark the relationship as dirty
1117
+ // so that non-materializing APIs like `hasManyReference.value()`
1118
+ // will get notified and updated.
1119
+ if (!relationship.state.hasReceivedData) {
1120
+ relationship.isDirty = true;
1121
+ }
1122
+ relationship.state.hasReceivedData = true;
1123
+
1124
+ // cache existing state
1125
+ const {
1126
+ definition
1127
+ } = relationship;
1128
+ const {
1129
+ type
1130
+ } = relationship.definition;
1131
+ const diff = diffCollection(resourceKeys, relationship, resourceKey => {
1132
+ if (type !== resourceKey.type) {
1133
+ {
1134
+ assertPolymorphicType(relationship.identifier, relationship.definition, resourceKey, graph.store);
1135
+ }
1136
+ graph.registerPolymorphicType(type, resourceKey.type);
1137
+ }
1138
+ // commit additions
1139
+ // TODO build this into the diff?
1140
+ // because we are not dirty if this was a committed local addition
1141
+ if (relationship.additions?.has(resourceKey)) {
1142
+ relationship.additions.delete(resourceKey);
1143
+ } else {
1144
+ {
1145
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1146
+ if (!relationship.isDirty) {
1147
+ // eslint-disable-next-line no-console
1148
+ console.log(`setting relationship to dirty because the remote addition was not in our previous list of local additions`);
1149
+ }
1150
+ }
1151
+ }
1152
+ }
1153
+ addToInverse(graph, resourceKey, definition.inverseKey, op.record, isRemote);
1154
+ }, resourceKey => {
1155
+ // commit removals
1156
+ // TODO build this into the diff?
1157
+ // because we are not dirty if this was a committed local addition
1158
+ if (relationship.removals?.has(resourceKey)) {
1159
+ relationship.removals.delete(resourceKey);
1160
+ } else {
1161
+ {
1162
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1163
+ if (!relationship.isDirty) {
1164
+ // eslint-disable-next-line no-console
1165
+ console.log(`setting relationship to dirty because the remote removal was not in our previous list of local removals`);
1166
+ }
1167
+ }
1168
+ }
1169
+ }
1170
+ removeFromInverse(graph, resourceKey, definition.inverseKey, op.record, isRemote);
1171
+ });
1172
+
1173
+ // replace existing state
1174
+ relationship.remoteMembers = diff.finalSet;
1175
+ relationship.remoteState = diff.finalState;
1176
+
1177
+ // changed also indicates a change in order
1178
+ if (diff.changed) {
1179
+ relationship.isDirty = true;
1180
+ }
1181
+
1182
+ // TODO unsure if we need this but it
1183
+ // may allow us to more efficiently patch
1184
+ // the associated ManyArray
1185
+ relationship._diff = diff;
1186
+ {
1187
+ // only do this for legacy hasMany, not collection
1188
+ // and provide a way to incrementally migrate
1189
+ if (
1190
+ // we do not guard by diff.changed here
1191
+ // because we want to clear local changes even if
1192
+ // no change has occurred to preserve the legacy behavior
1193
+ relationship.definition.kind === 'hasMany' && relationship.definition.resetOnRemoteUpdate !== false && (diff.changed || wasDirty)) {
1194
+ const deprecationInfo = {
1195
+ removals: [],
1196
+ additions: [],
1197
+ triggered: false
1198
+ };
1199
+ if (relationship.removals) {
1200
+ relationship.isDirty = true;
1201
+ relationship.removals.forEach(resourceKey => {
1202
+ deprecationInfo.triggered = true;
1203
+ deprecationInfo.removals.push(resourceKey);
1204
+ // reverse the removal
1205
+ // if we are still in removals at this point then
1206
+ // we were not "committed" which means we are present
1207
+ // in the remoteMembers. So we "add back" on the inverse.
1208
+ addToInverse(graph, resourceKey, definition.inverseKey, op.record, false);
1209
+ });
1210
+ relationship.removals = null;
1211
+ }
1212
+ if (relationship.additions) {
1213
+ relationship.additions.forEach(resourceKey => {
1214
+ // reverse the addition
1215
+ // if we are still in additions at this point then
1216
+ // we were not "committed" which means we are not present
1217
+ // in the remoteMembers. So we "remove" from the inverse.
1218
+ // however we only do this if we are not a "new" record.
1219
+ if (!checkIfNew(graph._realStore, resourceKey)) {
1220
+ deprecationInfo.triggered = true;
1221
+ deprecationInfo.additions.push(resourceKey);
1222
+ relationship.isDirty = true;
1223
+ relationship.additions.delete(resourceKey);
1224
+ removeFromInverse(graph, resourceKey, definition.inverseKey, op.record, false);
1225
+ }
1226
+ });
1227
+ if (relationship.additions.size === 0) {
1228
+ relationship.additions = null;
1229
+ }
1230
+ }
1231
+ if (deprecationInfo.triggered) {
1232
+ console.warn(`WarpDrive is changing the default semantics of updates to the remote state of relationships.\n\nThe following local state was cleared from the <${relationship.identifier.type}>.${relationship.definition.key} hasMany relationship but will not be once this deprecation is resolved by opting into the new behavior:\n\n\tAdded: [${deprecationInfo.additions.map(i => i.lid).join(', ')}]\n\tRemoved: [${deprecationInfo.removals.map(i => i.lid).join(', ')}]`);
1233
+ }
1234
+ }
1235
+ }
1236
+ if (relationship.isDirty && !wasDirty) {
1237
+ flushCanonical(graph, relationship);
1238
+ }
1239
+ }
1240
+ function addToInverse(graph, resourceKey, key, value, isRemote) {
1241
+ const relationship = graph.get(resourceKey, key);
1242
+ const {
1243
+ type
1244
+ } = relationship.definition;
1245
+ if (type !== value.type) {
1246
+ {
1247
+ assertPolymorphicType(relationship.identifier, relationship.definition, value, graph.store);
1248
+ }
1249
+ graph.registerPolymorphicType(type, value.type);
1250
+ }
1251
+ if (isBelongsTo(relationship)) {
1252
+ relationship.state.hasReceivedData = true;
1253
+ relationship.state.isEmpty = false;
1254
+ if (isRemote) {
1255
+ graph._addToTransaction(relationship);
1256
+ if (relationship.remoteState !== null) {
1257
+ removeFromInverse(graph, relationship.remoteState, relationship.definition.inverseKey, resourceKey, isRemote);
1258
+ }
1259
+ relationship.remoteState = value;
1260
+ }
1261
+ if (relationship.localState !== value) {
1262
+ if (!isRemote && relationship.localState) {
1263
+ removeFromInverse(graph, relationship.localState, relationship.definition.inverseKey, resourceKey, isRemote);
1264
+ }
1265
+ relationship.localState = value;
1266
+ notifyChange(graph, relationship);
1267
+ }
1268
+ } else if (isHasMany(relationship)) {
1269
+ if (isRemote) {
1270
+ // TODO this needs to alert stuffs
1271
+ // And patch state better
1272
+ // This is almost definitely wrong
1273
+ // WARNING WARNING WARNING
1274
+
1275
+ if (!relationship.remoteMembers.has(value)) {
1276
+ graph._addToTransaction(relationship);
1277
+ relationship.remoteState.push(value);
1278
+ relationship.remoteMembers.add(value);
1279
+ if (relationship.additions?.has(value)) {
1280
+ relationship.additions.delete(value);
1281
+ } else {
1282
+ relationship.isDirty = true;
1283
+ relationship.state.hasReceivedData = true;
1284
+ flushCanonical(graph, relationship);
1285
+ }
1286
+ }
1287
+ } else {
1288
+ // if we are not dirty but have a null localState then we
1289
+ // are mutating a relationship that has never been fetched
1290
+ // so we initialize localState to an empty array
1291
+ if (!relationship.isDirty && !relationship.localState) {
1292
+ relationship.localState = [];
1293
+ }
1294
+ if (_add(graph, resourceKey, relationship, value, null, isRemote)) {
1295
+ notifyChange(graph, relationship);
1296
+ }
1297
+ }
1298
+ } else {
1299
+ if (isRemote) {
1300
+ if (!relationship.remoteMembers.has(value)) {
1301
+ relationship.remoteMembers.add(value);
1302
+ relationship.localMembers.add(value);
1303
+ }
1304
+ } else {
1305
+ if (!relationship.localMembers.has(value)) {
1306
+ relationship.localMembers.add(value);
1307
+ }
1308
+ }
1309
+ }
1310
+ }
1311
+ function notifyInverseOfPotentialMaterialization(graph, resourceKey, key, value, isRemote) {
1312
+ const relationship = graph.get(resourceKey, key);
1313
+ if (isHasMany(relationship) && isRemote && relationship.remoteMembers.has(value)) {
1314
+ notifyChange(graph, relationship);
1315
+ }
1316
+ }
1317
+ function removeFromInverse(graph, resourceKey, key, value, isRemote) {
1318
+ const relationship = graph.get(resourceKey, key);
1319
+ if (isBelongsTo(relationship)) {
1320
+ relationship.state.isEmpty = true;
1321
+ if (isRemote) {
1322
+ graph._addToTransaction(relationship);
1323
+ relationship.remoteState = null;
1324
+ }
1325
+ if (relationship.localState === value) {
1326
+ relationship.localState = null;
1327
+ notifyChange(graph, relationship);
1328
+ }
1329
+ } else if (isHasMany(relationship)) {
1330
+ if (isRemote) {
1331
+ graph._addToTransaction(relationship);
1332
+ if (_removeRemote(relationship, value)) {
1333
+ notifyChange(graph, relationship);
1334
+ }
1335
+ } else {
1336
+ if (_removeLocal(relationship, value)) {
1337
+ notifyChange(graph, relationship);
1338
+ }
1339
+ }
1340
+ } else {
1341
+ if (isRemote) {
1342
+ relationship.remoteMembers.delete(value);
1343
+ relationship.localMembers.delete(value);
1344
+ } else {
1345
+ if (value && relationship.localMembers.has(value)) {
1346
+ relationship.localMembers.delete(value);
1347
+ }
1348
+ }
1349
+ }
1350
+ }
1351
+ function flushCanonical(graph, rel) {
1352
+ if (rel.accessed) {
1353
+ graph._scheduleLocalSync(rel);
1354
+ }
1355
+ }
1356
+ function replaceRelatedRecord(graph, op, isRemote = false) {
1357
+ const relationship = graph.get(op.record, op.field);
1358
+ (test => {
1359
+ if (!test) {
1360
+ throw new Error(`You can only '${op.op}' on a belongsTo relationship. ${op.record.type}.${op.field} is a ${relationship.definition.kind}`);
1361
+ }
1362
+ })(isBelongsTo(relationship));
1363
+ if (isRemote) {
1364
+ graph._addToTransaction(relationship);
1365
+ }
1366
+ const {
1367
+ definition,
1368
+ state
1369
+ } = relationship;
1370
+ const prop = isRemote ? 'remoteState' : 'localState';
1371
+ const existingState = relationship[prop];
1372
+
1373
+ /*
1374
+ case 1:1
1375
+ ========
1376
+ In a bi-directional graph with 1:1 edges, replacing a value
1377
+ results in up-to 4 discrete value transitions.
1378
+ If: A <-> B, C <-> D is the initial state,
1379
+ and: A <-> C, B, D is the final state
1380
+ then we would undergo the following 4 transitions.
1381
+ remove A from B
1382
+ add C to A
1383
+ remove C from D
1384
+ add A to C
1385
+ case 1:many
1386
+ ===========
1387
+ In a bi-directional graph with 1:Many edges, replacing a value
1388
+ results in up-to 3 discrete value transitions.
1389
+ If: A<->>B<<->D, C<<->D is the initial state (double arrows representing the many side)
1390
+ And: A<->>C<<->D, B<<->D is the final state
1391
+ Then we would undergo three transitions.
1392
+ remove A from B
1393
+ add C to A.
1394
+ add A to C
1395
+ case 1:?
1396
+ ========
1397
+ In a uni-directional graph with 1:? edges (modeled in WarpDrive with `inverse:null`) with
1398
+ artificial (implicit) inverses, replacing a value results in up-to 3 discrete value transitions.
1399
+ This is because a 1:? relationship is effectively 1:many.
1400
+ If: A->B, C->B is the initial state
1401
+ And: A->C, C->B is the final state
1402
+ Then we would undergo three transitions.
1403
+ Remove A from B
1404
+ Add C to A
1405
+ Add A to C
1406
+ */
1407
+
1408
+ // nothing for us to do
1409
+ if (op.value === existingState) {
1410
+ // if we were empty before but now know we are empty this needs to be true
1411
+ state.hasReceivedData = true;
1412
+ // if this is a remote update we still sync
1413
+ if (isRemote) {
1414
+ const {
1415
+ localState
1416
+ } = relationship;
1417
+ // don't sync if localState is a new record and our remoteState is null
1418
+ if (localState && checkIfNew(graph._realStore, localState) && !existingState) {
1419
+ return;
1420
+ }
1421
+ if (existingState && localState === existingState) {
1422
+ notifyInverseOfPotentialMaterialization(graph, existingState, definition.inverseKey, op.record, isRemote);
1423
+ } else {
1424
+ // if localState does not match existingState then we know
1425
+ // we have a local mutation that has not been persisted yet
1426
+ if (localState !== op.value && relationship.definition.resetOnRemoteUpdate !== false) {
1427
+ relationship.localState = existingState;
1428
+ console.warn(`WarpDrive is changing the default semantics of updates to the remote state of relationships.\n\nThe following local state was cleared from the <${relationship.identifier.type}>.${relationship.definition.key} belongsTo relationship but will not be once this deprecation is resolved:\n\n\t${localState ? 'Added: ' + localState.lid + '\n\t' : ''}${existingState ? 'Removed: ' + existingState.lid : ''}`);
1429
+ notifyChange(graph, relationship);
1430
+ }
1431
+ }
1432
+ }
1433
+ return;
1434
+ }
1435
+
1436
+ // remove this value from the inverse if required
1437
+ if (existingState) {
1438
+ removeFromInverse(graph, existingState, definition.inverseKey, op.record, isRemote);
1439
+ }
1440
+
1441
+ // update value to the new value
1442
+ relationship[prop] = op.value;
1443
+ state.hasReceivedData = true;
1444
+ state.isEmpty = op.value === null;
1445
+ state.isStale = false;
1446
+ state.hasFailedLoadAttempt = false;
1447
+ if (op.value) {
1448
+ if (definition.type !== op.value.type) {
1449
+ // assert(
1450
+ // `The '<${definition.inverseType}>.${op.field}' relationship expects only '${definition.type}' records since it is not polymorphic. Received a Record of type '${op.value.type}'`,
1451
+ // definition.isPolymorphic
1452
+ // );
1453
+
1454
+ // TODO this should now handle the deprecation warning if isPolymorphic is not set
1455
+ // but the record does turn out to be polymorphic
1456
+ // this should still assert if the user is relying on legacy inheritance/mixins to
1457
+ // provide polymorphic behavior and has not yet added the polymorphic flags
1458
+ {
1459
+ assertPolymorphicType(relationship.identifier, definition, op.value, graph.store);
1460
+ }
1461
+ graph.registerPolymorphicType(definition.type, op.value.type);
1462
+ }
1463
+ addToInverse(graph, op.value, definition.inverseKey, op.record, isRemote);
1464
+ }
1465
+ if (isRemote) {
1466
+ const {
1467
+ localState,
1468
+ remoteState
1469
+ } = relationship;
1470
+ if (localState && checkIfNew(graph._realStore, localState) && !remoteState) {
1471
+ return;
1472
+ }
1473
+ // when localState does not match the new remoteState and
1474
+ // localState === existingState then we had no local mutation
1475
+ // and we can safely sync the new remoteState to local
1476
+ if (localState !== remoteState && localState === existingState) {
1477
+ relationship.localState = remoteState;
1478
+ notifyChange(graph, relationship);
1479
+ // But when localState does not match the new remoteState and
1480
+ // and localState !== existingState then we know we have a local mutation
1481
+ // that has not been persisted yet.
1482
+ } else {
1483
+ if (localState !== remoteState && localState !== existingState && relationship.definition.resetOnRemoteUpdate !== false) {
1484
+ relationship.localState = remoteState;
1485
+ console.warn(`WarpDrive is changing the default semantics of updates to the remote state of relationships.\n\nThe following local state was cleared from the <${relationship.identifier.type}>.${relationship.definition.key} belongsTo relationship but will not be once this deprecation is resolved:\n\n\t${localState ? 'Added: ' + localState.lid + '\n\t' : ''}${existingState ? 'Removed: ' + existingState.lid : ''}`);
1486
+ notifyChange(graph, relationship);
1487
+ }
1488
+ }
1489
+ } else {
1490
+ notifyChange(graph, relationship);
1491
+ }
1492
+ }
1493
+ function _deprecatedCompare(priorLocalState, newState, newMembers, prevState, prevSet, onAdd, onDel, remoteClearsLocal) {
1494
+ const newLength = newState.length;
1495
+ const prevLength = prevState.length;
1496
+ const iterationLength = Math.max(newLength, prevLength);
1497
+ let changed = newMembers.size !== prevSet.size;
1498
+ let remoteOrderChanged = false;
1499
+ const added = new Set();
1500
+ const removed = new Set();
1501
+ const duplicates = new Map();
1502
+ const finalSet = new Set();
1503
+ const finalState = [];
1504
+ const priorLocalLength = priorLocalState?.length ?? 0;
1505
+ for (let i = 0, j = 0; i < iterationLength; i++) {
1506
+ let adv = false;
1507
+ let member;
1508
+
1509
+ // accumulate anything added
1510
+ if (i < newLength) {
1511
+ member = newState[i];
1512
+ if (!finalSet.has(member)) {
1513
+ finalState[j] = member;
1514
+ finalSet.add(member);
1515
+ adv = true;
1516
+ if (!prevSet.has(member)) {
1517
+ // Avoid unnecessarily notifying a change that already exists locally
1518
+ if (i < priorLocalLength) {
1519
+ const priorLocalMember = priorLocalState[i];
1520
+ if (priorLocalMember !== member) {
1521
+ changed = true;
1522
+ }
1523
+ }
1524
+ added.add(member);
1525
+ onAdd(member);
1526
+ }
1527
+ } else {
1528
+ let list = duplicates.get(member);
1529
+ if (list === undefined) {
1530
+ list = [];
1531
+ duplicates.set(member, list);
1532
+ }
1533
+ list.push(i);
1534
+ }
1535
+ }
1536
+
1537
+ // accumulate anything removed
1538
+ if (i < prevLength) {
1539
+ const prevMember = prevState[i];
1540
+
1541
+ // detect reordering, adjusting index for duplicates
1542
+ // j is always less than i and so if i < prevLength, j < prevLength
1543
+ if (member !== prevState[j]) {
1544
+ // the new remote order does not match the current remote order
1545
+ // indicating a change in membership or reordering
1546
+ remoteOrderChanged = true;
1547
+ // however: if the new remote order matches the current local order
1548
+ // we can disregard the change notification generation so long as
1549
+ // we are not configured to reset on remote update (which is deprecated)
1550
+ {
1551
+ if (!remoteClearsLocal && i < priorLocalLength) {
1552
+ const priorLocalMember = priorLocalState[j];
1553
+ if (priorLocalMember !== member) {
1554
+ changed = true;
1555
+ }
1556
+ } else {
1557
+ changed = true;
1558
+ }
1559
+ }
1560
+
1561
+ // if remote order hasn't changed but local order differs
1562
+ // and we are configured to reset on remote update (which is deprecated)
1563
+ // then we still need to mark the relationship as changed
1564
+ } else {
1565
+ if (remoteClearsLocal) {
1566
+ if (!changed && j < priorLocalLength) {
1567
+ const priorLocalMember = priorLocalState[j];
1568
+ if (priorLocalMember !== member) {
1569
+ changed = true;
1570
+ }
1571
+ }
1572
+ }
1573
+ }
1574
+ if (!newMembers.has(prevMember)) {
1575
+ changed = true;
1576
+ removed.add(prevMember);
1577
+ onDel(prevMember);
1578
+ }
1579
+ } else if (adv && j < prevLength && member !== prevState[j]) {
1580
+ changed = true;
1581
+ }
1582
+ if (adv) {
1583
+ j++;
1584
+ }
1585
+ }
1586
+ const diff = {
1587
+ add: added,
1588
+ del: removed,
1589
+ finalState,
1590
+ finalSet,
1591
+ changed,
1592
+ remoteOrderChanged
1593
+ };
1594
+ return {
1595
+ diff,
1596
+ duplicates
1597
+ };
1598
+ }
1599
+ function _compare(priorLocalState, finalState, finalSet, prevState, prevSet, onAdd, onDel, remoteClearsLocal) {
1600
+ const finalLength = finalState.length;
1601
+ const prevLength = prevState.length;
1602
+ const iterationLength = Math.max(finalLength, prevLength);
1603
+ const equalLength = priorLocalState ? finalLength === priorLocalState.length : finalLength === prevLength;
1604
+ let remoteOrderChanged = finalSet.size !== prevSet.size;
1605
+ let changed = priorLocalState ? finalSet.size !== priorLocalState.length : remoteOrderChanged;
1606
+ const added = new Set();
1607
+ const removed = new Set();
1608
+ const priorLocalLength = priorLocalState?.length ?? 0;
1609
+ {
1610
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1611
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1612
+ changed &&
1613
+ // eslint-disable-next-line no-console
1614
+ console.log(`changed because ${priorLocalState ? 'finalSet.size !== priorLocalState.length' : 'finalSet.size !== prevSet.size'}`);
1615
+ }
1616
+ }
1617
+ for (let i = 0; i < iterationLength; i++) {
1618
+ let member;
1619
+
1620
+ // accumulate anything added
1621
+ if (i < finalLength) {
1622
+ member = finalState[i];
1623
+ if (!prevSet.has(member)) {
1624
+ // Avoid unnecessarily notifying a change that already exists locally
1625
+ if (i < priorLocalLength) {
1626
+ const priorLocalMember = priorLocalState[i];
1627
+ if (priorLocalMember !== member) {
1628
+ {
1629
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1630
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-console
1631
+ !changed && console.log(`changed because priorLocalMember !== member && !prevSet.has(member)`);
1632
+ }
1633
+ }
1634
+ changed = true;
1635
+ }
1636
+ }
1637
+ added.add(member);
1638
+ onAdd(member);
1639
+ }
1640
+ }
1641
+
1642
+ // accumulate anything removed
1643
+ if (i < prevLength) {
1644
+ const prevMember = prevState[i];
1645
+
1646
+ // detect reordering
1647
+ if (equalLength && member !== prevMember) {
1648
+ // the new remote order does not match the current remote order
1649
+ // indicating a change in membership or reordering
1650
+ remoteOrderChanged = true;
1651
+ // however: if the new remote order matches the current local order
1652
+ // we can disregard the change notification generation so long as
1653
+ // we are not configured to reset on remote update (which is deprecated)
1654
+
1655
+ if (i < priorLocalLength) {
1656
+ const priorLocalMember = priorLocalState[i];
1657
+ if (priorLocalMember !== member) {
1658
+ {
1659
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1660
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-console
1661
+ !changed && console.log(`changed because priorLocalMember !== member && member !== prevMember`);
1662
+ }
1663
+ }
1664
+ changed = true;
1665
+ }
1666
+ } else if (i < finalLength) {
1667
+ // if we have exceeded the length of priorLocalState and we are within the range
1668
+ // of the finalState then we must have changed
1669
+ {
1670
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1671
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-console
1672
+ !changed && console.log(`changed because priorMember !== member && index >= priorLocalLength`);
1673
+ }
1674
+ }
1675
+ changed = true;
1676
+ }
1677
+
1678
+ // if remote order hasn't changed but local order differs
1679
+ // and we are configured to reset on remote update (which is deprecated)
1680
+ // then we still need to mark the relationship as changed
1681
+ } else {
1682
+ if (remoteClearsLocal) {
1683
+ if (equalLength && !changed && i < priorLocalLength) {
1684
+ const priorLocalMember = priorLocalState[i];
1685
+ if (priorLocalMember !== prevMember) {
1686
+ {
1687
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1688
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-console
1689
+ !changed && console.log(`changed because priorLocalMember !== prevMember && remoteClearsLocal`);
1690
+ }
1691
+ }
1692
+ changed = true;
1693
+ }
1694
+ }
1695
+ }
1696
+ }
1697
+ if (!finalSet.has(prevMember)) {
1698
+ // if we are within finalLength, we can only be "changed" if we've already exceeded
1699
+ // the index range of priorLocalState, as otherwise the previous member may still
1700
+ // be removed.
1701
+ //
1702
+ // prior local: [1, 2, 3, 4]
1703
+ // final state: [1, 2, 3]
1704
+ // prev remote state: [1, 2, 5, 3, 4]
1705
+ // i === 2
1706
+ // prevMember === 5
1707
+ // !finalSet.has(prevMember) === true
1708
+ //
1709
+ // because we will become changed at i===3,
1710
+ // we do not need to worry about becoming changed at i===2
1711
+ // as the arrays until now are still the same
1712
+ //
1713
+ // prior local: [1, 2, 3]
1714
+ // final state: [1, 2, 3, 4]
1715
+ // prev remote state: [1, 2, 5, 3, 4]
1716
+ // i === 2
1717
+ // prevMember === 5
1718
+ // !finalSet.has(prevMember) === true
1719
+ //
1720
+ // because we will become changed at i===3
1721
+ // we do not need to worry about becoming changed at i===2
1722
+ //
1723
+ // prior local: [1, 2, 3]
1724
+ // final state: [1, 2, 3]
1725
+ // prev remote state: [1, 2, 5, 3, 4]
1726
+ // i === 2
1727
+ // prevMember === 5
1728
+ // !finalSet.has(prevMember) === true
1729
+ //
1730
+ // because we have same length and same membership order
1731
+ // we do not need to worry about becoming changed at i===2
1732
+ //
1733
+ // if you do not have a priorLocalState you can't be changed
1734
+ // ergo, we never need to set changed in this branch.
1735
+ // this log can still be useful for debugging.
1736
+ {
1737
+ if (getGlobalConfig().WarpDrive.debug.DEBUG_RELATIONSHIP_NOTIFICATIONS || globalThis.getWarpDriveRuntimeConfig().debug.DEBUG_RELATIONSHIP_NOTIFICATIONS) {
1738
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1739
+ !changed &&
1740
+ // eslint-disable-next-line no-console
1741
+ console.log(`changed because i >= priorLocalLength && i < finalLength && !finalSet.has(prevMember)`);
1742
+ }
1743
+ } //
1744
+ // we do still set remoteOrderChanged as it has
1745
+ remoteOrderChanged = true;
1746
+ removed.add(prevMember);
1747
+ onDel(prevMember);
1748
+ }
1749
+ }
1750
+ }
1751
+ return {
1752
+ add: added,
1753
+ del: removed,
1754
+ finalState,
1755
+ finalSet,
1756
+ changed,
1757
+ remoteOrderChanged
1758
+ };
1759
+ }
1760
+ function diffCollection(finalState, relationship, onAdd, onDel) {
1761
+ const finalSet = new Set(finalState);
1762
+ const {
1763
+ localState: priorLocalState,
1764
+ remoteState,
1765
+ remoteMembers
1766
+ } = relationship;
1767
+ {
1768
+ if (finalState.length !== finalSet.size) {
1769
+ const {
1770
+ diff,
1771
+ duplicates
1772
+ } = _deprecatedCompare(priorLocalState, finalState, finalSet, remoteState, remoteMembers, onAdd, onDel, relationship.definition.resetOnRemoteUpdate);
1773
+ {
1774
+ console.warn(`Expected all entries in the relationship ${relationship.definition.type}:${relationship.definition.key} to be unique, see log for a list of duplicate entry indeces`); // eslint-disable-next-line no-console
1775
+ console.log(duplicates);
1776
+ }
1777
+ return diff;
1778
+ }
1779
+ }
1780
+ return _compare(priorLocalState, finalState, finalSet, remoteState, remoteMembers, onAdd, onDel, relationship.definition.resetOnRemoteUpdate);
1781
+ }
1782
+ function computeLocalState(storage) {
1783
+ if (!storage.isDirty) {
1784
+ (test => {
1785
+ if (!test) {
1786
+ throw new Error(`Expected localState to be present`);
1787
+ }
1788
+ })(Array.isArray(storage.localState));
1789
+ return storage.localState;
1790
+ }
1791
+ const state = storage.remoteState.slice();
1792
+ storage.removals?.forEach(v => {
1793
+ const index = state.indexOf(v);
1794
+ state.splice(index, 1);
1795
+ });
1796
+ storage.additions?.forEach(v => {
1797
+ state.push(v);
1798
+ });
1799
+ storage.localState = state;
1800
+ storage.isDirty = false;
1801
+ return state;
1802
+ }
1803
+
1804
+ /**
1805
+ * A function which attempts to add a value to the local state of a collection
1806
+ * relationship, and returns true if the value was added, or false if it was
1807
+ * already present.
1808
+ *
1809
+ * It will not generate a notification, will not update the relationships to dirty,
1810
+ * and will not update the inverse relationships, making it suitable for use as
1811
+ * an internal util to perform the just the addition to a specific side of a
1812
+ * relationship.
1813
+ *
1814
+ * @internal
1815
+ */
1816
+ function _add(graph, record, relationship, value, index, isRemote) {
1817
+ return !isRemote ? _addLocal(graph, record, relationship, value, index) : _addRemote(graph, record, relationship, value, index);
1818
+ }
1819
+ function _addRemote(graph, record, relationship, value, index) {
1820
+ (test => {
1821
+ if (!test) {
1822
+ throw new Error(`expected an identifier to add to the collection relationship`);
1823
+ }
1824
+ })(value);
1825
+ const {
1826
+ remoteMembers,
1827
+ additions,
1828
+ removals,
1829
+ remoteState
1830
+ } = relationship;
1831
+ (test => {
1832
+ if (!test) {
1833
+ throw new Error(`Cannot add a resource that is already present`);
1834
+ }
1835
+ })(!remoteMembers.has(value));
1836
+ if (remoteMembers.has(value)) {
1837
+ return false;
1838
+ }
1839
+
1840
+ // add to the remote state
1841
+ remoteMembers.add(value);
1842
+ (test => {
1843
+ if (!test) {
1844
+ throw new Error(`Cannot insert at an index that is not in bounds`);
1845
+ }
1846
+ })(index === null || index >= 0 && index < remoteState.length);
1847
+ const hasValidIndex = index !== null && index >= 0 && index < remoteState.length;
1848
+ if (hasValidIndex) {
1849
+ remoteState.splice(index, 0, value);
1850
+ } else {
1851
+ remoteState.push(value);
1852
+ }
1853
+
1854
+ // remove from additions if present
1855
+ if (additions?.has(value)) {
1856
+ additions.delete(value);
1857
+
1858
+ // nothing more to do this was our state already
1859
+ return false;
1860
+ }
1861
+ (test => {
1862
+ if (!test) {
1863
+ throw new Error(`Remote state indicated addition of a resource that was present only as a local mutation`);
1864
+ }
1865
+ })(!removals?.has(value));
1866
+
1867
+ // if the relationship already needs to recalc, we don't bother
1868
+ // attempting to patch the localState
1869
+ if (relationship.isDirty) {
1870
+ return true;
1871
+ }
1872
+
1873
+ // if we have existing localState
1874
+ // we attempt to patch it without blowing it away
1875
+ // as this is more efficient than recomputing
1876
+ // it allows us to preserve local ordering
1877
+ // to a small extent. Local ordering should not
1878
+ // be relied upon as any remote change could blow it away
1879
+ if (relationship.localState) {
1880
+ if (!hasValidIndex) {
1881
+ relationship.localState.push(value);
1882
+ } else if (index === 0) {
1883
+ relationship.localState.unshift(value);
1884
+ } else if (!removals?.size) {
1885
+ relationship.localState.splice(index, 0, value);
1886
+ } else {
1887
+ relationship.isDirty = true;
1888
+ }
1889
+ }
1890
+ return true;
1891
+ }
1892
+ function _addLocal(graph, record, relationship, value, index) {
1893
+ const {
1894
+ remoteMembers,
1895
+ removals
1896
+ } = relationship;
1897
+ let additions = relationship.additions;
1898
+ const hasPresence = remoteMembers.has(value) || additions?.has(value);
1899
+ if (hasPresence && !removals?.has(value)) {
1900
+ (test => {
1901
+ if (!test) {
1902
+ throw new Error(`Attempted to add the resource '${value.lid}' to the collection <${relationship.identifier.type}>.${relationship.definition.key} it was already in`);
1903
+ }
1904
+ })(hasPresence && !removals?.has(value));
1905
+ return false;
1906
+ }
1907
+ if (removals?.has(value)) {
1908
+ removals.delete(value);
1909
+ } else {
1910
+ if (!additions) {
1911
+ additions = relationship.additions = new Set();
1912
+ }
1913
+ relationship.state.hasReceivedData = true;
1914
+ additions.add(value);
1915
+ const {
1916
+ type
1917
+ } = relationship.definition;
1918
+ if (type !== value.type) {
1919
+ {
1920
+ assertPolymorphicType(record, relationship.definition, value, graph.store);
1921
+ }
1922
+ graph.registerPolymorphicType(value.type, type);
1923
+ }
1924
+ }
1925
+
1926
+ // if we have existing localState
1927
+ // and we have an index
1928
+ // apply the change, as this is more efficient
1929
+ // than recomputing localState and
1930
+ // it allows us to preserve local ordering
1931
+ // to a small extend. Local ordering should not
1932
+ // be relied upon as any remote change will blow it away
1933
+ if (relationship.localState) {
1934
+ if (index !== null) {
1935
+ relationship.localState.splice(index, 0, value);
1936
+ } else {
1937
+ relationship.localState.push(value);
1938
+ }
1939
+ }
1940
+ return true;
1941
+ }
1942
+ function _remove(graph, record, relationship, value, index, isRemote) {
1943
+ return !isRemote ? _removeLocal(relationship, value) : _removeRemote(relationship, value);
1944
+ }
1945
+ function _removeLocal(relationship, value) {
1946
+ (test => {
1947
+ if (!test) {
1948
+ throw new Error(`expected an identifier to remove from the collection relationship`);
1949
+ }
1950
+ })(value);
1951
+ const {
1952
+ remoteMembers,
1953
+ additions
1954
+ } = relationship;
1955
+ let removals = relationship.removals;
1956
+ const hasPresence = remoteMembers.has(value) || additions?.has(value);
1957
+ if (!hasPresence || removals?.has(value)) {
1958
+ (test => {
1959
+ if (!test) {
1960
+ throw new Error(`Attempted to remove the resource '${value.lid}' from the collection <${relationship.identifier.type}>.${relationship.definition.key} but it was not present`);
1961
+ }
1962
+ })(!hasPresence || removals?.has(value));
1963
+ return false;
1964
+ }
1965
+ if (additions?.has(value)) {
1966
+ additions.delete(value);
1967
+ } else {
1968
+ if (!removals) {
1969
+ removals = relationship.removals = new Set();
1970
+ }
1971
+ removals.add(value);
1972
+ }
1973
+
1974
+ // if we have existing localState
1975
+ // apply the change, as this is more efficient
1976
+ // than recomputing localState and
1977
+ // it allows us to preserve local ordering
1978
+ // to a small extend. Local ordering should not
1979
+ // be relied upon as any remote change will blow it away
1980
+ if (relationship.localState) {
1981
+ const index = relationship.localState.indexOf(value);
1982
+ (test => {
1983
+ if (!test) {
1984
+ throw new Error(`Cannot remove a resource that is not present`);
1985
+ }
1986
+ })(index !== -1);
1987
+ relationship.localState.splice(index, 1);
1988
+ }
1989
+ (test => {
1990
+ if (!test) {
1991
+ throw new Error(`Expected relationship to be dirty when performing a local mutation`);
1992
+ }
1993
+ })(relationship.localState || relationship.isDirty);
1994
+ return true;
1995
+ }
1996
+ function _removeRemote(relationship, value) {
1997
+ (test => {
1998
+ if (!test) {
1999
+ throw new Error(`expected an identifier to remove from the collection relationship`);
2000
+ }
2001
+ })(value);
2002
+ const {
2003
+ remoteMembers,
2004
+ additions,
2005
+ removals,
2006
+ remoteState
2007
+ } = relationship;
2008
+ (test => {
2009
+ if (!test) {
2010
+ throw new Error(`Cannot remove a resource that is not present`);
2011
+ }
2012
+ })(remoteMembers.has(value));
2013
+ if (!remoteMembers.has(value)) {
2014
+ return false;
2015
+ }
2016
+
2017
+ // remove from remote state
2018
+ remoteMembers.delete(value);
2019
+ let index = remoteState.indexOf(value);
2020
+ (test => {
2021
+ if (!test) {
2022
+ throw new Error(`Cannot remove a resource that is not present`);
2023
+ }
2024
+ })(index !== -1);
2025
+ remoteState.splice(index, 1);
2026
+
2027
+ // remove from removals if present
2028
+ if (removals?.has(value)) {
2029
+ removals.delete(value);
2030
+
2031
+ // nothing more to do this was our state already
2032
+ return false;
2033
+ }
2034
+ (test => {
2035
+ if (!test) {
2036
+ throw new Error(`Remote state indicated removal of a resource that was present only as a local mutation`);
2037
+ }
2038
+ })(!additions?.has(value));
2039
+
2040
+ // if we have existing localState
2041
+ // and we have an index
2042
+ // apply the change, as this is more efficient
2043
+ // than recomputing localState and
2044
+ // it allows us to preserve local ordering
2045
+ // to a small extend. Local ordering should not
2046
+ // be relied upon as any remote change will blow it away
2047
+ if (relationship.localState) {
2048
+ index = relationship.localState.indexOf(value);
2049
+ (test => {
2050
+ if (!test) {
2051
+ throw new Error(`Cannot remove a resource that is not present`);
2052
+ }
2053
+ })(index !== -1);
2054
+ relationship.localState.splice(index, 1);
2055
+ }
2056
+ (test => {
2057
+ if (!test) {
2058
+ throw new Error(`Expected relationship to be dirty when performing a local mutation`);
2059
+ }
2060
+ })(relationship.localState || relationship.isDirty);
2061
+ return true;
2062
+ }
2063
+ function rollbackRelationship(graph, key, field, relationship) {
2064
+ if (isBelongsTo(relationship)) {
2065
+ replaceRelatedRecord(graph, {
2066
+ op: 'replaceRelatedRecord',
2067
+ record: key,
2068
+ field,
2069
+ value: relationship.remoteState
2070
+ }, false);
2071
+ } else {
2072
+ replaceRelatedRecords(graph, {
2073
+ op: 'replaceRelatedRecords',
2074
+ record: key,
2075
+ field,
2076
+ value: relationship.remoteState.slice()
2077
+ }, false);
2078
+
2079
+ // when the change was a "reorder" only we wont have generated
2080
+ // a notification yet.
2081
+ // if we give rollback a unique operation we can use the ability of
2082
+ // diff to report a separate `remoteOrderChanged` flag to trigger this
2083
+ // if needed to avoid the duplicate.
2084
+ notifyChange(graph, relationship);
2085
+ }
2086
+ }
2087
+ function createState() {
2088
+ return {
2089
+ hasReceivedData: false,
2090
+ isEmpty: true,
2091
+ isStale: false,
2092
+ hasFailedLoadAttempt: false,
2093
+ shouldForceReload: false,
2094
+ hasDematerializedInverse: false
2095
+ };
2096
+ }
2097
+ function createCollectionEdge(definition, identifier) {
2098
+ return {
2099
+ definition,
2100
+ identifier,
2101
+ state: createState(),
2102
+ remoteMembers: new Set(),
2103
+ remoteState: [],
2104
+ additions: null,
2105
+ removals: null,
2106
+ meta: null,
2107
+ links: null,
2108
+ localState: null,
2109
+ isDirty: false,
2110
+ transactionRef: 0,
2111
+ accessed: false,
2112
+ _diff: undefined
2113
+ };
2114
+ }
2115
+ const cp = structuredClone;
2116
+ function legacyGetCollectionRelationshipData(source, getRemoteState) {
2117
+ source.accessed = true;
2118
+ const payload = {};
2119
+ if (source.state.hasReceivedData) {
2120
+ payload.data = getRemoteState ? source.remoteState.slice() : computeLocalState(source);
2121
+ }
2122
+ if (source.links) {
2123
+ payload.links = cp(source.links);
2124
+ }
2125
+ if (source.meta) {
2126
+ payload.meta = cp(source.meta);
2127
+ }
2128
+ return payload;
2129
+ }
2130
+
2131
+ /**
2132
+ Implicit relationships are relationships which have not been declared but the inverse side exists on
2133
+ another record somewhere
2134
+
2135
+ For example consider the following two models
2136
+
2137
+ ::: code-group
2138
+
2139
+ ```js [./models/comment.js]
2140
+ import { Model, attr } from '@warp-drive/legacy/model';
2141
+
2142
+ export default class Comment extends Model {
2143
+ @attr text;
2144
+ }
2145
+ ```
2146
+
2147
+ ```js [./models/post.js]
2148
+ import { Model, attr, hasMany } from '@warp-drive/legacy/model';
2149
+
2150
+ export default class Post extends Model {
2151
+ @attr title;
2152
+ @hasMany('comment', { async: true, inverse: null }) comments;
2153
+ }
2154
+ ```
2155
+
2156
+ :::
2157
+
2158
+ Then we would have a implicit 'post' relationship for the comment record in order
2159
+ to be do things like remove the comment from the post if the comment were to be deleted.
2160
+ */
2161
+
2162
+ function createImplicitEdge(definition, identifier) {
2163
+ return {
2164
+ definition,
2165
+ identifier,
2166
+ localMembers: new Set(),
2167
+ remoteMembers: new Set()
2168
+ };
2169
+ }
2170
+
2171
+ /**
2172
+ * Stores the data for one side of a "single" resource relationship.
2173
+ *
2174
+ * @private
2175
+ */
2176
+
2177
+ function createResourceEdge(definition, identifier) {
2178
+ return {
2179
+ definition,
2180
+ identifier,
2181
+ state: createState(),
2182
+ transactionRef: 0,
2183
+ localState: null,
2184
+ remoteState: null,
2185
+ meta: null,
2186
+ links: null,
2187
+ accessed: false
2188
+ };
2189
+ }
2190
+ function legacyGetResourceRelationshipData(source, getRemoteState) {
2191
+ source.accessed = true;
2192
+ let data;
2193
+ const payload = {};
2194
+ if (getRemoteState && source.remoteState) {
2195
+ data = source.remoteState;
2196
+ } else if (!getRemoteState && source.localState) {
2197
+ data = source.localState;
2198
+ }
2199
+ if ((getRemoteState && source.remoteState === null || source.localState === null) && source.state.hasReceivedData) {
2200
+ data = null;
2201
+ }
2202
+ if (source.links) {
2203
+ payload.links = source.links;
2204
+ }
2205
+ if (data !== undefined) {
2206
+ payload.data = data;
2207
+ }
2208
+ if (source.meta) {
2209
+ payload.meta = source.meta;
2210
+ }
2211
+ return payload;
2212
+ }
2213
+ function addToRelatedRecords(graph, op, isRemote) {
2214
+ const {
2215
+ record,
2216
+ value,
2217
+ index
2218
+ } = op;
2219
+ const relationship = graph.get(record, op.field);
2220
+ const _isBelongsTo = isBelongsTo(relationship);
2221
+ if (isRemote && _isBelongsTo) {
2222
+ if (value !== relationship.remoteState) {
2223
+ const newOp = {
2224
+ op: 'replaceRelatedRecord',
2225
+ record,
2226
+ field: op.field,
2227
+ value: value
2228
+ };
2229
+ return replaceRelatedRecord(graph, newOp, isRemote);
2230
+ }
2231
+ (test => {
2232
+ if (!test) {
2233
+ throw new Error(`Expected '${value?.lid}' (the value to add) to NOT be the same as the remote state '${relationship.remoteState?.lid ?? '<null>'}'`);
2234
+ }
2235
+ })(value === relationship.remoteState);
2236
+ return;
2237
+ }
2238
+ (test => {
2239
+ if (!test) {
2240
+ throw new Error(`You can only '${op.op}' on a hasMany relationship. ${record.type}.${op.field} is a ${relationship.definition.kind}`);
2241
+ }
2242
+ })(isHasMany(relationship));
2243
+
2244
+ // if we are not dirty but have a null localState then we
2245
+ // are mutating a relationship that has never been fetched
2246
+ // so we initialize localState to an empty array
2247
+ if (!relationship.isDirty && !relationship.localState) {
2248
+ relationship.localState = [];
2249
+ }
2250
+ if (Array.isArray(value)) {
2251
+ for (let i = 0; i < value.length; i++) {
2252
+ addRelatedRecord(graph, relationship, record, value[i], index !== undefined ? index + i : null, isRemote);
2253
+ }
2254
+ } else {
2255
+ addRelatedRecord(graph, relationship, record, value, index ?? null, isRemote);
2256
+ }
2257
+ notifyChange(graph, relationship);
2258
+ }
2259
+ function addRelatedRecord(graph, relationship, record, value, index, isRemote) {
2260
+ (test => {
2261
+ if (!test) {
2262
+ throw new Error(`expected an identifier to add to the collection relationship`);
2263
+ }
2264
+ })(value);
2265
+ if (_add(graph, record, relationship, value, index, isRemote)) {
2266
+ addToInverse(graph, value, relationship.definition.inverseKey, record, isRemote);
2267
+ }
2268
+ }
2269
+ function mergeIdentifier(graph, op, relationships) {
2270
+ Object.keys(relationships).forEach(key => {
2271
+ const rel = relationships[key];
2272
+ if (!rel) {
2273
+ return;
2274
+ }
2275
+ mergeIdentifierForRelationship(graph, op, rel);
2276
+ });
2277
+ }
2278
+ function mergeIdentifierForRelationship(graph, op, rel) {
2279
+ rel.identifier = op.value;
2280
+ forAllRelatedIdentifiers(rel, identifier => {
2281
+ const inverse = graph.get(identifier, rel.definition.inverseKey);
2282
+ mergeInRelationship(graph, inverse, op);
2283
+ });
2284
+ }
2285
+ function mergeInRelationship(graph, rel, op) {
2286
+ if (isBelongsTo(rel)) {
2287
+ mergeBelongsTo(graph, rel, op);
2288
+ } else if (isHasMany(rel)) {
2289
+ mergeHasMany(graph, rel, op);
2290
+ } else {
2291
+ mergeImplicit(graph, rel, op);
2292
+ }
2293
+ }
2294
+ function mergeBelongsTo(graph, rel, op) {
2295
+ if (rel.remoteState === op.record) {
2296
+ rel.remoteState = op.value;
2297
+ }
2298
+ if (rel.localState === op.record) {
2299
+ rel.localState = op.value;
2300
+ notifyChange(graph, rel);
2301
+ }
2302
+ }
2303
+ function mergeHasMany(graph, rel, op) {
2304
+ if (rel.remoteMembers.has(op.record)) {
2305
+ rel.remoteMembers.delete(op.record);
2306
+ rel.remoteMembers.add(op.value);
2307
+ const index = rel.remoteState.indexOf(op.record);
2308
+ rel.remoteState.splice(index, 1, op.value);
2309
+ rel.isDirty = true;
2310
+ }
2311
+ if (rel.additions?.has(op.record)) {
2312
+ rel.additions.delete(op.record);
2313
+ rel.additions.add(op.value);
2314
+ rel.isDirty = true;
2315
+ }
2316
+ if (rel.removals?.has(op.record)) {
2317
+ rel.removals.delete(op.record);
2318
+ rel.removals.add(op.value);
2319
+ rel.isDirty = true;
2320
+ }
2321
+ if (rel.isDirty) {
2322
+ notifyChange(graph, rel);
2323
+ }
2324
+ }
2325
+ function mergeImplicit(graph, rel, op) {
2326
+ if (rel.remoteMembers.has(op.record)) {
2327
+ rel.remoteMembers.delete(op.record);
2328
+ rel.remoteMembers.add(op.value);
2329
+ }
2330
+ if (rel.localMembers.has(op.record)) {
2331
+ rel.localMembers.delete(op.record);
2332
+ rel.localMembers.add(op.value);
2333
+ }
2334
+ }
2335
+ function removeFromRelatedRecords(graph, op, isRemote) {
2336
+ const {
2337
+ record,
2338
+ value
2339
+ } = op;
2340
+ const relationship = graph.get(record, op.field);
2341
+ const _isBelongsTo = isBelongsTo(relationship);
2342
+ if (isRemote && _isBelongsTo) {
2343
+ if (value === relationship.remoteState) {
2344
+ const newOp = {
2345
+ op: 'replaceRelatedRecord',
2346
+ record,
2347
+ field: op.field,
2348
+ value: null
2349
+ };
2350
+ return replaceRelatedRecord(graph, newOp, isRemote);
2351
+ }
2352
+ (test => {
2353
+ if (!test) {
2354
+ throw new Error(`Expected '${value?.lid}' (the value to remove) to be the same as the remote state '${relationship.remoteState?.lid ?? '<null>'}'`);
2355
+ }
2356
+ })(value === relationship.remoteState);
2357
+ return;
2358
+ }
2359
+ (test => {
2360
+ if (!test) {
2361
+ throw new Error(`You can only '${op.op}' on a hasMany relationship. ${record.type}.${op.field} is a ${relationship.definition.kind}`);
2362
+ }
2363
+ })(isHasMany(relationship));
2364
+ if (Array.isArray(value)) {
2365
+ for (let i = 0; i < value.length; i++) {
2366
+ removeRelatedRecord(graph, record, relationship, value[i], op.index ?? null, isRemote);
2367
+ }
2368
+ } else {
2369
+ removeRelatedRecord(graph, record, relationship, value, op.index ?? null, isRemote);
2370
+ }
2371
+ notifyChange(graph, relationship);
2372
+ }
2373
+ function removeRelatedRecord(graph, record, relationship, value, index, isRemote) {
2374
+ (test => {
2375
+ if (!test) {
2376
+ throw new Error(`expected an identifier to remove from the collection relationship`);
2377
+ }
2378
+ })(value);
2379
+ if (_remove(graph, record, relationship, value, index, isRemote)) {
2380
+ removeFromInverse(graph, value, relationship.definition.inverseKey, record, isRemote);
2381
+ }
2382
+ }
2383
+
2384
+ /*
2385
+ This method normalizes a link to an "links object". If the passed link is
2386
+ already an object it's returned without any modifications.
2387
+
2388
+ See http://jsonapi.org/format/#document-links for more information.
2389
+ */
2390
+ function _normalizeLink(link) {
2391
+ switch (typeof link) {
2392
+ case 'object':
2393
+ return link;
2394
+ case 'string':
2395
+ return {
2396
+ href: link
2397
+ };
2398
+ }
2399
+ }
2400
+
2401
+ /*
2402
+ Updates the "canonical" or "remote" state of a relationship, replacing any existing
2403
+ state and blowing away any local changes (excepting new records).
2404
+ */
2405
+ function updateRelationshipOperation(graph, op) {
2406
+ const relationship = graph.get(op.record, op.field);
2407
+ (test => {
2408
+ if (!test) {
2409
+ throw new Error(`Cannot update an implicit relationship`);
2410
+ }
2411
+ })(isHasMany(relationship) || isBelongsTo(relationship));
2412
+ const {
2413
+ definition,
2414
+ state,
2415
+ identifier
2416
+ } = relationship;
2417
+ const {
2418
+ isCollection
2419
+ } = definition;
2420
+ const payload = op.value;
2421
+ let hasRelationshipDataProperty = false;
2422
+ let hasUpdatedLink = false;
2423
+ if (payload.meta) {
2424
+ relationship.meta = payload.meta;
2425
+ }
2426
+ if (payload.data !== undefined) {
2427
+ hasRelationshipDataProperty = true;
2428
+ if (isCollection) {
2429
+ // TODO deprecate this case. We
2430
+ // have tests saying we support it.
2431
+ if (payload.data === null) {
2432
+ payload.data = [];
2433
+ }
2434
+ (test => {
2435
+ if (!test) {
2436
+ throw new Error(`Expected an array`);
2437
+ }
2438
+ })(Array.isArray(payload.data));
2439
+ const cache = graph.store.cacheKeyManager;
2440
+ graph.update({
2441
+ op: 'replaceRelatedRecords',
2442
+ record: identifier,
2443
+ field: op.field,
2444
+ value: upgradeIdentifiers(payload.data, cache)
2445
+ }, true);
2446
+ } else {
2447
+ graph.update({
2448
+ op: 'replaceRelatedRecord',
2449
+ record: identifier,
2450
+ field: op.field,
2451
+ value: payload.data ? graph.store.cacheKeyManager.upgradeIdentifier(payload.data) : null
2452
+ }, true);
2453
+ }
2454
+ } else if (definition.isAsync === false && !state.hasReceivedData) {
2455
+ hasRelationshipDataProperty = true;
2456
+ if (isCollection) {
2457
+ graph.update({
2458
+ op: 'replaceRelatedRecords',
2459
+ record: identifier,
2460
+ field: op.field,
2461
+ value: []
2462
+ }, true);
2463
+ } else {
2464
+ graph.update({
2465
+ op: 'replaceRelatedRecord',
2466
+ record: identifier,
2467
+ field: op.field,
2468
+ value: null
2469
+ }, true);
2470
+ }
2471
+ }
2472
+ if (payload.links) {
2473
+ const originalLinks = relationship.links;
2474
+ relationship.links = payload.links;
2475
+ if (payload.links.related) {
2476
+ const relatedLink = _normalizeLink(payload.links.related);
2477
+ const currentLink = originalLinks && originalLinks.related ? _normalizeLink(originalLinks.related) : null;
2478
+ const currentLinkHref = currentLink ? currentLink.href : null;
2479
+ if (relatedLink && relatedLink.href && relatedLink.href !== currentLinkHref) {
2480
+ console.warn(`You pushed a record of type '${identifier.type}' with a relationship '${definition.key}' configured as 'async: false'. You've included a link but no primary data, this may be an error in your payload. WarpDrive will treat this relationship as known-to-be-empty.`, definition.isAsync || state.hasReceivedData, {
2481
+ id: 'ds.store.push-link-for-sync-relationship'
2482
+ });
2483
+ (test => {
2484
+ if (!test) {
2485
+ throw new Error(`You have pushed a record of type '${identifier.type}' with '${definition.key}' as a link, but the value of that link is not a string.`);
2486
+ }
2487
+ })(typeof relatedLink.href === 'string' || relatedLink.href === null);
2488
+ hasUpdatedLink = true;
2489
+ }
2490
+ }
2491
+ }
2492
+
2493
+ /*
2494
+ Data being pushed into the relationship might contain only data or links,
2495
+ or a combination of both.
2496
+ IF contains only data
2497
+ IF contains both links and data
2498
+ state.isEmpty -> true if is empty array (has-many) or is null (belongs-to)
2499
+ state.hasReceivedData -> true
2500
+ hasDematerializedInverse -> false
2501
+ state.isStale -> false
2502
+ allInverseRecordsAreLoaded -> run-check-to-determine
2503
+ IF contains only links
2504
+ state.isStale -> true
2505
+ */
2506
+ relationship.state.hasFailedLoadAttempt = false;
2507
+ if (hasRelationshipDataProperty) {
2508
+ const relationshipIsEmpty = payload.data === null || Array.isArray(payload.data) && payload.data.length === 0;
2509
+
2510
+ // we don't need to notify here as the update op we pushed in above will notify once
2511
+ // membership is in the correct state.
2512
+ relationship.state.hasReceivedData = true;
2513
+ relationship.state.isStale = false;
2514
+ relationship.state.hasDematerializedInverse = false;
2515
+ relationship.state.isEmpty = relationshipIsEmpty;
2516
+ } else if (hasUpdatedLink) {
2517
+ // only notify stale if we have not previously received membership data.
2518
+ // within this same transaction
2519
+ // this prevents refetching when only one side of the relationship in the
2520
+ // payload contains the info while the other side contains just a link
2521
+ // this only works when the side with just a link is a belongsTo, as we
2522
+ // don't know if a hasMany has full information or not.
2523
+ // see #7049 for context.
2524
+ if (isCollection || !relationship.state.hasReceivedData || isStaleTransaction(relationship.transactionRef, graph._transaction)) {
2525
+ relationship.state.isStale = true;
2526
+ notifyChange(graph, relationship);
2527
+ } else {
2528
+ relationship.state.isStale = false;
2529
+ }
2530
+ }
2531
+ }
2532
+ function isStaleTransaction(relationshipTransactionId, graphTransactionId) {
2533
+ return relationshipTransactionId === 0 ||
2534
+ // relationship has never notified
2535
+ graphTransactionId === null ||
2536
+ // we are not in a transaction
2537
+ relationshipTransactionId < graphTransactionId // we are not part of the current transaction
2538
+ ;
2539
+ }
2540
+ function upgradeIdentifiers(arr, cache) {
2541
+ for (let i = 0; i < arr.length; i++) {
2542
+ arr[i] = cache.upgradeIdentifier(arr[i]);
2543
+ }
2544
+ return arr;
2545
+ }
2546
+ const Graphs = getOrSetGlobal('Graphs', new Map());
2547
+ /*
2548
+ * Graph acts as the cache for relationship data. It allows for
2549
+ * us to ask about and update relationships for a given Identifier
2550
+ * without requiring other objects for that Identifier to be
2551
+ * instantiated (such as `RecordData` or a `Record`)
2552
+ *
2553
+ * This also allows for us to make more substantive changes to relationships
2554
+ * with increasingly minor alterations to other portions of the internals
2555
+ * over time.
2556
+ *
2557
+ * The graph is made up of nodes and edges. Each unique identifier gets
2558
+ * its own node, which is a dictionary with a list of that node's edges
2559
+ * (or connections) to other nodes. In `Model` terms, a node represents a
2560
+ * record instance, with each key (an edge) in the dictionary correlating
2561
+ * to either a `hasMany` or `belongsTo` field on that record instance.
2562
+ *
2563
+ * The value for each key, or `edge` is the identifier(s) the node relates
2564
+ * to in the graph from that key.
2565
+ */
2566
+ class Graph {
2567
+ constructor(store) {
2568
+ this._definitionCache = Object.create(null);
2569
+ this._metaCache = Object.create(null);
2570
+ this._potentialPolymorphicTypes = Object.create(null);
2571
+ this.identifiers = new Map();
2572
+ this.store = store;
2573
+ this._realStore = store._store;
2574
+ this.isDestroyed = false;
2575
+ this._willSyncRemote = false;
2576
+ this._willSyncLocal = false;
2577
+ this._pushedUpdates = {
2578
+ belongsTo: undefined,
2579
+ hasMany: undefined,
2580
+ deletions: []
2581
+ };
2582
+ this._updatedRelationships = new Set();
2583
+ this._transaction = null;
2584
+ this._removing = null;
2585
+ this.silenceNotifications = false;
2586
+ }
2587
+ has(resourceKey, propertyName) {
2588
+ const relationships = this.identifiers.get(resourceKey);
2589
+ if (!relationships) {
2590
+ return false;
2591
+ }
2592
+ return relationships[propertyName] !== undefined;
2593
+ }
2594
+ getDefinition(resourceKey, propertyName) {
2595
+ let defs = this._metaCache[resourceKey.type];
2596
+ let meta = defs?.[propertyName];
2597
+ if (!meta) {
2598
+ const info = /*#__NOINLINE__*/upgradeDefinition(this, resourceKey, propertyName);
2599
+ (test => {
2600
+ if (!test) {
2601
+ throw new Error(`Could not determine relationship information for ${resourceKey.type}.${propertyName}`);
2602
+ }
2603
+ })(info !== null);
2604
+
2605
+ // if (info.rhs_definition?.kind === 'implicit') {
2606
+ // we should possibly also do this
2607
+ // but it would result in being extremely permissive for other relationships by accident
2608
+ // this.registerPolymorphicType(info.rhs_baseModelName, identifier.type);
2609
+ // }
2610
+
2611
+ meta = /*#__NOINLINE__*/isLHS(info, resourceKey.type, propertyName) ? info.lhs_definition : info.rhs_definition;
2612
+ defs = this._metaCache[resourceKey.type] = defs || {};
2613
+ defs[propertyName] = meta;
2614
+ }
2615
+ return meta;
2616
+ }
2617
+ get(resourceKey, propertyName) {
2618
+ (test => {
2619
+ if (!test) {
2620
+ throw new Error(`expected propertyName`);
2621
+ }
2622
+ })(propertyName);
2623
+ let relationships = this.identifiers.get(resourceKey);
2624
+ if (!relationships) {
2625
+ relationships = Object.create(null);
2626
+ this.identifiers.set(resourceKey, relationships);
2627
+ }
2628
+ let relationship = relationships[propertyName];
2629
+ if (!relationship) {
2630
+ const meta = this.getDefinition(resourceKey, propertyName);
2631
+ if (meta.kind === 'belongsTo') {
2632
+ relationship = relationships[propertyName] = createResourceEdge(meta, resourceKey);
2633
+ } else if (meta.kind === 'hasMany') {
2634
+ relationship = relationships[propertyName] = createCollectionEdge(meta, resourceKey);
2635
+ } else {
2636
+ (test => {
2637
+ if (!test) {
2638
+ throw new Error(`Expected kind to be implicit`);
2639
+ }
2640
+ })(meta.kind === 'implicit' && meta.isImplicit === true);
2641
+ relationship = relationships[propertyName] = createImplicitEdge(meta, resourceKey);
2642
+ }
2643
+ }
2644
+ return relationship;
2645
+ }
2646
+ getData(resourceKey, propertyName) {
2647
+ const relationship = this.get(resourceKey, propertyName);
2648
+ (test => {
2649
+ if (!test) {
2650
+ throw new Error(`Cannot getData() on an implicit relationship`);
2651
+ }
2652
+ })(!isImplicit(relationship));
2653
+ if (isBelongsTo(relationship)) {
2654
+ return legacyGetResourceRelationshipData(relationship, false);
2655
+ }
2656
+ return legacyGetCollectionRelationshipData(relationship, false);
2657
+ }
2658
+ getRemoteData(resourceKey, propertyName) {
2659
+ const relationship = this.get(resourceKey, propertyName);
2660
+ (test => {
2661
+ if (!test) {
2662
+ throw new Error(`Cannot getRemoteData() on an implicit relationship`);
2663
+ }
2664
+ })(!isImplicit(relationship));
2665
+ if (isBelongsTo(relationship)) {
2666
+ return legacyGetResourceRelationshipData(relationship, true);
2667
+ }
2668
+ return legacyGetCollectionRelationshipData(relationship, true);
2669
+ }
2670
+
2671
+ /*
2672
+ * Allows for the graph to dynamically discover polymorphic connections
2673
+ * without needing to walk prototype chains.
2674
+ *
2675
+ * Used by edges when an added `type` does not match the expected `type`
2676
+ * for that edge.
2677
+ *
2678
+ * Currently we assert before calling this. For a public API we will want
2679
+ * to call out to the schema manager to ask if we should consider these
2680
+ * types as equivalent for a given relationship.
2681
+ */
2682
+ registerPolymorphicType(type1, type2) {
2683
+ const typeCache = this._potentialPolymorphicTypes;
2684
+ let t1 = typeCache[type1];
2685
+ if (!t1) {
2686
+ t1 = typeCache[type1] = Object.create(null);
2687
+ }
2688
+ t1[type2] = true;
2689
+ let t2 = typeCache[type2];
2690
+ if (!t2) {
2691
+ t2 = typeCache[type2] = Object.create(null);
2692
+ }
2693
+ t2[type1] = true;
2694
+ }
2695
+ isReleasable(resourceKey) {
2696
+ const relationships = this.identifiers.get(resourceKey);
2697
+ if (!relationships) {
2698
+ {
2699
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2700
+ // eslint-disable-next-line no-console
2701
+ console.log(`graph: RELEASABLE ${String(resourceKey)}`);
2702
+ }
2703
+ }
2704
+ return true;
2705
+ }
2706
+ const keys = Object.keys(relationships);
2707
+ for (let i = 0; i < keys.length; i++) {
2708
+ const relationship = relationships[keys[i]];
2709
+ // account for previously unloaded relationships
2710
+ // typically from a prior deletion of a record that pointed to this one implicitly
2711
+ if (relationship === undefined) {
2712
+ continue;
2713
+ }
2714
+ (test => {
2715
+ if (!test) {
2716
+ throw new Error(`Expected a relationship`);
2717
+ }
2718
+ })(relationship);
2719
+ if (relationship.definition.inverseIsAsync && !checkIfNew(this._realStore, resourceKey)) {
2720
+ {
2721
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2722
+ // eslint-disable-next-line no-console
2723
+ console.log(`graph: <<NOT>> RELEASABLE ${String(resourceKey)}`);
2724
+ }
2725
+ }
2726
+ return false;
2727
+ }
2728
+ }
2729
+ {
2730
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2731
+ // eslint-disable-next-line no-console
2732
+ console.log(`graph: RELEASABLE ${String(resourceKey)}`);
2733
+ }
2734
+ }
2735
+ return true;
2736
+ }
2737
+ unload(resourceKey, silenceNotifications) {
2738
+ {
2739
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2740
+ // eslint-disable-next-line no-console
2741
+ console.log(`graph: unload ${String(resourceKey)}`);
2742
+ }
2743
+ }
2744
+ const relationships = this.identifiers.get(resourceKey);
2745
+ if (relationships) {
2746
+ // cleans up the graph but retains some nodes
2747
+ // to allow for rematerialization
2748
+ Object.keys(relationships).forEach(key => {
2749
+ const rel = relationships[key];
2750
+ if (!rel) {
2751
+ return;
2752
+ }
2753
+ /*#__NOINLINE__*/
2754
+ destroyRelationship(this, rel, silenceNotifications);
2755
+ if (/*#__NOINLINE__*/isImplicit(rel)) {
2756
+ // @ts-expect-error
2757
+ relationships[key] = undefined;
2758
+ }
2759
+ });
2760
+ }
2761
+ }
2762
+ _isDirty(resourceKey, field) {
2763
+ const relationships = this.identifiers.get(resourceKey);
2764
+ if (!relationships) {
2765
+ return false;
2766
+ }
2767
+ const relationship = relationships[field];
2768
+ if (!relationship) {
2769
+ return false;
2770
+ }
2771
+ if (isBelongsTo(relationship)) {
2772
+ return relationship.localState !== relationship.remoteState;
2773
+ } else if (isHasMany(relationship)) {
2774
+ const hasAdditions = relationship.additions !== null && relationship.additions.size > 0;
2775
+ const hasRemovals = relationship.removals !== null && relationship.removals.size > 0;
2776
+ return hasAdditions || hasRemovals || isReordered(relationship);
2777
+ }
2778
+ return false;
2779
+ }
2780
+ getChanged(resourceKey) {
2781
+ const relationships = this.identifiers.get(resourceKey);
2782
+ const changed = new Map();
2783
+ if (!relationships) {
2784
+ return changed;
2785
+ }
2786
+ const keys = Object.keys(relationships);
2787
+ for (let i = 0; i < keys.length; i++) {
2788
+ const field = keys[i];
2789
+ const relationship = relationships[field];
2790
+ if (!relationship) {
2791
+ continue;
2792
+ }
2793
+ if (isBelongsTo(relationship)) {
2794
+ if (relationship.localState !== relationship.remoteState) {
2795
+ changed.set(field, {
2796
+ kind: 'resource',
2797
+ remoteState: relationship.remoteState,
2798
+ localState: relationship.localState
2799
+ });
2800
+ }
2801
+ } else if (isHasMany(relationship)) {
2802
+ const hasAdditions = relationship.additions !== null && relationship.additions.size > 0;
2803
+ const hasRemovals = relationship.removals !== null && relationship.removals.size > 0;
2804
+ const reordered = isReordered(relationship);
2805
+ if (hasAdditions || hasRemovals || reordered) {
2806
+ changed.set(field, {
2807
+ kind: 'collection',
2808
+ additions: new Set(relationship.additions),
2809
+ removals: new Set(relationship.removals),
2810
+ remoteState: relationship.remoteState,
2811
+ localState: legacyGetCollectionRelationshipData(relationship, false).data || [],
2812
+ reordered
2813
+ });
2814
+ }
2815
+ }
2816
+ }
2817
+ return changed;
2818
+ }
2819
+ hasChanged(resourceKey) {
2820
+ const relationships = this.identifiers.get(resourceKey);
2821
+ if (!relationships) {
2822
+ return false;
2823
+ }
2824
+ const keys = Object.keys(relationships);
2825
+ for (let i = 0; i < keys.length; i++) {
2826
+ if (this._isDirty(resourceKey, keys[i])) {
2827
+ return true;
2828
+ }
2829
+ }
2830
+ return false;
2831
+ }
2832
+ rollback(resourceKey) {
2833
+ const relationships = this.identifiers.get(resourceKey);
2834
+ const changed = [];
2835
+ if (!relationships) {
2836
+ return changed;
2837
+ }
2838
+ const keys = Object.keys(relationships);
2839
+ for (let i = 0; i < keys.length; i++) {
2840
+ const field = keys[i];
2841
+ const relationship = relationships[field];
2842
+ if (!relationship) {
2843
+ continue;
2844
+ }
2845
+ if (this._isDirty(resourceKey, field)) {
2846
+ rollbackRelationship(this, resourceKey, field, relationship);
2847
+ changed.push(field);
2848
+ }
2849
+ }
2850
+ return changed;
2851
+ }
2852
+ remove(resourceKey) {
2853
+ {
2854
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2855
+ // eslint-disable-next-line no-console
2856
+ console.log(`graph: remove ${String(resourceKey)}`);
2857
+ }
2858
+ }
2859
+ (test => {
2860
+ if (!test) {
2861
+ throw new Error(`Cannot remove ${String(resourceKey)} while still removing ${String(this._removing)}`);
2862
+ }
2863
+ })(!this._removing);
2864
+ this._removing = resourceKey;
2865
+ this.unload(resourceKey);
2866
+ this.identifiers.delete(resourceKey);
2867
+ this._removing = null;
2868
+ }
2869
+
2870
+ /*
2871
+ * Remote state changes
2872
+ */
2873
+ push(op) {
2874
+ {
2875
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2876
+ // eslint-disable-next-line no-console
2877
+ console.log(`graph: push ${String(op.record)}`, op);
2878
+ }
2879
+ }
2880
+ if (op.op === 'deleteRecord') {
2881
+ this._pushedUpdates.deletions.push(op);
2882
+ } else {
2883
+ const definition = this.getDefinition(op.record, op.field);
2884
+ (test => {
2885
+ if (!test) {
2886
+ throw new Error(`Cannot push a remote update for an implicit relationship`);
2887
+ }
2888
+ })(definition.kind !== 'implicit');
2889
+ addPending(this._pushedUpdates, definition, op);
2890
+ }
2891
+ if (!this._willSyncRemote) {
2892
+ this._willSyncRemote = true;
2893
+ const store = getStore(this.store);
2894
+ if (!store._cbs) {
2895
+ store._run(() => this._flushRemoteQueue());
2896
+ } else {
2897
+ store._schedule('coalesce', () => this._flushRemoteQueue());
2898
+ }
2899
+ }
2900
+ }
2901
+
2902
+ /*
2903
+ * Local state changes
2904
+ */
2905
+
2906
+ update(op, isRemote = false) {
2907
+ (test => {
2908
+ if (!test) {
2909
+ throw new Error(`Cannot update an implicit relationship`);
2910
+ }
2911
+ })(op.op === 'deleteRecord' || op.op === 'mergeIdentifiers' || !isImplicit(this.get(op.record, op.field)));
2912
+ {
2913
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
2914
+ // eslint-disable-next-line no-console
2915
+ console.log(`graph: update (${isRemote ? 'remote' : 'local'}) ${String(op.record)}`, op);
2916
+ }
2917
+ }
2918
+ switch (op.op) {
2919
+ case 'mergeIdentifiers':
2920
+ {
2921
+ const relationships = this.identifiers.get(op.record);
2922
+ if (relationships) {
2923
+ /*#__NOINLINE__*/mergeIdentifier(this, op, relationships);
2924
+ }
2925
+ break;
2926
+ }
2927
+ case 'update':
2928
+ case 'updateRelationship':
2929
+ (test => {
2930
+ if (!test) {
2931
+ throw new Error(`Can only perform the operation updateRelationship on remote state`);
2932
+ }
2933
+ })(isRemote);
2934
+ {
2935
+ // in debug, assert payload validity eagerly
2936
+ // TODO add deprecations/assertion here for duplicates
2937
+ assertValidRelationshipPayload(this, op);
2938
+ }
2939
+ /*#__NOINLINE__*/
2940
+ updateRelationshipOperation(this, op);
2941
+ break;
2942
+ case 'deleteRecord':
2943
+ {
2944
+ (test => {
2945
+ if (!test) {
2946
+ throw new Error(`Can only perform the operation deleteRelationship on remote state`);
2947
+ }
2948
+ })(isRemote);
2949
+ const identifier = op.record;
2950
+ const relationships = this.identifiers.get(identifier);
2951
+ if (relationships) {
2952
+ Object.keys(relationships).forEach(key => {
2953
+ const rel = relationships[key];
2954
+ if (!rel) {
2955
+ return;
2956
+ }
2957
+ // works together with the has check
2958
+ // @ts-expect-error
2959
+ relationships[key] = undefined;
2960
+ /*#__NOINLINE__*/
2961
+ removeCompletelyFromInverse(this, rel);
2962
+ });
2963
+ this.identifiers.delete(identifier);
2964
+ }
2965
+ break;
2966
+ }
2967
+ case 'replaceRelatedRecord':
2968
+ /*#__NOINLINE__*/replaceRelatedRecord(this, op, isRemote);
2969
+ break;
2970
+ case 'add':
2971
+ /*#__NOINLINE__*/addToRelatedRecords(this, op, isRemote);
2972
+ break;
2973
+ case 'remove':
2974
+ /*#__NOINLINE__*/removeFromRelatedRecords(this, op, isRemote);
2975
+ break;
2976
+ case 'replaceRelatedRecords':
2977
+ /*#__NOINLINE__*/replaceRelatedRecords(this, op, isRemote);
2978
+ break;
2979
+ default:
2980
+ (test => {
2981
+ {
2982
+ throw new Error(`No local relationship update operation exists for '${op.op}'`);
2983
+ }
2984
+ })();
2985
+ }
2986
+ }
2987
+ _scheduleLocalSync(relationship) {
2988
+ this._updatedRelationships.add(relationship);
2989
+ if (!this._willSyncLocal) {
2990
+ this._willSyncLocal = true;
2991
+ getStore(this.store)._schedule('sync', () => this._flushLocalQueue());
2992
+ }
2993
+ }
2994
+ _flushRemoteQueue() {
2995
+ if (!this._willSyncRemote) {
2996
+ return;
2997
+ }
2998
+ {
2999
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
3000
+ // eslint-disable-next-line no-console
3001
+ console.groupCollapsed(`Graph: Initialized Transaction`);
3002
+ }
3003
+ }
3004
+ let transactionRef = peekTransient('transactionRef') ?? 0;
3005
+ this._transaction = ++transactionRef;
3006
+ setTransient('transactionRef', transactionRef);
3007
+ this._willSyncRemote = false;
3008
+ const updates = this._pushedUpdates;
3009
+ const {
3010
+ deletions,
3011
+ hasMany,
3012
+ belongsTo
3013
+ } = updates;
3014
+ updates.deletions = [];
3015
+ updates.hasMany = undefined;
3016
+ updates.belongsTo = undefined;
3017
+ for (let i = 0; i < deletions.length; i++) {
3018
+ this.update(deletions[i], true);
3019
+ }
3020
+ if (hasMany) {
3021
+ flushPending(this, hasMany);
3022
+ }
3023
+ if (belongsTo) {
3024
+ flushPending(this, belongsTo);
3025
+ }
3026
+ this._transaction = null;
3027
+ {
3028
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
3029
+ // eslint-disable-next-line no-console
3030
+ console.log(`Graph: transaction finalized`);
3031
+ // eslint-disable-next-line no-console
3032
+ console.groupEnd();
3033
+ }
3034
+ }
3035
+ }
3036
+ _addToTransaction(relationship) {
3037
+ (test => {
3038
+ if (!test) {
3039
+ throw new Error(`expected a transaction`);
3040
+ }
3041
+ })(this._transaction !== null);
3042
+ {
3043
+ if (getGlobalConfig().WarpDrive.debug.LOG_GRAPH || globalThis.getWarpDriveRuntimeConfig().debug.LOG_GRAPH) {
3044
+ // eslint-disable-next-line no-console
3045
+ console.log(`Graph: ${String(relationship.identifier)} ${relationship.definition.key} added to transaction`);
3046
+ }
3047
+ }
3048
+ relationship.transactionRef = this._transaction;
3049
+ }
3050
+ _flushLocalQueue() {
3051
+ if (!this._willSyncLocal) {
3052
+ return;
3053
+ }
3054
+ if (this.silenceNotifications) {
3055
+ this.silenceNotifications = false;
3056
+ this._updatedRelationships = new Set();
3057
+ return;
3058
+ }
3059
+ this._willSyncLocal = false;
3060
+ const updated = this._updatedRelationships;
3061
+ this._updatedRelationships = new Set();
3062
+ updated.forEach(rel => notifyChange(this, rel));
3063
+ }
3064
+ destroy() {
3065
+ Graphs.delete(this.store);
3066
+ {
3067
+ Graphs.delete(getStore(this.store));
3068
+ if (Graphs.size) {
3069
+ Graphs.forEach((_, key) => {
3070
+ (test => {
3071
+ if (!test) {
3072
+ throw new Error(`Memory Leak Detected, likely the test or app instance previous to this was not torn down properly`);
3073
+ }
3074
+ })(!key.isDestroyed && !key.isDestroying);
3075
+ });
3076
+ }
3077
+ }
3078
+ this.identifiers.clear();
3079
+ this.store = null;
3080
+ this.isDestroyed = true;
3081
+ }
3082
+ }
3083
+ function flushPending(graph, ops) {
3084
+ for (const type of ops.values()) {
3085
+ for (const opList of type.values()) {
3086
+ flushPendingList(graph, opList);
3087
+ }
3088
+ }
3089
+ }
3090
+ function flushPendingList(graph, opList) {
3091
+ for (let i = 0; i < opList.length; i++) {
3092
+ graph.update(opList[i], true);
3093
+ }
3094
+ }
3095
+
3096
+ // Handle dematerialization for relationship `rel`. In all cases, notify the
3097
+ // relationship of the dematerialization: this is done so the relationship can
3098
+ // notify its inverse which needs to update state
3099
+ //
3100
+ // If the inverse is sync, unloading this record is treated as a client-side
3101
+ // delete, so we remove the inverse records from this relationship to
3102
+ // disconnect the graph. Because it's not async, we don't need to keep around
3103
+ // the identifier as an id-wrapper for references
3104
+ function destroyRelationship(graph, rel, silenceNotifications) {
3105
+ if (isImplicit(rel)) {
3106
+ if (graph.isReleasable(rel.identifier)) {
3107
+ /*#__NOINLINE__*/removeCompletelyFromInverse(graph, rel);
3108
+ }
3109
+ return;
3110
+ }
3111
+ const {
3112
+ identifier
3113
+ } = rel;
3114
+ const {
3115
+ inverseKey
3116
+ } = rel.definition;
3117
+ if (!rel.definition.inverseIsImplicit) {
3118
+ /*#__NOINLINE__*/forAllRelatedIdentifiers(rel, inverseIdentifer => /*#__NOINLINE__*/notifyInverseOfDematerialization(graph, inverseIdentifer, inverseKey, identifier, silenceNotifications));
3119
+ }
3120
+ if (!rel.definition.inverseIsImplicit && !rel.definition.inverseIsAsync) {
3121
+ rel.state.isStale = true;
3122
+ /*#__NOINLINE__*/
3123
+ clearRelationship(rel);
3124
+
3125
+ // necessary to clear relationships in the ui from dematerialized records
3126
+ // hasMany is managed by Model which calls `retreiveLatest` after
3127
+ // dematerializing the resource-cache instance.
3128
+ // but sync belongsTo requires this since they don't have a proxy to update.
3129
+ // so we have to notify so it will "update" to null.
3130
+ // we should discuss whether we still care about this, probably fine to just
3131
+ // leave the ui relationship populated since the record is destroyed and
3132
+ // internally we've fully cleaned up.
3133
+ if (!rel.definition.isAsync && !silenceNotifications) {
3134
+ /*#__NOINLINE__*/notifyChange(graph, rel);
3135
+ }
3136
+ }
3137
+ }
3138
+ function notifyInverseOfDematerialization(graph, inverseIdentifier, inverseKey, resourceKey, silenceNotifications) {
3139
+ if (!graph.has(inverseIdentifier, inverseKey)) {
3140
+ return;
3141
+ }
3142
+ const relationship = graph.get(inverseIdentifier, inverseKey);
3143
+ (test => {
3144
+ if (!test) {
3145
+ throw new Error(`expected no implicit`);
3146
+ }
3147
+ })(!isImplicit(relationship));
3148
+
3149
+ // For remote members, it is possible that inverseRecordData has already been associated to
3150
+ // to another record. For such cases, do not dematerialize the inverseRecordData
3151
+ if (!isBelongsTo(relationship) || !relationship.localState || resourceKey === relationship.localState) {
3152
+ /*#__NOINLINE__*/removeDematerializedInverse(graph, relationship, resourceKey, silenceNotifications);
3153
+ }
3154
+ }
3155
+ function clearRelationship(relationship) {
3156
+ if (isBelongsTo(relationship)) {
3157
+ relationship.localState = null;
3158
+ relationship.remoteState = null;
3159
+ relationship.state.hasReceivedData = false;
3160
+ relationship.state.isEmpty = true;
3161
+ } else {
3162
+ relationship.remoteMembers.clear();
3163
+ relationship.remoteState = [];
3164
+ relationship.additions = null;
3165
+ relationship.removals = null;
3166
+ relationship.localState = null;
3167
+ }
3168
+ }
3169
+ function removeDematerializedInverse(graph, relationship, inverseIdentifier, silenceNotifications) {
3170
+ if (isBelongsTo(relationship)) {
3171
+ const localInverse = relationship.localState;
3172
+ if (!relationship.definition.isAsync || localInverse && checkIfNew(graph._realStore, localInverse)) {
3173
+ // unloading inverse of a sync relationship is treated as a client-side
3174
+ // delete, so actually remove the models don't merely invalidate the cp
3175
+ // cache.
3176
+ // if the record being unloaded only exists on the client, we similarly
3177
+ // treat it as a client side delete
3178
+ if (relationship.localState === localInverse && localInverse !== null) {
3179
+ relationship.localState = null;
3180
+ }
3181
+ if (relationship.remoteState === localInverse && localInverse !== null) {
3182
+ relationship.remoteState = null;
3183
+ relationship.state.hasReceivedData = true;
3184
+ relationship.state.isEmpty = true;
3185
+ if (relationship.localState && !checkIfNew(graph._realStore, relationship.localState)) {
3186
+ relationship.localState = null;
3187
+ }
3188
+ }
3189
+ } else {
3190
+ relationship.state.hasDematerializedInverse = true;
3191
+ }
3192
+ if (!silenceNotifications) {
3193
+ notifyChange(graph, relationship);
3194
+ }
3195
+ } else {
3196
+ if (!relationship.definition.isAsync || inverseIdentifier && checkIfNew(graph._realStore, inverseIdentifier)) {
3197
+ // unloading inverse of a sync relationship is treated as a client-side
3198
+ // delete, so actually remove the models don't merely invalidate the cp
3199
+ // cache.
3200
+ // if the record being unloaded only exists on the client, we similarly
3201
+ // treat it as a client side delete
3202
+ /*#__NOINLINE__*/
3203
+ removeIdentifierCompletelyFromRelationship(graph, relationship, inverseIdentifier);
3204
+ } else {
3205
+ relationship.state.hasDematerializedInverse = true;
3206
+ }
3207
+ if (!silenceNotifications) {
3208
+ notifyChange(graph, relationship);
3209
+ }
3210
+ }
3211
+ }
3212
+ function removeCompletelyFromInverse(graph, relationship) {
3213
+ const {
3214
+ identifier
3215
+ } = relationship;
3216
+ const {
3217
+ inverseKey
3218
+ } = relationship.definition;
3219
+ forAllRelatedIdentifiers(relationship, inverseIdentifier => {
3220
+ if (graph.has(inverseIdentifier, inverseKey)) {
3221
+ removeIdentifierCompletelyFromRelationship(graph, graph.get(inverseIdentifier, inverseKey), identifier);
3222
+ }
3223
+ });
3224
+ if (isBelongsTo(relationship)) {
3225
+ if (!relationship.definition.isAsync) {
3226
+ clearRelationship(relationship);
3227
+ }
3228
+ relationship.localState = null;
3229
+ } else if (isHasMany(relationship)) {
3230
+ if (!relationship.definition.isAsync) {
3231
+ clearRelationship(relationship);
3232
+ notifyChange(graph, relationship);
3233
+ }
3234
+ } else {
3235
+ relationship.remoteMembers.clear();
3236
+ relationship.localMembers.clear();
3237
+ }
3238
+ }
3239
+ function addPending(cache, definition, op) {
3240
+ const cacheForKind = cache[definition.kind] = cache[definition.kind] || new Map();
3241
+ let cacheForType = cacheForKind.get(definition.inverseType);
3242
+ if (!cacheForType) {
3243
+ cacheForType = new Map();
3244
+ cacheForKind.set(definition.inverseType, cacheForType);
3245
+ }
3246
+ let cacheForField = cacheForType.get(op.field);
3247
+ if (!cacheForField) {
3248
+ cacheForField = [];
3249
+ cacheForType.set(op.field, cacheForField);
3250
+ }
3251
+ cacheForField.push(op);
3252
+ }
3253
+ function isReordered(relationship) {
3254
+ // if we are dirty we are never re-ordered because accessing
3255
+ // the state would flush away any reordering.
3256
+ if (relationship.isDirty) {
3257
+ return false;
3258
+ }
3259
+ const {
3260
+ remoteState,
3261
+ localState,
3262
+ additions,
3263
+ removals
3264
+ } = relationship;
3265
+ if (localState === null) {
3266
+ // the relationship has never been accessed, so it hasn't been reordered either
3267
+ return false;
3268
+ }
3269
+ for (let i = 0, j = 0; i < remoteState.length; i++) {
3270
+ const member = remoteState[i];
3271
+ const localMember = localState[j];
3272
+ if (member !== localMember) {
3273
+ if (removals && removals.has(member)) {
3274
+ // dont increment j because we want to skip this
3275
+ continue;
3276
+ }
3277
+ if (additions && additions.has(localMember)) {
3278
+ // increment j to skip this localMember
3279
+ // decrement i to repeat this remoteMember
3280
+ j++;
3281
+ i--;
3282
+ continue;
3283
+ }
3284
+ return true;
3285
+ }
3286
+
3287
+ // if we made it here, increment j
3288
+ j++;
3289
+ }
3290
+ return false;
3291
+ }
3292
+
3293
+ /**
3294
+ Provides a performance tuned normalized graph for intelligently managing relationships between resources based on identity
3295
+
3296
+ While this Graph is abstract, it currently is a private implementation required as a peer-dependency by the {json:api} Cache Implementation.
3297
+
3298
+ We intend to make this Graph public API after some additional iteration during the 5.x timeframe, until then all APIs should be considered experimental and unstable, not fit for direct application or 3rd party library usage.
3299
+
3300
+ @module
3301
+ */
3302
+
3303
+ function isStore(maybeStore) {
3304
+ return maybeStore._instanceCache !== undefined;
3305
+ }
3306
+ function getWrapper(store) {
3307
+ return isStore(store) ? store._instanceCache._storeWrapper : store;
3308
+ }
3309
+ function peekGraph(store) {
3310
+ return Graphs.get(getWrapper(store));
3311
+ }
3312
+ function graphFor(store) {
3313
+ const wrapper = getWrapper(store);
3314
+ let graph = Graphs.get(wrapper);
3315
+ if (!graph) {
3316
+ graph = new Graph(wrapper);
3317
+ Graphs.set(wrapper, graph);
3318
+ getStore(wrapper)._graph = graph;
3319
+ {
3320
+ if (getStore(wrapper).isDestroying) {
3321
+ throw new Error(`Memory Leak Detected During Teardown`);
3322
+ }
3323
+ }
3324
+ }
3325
+ return graph;
3326
+ }
3327
+ export { graphFor, isBelongsTo, peekGraph };