@warp-drive/core 5.8.0-beta.0 → 5.8.0-beta.2

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 (275) hide show
  1. package/README.md +23 -36
  2. package/declarations/build-config.d.ts +18 -1
  3. package/declarations/configure.d.ts +1 -1
  4. package/declarations/graph/-private/-edge-definition.d.ts +12 -2
  5. package/declarations/index.d.ts +90 -8
  6. package/declarations/reactive/-private/default-mode.d.ts +1 -1
  7. package/declarations/reactive/-private/document.d.ts +58 -46
  8. package/declarations/reactive/-private/fields/extension.d.ts +1 -1
  9. package/declarations/reactive/-private/fields/managed-array.d.ts +2 -2
  10. package/declarations/reactive/-private/fields/managed-object.d.ts +1 -1
  11. package/declarations/reactive/-private/record.d.ts +10 -1
  12. package/declarations/reactive/-private/schema.d.ts +77 -4
  13. package/declarations/reactive/-private.d.ts +1 -0
  14. package/declarations/reactive.d.ts +13 -8
  15. package/declarations/request/-private/types.d.ts +1 -1
  16. package/declarations/request.d.ts +47 -0
  17. package/declarations/signals/-leaked.d.ts +2 -0
  18. package/declarations/signals/-private.d.ts +6 -0
  19. package/declarations/{store/-private/new-core-tmp → signals}/promise-state.d.ts +2 -1
  20. package/declarations/{store/-private/new-core-tmp → signals}/request-state.d.ts +6 -6
  21. package/declarations/{store/-private/new-core-tmp → signals}/request-subscription.d.ts +4 -4
  22. package/declarations/store/-private/cache-handler/types.d.ts +2 -16
  23. package/declarations/store/-private/caches/instance-cache.d.ts +5 -6
  24. package/declarations/store/-private/default-cache-policy.d.ts +147 -129
  25. package/declarations/store/-private/managers/cache-capabilities-manager.d.ts +1 -1
  26. package/declarations/store/-private/managers/cache-key-manager.d.ts +26 -8
  27. package/declarations/store/-private/managers/cache-manager.d.ts +7 -18
  28. package/declarations/store/-private/managers/notification-manager.d.ts +1 -1
  29. package/declarations/store/-private/record-arrays/legacy-many-array.d.ts +1 -1
  30. package/declarations/store/-private/record-arrays/resource-array.d.ts +1 -1
  31. package/declarations/store/-private/store-service.d.ts +43 -64
  32. package/declarations/store/-private.d.ts +0 -6
  33. package/declarations/store/-types/q/cache-capabilities-manager.d.ts +1 -1
  34. package/declarations/store/deprecated/-private.d.ts +2 -2
  35. package/declarations/store/deprecated/store.d.ts +33 -32
  36. package/declarations/store.d.ts +1 -0
  37. package/declarations/types/cache.d.ts +8 -6
  38. package/declarations/types/record.d.ts +132 -0
  39. package/declarations/types/request.d.ts +26 -14
  40. package/declarations/types/schema/fields.d.ts +37 -13
  41. package/declarations/{store/-types/q → types/schema}/schema-service.d.ts +15 -13
  42. package/declarations/types/spec/document.d.ts +34 -0
  43. package/declarations/types/symbols.d.ts +2 -2
  44. package/declarations/types.d.ts +1 -1
  45. package/dist/build-config.js +1 -1
  46. package/dist/configure-DPUFCemT.js +1940 -0
  47. package/dist/configure.js +2 -1
  48. package/dist/default-cache-policy-D7_u4YRH.js +572 -0
  49. package/dist/{context-C_7OLieY.js → future-BKkJJkj7.js} +174 -174
  50. package/dist/graph/-private.js +16 -6
  51. package/dist/{request-state-C955e0AL.js → index-CQP2NSqg.js} +8830 -9427
  52. package/dist/index.js +6 -382
  53. package/dist/reactive/-private.js +1 -1
  54. package/dist/reactive.js +4 -903
  55. package/dist/request.js +49 -1
  56. package/dist/signals/-leaked.js +1 -0
  57. package/dist/store/-private.js +1 -2
  58. package/dist/store.js +1 -533
  59. package/dist/symbols-3C1OkYtZ.js +39 -0
  60. package/dist/types/-private.js +1 -1
  61. package/dist/types/record.js +127 -0
  62. package/dist/types/request.js +14 -12
  63. package/dist/types/runtime.js +1 -1
  64. package/dist/types/schema/fields.js +14 -0
  65. package/dist/types/schema/schema-service.js +0 -0
  66. package/dist/types/symbols.js +2 -2
  67. package/dist/unpkg/dev/-leaked-Co0EI6Go.js +1939 -0
  68. package/dist/unpkg/dev/build-config/babel-macros.js +1 -0
  69. package/dist/unpkg/dev/build-config/canary-features.js +1 -0
  70. package/dist/unpkg/dev/build-config/debugging.js +1 -0
  71. package/dist/unpkg/dev/build-config/deprecations.js +1 -0
  72. package/dist/unpkg/dev/build-config/env.js +1 -0
  73. package/dist/unpkg/dev/build-config/macros.js +1 -0
  74. package/dist/unpkg/dev/build-config.js +1 -0
  75. package/dist/unpkg/dev/configure.js +1 -0
  76. package/dist/unpkg/dev/future-DFfOzSoe.js +672 -0
  77. package/dist/unpkg/dev/graph/-private.js +3132 -0
  78. package/dist/unpkg/dev/index-BzcBOnw9.js +9392 -0
  79. package/dist/unpkg/dev/index.js +6 -0
  80. package/dist/unpkg/dev/reactive/-private.js +1 -0
  81. package/dist/unpkg/dev/reactive.js +3 -0
  82. package/dist/unpkg/dev/request.js +49 -0
  83. package/dist/unpkg/dev/runtime-E1M51_-O.js +135 -0
  84. package/dist/unpkg/dev/signals/-leaked.js +1 -0
  85. package/dist/unpkg/dev/store/-private.js +55 -0
  86. package/dist/unpkg/dev/store.js +558 -0
  87. package/dist/unpkg/dev/types/-private.js +69 -0
  88. package/dist/unpkg/dev/types/cache/aliases.js +0 -0
  89. package/dist/unpkg/dev/types/cache/change.js +0 -0
  90. package/dist/unpkg/dev/types/cache/mutations.js +0 -0
  91. package/dist/unpkg/dev/types/cache/operations.js +0 -0
  92. package/dist/unpkg/dev/types/cache/relationship.js +0 -0
  93. package/dist/unpkg/dev/types/cache.js +0 -0
  94. package/dist/unpkg/dev/types/graph.js +0 -0
  95. package/dist/unpkg/dev/types/identifier.js +61 -0
  96. package/dist/unpkg/dev/types/json/raw.js +0 -0
  97. package/dist/unpkg/dev/types/params.js +0 -0
  98. package/dist/unpkg/dev/types/record.js +191 -0
  99. package/dist/unpkg/dev/types/request.js +77 -0
  100. package/dist/unpkg/dev/types/runtime.js +34 -0
  101. package/dist/unpkg/dev/types/schema/concepts.js +0 -0
  102. package/dist/unpkg/dev/types/schema/fields.js +505 -0
  103. package/dist/unpkg/dev/types/schema/fields.type-test.js +0 -0
  104. package/dist/unpkg/dev/types/schema/schema-service.js +0 -0
  105. package/dist/unpkg/dev/types/spec/document.js +0 -0
  106. package/dist/unpkg/dev/types/spec/error.js +0 -0
  107. package/dist/unpkg/dev/types/spec/json-api-raw.js +0 -0
  108. package/dist/unpkg/dev/types/symbols.js +84 -0
  109. package/dist/unpkg/dev/types/utils.js +0 -0
  110. package/dist/unpkg/dev/types.js +0 -0
  111. package/dist/unpkg/dev/utils/string.js +91 -0
  112. package/dist/unpkg/dev-deprecated/-leaked-DjMeRqdU.js +1939 -0
  113. package/dist/unpkg/dev-deprecated/-private-3C1OkYtZ.js +39 -0
  114. package/dist/unpkg/dev-deprecated/build-config/babel-macros.js +1 -0
  115. package/dist/unpkg/dev-deprecated/build-config/canary-features.js +1 -0
  116. package/dist/unpkg/dev-deprecated/build-config/debugging.js +1 -0
  117. package/dist/unpkg/dev-deprecated/build-config/deprecations.js +1 -0
  118. package/dist/unpkg/dev-deprecated/build-config/env.js +1 -0
  119. package/dist/unpkg/dev-deprecated/build-config/macros.js +1 -0
  120. package/dist/unpkg/dev-deprecated/build-config.js +1 -0
  121. package/dist/unpkg/dev-deprecated/configure.js +1 -0
  122. package/dist/unpkg/dev-deprecated/future-DFfOzSoe.js +672 -0
  123. package/dist/unpkg/dev-deprecated/graph/-private.js +3327 -0
  124. package/dist/unpkg/dev-deprecated/index-6TnTv-WG.js +10007 -0
  125. package/dist/unpkg/dev-deprecated/index.js +5 -0
  126. package/dist/unpkg/dev-deprecated/reactive/-private.js +1 -0
  127. package/dist/unpkg/dev-deprecated/reactive.js +3 -0
  128. package/dist/unpkg/dev-deprecated/request.js +49 -0
  129. package/dist/unpkg/dev-deprecated/runtime-DAu5b0IR.js +135 -0
  130. package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -0
  131. package/dist/unpkg/dev-deprecated/store/-private.js +1 -0
  132. package/dist/unpkg/dev-deprecated/store.js +558 -0
  133. package/dist/unpkg/dev-deprecated/types/-private.js +69 -0
  134. package/dist/unpkg/dev-deprecated/types/cache/aliases.js +0 -0
  135. package/dist/unpkg/dev-deprecated/types/cache/change.js +0 -0
  136. package/dist/unpkg/dev-deprecated/types/cache/mutations.js +0 -0
  137. package/dist/unpkg/dev-deprecated/types/cache/operations.js +0 -0
  138. package/dist/unpkg/dev-deprecated/types/cache/relationship.js +0 -0
  139. package/dist/unpkg/dev-deprecated/types/cache.js +0 -0
  140. package/dist/unpkg/dev-deprecated/types/graph.js +0 -0
  141. package/dist/unpkg/dev-deprecated/types/identifier.js +61 -0
  142. package/dist/unpkg/dev-deprecated/types/json/raw.js +0 -0
  143. package/dist/unpkg/dev-deprecated/types/params.js +0 -0
  144. package/dist/unpkg/dev-deprecated/types/record.js +191 -0
  145. package/dist/unpkg/dev-deprecated/types/request.js +77 -0
  146. package/dist/unpkg/dev-deprecated/types/runtime.js +34 -0
  147. package/dist/unpkg/dev-deprecated/types/schema/concepts.js +0 -0
  148. package/dist/unpkg/dev-deprecated/types/schema/fields.js +505 -0
  149. package/dist/unpkg/dev-deprecated/types/schema/fields.type-test.js +0 -0
  150. package/dist/unpkg/dev-deprecated/types/schema/schema-service.js +0 -0
  151. package/dist/unpkg/dev-deprecated/types/spec/document.js +0 -0
  152. package/dist/unpkg/dev-deprecated/types/spec/error.js +0 -0
  153. package/dist/unpkg/dev-deprecated/types/spec/json-api-raw.js +0 -0
  154. package/dist/unpkg/dev-deprecated/types/symbols.js +84 -0
  155. package/dist/unpkg/dev-deprecated/types/utils.js +0 -0
  156. package/dist/unpkg/dev-deprecated/types.js +0 -0
  157. package/dist/unpkg/dev-deprecated/utils/string.js +91 -0
  158. package/dist/unpkg/prod/-leaked-DUONXQDB.js +1676 -0
  159. package/dist/unpkg/prod/-private-sql1_mdx.js +39 -0
  160. package/dist/unpkg/prod/build-config/babel-macros.js +1 -0
  161. package/dist/unpkg/prod/build-config/canary-features.js +1 -0
  162. package/dist/unpkg/prod/build-config/debugging.js +1 -0
  163. package/dist/unpkg/prod/build-config/deprecations.js +1 -0
  164. package/dist/unpkg/prod/build-config/env.js +1 -0
  165. package/dist/unpkg/prod/build-config/macros.js +1 -0
  166. package/dist/unpkg/prod/build-config.js +1 -0
  167. package/dist/unpkg/prod/configure.js +2 -0
  168. package/dist/unpkg/prod/graph/-private.js +2235 -0
  169. package/dist/unpkg/prod/handler-EU_8ncB2.js +1619 -0
  170. package/dist/unpkg/prod/index.js +483 -0
  171. package/dist/unpkg/prod/promise-cache-DIT8Ypjq.js +19 -0
  172. package/dist/unpkg/prod/reactive/-private.js +1 -0
  173. package/dist/unpkg/prod/reactive.js +30 -0
  174. package/dist/unpkg/prod/request-BrJSCG6r.js +421 -0
  175. package/dist/unpkg/prod/request.js +2 -0
  176. package/dist/unpkg/prod/schema-BSkHyoWz.js +5219 -0
  177. package/dist/unpkg/prod/signals/-leaked.js +1 -0
  178. package/dist/unpkg/prod/store/-private.js +126 -0
  179. package/dist/unpkg/prod/store.js +437 -0
  180. package/dist/unpkg/prod/types/-private.js +49 -0
  181. package/dist/unpkg/prod/types/cache/aliases.js +0 -0
  182. package/dist/unpkg/prod/types/cache/change.js +0 -0
  183. package/dist/unpkg/prod/types/cache/mutations.js +0 -0
  184. package/dist/unpkg/prod/types/cache/operations.js +0 -0
  185. package/dist/unpkg/prod/types/cache/relationship.js +0 -0
  186. package/dist/unpkg/prod/types/cache.js +0 -0
  187. package/dist/unpkg/prod/types/graph.js +0 -0
  188. package/dist/unpkg/prod/types/identifier.js +61 -0
  189. package/dist/unpkg/prod/types/json/raw.js +0 -0
  190. package/dist/unpkg/prod/types/params.js +0 -0
  191. package/dist/unpkg/prod/types/record.js +191 -0
  192. package/dist/unpkg/prod/types/request.js +77 -0
  193. package/dist/unpkg/prod/types/runtime.js +34 -0
  194. package/dist/unpkg/prod/types/schema/concepts.js +0 -0
  195. package/dist/unpkg/prod/types/schema/fields.js +505 -0
  196. package/dist/unpkg/prod/types/schema/fields.type-test.js +0 -0
  197. package/dist/unpkg/prod/types/schema/schema-service.js +0 -0
  198. package/dist/unpkg/prod/types/spec/document.js +0 -0
  199. package/dist/unpkg/prod/types/spec/error.js +0 -0
  200. package/dist/unpkg/prod/types/spec/json-api-raw.js +0 -0
  201. package/dist/unpkg/prod/types/symbols.js +84 -0
  202. package/dist/unpkg/prod/types/utils.js +0 -0
  203. package/dist/unpkg/prod/types.js +0 -0
  204. package/dist/unpkg/prod/utils/string.js +72 -0
  205. package/dist/unpkg/prod-deprecated/-leaked-DRNv9VIX.js +1676 -0
  206. package/dist/unpkg/prod-deprecated/-private-3C1OkYtZ.js +39 -0
  207. package/dist/unpkg/prod-deprecated/build-config/babel-macros.js +1 -0
  208. package/dist/unpkg/prod-deprecated/build-config/canary-features.js +1 -0
  209. package/dist/unpkg/prod-deprecated/build-config/debugging.js +1 -0
  210. package/dist/unpkg/prod-deprecated/build-config/deprecations.js +1 -0
  211. package/dist/unpkg/prod-deprecated/build-config/env.js +1 -0
  212. package/dist/unpkg/prod-deprecated/build-config/macros.js +1 -0
  213. package/dist/unpkg/prod-deprecated/build-config.js +1 -0
  214. package/dist/unpkg/prod-deprecated/configure.js +2 -0
  215. package/dist/unpkg/prod-deprecated/graph/-private.js +2408 -0
  216. package/dist/unpkg/prod-deprecated/handler-CCIu4sQ3.js +334 -0
  217. package/dist/unpkg/prod-deprecated/hooks-Dv4Np0MY.js +26 -0
  218. package/dist/unpkg/prod-deprecated/index.js +483 -0
  219. package/dist/unpkg/prod-deprecated/promise-cache-DIT8Ypjq.js +19 -0
  220. package/dist/unpkg/prod-deprecated/reactive/-private.js +1 -0
  221. package/dist/unpkg/prod-deprecated/reactive.js +5 -0
  222. package/dist/unpkg/prod-deprecated/request-BrJSCG6r.js +421 -0
  223. package/dist/unpkg/prod-deprecated/request.js +2 -0
  224. package/dist/unpkg/prod-deprecated/schema-CJcjHv0E.js +6939 -0
  225. package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -0
  226. package/dist/unpkg/prod-deprecated/store/-private.js +88 -0
  227. package/dist/unpkg/prod-deprecated/store.js +437 -0
  228. package/dist/unpkg/prod-deprecated/types/-private.js +49 -0
  229. package/dist/unpkg/prod-deprecated/types/cache/aliases.js +0 -0
  230. package/dist/unpkg/prod-deprecated/types/cache/change.js +0 -0
  231. package/dist/unpkg/prod-deprecated/types/cache/mutations.js +0 -0
  232. package/dist/unpkg/prod-deprecated/types/cache/operations.js +0 -0
  233. package/dist/unpkg/prod-deprecated/types/cache/relationship.js +0 -0
  234. package/dist/unpkg/prod-deprecated/types/cache.js +0 -0
  235. package/dist/unpkg/prod-deprecated/types/graph.js +0 -0
  236. package/dist/unpkg/prod-deprecated/types/identifier.js +61 -0
  237. package/dist/unpkg/prod-deprecated/types/json/raw.js +0 -0
  238. package/dist/unpkg/prod-deprecated/types/params.js +0 -0
  239. package/dist/unpkg/prod-deprecated/types/record.js +191 -0
  240. package/dist/unpkg/prod-deprecated/types/request.js +77 -0
  241. package/dist/unpkg/prod-deprecated/types/runtime.js +34 -0
  242. package/dist/unpkg/prod-deprecated/types/schema/concepts.js +0 -0
  243. package/dist/unpkg/prod-deprecated/types/schema/fields.js +505 -0
  244. package/dist/unpkg/prod-deprecated/types/schema/fields.type-test.js +0 -0
  245. package/dist/unpkg/prod-deprecated/types/schema/schema-service.js +0 -0
  246. package/dist/unpkg/prod-deprecated/types/spec/document.js +0 -0
  247. package/dist/unpkg/prod-deprecated/types/spec/error.js +0 -0
  248. package/dist/unpkg/prod-deprecated/types/spec/json-api-raw.js +0 -0
  249. package/dist/unpkg/prod-deprecated/types/symbols.js +84 -0
  250. package/dist/unpkg/prod-deprecated/types/utils.js +0 -0
  251. package/dist/unpkg/prod-deprecated/types.js +0 -0
  252. package/dist/unpkg/prod-deprecated/utils/string.js +72 -0
  253. package/logos/README.md +2 -2
  254. package/logos/logo-yellow-slab.svg +1 -0
  255. package/logos/word-mark-black.svg +1 -0
  256. package/logos/word-mark-white.svg +1 -0
  257. package/package.json +12 -4
  258. package/declarations/store/-private/new-core-tmp/expensive-subscription.d.ts +0 -24
  259. package/dist/configure-C3x8YXzL.js +0 -181
  260. package/logos/NCC-1701-a-blue.svg +0 -4
  261. package/logos/NCC-1701-a-gold.svg +0 -4
  262. package/logos/NCC-1701-a-gold_100.svg +0 -1
  263. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  264. package/logos/NCC-1701-a.svg +0 -4
  265. package/logos/docs-badge.svg +0 -2
  266. package/logos/ember-data-logo-dark.svg +0 -12
  267. package/logos/ember-data-logo-light.svg +0 -12
  268. package/logos/social1.png +0 -0
  269. package/logos/social2.png +0 -0
  270. package/logos/warp-drive-logo-dark.svg +0 -4
  271. package/logos/warp-drive-logo-gold.svg +0 -4
  272. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/configure.d.ts +0 -0
  273. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/internal.d.ts +0 -0
  274. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/signal.d.ts +0 -0
  275. /package/dist/{symbols-sql1_mdx.js → unpkg/dev/-private-sql1_mdx.js} +0 -0
