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

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