@fozy-labs/rx-toolkit 0.5.3 → 0.6.0

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 (302) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +22 -13
  3. package/dist/common/devtools/reduxDevtools.js +17 -2
  4. package/dist/common/react/index.d.ts +1 -0
  5. package/dist/common/react/index.js +1 -0
  6. package/dist/common/react/useIsomorphicLayoutEffect.d.ts +17 -0
  7. package/dist/common/react/useIsomorphicLayoutEffect.js +17 -0
  8. package/dist/index.d.ts +1 -2
  9. package/dist/index.js +1 -2
  10. package/dist/query/api/createApi.d.ts +4 -0
  11. package/dist/query/api/createApi.js +9 -0
  12. package/dist/query/api/index.d.ts +1 -0
  13. package/dist/query/api/index.js +1 -0
  14. package/dist/query/constants.d.ts +12 -0
  15. package/dist/query/constants.js +15 -0
  16. package/dist/query/core/api/Api.d.ts +20 -0
  17. package/dist/query/core/api/Api.js +129 -0
  18. package/dist/query/core/api/constants.d.ts +2 -0
  19. package/dist/query/core/api/constants.js +3 -0
  20. package/dist/query/core/api/index.d.ts +4 -0
  21. package/dist/query/core/api/index.js +4 -0
  22. package/dist/query/core/api/mergeHooks.d.ts +2 -0
  23. package/dist/query/core/api/mergeHooks.js +26 -0
  24. package/dist/query/core/api/normalizeLinks.d.ts +2 -0
  25. package/dist/query/core/api/normalizeLinks.js +11 -0
  26. package/dist/query/core/cache/CacheEntry.d.ts +21 -0
  27. package/dist/query/core/cache/CacheEntry.js +54 -0
  28. package/dist/query/core/cache/CacheMap.d.ts +19 -0
  29. package/dist/query/core/cache/CacheMap.js +32 -0
  30. package/dist/query/core/cache/QueryCacheEntry.d.ts +21 -0
  31. package/dist/query/core/cache/QueryCacheEntry.js +136 -0
  32. package/dist/query/core/cache/index.d.ts +3 -0
  33. package/dist/query/core/cache/index.js +3 -0
  34. package/dist/query/core/command/Command.d.ts +67 -0
  35. package/dist/query/core/command/Command.js +253 -0
  36. package/dist/query/core/command/CommandAgent.d.ts +17 -0
  37. package/dist/query/core/command/CommandAgent.js +67 -0
  38. package/dist/query/core/command/LinkManager.d.ts +24 -0
  39. package/dist/query/core/command/LinkManager.js +71 -0
  40. package/dist/query/core/command/index.d.ts +2 -0
  41. package/dist/query/core/command/index.js +2 -0
  42. package/dist/query/core/errors/CacheEntryRemovedError.d.ts +7 -0
  43. package/dist/query/core/errors/CacheEntryRemovedError.js +9 -0
  44. package/dist/query/core/errors/MachineStateError.d.ts +8 -0
  45. package/dist/query/core/errors/MachineStateError.js +10 -0
  46. package/dist/query/core/errors/MachineTransitionError.d.ts +7 -0
  47. package/dist/query/core/errors/MachineTransitionError.js +9 -0
  48. package/dist/query/core/errors/index.d.ts +3 -0
  49. package/dist/query/core/errors/index.js +3 -0
  50. package/dist/query/core/index.d.ts +8 -0
  51. package/dist/query/core/index.js +8 -0
  52. package/dist/query/core/machine/Machine.d.ts +21 -0
  53. package/dist/query/core/machine/Machine.js +42 -0
  54. package/dist/query/core/machine/MachineBase.d.ts +31 -0
  55. package/dist/query/core/machine/MachineBase.js +176 -0
  56. package/dist/query/core/machine/MachineError.d.ts +10 -0
  57. package/dist/query/core/machine/MachineError.js +19 -0
  58. package/dist/query/core/machine/MachinePending.d.ts +13 -0
  59. package/dist/query/core/machine/MachinePending.js +32 -0
  60. package/dist/query/core/machine/MachineRefreshError.d.ts +12 -0
  61. package/dist/query/core/machine/MachineRefreshError.js +23 -0
  62. package/dist/query/core/machine/MachineRefreshing.d.ts +15 -0
  63. package/dist/query/core/machine/MachineRefreshing.js +43 -0
  64. package/dist/query/core/machine/MachineSuccess.d.ts +12 -0
  65. package/dist/query/core/machine/MachineSuccess.js +23 -0
  66. package/dist/query/core/machine/MachineWithData.d.ts +25 -0
  67. package/dist/query/core/machine/MachineWithData.js +73 -0
  68. package/dist/query/core/machine/index.d.ts +9 -0
  69. package/dist/query/core/machine/index.js +9 -0
  70. package/dist/query/core/machine/machine-helpers.d.ts +9 -0
  71. package/dist/query/core/machine/machine-helpers.js +80 -0
  72. package/dist/query/core/patcher/Patcher.d.ts +30 -0
  73. package/dist/query/core/patcher/Patcher.js +122 -0
  74. package/dist/query/core/patcher/index.d.ts +1 -0
  75. package/dist/query/core/patcher/index.js +1 -0
  76. package/dist/query/core/resource/Resource.d.ts +105 -0
  77. package/dist/query/core/resource/Resource.js +340 -0
  78. package/dist/query/core/resource/ResourceAgent.d.ts +37 -0
  79. package/dist/query/core/resource/ResourceAgent.js +179 -0
  80. package/dist/query/core/resource/index.d.ts +2 -0
  81. package/dist/query/core/resource/index.js +2 -0
  82. package/dist/query/core/snapshoter/Snapshoter.d.ts +22 -0
  83. package/dist/query/core/snapshoter/Snapshoter.js +78 -0
  84. package/dist/query/core/snapshoter/index.d.ts +2 -0
  85. package/dist/query/core/snapshoter/index.js +1 -0
  86. package/dist/query/core/syncer/Syncer.d.ts +32 -0
  87. package/dist/query/core/syncer/Syncer.js +85 -0
  88. package/dist/query/core/syncer/index.d.ts +2 -0
  89. package/dist/query/core/syncer/index.js +1 -0
  90. package/dist/query/index.d.ts +5 -10
  91. package/dist/query/index.js +5 -13
  92. package/dist/query/lib/broadcastSyncDriver.d.ts +5 -0
  93. package/dist/query/lib/broadcastSyncDriver.js +46 -0
  94. package/dist/query/lib/index.d.ts +3 -0
  95. package/dist/query/lib/index.js +3 -0
  96. package/dist/{query-v2 → query}/lib/stableStringify.js +5 -3
  97. package/dist/query/lib/toKeyed.d.ts +11 -0
  98. package/dist/query/lib/toKeyed.js +18 -0
  99. package/dist/query/react/ReactHooksPlugin.d.ts +31 -0
  100. package/dist/query/react/ReactHooksPlugin.js +21 -0
  101. package/dist/query/react/index.d.ts +3 -0
  102. package/dist/query/react/index.js +3 -0
  103. package/dist/query/react/useCommand.d.ts +2 -0
  104. package/dist/query/react/useCommand.js +14 -0
  105. package/dist/query/react/useResource.d.ts +2 -0
  106. package/dist/query/react/useResource.js +16 -0
  107. package/dist/query/types/api.d.ts +39 -0
  108. package/dist/query/types/cache.d.ts +51 -0
  109. package/dist/query/types/command.d.ts +52 -0
  110. package/dist/query/types/common.d.ts +65 -0
  111. package/dist/query/types/index.d.ts +8 -4
  112. package/dist/query/types/index.js +8 -5
  113. package/dist/query/types/plugin-hkt.d.ts +64 -0
  114. package/dist/query/types/resource.d.ts +49 -0
  115. package/dist/query/types/snapshot.d.ts +27 -0
  116. package/dist/query/types/snapshot.js +2 -0
  117. package/dist/query/types/state.d.ts +24 -0
  118. package/dist/signals/base/ComputeCache.js +1 -1
  119. package/dist/signals/base/Devtools.js +2 -6
  120. package/dist/signals/signals/Computed.d.ts +1 -0
  121. package/dist/signals/signals/Computed.js +5 -1
  122. package/dist/signals/signals/Effect.d.ts +0 -4
  123. package/dist/signals/signals/Effect.js +0 -6
  124. package/dist/signals/signals/LocalState.d.ts +1 -10
  125. package/dist/signals/signals/LocalState.js +0 -12
  126. package/dist/signals/signals/Signal.d.ts +2 -8
  127. package/dist/signals/signals/Signal.js +1 -10
  128. package/dist/signals/signals/State.d.ts +2 -1
  129. package/dist/signals/signals/State.js +9 -0
  130. package/dist/signals/types/SignalOptions.d.ts +0 -2
  131. package/dist/signals/types/normalizeSignalOptions.js +0 -3
  132. package/dist/signals/types/signals.types.d.ts +3 -1
  133. package/docs/CHANGELOG.md +61 -31
  134. package/docs/migrations/0.6.0.md +224 -0
  135. package/docs/query/README.md +52 -562
  136. package/docs/query/api/README.md +59 -0
  137. package/docs/query/api/_CacheEntry.md +39 -0
  138. package/docs/query/api/_CacheMap.md +30 -0
  139. package/docs/query/api/_QueryCacheEntry.md +81 -0
  140. package/docs/query/api/command-agent.md +60 -0
  141. package/docs/query/api/command.md +76 -0
  142. package/docs/query/api/resource-agent.md +68 -0
  143. package/docs/query/api/resource.md +77 -0
  144. package/docs/query/concepts/agent.md +70 -0
  145. package/docs/query/concepts/architecture.md +139 -0
  146. package/docs/query/concepts/cache.md +81 -0
  147. package/docs/query/concepts/dataflows.md +473 -0
  148. package/docs/query/concepts/keyed.md +42 -0
  149. package/docs/query/concepts/machine.md +106 -0
  150. package/docs/query/concepts/patching.md +85 -0
  151. package/docs/query/usage/broadcast.md +188 -0
  152. package/docs/query/usage/command.md +203 -0
  153. package/docs/query/usage/lifecycle.md +114 -0
  154. package/docs/query/usage/links.md +125 -0
  155. package/docs/query/usage/plugins.md +96 -0
  156. package/docs/query/usage/resource.md +206 -0
  157. package/docs/query/usage/snapshot.md +80 -0
  158. package/docs/usage/react/README.md +45 -91
  159. package/package.json +6 -9
  160. package/dist/query/SKIP_TOKEN.d.ts +0 -1
  161. package/dist/query/SKIP_TOKEN.js +0 -1
  162. package/dist/query/api/createCommand.d.ts +0 -21
  163. package/dist/query/api/createCommand.js +0 -20
  164. package/dist/query/api/createOperation.d.ts +0 -5
  165. package/dist/query/api/createOperation.js +0 -6
  166. package/dist/query/api/createResource.d.ts +0 -3
  167. package/dist/query/api/createResource.js +0 -2
  168. package/dist/query/api/createResourceDuplicator.d.ts +0 -4
  169. package/dist/query/api/createResourceDuplicator.js +0 -2
  170. package/dist/query/api/resetAllQueriesCache.d.ts +0 -1
  171. package/dist/query/api/resetAllQueriesCache.js +0 -4
  172. package/dist/query/core/Command/Command.d.ts +0 -35
  173. package/dist/query/core/Command/Command.js +0 -210
  174. package/dist/query/core/Command/CommandAgent.d.ts +0 -19
  175. package/dist/query/core/Command/CommandAgent.js +0 -54
  176. package/dist/query/core/Command/index.d.ts +0 -2
  177. package/dist/query/core/Command/index.js +0 -2
  178. package/dist/query/core/Operation/Operation.d.ts +0 -8
  179. package/dist/query/core/Operation/Operation.js +0 -4
  180. package/dist/query/core/Operation/OperationAgent.d.ts +0 -4
  181. package/dist/query/core/Operation/OperationAgent.js +0 -4
  182. package/dist/query/core/QueriesCache.d.ts +0 -9
  183. package/dist/query/core/QueriesCache.js +0 -28
  184. package/dist/query/core/QueriesLifetimeHooks.d.ts +0 -22
  185. package/dist/query/core/QueriesLifetimeHooks.js +0 -86
  186. package/dist/query/core/ResetAllQueriesSignal.d.ts +0 -6
  187. package/dist/query/core/ResetAllQueriesSignal.js +0 -11
  188. package/dist/query/core/Resource/Resource.d.ts +0 -51
  189. package/dist/query/core/Resource/Resource.js +0 -232
  190. package/dist/query/core/Resource/ResourceAgent.d.ts +0 -35
  191. package/dist/query/core/Resource/ResourceAgent.js +0 -110
  192. package/dist/query/core/Resource/ResourceDuplicator.d.ts +0 -73
  193. package/dist/query/core/Resource/ResourceDuplicator.js +0 -227
  194. package/dist/query/core/Resource/ResourceDuplicatorAgent.d.ts +0 -35
  195. package/dist/query/core/Resource/ResourceDuplicatorAgent.js +0 -110
  196. package/dist/query/core/Resource/ResourceRef.d.ts +0 -16
  197. package/dist/query/core/Resource/ResourceRef.js +0 -136
  198. package/dist/query/lib/IndirectMap.d.ts +0 -19
  199. package/dist/query/lib/IndirectMap.js +0 -88
  200. package/dist/query/lib/ReactiveCache.d.ts +0 -62
  201. package/dist/query/lib/ReactiveCache.js +0 -80
  202. package/dist/query/react/useCommandAgent.d.ts +0 -24
  203. package/dist/query/react/useCommandAgent.js +0 -39
  204. package/dist/query/react/useOperationAgent.d.ts +0 -6
  205. package/dist/query/react/useOperationAgent.js +0 -6
  206. package/dist/query/react/useResourceAgent.d.ts +0 -6
  207. package/dist/query/react/useResourceAgent.js +0 -31
  208. package/dist/query/react/useResourceRef.d.ts +0 -5
  209. package/dist/query/react/useResourceRef.js +0 -13
  210. package/dist/query/types/Command.types.d.ts +0 -154
  211. package/dist/query/types/Command.types.js +0 -1
  212. package/dist/query/types/Operation.types.d.ts +0 -13
  213. package/dist/query/types/Operation.types.js +0 -1
  214. package/dist/query/types/Resource.types.d.ts +0 -129
  215. package/dist/query/types/Resource.types.js +0 -1
  216. package/dist/query/types/shared.types.d.ts +0 -26
  217. package/dist/query/types/shared.types.js +0 -1
  218. package/dist/query-v2/api/createApi.d.ts +0 -10
  219. package/dist/query-v2/api/createApi.js +0 -83
  220. package/dist/query-v2/core/common/CacheEntry.d.ts +0 -29
  221. package/dist/query-v2/core/common/CacheEntry.js +0 -71
  222. package/dist/query-v2/core/common/CacheMap.d.ts +0 -38
  223. package/dist/query-v2/core/common/CacheMap.js +0 -127
  224. package/dist/query-v2/core/common/LifecycleHooks.d.ts +0 -22
  225. package/dist/query-v2/core/common/LifecycleHooks.js +0 -104
  226. package/dist/query-v2/core/common/index.d.ts +0 -3
  227. package/dist/query-v2/core/common/index.js +0 -3
  228. package/dist/query-v2/core/index.d.ts +0 -3
  229. package/dist/query-v2/core/index.js +0 -3
  230. package/dist/query-v2/core/machines/Machine.d.ts +0 -14
  231. package/dist/query-v2/core/machines/Machine.js +0 -33
  232. package/dist/query-v2/core/machines/MachineError.d.ts +0 -11
  233. package/dist/query-v2/core/machines/MachineError.js +0 -26
  234. package/dist/query-v2/core/machines/MachineIdle.d.ts +0 -8
  235. package/dist/query-v2/core/machines/MachineIdle.js +0 -19
  236. package/dist/query-v2/core/machines/MachinePending.d.ts +0 -12
  237. package/dist/query-v2/core/machines/MachinePending.js +0 -29
  238. package/dist/query-v2/core/machines/MachineRefreshing.d.ts +0 -14
  239. package/dist/query-v2/core/machines/MachineRefreshing.js +0 -46
  240. package/dist/query-v2/core/machines/MachineSuccess.d.ts +0 -16
  241. package/dist/query-v2/core/machines/MachineSuccess.js +0 -42
  242. package/dist/query-v2/core/machines/MachineWithData.d.ts +0 -18
  243. package/dist/query-v2/core/machines/MachineWithData.js +0 -40
  244. package/dist/query-v2/core/machines/Patcher.d.ts +0 -20
  245. package/dist/query-v2/core/machines/Patcher.js +0 -104
  246. package/dist/query-v2/core/machines/index.d.ts +0 -8
  247. package/dist/query-v2/core/machines/index.js +0 -8
  248. package/dist/query-v2/core/resource/ResourceV2.d.ts +0 -120
  249. package/dist/query-v2/core/resource/ResourceV2.js +0 -464
  250. package/dist/query-v2/core/resource/ResourceV2Agent.d.ts +0 -26
  251. package/dist/query-v2/core/resource/ResourceV2Agent.js +0 -132
  252. package/dist/query-v2/core/resource/index.d.ts +0 -2
  253. package/dist/query-v2/core/resource/index.js +0 -2
  254. package/dist/query-v2/index.d.ts +0 -11
  255. package/dist/query-v2/index.js +0 -17
  256. package/dist/query-v2/lib/NO_VALUE.d.ts +0 -2
  257. package/dist/query-v2/lib/NO_VALUE.js +0 -1
  258. package/dist/query-v2/lib/SKIP_TOKEN.d.ts +0 -2
  259. package/dist/query-v2/lib/SKIP_TOKEN.js +0 -1
  260. package/dist/query-v2/lib/index.d.ts +0 -4
  261. package/dist/query-v2/lib/index.js +0 -3
  262. package/dist/query-v2/plugins/ReactHooksPlugin.d.ts +0 -25
  263. package/dist/query-v2/plugins/ReactHooksPlugin.js +0 -19
  264. package/dist/query-v2/plugins/types.d.ts +0 -1
  265. package/dist/query-v2/react/__tests__/helpers.d.ts +0 -12
  266. package/dist/query-v2/react/__tests__/helpers.js +0 -33
  267. package/dist/query-v2/react/index.d.ts +0 -2
  268. package/dist/query-v2/react/index.js +0 -2
  269. package/dist/query-v2/react/useResourceV2Agent.d.ts +0 -12
  270. package/dist/query-v2/react/useResourceV2Agent.js +0 -36
  271. package/dist/query-v2/react/useResourceV2Ref.d.ts +0 -12
  272. package/dist/query-v2/react/useResourceV2Ref.js +0 -57
  273. package/dist/query-v2/snapshot/Snapshot.d.ts +0 -13
  274. package/dist/query-v2/snapshot/Snapshot.js +0 -76
  275. package/dist/query-v2/types/agent.types.d.ts +0 -54
  276. package/dist/query-v2/types/api.types.d.ts +0 -22
  277. package/dist/query-v2/types/cache.types.d.ts +0 -37
  278. package/dist/query-v2/types/index.d.ts +0 -9
  279. package/dist/query-v2/types/index.js +0 -9
  280. package/dist/query-v2/types/lifecycle.types.d.ts +0 -25
  281. package/dist/query-v2/types/machine.types.d.ts +0 -67
  282. package/dist/query-v2/types/plugin.types.d.ts +0 -38
  283. package/dist/query-v2/types/resource.types.d.ts +0 -35
  284. package/dist/query-v2/types/resource.types.js +0 -1
  285. package/dist/query-v2/types/shared.types.d.ts +0 -20
  286. package/dist/query-v2/types/shared.types.js +0 -1
  287. package/dist/query-v2/types/snapshot.types.d.ts +0 -21
  288. package/dist/query-v2/types/snapshot.types.js +0 -1
  289. package/docs/contributing/query-v2/README.md +0 -379
  290. package/docs/migrations/query-v2.md +0 -171
  291. package/docs/query-v2/README.md +0 -280
  292. package/docs/query-v2/api-reference.md +0 -235
  293. package/docs/query-v2/optimistic-updates.md +0 -148
  294. package/docs/query-v2/ssr.md +0 -130
  295. /package/dist/{query-v2 → query}/lib/stableStringify.d.ts +0 -0
  296. /package/dist/{query-v2/plugins/types.js → query/types/api.js} +0 -0
  297. /package/dist/{query-v2/types/agent.types.js → query/types/cache.js} +0 -0
  298. /package/dist/{query-v2/types/api.types.js → query/types/command.js} +0 -0
  299. /package/dist/{query-v2/types/cache.types.js → query/types/common.js} +0 -0
  300. /package/dist/{query-v2/types/lifecycle.types.js → query/types/plugin-hkt.js} +0 -0
  301. /package/dist/{query-v2/types/machine.types.js → query/types/resource.js} +0 -0
  302. /package/dist/{query-v2/types/plugin.types.js → query/types/state.js} +0 -0
