@warp-drive/core 5.6.0-alpha.11

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