@@ -0,0 +1,1676 @@
1
+ import { peekTransient, getOrSetGlobal, setTransient } from './types/-private.js';
2
+ import { b as getPromiseResult, s as setPromiseResult } from "./promise-cache-DIT8Ypjq.js";
3
+
4
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5
+
6
+ const ARRAY_SIGNAL = getOrSetGlobal('#[]', Symbol('#[]'));
7
+ const OBJECT_SIGNAL = getOrSetGlobal('#{}', Symbol('#{}'));
8
+
9
+ /**
10
+ * Requirements:
11
+ *
12
+ * Signal:
13
+ *
14
+ * - signal: a way of creating a reference that we can dirty when we desire to notify
15
+ * - @signal: a way of creating an accessor on an object that subscribes to a signal on access
16
+ * and notifies the signal on set, or of upgrading a descriptor to be such an accessor
17
+ * - defineSignal: a way of creating a signal on an object
18
+ * - notifySignal: a way of notifying the underlying signal that it has been dirtied
19
+ * - peekSignal: a way of inspecting the signal without notifying it
20
+ *
21
+ * - gate: a memoized getter function that re-runs when on access if its signal is dirty
22
+ * conceptually, a gate is a tightly coupled signal and memo
23
+ * - @gate: a way of creating a gate on an object or upgrading a descriptor with a getter
24
+ * to be a gate
25
+ * - defineGate: a way of creating a gate on an object
26
+ * - notifySignal: a way of notifying the signal for a gate that it has been dirtied
27
+ *
28
+ * - memo:
29
+ * - @memo: a way of creating a memoized getter on an object or upgrading a descriptor with a getter
30
+ * to be a memo
31
+ * - defineMemo: a way of creating a memo on an object
32
+ *
33
+ * - signalStore: storage bucket for signals associated to an object
34
+ * - withSignalStore: a way of pre-creating a signal store on an object
35
+ *
36
+ *
37
+ * @internal
38
+ */
39
+
40
+ /**
41
+ * An Opaque type that represents a framework specific or TC39 signal.
42
+ *
43
+ * It may be an array of signals or a single signal.
44
+ *
45
+ * @private
46
+ */
47
+
48
+ /**
49
+ * The hooks which MUST be configured in order to use reactive arrays,
50
+ * resources and documents with framework specfic signals or TC39 signals.
51
+ *
52
+ * Support for multiple frameworks simultaneously can be done via
53
+ * this abstraction by returning multiple signals from the `createSignal`
54
+ * method, and consuming the correct one via the correct framework via
55
+ * the `consumeSignal` and `notifySignal` methods.
56
+ *
57
+ * Unlike many signals implementations, WarpDrive does not wrap values as
58
+ * signals directly, but instead uses signals to alert the reactive layer
59
+ * to changes in the underlying cache. E.g. a signal is associated to a value,
60
+ * but does not serve as the cache for that value directly. We refer to this as
61
+ * a "gate", the pattern has also been called "side-signals".
62
+ *
63
+ * A no-op implementation is allowed, though it may lead to performance issues
64
+ * in locations that use createMemo as no memoization would be done. This is
65
+ * typically desirable only when integrating with a framework that does its own
66
+ * memoization and does not integrate with any signals-like primitive. For these
67
+ * scenarios you may also be interested in integrating with the {@link NotificationManager}
68
+ * more directly.
69
+ *
70
+ * @public
71
+ */
72
+
73
+ /**
74
+ * Contains information a {@link SignalHooks} implementation may want
75
+ * to use, such as the specialized key used for the signal
76
+ * representing an array's contents / length.
77
+ *
78
+ * ```ts
79
+ * interface HooksOptions {
80
+ * wellknown: {
81
+ * Array: symbol | string;
82
+ * }
83
+ * }
84
+ * ```
85
+ *
86
+ * @public
87
+ */
88
+
89
+ /**
90
+ * Configures the signals implementation to use. Supports multiple
91
+ * implementations simultaneously.
92
+ *
93
+ * See {@link HooksOptions} for the options passed to the provided function
94
+ * when called.
95
+ *
96
+ * See {@link SignalHooks} for the implementation the callback function should
97
+ * return.
98
+ *
99
+ * @public
100
+ * @param buildConfig - a function that takes options and returns a configuration object
101
+ */
102
+ function setupSignals(buildConfig) {
103
+ // We want to assert this but can't because too many package manager
104
+ // and bundler bugs exist that cause this to be called multiple times
105
+ // for what should be a single call.
106
+ // assert(`Cannot override configured signal hooks`, peekTransient('signalHooks') === null);
107
+ const hooks = buildConfig({
108
+ wellknown: {
109
+ Array: ARRAY_SIGNAL
110
+ }
111
+ });
112
+ setTransient('signalHooks', hooks);
113
+ }
114
+
115
+ /**
116
+ * Internal method for consuming the configured `createSignal` hook
117
+ *
118
+ * @private
119
+ */
120
+ function createSignal(obj, key) {
121
+ const signalHooks = peekTransient('signalHooks');
122
+ return signalHooks.createSignal(obj, key);
123
+ }
124
+
125
+ /**
126
+ * Internal method for consuming the configured `consumeSignal` hook
127
+ *
128
+ * @private
129
+ */
130
+ function consumeSignal(signal) {
131
+ const signalHooks = peekTransient('signalHooks');
132
+ return signalHooks.consumeSignal(signal);
133
+ }
134
+
135
+ /**
136
+ * Internal method for consuming the configured `notifySignal` hook
137
+ *
138
+ * @private
139
+ */
140
+ function notifySignal(signal) {
141
+ const signalHooks = peekTransient('signalHooks');
142
+ return signalHooks.notifySignal(signal);
143
+ }
144
+ function createMemo(object, key, fn) {
145
+ const signalHooks = peekTransient('signalHooks');
146
+ return signalHooks.createMemo(object, key, fn);
147
+ }
148
+ function willSyncFlushWatchers() {
149
+ const signalHooks = peekTransient('signalHooks');
150
+ return signalHooks.willSyncFlushWatchers();
151
+ }
152
+ function waitFor(promise) {
153
+ const signalHooks = peekTransient('signalHooks');
154
+ if (signalHooks?.waitFor) {
155
+ return signalHooks.waitFor(promise);
156
+ }
157
+ return promise;
158
+ }
159
+ const INITIALIZER_PROTO = {
160
+ isInitializer: true
161
+ };
162
+ function makeInitializer(fn) {
163
+ // we use a prototype to ensure that the initializer is not enumerable
164
+ // and does not interfere with the signal's value.
165
+ return Object.assign(Object.create(INITIALIZER_PROTO), {
166
+ value: fn
167
+ });
168
+ }
169
+ function isInitializer(obj) {
170
+ return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === INITIALIZER_PROTO;
171
+ }
172
+
173
+ /**
174
+ * A WarpDriveSignal is a wrapper around a framework specific or TC39 signal
175
+ * that enables us to store and manage the signal in a universal way.
176
+ *
177
+ * WarpDrive uses signals to manage three separate concepts:
178
+ *
179
+ * - as a `storage` for a value local to the object that we want to be reactive
180
+ * (see `@local` schema field for an example)
181
+ * - as a `gate` for a memoized getter that we want to act as a reactive property
182
+ * but whose value is computed/pulled from a non-reactive source elsewhere
183
+ * and whose latest value is stored in the signal
184
+ * (see `field` schema field for an example)
185
+ * - as a `gate` with a manually managed value updated on pull when `isStale` is true
186
+ *
187
+ *
188
+ * It offers
189
+ *
190
+ * - a non-reactive way to access/update the current value
191
+ * - a non-reactive way to mark the signal as dirtied
192
+ * - a non-reactive way to store content for why the signal was dirtied
193
+ * - access to the underlying Signal(s) in-use
194
+ *
195
+ * For debugging:
196
+ * - the "key" or "name" of the signal
197
+ * - the "object identity" or "context" to which the signal is attached
198
+ *
199
+ * @private
200
+ */
201
+
202
+ /**
203
+ * We attach signals to their context object via
204
+ * a Map attached to the object via this symbol.
205
+ *
206
+ * This allows us to store multiple signals
207
+ * on the same object with smaller memory
208
+ * overhead and no WeakMap lookups.
209
+ *
210
+ * Performance sensitive objects should
211
+ * pre-warm their shape by assigning this
212
+ * during initialization.
213
+ *
214
+ * ```ts
215
+ * initializeSignalStore(obj);
216
+ * ```
217
+ *
218
+ * @private
219
+ */
220
+ const Signals = getOrSetGlobal('Signals', Symbol('Signals'));
221
+
222
+ /**
223
+ * A util that will create a signal store on the object
224
+ * if it does not already exist and returns the associated
225
+ * signal store.
226
+ *
227
+ * @private
228
+ */
229
+ function withSignalStore(obj) {
230
+ if (!obj[Signals]) {
231
+ initializeSignalStore(obj);
232
+ }
233
+ return obj[Signals];
234
+ }
235
+
236
+ /**
237
+ * A util that will create a signal store on the object
238
+ * if it does not already exist.
239
+ *
240
+ * Useful for pre-warming the shape of an object to ensure
241
+ * a key-transition to add it is not required later.
242
+ *
243
+ * @private
244
+ */
245
+ function initializeSignalStore(obj) {
246
+ obj[Signals] = new Map();
247
+ }
248
+ function createInternalSignal(signals, obj, key, initialValue) {
249
+ const warpDriveSignal = {
250
+ key,
251
+ context: obj,
252
+ signal: createSignal(obj, key),
253
+ value: isInitializer(initialValue) ? initialValue.value.call(obj) : initialValue,
254
+ isStale: false
255
+ };
256
+ signals.set(key, warpDriveSignal);
257
+ return warpDriveSignal;
258
+ }
259
+ function getOrCreateInternalSignal(signals, obj, key, initialValue) {
260
+ let signal = peekInternalSignal(signals, key);
261
+ if (!signal) {
262
+ signal = createInternalSignal(signals, obj, key, initialValue);
263
+ }
264
+ return signal;
265
+ }
266
+ function createInternalMemo(signals, object, key, fn) {
267
+ {
268
+ const memo = createMemo(object, key, fn);
269
+ signals.set(key, memo);
270
+ return memo;
271
+ }
272
+ }
273
+ function peekInternalSignal(signals, key) {
274
+ return signals?.get(key);
275
+ }
276
+ function consumeInternalSignal(signal) {
277
+ consumeSignal(signal.signal);
278
+ }
279
+ function notifyInternalSignal(signal) {
280
+ if (signal) {
281
+ signal.isStale = true;
282
+ notifySignal(signal.signal);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Creates a signal for the key/object pairing and subscribes to the signal.
288
+ *
289
+ * Use when you need to ensure a signal exists and is subscribed to.
290
+ *
291
+ * @private
292
+ */
293
+ function entangleSignal(signals, obj, key, initialValue) {
294
+ let internalSignal = peekInternalSignal(signals, key);
295
+ if (!internalSignal) {
296
+ internalSignal = createInternalSignal(signals, obj, key, initialValue);
297
+ }
298
+ consumeInternalSignal(internalSignal);
299
+ return internalSignal;
300
+ }
301
+ function entangleInitiallyStaleSignal(signals, obj, key, initialValue) {
302
+ let internalSignal = peekInternalSignal(signals, key);
303
+ if (!internalSignal) {
304
+ internalSignal = createInternalSignal(signals, obj, key, initialValue);
305
+ internalSignal.isStale = true; // mark it as stale
306
+ }
307
+ consumeInternalSignal(internalSignal);
308
+ return internalSignal;
309
+ }
310
+ function createSignalDescriptor(key, intialValue) {
311
+ return {
312
+ enumerable: true,
313
+ configurable: false,
314
+ get() {
315
+ const signals = withSignalStore(this);
316
+ const internalSignal = entangleSignal(signals, this, key, intialValue);
317
+ internalSignal.isStale = false; // reset stale state
318
+ return internalSignal.value;
319
+ },
320
+ set(value) {
321
+ const signals = withSignalStore(this);
322
+ const internalSignal = getOrCreateInternalSignal(signals, this, key, intialValue);
323
+ if (internalSignal.value !== value) {
324
+ internalSignal.value = value;
325
+ notifyInternalSignal(internalSignal);
326
+ }
327
+ }
328
+ };
329
+ }
330
+
331
+ /**
332
+ * define an enumerable signal property.
333
+ *
334
+ * Akin to Object.defineProperty.
335
+ *
336
+ * The signal will be lazily created when accessed and scoped to the
337
+ * instance of the object.
338
+ *
339
+ * @private
340
+ */
341
+ function defineSignal(obj, key, v) {
342
+ Object.defineProperty(obj, key, createSignalDescriptor(key, v));
343
+ }
344
+
345
+ /**
346
+ * Define a non-enumerable signal property.
347
+ *
348
+ * @private
349
+ */
350
+ function defineNonEnumerableSignal(obj, key, v) {
351
+ const desc = createSignalDescriptor(key, v);
352
+ desc.enumerable = false;
353
+ Object.defineProperty(obj, key, desc);
354
+ }
355
+ /**
356
+ * Decorator version of creating a signal.
357
+ */
358
+ function signal(target, key, descriptor) {
359
+ return createSignalDescriptor(key, descriptor.initializer ? makeInitializer(descriptor.initializer) : null);
360
+ }
361
+
362
+ /**
363
+ * Decorator version of creating a memoized getter
364
+ */
365
+ function memoized(target, key, descriptor) {
366
+ // eslint-disable-next-line @typescript-eslint/unbound-method
367
+ const getter = descriptor.get;
368
+ descriptor.get = function () {
369
+ const signals = withSignalStore(this);
370
+ let memoSignal = signals.get(key);
371
+ if (!memoSignal) {
372
+ memoSignal = createInternalMemo(signals, this, key, getter.bind(this));
373
+ }
374
+ return memoSignal();
375
+ };
376
+ return descriptor;
377
+ }
378
+
379
+ /**
380
+ * Decorator version of creating a gate.
381
+ *
382
+ * @private
383
+ */
384
+ function gate(_target, key, desc) {
385
+ // eslint-disable-next-line @typescript-eslint/unbound-method
386
+ const getter = desc.get;
387
+ // eslint-disable-next-line @typescript-eslint/unbound-method
388
+ const setter = desc.set;
389
+ const isLocal = desc.isLocal;
390
+ desc.get = function () {
391
+ const signals = withSignalStore(this);
392
+ let internalSignal = peekInternalSignal(signals, key);
393
+ if (!internalSignal) {
394
+ internalSignal = createInternalSignal(signals, this, key, getter.call(this));
395
+ } else if (internalSignal.isStale) {
396
+ internalSignal.isStale = false;
397
+ internalSignal.value = getter.call(this);
398
+ }
399
+ consumeInternalSignal(internalSignal);
400
+ return internalSignal.value;
401
+ };
402
+ if (setter) {
403
+ desc.set = function (v) {
404
+ const signals = withSignalStore(this);
405
+ let internalSignal = peekInternalSignal(signals, key);
406
+ if (!internalSignal) {
407
+ // we can't use `v` as initialValue here because setters don't
408
+ // return the value and the final value may be different
409
+ // than what the setter was called with.
410
+ internalSignal = createInternalSignal(signals, this, key, undefined);
411
+ internalSignal.isStale = true;
412
+ }
413
+ setter.call(this, v);
414
+ // when a gate is set, we do not notify the signal
415
+ // as its update is controlled externally.
416
+ // unless it specifically sets itself to be locally managed
417
+ if (isLocal) {
418
+ internalSignal.isStale = true;
419
+ notifyInternalSignal(internalSignal);
420
+ }
421
+ };
422
+ }
423
+ return desc;
424
+ }
425
+ function defineGate(obj, key, desc) {
426
+ const options = Object.assign({
427
+ enumerable: true,
428
+ configurable: false
429
+ }, gate(obj, key, desc));
430
+ Object.defineProperty(obj, key, options);
431
+ }
432
+ const RequestCache = new WeakMap();
433
+ function isAbortError(error) {
434
+ return error instanceof DOMException && error.name === 'AbortError';
435
+ }
436
+ function upgradeLoadingState(state) {
437
+ return state;
438
+ }
439
+ async function watchStream(stream, loadingState) {
440
+ const state = upgradeLoadingState(loadingState);
441
+ const reader = stream.getReader();
442
+ let bytesLoaded = 0;
443
+ let shouldForward = state._stream !== null && state._stream.readable.locked;
444
+ let isForwarding = shouldForward;
445
+ let writer = state._stream?.writable.getWriter();
446
+ const buffer = [];
447
+ state._isPending = false;
448
+ state._isStarted = true;
449
+ state._startTime = performance.now();
450
+ while (true) {
451
+ const {
452
+ value,
453
+ done
454
+ } = await reader.read();
455
+ if (done) {
456
+ break;
457
+ }
458
+ bytesLoaded += value.byteLength;
459
+ state._bytesLoaded = bytesLoaded;
460
+ state._lastPacketTime = performance.now();
461
+ shouldForward = shouldForward || state._stream !== null && state._stream.readable.locked;
462
+ if (shouldForward) {
463
+ if (!isForwarding) {
464
+ isForwarding = true;
465
+ writer = state._stream.writable.getWriter();
466
+ for (const item of buffer) {
467
+ await writer.ready;
468
+ await writer.write(item);
469
+ }
470
+ buffer.length = 0;
471
+ }
472
+ await writer.ready;
473
+ await writer.write(value);
474
+ } else {
475
+ buffer.push(value);
476
+ }
477
+ }
478
+
479
+ // if we are still forwarding, we need to close the writer
480
+ if (isForwarding) {
481
+ await writer.ready;
482
+ await writer.close();
483
+ } else if (state._stream) {
484
+ // if we are not forwarding, we need to cancel the stream
485
+ await state._stream.readable.cancel('The Stream Has Already Ended');
486
+ state._stream = null;
487
+ }
488
+ const endTime = performance.now();
489
+ state._endTime = endTime;
490
+ state._isComplete = true;
491
+ state._isStarted = false;
492
+ }
493
+
494
+ /**
495
+ * Lazily consumes the stream of a request, providing a number of
496
+ * reactive properties that can be used to build UIs that respond
497
+ * to the progress of a request.
498
+ *
499
+ * @hideconstructor
500
+ */
501
+ class RequestLoadingState {
502
+ /** @internal */
503
+
504
+ /** @internal */
505
+
506
+ /** @internal */
507
+
508
+ /** @internal */
509
+
510
+ /** @internal */
511
+
512
+ /** @internal */
513
+
514
+ /** @internal */
515
+
516
+ /** @internal */
517
+
518
+ /** @internal */
519
+
520
+ /** @internal */
521
+
522
+ /** @internal */
523
+
524
+ /** @internal */
525
+ _stream = null;
526
+ /** @internal */
527
+ _future;
528
+ /** @internal */
529
+ _triggered = false;
530
+ /** @internal */
531
+ _trigger() {
532
+ if (this._triggered) {
533
+ return;
534
+ }
535
+ this._triggered = true;
536
+ const future = this._future;
537
+ const promise = future.getStream();
538
+ if (promise.sizeHint) {
539
+ this._sizeHint = promise.sizeHint;
540
+ }
541
+ this.promise = promise.then(stream => {
542
+ if (!stream) {
543
+ this._isPending = false;
544
+ this._isComplete = true;
545
+ return;
546
+ }
547
+ return watchStream(stream, this);
548
+ }, error => {
549
+ this._isPending = false;
550
+ this._isStarted = false;
551
+ if (isAbortError(error)) {
552
+ this._isCancelled = true;
553
+ this._isComplete = true;
554
+ }
555
+ this._isErrored = true;
556
+ this._error = error;
557
+ });
558
+ }
559
+ promise = null;
560
+ get isPending() {
561
+ this._trigger();
562
+ return this._isPending;
563
+ }
564
+ get sizeHint() {
565
+ this._trigger();
566
+ return this._sizeHint;
567
+ }
568
+ get stream() {
569
+ this._trigger();
570
+ if (!this._stream) {
571
+ if (this._isComplete || this._isCancelled || this._isErrored) {
572
+ return null;
573
+ }
574
+ this._stream = new TransformStream();
575
+ }
576
+ return this._stream.readable;
577
+ }
578
+ get isStarted() {
579
+ this._trigger();
580
+ return this._isStarted;
581
+ }
582
+ get bytesLoaded() {
583
+ this._trigger();
584
+ return this._bytesLoaded;
585
+ }
586
+ get startTime() {
587
+ this._trigger();
588
+ return this._startTime;
589
+ }
590
+ get endTime() {
591
+ this._trigger();
592
+ return this._endTime;
593
+ }
594
+ get lastPacketTime() {
595
+ this._trigger();
596
+ return this._lastPacketTime;
597
+ }
598
+ get isComplete() {
599
+ this._trigger();
600
+ return this._isComplete;
601
+ }
602
+ get isCancelled() {
603
+ this._trigger();
604
+ return this._isCancelled;
605
+ }
606
+ get isErrored() {
607
+ this._trigger();
608
+ return this._isErrored;
609
+ }
610
+ get error() {
611
+ this._trigger();
612
+ return this._error;
613
+ }
614
+ get elapsedTime() {
615
+ return (this.endTime || this.lastPacketTime) - this.startTime;
616
+ }
617
+ get completedRatio() {
618
+ return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;
619
+ }
620
+ get remainingRatio() {
621
+ return 1 - this.completedRatio;
622
+ }
623
+ get duration() {
624
+ return this.endTime - this.startTime;
625
+ }
626
+ get speed() {
627
+ // bytes per second
628
+ return this.bytesLoaded / (this.elapsedTime / 1000);
629
+ }
630
+ constructor(future) {
631
+ this._future = future;
632
+ }
633
+ abort = () => {
634
+ this._future.abort();
635
+ };
636
+ }
637
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isPending', true);
638
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isStarted', false);
639
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isComplete', false);
640
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isCancelled', false);
641
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isErrored', false);
642
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_error', null);
643
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_sizeHint', 0);
644
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_bytesLoaded', 0);
645
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_startTime', 0);
646
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_endTime', 0);
647
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_lastPacketTime', 0);
648
+
649
+ /**
650
+ * The state of a request in the "pending"
651
+ * state. This is the default initial state.
652
+ *
653
+ * Extends the {@link PendingPromise} interface.
654
+ *
655
+ */
656
+
657
+ /**
658
+ * The state of a request in the "fulfilled" state.
659
+ * This is the state of a request that has resolved
660
+ * successfully.
661
+ *
662
+ * Extends the {@link ResolvedPromise} interface.
663
+ *
664
+ */
665
+
666
+ /**
667
+ * The state of a request in the "rejected" state.
668
+ * This is the state of a request that has rejected
669
+ * with an error.
670
+ *
671
+ * Extends the {@link RejectedPromise} interface.
672
+ *
673
+ */
674
+
675
+ /**
676
+ * The state of a request in the "cancelled" state.
677
+ * This is the state of a promise that has been
678
+ * cancelled.
679
+ *
680
+ */
681
+
682
+ /**
683
+ * RequestState extends the concept of {@link PromiseState} to provide a reactive
684
+ * wrapper for a request {@link Future} which allows you write declarative code
685
+ * around a Future's control flow.
686
+ *
687
+ * It is useful in both Template and JavaScript contexts, allowing you
688
+ * to quickly derive behaviors and data from pending, error and success
689
+ * states.
690
+ *
691
+ * The key difference between a {@link Promise} and a Future is that Futures provide
692
+ * access to a {@link ReadableStream | stream} of their content, the {@link RequestKey} of the request (if any)
693
+ * as well as the ability to attempt to {@link Future.abort | abort} the request.
694
+ *
695
+ * ```ts
696
+ * interface Future<T> extends Promise<T>> {
697
+ * getStream(): Promise<ReadableStream>;
698
+ * abort(): void;
699
+ * lid: RequestKey | null;
700
+ * }
701
+ * ```
702
+ *
703
+ * These additional APIs allow us to craft even richer state experiences.
704
+ *
705
+ * To get the state of a request, use {@link getRequestState}.
706
+ *
707
+ * See also:
708
+ * - {@link PendingRequest}
709
+ * - {@link ResolvedRequest}
710
+ * - {@link RejectedRequest}
711
+ * - {@link CancelledRequest}
712
+ *
713
+ */
714
+
715
+ const RequestStateProto = {};
716
+ function performRefresh(requester, request, isReload) {
717
+ const req = Object.assign({}, request);
718
+ const cacheOptions = Object.assign({}, req.cacheOptions);
719
+ if (isReload) {
720
+ // force direct to network
721
+ cacheOptions.reload = true;
722
+ } else if (isReload === false) {
723
+ // delete reload to ensure we use backgroundReload / policy
724
+ delete cacheOptions.reload;
725
+ cacheOptions.backgroundReload = true;
726
+ } else {
727
+ // delete props to ensure we use the policy
728
+ delete cacheOptions.backgroundReload;
729
+ delete cacheOptions.reload;
730
+ }
731
+ req.cacheOptions = cacheOptions;
732
+ return requester.request(req);
733
+ }
734
+
735
+ // TODO introduce a new mechanism for defining multiple properties
736
+ // that share a common signal
737
+ defineSignal(RequestStateProto, 'reason', null);
738
+ defineSignal(RequestStateProto, 'value', null);
739
+ defineSignal(RequestStateProto, 'result', null);
740
+ defineSignal(RequestStateProto, 'error', null);
741
+ defineSignal(RequestStateProto, 'status', 'pending');
742
+ defineSignal(RequestStateProto, 'isPending', true);
743
+ defineSignal(RequestStateProto, 'isLoading', true);
744
+ defineSignal(RequestStateProto, 'isSuccess', false);
745
+ defineSignal(RequestStateProto, 'isError', false);
746
+ defineSignal(RequestStateProto, 'request', null);
747
+ defineSignal(RequestStateProto, 'response', null);
748
+ Object.defineProperty(RequestStateProto, 'isCancelled', {
749
+ get() {
750
+ return this.isError && isAbortError(this.reason);
751
+ }
752
+ });
753
+ Object.defineProperty(RequestStateProto, 'loadingState', {
754
+ get() {
755
+ if (!this._loadingState) {
756
+ this._loadingState = new RequestLoadingState(this._request);
757
+ }
758
+ return this._loadingState;
759
+ }
760
+ });
761
+ function createRequestState(future) {
762
+ const state = getPromiseResult(future);
763
+ const promiseState = Object.create(RequestStateProto);
764
+ promiseState._request = future;
765
+ // @ts-expect-error - we still attach it for PendingState
766
+ promiseState.reload = () => {
767
+ return performRefresh(future.requester, promiseState.request, true);
768
+ };
769
+
770
+ // @ts-expect-error - we still attach it for PendingState
771
+ promiseState.refresh = (usePolicy = false) => {
772
+ return performRefresh(future.requester, promiseState.request, usePolicy === true ? null : false);
773
+ };
774
+ if (state) {
775
+ if (state.isError) {
776
+ promiseState.error = state.result;
777
+ promiseState.reason = state.result;
778
+ promiseState.status = 'rejected';
779
+ promiseState.isError = true;
780
+ promiseState.isPending = false;
781
+ promiseState.isLoading = false;
782
+ promiseState.request = state.result.request;
783
+ promiseState.response = state.result.response;
784
+ } else {
785
+ promiseState.result = state.result.content;
786
+ promiseState.value = state.result.content;
787
+ promiseState.status = 'fulfilled';
788
+ promiseState.isSuccess = true;
789
+ promiseState.isPending = false;
790
+ promiseState.isLoading = false;
791
+ promiseState.request = state.result.request;
792
+ promiseState.response = state.result.response;
793
+ }
794
+ } else {
795
+ void future.then(result => {
796
+ setPromiseResult(future, {
797
+ isError: false,
798
+ result
799
+ });
800
+ promiseState.result = result.content;
801
+ promiseState.value = result.content;
802
+ promiseState.status = 'fulfilled';
803
+ promiseState.isSuccess = true;
804
+ promiseState.isPending = false;
805
+ promiseState.isLoading = false;
806
+ promiseState.request = result.request;
807
+ promiseState.response = result.response;
808
+ }, error => {
809
+ setPromiseResult(future, {
810
+ isError: true,
811
+ result: error
812
+ });
813
+ promiseState.error = error;
814
+ promiseState.reason = error;
815
+ promiseState.status = 'rejected';
816
+ promiseState.isError = true;
817
+ promiseState.isPending = false;
818
+ promiseState.isLoading = false;
819
+ promiseState.request = error.request;
820
+ promiseState.response = error.response;
821
+ });
822
+ }
823
+ return promiseState;
824
+ }
825
+
826
+ /**
827
+ * `getRequestState` can be used in both JavaScript and Template contexts.
828
+ *
829
+ * ```ts
830
+ * import { getRequestState } from '@warp-drive/ember';
831
+ *
832
+ * const state = getRequestState(future);
833
+ * ```
834
+ *
835
+ * For instance, we could write a getter on a component that updates whenever
836
+ * the request state advances or the future changes, by combining the function
837
+ * with the use of `@cached`
838
+ *
839
+ * ```ts
840
+ * class Component {
841
+ * @cached
842
+ * get title() {
843
+ * const state = getRequestState(this.args.request);
844
+ * if (state.isPending) {
845
+ * return 'loading...';
846
+ * }
847
+ * if (state.isError) { return null; }
848
+ * return state.result.title;
849
+ * }
850
+ * }
851
+ * ```
852
+ *
853
+ * Or in a template as a helper:
854
+ *
855
+ * ```gjs
856
+ * import { getRequestState } from '@warp-drive/ember';
857
+ *
858
+ * <template>
859
+ * {{#let (getRequestState @request) as |state|}}
860
+ * {{#if state.isPending}}
861
+ * <Spinner />
862
+ * {{else if state.isError}}
863
+ * <ErrorForm @error={{state.error}} />
864
+ * {{else}}
865
+ * <h1>{{state.result.title}}</h1>
866
+ * {{/if}}
867
+ * {{/let}}
868
+ * </template>
869
+ * ```
870
+ *
871
+ * If looking to use in a template, consider also the `<Request />` component
872
+ * which offers a number of additional capabilities for requests *beyond* what
873
+ * `RequestState` provides.
874
+ *
875
+ */
876
+ function getRequestState(future) {
877
+ let state = RequestCache.get(future);
878
+ if (!state) {
879
+ state = createRequestState(future);
880
+ RequestCache.set(future, state);
881
+ }
882
+ return state;
883
+ }
884
+ function decorateMethodV2(prototype, prop, decorators) {
885
+ const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
886
+ let desc = {
887
+ ...origDesc
888
+ };
889
+ for (let decorator of decorators) {
890
+ desc = decorator(prototype, prop, desc) || desc;
891
+ }
892
+ if (desc.initializer !== void 0) {
893
+ desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
894
+ desc.initializer = void 0;
895
+ }
896
+ Object.defineProperty(prototype, prop, desc);
897
+ }
898
+ const DEFAULT_DEADLINE = 30_000;
899
+ const DISPOSE = Symbol.dispose || Symbol.for('dispose');
900
+
901
+ /**
902
+ * Utilities to assist in recovering from the error.
903
+ */
904
+
905
+ /** @deprecated use {@link RecoveryFeatures} */
906
+
907
+ /**
908
+ * Utilities for keeping the request fresh
909
+ */
910
+
911
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
912
+
913
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
914
+
915
+ /**
916
+ * A reactive class
917
+ *
918
+ * @hideconstructor
919
+ */
920
+ class RequestSubscription {
921
+ /**
922
+ * Whether the browser reports that the network is online.
923
+ */
924
+
925
+ /**
926
+ * Whether the browser reports that the tab is hidden.
927
+ */
928
+
929
+ /**
930
+ * Whether the component is currently refreshing the request.
931
+ */
932
+
933
+ /**
934
+ * The most recent blocking request that was made, typically
935
+ * the result of a reload.
936
+ *
937
+ * This will never be the original request passed as an arg to
938
+ * the component.
939
+ *
940
+ * @internal
941
+ */
942
+
943
+ /**
944
+ * The most recent request that was made, typically due to either a
945
+ * reload or a refresh.
946
+ *
947
+ * This will never be the original request passed as an arg to
948
+ * the component.
949
+ *
950
+ * @internal
951
+ */
952
+
953
+ /**
954
+ * The time at which the network was reported as offline.
955
+ *
956
+ * @internal
957
+ */
958
+
959
+ /** @internal */
960
+
961
+ /** @internal */
962
+
963
+ /** @internal */
964
+
965
+ /** @internal */
966
+
967
+ /** @internal */
968
+
969
+ /**
970
+ * The event listener for network status changes,
971
+ * cached to use the reference for removal.
972
+ *
973
+ * @internal
974
+ */
975
+
976
+ /**
977
+ * The event listener for visibility status changes,
978
+ * cached to use the reference for removal.
979
+ *
980
+ * @internal
981
+ */
982
+
983
+ /**
984
+ * The last request passed as an arg to the component,
985
+ * cached for comparison.
986
+ *
987
+ * @internal
988
+ */
989
+
990
+ /**
991
+ * The last query passed as an arg to the component,
992
+ * cached for comparison.
993
+ *
994
+ * @internal
995
+ */
996
+
997
+ /** @internal */
998
+
999
+ /** @internal */
1000
+
1001
+ /** @internal */
1002
+
1003
+ /**
1004
+ * The Store this subscription subscribes to or the RequestManager
1005
+ * which issues this request.
1006
+ */
1007
+
1008
+ /**
1009
+ * The Store or RequestManager that the last subscription is attached to.
1010
+ *
1011
+ * This differs from 'store' because a <Request /> may be passed a
1012
+ * request originating from a different store than the <Request />
1013
+ * component would use if it were to issue the request itself.
1014
+ *
1015
+ * @internal
1016
+ */
1017
+ _requester;
1018
+ constructor(store, args) {
1019
+ this._args = args;
1020
+ this.store = store;
1021
+ this._subscribedTo = null;
1022
+ this._subscription = null;
1023
+ this._intervalStart = null;
1024
+ this._invalidated = false;
1025
+ this._nextInterval = null;
1026
+ this._requester = null;
1027
+ this.isDestroyed = false;
1028
+ this[DISPOSE] = _DISPOSE;
1029
+ this._installListeners();
1030
+ void this._beginPolling();
1031
+ }
1032
+
1033
+ /**
1034
+ * @internal
1035
+ */
1036
+ async _beginPolling() {
1037
+ // await the initial request
1038
+ try {
1039
+ if (!this.isIdle) {
1040
+ await this.request;
1041
+ }
1042
+ } catch {
1043
+ // ignore errors here, we just want to wait for the request to finish
1044
+ } finally {
1045
+ if (!this.isDestroyed) {
1046
+ void this._scheduleInterval();
1047
+ }
1048
+ }
1049
+ }
1050
+ get isIdle() {
1051
+ const {
1052
+ request,
1053
+ query
1054
+ } = this._args;
1055
+ return Boolean(!request && !query);
1056
+ }
1057
+ static {
1058
+ decorateMethodV2(this.prototype, "isIdle", [memoized]);
1059
+ }
1060
+ get autorefreshTypes() {
1061
+ const {
1062
+ autorefresh
1063
+ } = this._args;
1064
+ let types;
1065
+ if (autorefresh === true) {
1066
+ types = ['online', 'invalid'];
1067
+ } else if (typeof autorefresh === 'string') {
1068
+ types = autorefresh.split(',');
1069
+ } else {
1070
+ types = [];
1071
+ }
1072
+ return new Set(types);
1073
+ }
1074
+
1075
+ // we only run this function on component creation
1076
+ // and when an update is triggered, so it does not
1077
+ // react to changes in the autorefreshThreshold
1078
+ // or autorefresh args.
1079
+ //
1080
+ // if we need to react to those changes, we can
1081
+ // use a modifier or internal component or some
1082
+ // such to trigger a re-run of this function.
1083
+ /** @internal */
1084
+ static {
1085
+ decorateMethodV2(this.prototype, "autorefreshTypes", [memoized]);
1086
+ }
1087
+ async _scheduleInterval() {
1088
+ const {
1089
+ autorefreshThreshold
1090
+ } = this._args;
1091
+ const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;
1092
+ if (
1093
+ // dont schedule in SSR
1094
+ typeof window === 'undefined' ||
1095
+ // dont schedule without a threshold
1096
+ !hasValidThreshold ||
1097
+ // dont schedule if we weren't told to
1098
+ !this.autorefreshTypes.has('interval') ||
1099
+ // dont schedule if we're already scheduled
1100
+ this._intervalStart !== null) {
1101
+ return;
1102
+ }
1103
+
1104
+ // if we have a current request, wait for it to finish
1105
+ // before scheduling the next one
1106
+ if (this._latestRequest) {
1107
+ try {
1108
+ await this._latestRequest;
1109
+ } catch {
1110
+ // ignore errors here, we just want to wait for the request to finish
1111
+ }
1112
+ if (this.isDestroyed) {
1113
+ return;
1114
+ }
1115
+ }
1116
+
1117
+ // setup the next interval
1118
+ this._intervalStart = Date.now();
1119
+ this._nextInterval = setTimeout(() => {
1120
+ this._maybeUpdate();
1121
+ }, autorefreshThreshold);
1122
+ }
1123
+
1124
+ /** @internal */
1125
+ _clearInterval() {
1126
+ if (this._nextInterval) {
1127
+ clearTimeout(this._nextInterval);
1128
+ this._intervalStart = null;
1129
+ }
1130
+ }
1131
+ /**
1132
+ * @internal
1133
+ */
1134
+ _updateSubscriptions() {
1135
+ if (this.isIdle) {
1136
+ return;
1137
+ }
1138
+ const requestId = this._request.lid;
1139
+
1140
+ // if we're already subscribed to this request, we don't need to do anything
1141
+ if (this._subscribedTo === requestId) {
1142
+ return;
1143
+ }
1144
+
1145
+ // if we're subscribed to a different request, we need to unsubscribe
1146
+ this._removeSubscriptions();
1147
+
1148
+ // if we have a request, we need to subscribe to it
1149
+ const store = this._getRequester();
1150
+ this._requester = store;
1151
+ if (requestId && isStore(store)) {
1152
+ this._subscribedTo = requestId;
1153
+ this._subscription = store.notifications.subscribe(requestId, (_id, op) => {
1154
+ // ignore subscription events that occur while our own component's request
1155
+ // is occurring
1156
+ if (this._isUpdating) {
1157
+ return;
1158
+ }
1159
+ switch (op) {
1160
+ case 'invalidated':
1161
+ {
1162
+ // if we're subscribed to invalidations, we need to update
1163
+ if (this.autorefreshTypes.has('invalid')) {
1164
+ this._invalidated = true;
1165
+ this._maybeUpdate();
1166
+ }
1167
+ break;
1168
+ }
1169
+ case 'state':
1170
+ {
1171
+ const latest = store.requestManager._deduped.get(requestId);
1172
+ const priority = latest?.priority;
1173
+ const state = this.reqState;
1174
+ if (!priority) {
1175
+ // if there is no priority, we have completed whatever request
1176
+ // was occurring and so we are no longer refreshing (if we were)
1177
+ this.isRefreshing = false;
1178
+ } else if (priority.blocking && !state.isLoading) {
1179
+ // if we are blocking, there is an active request for this identity
1180
+ // that MUST be fulfilled from network (not cache).
1181
+ // Thus this is not "refreshing" because we should clear out and
1182
+ // block on this request.
1183
+ //
1184
+ // we receive state notifications when either a request initiates
1185
+ // or completes.
1186
+ //
1187
+ // In the completes case: we may receive the state notification
1188
+ // slightly before the request is finalized because the NotificationManager
1189
+ // may sync flush it (and thus deliver it before the microtask completes)
1190
+ //
1191
+ // In the initiates case: we aren't supposed to receive one unless there
1192
+ // is no other request in flight for this identity.
1193
+ //
1194
+ // However, there is a race condition here where the completed
1195
+ // notification can trigger an update that generates a new request
1196
+ // thus giving us an initiated notification before the older request
1197
+ // finalizes.
1198
+ //
1199
+ // When this occurs, if the triggered update happens to have caused
1200
+ // a new request to be made for the same identity AND that request
1201
+ // is the one passed into this component as the @request arg, then
1202
+ // getRequestState will return the state of the new request.
1203
+ // We can detect this by checking if the request state is "loading"
1204
+ // as outside of this case we would have a completed request.
1205
+ //
1206
+ // That is the reason for the `&& !state.isLoading` check above.
1207
+
1208
+ // TODO should we just treat this as refreshing?
1209
+ this.isRefreshing = false;
1210
+ this._maybeUpdate('policy', true);
1211
+ } else {
1212
+ this.isRefreshing = true;
1213
+ }
1214
+ }
1215
+ }
1216
+ });
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * @internal
1222
+ */
1223
+ _removeSubscriptions() {
1224
+ const store = this._requester;
1225
+ if (this._subscription && store && isStore(store)) {
1226
+ store.notifications.unsubscribe(this._subscription);
1227
+ this._subscribedTo = null;
1228
+ this._subscription = null;
1229
+ this._requester = null;
1230
+ }
1231
+ }
1232
+
1233
+ /**
1234
+ * Install the event listeners for network and visibility changes.
1235
+ * This is only done in browser environments with a global `window`.
1236
+ *
1237
+ * @internal
1238
+ */
1239
+ _installListeners() {
1240
+ if (typeof window === 'undefined') {
1241
+ return;
1242
+ }
1243
+ this.isOnline = window.navigator.onLine;
1244
+ this._unavailableStart = this.isOnline ? null : Date.now();
1245
+ this.isHidden = document.visibilityState === 'hidden';
1246
+ this._onlineChanged = event => {
1247
+ this.isOnline = event.type === 'online';
1248
+ if (event.type === 'offline' && this._unavailableStart === null) {
1249
+ this._unavailableStart = Date.now();
1250
+ }
1251
+ this._maybeUpdate();
1252
+ };
1253
+ this._backgroundChanged = () => {
1254
+ const isHidden = document.visibilityState === 'hidden';
1255
+ this.isHidden = isHidden;
1256
+ if (isHidden && this._unavailableStart === null) {
1257
+ this._unavailableStart = Date.now();
1258
+ }
1259
+ this._maybeUpdate();
1260
+ };
1261
+ window.addEventListener('online', this._onlineChanged, {
1262
+ passive: true,
1263
+ capture: true
1264
+ });
1265
+ window.addEventListener('offline', this._onlineChanged, {
1266
+ passive: true,
1267
+ capture: true
1268
+ });
1269
+ document.addEventListener('visibilitychange', this._backgroundChanged, {
1270
+ passive: true,
1271
+ capture: true
1272
+ });
1273
+ }
1274
+
1275
+ /**
1276
+ * If the network is online and the tab is visible, either reload or refresh the request
1277
+ * based on the component's configuration and the requested update mode.
1278
+ *
1279
+ * Valid modes are:
1280
+ *
1281
+ * - `'reload'`: Force a reload of the request.
1282
+ * - `'refresh'`: Refresh the request in the background.
1283
+ * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.
1284
+ * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.
1285
+ *
1286
+ * @internal
1287
+ */
1288
+ _maybeUpdate(mode, silent) {
1289
+ if (this.isIdle) {
1290
+ return;
1291
+ }
1292
+ const {
1293
+ reqState
1294
+ } = this;
1295
+ if (reqState.isPending) {
1296
+ return;
1297
+ }
1298
+ const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));
1299
+ if (!canAttempt) {
1300
+ if (!silent && mode && mode !== '_invalidated') {
1301
+ throw new Error(`Reload not available: the network is not online or the tab is hidden`);
1302
+ }
1303
+ return;
1304
+ }
1305
+ const {
1306
+ autorefreshTypes
1307
+ } = this;
1308
+ let shouldAttempt = this._invalidated || Boolean(mode);
1309
+ if (!shouldAttempt && autorefreshTypes.has('online')) {
1310
+ const {
1311
+ _unavailableStart
1312
+ } = this;
1313
+ const {
1314
+ autorefreshThreshold
1315
+ } = this._args;
1316
+ const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;
1317
+ shouldAttempt = Boolean(_unavailableStart && Date.now() - _unavailableStart > deadline);
1318
+ }
1319
+ if (!shouldAttempt && autorefreshTypes.has('interval')) {
1320
+ const {
1321
+ _intervalStart
1322
+ } = this;
1323
+ const {
1324
+ autorefreshThreshold
1325
+ } = this._args;
1326
+ if (_intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {
1327
+ shouldAttempt = Boolean(Date.now() - _intervalStart >= autorefreshThreshold);
1328
+ }
1329
+ }
1330
+ this._unavailableStart = null;
1331
+ this._invalidated = false;
1332
+ if (shouldAttempt) {
1333
+ this._clearInterval();
1334
+ this._isUpdating = true;
1335
+ const realMode = mode === '_invalidated' ? null : mode;
1336
+ const val = realMode ?? this._args.autorefreshBehavior ?? 'policy';
1337
+
1338
+ // if the future was generated by an older store version, it may not have
1339
+ // a requester set. In this case we append it to ensure that reload and
1340
+ // refresh will work appropriately.
1341
+ const requester = this._getRequester();
1342
+ if (!reqState._request.requester) {
1343
+ reqState._request.requester = requester;
1344
+ }
1345
+ switch (val) {
1346
+ case 'reload':
1347
+ this._latestRequest = reqState.reload();
1348
+ break;
1349
+ case 'refresh':
1350
+ this._latestRequest = reqState.refresh();
1351
+ break;
1352
+ case 'policy':
1353
+ this._latestRequest = reqState.refresh(true);
1354
+ break;
1355
+ }
1356
+ if (val !== 'refresh') {
1357
+ this._localRequest = this._latestRequest;
1358
+ }
1359
+ void this._scheduleInterval();
1360
+ void this._latestRequest.finally(() => {
1361
+ this._isUpdating = false;
1362
+ });
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * @internal
1368
+ */
1369
+ _getRequester() {
1370
+ // Note: we check for the requester's presence
1371
+ // as well as the request's presence because we may
1372
+ // be subscribed to a request issued by a store from an older
1373
+ // version of the library that didn't yet set requester.
1374
+ if (this._args.request?.requester) {
1375
+ return this._args.request.requester;
1376
+ }
1377
+ return this.store;
1378
+ }
1379
+
1380
+ /**
1381
+ * Retry the request, reloading it from the server.
1382
+ */
1383
+ retry = async () => {
1384
+ this._maybeUpdate('reload');
1385
+ await this._localRequest;
1386
+ };
1387
+
1388
+ /**
1389
+ * Refresh the request, updating it in the background.
1390
+ */
1391
+ refresh = async () => {
1392
+ this._maybeUpdate('refresh');
1393
+ await this._latestRequest;
1394
+ };
1395
+
1396
+ /**
1397
+ * features to yield to the error slot of a component
1398
+ */
1399
+ get errorFeatures() {
1400
+ return {
1401
+ isHidden: this.isHidden,
1402
+ isOnline: this.isOnline,
1403
+ retry: this.retry
1404
+ };
1405
+ }
1406
+
1407
+ /**
1408
+ * features to yield to the content slot of a component
1409
+ */
1410
+ static {
1411
+ decorateMethodV2(this.prototype, "errorFeatures", [memoized]);
1412
+ }
1413
+ get contentFeatures() {
1414
+ const feat = {
1415
+ isHidden: this.isHidden,
1416
+ isOnline: this.isOnline,
1417
+ reload: this.retry,
1418
+ refresh: this.refresh,
1419
+ isRefreshing: this.isRefreshing,
1420
+ latestRequest: this._latestRequest
1421
+ };
1422
+ if (feat.isRefreshing) {
1423
+ feat.abort = () => {
1424
+ this._latestRequest?.abort();
1425
+ };
1426
+ }
1427
+ return feat;
1428
+ }
1429
+
1430
+ /**
1431
+ * @internal
1432
+ */
1433
+ static {
1434
+ decorateMethodV2(this.prototype, "contentFeatures", [memoized]);
1435
+ }
1436
+ get _request() {
1437
+ const {
1438
+ request,
1439
+ query
1440
+ } = this._args;
1441
+ const {
1442
+ _localRequest,
1443
+ _originalRequest,
1444
+ _originalQuery
1445
+ } = this;
1446
+ const isOriginalRequest = request === _originalRequest && query === _originalQuery;
1447
+ if (_localRequest && isOriginalRequest) {
1448
+ return _localRequest;
1449
+ }
1450
+
1451
+ // update state checks for the next time
1452
+ this._originalQuery = query;
1453
+ this._originalRequest = request;
1454
+ if (request) {
1455
+ return request;
1456
+ }
1457
+ return this.store.request(query);
1458
+ }
1459
+ static {
1460
+ decorateMethodV2(this.prototype, "_request", [memoized]);
1461
+ }
1462
+ get request() {
1463
+ {
1464
+ const request = this._request;
1465
+ this._updateSubscriptions();
1466
+ return request;
1467
+ }
1468
+ }
1469
+ static {
1470
+ decorateMethodV2(this.prototype, "request", [memoized]);
1471
+ }
1472
+ get reqState() {
1473
+ return getRequestState(this.request);
1474
+ }
1475
+ get result() {
1476
+ return this.reqState.result;
1477
+ }
1478
+ }
1479
+ defineSignal(RequestSubscription.prototype, 'isOnline', true);
1480
+ defineSignal(RequestSubscription.prototype, 'isHidden', false);
1481
+ defineSignal(RequestSubscription.prototype, 'isRefreshing', false);
1482
+ defineSignal(RequestSubscription.prototype, '_localRequest', undefined);
1483
+ defineSignal(RequestSubscription.prototype, '_latestRequest', undefined);
1484
+ function isStore(store) {
1485
+ return 'requestManager' in store;
1486
+ }
1487
+ function createRequestSubscription(store, args) {
1488
+ return new RequestSubscription(store, args);
1489
+ }
1490
+ function upgradeSubscription(sub) {
1491
+ return sub;
1492
+ }
1493
+ function _DISPOSE() {
1494
+ const self = upgradeSubscription(this);
1495
+ self.isDestroyed = true;
1496
+ self._removeSubscriptions();
1497
+ if (typeof window === 'undefined') {
1498
+ return;
1499
+ }
1500
+ self._clearInterval();
1501
+ window.removeEventListener('online', self._onlineChanged, {
1502
+ passive: true,
1503
+ capture: true
1504
+ });
1505
+ window.removeEventListener('offline', self._onlineChanged, {
1506
+ passive: true,
1507
+ capture: true
1508
+ });
1509
+ document.removeEventListener('visibilitychange', self._backgroundChanged, {
1510
+ passive: true,
1511
+ capture: true
1512
+ });
1513
+ }
1514
+ const PromiseCache = new WeakMap();
1515
+
1516
+ /**
1517
+ * The state of a promise in the "pending"
1518
+ * state. This is the default initial state.
1519
+ *
1520
+ */
1521
+
1522
+ /**
1523
+ * The state of a promise in the "fulfilled" state.
1524
+ * This is the state of a promise that has resolved
1525
+ * successfully.
1526
+ *
1527
+ */
1528
+
1529
+ /**
1530
+ * The state of a promise in the "rejected" state.
1531
+ * This is the state of a promise that has rejected
1532
+ * with an error.
1533
+ *
1534
+ */
1535
+
1536
+ /**
1537
+ * The state of a promise. This is the type that is returned
1538
+ * from `getPromiseState`.
1539
+ *
1540
+ * See also:
1541
+ * - {@link PendingPromise}
1542
+ * - {@link ResolvedPromise}
1543
+ * - {@link RejectedPromise}
1544
+ *
1545
+ */
1546
+
1547
+ const PromiseStateProto = {};
1548
+
1549
+ // TODO introduce a new mechanism for defining multiple properties
1550
+ // that share a common signal
1551
+ defineSignal(PromiseStateProto, 'reason', null);
1552
+ defineSignal(PromiseStateProto, 'value', null);
1553
+ defineSignal(PromiseStateProto, 'result', null);
1554
+ defineSignal(PromiseStateProto, 'error', null);
1555
+ defineSignal(PromiseStateProto, 'status', 'pending');
1556
+ defineSignal(PromiseStateProto, 'isPending', true);
1557
+ defineSignal(PromiseStateProto, 'isLoading', true);
1558
+ defineSignal(PromiseStateProto, 'isSuccess', false);
1559
+ defineSignal(PromiseStateProto, 'isError', false);
1560
+ function createPromiseState(promise) {
1561
+ const state = getPromiseResult(promise);
1562
+ const promiseState = Object.create(PromiseStateProto);
1563
+ if (state) {
1564
+ if (state.isError) {
1565
+ promiseState.error = state.result;
1566
+ promiseState.reason = state.result;
1567
+ promiseState.status = 'rejected';
1568
+ promiseState.isError = true;
1569
+ promiseState.isPending = false;
1570
+ promiseState.isLoading = false;
1571
+ } else {
1572
+ promiseState.result = state.result;
1573
+ promiseState.value = state.result;
1574
+ promiseState.status = 'fulfilled';
1575
+ promiseState.isSuccess = true;
1576
+ promiseState.isPending = false;
1577
+ promiseState.isLoading = false;
1578
+ }
1579
+ } else {
1580
+ void promise.then(result => {
1581
+ setPromiseResult(promise, {
1582
+ isError: false,
1583
+ result
1584
+ });
1585
+ promiseState.result = result;
1586
+ promiseState.value = result;
1587
+ promiseState.status = 'fulfilled';
1588
+ promiseState.isSuccess = true;
1589
+ promiseState.isPending = false;
1590
+ promiseState.isLoading = false;
1591
+ }, error => {
1592
+ setPromiseResult(promise, {
1593
+ isError: true,
1594
+ result: error
1595
+ });
1596
+ promiseState.error = error;
1597
+ promiseState.reason = error;
1598
+ promiseState.status = 'rejected';
1599
+ promiseState.isError = true;
1600
+ promiseState.isPending = false;
1601
+ promiseState.isLoading = false;
1602
+ });
1603
+ }
1604
+ return promiseState;
1605
+ }
1606
+ const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
1607
+ function isLegacyAwaitable(promise) {
1608
+ return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;
1609
+ }
1610
+ function getPromise(promise) {
1611
+ return isLegacyAwaitable(promise) ? promise.promise : promise;
1612
+ }
1613
+
1614
+ /**
1615
+ * Returns a reactive state-machine for the provided promise or awaitable.
1616
+ *
1617
+ * Repeat calls to `getPromiseState` with the same promise will return the same state object
1618
+ * making is safe and easy to use in templates and JavaScript code to produce reactive
1619
+ * behaviors around promises.
1620
+ *
1621
+ * `getPromiseState` can be used in both JavaScript and Template contexts.
1622
+ *
1623
+ * ```ts
1624
+ * import { getPromiseState } from '@warp-drive/ember';
1625
+ *
1626
+ * const state = getPromiseState(promise);
1627
+ * ```
1628
+ *
1629
+ * For instance, we could write a getter on a component that updates whenever
1630
+ * the promise state advances or the promise changes, by combining the function
1631
+ * with the use of `@cached`
1632
+ *
1633
+ * ```ts
1634
+ * class Component {
1635
+ * @cached
1636
+ * get title() {
1637
+ * const state = getPromiseState(this.args.request);
1638
+ * if (state.isPending) {
1639
+ * return 'loading...';
1640
+ * }
1641
+ * if (state.isError) { return null; }
1642
+ * return state.result.title;
1643
+ * }
1644
+ * }
1645
+ * ```
1646
+ *
1647
+ * Or in a template as a helper:
1648
+ *
1649
+ * ```gjs
1650
+ * import { getPromiseState } from '@warp-drive/ember';
1651
+ *
1652
+ * <template>
1653
+ * {{#let (getPromiseState @request) as |state|}}
1654
+ * {{#if state.isPending}} <Spinner />
1655
+ * {{else if state.isError}} <ErrorForm @error={{state.error}} />
1656
+ * {{else}}
1657
+ * <h1>{{state.result.title}}</h1>
1658
+ * {{/if}}
1659
+ * {{/let}}
1660
+ * </template>
1661
+ * ```
1662
+ *
1663
+ * If looking to use in a template, consider also the `<Await />` component.
1664
+ *
1665
+ * See also {@link PromiseState}
1666
+ */
1667
+ function getPromiseState(promise) {
1668
+ const _promise = getPromise(promise);
1669
+ let state = PromiseCache.get(_promise);
1670
+ if (!state) {
1671
+ state = createPromiseState(_promise);
1672
+ PromiseCache.set(_promise, state);
1673
+ }
1674
+ return state;
1675
+ }
1676
+ export { ARRAY_SIGNAL as A, DISPOSE as D, OBJECT_SIGNAL as O, Signals as S, withSignalStore as a, createInternalSignal as b, consumeInternalSignal as c, defineGate as d, createSignalDescriptor as e, defineSignal as f, getOrCreateInternalSignal as g, entangleSignal as h, entangleInitiallyStaleSignal as i, createInternalMemo as j, createRequestSubscription as k, getRequestState as l, getPromiseState as m, notifyInternalSignal as n, defineNonEnumerableSignal as o, peekInternalSignal as p, signal as q, waitFor as r, setupSignals as s, gate as t, memoized as u, willSyncFlushWatchers as w };