@@ -1,154 +0,0 @@
1
- import { ReadableSignalLike } from "../../signals/types";
2
- import { ResourceDefinition, ResourceInstance } from "./Resource.types";
3
- import { FallbackOnNever, OnCacheEntryAdded, OnQueryStarted } from "./shared.types";
4
- /**
5
- * Функция создания команды
6
- */
7
- export type CommandCreateFn<ARGS, RESULT, SELECTED = never> = (options: CommandCreateOptions<CommandDefinition<ARGS, RESULT, SELECTED>>) => CommandInstance<CommandDefinition<ARGS, RESULT, SELECTED>>;
8
- /**
9
- * Опции создания команды
10
- */
11
- export type CommandCreateOptions<D extends CommandDefinition> = {
12
- /** Функция селектора для преобразования результата команды */
13
- select?: (data: D["Result"]) => D["Selected"];
14
- /** Функция выполнения команды */
15
- queryFn: (args: D["Args"]) => Promise<D["Result"]>;
16
- /** Связанные ресурсы */
17
- link?: (link: <RD extends ResourceDefinition>(options: LinkOptions<D, RD>) => void) => void;
18
- /**
19
- * Время жизни кеша в миллисекундах. По умолчанию 1_000 (1 секунда).
20
- * Если указано false - кеш не удаляется автоматически.
21
- */
22
- cacheLifetime?: number | false;
23
- /**
24
- * Хук, вызываемый при добавлении нового элемента в кеш.
25
- * Также позволяет отследить:
26
- * - когда данные были загружены (впервые)
27
- * - когда элемент был удален из кеша
28
- */
29
- onCacheEntryAdded?: OnCacheEntryAdded<D["Args"], D["Data"]>;
30
- /**
31
- * Хук, вызываемый при старте запроса.
32
- * Также позволяет отследить:
33
- * - завершение запроса с результатом или ошибкой
34
- */
35
- onQueryStarted?: OnQueryStarted<D["Args"], D["Result"]>;
36
- /**
37
- * Настройка отображения в devtools
38
- */
39
- devtoolsName?: string | false;
40
- };
41
- /**
42
- * Настройки связи команды с ресурсом
43
- */
44
- export type LinkOptions<D extends CommandDefinition, RD extends ResourceDefinition> = {
45
- /**
46
- * Целевой ресурс, с которым связывается команда
47
- * @required
48
- */
49
- resource: ResourceInstance<RD>;
50
- /**
51
- * Функция для получения аргументов ресурса из аргументов команды.
52
- * Используется для определения какой именно элемент в кэше ресурса нужно обновить
53
- * @required
54
- */
55
- forwardArgs: (args: D["Args"]) => RD["Args"];
56
- /**
57
- * Флаг для инвалидации (очистки) кэша ресурса после выполнения команды.
58
- * При true - кэш будет очищен и ресурс будет перезагружен при следующем обращении
59
- * @optional @default false
60
- */
61
- invalidate?: boolean;
62
- /**
63
- * Флаг для блокировки ресурса во время выполнения команды.
64
- * При true - ресурс будет заблокирован и не сможет выполнять новые запросы
65
- * @optional @default false
66
- */
67
- lock?: boolean;
68
- /**
69
- * Функция для обновления кэша ресурса после успешного выполнения команды.
70
- * Получает draft объект для мутации, аргументы команды и результат команды
71
- * @optional
72
- */
73
- update?: (tools: {
74
- /** Immer draft объект для мутации кэша ресурса */
75
- draft: RD["Data"];
76
- /** Аргументы, с которыми была вызвана команда */
77
- args: D["Args"];
78
- /** Результат выполнения команды */
79
- data: D["Data"];
80
- }) => void | RD["Data"] | Promise<RD["Data"]>;
81
- /**
82
- * Функция для оптимистичного обновления кэша ресурса ДО выполнения команды.
83
- * Позволяет обновить UI немедленно, до получения ответа от сервера
84
- * @optional
85
- */
86
- optimisticUpdate?: (tools: {
87
- /** Immer draft объект для мутации кэша ресурса */
88
- draft: RD["Data"];
89
- /** Аргументы, с которыми была вызвана команда */
90
- args: D["Args"];
91
- }) => void | RD["Data"] | Promise<RD["Data"]>;
92
- /**
93
- * Функция для создания нового элемента в кэше ресурса.
94
- * Используется когда команда создает новую сущность, которую нужно добавить в кэш
95
- * @optional
96
- */
97
- create?: (tools: {
98
- /** Аргументы, с которыми была вызвана команда */
99
- args: D["Args"];
100
- /** Результат выполнения команды */
101
- data: D["Data"];
102
- }) => RD["Data"] | Promise<RD["Data"]>;
103
- };
104
- /**
105
- * Определение типов команды
106
- */
107
- export type CommandDefinition<A = any, R = any, S = any> = {
108
- Args: A;
109
- Result: R;
110
- Selected: S;
111
- Data: FallbackOnNever<S, R>;
112
- };
113
- /**
114
- * Экземпляр команды
115
- */
116
- export type CommandInstance<D extends CommandDefinition> = {
117
- /** Создает агента для выполнения команды */
118
- createAgent(): CommandAgentInstance<D>;
119
- /**
120
- * Выполняет команду с указанными аргументами
121
- * @deprecated
122
- */
123
- mutate: (args: D["Args"]) => Promise<D["Data"]>;
124
- };
125
- /**
126
- * Агент для выполнения команды
127
- */
128
- export type CommandAgentInstance<D extends CommandDefinition> = {
129
- /** Observable состояния выполнения команды */
130
- state$: ReadableSignalLike<CommandQueryState<D>>;
131
- /** Инициирует выполнение команды с указанными аргументами */
132
- initiate(args: D["Args"]): void;
133
- /** Создает новый агент команды */
134
- createAgent(): CommandAgentInstance<D>;
135
- };
136
- /**
137
- * Состояние выполнения команды
138
- */
139
- export type CommandQueryState<D extends CommandDefinition> = {
140
- /** Выполняется ли команда в данный момент */
141
- isLoading: boolean;
142
- /** Завершена ли команда */
143
- isDone: boolean;
144
- /** Успешно ли завершена команда (false по умолчанию) */
145
- isSuccess: boolean;
146
- /** Произошла ли ошибка при выполнении команды (false по умолчанию) */
147
- isError: boolean;
148
- /** Оригинал ошибки, если есть */
149
- error: unknown | undefined;
150
- /** Результат выполнения команды */
151
- data: D["Data"] | undefined;
152
- /** Аргументы команды */
153
- args: D["Args"];
154
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,13 +0,0 @@
1
- import { CommandAgentInstance, CommandCreateFn, CommandCreateOptions, CommandDefinition, CommandInstance, CommandQueryState } from "./Command.types";
2
- /** @deprecated Use `CommandCreateFn` instead. Will be removed in v0.6.0. */
3
- export type OperationCreateFn<ARGS, RESULT, SELECTED = never> = CommandCreateFn<ARGS, RESULT, SELECTED>;
4
- /** @deprecated Use `CommandCreateOptions` instead. Will be removed in v0.6.0. */
5
- export type OperationCreateOptions<D extends CommandDefinition> = CommandCreateOptions<D>;
6
- /** @deprecated Use `CommandDefinition` instead. Will be removed in v0.6.0. */
7
- export type OperationDefinition<A = any, R = any, S = any> = CommandDefinition<A, R, S>;
8
- /** @deprecated Use `CommandInstance` instead. Will be removed in v0.6.0. */
9
- export type OperationInstance<D extends CommandDefinition> = CommandInstance<D>;
10
- /** @deprecated Use `CommandAgentInstance` instead. Will be removed in v0.6.0. */
11
- export type OperationAgentInstanse<D extends CommandDefinition> = CommandAgentInstance<D>;
12
- /** @deprecated Use `CommandQueryState` instead. Will be removed in v0.6.0. */
13
- export type OperationQueryState<D extends CommandDefinition> = CommandQueryState<D>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,129 +0,0 @@
1
- import { Patch as ImmerPatch } from "immer";
2
- import { ReadableSignalLike } from "../../signals/types";
3
- import { FallbackOnNever, OnCacheEntryAdded, OnQueryStarted } from "./shared.types";
4
- /**
5
- * Функция создания ресурса
6
- */
7
- export type ResourceCreateFn<ARGS, RESULT, SELECTED = never> = (options: ResourceCreateOptions<ResourceDefinition<ARGS, RESULT, SELECTED>>) => ResourceInstance<ResourceDefinition<ARGS, RESULT, SELECTED>>;
8
- /**
9
- * Опции создания ресурса
10
- */
11
- export type ResourceCreateOptions<D extends ResourceDefinition> = {
12
- /** Функция селектора для преобразования данных */
13
- select?: (data: D["Result"]) => D["Selected"];
14
- /** Функция запроса данных */
15
- queryFn: (args: D["Args"], tools: ResourceQueryFnTools) => Promise<D["Result"]>;
16
- /**
17
- * Время жизни кеша в миллисекундах. По умолчанию 60_000 (1 минута).
18
- * Если указано false - кеш не удаляется автоматически.
19
- */
20
- cacheLifetime?: number | false;
21
- /**
22
- * Хук, вызываемый при добавлении нового элемента в кеш.
23
- * Также позволяет отследить:
24
- * - когда данные были загружены (впервые)
25
- * - когда элемент был удален из кеша
26
- */
27
- onCacheEntryAdded?: OnCacheEntryAdded<D["Args"], D["Data"]>;
28
- /**
29
- * Хук, вызываемый при старте запроса.
30
- * Также позволяет отследить:
31
- * - завершение запроса с результатом или ошибкой
32
- */
33
- onQueryStarted?: OnQueryStarted<D["Args"], D["Result"]>;
34
- /**
35
- * Настройка отображения в devtools
36
- */
37
- devtoolsName?: string | false;
38
- /**
39
- * Сравнение аргументов между собой
40
- */
41
- compareArgsFn?: (args1: D["Args"], args2: D["Args"]) => boolean;
42
- };
43
- /**
44
- * Определение типов ресурса
45
- */
46
- export type ResourceDefinition<A = any, R = any, S = any> = {
47
- Args: A;
48
- Result: R;
49
- Selected: S;
50
- Data: FallbackOnNever<S, R>;
51
- };
52
- /** Инструменты для функции запроса */
53
- export type ResourceQueryFnTools = {
54
- /** Сигнал для отмены запроса */
55
- abortSignal?: AbortSignal;
56
- };
57
- /**
58
- * Экземпляр ресурса
59
- */
60
- export type ResourceInstance<D extends ResourceDefinition> = {
61
- /** Создает агента для работы с ресурсом */
62
- createAgent(): ResourceAgentInstance<D>;
63
- /** Создает ссылку на ресурс с указанными аргументами */
64
- createRef(args: D["Args"]): ResourceRefInstance<D>;
65
- };
66
- /**
67
- * Агент для работы с ресурсом
68
- */
69
- export type ResourceAgentInstance<D extends ResourceDefinition> = {
70
- /** Observable состояния запроса */
71
- state$: ReadableSignalLike<ResourceQueryState<D>>;
72
- /** Инициирует запрос с указанными аргументами */
73
- initiate(args: D["Args"], force?: boolean): void;
74
- /** Сравнивает аргументы между собой */
75
- compareArgs(args1: D["Args"], args2: D["Args"]): boolean;
76
- };
77
- /**
78
- * Состояние запроса ресурса
79
- */
80
- export type ResourceQueryState<D extends ResourceDefinition> = {
81
- /** Инициализирован ли хотя бы один запрос */
82
- isInitiated: boolean;
83
- /** Загрузка */
84
- isLoading: boolean;
85
- /** Первая загрузка */
86
- isInitialLoading: boolean;
87
- /** Завершен ли запрос */
88
- isDone: boolean;
89
- /** Успешно ли завершен последний запрос (false по умолчанию) */
90
- isSuccess: boolean;
91
- /** Произошла ли ошибка последнего запроса (false по умолчанию) */
92
- isError: boolean;
93
- /** Заблокирован ли ресурс */
94
- isLocked: boolean;
95
- /** Перезагружается ли ресурс */
96
- isReloading: boolean;
97
- /** Оригинал ошибки, если есть */
98
- error: unknown | undefined;
99
- /** Данные, полученные в результате запроса (или select данных) */
100
- data: D["Data"] | undefined;
101
- /** Аргументы запроса */
102
- args: D["Args"] | undefined;
103
- };
104
- /**
105
- * Транзакция ресурса
106
- */
107
- export type ResourceTransaction = {
108
- patches: ImmerPatch[];
109
- inversePatches: ImmerPatch[];
110
- status: "pending" | "committed" | "aborted";
111
- abort(): void;
112
- commit(): void;
113
- };
114
- /**
115
- * Эте не ссылка в "классическом" понимании, а абстракция
116
- * для работы с элементом кеша ресурса.
117
- */
118
- export type ResourceRefInstance<D extends ResourceDefinition> = {
119
- get has(): boolean;
120
- lock(): {
121
- unlock: () => void;
122
- };
123
- unlockOne(): void;
124
- patch(patchFn: (data: D["Data"]) => void): ResourceTransaction | null;
125
- invalidate(): void;
126
- create(data: D["Data"]): void;
127
- };
128
- /** @deprecated Use ResourceRefInstance. Will be removed in v0.6.0 */
129
- export type ResourceRefInstanse<D extends ResourceDefinition> = ResourceRefInstance<D>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,26 +0,0 @@
1
- import { Subject } from "rxjs";
2
- export type Prettify<T> = {
3
- [KeyType in keyof T]: T[KeyType];
4
- } & {};
5
- export type FallbackOnNever<T, F> = [T] extends [never] ? F : T;
6
- export type CacheEntryAddedTools<DATA> = {
7
- /** Функция для ожидания загрузки данных в кеш */
8
- $cacheDataLoaded: Promise<void>;
9
- /** Функция для ожидания удаления кеша */
10
- $cacheEntryRemoved: Promise<void>;
11
- dataChanged$: Subject<DATA>;
12
- };
13
- export type QueryStartedTools<DATA> = {
14
- /** Функция для уведомления об успешном завершении запроса */
15
- $queryFulfilled: Promise<{
16
- data: DATA;
17
- error: undefined;
18
- isError: false;
19
- } | {
20
- data: undefined;
21
- error: unknown;
22
- isError: true;
23
- }>;
24
- };
25
- export type OnCacheEntryAdded<ARGS, DATA> = (args: ARGS, tools: CacheEntryAddedTools<DATA>) => void;
26
- export type OnQueryStarted<ARGS, DATA> = (args: ARGS, tools: QueryStartedTools<DATA>) => void;
@@ -1 +0,0 @@
1
- export {};
@@ -1,10 +0,0 @@
1
- import type { IApi, ICreateApiOptions } from "../../query-v2/types/api.types";
2
- import type { IPlugin } from "../../query-v2/types/plugin.types";
3
- /**
4
- * Create a query-v2 API instance — the root entry point for managing resources, snapshots, and plugins.
5
- *
6
- * @param options - Configuration for the API instance (keyPrefix, plugins, snapshot, cache settings).
7
- * @returns API instance with `createResource`, `resetAll`, and `getSnapshot` methods.
8
- * @see docs/query-v2/README.md
9
- */
10
- export declare function createApi<TPlugins extends IPlugin[] = []>(options?: ICreateApiOptions<TPlugins>): IApi<TPlugins>;
@@ -1,83 +0,0 @@
1
- import { ResourceV2 } from "../../query-v2/core/resource/ResourceV2";
2
- import { getSnapshot, hydrateSnapshot } from "../../query-v2/snapshot/Snapshot";
3
- const DEFAULT_CACHE_LIFETIME = 60_000;
4
- const DEFAULT_MAX_SNAPSHOT_DATA_AGE = 300_000; // 5 minutes
5
- /**
6
- * Create a query-v2 API instance — the root entry point for managing resources, snapshots, and plugins.
7
- *
8
- * @param options - Configuration for the API instance (keyPrefix, plugins, snapshot, cache settings).
9
- * @returns API instance with `createResource`, `resetAll`, and `getSnapshot` methods.
10
- * @see docs/query-v2/README.md
11
- */
12
- export function createApi(options = {}) {
13
- const { keyPrefix = null, keyStrategy = "serialize", serializeArgs, compareArg, initialSnapshot = null, cacheLifetime = DEFAULT_CACHE_LIFETIME, plugins = [], maxSnapshotDataAge = DEFAULT_MAX_SNAPSHOT_DATA_AGE, doCacheArgs = false, } = options;
14
- // ADR-6: Generic registry (Map, not typed to resources only)
15
- const registry = new Map();
16
- // Plugin initialization: call install() once per plugin
17
- const pluginContext = {
18
- get api() {
19
- return api;
20
- },
21
- keyStrategy,
22
- };
23
- for (const plugin of plugins) {
24
- plugin.install(pluginContext);
25
- }
26
- const api = {
27
- createResource(resourceOptions) {
28
- // Merge: resource options override API defaults
29
- const mergedConfig = {
30
- key: resourceOptions.key,
31
- keyPrefix: keyPrefix ?? undefined,
32
- keyStrategy,
33
- queryFn: resourceOptions.queryFn,
34
- onCacheEntryAdded: resourceOptions.onCacheEntryAdded,
35
- onQueryStarted: resourceOptions.onQueryStarted,
36
- serializeArgs: resourceOptions.serializeArgs ?? serializeArgs,
37
- compareArg: resourceOptions.compareArg ?? compareArg,
38
- cacheLifetime: resourceOptions.cacheLifetime ?? cacheLifetime,
39
- beforeDevtoolsPush: resourceOptions.beforeDevtoolsPush,
40
- maxSnapshotDataAge: resourceOptions.maxSnapshotDataAge ?? maxSnapshotDataAge,
41
- doCacheArgs: resourceOptions.doCacheArgs ?? doCacheArgs,
42
- };
43
- // Validate unique key (for serialize strategy, key is expected for snapshot)
44
- const resourceKey = mergedConfig.key;
45
- if (resourceKey != null) {
46
- if (registry.has(resourceKey)) {
47
- throw new Error(`Duplicate resource key "${resourceKey}". Each resource must have a unique key.`);
48
- }
49
- }
50
- // Create resource
51
- const resource = new ResourceV2(mergedConfig);
52
- // Apply plugin augmentations
53
- const augmentations = {};
54
- for (const plugin of plugins) {
55
- const pluginContributions = plugin.augmentResource(resource, resourceOptions);
56
- Object.assign(augmentations, pluginContributions);
57
- }
58
- // Create the augmented resource
59
- const augmentedResource = Object.assign(resource, augmentations);
60
- // Register resource
61
- if (resourceKey != null) {
62
- registry.set(resourceKey, resource);
63
- }
64
- // Hydrate from initial snapshot if available
65
- if (initialSnapshot && resourceKey != null) {
66
- const snapshotMaxAge = mergedConfig.maxSnapshotDataAge ?? maxSnapshotDataAge;
67
- const singleResourceRegistry = new Map();
68
- singleResourceRegistry.set(resourceKey, resource);
69
- hydrateSnapshot(initialSnapshot, singleResourceRegistry, keyPrefix, snapshotMaxAge);
70
- }
71
- return augmentedResource;
72
- },
73
- resetAll() {
74
- for (const [, resource] of registry) {
75
- resource.resetCache();
76
- }
77
- },
78
- getSnapshot() {
79
- return getSnapshot(registry, keyPrefix, keyStrategy);
80
- },
81
- };
82
- return api;
83
- }
@@ -1,29 +0,0 @@
1
- import type { TBeforeDevtoolsPushFn } from "../../../query-v2/types/shared.types";
2
- import type { TMachineInstance } from "../machines/Machine";
3
- export interface CacheEntryOptions {
4
- keyParts?: string[];
5
- beforeDevtoolsPush?: TBeforeDevtoolsPushFn<unknown>;
6
- }
7
- /**
8
- * Cache entry wrapping a reactive signal over a state machine instance.
9
- * Represents a single cached query result with its full lifecycle (idle → pending → success/error).
10
- */
11
- export declare class CacheEntry<TData = unknown, TError = Error> {
12
- private readonly _signal;
13
- private readonly _onClean$;
14
- private _completed;
15
- constructor(initialMachine: TMachineInstance<TData, TError>, options?: CacheEntryOptions);
16
- /** Reactive accessor for the current machine state — reading this registers a signal dependency. */
17
- get machine$(): () => TMachineInstance<TData, TError>;
18
- /** Non-reactive read of the current machine state (does not register a signal dependency). */
19
- peek(): TMachineInstance<TData, TError>;
20
- /** Transition to a new machine state. No-op if the entry has been completed. */
21
- set(machine: TMachineInstance<TData, TError>): void;
22
- get onClean$(): {
23
- subscribe: (cb: () => void) => {
24
- unsubscribe: () => void;
25
- };
26
- };
27
- /** Complete the entry — aborts pending patches, resets to idle, and notifies cleanup listeners. */
28
- complete(): void;
29
- }
@@ -1,71 +0,0 @@
1
- import { Subject } from "rxjs";
2
- import { Signal } from "../../../signals";
3
- import { MachineIdle } from "../machines/MachineIdle";
4
- import { MachineWithData } from "../machines/MachineWithData";
5
- /**
6
- * Cache entry wrapping a reactive signal over a state machine instance.
7
- * Represents a single cached query result with its full lifecycle (idle → pending → success/error).
8
- */
9
- export class CacheEntry {
10
- _signal;
11
- _onClean$ = new Subject();
12
- _completed = false;
13
- constructor(initialMachine, options) {
14
- const userCallback = options?.beforeDevtoolsPush;
15
- // Default beforeDevtoolsPush projects machine → machine.state for devtools (ADR-8).
16
- // The push function types are mismatched intentionally: we push plain state objects
17
- // instead of machine instances to keep devtools output JSON-friendly.
18
- const beforeDevtoolsPush = ((newValue, push) => {
19
- const machine = newValue;
20
- const state = machine.state;
21
- if (userCallback) {
22
- userCallback(state, push);
23
- }
24
- else {
25
- push(state);
26
- }
27
- });
28
- this._signal = Signal.state(initialMachine, {
29
- key: options?.keyParts?.join("/"),
30
- beforeDevtoolsPush,
31
- });
32
- }
33
- /** Reactive accessor for the current machine state — reading this registers a signal dependency. */
34
- get machine$() {
35
- return this._signal;
36
- }
37
- /** Non-reactive read of the current machine state (does not register a signal dependency). */
38
- peek() {
39
- return this._signal.peek();
40
- }
41
- /** Transition to a new machine state. No-op if the entry has been completed. */
42
- set(machine) {
43
- if (this._completed)
44
- return;
45
- this._signal.set(machine);
46
- }
47
- get onClean$() {
48
- return {
49
- subscribe: (cb) => {
50
- const sub = this._onClean$.subscribe(cb);
51
- return { unsubscribe: () => sub.unsubscribe() };
52
- },
53
- };
54
- }
55
- /** Complete the entry — aborts pending patches, resets to idle, and notifies cleanup listeners. */
56
- complete() {
57
- if (this._completed)
58
- return;
59
- this._completed = true;
60
- // Layer 3 (ADR-4): Abort all pending patches on MachineWithData instances
61
- const current = this._signal.peek();
62
- if (current instanceof MachineWithData) {
63
- current.abortAllPendingPatches();
64
- }
65
- // Set to idle to release data references
66
- this._signal.set(MachineIdle.create());
67
- // Notify cleanup listeners
68
- this._onClean$.next();
69
- this._onClean$.complete();
70
- }
71
- }
@@ -1,38 +0,0 @@
1
- import type { ICacheMapOptions } from "../../../query-v2/types/cache.types";
2
- import type { CacheEntry } from "./CacheEntry";
3
- declare class SerializedCacheMap<TArgs, TData, TError = Error> {
4
- private readonly _map;
5
- private readonly _serializeArgs;
6
- private readonly _argsMemo;
7
- constructor(serializeArgs: (args: unknown) => string, doCacheArgs: boolean);
8
- private _serialize;
9
- get(args: TArgs): CacheEntry<TData, TError> | undefined;
10
- set(args: TArgs, entry: CacheEntry<TData, TError>): void;
11
- getOrCreate(args: TArgs, factory: () => CacheEntry<TData, TError>): CacheEntry<TData, TError>;
12
- delete(args: TArgs): boolean;
13
- has(args: TArgs): boolean;
14
- values(): Iterable<CacheEntry<TData, TError>>;
15
- entries(): Iterable<[string, CacheEntry<TData, TError>]>;
16
- clear(): void;
17
- get size(): number;
18
- }
19
- declare class CompareCacheMap<TArgs, TData, TError = Error> {
20
- private readonly _items;
21
- private readonly _compareArg;
22
- constructor(compareArg: (a: unknown, b: unknown) => boolean);
23
- private _findIndex;
24
- get(args: TArgs): CacheEntry<TData, TError> | undefined;
25
- set(args: TArgs, entry: CacheEntry<TData, TError>): void;
26
- getOrCreate(args: TArgs, factory: () => CacheEntry<TData, TError>): CacheEntry<TData, TError>;
27
- delete(args: TArgs): boolean;
28
- has(args: TArgs): boolean;
29
- values(): Iterable<CacheEntry<TData, TError>>;
30
- entries(): Iterable<[TArgs, CacheEntry<TData, TError>]>;
31
- clear(): void;
32
- get size(): number;
33
- }
34
- export type TCacheMapInstance<TArgs, TData, TError = Error> = SerializedCacheMap<TArgs, TData, TError> | CompareCacheMap<TArgs, TData, TError>;
35
- export declare const CacheMap: {
36
- create<TArgs, TData, TError = Error>(options: ICacheMapOptions<TArgs>): TCacheMapInstance<TArgs, TData, TError>;
37
- };
38
- export {};