jazz-tools 0.14.27 → 0.15.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 (871) hide show
  1. package/.svelte-kit/__package__/Provider.svelte +61 -0
  2. package/.svelte-kit/__package__/Provider.svelte.d.ts +19 -0
  3. package/.svelte-kit/__package__/Provider.svelte.d.ts.map +1 -0
  4. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.d.ts +11 -0
  5. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.d.ts.map +1 -0
  6. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.js +20 -0
  7. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte +81 -0
  8. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte.d.ts +9 -0
  9. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte.d.ts.map +1 -0
  10. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.d.ts +12 -0
  11. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.d.ts.map +1 -0
  12. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.js +30 -0
  13. package/.svelte-kit/__package__/auth/index.d.ts +4 -0
  14. package/.svelte-kit/__package__/auth/index.d.ts.map +1 -0
  15. package/.svelte-kit/__package__/auth/index.js +3 -0
  16. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.d.ts +6 -0
  17. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.d.ts.map +1 -0
  18. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.js +22 -0
  19. package/.svelte-kit/__package__/index.d.ts +6 -0
  20. package/.svelte-kit/__package__/index.d.ts.map +1 -0
  21. package/.svelte-kit/__package__/index.js +5 -0
  22. package/.svelte-kit/__package__/jazz.class.svelte.d.ts +21 -0
  23. package/.svelte-kit/__package__/jazz.class.svelte.d.ts.map +1 -0
  24. package/.svelte-kit/__package__/jazz.class.svelte.js +117 -0
  25. package/.svelte-kit/__package__/jazz.svelte.d.ts +39 -0
  26. package/.svelte-kit/__package__/jazz.svelte.d.ts.map +1 -0
  27. package/.svelte-kit/__package__/jazz.svelte.js +70 -0
  28. package/.svelte-kit/__package__/testing.d.ts +10 -0
  29. package/.svelte-kit/__package__/testing.d.ts.map +1 -0
  30. package/.svelte-kit/__package__/testing.js +23 -0
  31. package/.turbo/turbo-build.log +180 -11
  32. package/CHANGELOG.md +21 -0
  33. package/README.md +2 -2
  34. package/dist/browser/BrowserContextManager.d.ts +31 -0
  35. package/dist/browser/BrowserContextManager.d.ts.map +1 -0
  36. package/dist/browser/auth/LocalStorageKVStore.d.ts +9 -0
  37. package/dist/browser/auth/LocalStorageKVStore.d.ts.map +1 -0
  38. package/dist/browser/auth/PasskeyAuth.d.ts +27 -0
  39. package/dist/browser/auth/PasskeyAuth.d.ts.map +1 -0
  40. package/dist/browser/createBrowserContext.d.ts +47 -0
  41. package/dist/browser/createBrowserContext.d.ts.map +1 -0
  42. package/dist/browser/index.d.ts +23 -0
  43. package/dist/browser/index.d.ts.map +1 -0
  44. package/dist/browser/index.js +469 -0
  45. package/dist/browser/index.js.map +1 -0
  46. package/dist/browser/storageOptions.d.ts +8 -0
  47. package/dist/browser/storageOptions.d.ts.map +1 -0
  48. package/dist/browser/tests/LocalStorageKVStore.test.d.ts +2 -0
  49. package/dist/browser/tests/LocalStorageKVStore.test.d.ts.map +1 -0
  50. package/dist/browser/tests/PasskeyAuth.test.d.ts +2 -0
  51. package/dist/browser/tests/PasskeyAuth.test.d.ts.map +1 -0
  52. package/dist/browser/tests/createInviteLink.test.d.ts +2 -0
  53. package/dist/browser/tests/createInviteLink.test.d.ts.map +1 -0
  54. package/dist/browser/tests/storageOptions.test.d.ts +2 -0
  55. package/dist/browser/tests/storageOptions.test.d.ts.map +1 -0
  56. package/dist/browser/tests/utils.d.ts +11 -0
  57. package/dist/browser/tests/utils.d.ts.map +1 -0
  58. package/dist/browser/utils/export-account-inspector.d.ts +6 -0
  59. package/dist/browser/utils/export-account-inspector.d.ts.map +1 -0
  60. package/dist/browser-media-images/index.d.ts +7 -0
  61. package/dist/browser-media-images/index.d.ts.map +1 -0
  62. package/dist/browser-media-images/index.js +70 -0
  63. package/dist/browser-media-images/index.js.map +1 -0
  64. package/dist/chunk-FSIM7N33.js +4827 -0
  65. package/dist/chunk-FSIM7N33.js.map +1 -0
  66. package/dist/expo/auth/clerk/index.d.ts +7 -0
  67. package/dist/expo/auth/clerk/index.d.ts.map +1 -0
  68. package/dist/expo/crypto.d.ts +2 -0
  69. package/dist/expo/crypto.d.ts.map +1 -0
  70. package/dist/expo/crypto.js +3 -0
  71. package/dist/expo/crypto.js.map +1 -0
  72. package/dist/expo/index.d.ts +6 -0
  73. package/dist/expo/index.d.ts.map +1 -0
  74. package/dist/expo/index.js +168 -0
  75. package/dist/expo/index.js.map +1 -0
  76. package/dist/expo/provider.d.ts +4 -0
  77. package/dist/expo/provider.d.ts.map +1 -0
  78. package/dist/expo/storage/expo-secure-store-adapter.d.ts +8 -0
  79. package/dist/expo/storage/expo-secure-store-adapter.d.ts.map +1 -0
  80. package/dist/expo/storage/expo-sqlite-adapter.d.ts +18 -0
  81. package/dist/expo/storage/expo-sqlite-adapter.d.ts.map +1 -0
  82. package/dist/expo/testing.d.ts +2 -0
  83. package/dist/expo/testing.d.ts.map +1 -0
  84. package/dist/expo/testing.js +3 -0
  85. package/dist/expo/testing.js.map +1 -0
  86. package/dist/index.d.ts +1 -2
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +172 -6
  89. package/dist/index.js.map +1 -1
  90. package/dist/inspector/custom-element-CWW72LEG.js +31971 -0
  91. package/dist/inspector/custom-element-CWW72LEG.js.map +1 -0
  92. package/dist/inspector/custom-element.d.ts +13 -0
  93. package/dist/inspector/custom-element.d.ts.map +1 -0
  94. package/dist/inspector/index.d.ts +12 -0
  95. package/dist/inspector/index.d.ts.map +1 -0
  96. package/dist/inspector/index.js +2027 -0
  97. package/dist/inspector/index.js.map +1 -0
  98. package/dist/inspector/register-custom-element.d.ts +2 -0
  99. package/dist/inspector/register-custom-element.d.ts.map +1 -0
  100. package/dist/inspector/register-custom-element.js +5 -0
  101. package/dist/inspector/register-custom-element.js.map +1 -0
  102. package/dist/inspector/ui/badge.d.ts +4 -0
  103. package/dist/inspector/ui/badge.d.ts.map +1 -0
  104. package/dist/inspector/ui/button.d.ts +9 -0
  105. package/dist/inspector/ui/button.d.ts.map +1 -0
  106. package/dist/inspector/ui/card.d.ts +10 -0
  107. package/dist/inspector/ui/card.d.ts.map +1 -0
  108. package/dist/inspector/ui/global-styles.d.ts +4 -0
  109. package/dist/inspector/ui/global-styles.d.ts.map +1 -0
  110. package/dist/inspector/ui/grid.d.ts +4 -0
  111. package/dist/inspector/ui/grid.d.ts.map +1 -0
  112. package/dist/inspector/ui/heading.d.ts +4 -0
  113. package/dist/inspector/ui/heading.d.ts.map +1 -0
  114. package/dist/inspector/ui/icon.d.ts +30 -0
  115. package/dist/inspector/ui/icon.d.ts.map +1 -0
  116. package/dist/inspector/ui/icons/chevron-down-icon.d.ts +2 -0
  117. package/dist/inspector/ui/icons/chevron-down-icon.d.ts.map +1 -0
  118. package/dist/inspector/ui/icons/delete-icon.d.ts +2 -0
  119. package/dist/inspector/ui/icons/delete-icon.d.ts.map +1 -0
  120. package/dist/inspector/ui/icons/link-icon.d.ts +2 -0
  121. package/dist/inspector/ui/icons/link-icon.d.ts.map +1 -0
  122. package/dist/inspector/ui/input.d.ts +11 -0
  123. package/dist/inspector/ui/input.d.ts.map +1 -0
  124. package/dist/inspector/ui/select.d.ts +5 -0
  125. package/dist/inspector/ui/select.d.ts.map +1 -0
  126. package/dist/inspector/ui/table.d.ts +8 -0
  127. package/dist/inspector/ui/table.d.ts.map +1 -0
  128. package/dist/inspector/ui/text.d.ts +10 -0
  129. package/dist/inspector/ui/text.d.ts.map +1 -0
  130. package/dist/inspector/viewer/account-or-group-text.d.ts +8 -0
  131. package/dist/inspector/viewer/account-or-group-text.d.ts.map +1 -0
  132. package/dist/inspector/viewer/account-view.d.ts +8 -0
  133. package/dist/inspector/viewer/account-view.d.ts.map +1 -0
  134. package/dist/inspector/viewer/breadcrumbs.d.ts +9 -0
  135. package/dist/inspector/viewer/breadcrumbs.d.ts.map +1 -0
  136. package/dist/inspector/viewer/co-stream-view.d.ts +18 -0
  137. package/dist/inspector/viewer/co-stream-view.d.ts.map +1 -0
  138. package/dist/inspector/viewer/grid-view.d.ts +9 -0
  139. package/dist/inspector/viewer/grid-view.d.ts.map +1 -0
  140. package/dist/inspector/viewer/group-view.d.ts +8 -0
  141. package/dist/inspector/viewer/group-view.d.ts.map +1 -0
  142. package/dist/inspector/viewer/inpsector-button.d.ts +6 -0
  143. package/dist/inspector/viewer/inpsector-button.d.ts.map +1 -0
  144. package/dist/inspector/viewer/new-app.d.ts +11 -0
  145. package/dist/inspector/viewer/new-app.d.ts.map +1 -0
  146. package/dist/inspector/viewer/page-stack.d.ts +15 -0
  147. package/dist/inspector/viewer/page-stack.d.ts.map +1 -0
  148. package/dist/inspector/viewer/page.d.ts +16 -0
  149. package/dist/inspector/viewer/page.d.ts.map +1 -0
  150. package/dist/inspector/viewer/raw-data-card.d.ts +5 -0
  151. package/dist/inspector/viewer/raw-data-card.d.ts.map +1 -0
  152. package/dist/inspector/viewer/role-display.d.ts +6 -0
  153. package/dist/inspector/viewer/role-display.d.ts.map +1 -0
  154. package/dist/inspector/viewer/table-viewer.d.ts +9 -0
  155. package/dist/inspector/viewer/table-viewer.d.ts.map +1 -0
  156. package/dist/inspector/viewer/type-icon.d.ts +11 -0
  157. package/dist/inspector/viewer/type-icon.d.ts.map +1 -0
  158. package/dist/inspector/viewer/types.d.ts +7 -0
  159. package/dist/inspector/viewer/types.d.ts.map +1 -0
  160. package/dist/inspector/viewer/use-page-path.d.ts +10 -0
  161. package/dist/inspector/viewer/use-page-path.d.ts.map +1 -0
  162. package/dist/inspector/viewer/use-resolve-covalue.d.ts +67 -0
  163. package/dist/inspector/viewer/use-resolve-covalue.d.ts.map +1 -0
  164. package/dist/inspector/viewer/value-renderer.d.ts +12 -0
  165. package/dist/inspector/viewer/value-renderer.d.ts.map +1 -0
  166. package/dist/prosemirror/index.d.ts +3 -0
  167. package/dist/prosemirror/index.d.ts.map +1 -0
  168. package/dist/prosemirror/index.js +2185 -0
  169. package/dist/prosemirror/index.js.map +1 -0
  170. package/dist/prosemirror/lib/converter.d.ts +33 -0
  171. package/dist/prosemirror/lib/converter.d.ts.map +1 -0
  172. package/dist/prosemirror/lib/plugin.d.ts +43 -0
  173. package/dist/prosemirror/lib/plugin.d.ts.map +1 -0
  174. package/dist/prosemirror/lib/sync.d.ts +35 -0
  175. package/dist/prosemirror/lib/sync.d.ts.map +1 -0
  176. package/dist/prosemirror/tests/plugin.test.d.ts +2 -0
  177. package/dist/prosemirror/tests/plugin.test.d.ts.map +1 -0
  178. package/dist/react/auth/Clerk.d.ts +7 -0
  179. package/dist/react/auth/Clerk.d.ts.map +1 -0
  180. package/dist/react/auth/DemoAuth.d.ts +5 -0
  181. package/dist/react/auth/DemoAuth.d.ts.map +1 -0
  182. package/dist/react/auth/PasskeyAuth.d.ts +24 -0
  183. package/dist/react/auth/PasskeyAuth.d.ts.map +1 -0
  184. package/dist/react/auth/PassphraseAuth.d.ts +6 -0
  185. package/dist/react/auth/PassphraseAuth.d.ts.map +1 -0
  186. package/dist/react/auth/auth.d.ts +6 -0
  187. package/dist/react/auth/auth.d.ts.map +1 -0
  188. package/dist/react/hooks.d.ts +9 -0
  189. package/dist/react/hooks.d.ts.map +1 -0
  190. package/dist/react/index.d.ts +8 -0
  191. package/dist/react/index.d.ts.map +1 -0
  192. package/dist/react/index.js +700 -0
  193. package/dist/react/index.js.map +1 -0
  194. package/dist/react/media.d.ts +24 -0
  195. package/dist/react/media.d.ts.map +1 -0
  196. package/dist/react/provider.d.ts +10 -0
  197. package/dist/react/provider.d.ts.map +1 -0
  198. package/dist/react/ssr.d.ts +4 -0
  199. package/dist/react/ssr.d.ts.map +1 -0
  200. package/dist/react/ssr.js +25 -0
  201. package/dist/react/ssr.js.map +1 -0
  202. package/dist/react/testing.d.ts +2 -0
  203. package/dist/react/testing.d.ts.map +1 -0
  204. package/dist/react/testing.js +5 -0
  205. package/dist/react/testing.js.map +1 -0
  206. package/dist/react/tests/testUtils.d.ts +14 -0
  207. package/dist/react/tests/testUtils.d.ts.map +1 -0
  208. package/dist/react/tests/useAcceptInvite.test.d.ts +2 -0
  209. package/dist/react/tests/useAcceptInvite.test.d.ts.map +1 -0
  210. package/dist/react-core/auth/DemoAuth.d.ts +17 -0
  211. package/dist/react-core/auth/DemoAuth.d.ts.map +1 -0
  212. package/dist/react-core/auth/PassphraseAuth.d.ts +21 -0
  213. package/dist/react-core/auth/PassphraseAuth.d.ts.map +1 -0
  214. package/dist/react-core/auth/index.d.ts +3 -0
  215. package/dist/react-core/auth/index.d.ts.map +1 -0
  216. package/dist/react-core/chunk-7DYMJ74I.js +12 -0
  217. package/dist/react-core/chunk-7DYMJ74I.js.map +1 -0
  218. package/dist/react-core/hooks.d.ts +17 -0
  219. package/dist/react-core/hooks.d.ts.map +1 -0
  220. package/dist/react-core/index.d.ts +4 -0
  221. package/dist/react-core/index.d.ts.map +1 -0
  222. package/dist/react-core/index.js +302 -0
  223. package/dist/react-core/index.js.map +1 -0
  224. package/dist/react-core/provider.d.ts +5 -0
  225. package/dist/react-core/provider.d.ts.map +1 -0
  226. package/dist/react-core/testing.d.ts +10 -0
  227. package/dist/react-core/testing.d.ts.map +1 -0
  228. package/dist/react-core/testing.js +43 -0
  229. package/dist/react-core/testing.js.map +1 -0
  230. package/dist/react-core/tests/fixtures.d.ts.map +1 -0
  231. package/dist/react-core/tests/testUtils.d.ts +15 -0
  232. package/dist/react-core/tests/testUtils.d.ts.map +1 -0
  233. package/dist/react-core/tests/useAccount.test.d.ts +2 -0
  234. package/dist/react-core/tests/useAccount.test.d.ts.map +1 -0
  235. package/dist/react-core/tests/useCoState.test.d.ts +2 -0
  236. package/dist/react-core/tests/useCoState.test.d.ts.map +1 -0
  237. package/dist/react-core/tests/useInboxSender.test.d.ts +2 -0
  238. package/dist/react-core/tests/useInboxSender.test.d.ts.map +1 -0
  239. package/dist/react-core/tests/useIsAuthenticated.test.d.ts +2 -0
  240. package/dist/react-core/tests/useIsAuthenticated.test.d.ts.map +1 -0
  241. package/dist/react-core/tests/usePassPhraseAuth.test.d.ts +2 -0
  242. package/dist/react-core/tests/usePassPhraseAuth.test.d.ts.map +1 -0
  243. package/dist/react-core/utils.d.ts +4 -0
  244. package/dist/react-core/utils.d.ts.map +1 -0
  245. package/dist/react-native/crypto.d.ts +2 -0
  246. package/dist/react-native/crypto.d.ts.map +1 -0
  247. package/dist/react-native/crypto.js +3 -0
  248. package/dist/react-native/crypto.js.map +1 -0
  249. package/dist/react-native/index.d.ts +5 -0
  250. package/dist/react-native/index.d.ts.map +1 -0
  251. package/dist/react-native/index.js +103 -0
  252. package/dist/react-native/index.js.map +1 -0
  253. package/dist/react-native/provider.d.ts +4 -0
  254. package/dist/react-native/provider.d.ts.map +1 -0
  255. package/dist/react-native/storage/mmkv-store-adapter.d.ts +8 -0
  256. package/dist/react-native/storage/mmkv-store-adapter.d.ts.map +1 -0
  257. package/dist/react-native/storage/op-sqlite-adapter.d.ts +13 -0
  258. package/dist/react-native/storage/op-sqlite-adapter.d.ts.map +1 -0
  259. package/dist/react-native/testing.d.ts +2 -0
  260. package/dist/react-native/testing.d.ts.map +1 -0
  261. package/dist/react-native/testing.js +3 -0
  262. package/dist/react-native/testing.js.map +1 -0
  263. package/dist/react-native-core/ReactNativeContextManager.d.ts +31 -0
  264. package/dist/react-native-core/ReactNativeContextManager.d.ts.map +1 -0
  265. package/dist/react-native-core/auth/DemoAuthUI.d.ts +8 -0
  266. package/dist/react-native-core/auth/DemoAuthUI.d.ts.map +1 -0
  267. package/dist/react-native-core/auth/auth.d.ts +3 -0
  268. package/dist/react-native-core/auth/auth.d.ts.map +1 -0
  269. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts +15 -0
  270. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts.map +1 -0
  271. package/dist/react-native-core/crypto/index.d.ts +2 -0
  272. package/dist/react-native-core/crypto/index.d.ts.map +1 -0
  273. package/dist/react-native-core/crypto.js +65 -0
  274. package/dist/react-native-core/crypto.js.map +1 -0
  275. package/dist/react-native-core/hooks.d.ts +8 -0
  276. package/dist/react-native-core/hooks.d.ts.map +1 -0
  277. package/dist/react-native-core/index.d.ts +9 -0
  278. package/dist/react-native-core/index.d.ts.map +1 -0
  279. package/dist/react-native-core/index.js +669 -0
  280. package/dist/react-native-core/index.js.map +1 -0
  281. package/dist/react-native-core/media.d.ts +24 -0
  282. package/dist/react-native-core/media.d.ts.map +1 -0
  283. package/dist/react-native-core/platform.d.ts +45 -0
  284. package/dist/react-native-core/platform.d.ts.map +1 -0
  285. package/dist/react-native-core/provider.d.ts +10 -0
  286. package/dist/react-native-core/provider.d.ts.map +1 -0
  287. package/dist/react-native-core/storage/kv-store-context.d.ts +17 -0
  288. package/dist/react-native-core/storage/kv-store-context.d.ts.map +1 -0
  289. package/dist/react-native-core/storage/sqlite-react-native.d.ts +9 -0
  290. package/dist/react-native-core/storage/sqlite-react-native.d.ts.map +1 -0
  291. package/dist/react-native-core/testing.js +3 -0
  292. package/dist/react-native-core/testing.js.map +1 -0
  293. package/dist/react-native-media-images/index.d.ts +7 -0
  294. package/dist/react-native-media-images/index.d.ts.map +1 -0
  295. package/dist/react-native-media-images/index.js +177 -0
  296. package/dist/react-native-media-images/index.js.map +1 -0
  297. package/dist/svelte/Provider.svelte +61 -0
  298. package/dist/svelte/Provider.svelte.d.ts +19 -0
  299. package/dist/svelte/Provider.svelte.d.ts.map +1 -0
  300. package/dist/svelte/auth/PasskeyAuth.svelte.d.ts +11 -0
  301. package/dist/svelte/auth/PasskeyAuth.svelte.d.ts.map +1 -0
  302. package/dist/svelte/auth/PasskeyAuth.svelte.js +20 -0
  303. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte +81 -0
  304. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte.d.ts +9 -0
  305. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte.d.ts.map +1 -0
  306. package/dist/svelte/auth/PassphraseAuth.svelte.d.ts +12 -0
  307. package/dist/svelte/auth/PassphraseAuth.svelte.d.ts.map +1 -0
  308. package/dist/svelte/auth/PassphraseAuth.svelte.js +30 -0
  309. package/dist/svelte/auth/index.d.ts +4 -0
  310. package/dist/svelte/auth/index.d.ts.map +1 -0
  311. package/dist/svelte/auth/index.js +3 -0
  312. package/dist/svelte/auth/useIsAuthenticated.svelte.d.ts +6 -0
  313. package/dist/svelte/auth/useIsAuthenticated.svelte.d.ts.map +1 -0
  314. package/dist/svelte/auth/useIsAuthenticated.svelte.js +22 -0
  315. package/dist/svelte/index.d.ts +6 -0
  316. package/dist/svelte/index.d.ts.map +1 -0
  317. package/dist/svelte/index.js +5 -0
  318. package/dist/svelte/jazz.class.svelte.d.ts +21 -0
  319. package/dist/svelte/jazz.class.svelte.d.ts.map +1 -0
  320. package/dist/svelte/jazz.class.svelte.js +117 -0
  321. package/dist/svelte/jazz.svelte.d.ts +39 -0
  322. package/dist/svelte/jazz.svelte.d.ts.map +1 -0
  323. package/dist/svelte/jazz.svelte.js +70 -0
  324. package/dist/svelte/testing.d.ts +10 -0
  325. package/dist/svelte/testing.d.ts.map +1 -0
  326. package/dist/svelte/testing.js +23 -0
  327. package/dist/testing.d.ts +1 -42
  328. package/dist/testing.d.ts.map +1 -1
  329. package/dist/testing.js +2 -2
  330. package/dist/testing.js.map +1 -1
  331. package/dist/tiptap/index.d.ts +11 -0
  332. package/dist/tiptap/index.d.ts.map +1 -0
  333. package/dist/tiptap/index.js +22 -0
  334. package/dist/tiptap/index.js.map +1 -0
  335. package/dist/tools/auth/AuthSecretStorage.d.ts.map +1 -0
  336. package/dist/tools/auth/DemoAuth.d.ts.map +1 -0
  337. package/dist/tools/auth/InMemoryKVStore.d.ts.map +1 -0
  338. package/dist/tools/auth/KvStoreContext.d.ts.map +1 -0
  339. package/dist/tools/auth/PassphraseAuth.d.ts.map +1 -0
  340. package/dist/tools/auth/clerk/getClerkUsername.d.ts +3 -0
  341. package/dist/tools/auth/clerk/getClerkUsername.d.ts.map +1 -0
  342. package/dist/tools/auth/clerk/index.d.ts +25 -0
  343. package/dist/tools/auth/clerk/index.d.ts.map +1 -0
  344. package/dist/tools/auth/clerk/tests/JazzClerkAuth.test.d.ts +2 -0
  345. package/dist/tools/auth/clerk/tests/JazzClerkAuth.test.d.ts.map +1 -0
  346. package/dist/tools/auth/clerk/tests/getClerkUsername.test.d.ts +2 -0
  347. package/dist/tools/auth/clerk/tests/getClerkUsername.test.d.ts.map +1 -0
  348. package/dist/tools/auth/clerk/tests/types.test.d.ts +2 -0
  349. package/dist/tools/auth/clerk/tests/types.test.d.ts.map +1 -0
  350. package/dist/tools/auth/clerk/types.d.ts +32 -0
  351. package/dist/tools/auth/clerk/types.d.ts.map +1 -0
  352. package/dist/tools/coValues/CoValueBase.d.ts.map +1 -0
  353. package/dist/tools/coValues/account.d.ts.map +1 -0
  354. package/dist/tools/coValues/coFeed.d.ts +368 -0
  355. package/dist/tools/coValues/coFeed.d.ts.map +1 -0
  356. package/dist/tools/coValues/coList.d.ts.map +1 -0
  357. package/dist/tools/coValues/coMap.d.ts.map +1 -0
  358. package/dist/tools/coValues/coPlainText.d.ts.map +1 -0
  359. package/dist/tools/coValues/coRichText.d.ts.map +1 -0
  360. package/dist/tools/coValues/deepLoading.d.ts.map +1 -0
  361. package/dist/tools/coValues/extensions/imageDef.d.ts.map +1 -0
  362. package/dist/tools/coValues/group.d.ts.map +1 -0
  363. package/dist/tools/coValues/inbox.d.ts.map +1 -0
  364. package/dist/tools/coValues/interfaces.d.ts.map +1 -0
  365. package/dist/tools/coValues/profile.d.ts.map +1 -0
  366. package/dist/tools/coValues/registeredSchemas.d.ts.map +1 -0
  367. package/dist/tools/coValues/schemaUnion.d.ts.map +1 -0
  368. package/dist/tools/exports.d.ts +24 -0
  369. package/dist/tools/exports.d.ts.map +1 -0
  370. package/dist/tools/implementation/ContextManager.d.ts.map +1 -0
  371. package/dist/tools/implementation/activeAccountContext.d.ts.map +1 -0
  372. package/dist/tools/implementation/anonymousJazzAgent.d.ts.map +1 -0
  373. package/dist/tools/implementation/createContext.d.ts.map +1 -0
  374. package/dist/tools/implementation/devtoolsFormatters.d.ts.map +1 -0
  375. package/dist/tools/implementation/errors.d.ts.map +1 -0
  376. package/dist/tools/implementation/inspect.d.ts.map +1 -0
  377. package/dist/tools/implementation/invites.d.ts.map +1 -0
  378. package/dist/tools/implementation/refs.d.ts.map +1 -0
  379. package/dist/tools/implementation/schema.d.ts.map +1 -0
  380. package/dist/tools/implementation/symbols.d.ts.map +1 -0
  381. package/dist/tools/implementation/zodSchema/coExport.d.ts.map +1 -0
  382. package/dist/tools/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts.map +1 -0
  383. package/dist/tools/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts.map +1 -0
  384. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +1 -0
  385. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +1 -0
  386. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +1 -0
  387. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +1 -0
  388. package/dist/tools/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts.map +1 -0
  389. package/dist/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts.map +1 -0
  390. package/dist/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts.map +1 -0
  391. package/dist/tools/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts.map +1 -0
  392. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts.map +1 -0
  393. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts.map +1 -0
  394. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts.map +1 -0
  395. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts.map +1 -0
  396. package/dist/tools/implementation/zodSchema/unionUtils.d.ts.map +1 -0
  397. package/dist/tools/implementation/zodSchema/zodCo.d.ts.map +1 -0
  398. package/dist/tools/implementation/zodSchema/zodReExport.d.ts.map +1 -0
  399. package/dist/tools/implementation/zodSchema/zodSchema.d.ts.map +1 -0
  400. package/dist/tools/index.d.ts +3 -0
  401. package/dist/tools/index.d.ts.map +1 -0
  402. package/dist/tools/internal.d.ts.map +1 -0
  403. package/dist/tools/lib/cache.d.ts.map +1 -0
  404. package/dist/tools/lib/cache.test.d.ts.map +1 -0
  405. package/dist/tools/lib/migration.d.ts.map +1 -0
  406. package/dist/tools/subscribe/CoValueCoreSubscription.d.ts.map +1 -0
  407. package/dist/tools/subscribe/JazzError.d.ts.map +1 -0
  408. package/dist/tools/subscribe/SubscriptionScope.d.ts.map +1 -0
  409. package/dist/tools/subscribe/index.d.ts.map +1 -0
  410. package/dist/tools/subscribe/types.d.ts.map +1 -0
  411. package/dist/tools/subscribe/utils.d.ts.map +1 -0
  412. package/dist/tools/testing.d.ts +43 -0
  413. package/dist/tools/testing.d.ts.map +1 -0
  414. package/dist/tools/tests/AuthSecretStorage.test.d.ts.map +1 -0
  415. package/dist/tools/tests/ContextManager.test.d.ts.map +1 -0
  416. package/dist/tools/tests/DemoAuth.test.d.ts.map +1 -0
  417. package/dist/tools/tests/PassphraseAuth.test.d.ts.map +1 -0
  418. package/dist/tools/tests/account.test.d.ts.map +1 -0
  419. package/dist/tools/tests/coFeed.test-d.d.ts.map +1 -0
  420. package/dist/tools/tests/coFeed.test.d.ts.map +1 -0
  421. package/dist/tools/tests/coList.test-d.d.ts.map +1 -0
  422. package/dist/tools/tests/coList.test.d.ts.map +1 -0
  423. package/dist/tools/tests/coMap.record.test-d.d.ts.map +1 -0
  424. package/dist/tools/tests/coMap.record.test.d.ts.map +1 -0
  425. package/dist/tools/tests/coMap.test-d.d.ts.map +1 -0
  426. package/dist/tools/tests/coMap.test.d.ts.map +1 -0
  427. package/dist/tools/tests/coPlainText.test.d.ts.map +1 -0
  428. package/dist/tools/tests/createContext.test.d.ts.map +1 -0
  429. package/dist/tools/tests/deepLoading.test.d.ts.map +1 -0
  430. package/dist/tools/tests/fixtures.d.ts +2 -0
  431. package/dist/tools/tests/fixtures.d.ts.map +1 -0
  432. package/dist/tools/tests/groupsAndAccounts.test.d.ts.map +1 -0
  433. package/dist/tools/tests/imageDef.test.d.ts.map +1 -0
  434. package/dist/tools/tests/inbox.test.d.ts.map +1 -0
  435. package/dist/tools/tests/interfaces.test.d.ts.map +1 -0
  436. package/dist/tools/tests/invites.test.d.ts.map +1 -0
  437. package/dist/tools/tests/load.test.d.ts.map +1 -0
  438. package/dist/tools/tests/patterns/notifications.test.d.ts.map +1 -0
  439. package/dist/tools/tests/patterns/requestToJoin.test.d.ts.map +1 -0
  440. package/dist/tools/tests/schema.test.d.ts.map +1 -0
  441. package/dist/tools/tests/schemaUnion.test.d.ts.map +1 -0
  442. package/dist/tools/tests/subscribe.test.d.ts.map +1 -0
  443. package/dist/tools/tests/testing.test.d.ts.map +1 -0
  444. package/dist/tools/tests/utils.d.ts.map +1 -0
  445. package/dist/tools/tests/zod.test.d.ts.map +1 -0
  446. package/dist/tools/types.d.ts.map +1 -0
  447. package/dist/worker/index.d.ts +25 -0
  448. package/dist/worker/index.d.ts.map +1 -0
  449. package/dist/worker/index.js +93 -0
  450. package/dist/worker/index.js.map +1 -0
  451. package/package.json +193 -11
  452. package/src/browser/BrowserContextManager.ts +85 -0
  453. package/src/browser/auth/LocalStorageKVStore.ts +21 -0
  454. package/src/browser/auth/PasskeyAuth.ts +175 -0
  455. package/src/browser/createBrowserContext.ts +326 -0
  456. package/src/browser/index.ts +72 -0
  457. package/src/browser/storageOptions.ts +17 -0
  458. package/src/browser/tests/LocalStorageKVStore.test.ts +67 -0
  459. package/src/browser/tests/PasskeyAuth.test.ts +242 -0
  460. package/src/browser/tests/createInviteLink.test.ts +18 -0
  461. package/src/browser/tests/storageOptions.test.ts +33 -0
  462. package/src/browser/tests/utils.ts +93 -0
  463. package/src/browser/utils/export-account-inspector.ts +58 -0
  464. package/src/browser-media-images/index.ts +130 -0
  465. package/src/expo/auth/clerk/README.md +44 -0
  466. package/src/expo/auth/clerk/index.tsx +80 -0
  467. package/src/expo/crypto.ts +1 -0
  468. package/src/expo/index.ts +6 -0
  469. package/src/expo/provider.tsx +29 -0
  470. package/src/expo/storage/expo-secure-store-adapter.ts +29 -0
  471. package/src/expo/storage/expo-sqlite-adapter.ts +94 -0
  472. package/src/expo/testing.ts +1 -0
  473. package/src/index.ts +1 -3
  474. package/src/inspector/custom-element.tsx +63 -0
  475. package/src/inspector/index.ts +23 -0
  476. package/src/inspector/register-custom-element.ts +3 -0
  477. package/src/inspector/ui/badge.tsx +20 -0
  478. package/src/inspector/ui/button.tsx +81 -0
  479. package/src/inspector/ui/card.tsx +23 -0
  480. package/src/inspector/ui/global-styles.tsx +74 -0
  481. package/src/inspector/ui/grid.tsx +48 -0
  482. package/src/inspector/ui/heading.tsx +15 -0
  483. package/src/inspector/ui/icon.tsx +71 -0
  484. package/src/inspector/ui/icons/chevron-down-icon.tsx +16 -0
  485. package/src/inspector/ui/icons/delete-icon.tsx +19 -0
  486. package/src/inspector/ui/icons/link-icon.tsx +18 -0
  487. package/src/inspector/ui/input.tsx +51 -0
  488. package/src/inspector/ui/select.tsx +73 -0
  489. package/src/inspector/ui/table.tsx +90 -0
  490. package/src/inspector/ui/text.tsx +62 -0
  491. package/src/inspector/viewer/account-or-group-text.tsx +52 -0
  492. package/src/inspector/viewer/account-view.tsx +34 -0
  493. package/src/inspector/viewer/breadcrumbs.tsx +52 -0
  494. package/src/inspector/viewer/co-stream-view.tsx +374 -0
  495. package/src/inspector/viewer/grid-view.tsx +90 -0
  496. package/src/inspector/viewer/group-view.tsx +67 -0
  497. package/src/inspector/viewer/inpsector-button.tsx +89 -0
  498. package/src/inspector/viewer/new-app.tsx +171 -0
  499. package/src/inspector/viewer/page-stack.tsx +56 -0
  500. package/src/inspector/viewer/page.tsx +199 -0
  501. package/src/inspector/viewer/raw-data-card.tsx +53 -0
  502. package/src/inspector/viewer/role-display.tsx +28 -0
  503. package/src/inspector/viewer/table-viewer.tsx +184 -0
  504. package/src/inspector/viewer/type-icon.tsx +63 -0
  505. package/src/inspector/viewer/types.ts +11 -0
  506. package/src/inspector/viewer/use-page-path.ts +52 -0
  507. package/src/inspector/viewer/use-resolve-covalue.ts +214 -0
  508. package/src/inspector/viewer/value-renderer.tsx +266 -0
  509. package/src/prosemirror/index.ts +2 -0
  510. package/src/prosemirror/lib/converter.ts +50 -0
  511. package/src/prosemirror/lib/plugin.ts +120 -0
  512. package/src/prosemirror/lib/sync.ts +96 -0
  513. package/src/prosemirror/tests/plugin.test.ts +127 -0
  514. package/src/react/auth/Clerk.tsx +82 -0
  515. package/src/react/auth/DemoAuth.tsx +121 -0
  516. package/src/react/auth/PasskeyAuth.tsx +168 -0
  517. package/src/react/auth/PassphraseAuth.tsx +196 -0
  518. package/src/react/auth/auth.ts +9 -0
  519. package/src/react/hooks.tsx +53 -0
  520. package/src/react/index.ts +16 -0
  521. package/src/react/media.tsx +74 -0
  522. package/src/react/provider.tsx +114 -0
  523. package/src/react/scratch.tsx +50 -0
  524. package/src/react/ssr.ts +25 -0
  525. package/src/react/testing.tsx +1 -0
  526. package/src/react/tests/testUtils.tsx +54 -0
  527. package/src/react/tests/useAcceptInvite.test.ts +55 -0
  528. package/src/react-core/auth/DemoAuth.tsx +47 -0
  529. package/src/react-core/auth/PassphraseAuth.tsx +58 -0
  530. package/src/react-core/auth/index.ts +2 -0
  531. package/src/react-core/hooks.ts +310 -0
  532. package/src/react-core/index.ts +3 -0
  533. package/src/react-core/provider.tsx +11 -0
  534. package/src/react-core/testing.tsx +42 -0
  535. package/src/react-core/tests/testUtils.tsx +65 -0
  536. package/src/react-core/tests/useAccount.test.ts +238 -0
  537. package/src/react-core/tests/useCoState.test.ts +553 -0
  538. package/src/react-core/tests/useDemoAuth.test.tsx +84 -0
  539. package/src/react-core/tests/useInboxSender.test.ts +58 -0
  540. package/src/react-core/tests/useIsAuthenticated.test.ts +34 -0
  541. package/src/react-core/tests/usePassPhraseAuth.test.ts +180 -0
  542. package/src/react-core/utils.ts +28 -0
  543. package/src/react-native/crypto.ts +1 -0
  544. package/src/react-native/index.ts +5 -0
  545. package/src/react-native/provider.tsx +30 -0
  546. package/src/react-native/storage/mmkv-store-adapter.ts +24 -0
  547. package/src/react-native/storage/op-sqlite-adapter.ts +79 -0
  548. package/src/react-native/testing.ts +1 -0
  549. package/src/react-native-core/ReactNativeContextManager.ts +84 -0
  550. package/src/react-native-core/auth/DemoAuthUI.tsx +202 -0
  551. package/src/react-native-core/auth/auth.ts +14 -0
  552. package/src/react-native-core/crypto/RNQuickCrypto.ts +92 -0
  553. package/src/react-native-core/crypto/index.ts +1 -0
  554. package/src/react-native-core/hooks.tsx +64 -0
  555. package/src/react-native-core/index.ts +9 -0
  556. package/src/react-native-core/media.tsx +99 -0
  557. package/src/react-native-core/platform.ts +250 -0
  558. package/src/react-native-core/provider.tsx +115 -0
  559. package/src/react-native-core/storage/sqlite-react-native.ts +19 -0
  560. package/src/react-native-core/testing.tsx +1 -0
  561. package/src/react-native-media-images/index.ts +238 -0
  562. package/src/svelte/Provider.svelte +61 -0
  563. package/src/svelte/auth/PasskeyAuth.svelte.ts +42 -0
  564. package/src/svelte/auth/PasskeyAuthBasicUI.svelte +81 -0
  565. package/src/svelte/auth/PassphraseAuth.svelte.ts +49 -0
  566. package/src/svelte/auth/index.ts +3 -0
  567. package/src/svelte/auth/useIsAuthenticated.svelte.ts +28 -0
  568. package/src/svelte/index.ts +5 -0
  569. package/src/svelte/jazz.class.svelte.ts +172 -0
  570. package/src/svelte/jazz.svelte.ts +109 -0
  571. package/src/svelte/testing.ts +42 -0
  572. package/src/testing.ts +1 -312
  573. package/src/tiptap/index.ts +28 -0
  574. package/src/tools/auth/KvStoreContext.ts +39 -0
  575. package/src/tools/auth/clerk/getClerkUsername.ts +36 -0
  576. package/src/tools/auth/clerk/index.ts +174 -0
  577. package/src/tools/auth/clerk/tests/JazzClerkAuth.test.ts +284 -0
  578. package/src/tools/auth/clerk/tests/getClerkUsername.test.ts +81 -0
  579. package/src/tools/auth/clerk/tests/types.test.ts +49 -0
  580. package/src/tools/auth/clerk/types.ts +56 -0
  581. package/src/tools/coValues/coFeed.ts +943 -0
  582. package/src/tools/exports.ts +117 -0
  583. package/src/tools/index.ts +8 -0
  584. package/src/tools/testing.ts +301 -0
  585. package/src/tools/tests/coFeed.test.ts +771 -0
  586. package/src/tools/tests/fixtures.ts +2050 -0
  587. package/src/worker/index.ts +127 -0
  588. package/tsconfig.json +10 -3
  589. package/tsconfig.svelte.json +6 -0
  590. package/tsup.config.ts +143 -9
  591. package/dist/auth/AuthSecretStorage.d.ts.map +0 -1
  592. package/dist/auth/DemoAuth.d.ts.map +0 -1
  593. package/dist/auth/InMemoryKVStore.d.ts.map +0 -1
  594. package/dist/auth/KvStoreContext.d.ts.map +0 -1
  595. package/dist/auth/PassphraseAuth.d.ts.map +0 -1
  596. package/dist/chunk-G3QC4FAY.js +0 -4826
  597. package/dist/chunk-G3QC4FAY.js.map +0 -1
  598. package/dist/coValues/CoValueBase.d.ts.map +0 -1
  599. package/dist/coValues/account.d.ts.map +0 -1
  600. package/dist/coValues/coFeed.d.ts +0 -367
  601. package/dist/coValues/coFeed.d.ts.map +0 -1
  602. package/dist/coValues/coList.d.ts.map +0 -1
  603. package/dist/coValues/coMap.d.ts.map +0 -1
  604. package/dist/coValues/coPlainText.d.ts.map +0 -1
  605. package/dist/coValues/coRichText.d.ts.map +0 -1
  606. package/dist/coValues/deepLoading.d.ts.map +0 -1
  607. package/dist/coValues/extensions/imageDef.d.ts.map +0 -1
  608. package/dist/coValues/group.d.ts.map +0 -1
  609. package/dist/coValues/inbox.d.ts.map +0 -1
  610. package/dist/coValues/interfaces.d.ts.map +0 -1
  611. package/dist/coValues/profile.d.ts.map +0 -1
  612. package/dist/coValues/registeredSchemas.d.ts.map +0 -1
  613. package/dist/coValues/schemaUnion.d.ts.map +0 -1
  614. package/dist/exports.d.ts +0 -23
  615. package/dist/exports.d.ts.map +0 -1
  616. package/dist/implementation/ContextManager.d.ts.map +0 -1
  617. package/dist/implementation/activeAccountContext.d.ts.map +0 -1
  618. package/dist/implementation/anonymousJazzAgent.d.ts.map +0 -1
  619. package/dist/implementation/createContext.d.ts.map +0 -1
  620. package/dist/implementation/devtoolsFormatters.d.ts.map +0 -1
  621. package/dist/implementation/errors.d.ts.map +0 -1
  622. package/dist/implementation/inspect.d.ts.map +0 -1
  623. package/dist/implementation/invites.d.ts.map +0 -1
  624. package/dist/implementation/refs.d.ts.map +0 -1
  625. package/dist/implementation/schema.d.ts.map +0 -1
  626. package/dist/implementation/symbols.d.ts.map +0 -1
  627. package/dist/implementation/zodSchema/coExport.d.ts.map +0 -1
  628. package/dist/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts.map +0 -1
  629. package/dist/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts.map +0 -1
  630. package/dist/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +0 -1
  631. package/dist/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +0 -1
  632. package/dist/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +0 -1
  633. package/dist/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +0 -1
  634. package/dist/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts.map +0 -1
  635. package/dist/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts.map +0 -1
  636. package/dist/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts.map +0 -1
  637. package/dist/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts.map +0 -1
  638. package/dist/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts.map +0 -1
  639. package/dist/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts.map +0 -1
  640. package/dist/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts.map +0 -1
  641. package/dist/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts.map +0 -1
  642. package/dist/implementation/zodSchema/unionUtils.d.ts.map +0 -1
  643. package/dist/implementation/zodSchema/zodCo.d.ts.map +0 -1
  644. package/dist/implementation/zodSchema/zodReExport.d.ts.map +0 -1
  645. package/dist/implementation/zodSchema/zodSchema.d.ts.map +0 -1
  646. package/dist/internal.d.ts.map +0 -1
  647. package/dist/lib/cache.d.ts.map +0 -1
  648. package/dist/lib/cache.test.d.ts.map +0 -1
  649. package/dist/lib/migration.d.ts.map +0 -1
  650. package/dist/subscribe/CoValueCoreSubscription.d.ts.map +0 -1
  651. package/dist/subscribe/JazzError.d.ts.map +0 -1
  652. package/dist/subscribe/SubscriptionScope.d.ts.map +0 -1
  653. package/dist/subscribe/index.d.ts.map +0 -1
  654. package/dist/subscribe/types.d.ts.map +0 -1
  655. package/dist/subscribe/utils.d.ts.map +0 -1
  656. package/dist/tests/AuthSecretStorage.test.d.ts.map +0 -1
  657. package/dist/tests/ContextManager.test.d.ts.map +0 -1
  658. package/dist/tests/DemoAuth.test.d.ts.map +0 -1
  659. package/dist/tests/PassphraseAuth.test.d.ts.map +0 -1
  660. package/dist/tests/account.test.d.ts.map +0 -1
  661. package/dist/tests/coFeed.test-d.d.ts.map +0 -1
  662. package/dist/tests/coFeed.test.d.ts.map +0 -1
  663. package/dist/tests/coList.test-d.d.ts.map +0 -1
  664. package/dist/tests/coList.test.d.ts.map +0 -1
  665. package/dist/tests/coMap.record.test-d.d.ts.map +0 -1
  666. package/dist/tests/coMap.record.test.d.ts.map +0 -1
  667. package/dist/tests/coMap.test-d.d.ts.map +0 -1
  668. package/dist/tests/coMap.test.d.ts.map +0 -1
  669. package/dist/tests/coPlainText.test.d.ts.map +0 -1
  670. package/dist/tests/createContext.test.d.ts.map +0 -1
  671. package/dist/tests/deepLoading.test.d.ts.map +0 -1
  672. package/dist/tests/fixtures.d.ts.map +0 -1
  673. package/dist/tests/groupsAndAccounts.test.d.ts.map +0 -1
  674. package/dist/tests/imageDef.test.d.ts.map +0 -1
  675. package/dist/tests/inbox.test.d.ts.map +0 -1
  676. package/dist/tests/interfaces.test.d.ts.map +0 -1
  677. package/dist/tests/invites.test.d.ts.map +0 -1
  678. package/dist/tests/load.test.d.ts.map +0 -1
  679. package/dist/tests/patterns/notifications.test.d.ts.map +0 -1
  680. package/dist/tests/patterns/requestToJoin.test.d.ts.map +0 -1
  681. package/dist/tests/schema.test.d.ts.map +0 -1
  682. package/dist/tests/schemaUnion.test.d.ts.map +0 -1
  683. package/dist/tests/subscribe.test.d.ts.map +0 -1
  684. package/dist/tests/testing.test.d.ts.map +0 -1
  685. package/dist/tests/utils.d.ts.map +0 -1
  686. package/dist/tests/zod.test.d.ts.map +0 -1
  687. package/dist/types.d.ts.map +0 -1
  688. package/src/coValues/coFeed.ts +0 -938
  689. package/src/exports.ts +0 -108
  690. package/src/tests/coFeed.test.ts +0 -722
  691. /package/dist/{tests → react-core/tests}/fixtures.d.ts +0 -0
  692. /package/dist/{auth → tools/auth}/AuthSecretStorage.d.ts +0 -0
  693. /package/dist/{auth → tools/auth}/DemoAuth.d.ts +0 -0
  694. /package/dist/{auth → tools/auth}/InMemoryKVStore.d.ts +0 -0
  695. /package/dist/{auth → tools/auth}/KvStoreContext.d.ts +0 -0
  696. /package/dist/{auth → tools/auth}/PassphraseAuth.d.ts +0 -0
  697. /package/dist/{coValues → tools/coValues}/CoValueBase.d.ts +0 -0
  698. /package/dist/{coValues → tools/coValues}/account.d.ts +0 -0
  699. /package/dist/{coValues → tools/coValues}/coList.d.ts +0 -0
  700. /package/dist/{coValues → tools/coValues}/coMap.d.ts +0 -0
  701. /package/dist/{coValues → tools/coValues}/coPlainText.d.ts +0 -0
  702. /package/dist/{coValues → tools/coValues}/coRichText.d.ts +0 -0
  703. /package/dist/{coValues → tools/coValues}/deepLoading.d.ts +0 -0
  704. /package/dist/{coValues → tools/coValues}/extensions/imageDef.d.ts +0 -0
  705. /package/dist/{coValues → tools/coValues}/group.d.ts +0 -0
  706. /package/dist/{coValues → tools/coValues}/inbox.d.ts +0 -0
  707. /package/dist/{coValues → tools/coValues}/interfaces.d.ts +0 -0
  708. /package/dist/{coValues → tools/coValues}/profile.d.ts +0 -0
  709. /package/dist/{coValues → tools/coValues}/registeredSchemas.d.ts +0 -0
  710. /package/dist/{coValues → tools/coValues}/schemaUnion.d.ts +0 -0
  711. /package/dist/{implementation → tools/implementation}/ContextManager.d.ts +0 -0
  712. /package/dist/{implementation → tools/implementation}/activeAccountContext.d.ts +0 -0
  713. /package/dist/{implementation → tools/implementation}/anonymousJazzAgent.d.ts +0 -0
  714. /package/dist/{implementation → tools/implementation}/createContext.d.ts +0 -0
  715. /package/dist/{implementation → tools/implementation}/devtoolsFormatters.d.ts +0 -0
  716. /package/dist/{implementation → tools/implementation}/errors.d.ts +0 -0
  717. /package/dist/{implementation → tools/implementation}/inspect.d.ts +0 -0
  718. /package/dist/{implementation → tools/implementation}/invites.d.ts +0 -0
  719. /package/dist/{implementation → tools/implementation}/refs.d.ts +0 -0
  720. /package/dist/{implementation → tools/implementation}/schema.d.ts +0 -0
  721. /package/dist/{implementation → tools/implementation}/symbols.d.ts +0 -0
  722. /package/dist/{implementation → tools/implementation}/zodSchema/coExport.d.ts +0 -0
  723. /package/dist/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts +0 -0
  724. /package/dist/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts +0 -0
  725. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/AccountSchema.d.ts +0 -0
  726. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoFeedSchema.d.ts +0 -0
  727. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoListSchema.d.ts +0 -0
  728. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoMapSchema.d.ts +0 -0
  729. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoRecordSchema.d.ts +0 -0
  730. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/FileStreamSchema.d.ts +0 -0
  731. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/PlainTextSchema.d.ts +0 -0
  732. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/RichTextSchema.d.ts +0 -0
  733. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchema.d.ts +0 -0
  734. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts +0 -0
  735. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts +0 -0
  736. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts +0 -0
  737. /package/dist/{implementation → tools/implementation}/zodSchema/unionUtils.d.ts +0 -0
  738. /package/dist/{implementation → tools/implementation}/zodSchema/zodCo.d.ts +0 -0
  739. /package/dist/{implementation → tools/implementation}/zodSchema/zodReExport.d.ts +0 -0
  740. /package/dist/{implementation → tools/implementation}/zodSchema/zodSchema.d.ts +0 -0
  741. /package/dist/{internal.d.ts → tools/internal.d.ts} +0 -0
  742. /package/dist/{lib → tools/lib}/cache.d.ts +0 -0
  743. /package/dist/{lib → tools/lib}/cache.test.d.ts +0 -0
  744. /package/dist/{lib → tools/lib}/migration.d.ts +0 -0
  745. /package/dist/{subscribe → tools/subscribe}/CoValueCoreSubscription.d.ts +0 -0
  746. /package/dist/{subscribe → tools/subscribe}/JazzError.d.ts +0 -0
  747. /package/dist/{subscribe → tools/subscribe}/SubscriptionScope.d.ts +0 -0
  748. /package/dist/{subscribe → tools/subscribe}/index.d.ts +0 -0
  749. /package/dist/{subscribe → tools/subscribe}/types.d.ts +0 -0
  750. /package/dist/{subscribe → tools/subscribe}/utils.d.ts +0 -0
  751. /package/dist/{tests → tools/tests}/AuthSecretStorage.test.d.ts +0 -0
  752. /package/dist/{tests → tools/tests}/ContextManager.test.d.ts +0 -0
  753. /package/dist/{tests → tools/tests}/DemoAuth.test.d.ts +0 -0
  754. /package/dist/{tests → tools/tests}/PassphraseAuth.test.d.ts +0 -0
  755. /package/dist/{tests → tools/tests}/account.test.d.ts +0 -0
  756. /package/dist/{tests → tools/tests}/coFeed.test-d.d.ts +0 -0
  757. /package/dist/{tests → tools/tests}/coFeed.test.d.ts +0 -0
  758. /package/dist/{tests → tools/tests}/coList.test-d.d.ts +0 -0
  759. /package/dist/{tests → tools/tests}/coList.test.d.ts +0 -0
  760. /package/dist/{tests → tools/tests}/coMap.record.test-d.d.ts +0 -0
  761. /package/dist/{tests → tools/tests}/coMap.record.test.d.ts +0 -0
  762. /package/dist/{tests → tools/tests}/coMap.test-d.d.ts +0 -0
  763. /package/dist/{tests → tools/tests}/coMap.test.d.ts +0 -0
  764. /package/dist/{tests → tools/tests}/coPlainText.test.d.ts +0 -0
  765. /package/dist/{tests → tools/tests}/createContext.test.d.ts +0 -0
  766. /package/dist/{tests → tools/tests}/deepLoading.test.d.ts +0 -0
  767. /package/dist/{tests → tools/tests}/groupsAndAccounts.test.d.ts +0 -0
  768. /package/dist/{tests → tools/tests}/imageDef.test.d.ts +0 -0
  769. /package/dist/{tests → tools/tests}/inbox.test.d.ts +0 -0
  770. /package/dist/{tests → tools/tests}/interfaces.test.d.ts +0 -0
  771. /package/dist/{tests → tools/tests}/invites.test.d.ts +0 -0
  772. /package/dist/{tests → tools/tests}/load.test.d.ts +0 -0
  773. /package/dist/{tests → tools/tests}/patterns/notifications.test.d.ts +0 -0
  774. /package/dist/{tests → tools/tests}/patterns/requestToJoin.test.d.ts +0 -0
  775. /package/dist/{tests → tools/tests}/schema.test.d.ts +0 -0
  776. /package/dist/{tests → tools/tests}/schemaUnion.test.d.ts +0 -0
  777. /package/dist/{tests → tools/tests}/subscribe.test.d.ts +0 -0
  778. /package/dist/{tests → tools/tests}/testing.test.d.ts +0 -0
  779. /package/dist/{tests → tools/tests}/utils.d.ts +0 -0
  780. /package/dist/{tests → tools/tests}/zod.test.d.ts +0 -0
  781. /package/dist/{types.d.ts → tools/types.d.ts} +0 -0
  782. /package/src/{tests → react-core/tests}/fixtures.ts +0 -0
  783. /package/src/{auth/KvStoreContext.ts → react-native-core/storage/kv-store-context.ts} +0 -0
  784. /package/src/{auth → tools/auth}/AuthSecretStorage.ts +0 -0
  785. /package/src/{auth → tools/auth}/DemoAuth.ts +0 -0
  786. /package/src/{auth → tools/auth}/InMemoryKVStore.ts +0 -0
  787. /package/src/{auth → tools/auth}/PassphraseAuth.ts +0 -0
  788. /package/src/{coValues → tools/coValues}/CoValueBase.ts +0 -0
  789. /package/src/{coValues → tools/coValues}/account.ts +0 -0
  790. /package/src/{coValues → tools/coValues}/coList.ts +0 -0
  791. /package/src/{coValues → tools/coValues}/coMap.ts +0 -0
  792. /package/src/{coValues → tools/coValues}/coPlainText.ts +0 -0
  793. /package/src/{coValues → tools/coValues}/coRichText.ts +0 -0
  794. /package/src/{coValues → tools/coValues}/deepLoading.ts +0 -0
  795. /package/src/{coValues → tools/coValues}/extensions/imageDef.ts +0 -0
  796. /package/src/{coValues → tools/coValues}/group.ts +0 -0
  797. /package/src/{coValues → tools/coValues}/inbox.ts +0 -0
  798. /package/src/{coValues → tools/coValues}/interfaces.ts +0 -0
  799. /package/src/{coValues → tools/coValues}/profile.ts +0 -0
  800. /package/src/{coValues → tools/coValues}/registeredSchemas.ts +0 -0
  801. /package/src/{coValues → tools/coValues}/schemaUnion.ts +0 -0
  802. /package/src/{implementation → tools/implementation}/ContextManager.ts +0 -0
  803. /package/src/{implementation → tools/implementation}/activeAccountContext.ts +0 -0
  804. /package/src/{implementation → tools/implementation}/anonymousJazzAgent.ts +0 -0
  805. /package/src/{implementation → tools/implementation}/createContext.ts +0 -0
  806. /package/src/{implementation → tools/implementation}/devtoolsFormatters.ts +0 -0
  807. /package/src/{implementation → tools/implementation}/errors.ts +0 -0
  808. /package/src/{implementation → tools/implementation}/inspect.ts +0 -0
  809. /package/src/{implementation → tools/implementation}/invites.ts +0 -0
  810. /package/src/{implementation → tools/implementation}/refs.ts +0 -0
  811. /package/src/{implementation → tools/implementation}/schema.ts +0 -0
  812. /package/src/{implementation → tools/implementation}/symbols.ts +0 -0
  813. /package/src/{implementation → tools/implementation}/zodSchema/coExport.ts +0 -0
  814. /package/src/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodFieldToCoFieldDef.ts +0 -0
  815. /package/src/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodSchemaToCoSchema.ts +0 -0
  816. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/AccountSchema.ts +0 -0
  817. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoFeedSchema.ts +0 -0
  818. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoListSchema.ts +0 -0
  819. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoMapSchema.ts +0 -0
  820. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoRecordSchema.ts +0 -0
  821. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/FileStreamSchema.ts +0 -0
  822. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/PlainTextSchema.ts +0 -0
  823. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/RichTextSchema.ts +0 -0
  824. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchema.ts +0 -0
  825. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.ts +0 -0
  826. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.ts +0 -0
  827. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.ts +0 -0
  828. /package/src/{implementation → tools/implementation}/zodSchema/unionUtils.ts +0 -0
  829. /package/src/{implementation → tools/implementation}/zodSchema/zodCo.ts +0 -0
  830. /package/src/{implementation → tools/implementation}/zodSchema/zodReExport.ts +0 -0
  831. /package/src/{implementation → tools/implementation}/zodSchema/zodSchema.ts +0 -0
  832. /package/src/{internal.ts → tools/internal.ts} +0 -0
  833. /package/src/{lib → tools/lib}/cache.test.ts +0 -0
  834. /package/src/{lib → tools/lib}/cache.ts +0 -0
  835. /package/src/{lib → tools/lib}/migration.ts +0 -0
  836. /package/src/{subscribe → tools/subscribe}/CoValueCoreSubscription.ts +0 -0
  837. /package/src/{subscribe → tools/subscribe}/JazzError.ts +0 -0
  838. /package/src/{subscribe → tools/subscribe}/SubscriptionScope.ts +0 -0
  839. /package/src/{subscribe → tools/subscribe}/index.ts +0 -0
  840. /package/src/{subscribe → tools/subscribe}/types.ts +0 -0
  841. /package/src/{subscribe → tools/subscribe}/utils.ts +0 -0
  842. /package/src/{tests → tools/tests}/AuthSecretStorage.test.ts +0 -0
  843. /package/src/{tests → tools/tests}/ContextManager.test.ts +0 -0
  844. /package/src/{tests → tools/tests}/DemoAuth.test.ts +0 -0
  845. /package/src/{tests → tools/tests}/PassphraseAuth.test.ts +0 -0
  846. /package/src/{tests → tools/tests}/account.test.ts +0 -0
  847. /package/src/{tests → tools/tests}/coFeed.test-d.ts +0 -0
  848. /package/src/{tests → tools/tests}/coList.test-d.ts +0 -0
  849. /package/src/{tests → tools/tests}/coList.test.ts +0 -0
  850. /package/src/{tests → tools/tests}/coMap.record.test-d.ts +0 -0
  851. /package/src/{tests → tools/tests}/coMap.record.test.ts +0 -0
  852. /package/src/{tests → tools/tests}/coMap.test-d.ts +0 -0
  853. /package/src/{tests → tools/tests}/coMap.test.ts +0 -0
  854. /package/src/{tests → tools/tests}/coPlainText.test.ts +0 -0
  855. /package/src/{tests → tools/tests}/createContext.test.ts +0 -0
  856. /package/src/{tests → tools/tests}/deepLoading.test.ts +0 -0
  857. /package/src/{tests → tools/tests}/groupsAndAccounts.test.ts +0 -0
  858. /package/src/{tests → tools/tests}/imageDef.test.ts +0 -0
  859. /package/src/{tests → tools/tests}/inbox.test.ts +0 -0
  860. /package/src/{tests → tools/tests}/interfaces.test.ts +0 -0
  861. /package/src/{tests → tools/tests}/invites.test.ts +0 -0
  862. /package/src/{tests → tools/tests}/load.test.ts +0 -0
  863. /package/src/{tests → tools/tests}/patterns/notifications.test.ts +0 -0
  864. /package/src/{tests → tools/tests}/patterns/requestToJoin.test.ts +0 -0
  865. /package/src/{tests → tools/tests}/schema.test.ts +0 -0
  866. /package/src/{tests → tools/tests}/schemaUnion.test.ts +0 -0
  867. /package/src/{tests → tools/tests}/subscribe.test.ts +0 -0
  868. /package/src/{tests → tools/tests}/testing.test.ts +0 -0
  869. /package/src/{tests → tools/tests}/utils.ts +0 -0
  870. /package/src/{tests → tools/tests}/zod.test.ts +0 -0
  871. /package/src/{types.ts → tools/types.ts} +0 -0
@@ -0,0 +1,4827 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/tools/implementation/zodSchema/zodReExport.ts
8
+ var zodReExport_exports = {};
9
+ __export(zodReExport_exports, {
10
+ array: () => array,
11
+ base64: () => base64,
12
+ base64url: () => base64url,
13
+ boolean: () => boolean,
14
+ cidrv4: () => cidrv4,
15
+ cidrv6: () => cidrv6,
16
+ cuid: () => cuid,
17
+ cuid2: () => cuid2,
18
+ date: () => date,
19
+ discriminatedUnion: () => discriminatedUnion,
20
+ email: () => email,
21
+ emoji: () => emoji,
22
+ enum: () => enum2,
23
+ int: () => int,
24
+ int32: () => int32,
25
+ ipv4: () => ipv4,
26
+ ipv6: () => ipv6,
27
+ iso: () => iso,
28
+ json: () => json,
29
+ literal: () => literal,
30
+ nanoid: () => nanoid,
31
+ number: () => number,
32
+ object: () => object,
33
+ optional: () => optional,
34
+ strictObject: () => strictObject,
35
+ string: () => string,
36
+ templateLiteral: () => templateLiteral,
37
+ tuple: () => tuple,
38
+ ulid: () => ulid,
39
+ union: () => union,
40
+ url: () => url,
41
+ uuid: () => uuid,
42
+ z: () => z
43
+ });
44
+ import {
45
+ string,
46
+ number,
47
+ boolean,
48
+ union,
49
+ object,
50
+ array,
51
+ templateLiteral,
52
+ json,
53
+ tuple,
54
+ date,
55
+ emoji,
56
+ base64,
57
+ base64url,
58
+ nanoid,
59
+ cuid,
60
+ cuid2,
61
+ ulid,
62
+ ipv4,
63
+ ipv6,
64
+ email,
65
+ url,
66
+ uuid,
67
+ literal,
68
+ enum as enum2,
69
+ cidrv4,
70
+ cidrv6,
71
+ iso,
72
+ int32,
73
+ strictObject,
74
+ discriminatedUnion,
75
+ int,
76
+ optional,
77
+ z
78
+ } from "zod/v4";
79
+
80
+ // src/tools/coValues/CoValueBase.ts
81
+ import { ControlledAccount, RawAccount } from "cojson";
82
+ var CoValueBase = class {
83
+ get _owner() {
84
+ const schema = this._raw.group instanceof RawAccount ? RegisteredSchemas["Account"] : RegisteredSchemas["Group"];
85
+ return accessChildById(this, this._raw.group.id, {
86
+ ref: schema,
87
+ optional: false
88
+ });
89
+ }
90
+ /** @private */
91
+ get _loadedAs() {
92
+ const agent = this._raw.core.node.getCurrentAgent();
93
+ if (agent instanceof ControlledAccount) {
94
+ return coValuesCache.get(
95
+ agent.account,
96
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
97
+ agent.account
98
+ )
99
+ );
100
+ }
101
+ return new AnonymousJazzAgent(this._raw.core.node);
102
+ }
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ constructor(..._args) {
105
+ Object.defineProperty(this, "_instanceID", {
106
+ value: `instance-${Math.random().toString(36).slice(2)}`,
107
+ enumerable: false
108
+ });
109
+ }
110
+ /** @category Internals */
111
+ static fromRaw(raw) {
112
+ return new this({ fromRaw: raw });
113
+ }
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
+ toJSON() {
116
+ return {
117
+ id: this.id,
118
+ type: this._type,
119
+ error: "unknown CoValue class"
120
+ };
121
+ }
122
+ [inspect]() {
123
+ return this.toJSON();
124
+ }
125
+ /** @category Type Helpers */
126
+ castAs(schema) {
127
+ const cl = "getCoSchema" in schema ? schema.getCoSchema() : schema;
128
+ if (this.constructor === cl) {
129
+ return this;
130
+ }
131
+ return cl.fromRaw(this._raw);
132
+ }
133
+ };
134
+
135
+ // src/tools/implementation/inspect.ts
136
+ var inspect = Symbol.for("nodejs.util.inspect.custom");
137
+
138
+ // src/tools/implementation/symbols.ts
139
+ var SchemaInit = "$SchemaInit$";
140
+ var ItemsSym = "$items$";
141
+
142
+ // src/tools/coValues/registeredSchemas.ts
143
+ var RegisteredSchemas = {};
144
+
145
+ // src/tools/coValues/coMap.ts
146
+ import {
147
+ cojsonInternals
148
+ } from "cojson";
149
+ var _CoMap = class _CoMap extends CoValueBase {
150
+ /** @internal */
151
+ get _schema() {
152
+ return this.constructor._schema;
153
+ }
154
+ /**
155
+ * The timestamp of the creation time of the CoMap
156
+ */
157
+ get _createdAt() {
158
+ return this._raw.earliestTxMadeAt ?? Number.MAX_SAFE_INTEGER;
159
+ }
160
+ /**
161
+ * The timestamp of the last updated time of the CoMap
162
+ */
163
+ get _lastUpdatedAt() {
164
+ return this._raw.latestTxMadeAt;
165
+ }
166
+ /**
167
+ * If property `prop` is a `coField.ref(...)`, you can use `coMaps._refs.prop` to access
168
+ * the `Ref` instead of the potentially loaded/null value.
169
+ *
170
+ * This allows you to always get the ID or load the value manually.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * person._refs.pet.id; // => ID<Animal>
175
+ * person._refs.pet.value;
176
+ * // => Animal | null
177
+ * const pet = await person._refs.pet.load();
178
+ * ```
179
+ *
180
+ * @category Content
181
+ **/
182
+ get _refs() {
183
+ return makeRefs(
184
+ this,
185
+ (key) => this._raw.get(key),
186
+ () => {
187
+ const keys = this._raw.keys().filter((key) => {
188
+ const descriptor = this.getDescriptor(key);
189
+ return descriptor && descriptor !== "json" && isRefEncoded(descriptor);
190
+ });
191
+ return keys;
192
+ },
193
+ this._loadedAs,
194
+ (key) => this.getDescriptor(key)
195
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
196
+ );
197
+ }
198
+ /** @internal */
199
+ getEditFromRaw(target, rawEdit, descriptor, key) {
200
+ return {
201
+ value: descriptor === "json" ? rawEdit.value : "encoded" in descriptor ? rawEdit.value === null || rawEdit.value === void 0 ? rawEdit.value : descriptor.encoded.decode(rawEdit.value) : accessChildById(target, rawEdit.value, descriptor),
202
+ ref: descriptor !== "json" && isRefEncoded(descriptor) ? new Ref(
203
+ rawEdit.value,
204
+ target._loadedAs,
205
+ descriptor,
206
+ target
207
+ ) : void 0,
208
+ get by() {
209
+ return rawEdit.by && accessChildById(target, rawEdit.by, {
210
+ ref: Account,
211
+ optional: false
212
+ });
213
+ },
214
+ madeAt: rawEdit.at,
215
+ key
216
+ };
217
+ }
218
+ /** @category Collaboration */
219
+ get _edits() {
220
+ const map = this;
221
+ return new Proxy(
222
+ {},
223
+ {
224
+ get(_target, key) {
225
+ const rawEdit = map._raw.lastEditAt(key);
226
+ if (!rawEdit) return void 0;
227
+ const descriptor = map.getDescriptor(key);
228
+ if (!descriptor) return void 0;
229
+ return {
230
+ ...map.getEditFromRaw(map, rawEdit, descriptor, key),
231
+ get all() {
232
+ return [...map._raw.editsAt(key)].map(
233
+ (rawEdit2) => map.getEditFromRaw(map, rawEdit2, descriptor, key)
234
+ );
235
+ }
236
+ };
237
+ },
238
+ ownKeys(_target) {
239
+ return map._raw.keys();
240
+ },
241
+ getOwnPropertyDescriptor(target, key) {
242
+ return {
243
+ value: Reflect.get(target, key),
244
+ writable: false,
245
+ enumerable: true,
246
+ configurable: true
247
+ };
248
+ }
249
+ }
250
+ );
251
+ }
252
+ /** @internal */
253
+ constructor(options) {
254
+ super();
255
+ if (options) {
256
+ if ("fromRaw" in options) {
257
+ Object.defineProperties(this, {
258
+ id: {
259
+ value: options.fromRaw.id,
260
+ enumerable: false
261
+ },
262
+ _raw: { value: options.fromRaw, enumerable: false }
263
+ });
264
+ } else {
265
+ throw new Error("Invalid CoMap constructor arguments");
266
+ }
267
+ }
268
+ return new Proxy(this, CoMapProxyHandler);
269
+ }
270
+ /**
271
+ * Create a new CoMap with the given initial values and owner.
272
+ *
273
+ * The owner (a Group or Account) determines access rights to the CoMap.
274
+ *
275
+ * The CoMap will immediately be persisted and synced to connected peers.
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * const person = Person.create({
280
+ * name: "Alice",
281
+ * age: 42,
282
+ * pet: cat,
283
+ * }, { owner: friendGroup });
284
+ * ```
285
+ *
286
+ * @category Creation
287
+ **/
288
+ static create(init, options) {
289
+ const instance = new this();
290
+ const { owner, uniqueness } = parseCoValueCreateOptions(options);
291
+ const raw = instance.rawFromInit(init, owner, uniqueness);
292
+ Object.defineProperties(instance, {
293
+ id: {
294
+ value: raw.id,
295
+ enumerable: false
296
+ },
297
+ _raw: { value: raw, enumerable: false }
298
+ });
299
+ return instance;
300
+ }
301
+ /**
302
+ * Return a JSON representation of the `CoMap`
303
+ * @category Content
304
+ */
305
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
306
+ toJSON(_key, processedValues) {
307
+ const result = {
308
+ id: this.id,
309
+ _type: this._type
310
+ };
311
+ for (const key of this._raw.keys()) {
312
+ const tKey = key;
313
+ const descriptor = this.getDescriptor(tKey);
314
+ if (!descriptor) {
315
+ continue;
316
+ }
317
+ if (descriptor == "json" || "encoded" in descriptor) {
318
+ result[key] = this._raw.get(key);
319
+ } else if (isRefEncoded(descriptor)) {
320
+ const id = this._raw.get(key);
321
+ if (processedValues?.includes(id) || id === this.id) {
322
+ result[key] = { _circular: id };
323
+ continue;
324
+ }
325
+ const ref2 = this[tKey];
326
+ if (ref2 && typeof ref2 === "object" && "toJSON" in ref2 && typeof ref2.toJSON === "function") {
327
+ const jsonedRef = ref2.toJSON(tKey, [
328
+ ...processedValues || [],
329
+ this.id
330
+ ]);
331
+ result[key] = jsonedRef;
332
+ }
333
+ } else {
334
+ result[key] = void 0;
335
+ }
336
+ }
337
+ return result;
338
+ }
339
+ [inspect]() {
340
+ return this.toJSON();
341
+ }
342
+ /**
343
+ * Create a new `RawCoMap` from an initialization object
344
+ * @internal
345
+ */
346
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
+ rawFromInit(init, owner, uniqueness) {
348
+ const rawOwner = owner._raw;
349
+ const rawInit = {};
350
+ if (init)
351
+ for (const key of Object.keys(init)) {
352
+ const initValue = init[key];
353
+ const descriptor = this.getDescriptor(key);
354
+ if (!descriptor) {
355
+ continue;
356
+ }
357
+ if (descriptor === "json") {
358
+ rawInit[key] = initValue;
359
+ } else if (isRefEncoded(descriptor)) {
360
+ if (initValue) {
361
+ rawInit[key] = initValue.id;
362
+ }
363
+ } else if ("encoded" in descriptor) {
364
+ rawInit[key] = descriptor.encoded.encode(
365
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
366
+ initValue
367
+ );
368
+ }
369
+ }
370
+ return rawOwner.createMap(rawInit, null, "private", uniqueness);
371
+ }
372
+ getDescriptor(key) {
373
+ return this._schema?.[key] || this._schema?.[ItemsSym];
374
+ }
375
+ /**
376
+ * Declare a Record-like CoMap schema, by extending `CoMap.Record(...)` and passing the value schema using `co`. Keys are always `string`.
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * import { coField, CoMap } from "jazz-tools";
381
+ *
382
+ * class ColorToFruitMap extends CoMap.Record(
383
+ * coField.ref(Fruit)
384
+ * ) {}
385
+ *
386
+ * // assume we have map: ColorToFruitMap
387
+ * // and strawberry: Fruit
388
+ * map["red"] = strawberry;
389
+ * ```
390
+ *
391
+ * @category Declaration
392
+ */
393
+ static Record(value) {
394
+ var _a, _b;
395
+ class RecordLikeCoMap extends (_b = _CoMap, _a = ItemsSym, _b) {
396
+ constructor() {
397
+ super(...arguments);
398
+ this[_a] = value;
399
+ }
400
+ }
401
+ return RecordLikeCoMap;
402
+ }
403
+ /**
404
+ * Load a `CoMap` with a given ID, as a given account.
405
+ *
406
+ * `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving.
407
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
408
+ *
409
+ * You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues.
410
+ *
411
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
412
+ *
413
+ * @example
414
+ * ```ts
415
+ * const person = await Person.load(
416
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
417
+ * { pet: {} }
418
+ * );
419
+ * ```
420
+ *
421
+ * @category Subscription & Loading
422
+ */
423
+ static load(id, options) {
424
+ return loadCoValueWithoutMe(this, id, options);
425
+ }
426
+ static subscribe(id, ...args) {
427
+ const { options, listener } = parseSubscribeRestArgs(args);
428
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
429
+ }
430
+ static findUnique(unique, ownerID, as) {
431
+ as ||= activeAccountContext.get();
432
+ const header = {
433
+ type: "comap",
434
+ ruleset: {
435
+ type: "ownedByGroup",
436
+ group: ownerID
437
+ },
438
+ meta: null,
439
+ uniqueness: unique
440
+ };
441
+ const crypto = as._type === "Anonymous" ? as.node.crypto : as._raw.core.node.crypto;
442
+ return cojsonInternals.idforHeader(header, crypto);
443
+ }
444
+ /**
445
+ * Given an already loaded `CoMap`, ensure that the specified fields are loaded to the specified depth.
446
+ *
447
+ * Works like `CoMap.load()`, but you don't need to pass the ID or the account to load as again.
448
+ *
449
+ * @category Subscription & Loading
450
+ */
451
+ ensureLoaded(options) {
452
+ return ensureCoValueLoaded(this, options);
453
+ }
454
+ subscribe(...args) {
455
+ const { options, listener } = parseSubscribeRestArgs(args);
456
+ return subscribeToExistingCoValue(this, options, listener);
457
+ }
458
+ applyDiff(newValues) {
459
+ for (const key in newValues) {
460
+ if (Object.prototype.hasOwnProperty.call(newValues, key)) {
461
+ const tKey = key;
462
+ const descriptor = this.getDescriptor(key);
463
+ if (!descriptor) continue;
464
+ const newValue = newValues[tKey];
465
+ const currentValue = this[tKey];
466
+ if (descriptor === "json" || "encoded" in descriptor) {
467
+ if (currentValue !== newValue) {
468
+ this[tKey] = newValue;
469
+ }
470
+ } else if (isRefEncoded(descriptor)) {
471
+ const currentId = currentValue?.id;
472
+ const newId = newValue?.id;
473
+ if (currentId !== newId) {
474
+ this[tKey] = newValue;
475
+ }
476
+ }
477
+ }
478
+ }
479
+ return this;
480
+ }
481
+ /**
482
+ * Wait for the `CoMap` to be uploaded to the other peers.
483
+ *
484
+ * @category Subscription & Loading
485
+ */
486
+ waitForSync(options) {
487
+ return this._raw.core.waitForSync(options);
488
+ }
489
+ };
490
+ _CoMap.prototype._type = "CoMap";
491
+ var CoMap = _CoMap;
492
+ var CoMapProxyHandler = {
493
+ get(target, key, receiver) {
494
+ if (key === "_schema") {
495
+ return Reflect.get(target, key);
496
+ } else if (key in target) {
497
+ return Reflect.get(target, key, receiver);
498
+ } else {
499
+ if (typeof key !== "string") {
500
+ return void 0;
501
+ }
502
+ const descriptor = target.getDescriptor(key);
503
+ if (!descriptor) {
504
+ return void 0;
505
+ }
506
+ const raw = target._raw.get(key);
507
+ if (descriptor === "json") {
508
+ return raw;
509
+ } else if ("encoded" in descriptor) {
510
+ return raw === void 0 ? void 0 : descriptor.encoded.decode(raw);
511
+ } else if (isRefEncoded(descriptor)) {
512
+ return raw === void 0 || raw === null ? void 0 : accessChildByKey(target, raw, key);
513
+ }
514
+ }
515
+ },
516
+ set(target, key, value, receiver) {
517
+ if ((typeof key === "string" || ItemsSym) && typeof value === "object" && value !== null && SchemaInit in value) {
518
+ target.constructor._schema ||= {};
519
+ target.constructor._schema[key] = value[SchemaInit];
520
+ return true;
521
+ }
522
+ const descriptor = target.getDescriptor(key);
523
+ if (!descriptor) return false;
524
+ if (typeof key === "string") {
525
+ if (descriptor === "json") {
526
+ target._raw.set(key, value);
527
+ } else if ("encoded" in descriptor) {
528
+ target._raw.set(key, descriptor.encoded.encode(value));
529
+ } else if (isRefEncoded(descriptor)) {
530
+ if (value === void 0) {
531
+ if (descriptor.optional) {
532
+ target._raw.set(key, null);
533
+ } else {
534
+ throw new Error(
535
+ `Cannot set required reference ${key} to undefined`
536
+ );
537
+ }
538
+ } else if (value?.id) {
539
+ target._raw.set(key, value.id);
540
+ } else {
541
+ throw new Error(
542
+ `Cannot set reference ${key} to a non-CoValue. Got ${value}`
543
+ );
544
+ }
545
+ }
546
+ return true;
547
+ } else {
548
+ return Reflect.set(target, key, value, receiver);
549
+ }
550
+ },
551
+ defineProperty(target, key, attributes) {
552
+ if ("value" in attributes && typeof attributes.value === "object" && SchemaInit in attributes.value) {
553
+ target.constructor._schema ||= {};
554
+ target.constructor._schema[key] = attributes.value[SchemaInit];
555
+ return true;
556
+ } else {
557
+ return Reflect.defineProperty(target, key, attributes);
558
+ }
559
+ },
560
+ ownKeys(target) {
561
+ const keys = Reflect.ownKeys(target).filter((k) => k !== ItemsSym);
562
+ for (const key of target._raw.keys()) {
563
+ if (!keys.includes(key)) {
564
+ keys.push(key);
565
+ }
566
+ }
567
+ return keys;
568
+ },
569
+ getOwnPropertyDescriptor(target, key) {
570
+ if (key in target) {
571
+ return Reflect.getOwnPropertyDescriptor(target, key);
572
+ } else {
573
+ const descriptor = target.getDescriptor(key);
574
+ if (descriptor || key in target._raw.latest) {
575
+ return {
576
+ enumerable: true,
577
+ configurable: true,
578
+ writable: true
579
+ };
580
+ }
581
+ }
582
+ },
583
+ has(target, key) {
584
+ const descriptor = target.getDescriptor(key);
585
+ if (target._raw && typeof key === "string" && descriptor) {
586
+ return target._raw.get(key) !== void 0;
587
+ } else {
588
+ return Reflect.has(target, key);
589
+ }
590
+ },
591
+ deleteProperty(target, key) {
592
+ const descriptor = target.getDescriptor(key);
593
+ if (typeof key === "string" && descriptor) {
594
+ target._raw.delete(key);
595
+ return true;
596
+ } else {
597
+ return Reflect.deleteProperty(target, key);
598
+ }
599
+ }
600
+ };
601
+ RegisteredSchemas["CoMap"] = CoMap;
602
+
603
+ // src/tools/coValues/coList.ts
604
+ import { ControlledAccount as ControlledAccount2, RawAccount as RawAccount2 } from "cojson";
605
+ import { calcPatch } from "fast-myers-diff";
606
+ var _CoList = class _CoList extends Array {
607
+ /**
608
+ * Declare a `CoList` by subclassing `CoList.Of(...)` and passing the item schema using `co`.
609
+ *
610
+ * @example
611
+ * ```ts
612
+ * class ColorList extends CoList.Of(
613
+ * coField.string
614
+ * ) {}
615
+ * class AnimalList extends CoList.Of(
616
+ * coField.ref(Animal)
617
+ * ) {}
618
+ * ```
619
+ *
620
+ * @category Declaration
621
+ */
622
+ static Of(item) {
623
+ var _a, _b;
624
+ return class CoListOf extends (_b = _CoList, _a = coField.items, _b) {
625
+ constructor() {
626
+ super(...arguments);
627
+ this[_a] = item;
628
+ }
629
+ };
630
+ }
631
+ /**
632
+ * @ignore
633
+ * @deprecated Use UPPERCASE `CoList.Of` instead! */
634
+ static of(..._args) {
635
+ throw new Error("Can't use Array.of with CoLists");
636
+ }
637
+ /** @internal */
638
+ get _schema() {
639
+ return this.constructor._schema;
640
+ }
641
+ /** @category Collaboration */
642
+ get _owner() {
643
+ return this._raw.group instanceof RawAccount2 ? anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
644
+ this._raw.group
645
+ ) : RegisteredSchemas["Group"].fromRaw(this._raw.group);
646
+ }
647
+ /**
648
+ * If a `CoList`'s items are a `coField.ref(...)`, you can use `coList._refs[i]` to access
649
+ * the `Ref` instead of the potentially loaded/null value.
650
+ *
651
+ * This allows you to always get the ID or load the value manually.
652
+ *
653
+ * @example
654
+ * ```ts
655
+ * animals._refs[0].id; // => ID<Animal>
656
+ * animals._refs[0].value;
657
+ * // => Animal | null
658
+ * const animal = await animals._refs[0].load();
659
+ * ```
660
+ *
661
+ * @category Content
662
+ **/
663
+ get _refs() {
664
+ return makeRefs(
665
+ this,
666
+ (idx) => this._raw.get(idx),
667
+ () => Array.from({ length: this._raw.entries().length }, (_, idx) => idx),
668
+ this._loadedAs,
669
+ (_idx) => this._schema[ItemsSym]
670
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
671
+ );
672
+ }
673
+ get _edits() {
674
+ throw new Error("Not implemented");
675
+ }
676
+ get _loadedAs() {
677
+ const agent = this._raw.core.node.getCurrentAgent();
678
+ if (agent instanceof ControlledAccount2) {
679
+ return coValuesCache.get(
680
+ agent.account,
681
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
682
+ agent.account
683
+ )
684
+ );
685
+ }
686
+ return new AnonymousJazzAgent(this._raw.core.node);
687
+ }
688
+ static get [(ItemsSym, Symbol.species)]() {
689
+ return Array;
690
+ }
691
+ getItemsDescriptor() {
692
+ return this._schema?.[ItemsSym];
693
+ }
694
+ constructor(options) {
695
+ super();
696
+ Object.defineProperty(this, "_instanceID", {
697
+ value: `instance-${Math.random().toString(36).slice(2)}`,
698
+ enumerable: false
699
+ });
700
+ if (options && "fromRaw" in options) {
701
+ Object.defineProperties(this, {
702
+ id: {
703
+ value: options.fromRaw.id,
704
+ enumerable: false
705
+ },
706
+ _raw: { value: options.fromRaw, enumerable: false }
707
+ });
708
+ }
709
+ return new Proxy(this, CoListProxyHandler);
710
+ }
711
+ /**
712
+ * Create a new CoList with the given initial values and owner.
713
+ *
714
+ * The owner (a Group or Account) determines access rights to the CoMap.
715
+ *
716
+ * The CoList will immediately be persisted and synced to connected peers.
717
+ *
718
+ * @example
719
+ * ```ts
720
+ * const colours = ColorList.create(
721
+ * ["red", "green", "blue"],
722
+ * { owner: me }
723
+ * );
724
+ * const animals = AnimalList.create(
725
+ * [cat, dog, fish],
726
+ * { owner: me }
727
+ * );
728
+ * ```
729
+ *
730
+ * @category Creation
731
+ **/
732
+ static create(items, options) {
733
+ const { owner } = parseCoValueCreateOptions(options);
734
+ const instance = new this({ init: items, owner });
735
+ const raw = owner._raw.createList(
736
+ toRawItems(items, instance._schema[ItemsSym])
737
+ );
738
+ Object.defineProperties(instance, {
739
+ id: {
740
+ value: raw.id,
741
+ enumerable: false
742
+ },
743
+ _raw: { value: raw, enumerable: false }
744
+ });
745
+ return instance;
746
+ }
747
+ push(...items) {
748
+ this._raw.appendItems(
749
+ toRawItems(items, this._schema[ItemsSym]),
750
+ void 0,
751
+ "private"
752
+ );
753
+ return this._raw.entries().length;
754
+ }
755
+ unshift(...items) {
756
+ for (const item of toRawItems(items, this._schema[ItemsSym])) {
757
+ this._raw.prepend(item);
758
+ }
759
+ return this._raw.entries().length;
760
+ }
761
+ pop() {
762
+ const last = this[this.length - 1];
763
+ this._raw.delete(this.length - 1);
764
+ return last;
765
+ }
766
+ shift() {
767
+ const first = this[0];
768
+ this._raw.delete(0);
769
+ return first;
770
+ }
771
+ /**
772
+ * Splice the `CoList` at a given index.
773
+ *
774
+ * @param start - The index to start the splice.
775
+ * @param deleteCount - The number of items to delete.
776
+ * @param items - The items to insert.
777
+ */
778
+ splice(start, deleteCount, ...items) {
779
+ const deleted = this.slice(start, start + deleteCount);
780
+ for (let idxToDelete = start + deleteCount - 1; idxToDelete >= start; idxToDelete--) {
781
+ this._raw.delete(idxToDelete);
782
+ }
783
+ const rawItems = toRawItems(items, this._schema[ItemsSym]);
784
+ if (rawItems.length === 0) {
785
+ return deleted;
786
+ }
787
+ if (rawItems.length === 1) {
788
+ const item = rawItems[0];
789
+ if (item === void 0) return deleted;
790
+ if (start === 0) {
791
+ this._raw.prepend(item);
792
+ } else {
793
+ this._raw.append(item, Math.max(start - 1, 0));
794
+ }
795
+ return deleted;
796
+ }
797
+ if (start === 0) {
798
+ for (let i = rawItems.length - 1; i >= 0; i--) {
799
+ const item = rawItems[i];
800
+ if (item === void 0) continue;
801
+ this._raw.prepend(item);
802
+ }
803
+ } else {
804
+ let appendAfter = Math.max(start - 1, 0);
805
+ for (const item of rawItems) {
806
+ if (item === void 0) continue;
807
+ this._raw.append(item, appendAfter);
808
+ appendAfter++;
809
+ }
810
+ }
811
+ return deleted;
812
+ }
813
+ /**
814
+ * Modify the `CoList` to match another list, where the changes are managed internally.
815
+ *
816
+ * @param result - The resolved list of items.
817
+ */
818
+ applyDiff(result) {
819
+ const current = this._raw.asArray();
820
+ const comparator = isRefEncoded(this._schema[ItemsSym]) ? (aIdx, bIdx) => {
821
+ return current[aIdx]?.id === result[bIdx]?.id;
822
+ } : void 0;
823
+ const patches = [...calcPatch(current, result, comparator)];
824
+ for (const [from, to, insert] of patches.reverse()) {
825
+ this.splice(from, to - from, ...insert);
826
+ }
827
+ }
828
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
829
+ toJSON(_key, seenAbove) {
830
+ const itemDescriptor = this._schema[ItemsSym];
831
+ if (itemDescriptor === "json") {
832
+ return this._raw.asArray();
833
+ } else if ("encoded" in itemDescriptor) {
834
+ return this._raw.asArray().map((e) => itemDescriptor.encoded.encode(e));
835
+ } else if (isRefEncoded(itemDescriptor)) {
836
+ return this.map(
837
+ (item, idx) => seenAbove?.includes(item?.id) ? { _circular: item.id } : item?.toJSON(idx + "", [
838
+ ...seenAbove || [],
839
+ this.id
840
+ ])
841
+ );
842
+ } else {
843
+ return [];
844
+ }
845
+ }
846
+ [inspect]() {
847
+ return this.toJSON();
848
+ }
849
+ /** @category Internals */
850
+ static fromRaw(raw) {
851
+ return new this({ fromRaw: raw });
852
+ }
853
+ /** @internal */
854
+ static schema(def) {
855
+ this._schema ||= {};
856
+ Object.assign(this._schema, def);
857
+ }
858
+ /**
859
+ * Load a `CoList` with a given ID, as a given account.
860
+ *
861
+ * `depth` specifies if item CoValue references should be loaded as well before resolving.
862
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
863
+ *
864
+ * You can pass `[]` or for shallowly loading only this CoList, or `[itemDepth]` for recursively loading referenced CoValues.
865
+ *
866
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
867
+ *
868
+ * @example
869
+ * ```ts
870
+ * const animalsWithVets =
871
+ * await ListOfAnimals.load(
872
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
873
+ * me,
874
+ * [{ vet: {} }]
875
+ * );
876
+ * ```
877
+ *
878
+ * @category Subscription & Loading
879
+ */
880
+ static load(id, options) {
881
+ return loadCoValueWithoutMe(this, id, options);
882
+ }
883
+ static subscribe(id, ...args) {
884
+ const { options, listener } = parseSubscribeRestArgs(args);
885
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
886
+ }
887
+ /**
888
+ * Given an already loaded `CoList`, ensure that items are loaded to the specified depth.
889
+ *
890
+ * Works like `CoList.load()`, but you don't need to pass the ID or the account to load as again.
891
+ *
892
+ * @category Subscription & Loading
893
+ */
894
+ ensureLoaded(options) {
895
+ return ensureCoValueLoaded(this, options);
896
+ }
897
+ subscribe(...args) {
898
+ const { options, listener } = parseSubscribeRestArgs(args);
899
+ return subscribeToExistingCoValue(this, options, listener);
900
+ }
901
+ /** @category Type Helpers */
902
+ castAs(cl) {
903
+ return cl.fromRaw(this._raw);
904
+ }
905
+ /**
906
+ * Wait for the `CoList` to be uploaded to the other peers.
907
+ *
908
+ * @category Subscription & Loading
909
+ */
910
+ waitForSync(options) {
911
+ return this._raw.core.waitForSync(options);
912
+ }
913
+ };
914
+ _CoList.prototype._type = "CoList";
915
+ var CoList = _CoList;
916
+ function toRawItems(items, itemDescriptor) {
917
+ const rawItems = itemDescriptor === "json" ? items : "encoded" in itemDescriptor ? items?.map((e) => itemDescriptor.encoded.encode(e)) : isRefEncoded(itemDescriptor) ? items?.map((v) => {
918
+ if (!v) return null;
919
+ return v.id;
920
+ }) : (() => {
921
+ throw new Error("Invalid element descriptor");
922
+ })();
923
+ return rawItems;
924
+ }
925
+ var CoListProxyHandler = {
926
+ get(target, key, receiver) {
927
+ if (typeof key === "string" && !isNaN(+key)) {
928
+ const itemDescriptor = target._schema[ItemsSym];
929
+ const rawValue = target._raw.get(Number(key));
930
+ if (itemDescriptor === "json") {
931
+ return rawValue;
932
+ } else if ("encoded" in itemDescriptor) {
933
+ return rawValue === void 0 ? void 0 : itemDescriptor.encoded.decode(rawValue);
934
+ } else if (isRefEncoded(itemDescriptor)) {
935
+ return rawValue === void 0 || rawValue === null ? void 0 : accessChildByKey(target, rawValue, key);
936
+ }
937
+ } else if (key === "length") {
938
+ return target._raw.entries().length;
939
+ } else {
940
+ return Reflect.get(target, key, receiver);
941
+ }
942
+ },
943
+ set(target, key, value, receiver) {
944
+ if (key === ItemsSym && typeof value === "object" && SchemaInit in value) {
945
+ target.constructor._schema ||= {};
946
+ target.constructor._schema[ItemsSym] = value[SchemaInit];
947
+ return true;
948
+ }
949
+ if (typeof key === "string" && !isNaN(+key)) {
950
+ const itemDescriptor = target._schema[ItemsSym];
951
+ let rawValue;
952
+ if (itemDescriptor === "json") {
953
+ rawValue = value;
954
+ } else if ("encoded" in itemDescriptor) {
955
+ rawValue = itemDescriptor.encoded.encode(value);
956
+ } else if (isRefEncoded(itemDescriptor)) {
957
+ if (value === void 0) {
958
+ if (itemDescriptor.optional) {
959
+ rawValue = null;
960
+ } else {
961
+ throw new Error(
962
+ `Cannot set required reference ${key} to undefined`
963
+ );
964
+ }
965
+ } else if (value?.id) {
966
+ rawValue = value.id;
967
+ } else {
968
+ throw new Error(
969
+ `Cannot set reference ${key} to a non-CoValue. Got ${value}`
970
+ );
971
+ }
972
+ }
973
+ target._raw.replace(Number(key), rawValue);
974
+ return true;
975
+ } else {
976
+ return Reflect.set(target, key, value, receiver);
977
+ }
978
+ },
979
+ defineProperty(target, key, descriptor) {
980
+ if (descriptor.value && key === ItemsSym && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
981
+ target.constructor._schema ||= {};
982
+ target.constructor._schema[ItemsSym] = descriptor.value[SchemaInit];
983
+ return true;
984
+ } else {
985
+ return Reflect.defineProperty(target, key, descriptor);
986
+ }
987
+ },
988
+ has(target, key) {
989
+ if (typeof key === "string" && !isNaN(+key)) {
990
+ return Number(key) < target._raw.entries().length;
991
+ } else {
992
+ return Reflect.has(target, key);
993
+ }
994
+ }
995
+ };
996
+
997
+ // src/tools/coValues/coFeed.ts
998
+ import { MAX_RECOMMENDED_TX_SIZE, cojsonInternals as cojsonInternals2 } from "cojson";
999
+ var _CoFeed = class _CoFeed extends CoValueBase {
1000
+ /**
1001
+ * Declare a `CoFeed` by subclassing `CoFeed.Of(...)` and passing the item schema using a `co` primitive or a `coField.ref`.
1002
+ *
1003
+ * @example
1004
+ * ```ts
1005
+ * class ColorFeed extends CoFeed.Of(coField.string) {}
1006
+ * class AnimalFeed extends CoFeed.Of(coField.ref(Animal)) {}
1007
+ * ```
1008
+ *
1009
+ * @category Declaration
1010
+ */
1011
+ static Of(item) {
1012
+ var _a, _b;
1013
+ const cls = class CoFeedOf extends (_b = _CoFeed, _a = coField.items, _b) {
1014
+ constructor() {
1015
+ super(...arguments);
1016
+ this[_a] = item;
1017
+ }
1018
+ };
1019
+ cls._schema ||= {};
1020
+ cls._schema[ItemsSym] = item[SchemaInit];
1021
+ return cls;
1022
+ }
1023
+ /** @internal */
1024
+ get _schema() {
1025
+ return this.constructor._schema;
1026
+ }
1027
+ /**
1028
+ * The current account's view of this `CoFeed`
1029
+ * @category Content
1030
+ */
1031
+ get byMe() {
1032
+ if (this._loadedAs._type === "Account") {
1033
+ return this.perAccount[this._loadedAs.id];
1034
+ } else {
1035
+ return void 0;
1036
+ }
1037
+ }
1038
+ /**
1039
+ * The per-account view of this `CoFeed`
1040
+ *
1041
+ * @example
1042
+ * ```ts
1043
+ * // Access entries directly by account ID
1044
+ * const aliceEntries = feed[aliceAccount.id];
1045
+ * console.log(aliceEntries.value); // Latest value from Alice
1046
+ *
1047
+ * // Iterate through all accounts' entries
1048
+ * for (const [accountId, entries] of Object.entries(feed)) {
1049
+ * console.log(`Latest entry from ${accountId}:`, entries.value);
1050
+ *
1051
+ * // Access all entries from this account
1052
+ * for (const entry of entries.all) {
1053
+ * console.log(`Entry made at ${entry.madeAt}:`, entry.value);
1054
+ * }
1055
+ * }
1056
+ * ```
1057
+ *
1058
+ * @category Content
1059
+ */
1060
+ get perAccount() {
1061
+ return new Proxy({}, CoStreamPerAccountProxyHandler(this));
1062
+ }
1063
+ /**
1064
+ * The per-session view of this `CoFeed`
1065
+ * @category Content
1066
+ */
1067
+ get perSession() {
1068
+ return new Proxy(
1069
+ {},
1070
+ CoStreamPerSessionProxyHandler(this, this)
1071
+ );
1072
+ }
1073
+ /**
1074
+ * The current session's view of this `CoFeed`
1075
+ *
1076
+ * This is a shortcut for `this.perSession` where the session ID is the current session ID.
1077
+ *
1078
+ * @category Content
1079
+ */
1080
+ get inCurrentSession() {
1081
+ if (this._loadedAs._type === "Account") {
1082
+ return this.perSession[this._loadedAs.sessionID];
1083
+ } else {
1084
+ return void 0;
1085
+ }
1086
+ }
1087
+ constructor(options) {
1088
+ super();
1089
+ if (options && "fromRaw" in options) {
1090
+ Object.defineProperties(this, {
1091
+ id: {
1092
+ value: options.fromRaw.id,
1093
+ enumerable: false
1094
+ },
1095
+ _raw: { value: options.fromRaw, enumerable: false }
1096
+ });
1097
+ }
1098
+ return this;
1099
+ }
1100
+ /**
1101
+ * Create a new `CoFeed`
1102
+ * @category Creation
1103
+ */
1104
+ static create(init, options) {
1105
+ const { owner } = parseCoValueCreateOptions(options);
1106
+ const instance = new this({ init, owner });
1107
+ const raw = owner._raw.createStream();
1108
+ Object.defineProperties(instance, {
1109
+ id: {
1110
+ value: raw.id,
1111
+ enumerable: false
1112
+ },
1113
+ _raw: { value: raw, enumerable: false }
1114
+ });
1115
+ if (init) {
1116
+ instance.push(...init);
1117
+ }
1118
+ return instance;
1119
+ }
1120
+ getItemsDescriptor() {
1121
+ return this._schema?.[ItemsSym];
1122
+ }
1123
+ /**
1124
+ * Push items to this `CoFeed`
1125
+ *
1126
+ * Items are appended to the current session's log. Each session (tab, device, app instance)
1127
+ * maintains its own append-only log, which is then aggregated into the per-account view.
1128
+ *
1129
+ * @example
1130
+ * ```ts
1131
+ * // Adds items to current session's log
1132
+ * feed.push("item1", "item2");
1133
+ *
1134
+ * // View items from current session
1135
+ * console.log(feed.inCurrentSession);
1136
+ *
1137
+ * // View aggregated items from all sessions for current account
1138
+ * console.log(feed.byMe);
1139
+ * ```
1140
+ *
1141
+ * @category Content
1142
+ */
1143
+ push(...items) {
1144
+ for (const item of items) {
1145
+ this.pushItem(item);
1146
+ }
1147
+ }
1148
+ pushItem(item) {
1149
+ const itemDescriptor = this._schema[ItemsSym];
1150
+ if (itemDescriptor === "json") {
1151
+ this._raw.push(item);
1152
+ } else if ("encoded" in itemDescriptor) {
1153
+ this._raw.push(itemDescriptor.encoded.encode(item));
1154
+ } else if (isRefEncoded(itemDescriptor)) {
1155
+ this._raw.push(item.id);
1156
+ }
1157
+ }
1158
+ /**
1159
+ * Get a JSON representation of the `CoFeed`
1160
+ * @category
1161
+ */
1162
+ toJSON() {
1163
+ const itemDescriptor = this._schema[ItemsSym];
1164
+ const mapper = itemDescriptor === "json" ? (v) => v : "encoded" in itemDescriptor ? itemDescriptor.encoded.encode : (v) => v && v.id;
1165
+ return {
1166
+ id: this.id,
1167
+ _type: this._type,
1168
+ ...Object.fromEntries(
1169
+ Object.entries(this).map(([account, entry]) => [
1170
+ account,
1171
+ mapper(entry.value)
1172
+ ])
1173
+ ),
1174
+ in: Object.fromEntries(
1175
+ Object.entries(this.perSession).map(([session, entry]) => [
1176
+ session,
1177
+ mapper(entry.value)
1178
+ ])
1179
+ )
1180
+ };
1181
+ }
1182
+ /** @internal */
1183
+ [(ItemsSym, inspect)]() {
1184
+ return this.toJSON();
1185
+ }
1186
+ /** @internal */
1187
+ static schema(def) {
1188
+ this._schema ||= {};
1189
+ Object.assign(this._schema, def);
1190
+ }
1191
+ /**
1192
+ * Load a `CoFeed`
1193
+ * @category Subscription & Loading
1194
+ */
1195
+ static load(id, options) {
1196
+ return loadCoValueWithoutMe(this, id, options);
1197
+ }
1198
+ static subscribe(id, ...args) {
1199
+ const { options, listener } = parseSubscribeRestArgs(args);
1200
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1201
+ }
1202
+ /**
1203
+ * Ensure a `CoFeed` is loaded to the specified depth
1204
+ *
1205
+ * @returns A new instance of the same CoFeed that's loaded to the specified depth
1206
+ * @category Subscription & Loading
1207
+ */
1208
+ ensureLoaded(options) {
1209
+ return ensureCoValueLoaded(this, options);
1210
+ }
1211
+ subscribe(...args) {
1212
+ const { options, listener } = parseSubscribeRestArgs(args);
1213
+ return subscribeToExistingCoValue(this, options, listener);
1214
+ }
1215
+ /**
1216
+ * Wait for the `CoFeed` to be uploaded to the other peers.
1217
+ *
1218
+ * @category Subscription & Loading
1219
+ */
1220
+ waitForSync(options) {
1221
+ return this._raw.core.waitForSync(options);
1222
+ }
1223
+ };
1224
+ _CoFeed.prototype._type = "CoStream";
1225
+ var CoFeed = _CoFeed;
1226
+ function entryFromRawEntry(accessFrom, rawEntry, loadedAs, accountID, itemField) {
1227
+ return {
1228
+ get value() {
1229
+ if (itemField === "json") {
1230
+ return rawEntry.value;
1231
+ } else if ("encoded" in itemField) {
1232
+ return itemField.encoded.decode(rawEntry.value);
1233
+ } else if (isRefEncoded(itemField)) {
1234
+ return accessChildById(
1235
+ accessFrom,
1236
+ rawEntry.value,
1237
+ itemField
1238
+ );
1239
+ } else {
1240
+ throw new Error("Invalid item field schema");
1241
+ }
1242
+ },
1243
+ get ref() {
1244
+ if (itemField !== "json" && isRefEncoded(itemField)) {
1245
+ const rawId = rawEntry.value;
1246
+ return new Ref(
1247
+ rawId,
1248
+ loadedAs,
1249
+ itemField,
1250
+ accessFrom
1251
+ );
1252
+ } else {
1253
+ return void 0;
1254
+ }
1255
+ },
1256
+ get by() {
1257
+ return accountID && accessChildById(accessFrom, accountID, {
1258
+ ref: Account,
1259
+ optional: false
1260
+ });
1261
+ },
1262
+ madeAt: rawEntry.at,
1263
+ tx: rawEntry.tx
1264
+ };
1265
+ }
1266
+ var CoStreamPerAccountProxyHandler = (innerTarget) => ({
1267
+ get(_target, key, receiver) {
1268
+ if (typeof key === "string" && key.startsWith("co_")) {
1269
+ const rawEntry = innerTarget._raw.lastItemBy(key);
1270
+ if (!rawEntry) return;
1271
+ const entry = entryFromRawEntry(
1272
+ receiver,
1273
+ rawEntry,
1274
+ innerTarget._loadedAs,
1275
+ key,
1276
+ innerTarget._schema[ItemsSym]
1277
+ );
1278
+ Object.defineProperty(entry, "all", {
1279
+ get: () => {
1280
+ const allRawEntries = innerTarget._raw.itemsBy(key);
1281
+ return function* () {
1282
+ while (true) {
1283
+ const rawEntry2 = allRawEntries.next();
1284
+ if (rawEntry2.done) return;
1285
+ yield entryFromRawEntry(
1286
+ receiver,
1287
+ rawEntry2.value,
1288
+ innerTarget._loadedAs,
1289
+ key,
1290
+ innerTarget._schema[ItemsSym]
1291
+ );
1292
+ }
1293
+ }();
1294
+ }
1295
+ });
1296
+ return entry;
1297
+ } else {
1298
+ return Reflect.get(innerTarget, key, receiver);
1299
+ }
1300
+ },
1301
+ ownKeys(_target) {
1302
+ return Array.from(innerTarget._raw.accounts());
1303
+ },
1304
+ getOwnPropertyDescriptor(_target, key) {
1305
+ if (typeof key === "string" && key.startsWith("co_")) {
1306
+ return {
1307
+ configurable: true,
1308
+ enumerable: true,
1309
+ writable: false
1310
+ };
1311
+ } else {
1312
+ return Reflect.getOwnPropertyDescriptor(innerTarget, key);
1313
+ }
1314
+ }
1315
+ });
1316
+ var CoStreamPerSessionProxyHandler = (innerTarget, accessFrom) => ({
1317
+ get(_target, key, receiver) {
1318
+ if (typeof key === "string" && key.includes("session")) {
1319
+ const sessionID = key;
1320
+ const rawEntry = innerTarget._raw.lastItemIn(sessionID);
1321
+ if (!rawEntry) return;
1322
+ const by = cojsonInternals2.accountOrAgentIDfromSessionID(sessionID);
1323
+ const entry = entryFromRawEntry(
1324
+ accessFrom,
1325
+ rawEntry,
1326
+ innerTarget._loadedAs,
1327
+ cojsonInternals2.isAccountID(by) ? by : void 0,
1328
+ innerTarget._schema[ItemsSym]
1329
+ );
1330
+ Object.defineProperty(entry, "all", {
1331
+ get: () => {
1332
+ const allRawEntries = innerTarget._raw.itemsIn(sessionID);
1333
+ return function* () {
1334
+ while (true) {
1335
+ const rawEntry2 = allRawEntries.next();
1336
+ if (rawEntry2.done) return;
1337
+ yield entryFromRawEntry(
1338
+ accessFrom,
1339
+ rawEntry2.value,
1340
+ innerTarget._loadedAs,
1341
+ cojsonInternals2.isAccountID(by) ? by : void 0,
1342
+ innerTarget._schema[ItemsSym]
1343
+ );
1344
+ }
1345
+ }();
1346
+ }
1347
+ });
1348
+ return entry;
1349
+ } else {
1350
+ return Reflect.get(innerTarget, key, receiver);
1351
+ }
1352
+ },
1353
+ ownKeys() {
1354
+ return innerTarget._raw.sessions();
1355
+ },
1356
+ getOwnPropertyDescriptor(target, key) {
1357
+ if (typeof key === "string" && key.startsWith("co_")) {
1358
+ return {
1359
+ configurable: true,
1360
+ enumerable: true,
1361
+ writable: false
1362
+ };
1363
+ } else {
1364
+ return Reflect.getOwnPropertyDescriptor(target, key);
1365
+ }
1366
+ }
1367
+ });
1368
+ var FileStream = class extends CoValueBase {
1369
+ constructor(options) {
1370
+ super();
1371
+ let raw;
1372
+ if ("fromRaw" in options) {
1373
+ raw = options.fromRaw;
1374
+ } else {
1375
+ const rawOwner = options.owner._raw;
1376
+ raw = rawOwner.createBinaryStream();
1377
+ }
1378
+ Object.defineProperties(this, {
1379
+ id: {
1380
+ value: raw.id,
1381
+ enumerable: false
1382
+ },
1383
+ _type: { value: "BinaryCoStream", enumerable: false },
1384
+ _raw: { value: raw, enumerable: false }
1385
+ });
1386
+ }
1387
+ /**
1388
+ * Create a new empty `FileStream` instance.
1389
+ *
1390
+ * @param options - Configuration options for the new FileStream
1391
+ * @param options.owner - The Account or Group that will own this FileStream and control access rights
1392
+ *
1393
+ * @example
1394
+ * ```typescript
1395
+ * // Create owned by an account
1396
+ * const stream = FileStream.create({ owner: myAccount });
1397
+ *
1398
+ * // Create owned by a group
1399
+ * const stream = FileStream.create({ owner: teamGroup });
1400
+ *
1401
+ * // Create with implicit owner
1402
+ * const stream = FileStream.create(myAccount);
1403
+ * ```
1404
+ *
1405
+ * @remarks
1406
+ * For uploading an existing file or blob, use {@link FileStream.createFromBlob} instead.
1407
+ *
1408
+ * @category Creation
1409
+ */
1410
+ static create(options) {
1411
+ return new this(parseCoValueCreateOptions(options));
1412
+ }
1413
+ getMetadata() {
1414
+ return this._raw.getBinaryStreamInfo();
1415
+ }
1416
+ getChunks(options) {
1417
+ return this._raw.getBinaryChunks(options?.allowUnfinished);
1418
+ }
1419
+ isBinaryStreamEnded() {
1420
+ return this._raw.isBinaryStreamEnded();
1421
+ }
1422
+ start(options) {
1423
+ this._raw.startBinaryStream(options);
1424
+ }
1425
+ push(data) {
1426
+ this._raw.pushBinaryStreamChunk(data);
1427
+ }
1428
+ end() {
1429
+ this._raw.endBinaryStream();
1430
+ }
1431
+ toBlob(options) {
1432
+ const chunks = this.getChunks({
1433
+ allowUnfinished: options?.allowUnfinished
1434
+ });
1435
+ if (!chunks) {
1436
+ return void 0;
1437
+ }
1438
+ return new Blob(chunks.chunks, { type: chunks.mimeType });
1439
+ }
1440
+ /**
1441
+ * Load a `FileStream` as a `Blob`
1442
+ *
1443
+ * @category Content
1444
+ */
1445
+ static async loadAsBlob(id, options) {
1446
+ let stream = await this.load(id, options);
1447
+ return stream?.toBlob({
1448
+ allowUnfinished: options?.allowUnfinished
1449
+ });
1450
+ }
1451
+ /**
1452
+ * Create a `FileStream` from a `Blob` or `File`
1453
+ *
1454
+ * @example
1455
+ * ```ts
1456
+ * import { coField, FileStream } from "jazz-tools";
1457
+ *
1458
+ * const fileStream = await FileStream.createFromBlob(file, {owner: group})
1459
+ * ```
1460
+ * @category Content
1461
+ */
1462
+ static async createFromBlob(blob, options) {
1463
+ const stream = this.create(options);
1464
+ const onProgress = options && "onProgress" in options ? options.onProgress : void 0;
1465
+ const start = Date.now();
1466
+ const data = new Uint8Array(await blob.arrayBuffer());
1467
+ stream.start({
1468
+ mimeType: blob.type,
1469
+ totalSizeBytes: blob.size,
1470
+ fileName: blob instanceof File ? blob.name : void 0
1471
+ });
1472
+ const chunkSize = MAX_RECOMMENDED_TX_SIZE;
1473
+ let lastProgressUpdate = Date.now();
1474
+ for (let idx = 0; idx < data.length; idx += chunkSize) {
1475
+ stream.push(data.slice(idx, idx + chunkSize));
1476
+ if (Date.now() - lastProgressUpdate > 100) {
1477
+ onProgress?.(idx / data.length);
1478
+ lastProgressUpdate = Date.now();
1479
+ }
1480
+ await new Promise((resolve) => setTimeout(resolve, 0));
1481
+ }
1482
+ stream.end();
1483
+ const end = Date.now();
1484
+ console.debug(
1485
+ "Finished creating binary stream in",
1486
+ (end - start) / 1e3,
1487
+ "s - Throughput in MB/s",
1488
+ 1e3 * (blob.size / (end - start)) / (1024 * 1024)
1489
+ );
1490
+ onProgress?.(1);
1491
+ return stream;
1492
+ }
1493
+ /**
1494
+ * Get a JSON representation of the `FileStream`
1495
+ * @category Content
1496
+ */
1497
+ toJSON() {
1498
+ return {
1499
+ id: this.id,
1500
+ _type: this._type,
1501
+ ...this.getChunks()
1502
+ };
1503
+ }
1504
+ /** @internal */
1505
+ [inspect]() {
1506
+ return this.toJSON();
1507
+ }
1508
+ /**
1509
+ * Load a `FileStream`
1510
+ * @category Subscription & Loading
1511
+ */
1512
+ static async load(id, options) {
1513
+ const stream = await loadCoValueWithoutMe(this, id, options);
1514
+ if (!options?.allowUnfinished && !stream?.isBinaryStreamEnded()) {
1515
+ return new Promise((resolve) => {
1516
+ subscribeToCoValueWithoutMe(
1517
+ this,
1518
+ id,
1519
+ options || {},
1520
+ (value, unsubscribe) => {
1521
+ if (value.isBinaryStreamEnded()) {
1522
+ unsubscribe();
1523
+ resolve(value);
1524
+ }
1525
+ }
1526
+ );
1527
+ });
1528
+ }
1529
+ return stream;
1530
+ }
1531
+ static subscribe(id, ...args) {
1532
+ const { options, listener } = parseSubscribeRestArgs(args);
1533
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1534
+ }
1535
+ /**
1536
+ * An instance method to subscribe to an existing `FileStream`
1537
+ * @category Subscription & Loading
1538
+ */
1539
+ subscribe(listener) {
1540
+ return subscribeToExistingCoValue(this, {}, listener);
1541
+ }
1542
+ /**
1543
+ * Wait for the `FileStream` to be uploaded to the other peers.
1544
+ *
1545
+ * @category Subscription & Loading
1546
+ */
1547
+ waitForSync(options) {
1548
+ return this._raw.core.waitForSync(options);
1549
+ }
1550
+ };
1551
+
1552
+ // src/tools/coValues/account.ts
1553
+ import {
1554
+ ControlledAccount as ControlledAccount3,
1555
+ LocalNode,
1556
+ cojsonInternals as cojsonInternals3
1557
+ } from "cojson";
1558
+ var _Account = class _Account extends CoValueBase {
1559
+ get _schema() {
1560
+ return this.constructor._schema;
1561
+ }
1562
+ get _owner() {
1563
+ return this;
1564
+ }
1565
+ get _loadedAs() {
1566
+ if (this.isLocalNodeOwner) return this;
1567
+ const agent = this._raw.core.node.getCurrentAgent();
1568
+ if (agent instanceof ControlledAccount3) {
1569
+ return coValuesCache.get(
1570
+ agent.account,
1571
+ () => _Account.fromRaw(agent.account)
1572
+ );
1573
+ }
1574
+ return new AnonymousJazzAgent(this._raw.core.node);
1575
+ }
1576
+ getDescriptor(key) {
1577
+ if (key === "profile") {
1578
+ return this._schema.profile;
1579
+ } else if (key === "root") {
1580
+ return this._schema.root;
1581
+ }
1582
+ return void 0;
1583
+ }
1584
+ get _refs() {
1585
+ const profileID = this._raw.get("profile");
1586
+ const rootID = this._raw.get("root");
1587
+ return {
1588
+ profile: profileID ? new Ref(
1589
+ profileID,
1590
+ this._loadedAs,
1591
+ this._schema.profile,
1592
+ this
1593
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1594
+ ) : void 0,
1595
+ root: rootID ? new Ref(
1596
+ rootID,
1597
+ this._loadedAs,
1598
+ this._schema.root,
1599
+ this
1600
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1601
+ ) : void 0
1602
+ };
1603
+ }
1604
+ /**
1605
+ * Whether this account is the currently active account.
1606
+ */
1607
+ get isMe() {
1608
+ return activeAccountContext.get().id === this.id;
1609
+ }
1610
+ constructor(options) {
1611
+ super();
1612
+ if (!("fromRaw" in options)) {
1613
+ throw new Error("Can only construct account from raw or with .create()");
1614
+ }
1615
+ this.isLocalNodeOwner = options.fromRaw.id == options.fromRaw.core.node.getCurrentAgent().id;
1616
+ Object.defineProperties(this, {
1617
+ id: {
1618
+ value: options.fromRaw.id,
1619
+ enumerable: false
1620
+ },
1621
+ _raw: { value: options.fromRaw, enumerable: false },
1622
+ _type: { value: "Account", enumerable: false }
1623
+ });
1624
+ if (this.isLocalNodeOwner) {
1625
+ this.sessionID = options.fromRaw.core.node.currentSessionID;
1626
+ }
1627
+ return new Proxy(this, AccountAndGroupProxyHandler);
1628
+ }
1629
+ myRole() {
1630
+ if (this.isLocalNodeOwner) {
1631
+ return "admin";
1632
+ }
1633
+ }
1634
+ getRoleOf(member) {
1635
+ if (member === "me") {
1636
+ return this.isMe ? "admin" : void 0;
1637
+ }
1638
+ if (member === this.id) {
1639
+ return "admin";
1640
+ }
1641
+ return void 0;
1642
+ }
1643
+ getParentGroups() {
1644
+ return [];
1645
+ }
1646
+ get members() {
1647
+ const ref2 = new Ref(
1648
+ this.id,
1649
+ this._loadedAs,
1650
+ {
1651
+ ref: () => this.constructor,
1652
+ optional: false
1653
+ },
1654
+ this
1655
+ );
1656
+ return [{ id: this.id, role: "admin", ref: ref2, account: this }];
1657
+ }
1658
+ canRead(value) {
1659
+ const role = value._owner.getRoleOf(this.id);
1660
+ return role === "admin" || role === "writer" || role === "reader" || role === "writeOnly";
1661
+ }
1662
+ canWrite(value) {
1663
+ const role = value._owner.getRoleOf(this.id);
1664
+ return role === "admin" || role === "writer" || role === "writeOnly";
1665
+ }
1666
+ canAdmin(value) {
1667
+ return value._owner.getRoleOf(this.id) === "admin";
1668
+ }
1669
+ async acceptInvite(valueID, inviteSecret, coValueClass) {
1670
+ if (!this.isLocalNodeOwner) {
1671
+ throw new Error("Only a controlled account can accept invites");
1672
+ }
1673
+ await this._raw.core.node.acceptInvite(
1674
+ valueID,
1675
+ inviteSecret
1676
+ );
1677
+ return loadCoValue(anySchemaToCoSchema(coValueClass), valueID, {
1678
+ loadAs: this
1679
+ });
1680
+ }
1681
+ /** @private */
1682
+ static async create(options) {
1683
+ const { node } = await LocalNode.withNewlyCreatedAccount({
1684
+ ...options,
1685
+ migration: async (rawAccount, _node, creationProps) => {
1686
+ const account = new this({
1687
+ fromRaw: rawAccount
1688
+ });
1689
+ await account.applyMigration?.(creationProps);
1690
+ }
1691
+ });
1692
+ return this.fromNode(node);
1693
+ }
1694
+ static getMe() {
1695
+ return activeAccountContext.get();
1696
+ }
1697
+ static async createAs(as, options) {
1698
+ const connectedPeers = cojsonInternals3.connectedPeers(
1699
+ "creatingAccount",
1700
+ "createdAccount",
1701
+ { peer1role: "server", peer2role: "client" }
1702
+ );
1703
+ as._raw.core.node.syncManager.addPeer(connectedPeers[1]);
1704
+ const account = await this.create({
1705
+ creationProps: options.creationProps,
1706
+ crypto: as._raw.core.node.crypto,
1707
+ peersToLoadFrom: [connectedPeers[0]]
1708
+ });
1709
+ await account.waitForAllCoValuesSync();
1710
+ return account;
1711
+ }
1712
+ static fromNode(node) {
1713
+ return new this({
1714
+ fromRaw: node.expectCurrentAccount("jazz-tools/Account.fromNode")
1715
+ });
1716
+ }
1717
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1718
+ toJSON() {
1719
+ return {
1720
+ id: this.id,
1721
+ _type: this._type
1722
+ };
1723
+ }
1724
+ [inspect]() {
1725
+ return this.toJSON();
1726
+ }
1727
+ async applyMigration(creationProps) {
1728
+ await this.migrate(creationProps);
1729
+ if (this.profile === void 0 && creationProps) {
1730
+ const profileGroup = RegisteredSchemas["Group"].create({ owner: this });
1731
+ this.profile = Profile.create({ name: creationProps.name }, profileGroup);
1732
+ profileGroup.addMember("everyone", "reader");
1733
+ } else if (this.profile && creationProps) {
1734
+ if (this.profile._owner._type !== "Group") {
1735
+ throw new Error("Profile must be owned by a Group", {
1736
+ cause: `The profile of the account "${this.id}" was created with an Account as owner, which is not allowed.`
1737
+ });
1738
+ }
1739
+ }
1740
+ const node = this._raw.core.node;
1741
+ const profile = node.expectCoValueLoaded(this._raw.get("profile")).getCurrentContent();
1742
+ if (!profile.get("inbox")) {
1743
+ const inboxRoot = createInboxRoot(this);
1744
+ profile.set("inbox", inboxRoot.id);
1745
+ profile.set("inboxInvite", inboxRoot.inviteLink);
1746
+ }
1747
+ }
1748
+ // Placeholder method for subclasses to override
1749
+ migrate(creationProps) {
1750
+ creationProps;
1751
+ }
1752
+ /** @category Subscription & Loading */
1753
+ static load(id, options) {
1754
+ return loadCoValueWithoutMe(this, id, options);
1755
+ }
1756
+ static subscribe(id, ...args) {
1757
+ const { options, listener } = parseSubscribeRestArgs(args);
1758
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1759
+ }
1760
+ /** @category Subscription & Loading */
1761
+ ensureLoaded(options) {
1762
+ return ensureCoValueLoaded(this, options);
1763
+ }
1764
+ subscribe(...args) {
1765
+ const { options, listener } = parseSubscribeRestArgs(args);
1766
+ return subscribeToExistingCoValue(this, options, listener);
1767
+ }
1768
+ /**
1769
+ * Wait for the `Account` to be uploaded to the other peers.
1770
+ *
1771
+ * @category Subscription & Loading
1772
+ */
1773
+ waitForSync(options) {
1774
+ return this._raw.core.waitForSync(options);
1775
+ }
1776
+ /**
1777
+ * Wait for all the available `CoValues` to be uploaded to the other peers.
1778
+ *
1779
+ * @category Subscription & Loading
1780
+ */
1781
+ waitForAllCoValuesSync(options) {
1782
+ return this._raw.core.node.syncManager.waitForAllCoValuesSync(
1783
+ options?.timeout
1784
+ );
1785
+ }
1786
+ };
1787
+ _Account._schema = {
1788
+ profile: {
1789
+ ref: () => Profile,
1790
+ optional: false
1791
+ },
1792
+ root: {
1793
+ ref: () => RegisteredSchemas["CoMap"],
1794
+ optional: true
1795
+ }
1796
+ };
1797
+ var Account = _Account;
1798
+ var AccountAndGroupProxyHandler = {
1799
+ get(target, key, receiver) {
1800
+ if (key === "profile" || key === "root") {
1801
+ const id = target._raw.get(key);
1802
+ if (id) {
1803
+ return accessChildByKey(target, id, key);
1804
+ } else {
1805
+ return void 0;
1806
+ }
1807
+ } else {
1808
+ return Reflect.get(target, key, receiver);
1809
+ }
1810
+ },
1811
+ set(target, key, value, receiver) {
1812
+ if ((key === "profile" || key === "root") && typeof value === "object" && SchemaInit in value) {
1813
+ target.constructor._schema ||= {};
1814
+ target.constructor._schema[key] = value[SchemaInit];
1815
+ return true;
1816
+ } else if (key === "profile") {
1817
+ if (value) {
1818
+ target._raw.set(
1819
+ "profile",
1820
+ value.id,
1821
+ "trusting"
1822
+ );
1823
+ }
1824
+ return true;
1825
+ } else if (key === "root") {
1826
+ if (value) {
1827
+ target._raw.set("root", value.id);
1828
+ }
1829
+ return true;
1830
+ } else {
1831
+ return Reflect.set(target, key, value, receiver);
1832
+ }
1833
+ },
1834
+ defineProperty(target, key, descriptor) {
1835
+ if ((key === "profile" || key === "root") && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
1836
+ target.constructor._schema ||= {};
1837
+ target.constructor._schema[key] = descriptor.value[SchemaInit];
1838
+ return true;
1839
+ } else {
1840
+ return Reflect.defineProperty(target, key, descriptor);
1841
+ }
1842
+ }
1843
+ };
1844
+ function isControlledAccount(account) {
1845
+ return account.isLocalNodeOwner;
1846
+ }
1847
+ RegisteredSchemas["Account"] = Account;
1848
+
1849
+ // src/tools/coValues/group.ts
1850
+ var _Group = class _Group extends CoValueBase {
1851
+ get _schema() {
1852
+ return this.constructor._schema;
1853
+ }
1854
+ get _refs() {
1855
+ const profileID = this._raw.get("profile");
1856
+ const rootID = this._raw.get("root");
1857
+ return {
1858
+ profile: profileID ? new Ref(
1859
+ profileID,
1860
+ this._loadedAs,
1861
+ this._schema.profile,
1862
+ this
1863
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1864
+ ) : void 0,
1865
+ root: rootID ? new Ref(
1866
+ rootID,
1867
+ this._loadedAs,
1868
+ this._schema.root,
1869
+ this
1870
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1871
+ ) : void 0
1872
+ };
1873
+ }
1874
+ /** @deprecated Don't use constructor directly, use .create */
1875
+ constructor(options) {
1876
+ super();
1877
+ let raw;
1878
+ if (options && "fromRaw" in options) {
1879
+ raw = options.fromRaw;
1880
+ } else {
1881
+ const initOwner = options.owner;
1882
+ if (!initOwner) throw new Error("No owner provided");
1883
+ if (initOwner._type === "Account" && isControlledAccount(initOwner)) {
1884
+ const rawOwner = initOwner._raw;
1885
+ raw = rawOwner.core.node.createGroup();
1886
+ } else {
1887
+ throw new Error("Can only construct group as a controlled account");
1888
+ }
1889
+ }
1890
+ Object.defineProperties(this, {
1891
+ id: {
1892
+ value: raw.id,
1893
+ enumerable: false
1894
+ },
1895
+ _raw: { value: raw, enumerable: false }
1896
+ });
1897
+ return new Proxy(this, AccountAndGroupProxyHandler);
1898
+ }
1899
+ static create(options) {
1900
+ return new this(parseGroupCreateOptions(options));
1901
+ }
1902
+ myRole() {
1903
+ return this._raw.myRole();
1904
+ }
1905
+ addMember(member, role) {
1906
+ if (member !== "everyone" && member._type === "Group") {
1907
+ if (role === "writeOnly")
1908
+ throw new Error("Cannot add group as member with write-only role");
1909
+ this._raw.extend(member._raw, role);
1910
+ } else if (role !== void 0 && role !== "inherit") {
1911
+ this._raw.addMember(member === "everyone" ? member : member._raw, role);
1912
+ }
1913
+ }
1914
+ removeMember(member) {
1915
+ if (member !== "everyone" && member._type === "Group") {
1916
+ return this._raw.revokeExtend(member._raw);
1917
+ } else {
1918
+ return this._raw.removeMember(
1919
+ member === "everyone" ? member : member._raw
1920
+ );
1921
+ }
1922
+ }
1923
+ get members() {
1924
+ const members = [];
1925
+ const refEncodedAccountSchema = {
1926
+ ref: () => Account,
1927
+ optional: false
1928
+ };
1929
+ for (const accountID of this._raw.getAllMemberKeysSet()) {
1930
+ if (!isAccountID(accountID)) continue;
1931
+ const role = this._raw.roleOf(accountID);
1932
+ if (role === "admin" || role === "writer" || role === "reader" || role === "writeOnly") {
1933
+ const ref2 = new Ref(
1934
+ accountID,
1935
+ this._loadedAs,
1936
+ refEncodedAccountSchema,
1937
+ this
1938
+ );
1939
+ const group = this;
1940
+ members.push({
1941
+ id: accountID,
1942
+ role,
1943
+ ref: ref2,
1944
+ get account() {
1945
+ return accessChildById(group, accountID, refEncodedAccountSchema);
1946
+ }
1947
+ });
1948
+ }
1949
+ }
1950
+ return members;
1951
+ }
1952
+ getRoleOf(member) {
1953
+ if (member === "me") {
1954
+ return this._raw.roleOf(
1955
+ activeAccountContext.get().id
1956
+ );
1957
+ }
1958
+ return this._raw.roleOf(
1959
+ member === "everyone" ? member : member
1960
+ );
1961
+ }
1962
+ /**
1963
+ * Make the group public, so that everyone can read it.
1964
+ * Alias for `addMember("everyone", role)`.
1965
+ *
1966
+ * @param role - Optional: the role to grant to everyone. Defaults to "reader".
1967
+ * @returns The group itself.
1968
+ */
1969
+ makePublic(role = "reader") {
1970
+ this.addMember("everyone", role);
1971
+ return this;
1972
+ }
1973
+ getParentGroups() {
1974
+ return this._raw.getParentGroups().map((group) => _Group.fromRaw(group));
1975
+ }
1976
+ /** @category Identity & Permissions
1977
+ * Gives members of a parent group membership in this group.
1978
+ * @deprecated Use `addMember` instead.
1979
+ * @param parent The group that will gain access to this group.
1980
+ * @param roleMapping The role all members of the parent group should have in this group.
1981
+ * @returns This group.
1982
+ */
1983
+ extend(parent, roleMapping) {
1984
+ this._raw.extend(parent._raw, roleMapping);
1985
+ return this;
1986
+ }
1987
+ /** @category Identity & Permissions
1988
+ * Revokes membership from members a parent group.
1989
+ * @deprecated Use `removeMember` instead.
1990
+ * @param parent The group that will lose access to this group.
1991
+ * @returns This group.
1992
+ */
1993
+ async revokeExtend(parent) {
1994
+ await this._raw.revokeExtend(parent._raw);
1995
+ return this;
1996
+ }
1997
+ /** @category Subscription & Loading */
1998
+ static load(id, options) {
1999
+ return loadCoValueWithoutMe(this, id, options);
2000
+ }
2001
+ static subscribe(id, ...args) {
2002
+ const { options, listener } = parseSubscribeRestArgs(args);
2003
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2004
+ }
2005
+ /** @category Subscription & Loading */
2006
+ ensureLoaded(options) {
2007
+ return ensureCoValueLoaded(this, options);
2008
+ }
2009
+ subscribe(...args) {
2010
+ const { options, listener } = parseSubscribeRestArgs(args);
2011
+ return subscribeToExistingCoValue(this, options, listener);
2012
+ }
2013
+ /**
2014
+ * Wait for the `Group` to be uploaded to the other peers.
2015
+ *
2016
+ * @category Subscription & Loading
2017
+ */
2018
+ waitForSync(options) {
2019
+ return this._raw.core.waitForSync(options);
2020
+ }
2021
+ };
2022
+ _Group.prototype._type = "Group";
2023
+ _Group._schema = {
2024
+ profile: "json",
2025
+ root: "json"
2026
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2027
+ };
2028
+ Object.defineProperty(_Group.prototype, "_schema", {
2029
+ get: () => _Group._schema
2030
+ });
2031
+ var Group = _Group;
2032
+ RegisteredSchemas["Group"] = Group;
2033
+ function isAccountID(id) {
2034
+ return id.startsWith("co_");
2035
+ }
2036
+
2037
+ // src/tools/coValues/profile.ts
2038
+ var Profile = class extends CoMap {
2039
+ constructor() {
2040
+ super(...arguments);
2041
+ this.name = coField.string;
2042
+ this.inbox = coField.optional.string;
2043
+ this.inboxInvite = coField.optional.string;
2044
+ }
2045
+ /**
2046
+ * Creates a new profile with the given initial values and owner.
2047
+ *
2048
+ * The owner (a Group) determines access rights to the Profile.
2049
+ *
2050
+ * @category Creation
2051
+ */
2052
+ static create(init, options) {
2053
+ const owner = options !== void 0 && "owner" in options ? options.owner : options;
2054
+ if (owner?._type === "Account") {
2055
+ throw new Error("Profiles should be owned by a group");
2056
+ }
2057
+ return super.create(init, options);
2058
+ }
2059
+ };
2060
+
2061
+ // src/tools/coValues/inbox.ts
2062
+ import { RawAccount as RawAccount4 } from "cojson";
2063
+ function createInboxRoot(account) {
2064
+ if (!account.isLocalNodeOwner) {
2065
+ throw new Error("Account is not controlled");
2066
+ }
2067
+ const rawAccount = account._raw;
2068
+ const group = rawAccount.core.node.createGroup();
2069
+ const messagesFeed = group.createStream();
2070
+ const inboxRoot = rawAccount.createMap();
2071
+ const processedFeed = rawAccount.createStream();
2072
+ const failedFeed = rawAccount.createStream();
2073
+ const inviteLink = `${messagesFeed.id}/${group.createInvite("writeOnly")}`;
2074
+ inboxRoot.set("messages", messagesFeed.id);
2075
+ inboxRoot.set("processed", processedFeed.id);
2076
+ inboxRoot.set("failed", failedFeed.id);
2077
+ return {
2078
+ id: inboxRoot.id,
2079
+ inviteLink
2080
+ };
2081
+ }
2082
+ async function createInboxMessage(payload, inboxOwner) {
2083
+ const group = payload._raw.group;
2084
+ if (group instanceof RawAccount4) {
2085
+ throw new Error("Inbox messages should be owned by a group");
2086
+ }
2087
+ group.addMember(inboxOwner, "writer");
2088
+ const message = group.createMap({
2089
+ payload: payload.id,
2090
+ result: void 0,
2091
+ processed: false,
2092
+ error: void 0
2093
+ });
2094
+ await payload._raw.core.waitForSync();
2095
+ await message.core.waitForSync();
2096
+ return message;
2097
+ }
2098
+ var Inbox = class _Inbox {
2099
+ constructor(account, root, messages, processed, failed) {
2100
+ this.processing = /* @__PURE__ */ new Set();
2101
+ this.account = account;
2102
+ this.root = root;
2103
+ this.messages = messages;
2104
+ this.processed = processed;
2105
+ this.failed = failed;
2106
+ }
2107
+ subscribe(Schema, callback, options = {}) {
2108
+ const processed = /* @__PURE__ */ new Set();
2109
+ const failed = /* @__PURE__ */ new Map();
2110
+ const node = this.account._raw.core.node;
2111
+ this.processed.subscribe((stream) => {
2112
+ for (const items of Object.values(stream.items)) {
2113
+ for (const item of items) {
2114
+ processed.add(item.value);
2115
+ }
2116
+ }
2117
+ });
2118
+ const { account } = this;
2119
+ const { retries = 3 } = options;
2120
+ let failTimer = void 0;
2121
+ const clearFailTimer = () => {
2122
+ clearTimeout(failTimer);
2123
+ failTimer = void 0;
2124
+ };
2125
+ const handleNewMessages = (stream) => {
2126
+ clearFailTimer();
2127
+ for (const [sessionID, items] of Object.entries(stream.items)) {
2128
+ const accountID = getAccountIDfromSessionID(sessionID);
2129
+ if (!accountID) {
2130
+ console.warn("Received message from unknown account", sessionID);
2131
+ continue;
2132
+ }
2133
+ for (const item of items) {
2134
+ const txKey = `${sessionID}/${item.tx.txIndex}`;
2135
+ if (!processed.has(txKey) && !this.processing.has(txKey)) {
2136
+ this.processing.add(txKey);
2137
+ const id = item.value;
2138
+ node.load(id).then((message) => {
2139
+ if (message === "unavailable") {
2140
+ return Promise.reject(
2141
+ new Error("Unable to load inbox message " + id)
2142
+ );
2143
+ }
2144
+ return loadCoValue(
2145
+ anySchemaToCoSchema(Schema),
2146
+ message.get("payload"),
2147
+ {
2148
+ loadAs: account
2149
+ }
2150
+ );
2151
+ }).then((value) => {
2152
+ if (!value) {
2153
+ return Promise.reject(
2154
+ new Error("Unable to load inbox message " + id)
2155
+ );
2156
+ }
2157
+ return callback(value, accountID);
2158
+ }).then((result) => {
2159
+ const inboxMessage = node.expectCoValueLoaded(item.value).getCurrentContent();
2160
+ if (result) {
2161
+ inboxMessage.set("result", result.id);
2162
+ }
2163
+ inboxMessage.set("processed", true);
2164
+ this.processed.push(txKey);
2165
+ this.processing.delete(txKey);
2166
+ }).catch((error) => {
2167
+ console.error("Error processing inbox message", error);
2168
+ this.processing.delete(txKey);
2169
+ const errors = failed.get(txKey) ?? [];
2170
+ const stringifiedError = String(error);
2171
+ errors.push(stringifiedError);
2172
+ let inboxMessage;
2173
+ try {
2174
+ inboxMessage = node.expectCoValueLoaded(item.value).getCurrentContent();
2175
+ inboxMessage.set("error", stringifiedError);
2176
+ } catch (error2) {
2177
+ }
2178
+ if (errors.length > retries) {
2179
+ inboxMessage?.set("processed", true);
2180
+ this.processed.push(txKey);
2181
+ this.failed.push({ errors, value: item.value });
2182
+ } else {
2183
+ failed.set(txKey, errors);
2184
+ if (!failTimer) {
2185
+ failTimer = setTimeout(
2186
+ () => handleNewMessages(stream),
2187
+ 100
2188
+ );
2189
+ }
2190
+ }
2191
+ });
2192
+ }
2193
+ }
2194
+ }
2195
+ };
2196
+ const unsubscribe = this.messages.subscribe(handleNewMessages);
2197
+ return () => {
2198
+ unsubscribe();
2199
+ clearFailTimer();
2200
+ };
2201
+ }
2202
+ static async load(account) {
2203
+ const profile = account.profile;
2204
+ if (!profile) {
2205
+ throw new Error("Account profile should already be loaded");
2206
+ }
2207
+ if (!profile.inbox) {
2208
+ throw new Error("The account has not set up their inbox");
2209
+ }
2210
+ const node = account._raw.core.node;
2211
+ const root = await node.load(profile.inbox);
2212
+ if (root === "unavailable") {
2213
+ throw new Error("Inbox not found");
2214
+ }
2215
+ const [messages, processed, failed] = await Promise.all([
2216
+ node.load(root.get("messages")),
2217
+ node.load(root.get("processed")),
2218
+ node.load(root.get("failed"))
2219
+ ]);
2220
+ if (messages === "unavailable" || processed === "unavailable" || failed === "unavailable") {
2221
+ throw new Error("Inbox not found");
2222
+ }
2223
+ return new _Inbox(account, root, messages, processed, failed);
2224
+ }
2225
+ };
2226
+ var InboxSender = class _InboxSender {
2227
+ constructor(currentAccount, owner, messages) {
2228
+ this.currentAccount = currentAccount;
2229
+ this.owner = owner;
2230
+ this.messages = messages;
2231
+ }
2232
+ getOwnerAccount() {
2233
+ return this.owner;
2234
+ }
2235
+ async sendMessage(message) {
2236
+ const inboxMessage = await createInboxMessage(message, this.owner);
2237
+ this.messages.push(inboxMessage.id);
2238
+ return new Promise((resolve, reject) => {
2239
+ inboxMessage.subscribe((message2) => {
2240
+ if (message2.get("processed")) {
2241
+ const error = message2.get("error");
2242
+ if (error) {
2243
+ reject(new Error(error));
2244
+ } else {
2245
+ resolve(
2246
+ message2.get("result")
2247
+ );
2248
+ }
2249
+ }
2250
+ });
2251
+ });
2252
+ }
2253
+ static async load(inboxOwnerID, currentAccount) {
2254
+ currentAccount ||= activeAccountContext.get();
2255
+ const node = currentAccount._raw.core.node;
2256
+ const inboxOwnerRaw = await node.load(
2257
+ inboxOwnerID
2258
+ );
2259
+ if (inboxOwnerRaw === "unavailable") {
2260
+ throw new Error("Failed to load the inbox owner");
2261
+ }
2262
+ const inboxOwnerProfileRaw = await node.load(inboxOwnerRaw.get("profile"));
2263
+ if (inboxOwnerProfileRaw === "unavailable") {
2264
+ throw new Error("Failed to load the inbox owner profile");
2265
+ }
2266
+ if (inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "reader" && inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "writer" && inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "admin") {
2267
+ throw new Error(
2268
+ "Insufficient permissions to access the inbox, make sure its user profile is publicly readable."
2269
+ );
2270
+ }
2271
+ const inboxInvite = inboxOwnerProfileRaw.get("inboxInvite");
2272
+ if (!inboxInvite) {
2273
+ throw new Error("The user has not set up their inbox");
2274
+ }
2275
+ const id = await acceptInvite(inboxInvite, currentAccount);
2276
+ const messages = await node.load(id);
2277
+ if (messages === "unavailable") {
2278
+ throw new Error("Inbox not found");
2279
+ }
2280
+ return new _InboxSender(currentAccount, inboxOwnerRaw, messages);
2281
+ }
2282
+ };
2283
+ async function acceptInvite(invite, account) {
2284
+ account ||= activeAccountContext.get();
2285
+ const id = invite.slice(0, invite.indexOf("/"));
2286
+ const inviteSecret = invite.slice(invite.indexOf("/") + 1);
2287
+ if (!id?.startsWith("co_z") || !inviteSecret.startsWith("inviteSecret_")) {
2288
+ throw new Error("Invalid inbox ticket");
2289
+ }
2290
+ if (!account.isLocalNodeOwner) {
2291
+ throw new Error("Account is not controlled");
2292
+ }
2293
+ await account._raw.core.node.acceptInvite(id, inviteSecret);
2294
+ return id;
2295
+ }
2296
+ function getAccountIDfromSessionID(sessionID) {
2297
+ const until = sessionID.indexOf("_session");
2298
+ const accountID = sessionID.slice(0, until);
2299
+ if (accountID.startsWith("co_z")) {
2300
+ return accountID;
2301
+ }
2302
+ return;
2303
+ }
2304
+
2305
+ // src/tools/coValues/coPlainText.ts
2306
+ import {
2307
+ ControlledAccount as ControlledAccount4,
2308
+ RawAccount as RawAccount5,
2309
+ stringifyOpID
2310
+ } from "cojson";
2311
+ import { calcPatch as calcPatch2 } from "fast-myers-diff";
2312
+
2313
+ // src/tools/lib/cache.ts
2314
+ var weakMap = /* @__PURE__ */ new WeakMap();
2315
+ var coValuesCache = {
2316
+ get: (raw, compute) => {
2317
+ const cached = weakMap.get(raw);
2318
+ if (cached) {
2319
+ return cached;
2320
+ }
2321
+ const computed = compute();
2322
+ weakMap.set(raw, computed);
2323
+ return computed;
2324
+ }
2325
+ };
2326
+
2327
+ // src/tools/coValues/coPlainText.ts
2328
+ var CoPlainText = class extends String {
2329
+ get _owner() {
2330
+ return this._raw.group instanceof RawAccount5 ? Account.fromRaw(this._raw.group) : Group.fromRaw(this._raw.group);
2331
+ }
2332
+ get _loadedAs() {
2333
+ const agent = this._raw.core.node.getCurrentAgent();
2334
+ if (agent instanceof ControlledAccount4) {
2335
+ return coValuesCache.get(
2336
+ agent.account,
2337
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
2338
+ agent.account
2339
+ )
2340
+ );
2341
+ }
2342
+ return new AnonymousJazzAgent(this._raw.core.node);
2343
+ }
2344
+ /** @internal */
2345
+ constructor(options) {
2346
+ if (!options) {
2347
+ super("");
2348
+ return;
2349
+ }
2350
+ if ("fromRaw" in options) {
2351
+ super(options.fromRaw.toString());
2352
+ const raw = options.fromRaw;
2353
+ Object.defineProperties(this, {
2354
+ id: { value: raw.id, enumerable: false },
2355
+ _type: { value: "CoPlainText", enumerable: false },
2356
+ _raw: { value: raw, enumerable: false }
2357
+ });
2358
+ return;
2359
+ }
2360
+ if ("text" in options && "owner" in options) {
2361
+ super(options.text);
2362
+ const raw = options.owner._raw.createPlainText(options.text);
2363
+ Object.defineProperties(this, {
2364
+ id: { value: raw.id, enumerable: false },
2365
+ _type: { value: "CoPlainText", enumerable: false },
2366
+ _raw: { value: raw, enumerable: false }
2367
+ });
2368
+ return;
2369
+ }
2370
+ throw new Error("Invalid constructor arguments");
2371
+ }
2372
+ /**
2373
+ * Create a new `CoPlainText` with the given text and owner.
2374
+ *
2375
+ * The owner (a Group or Account) determines access rights to the CoPlainText.
2376
+ *
2377
+ * The CoPlainText will immediately be persisted and synced to connected peers.
2378
+ *
2379
+ * @example
2380
+ * ```ts
2381
+ * const text = CoPlainText.create("Hello, world!", { owner: me });
2382
+ * ```
2383
+ *
2384
+ * @category Creation
2385
+ */
2386
+ static create(text, options) {
2387
+ const { owner } = parseCoValueCreateOptions(options);
2388
+ return new this({ text, owner });
2389
+ }
2390
+ get length() {
2391
+ return this._raw.toString().length;
2392
+ }
2393
+ toString() {
2394
+ return this._raw.toString();
2395
+ }
2396
+ valueOf() {
2397
+ return this._raw.toString();
2398
+ }
2399
+ toJSON() {
2400
+ return this._raw.toString();
2401
+ }
2402
+ [inspect]() {
2403
+ return this.toJSON();
2404
+ }
2405
+ insertBefore(idx, text) {
2406
+ this._raw.insertBefore(idx, text);
2407
+ }
2408
+ insertAfter(idx, text) {
2409
+ this._raw.insertAfter(idx, text);
2410
+ }
2411
+ deleteRange(range) {
2412
+ this._raw.deleteRange(range);
2413
+ }
2414
+ posBefore(idx) {
2415
+ return this._raw.mapping.opIDbeforeIdx[idx];
2416
+ }
2417
+ posAfter(idx) {
2418
+ return this._raw.mapping.opIDafterIdx[idx];
2419
+ }
2420
+ idxBefore(pos) {
2421
+ return this._raw.mapping.idxBeforeOpID[stringifyOpID(pos)];
2422
+ }
2423
+ idxAfter(pos) {
2424
+ return this._raw.mapping.idxAfterOpID[stringifyOpID(pos)];
2425
+ }
2426
+ static fromRaw(raw) {
2427
+ return new this({ fromRaw: raw });
2428
+ }
2429
+ /**
2430
+ * Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
2431
+ *
2432
+ * @category Mutation
2433
+ */
2434
+ applyDiff(other) {
2435
+ const current = this._raw.toString();
2436
+ const currentGraphemes = this._raw.toGraphemes(current);
2437
+ const otherGraphemes = this._raw.toGraphemes(other);
2438
+ const patches = [...calcPatch2(currentGraphemes, otherGraphemes)];
2439
+ for (const [from, to, insert] of patches.reverse()) {
2440
+ if (to > from) {
2441
+ this.deleteRange({ from, to });
2442
+ }
2443
+ if (insert.length > 0) {
2444
+ this.insertBefore(from, this._raw.fromGraphemes(insert));
2445
+ }
2446
+ }
2447
+ }
2448
+ /**
2449
+ * Load a `CoPlainText` with a given ID, as a given account.
2450
+ *
2451
+ * @category Subscription & Loading
2452
+ */
2453
+ static load(id, options) {
2454
+ return loadCoValueWithoutMe(this, id, options);
2455
+ }
2456
+ static subscribe(id, ...args) {
2457
+ const { options, listener } = parseSubscribeRestArgs(args);
2458
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2459
+ }
2460
+ /**
2461
+ * Given an already loaded `CoPlainText`, subscribe to updates to the `CoPlainText` and ensure that the specified fields are loaded to the specified depth.
2462
+ *
2463
+ * Works like `CoPlainText.subscribe()`, but you don't need to pass the ID or the account to load as again.
2464
+ *
2465
+ * Returns an unsubscribe function that you should call when you no longer need updates.
2466
+ *
2467
+ * @category Subscription & Loading
2468
+ **/
2469
+ subscribe(listener) {
2470
+ return subscribeToExistingCoValue(this, {}, listener);
2471
+ }
2472
+ /**
2473
+ * Allow CoPlainText to behave like a primitive string in most contexts (e.g.,
2474
+ * string concatenation, template literals, React rendering, etc.) by implementing
2475
+ * Symbol.toPrimitive. This eliminates the need to call .toString() explicitly.
2476
+ *
2477
+ * The 'hint' parameter indicates the preferred type of conversion:
2478
+ * - 'string': prefer string conversion
2479
+ * - 'number': prefer number conversion (attempt to parse the text as a number)
2480
+ * - 'default': usually treat as string
2481
+ */
2482
+ [Symbol.toPrimitive](hint) {
2483
+ if (hint === "number") {
2484
+ return Number(this._raw.toString());
2485
+ }
2486
+ return this._raw.toString();
2487
+ }
2488
+ };
2489
+
2490
+ // src/tools/coValues/coRichText.ts
2491
+ var CoRichText = class extends CoPlainText {
2492
+ };
2493
+
2494
+ // src/tools/coValues/schemaUnion.ts
2495
+ var SchemaUnion = class _SchemaUnion extends CoValueBase {
2496
+ /**
2497
+ * Create a new union type from a discriminator function.
2498
+ *
2499
+ * The discriminator function receives the raw data and should return the appropriate concrete class to use for that data.
2500
+ *
2501
+ * When loading a SchemaUnion, the correct subclass will be instantiated based on the discriminator.
2502
+ *
2503
+ * @param discriminator - Function that determines which concrete type to use
2504
+ * @returns A new class that can create/load instances of the union type
2505
+ *
2506
+ * @example
2507
+ * ```ts
2508
+ * const WidgetUnion = SchemaUnion.Of<BaseWidget>((raw) => {
2509
+ * switch (raw.get("type")) {
2510
+ * case "button": return ButtonWidget;
2511
+ * case "slider": return SliderWidget;
2512
+ * default: throw new Error("Unknown widget type");
2513
+ * }
2514
+ * });
2515
+ *
2516
+ * const widget = await loadCoValue(WidgetUnion, id, me, {});
2517
+ *
2518
+ * // You can narrow the returned instance to a subclass by using `instanceof`
2519
+ * if (widget instanceof ButtonWidget) {
2520
+ * console.log(widget.label);
2521
+ * } else if (widget instanceof SliderWidget) {
2522
+ * console.log(widget.min, widget.max);
2523
+ * }
2524
+ * ```
2525
+ *
2526
+ * @category Declaration
2527
+ **/
2528
+ static Of(discriminator) {
2529
+ return class SchemaUnionClass extends _SchemaUnion {
2530
+ static fromRaw(raw) {
2531
+ const ResolvedClass = discriminator(
2532
+ raw
2533
+ );
2534
+ return ResolvedClass.fromRaw(raw);
2535
+ }
2536
+ };
2537
+ }
2538
+ /**
2539
+ * Create an instance from raw data. This is called internally and should not be used directly.
2540
+ * Use {@link SchemaUnion.Of} to create a union type instead.
2541
+ *
2542
+ * @internal
2543
+ */
2544
+ // @ts-ignore
2545
+ static fromRaw(raw) {
2546
+ throw new Error("Not implemented");
2547
+ }
2548
+ };
2549
+
2550
+ // src/tools/implementation/anonymousJazzAgent.ts
2551
+ var AnonymousJazzAgent = class {
2552
+ constructor(node) {
2553
+ this.node = node;
2554
+ this._type = "Anonymous";
2555
+ }
2556
+ };
2557
+
2558
+ // src/tools/implementation/activeAccountContext.ts
2559
+ var ActiveAccountContext = class {
2560
+ constructor() {
2561
+ this.activeAccount = null;
2562
+ this.guestMode = false;
2563
+ }
2564
+ set(account) {
2565
+ this.activeAccount = account;
2566
+ this.guestMode = false;
2567
+ }
2568
+ setGuestMode() {
2569
+ this.activeAccount = null;
2570
+ this.guestMode = true;
2571
+ }
2572
+ maybeGet() {
2573
+ return this.activeAccount;
2574
+ }
2575
+ get() {
2576
+ if (!this.activeAccount) {
2577
+ if (this.guestMode) {
2578
+ throw new Error(
2579
+ "Something that expects a full active account was called in guest mode."
2580
+ );
2581
+ }
2582
+ throw new Error("No active account");
2583
+ }
2584
+ return this.activeAccount;
2585
+ }
2586
+ };
2587
+ var activeAccountContext = new ActiveAccountContext();
2588
+
2589
+ // src/tools/implementation/refs.ts
2590
+ var Ref = class {
2591
+ constructor(id, controlledAccount, schema, parent) {
2592
+ this.id = id;
2593
+ this.controlledAccount = controlledAccount;
2594
+ this.schema = schema;
2595
+ this.parent = parent;
2596
+ if (!isRefEncoded(schema)) {
2597
+ throw new Error("Ref must be constructed with a ref schema");
2598
+ }
2599
+ }
2600
+ async load() {
2601
+ const subscriptionScope = getSubscriptionScope(this.parent);
2602
+ subscriptionScope.subscribeToId(this.id, this.schema);
2603
+ const node = subscriptionScope.childNodes.get(this.id);
2604
+ if (!node) {
2605
+ return null;
2606
+ }
2607
+ const value = node.value;
2608
+ if (value?.type === "loaded") {
2609
+ return value.value;
2610
+ } else {
2611
+ return new Promise((resolve) => {
2612
+ const unsubscribe = node.subscribe((value2) => {
2613
+ if (value2?.type === "loaded") {
2614
+ unsubscribe();
2615
+ resolve(value2.value);
2616
+ } else if (value2?.type === "unavailable") {
2617
+ unsubscribe();
2618
+ resolve(null);
2619
+ } else if (value2?.type === "unauthorized") {
2620
+ unsubscribe();
2621
+ resolve(null);
2622
+ }
2623
+ });
2624
+ });
2625
+ }
2626
+ }
2627
+ get value() {
2628
+ return accessChildById(this.parent, this.id, this.schema);
2629
+ }
2630
+ };
2631
+ function makeRefs(parent, getIdForKey, getKeysWithIds, controlledAccount, refSchemaForKey) {
2632
+ const refs = {};
2633
+ return new Proxy(refs, {
2634
+ get(_target, key) {
2635
+ if (key === Symbol.iterator) {
2636
+ return function* () {
2637
+ for (const key2 of getKeysWithIds()) {
2638
+ yield new Ref(
2639
+ getIdForKey(key2),
2640
+ controlledAccount,
2641
+ refSchemaForKey(key2),
2642
+ parent
2643
+ );
2644
+ }
2645
+ };
2646
+ }
2647
+ if (typeof key === "symbol") return void 0;
2648
+ if (key === "length") {
2649
+ return getKeysWithIds().length;
2650
+ }
2651
+ const id = getIdForKey(key);
2652
+ if (!id) return void 0;
2653
+ return new Ref(
2654
+ id,
2655
+ controlledAccount,
2656
+ refSchemaForKey(key),
2657
+ parent
2658
+ );
2659
+ },
2660
+ ownKeys() {
2661
+ return getKeysWithIds().map((key) => key.toString());
2662
+ },
2663
+ getOwnPropertyDescriptor(target, key) {
2664
+ const id = getIdForKey(key);
2665
+ if (id) {
2666
+ return {
2667
+ enumerable: true,
2668
+ configurable: true,
2669
+ writable: true
2670
+ };
2671
+ } else {
2672
+ return Reflect.getOwnPropertyDescriptor(target, key);
2673
+ }
2674
+ }
2675
+ });
2676
+ }
2677
+
2678
+ // src/tools/implementation/schema.ts
2679
+ var Encoders = {
2680
+ Date: {
2681
+ encode: (value) => value.toISOString(),
2682
+ decode: (value) => new Date(value)
2683
+ },
2684
+ OptionalDate: {
2685
+ encode: (value) => value?.toISOString() || null,
2686
+ decode: (value) => value === null ? void 0 : new Date(value)
2687
+ }
2688
+ };
2689
+ var optional2 = {
2690
+ ref: optionalRef,
2691
+ json() {
2692
+ return { [SchemaInit]: "json" };
2693
+ },
2694
+ encoded(arg) {
2695
+ return { [SchemaInit]: { encoded: arg } };
2696
+ },
2697
+ string: {
2698
+ [SchemaInit]: "json"
2699
+ },
2700
+ number: {
2701
+ [SchemaInit]: "json"
2702
+ },
2703
+ boolean: {
2704
+ [SchemaInit]: "json"
2705
+ },
2706
+ null: {
2707
+ [SchemaInit]: "json"
2708
+ },
2709
+ Date: {
2710
+ [SchemaInit]: { encoded: Encoders.OptionalDate }
2711
+ },
2712
+ literal(..._lit) {
2713
+ return { [SchemaInit]: "json" };
2714
+ }
2715
+ };
2716
+ var coField = {
2717
+ string: {
2718
+ [SchemaInit]: "json"
2719
+ },
2720
+ number: {
2721
+ [SchemaInit]: "json"
2722
+ },
2723
+ boolean: {
2724
+ [SchemaInit]: "json"
2725
+ },
2726
+ null: {
2727
+ [SchemaInit]: "json"
2728
+ },
2729
+ Date: {
2730
+ [SchemaInit]: { encoded: Encoders.Date }
2731
+ },
2732
+ literal(..._lit) {
2733
+ return { [SchemaInit]: "json" };
2734
+ },
2735
+ json() {
2736
+ return { [SchemaInit]: "json" };
2737
+ },
2738
+ encoded(arg) {
2739
+ return { [SchemaInit]: { encoded: arg } };
2740
+ },
2741
+ ref,
2742
+ items: ItemsSym,
2743
+ optional: optional2
2744
+ };
2745
+ function optionalRef(arg) {
2746
+ return ref(arg, { optional: true });
2747
+ }
2748
+ function ref(arg, options) {
2749
+ return {
2750
+ [SchemaInit]: {
2751
+ ref: arg,
2752
+ optional: options?.optional || false
2753
+ }
2754
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2755
+ };
2756
+ }
2757
+ function isRefEncoded(schema) {
2758
+ return typeof schema === "object" && "ref" in schema && "optional" in schema && typeof schema.ref === "function";
2759
+ }
2760
+ function instantiateRefEncoded(schema, raw) {
2761
+ return isCoValueClass(schema.ref) ? schema.ref.fromRaw(raw) : schema.ref(
2762
+ raw
2763
+ ).fromRaw(raw);
2764
+ }
2765
+
2766
+ // src/tools/lib/migration.ts
2767
+ function applyCoValueMigrations(instance) {
2768
+ const node = instance._raw.core.node;
2769
+ const migratedCoValues = node._migratedCoValues ??= /* @__PURE__ */ new Set();
2770
+ if ("migrate" in instance && typeof instance.migrate === "function" && instance._type !== "Account" && !migratedCoValues.has(instance.id)) {
2771
+ migratedCoValues.add(instance.id);
2772
+ const result = instance.migrate?.(instance);
2773
+ if (result && "then" in result) {
2774
+ throw new Error("Migration function cannot be async");
2775
+ }
2776
+ }
2777
+ }
2778
+
2779
+ // src/tools/subscribe/CoValueCoreSubscription.ts
2780
+ var CoValueCoreSubscription = class {
2781
+ constructor(node, id, listener) {
2782
+ this.node = node;
2783
+ this.id = id;
2784
+ this.listener = listener;
2785
+ this._unsubscribe = () => {
2786
+ };
2787
+ this.unsubscribed = false;
2788
+ const entry = this.node.getCoValue(this.id);
2789
+ if (entry?.isAvailable()) {
2790
+ this.subscribe(entry.getCurrentContent());
2791
+ } else {
2792
+ this.node.loadCoValueCore(this.id).then((value) => {
2793
+ if (this.unsubscribed) return;
2794
+ if (value.isAvailable()) {
2795
+ this.subscribe(value.getCurrentContent());
2796
+ } else {
2797
+ this.listener("unavailable");
2798
+ this.subscribeToState();
2799
+ }
2800
+ });
2801
+ }
2802
+ }
2803
+ subscribeToState() {
2804
+ const entry = this.node.getCoValue(this.id);
2805
+ const handleStateChange = (core, unsubFromStateChange2) => {
2806
+ if (this.unsubscribed) {
2807
+ unsubFromStateChange2();
2808
+ return;
2809
+ }
2810
+ if (core.isAvailable()) {
2811
+ this.subscribe(core.getCurrentContent());
2812
+ unsubFromStateChange2();
2813
+ }
2814
+ };
2815
+ const unsubFromStateChange = entry.subscribe(handleStateChange);
2816
+ this._unsubscribe = () => {
2817
+ unsubFromStateChange();
2818
+ };
2819
+ }
2820
+ subscribe(value) {
2821
+ if (this.unsubscribed) return;
2822
+ this._unsubscribe = value.subscribe((value2) => {
2823
+ this.listener(value2);
2824
+ });
2825
+ this.listener(value);
2826
+ }
2827
+ unsubscribe() {
2828
+ if (this.unsubscribed) return;
2829
+ this.unsubscribed = true;
2830
+ this._unsubscribe();
2831
+ }
2832
+ };
2833
+
2834
+ // src/tools/subscribe/JazzError.ts
2835
+ var JazzError = class _JazzError {
2836
+ constructor(id, type, issues) {
2837
+ this.id = id;
2838
+ this.type = type;
2839
+ this.issues = issues;
2840
+ }
2841
+ toString() {
2842
+ return this.issues.map((issue) => {
2843
+ let message = `${issue.message}`;
2844
+ if (this.id) {
2845
+ message += ` from ${this.id}`;
2846
+ }
2847
+ if (issue.path.length > 0) {
2848
+ message += ` on path ${issue.path.join(".")}`;
2849
+ }
2850
+ return message;
2851
+ }).join("\n");
2852
+ }
2853
+ prependPath(item) {
2854
+ if (this.issues.length === 0) {
2855
+ return this;
2856
+ }
2857
+ const issues = this.issues.map((issue) => {
2858
+ return {
2859
+ ...issue,
2860
+ path: [item].concat(issue.path)
2861
+ };
2862
+ });
2863
+ return new _JazzError(this.id, this.type, issues);
2864
+ }
2865
+ };
2866
+
2867
+ // src/tools/subscribe/utils.ts
2868
+ import { RawAccount as RawAccount6 } from "cojson";
2869
+ function getOwnerFromRawValue(raw) {
2870
+ const owner = raw.group;
2871
+ return coValuesCache.get(
2872
+ owner,
2873
+ () => owner instanceof RawAccount6 ? anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(owner) : RegisteredSchemas["Group"].fromRaw(owner)
2874
+ );
2875
+ }
2876
+ function createCoValue(ref2, raw, subscriptionScope) {
2877
+ const freshValueInstance = instantiateRefEncoded(ref2, raw);
2878
+ Object.defineProperty(freshValueInstance, "_subscriptionScope", {
2879
+ value: subscriptionScope,
2880
+ writable: false,
2881
+ enumerable: false,
2882
+ configurable: false
2883
+ });
2884
+ return {
2885
+ type: "loaded",
2886
+ value: freshValueInstance,
2887
+ id: subscriptionScope.id
2888
+ };
2889
+ }
2890
+
2891
+ // src/tools/subscribe/SubscriptionScope.ts
2892
+ var SubscriptionScope = class _SubscriptionScope {
2893
+ constructor(node, resolve, id, schema) {
2894
+ this.node = node;
2895
+ this.id = id;
2896
+ this.schema = schema;
2897
+ this.childNodes = /* @__PURE__ */ new Map();
2898
+ this.childValues = /* @__PURE__ */ new Map();
2899
+ this.childErrors = /* @__PURE__ */ new Map();
2900
+ this.validationErrors = /* @__PURE__ */ new Map();
2901
+ this.dirty = false;
2902
+ this.idsSubscribed = /* @__PURE__ */ new Set();
2903
+ this.autoloaded = /* @__PURE__ */ new Set();
2904
+ this.autoloadedKeys = /* @__PURE__ */ new Set();
2905
+ this.skipInvalidKeys = /* @__PURE__ */ new Set();
2906
+ this.totalValidTransactions = 0;
2907
+ this.migrated = false;
2908
+ this.migrating = false;
2909
+ this.silenceUpdates = false;
2910
+ this.handleChildUpdate = (id, value, key) => {
2911
+ if (value.type === "unloaded") {
2912
+ return;
2913
+ }
2914
+ this.childValues.set(id, value);
2915
+ if (value.type === "unavailable" || value.type === "unauthorized") {
2916
+ this.childErrors.set(id, value.prependPath(key ?? id));
2917
+ this.errorFromChildren = this.computeChildErrors();
2918
+ } else if (this.errorFromChildren && this.childErrors.has(id)) {
2919
+ this.childErrors.delete(id);
2920
+ this.errorFromChildren = this.computeChildErrors();
2921
+ }
2922
+ if (this.shouldSendUpdates()) {
2923
+ if (this.value.type === "loaded") {
2924
+ this.updateValue(
2925
+ createCoValue(this.schema, this.value.value._raw, this)
2926
+ );
2927
+ }
2928
+ }
2929
+ this.triggerUpdate();
2930
+ };
2931
+ this.subscribers = /* @__PURE__ */ new Set();
2932
+ this.resolve = resolve;
2933
+ this.value = { type: "unloaded", id };
2934
+ let lastUpdate;
2935
+ this.subscription = new CoValueCoreSubscription(node, id, (value) => {
2936
+ lastUpdate = value;
2937
+ if (!this.migrated && value !== "unavailable") {
2938
+ if (this.migrating) {
2939
+ return;
2940
+ }
2941
+ this.migrating = true;
2942
+ applyCoValueMigrations(instantiateRefEncoded(this.schema, value));
2943
+ this.migrated = true;
2944
+ this.handleUpdate(lastUpdate);
2945
+ return;
2946
+ }
2947
+ this.handleUpdate(value);
2948
+ });
2949
+ }
2950
+ updateValue(value) {
2951
+ this.value = value;
2952
+ this.dirty = true;
2953
+ }
2954
+ handleUpdate(update) {
2955
+ if (update === "unavailable") {
2956
+ if (this.value.type === "unloaded") {
2957
+ this.updateValue(
2958
+ new JazzError(this.id, "unavailable", [
2959
+ {
2960
+ code: "unavailable",
2961
+ message: "The value is unavailable",
2962
+ params: {
2963
+ id: this.id
2964
+ },
2965
+ path: []
2966
+ }
2967
+ ])
2968
+ );
2969
+ }
2970
+ this.triggerUpdate();
2971
+ return;
2972
+ }
2973
+ const ruleset = update.core.verified.header.ruleset;
2974
+ const hasAccess = ruleset.type !== "ownedByGroup" || getOwnerFromRawValue(update).myRole() !== void 0;
2975
+ if (!hasAccess) {
2976
+ if (this.value.type !== "unauthorized") {
2977
+ this.updateValue(
2978
+ new JazzError(this.id, "unauthorized", [
2979
+ {
2980
+ code: "unauthorized",
2981
+ message: "The current user is not authorized to access this value",
2982
+ params: {
2983
+ id: this.id
2984
+ },
2985
+ path: []
2986
+ }
2987
+ ])
2988
+ );
2989
+ this.triggerUpdate();
2990
+ }
2991
+ return;
2992
+ }
2993
+ this.silenceUpdates = true;
2994
+ if (this.value.type !== "loaded") {
2995
+ this.updateValue(createCoValue(this.schema, update, this));
2996
+ this.loadChildren();
2997
+ } else {
2998
+ const hasChanged = update.totalValidTransactions !== this.totalValidTransactions || // Checking the identity of the _raw value makes us cover the cases where the group
2999
+ // has been updated and the coValues that don't update the totalValidTransactions value (e.g. FileStream)
3000
+ this.value.value._raw !== update;
3001
+ if (this.loadChildren()) {
3002
+ this.updateValue(createCoValue(this.schema, update, this));
3003
+ } else if (hasChanged) {
3004
+ this.updateValue(createCoValue(this.schema, update, this));
3005
+ }
3006
+ }
3007
+ this.totalValidTransactions = update.totalValidTransactions;
3008
+ this.silenceUpdates = false;
3009
+ this.triggerUpdate();
3010
+ }
3011
+ computeChildErrors() {
3012
+ let issues = [];
3013
+ let errorType = "unavailable";
3014
+ if (this.childErrors.size === 0 && this.validationErrors.size === 0) {
3015
+ return void 0;
3016
+ }
3017
+ for (const [key, value] of this.childErrors.entries()) {
3018
+ if (this.autoloaded.has(key)) {
3019
+ continue;
3020
+ }
3021
+ if (this.skipInvalidKeys.has(key)) {
3022
+ continue;
3023
+ }
3024
+ errorType = value.type;
3025
+ if (value.issues) {
3026
+ issues.push(...value.issues);
3027
+ }
3028
+ }
3029
+ for (const [key, value] of this.validationErrors.entries()) {
3030
+ if (this.skipInvalidKeys.has(key)) {
3031
+ continue;
3032
+ }
3033
+ errorType = value.type;
3034
+ if (value.issues) {
3035
+ issues.push(...value.issues);
3036
+ }
3037
+ }
3038
+ if (issues.length) {
3039
+ return new JazzError(this.id, errorType, issues);
3040
+ }
3041
+ return void 0;
3042
+ }
3043
+ shouldSendUpdates() {
3044
+ if (this.value.type === "unloaded") return false;
3045
+ if (this.value.type !== "loaded") return true;
3046
+ for (const value of this.childValues.values()) {
3047
+ if (value.type === "unloaded" && !this.autoloaded.has(value.id)) {
3048
+ return false;
3049
+ }
3050
+ }
3051
+ return true;
3052
+ }
3053
+ getCurrentValue() {
3054
+ if (this.value.type === "unauthorized" || this.value.type === "unavailable") {
3055
+ console.error(this.value.toString());
3056
+ return null;
3057
+ }
3058
+ if (!this.shouldSendUpdates()) {
3059
+ return void 0;
3060
+ }
3061
+ if (this.errorFromChildren) {
3062
+ console.error(this.errorFromChildren.toString());
3063
+ return null;
3064
+ }
3065
+ if (this.value.type === "loaded") {
3066
+ return this.value.value;
3067
+ }
3068
+ return void 0;
3069
+ }
3070
+ triggerUpdate() {
3071
+ if (!this.shouldSendUpdates()) return;
3072
+ if (!this.dirty) return;
3073
+ if (this.subscribers.size === 0) return;
3074
+ if (this.silenceUpdates) return;
3075
+ const error = this.errorFromChildren;
3076
+ const value = this.value;
3077
+ if (error) {
3078
+ this.subscribers.forEach((listener) => listener(error));
3079
+ } else if (value.type !== "unloaded") {
3080
+ this.subscribers.forEach((listener) => listener(value));
3081
+ }
3082
+ this.dirty = false;
3083
+ }
3084
+ subscribe(listener) {
3085
+ this.subscribers.add(listener);
3086
+ return () => {
3087
+ this.subscribers.delete(listener);
3088
+ };
3089
+ }
3090
+ setListener(listener) {
3091
+ this.subscribers.add(listener);
3092
+ this.triggerUpdate();
3093
+ }
3094
+ subscribeToKey(key) {
3095
+ if (this.resolve === true || !this.resolve) {
3096
+ this.resolve = {};
3097
+ }
3098
+ if (this.resolve.$each || key in this.resolve) {
3099
+ return;
3100
+ }
3101
+ const resolve = this.resolve;
3102
+ resolve[key] = true;
3103
+ this.autoloadedKeys.add(key);
3104
+ if (this.value.type !== "loaded") {
3105
+ return;
3106
+ }
3107
+ const value = this.value.value;
3108
+ this.silenceUpdates = true;
3109
+ if (value._type === "CoMap" || value._type === "Account") {
3110
+ const map = value;
3111
+ this.loadCoMapKey(map, key, true);
3112
+ } else if (value._type === "CoList") {
3113
+ const list = value;
3114
+ this.loadCoListKey(list, key, true);
3115
+ }
3116
+ this.silenceUpdates = false;
3117
+ }
3118
+ subscribeToId(id, descriptor) {
3119
+ if (this.idsSubscribed.has(id) || this.childValues.has(id)) {
3120
+ return;
3121
+ }
3122
+ this.idsSubscribed.add(id);
3123
+ this.autoloaded.add(id);
3124
+ this.silenceUpdates = true;
3125
+ this.childValues.set(id, { type: "unloaded", id });
3126
+ const child = new _SubscriptionScope(
3127
+ this.node,
3128
+ true,
3129
+ id,
3130
+ descriptor
3131
+ );
3132
+ this.childNodes.set(id, child);
3133
+ child.setListener((value) => this.handleChildUpdate(id, value));
3134
+ this.silenceUpdates = false;
3135
+ }
3136
+ loadChildren() {
3137
+ const { resolve } = this;
3138
+ if (this.value.type !== "loaded") {
3139
+ return false;
3140
+ }
3141
+ const value = this.value.value;
3142
+ const depth = typeof resolve !== "object" || resolve === null ? {} : resolve;
3143
+ let hasChanged = false;
3144
+ const idsToLoad = new Set(this.idsSubscribed);
3145
+ const coValueType = value._type;
3146
+ if (Object.keys(depth).length > 0) {
3147
+ if (coValueType === "CoMap" || coValueType === "Account") {
3148
+ const map = value;
3149
+ const keys = "$each" in depth ? map._raw.keys() : Object.keys(depth);
3150
+ for (const key of keys) {
3151
+ const id = this.loadCoMapKey(map, key, depth[key] ?? depth.$each);
3152
+ if (id) {
3153
+ idsToLoad.add(id);
3154
+ }
3155
+ }
3156
+ } else if (value._type === "CoList") {
3157
+ const list = value;
3158
+ const descriptor = list.getItemsDescriptor();
3159
+ if (descriptor && isRefEncoded(descriptor)) {
3160
+ list._raw.processNewTransactions();
3161
+ const entries = list._raw.entries();
3162
+ const keys = "$each" in depth ? Object.keys(entries) : Object.keys(depth);
3163
+ for (const key of keys) {
3164
+ const id = this.loadCoListKey(list, key, depth[key] ?? depth.$each);
3165
+ if (id) {
3166
+ idsToLoad.add(id);
3167
+ }
3168
+ }
3169
+ }
3170
+ } else if (value._type === "CoStream") {
3171
+ const stream = value;
3172
+ const descriptor = stream.getItemsDescriptor();
3173
+ if (descriptor && isRefEncoded(descriptor)) {
3174
+ for (const session of stream._raw.sessions()) {
3175
+ const values = stream._raw.items[session] ?? [];
3176
+ for (const [i, item] of values.entries()) {
3177
+ const key = `${session}/${i}`;
3178
+ if (!depth.$each && !depth[key]) {
3179
+ continue;
3180
+ }
3181
+ const id = item.value;
3182
+ if (id) {
3183
+ idsToLoad.add(id);
3184
+ this.loadChildNode(id, depth[key] ?? depth.$each, descriptor);
3185
+ this.validationErrors.delete(key);
3186
+ } else if (!descriptor.optional) {
3187
+ this.validationErrors.set(
3188
+ key,
3189
+ new JazzError(void 0, "unavailable", [
3190
+ {
3191
+ code: "validationError",
3192
+ message: `The ref on position ${key} requested on ${stream.constructor.name} is missing`,
3193
+ params: {},
3194
+ path: [key]
3195
+ }
3196
+ ])
3197
+ );
3198
+ }
3199
+ }
3200
+ }
3201
+ }
3202
+ }
3203
+ }
3204
+ this.errorFromChildren = this.computeChildErrors();
3205
+ for (const id of this.childNodes.keys()) {
3206
+ if (!idsToLoad.has(id)) {
3207
+ hasChanged = true;
3208
+ const childNode = this.childNodes.get(id);
3209
+ if (childNode) {
3210
+ childNode.destroy();
3211
+ }
3212
+ this.childNodes.delete(id);
3213
+ this.childValues.delete(id);
3214
+ }
3215
+ }
3216
+ return hasChanged;
3217
+ }
3218
+ loadCoMapKey(map, key, depth) {
3219
+ if (key === "$onError") {
3220
+ return void 0;
3221
+ }
3222
+ const id = map._raw.get(key);
3223
+ const descriptor = map.getDescriptor(key);
3224
+ if (!descriptor) {
3225
+ this.childErrors.set(
3226
+ key,
3227
+ new JazzError(void 0, "unavailable", [
3228
+ {
3229
+ code: "validationError",
3230
+ message: `The ref ${key} requested on ${map.constructor.name} is not defined in the schema`,
3231
+ params: {},
3232
+ path: [key]
3233
+ }
3234
+ ])
3235
+ );
3236
+ return void 0;
3237
+ }
3238
+ if (isRefEncoded(descriptor)) {
3239
+ if (id) {
3240
+ this.loadChildNode(id, depth, descriptor, key);
3241
+ this.validationErrors.delete(key);
3242
+ return id;
3243
+ } else if (!descriptor.optional) {
3244
+ this.validationErrors.set(
3245
+ key,
3246
+ new JazzError(void 0, "unavailable", [
3247
+ {
3248
+ code: "validationError",
3249
+ message: `The ref ${key} requested on ${map.constructor.name} is missing`,
3250
+ params: {},
3251
+ path: [key]
3252
+ }
3253
+ ])
3254
+ );
3255
+ }
3256
+ }
3257
+ return void 0;
3258
+ }
3259
+ loadCoListKey(list, key, depth) {
3260
+ const descriptor = list.getItemsDescriptor();
3261
+ if (!descriptor || !isRefEncoded(descriptor)) {
3262
+ return void 0;
3263
+ }
3264
+ const entries = list._raw.entries();
3265
+ const entry = entries[Number(key)];
3266
+ if (!entry) {
3267
+ return void 0;
3268
+ }
3269
+ const id = entry.value;
3270
+ if (id) {
3271
+ this.loadChildNode(id, depth, descriptor, key);
3272
+ this.validationErrors.delete(key);
3273
+ return id;
3274
+ } else if (!descriptor.optional) {
3275
+ this.validationErrors.set(
3276
+ key,
3277
+ new JazzError(void 0, "unavailable", [
3278
+ {
3279
+ code: "validationError",
3280
+ message: `The ref on position ${key} requested on ${list.constructor.name} is missing`,
3281
+ params: {},
3282
+ path: [key]
3283
+ }
3284
+ ])
3285
+ );
3286
+ }
3287
+ return void 0;
3288
+ }
3289
+ loadChildNode(id, query, descriptor, key) {
3290
+ if (this.childValues.has(id)) {
3291
+ return;
3292
+ }
3293
+ if (key && this.autoloadedKeys.has(key)) {
3294
+ this.autoloaded.add(id);
3295
+ }
3296
+ const skipInvalid = typeof query === "object" && query.$onError === null;
3297
+ if (skipInvalid) {
3298
+ if (key) {
3299
+ this.skipInvalidKeys.add(key);
3300
+ }
3301
+ this.skipInvalidKeys.add(id);
3302
+ }
3303
+ const resolve = typeof query === "object" && query !== null ? { ...query } : query;
3304
+ this.childValues.set(id, { type: "unloaded", id });
3305
+ const child = new _SubscriptionScope(
3306
+ this.node,
3307
+ resolve,
3308
+ id,
3309
+ descriptor
3310
+ );
3311
+ this.childNodes.set(id, child);
3312
+ child.setListener((value) => this.handleChildUpdate(id, value, key));
3313
+ }
3314
+ destroy() {
3315
+ this.subscription.unsubscribe();
3316
+ this.subscribers.clear();
3317
+ this.childNodes.forEach((child) => child.destroy());
3318
+ }
3319
+ };
3320
+
3321
+ // src/tools/subscribe/index.ts
3322
+ function getSubscriptionScope(value) {
3323
+ const subscriptionScope = value._subscriptionScope;
3324
+ if (subscriptionScope) {
3325
+ return subscriptionScope;
3326
+ }
3327
+ const node = value._raw.core.node;
3328
+ const resolve = true;
3329
+ const id = value.id;
3330
+ const newSubscriptionScope = new SubscriptionScope(node, resolve, id, {
3331
+ ref: value.constructor,
3332
+ optional: false
3333
+ });
3334
+ Object.defineProperty(value, "_subscriptionScope", {
3335
+ value: subscriptionScope,
3336
+ writable: false,
3337
+ enumerable: false,
3338
+ configurable: false
3339
+ });
3340
+ return newSubscriptionScope;
3341
+ }
3342
+ function accessChildByKey(parent, childId, key) {
3343
+ const subscriptionScope = getSubscriptionScope(parent);
3344
+ if (!subscriptionScope.childValues.has(childId)) {
3345
+ subscriptionScope.subscribeToKey(key);
3346
+ }
3347
+ const value = subscriptionScope.childValues.get(childId);
3348
+ if (value?.type === "loaded") {
3349
+ return value.value;
3350
+ } else {
3351
+ return null;
3352
+ }
3353
+ }
3354
+ function accessChildById(parent, childId, schema) {
3355
+ const subscriptionScope = getSubscriptionScope(parent);
3356
+ subscriptionScope.subscribeToId(childId, schema);
3357
+ const value = subscriptionScope.childValues.get(childId);
3358
+ if (value?.type === "loaded") {
3359
+ return value.value;
3360
+ } else {
3361
+ return null;
3362
+ }
3363
+ }
3364
+
3365
+ // src/tools/implementation/createContext.ts
3366
+ import {
3367
+ LocalNode as LocalNode2
3368
+ } from "cojson";
3369
+ async function randomSessionProvider(accountID, crypto) {
3370
+ return {
3371
+ sessionID: crypto.newRandomSessionID(accountID),
3372
+ sessionDone: () => {
3373
+ }
3374
+ };
3375
+ }
3376
+ async function createJazzContextFromExistingCredentials({
3377
+ credentials,
3378
+ peersToLoadFrom,
3379
+ crypto,
3380
+ AccountSchema: PropsAccountSchema,
3381
+ sessionProvider,
3382
+ onLogOut
3383
+ }) {
3384
+ const { sessionID, sessionDone } = await sessionProvider(
3385
+ credentials.accountID,
3386
+ crypto
3387
+ );
3388
+ const CurrentAccountSchema = PropsAccountSchema ?? RegisteredSchemas["Account"];
3389
+ const AccountClass = anySchemaToCoSchema(CurrentAccountSchema);
3390
+ const node = await LocalNode2.withLoadedAccount({
3391
+ accountID: credentials.accountID,
3392
+ accountSecret: credentials.secret,
3393
+ sessionID,
3394
+ peersToLoadFrom,
3395
+ crypto,
3396
+ migration: async (rawAccount, _node, creationProps) => {
3397
+ const account2 = AccountClass.fromRaw(rawAccount);
3398
+ activeAccountContext.set(account2);
3399
+ await account2.applyMigration(creationProps);
3400
+ }
3401
+ });
3402
+ const account = AccountClass.fromNode(node);
3403
+ activeAccountContext.set(account);
3404
+ return {
3405
+ node,
3406
+ account,
3407
+ done: () => {
3408
+ node.gracefulShutdown();
3409
+ sessionDone();
3410
+ },
3411
+ logOut: async () => {
3412
+ node.gracefulShutdown();
3413
+ sessionDone();
3414
+ await onLogOut?.();
3415
+ }
3416
+ };
3417
+ }
3418
+ async function createJazzContextForNewAccount({
3419
+ creationProps,
3420
+ initialAgentSecret,
3421
+ peersToLoadFrom,
3422
+ crypto,
3423
+ AccountSchema: PropsAccountSchema,
3424
+ onLogOut
3425
+ }) {
3426
+ const CurrentAccountSchema = PropsAccountSchema ?? RegisteredSchemas["Account"];
3427
+ const AccountClass = anySchemaToCoSchema(CurrentAccountSchema);
3428
+ const { node } = await LocalNode2.withNewlyCreatedAccount({
3429
+ creationProps,
3430
+ peersToLoadFrom,
3431
+ crypto,
3432
+ initialAgentSecret,
3433
+ migration: async (rawAccount, _node, creationProps2) => {
3434
+ const account2 = AccountClass.fromRaw(rawAccount);
3435
+ activeAccountContext.set(account2);
3436
+ await account2.applyMigration(creationProps2);
3437
+ }
3438
+ });
3439
+ const account = AccountClass.fromNode(node);
3440
+ activeAccountContext.set(account);
3441
+ return {
3442
+ node,
3443
+ account,
3444
+ done: () => {
3445
+ node.gracefulShutdown();
3446
+ },
3447
+ logOut: async () => {
3448
+ node.gracefulShutdown();
3449
+ await onLogOut?.();
3450
+ }
3451
+ };
3452
+ }
3453
+ async function createJazzContext(options) {
3454
+ const crypto = options.crypto;
3455
+ let context;
3456
+ const authSecretStorage = options.authSecretStorage;
3457
+ await authSecretStorage.migrate();
3458
+ const credentials = options.credentials ?? await authSecretStorage.get();
3459
+ if (credentials && !options.newAccountProps) {
3460
+ context = await createJazzContextFromExistingCredentials({
3461
+ credentials: {
3462
+ accountID: credentials.accountID,
3463
+ secret: credentials.accountSecret
3464
+ },
3465
+ peersToLoadFrom: options.peersToLoadFrom,
3466
+ crypto,
3467
+ AccountSchema: options.AccountSchema,
3468
+ sessionProvider: options.sessionProvider,
3469
+ onLogOut: () => {
3470
+ authSecretStorage.clearWithoutNotify();
3471
+ }
3472
+ });
3473
+ } else {
3474
+ const secretSeed = options.crypto.newRandomSecretSeed();
3475
+ const initialAgentSecret = options.newAccountProps?.secret ?? crypto.agentSecretFromSecretSeed(secretSeed);
3476
+ const creationProps = options.newAccountProps?.creationProps ?? {
3477
+ name: options.defaultProfileName ?? "Anonymous user"
3478
+ };
3479
+ context = await createJazzContextForNewAccount({
3480
+ creationProps,
3481
+ initialAgentSecret,
3482
+ peersToLoadFrom: options.peersToLoadFrom,
3483
+ crypto,
3484
+ AccountSchema: options.AccountSchema,
3485
+ onLogOut: async () => {
3486
+ await authSecretStorage.clearWithoutNotify();
3487
+ }
3488
+ });
3489
+ if (!options.newAccountProps) {
3490
+ await authSecretStorage.setWithoutNotify({
3491
+ accountID: context.account.id,
3492
+ secretSeed,
3493
+ accountSecret: context.node.getCurrentAgent().agentSecret,
3494
+ provider: "anonymous"
3495
+ });
3496
+ }
3497
+ }
3498
+ return {
3499
+ ...context,
3500
+ authSecretStorage
3501
+ };
3502
+ }
3503
+ function createAnonymousJazzContext({
3504
+ peersToLoadFrom,
3505
+ crypto
3506
+ }) {
3507
+ const agentSecret = crypto.newRandomAgentSecret();
3508
+ const node = new LocalNode2(
3509
+ agentSecret,
3510
+ crypto.newRandomSessionID(crypto.getAgentID(agentSecret)),
3511
+ crypto
3512
+ );
3513
+ for (const peer of peersToLoadFrom) {
3514
+ node.syncManager.addPeer(peer);
3515
+ }
3516
+ activeAccountContext.setGuestMode();
3517
+ return {
3518
+ agent: new AnonymousJazzAgent(node),
3519
+ done: () => {
3520
+ },
3521
+ logOut: async () => {
3522
+ }
3523
+ };
3524
+ }
3525
+
3526
+ // src/tools/implementation/zodSchema/zodSchema.ts
3527
+ function isZodObject(schema) {
3528
+ return schema.def?.type === "object";
3529
+ }
3530
+ function isZodArray(schema) {
3531
+ return schema.def?.type === "array";
3532
+ }
3533
+ function isZodCustom(schema) {
3534
+ return schema.def?.type === "custom";
3535
+ }
3536
+ function getDef(schema) {
3537
+ return schema.def;
3538
+ }
3539
+
3540
+ // src/tools/implementation/zodSchema/zodCo.ts
3541
+ function enrichCoMapSchema(schema) {
3542
+ const baseCatchall = schema.catchall;
3543
+ const enrichedSchema = Object.assign(schema, {
3544
+ collaborative: true,
3545
+ create: (...args) => {
3546
+ return coSchema.create(...args);
3547
+ },
3548
+ load: (...args) => {
3549
+ return coSchema.load(...args);
3550
+ },
3551
+ subscribe: (...args) => {
3552
+ return coSchema.subscribe(...args);
3553
+ },
3554
+ findUnique: (...args) => {
3555
+ return coSchema.findUnique(...args);
3556
+ },
3557
+ catchall: (index) => {
3558
+ return enrichCoMapSchema(baseCatchall(index));
3559
+ },
3560
+ withHelpers: (helpers) => {
3561
+ return Object.assign(schema, helpers(schema));
3562
+ },
3563
+ withMigration: (migration) => {
3564
+ coSchema.prototype.migrate = migration;
3565
+ return enrichedSchema;
3566
+ },
3567
+ getCoSchema: () => {
3568
+ return coSchema;
3569
+ }
3570
+ });
3571
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3572
+ return enrichedSchema;
3573
+ }
3574
+ var coMapDefiner = (shape) => {
3575
+ const objectSchema = z.object(shape).meta({
3576
+ collaborative: true
3577
+ });
3578
+ return enrichCoMapSchema(objectSchema);
3579
+ };
3580
+ function enrichAccountSchema(schema) {
3581
+ const enrichedSchema = Object.assign(schema, {
3582
+ collaborative: true,
3583
+ builtin: "Account",
3584
+ create: (...args) => {
3585
+ return coSchema.create(...args);
3586
+ },
3587
+ createAs: (...args) => {
3588
+ return coSchema.createAs(...args);
3589
+ },
3590
+ getMe: (...args) => {
3591
+ return coSchema.getMe(...args);
3592
+ },
3593
+ load: (...args) => {
3594
+ return coSchema.load(...args);
3595
+ },
3596
+ subscribe: (...args) => {
3597
+ return coSchema.subscribe(...args);
3598
+ },
3599
+ withHelpers: (helpers) => {
3600
+ return Object.assign(schema, helpers(schema));
3601
+ },
3602
+ fromRaw: (...args) => {
3603
+ return coSchema.fromRaw(...args);
3604
+ },
3605
+ withMigration: (migration) => {
3606
+ coSchema.prototype.migrate = async function(creationProps) {
3607
+ await migration(this, creationProps);
3608
+ };
3609
+ return enrichedSchema;
3610
+ },
3611
+ getCoSchema: () => {
3612
+ return coSchema;
3613
+ }
3614
+ });
3615
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3616
+ return enrichedSchema;
3617
+ }
3618
+ var coAccountDefiner = (shape = {
3619
+ profile: coMapDefiner({
3620
+ name: z.string(),
3621
+ inbox: z.optional(z.string()),
3622
+ inboxInvite: z.optional(z.string())
3623
+ }),
3624
+ root: coMapDefiner({})
3625
+ }) => {
3626
+ const objectSchema = z.object(shape).meta({
3627
+ collaborative: true
3628
+ });
3629
+ return enrichAccountSchema(objectSchema);
3630
+ };
3631
+ var coRecordDefiner = (_keyType, valueType) => {
3632
+ return coMapDefiner({}).catchall(valueType);
3633
+ };
3634
+ function enrichCoListSchema(schema) {
3635
+ const enrichedSchema = Object.assign(schema, {
3636
+ collaborative: true,
3637
+ create: (...args) => {
3638
+ return coSchema.create(...args);
3639
+ },
3640
+ load: (...args) => {
3641
+ return coSchema.load(...args);
3642
+ },
3643
+ subscribe: (...args) => {
3644
+ return coSchema.subscribe(...args);
3645
+ },
3646
+ withHelpers: (helpers) => {
3647
+ return Object.assign(schema, helpers(schema));
3648
+ },
3649
+ getCoSchema: () => {
3650
+ return coSchema;
3651
+ }
3652
+ });
3653
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3654
+ return enrichedSchema;
3655
+ }
3656
+ var coListDefiner = (element) => {
3657
+ const arraySchema = z.array(element).meta({
3658
+ collaborative: true
3659
+ });
3660
+ return enrichCoListSchema(arraySchema);
3661
+ };
3662
+ var coProfileDefiner = (shape = {}) => {
3663
+ const ehnancedShape = Object.assign(shape ?? {}, {
3664
+ name: z.string(),
3665
+ inbox: z.optional(z.string()),
3666
+ inboxInvite: z.optional(z.string())
3667
+ });
3668
+ return coMapDefiner(ehnancedShape);
3669
+ };
3670
+ function enrichCoFeedSchema(schema, element) {
3671
+ const enrichedSchema = Object.assign(schema, {
3672
+ collaborative: true,
3673
+ builtin: "CoFeed",
3674
+ element,
3675
+ create: (...args) => {
3676
+ return coSchema.create(...args);
3677
+ },
3678
+ load: (...args) => {
3679
+ return coSchema.load(...args);
3680
+ },
3681
+ subscribe: (...args) => {
3682
+ return coSchema.subscribe(...args);
3683
+ },
3684
+ withHelpers: (helpers) => {
3685
+ return Object.assign(schema, helpers(schema));
3686
+ },
3687
+ getCoSchema: () => {
3688
+ return coSchema;
3689
+ }
3690
+ });
3691
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3692
+ return enrichedSchema;
3693
+ }
3694
+ var coFeedDefiner = (element) => {
3695
+ return enrichCoFeedSchema(z.instanceof(CoFeed), element);
3696
+ };
3697
+ function enrichFileStreamSchema(schema) {
3698
+ const enrichedSchema = Object.assign(schema, {
3699
+ collaborative: true,
3700
+ builtin: "FileStream",
3701
+ create: (...args) => {
3702
+ return coSchema.create(...args);
3703
+ },
3704
+ createFromBlob: (...args) => {
3705
+ return coSchema.createFromBlob(...args);
3706
+ },
3707
+ load: (...args) => {
3708
+ return coSchema.load(...args);
3709
+ },
3710
+ loadAsBlob: (...args) => {
3711
+ return coSchema.loadAsBlob(...args);
3712
+ },
3713
+ subscribe: (...args) => {
3714
+ return coSchema.subscribe(...args);
3715
+ },
3716
+ getCoSchema: () => {
3717
+ return coSchema;
3718
+ }
3719
+ });
3720
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3721
+ return enrichedSchema;
3722
+ }
3723
+ var coFileStreamDefiner = () => {
3724
+ return enrichFileStreamSchema(z.instanceof(FileStream));
3725
+ };
3726
+ function enrichPlainTextSchema(schema) {
3727
+ const enrichedSchema = Object.assign(schema, {
3728
+ collaborative: true,
3729
+ builtin: "CoPlainText",
3730
+ create: (...args) => {
3731
+ return coSchema.create(...args);
3732
+ },
3733
+ load: (...args) => {
3734
+ return coSchema.load(...args);
3735
+ },
3736
+ subscribe: (...args) => {
3737
+ return coSchema.subscribe(...args);
3738
+ },
3739
+ fromRaw: (...args) => {
3740
+ return coSchema.fromRaw(...args);
3741
+ },
3742
+ getCoSchema: () => {
3743
+ return coSchema;
3744
+ }
3745
+ });
3746
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3747
+ return enrichedSchema;
3748
+ }
3749
+ var coPlainTextDefiner = () => {
3750
+ return enrichPlainTextSchema(z.instanceof(CoPlainText));
3751
+ };
3752
+ function enrichRichTextSchema(schema) {
3753
+ const enrichedSchema = Object.assign(schema, {
3754
+ collaborative: true,
3755
+ builtin: "CoRichText",
3756
+ create: (...args) => {
3757
+ return coSchema.create(...args);
3758
+ },
3759
+ load: (...args) => {
3760
+ return coSchema.load(...args);
3761
+ },
3762
+ subscribe: (...args) => {
3763
+ return coSchema.subscribe(...args);
3764
+ },
3765
+ getCoSchema: () => {
3766
+ return coSchema;
3767
+ }
3768
+ });
3769
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3770
+ return enrichedSchema;
3771
+ }
3772
+ var coRichTextDefiner = () => {
3773
+ return enrichRichTextSchema(z.instanceof(CoRichText));
3774
+ };
3775
+ var coImageDefiner = () => {
3776
+ return ImageDefinition;
3777
+ };
3778
+
3779
+ // src/tools/implementation/zodSchema/coExport.ts
3780
+ var coExport_exports = {};
3781
+ __export(coExport_exports, {
3782
+ account: () => coAccountDefiner,
3783
+ feed: () => coFeedDefiner,
3784
+ fileStream: () => coFileStreamDefiner,
3785
+ image: () => coImageDefiner,
3786
+ list: () => coListDefiner,
3787
+ map: () => coMapDefiner,
3788
+ plainText: () => coPlainTextDefiner,
3789
+ profile: () => coProfileDefiner,
3790
+ record: () => coRecordDefiner,
3791
+ richText: () => coRichTextDefiner
3792
+ });
3793
+
3794
+ // src/tools/implementation/zodSchema/unionUtils.ts
3795
+ import { RawCoList } from "cojson";
3796
+ function schemaUnionDiscriminatorFor(schema) {
3797
+ if (isUnionOfCoMapsDeeply(schema)) {
3798
+ if (!schema._zod.disc || schema._zod.disc.size == 0) {
3799
+ throw new Error(
3800
+ "z.union() of collaborative types is not supported, use z.discriminatedUnion() instead"
3801
+ );
3802
+ }
3803
+ const discriminator = schema._zod.def.discriminator;
3804
+ const field = schema._zod.disc.get(discriminator);
3805
+ if (!field) {
3806
+ throw new Error(
3807
+ "z.discriminatedUnion() of collaborative types with non-existent discriminator key is not supported"
3808
+ );
3809
+ }
3810
+ for (const value of field.values) {
3811
+ if (typeof value !== "string" && typeof value !== "number") {
3812
+ throw new Error(
3813
+ "z.discriminatedUnion() of collaborative types with non-string or non-number discriminator value is not supported"
3814
+ );
3815
+ }
3816
+ }
3817
+ const availableOptions = [];
3818
+ for (const option of schema._zod.def.options) {
3819
+ if (option._zod.def.type === "object") {
3820
+ availableOptions.push(option);
3821
+ } else if (option._zod.def.type === "union") {
3822
+ for (const subOption of option._zod.def.options) {
3823
+ if (subOption._zod.def.type === "object") {
3824
+ availableOptions.push(subOption);
3825
+ }
3826
+ }
3827
+ } else {
3828
+ throw new Error(
3829
+ "Unsupported zod type in z.discriminatedUnion() of collaborative types"
3830
+ );
3831
+ }
3832
+ }
3833
+ const determineSchema = (_raw) => {
3834
+ if (_raw instanceof RawCoList) {
3835
+ throw new Error(
3836
+ "z.discriminatedUnion() of collaborative types is not supported for CoLists"
3837
+ );
3838
+ }
3839
+ for (const option of availableOptions) {
3840
+ let match = true;
3841
+ for (const key of schema._zod.disc.keys()) {
3842
+ const discriminatorDef = option._zod.def.shape[key];
3843
+ const discriminatorValue = _raw.get(key);
3844
+ if (discriminatorValue && typeof discriminatorValue === "object") {
3845
+ throw new Error("Discriminator must be a primitive value");
3846
+ }
3847
+ if (!discriminatorDef) {
3848
+ if (key === discriminator) {
3849
+ match = false;
3850
+ break;
3851
+ } else {
3852
+ continue;
3853
+ }
3854
+ }
3855
+ if (discriminatorDef._zod.def.type !== "literal") {
3856
+ break;
3857
+ }
3858
+ const literalDef = discriminatorDef._zod.def;
3859
+ if (!Array.from(literalDef.values).includes(discriminatorValue)) {
3860
+ match = false;
3861
+ break;
3862
+ }
3863
+ }
3864
+ if (match) {
3865
+ return zodSchemaToCoSchema2(option);
3866
+ }
3867
+ }
3868
+ throw new Error(
3869
+ "z.discriminatedUnion() of collaborative types with no matching discriminator value found"
3870
+ );
3871
+ };
3872
+ return determineSchema;
3873
+ } else {
3874
+ throw new Error(
3875
+ "z.discriminatedUnion() of non-collaborative types is not supported"
3876
+ );
3877
+ }
3878
+ }
3879
+ function isUnionOfCoMapsDeeply(schema) {
3880
+ if (schema instanceof z.core.$ZodUnion) {
3881
+ return schema._zod.def.options.every(isCoMapOrUnionOfCoMapsDeeply);
3882
+ } else {
3883
+ return false;
3884
+ }
3885
+ }
3886
+ function isCoMapOrUnionOfCoMapsDeeply(schema) {
3887
+ if (schema instanceof z.core.$ZodObject && "collaborative" in schema && schema.collaborative) {
3888
+ return true;
3889
+ } else if (schema instanceof z.core.$ZodUnion) {
3890
+ return schema._zod.def.options.every(isCoMapOrUnionOfCoMapsDeeply);
3891
+ } else {
3892
+ return false;
3893
+ }
3894
+ }
3895
+ function isUnionOfPrimitivesDeeply(schema) {
3896
+ if (schema instanceof z.core.$ZodUnion) {
3897
+ return schema._zod.def.options.every(isUnionOfPrimitivesDeeply);
3898
+ } else {
3899
+ return !("collaborative" in schema);
3900
+ }
3901
+ }
3902
+
3903
+ // src/tools/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.ts
3904
+ function zodFieldToCoFieldDef(schema) {
3905
+ if (isCoValueClass(schema)) {
3906
+ return coField.ref(schema);
3907
+ } else {
3908
+ if ("_zod" in schema) {
3909
+ if (schema._zod.def.type === "optional") {
3910
+ const inner = zodSchemaToCoSchemaOrKeepPrimitive(
3911
+ schema._zod.def.innerType
3912
+ );
3913
+ if (isCoValueClass(inner)) {
3914
+ return coField.ref(inner, { optional: true });
3915
+ } else {
3916
+ return zodFieldToCoFieldDef(inner);
3917
+ }
3918
+ } else if (schema._zod.def.type === "string") {
3919
+ return coField.string;
3920
+ } else if (schema._zod.def.type === "number") {
3921
+ return coField.number;
3922
+ } else if (schema._zod.def.type === "boolean") {
3923
+ return coField.boolean;
3924
+ } else if (schema._zod.def.type === "null") {
3925
+ return coField.null;
3926
+ } else if (schema._zod.def.type === "enum") {
3927
+ return coField.string;
3928
+ } else if (schema._zod.def.type === "readonly") {
3929
+ return zodFieldToCoFieldDef(
3930
+ schema.def.innerType
3931
+ );
3932
+ } else if (schema._zod.def.type === "date") {
3933
+ return coField.optional.Date;
3934
+ } else if (schema._zod.def.type === "template_literal") {
3935
+ return coField.string;
3936
+ } else if (schema._zod.def.type === "lazy") {
3937
+ return zodFieldToCoFieldDef(
3938
+ schema.unwrap()
3939
+ );
3940
+ } else if (schema._zod.def.type === "default" || schema._zod.def.type === "catch") {
3941
+ console.warn(
3942
+ "z.default()/z.catch() are not supported in collaborative schemas. They will be ignored."
3943
+ );
3944
+ return zodFieldToCoFieldDef(
3945
+ schema.def.innerType
3946
+ );
3947
+ } else if (schema._zod.def.type === "literal") {
3948
+ if (schema._zod.def.values.some(
3949
+ (literal2) => typeof literal2 === "undefined"
3950
+ )) {
3951
+ throw new Error("z.literal() with undefined is not supported");
3952
+ }
3953
+ if (schema._zod.def.values.some((literal2) => literal2 === null)) {
3954
+ throw new Error("z.literal() with null is not supported");
3955
+ }
3956
+ if (schema._zod.def.values.some((literal2) => typeof literal2 === "bigint")) {
3957
+ throw new Error("z.literal() with bigint is not supported");
3958
+ }
3959
+ return coField.literal(
3960
+ ...schema._zod.def.values
3961
+ );
3962
+ } else if (schema._zod.def.type === "object" || schema._zod.def.type === "array" || schema._zod.def.type === "tuple") {
3963
+ return coField.json();
3964
+ } else if (schema._zod.def.type === "custom") {
3965
+ if ("builtin" in schema) {
3966
+ return zodFieldToCoFieldDef(schema.builtin);
3967
+ } else {
3968
+ throw new Error(`Unsupported custom zod type`);
3969
+ }
3970
+ } else if (schema._zod.def.type === "union") {
3971
+ if (isUnionOfPrimitivesDeeply(schema)) {
3972
+ return coField.json();
3973
+ } else if (isUnionOfCoMapsDeeply(schema)) {
3974
+ return coField.ref(
3975
+ schemaUnionDiscriminatorFor(schema)
3976
+ );
3977
+ } else {
3978
+ throw new Error(
3979
+ "z.union()/z.discriminatedUnion() of mixed collaborative and non-collaborative types is not supported"
3980
+ );
3981
+ }
3982
+ } else {
3983
+ throw new Error(
3984
+ `Unsupported zod type: ${schema._zod?.def?.type || JSON.stringify(schema)}`
3985
+ );
3986
+ }
3987
+ } else {
3988
+ throw new Error(`Unsupported zod type: ${schema}`);
3989
+ }
3990
+ }
3991
+ }
3992
+
3993
+ // src/tools/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.ts
3994
+ var coSchemasForZodSchemas = /* @__PURE__ */ new Map();
3995
+ function tryZodSchemaToCoSchema(schema) {
3996
+ if ("collaborative" in schema && schema.collaborative) {
3997
+ if (coSchemasForZodSchemas.has(schema)) {
3998
+ return coSchemasForZodSchemas.get(schema);
3999
+ }
4000
+ if (isZodObject(schema)) {
4001
+ const def = getDef(schema);
4002
+ const ClassToExtend = "builtin" in schema && schema.builtin === "Account" ? Account : CoMap;
4003
+ const coSchema = class ZCoMap extends ClassToExtend {
4004
+ constructor(options) {
4005
+ super(options);
4006
+ for (const [field, fieldType] of Object.entries(
4007
+ def.shape
4008
+ )) {
4009
+ this[field] = zodFieldToCoFieldDef(
4010
+ zodSchemaToCoSchemaOrKeepPrimitive(fieldType)
4011
+ );
4012
+ }
4013
+ if (def.catchall) {
4014
+ this[coField.items] = zodFieldToCoFieldDef(
4015
+ zodSchemaToCoSchemaOrKeepPrimitive(def.catchall)
4016
+ );
4017
+ }
4018
+ }
4019
+ };
4020
+ coSchemasForZodSchemas.set(schema, coSchema);
4021
+ return coSchema;
4022
+ } else if (isZodArray(schema)) {
4023
+ const def = getDef(schema);
4024
+ const coSchema = class ZCoList extends CoList {
4025
+ constructor(options) {
4026
+ super(options);
4027
+ this[coField.items] = zodFieldToCoFieldDef(
4028
+ zodSchemaToCoSchemaOrKeepPrimitive(def.element)
4029
+ );
4030
+ }
4031
+ };
4032
+ coSchemasForZodSchemas.set(schema, coSchema);
4033
+ return coSchema;
4034
+ } else if (isZodCustom(schema)) {
4035
+ if ("builtin" in schema) {
4036
+ if (schema.builtin === "CoFeed" && "element" in schema) {
4037
+ return CoFeed.Of(
4038
+ zodFieldToCoFieldDef(
4039
+ zodSchemaToCoSchemaOrKeepPrimitive(
4040
+ schema.element
4041
+ )
4042
+ )
4043
+ );
4044
+ } else if (schema.builtin === "FileStream") {
4045
+ return FileStream;
4046
+ } else if (schema.builtin === "CoPlainText") {
4047
+ return CoPlainText;
4048
+ } else if (schema.builtin === "CoRichText") {
4049
+ return CoRichText;
4050
+ } else {
4051
+ throw new Error(`Unsupported builtin type: ${schema.builtin}`);
4052
+ }
4053
+ } else {
4054
+ throw new Error(`Unsupported custom zod type`);
4055
+ }
4056
+ } else {
4057
+ throw new Error(
4058
+ `Unsupported zod CoValue type for top-level schema: ${schema._zod?.def?.type || JSON.stringify(schema, void 0, 2)}`
4059
+ );
4060
+ }
4061
+ } else if (schema instanceof z.core.$ZodDiscriminatedUnion) {
4062
+ if (isUnionOfCoMapsDeeply(schema)) {
4063
+ return SchemaUnion.Of(
4064
+ schemaUnionDiscriminatorFor(schema)
4065
+ );
4066
+ } else {
4067
+ throw new Error(
4068
+ "z.discriminatedUnion() of non-collaborative types is not supported as a top-level schema"
4069
+ );
4070
+ }
4071
+ } else {
4072
+ return null;
4073
+ }
4074
+ }
4075
+ function zodSchemaToCoSchema2(schema) {
4076
+ const coSchema = tryZodSchemaToCoSchema(schema);
4077
+ if (!coSchema) {
4078
+ throw new Error(
4079
+ `Unsupported zod type: ${schema._zod?.def?.type || JSON.stringify(schema)}`
4080
+ );
4081
+ }
4082
+ return coSchema;
4083
+ }
4084
+ function anySchemaToCoSchema(schema) {
4085
+ if (isCoValueClass(schema)) {
4086
+ return schema;
4087
+ } else if ("getCoSchema" in schema) {
4088
+ return schema.getCoSchema();
4089
+ } else if ("def" in schema) {
4090
+ const coSchema = tryZodSchemaToCoSchema(schema);
4091
+ if (!coSchema) {
4092
+ throw new Error(
4093
+ `Unsupported zod type: ${schema.def?.type || JSON.stringify(schema)}`
4094
+ );
4095
+ }
4096
+ return coSchema;
4097
+ }
4098
+ throw new Error(`Unsupported schema: ${JSON.stringify(schema)}`);
4099
+ }
4100
+ function zodSchemaToCoSchemaOrKeepPrimitive(schema) {
4101
+ const coSchema = tryZodSchemaToCoSchema(schema);
4102
+ if (!coSchema) {
4103
+ return schema;
4104
+ }
4105
+ return coSchema;
4106
+ }
4107
+
4108
+ // src/tools/coValues/extensions/imageDef.ts
4109
+ var ImageDefinitionBase = coMapDefiner({
4110
+ originalSize: z.tuple([z.number(), z.number()]),
4111
+ placeholderDataURL: z.string().optional()
4112
+ }).catchall(coFileStreamDefiner());
4113
+ var ImageDefinition = ImageDefinitionBase.withHelpers((Self) => ({
4114
+ highestResAvailable(imageDef, options) {
4115
+ const resolutions = Object.keys(imageDef).filter(
4116
+ (key) => key.match(/^\d+x\d+$/)
4117
+ );
4118
+ let maxWidth = options?.maxWidth;
4119
+ if (options?.targetWidth) {
4120
+ const targetWidth = options.targetWidth;
4121
+ const widths = resolutions.map((res) => Number(res.split("x")[0]));
4122
+ maxWidth = Math.min(...widths.filter((w) => w >= targetWidth));
4123
+ }
4124
+ const validResolutions = resolutions.filter(
4125
+ (key) => maxWidth === void 0 || Number(key.split("x")[0]) <= maxWidth
4126
+ );
4127
+ validResolutions.sort((a, b) => {
4128
+ const aWidth = Number(a.split("x")[0]);
4129
+ const bWidth = Number(b.split("x")[0]);
4130
+ return aWidth - bWidth;
4131
+ });
4132
+ let highestAvailableResolution;
4133
+ for (const resolution of validResolutions) {
4134
+ if (imageDef[resolution] && imageDef[resolution]?.getChunks()) {
4135
+ highestAvailableResolution = resolution;
4136
+ }
4137
+ }
4138
+ return highestAvailableResolution && {
4139
+ res: highestAvailableResolution,
4140
+ stream: imageDef[highestAvailableResolution]
4141
+ };
4142
+ }
4143
+ }));
4144
+
4145
+ // src/tools/implementation/ContextManager.ts
4146
+ import { cojsonInternals as cojsonInternals4 } from "cojson";
4147
+ import { PureJSCrypto } from "cojson/dist/crypto/PureJSCrypto";
4148
+
4149
+ // src/tools/auth/KvStoreContext.ts
4150
+ var KvStoreContext = class _KvStoreContext {
4151
+ constructor() {
4152
+ this.storageInstance = null;
4153
+ }
4154
+ static getInstance() {
4155
+ if (!_KvStoreContext.instance) {
4156
+ _KvStoreContext.instance = new _KvStoreContext();
4157
+ }
4158
+ return _KvStoreContext.instance;
4159
+ }
4160
+ isInitialized() {
4161
+ return this.storageInstance !== null;
4162
+ }
4163
+ initialize(store) {
4164
+ if (!this.storageInstance) {
4165
+ this.storageInstance = store;
4166
+ }
4167
+ }
4168
+ getStorage() {
4169
+ if (!this.storageInstance) {
4170
+ throw new Error("Storage instance is not initialized.");
4171
+ }
4172
+ return this.storageInstance;
4173
+ }
4174
+ };
4175
+ var KvStoreContext_default = KvStoreContext;
4176
+
4177
+ // src/tools/auth/AuthSecretStorage.ts
4178
+ var STORAGE_KEY = "jazz-logged-in-secret";
4179
+ var AuthSecretStorage = class {
4180
+ constructor() {
4181
+ this.listeners = /* @__PURE__ */ new Set();
4182
+ this.isAuthenticated = false;
4183
+ }
4184
+ async migrate() {
4185
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4186
+ if (!await kvStore.get(STORAGE_KEY)) {
4187
+ const demoAuthSecret = await kvStore.get("demo-auth-logged-in-secret");
4188
+ if (demoAuthSecret) {
4189
+ const parsed = JSON.parse(demoAuthSecret);
4190
+ await kvStore.set(
4191
+ STORAGE_KEY,
4192
+ JSON.stringify({
4193
+ accountID: parsed.accountID,
4194
+ accountSecret: parsed.accountSecret,
4195
+ provider: "demo"
4196
+ })
4197
+ );
4198
+ await kvStore.delete("demo-auth-logged-in-secret");
4199
+ }
4200
+ const clerkAuthSecret = await kvStore.get("jazz-clerk-auth");
4201
+ if (clerkAuthSecret) {
4202
+ const parsed = JSON.parse(clerkAuthSecret);
4203
+ await kvStore.set(
4204
+ STORAGE_KEY,
4205
+ JSON.stringify({
4206
+ accountID: parsed.accountID,
4207
+ accountSecret: parsed.secret,
4208
+ provider: "clerk"
4209
+ })
4210
+ );
4211
+ await kvStore.delete("jazz-clerk-auth");
4212
+ }
4213
+ }
4214
+ const value = await kvStore.get(STORAGE_KEY);
4215
+ if (value) {
4216
+ const parsed = JSON.parse(value);
4217
+ if ("secret" in parsed) {
4218
+ await kvStore.set(
4219
+ STORAGE_KEY,
4220
+ JSON.stringify({
4221
+ accountID: parsed.accountID,
4222
+ secretSeed: parsed.secretSeed,
4223
+ accountSecret: parsed.secret,
4224
+ provider: parsed.provider
4225
+ })
4226
+ );
4227
+ }
4228
+ }
4229
+ }
4230
+ async get() {
4231
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4232
+ const data = await kvStore.get(STORAGE_KEY);
4233
+ if (!data) return null;
4234
+ const parsed = JSON.parse(data);
4235
+ if (!parsed.accountID || !parsed.accountSecret) {
4236
+ throw new Error("Invalid auth secret storage data");
4237
+ }
4238
+ return {
4239
+ accountID: parsed.accountID,
4240
+ secretSeed: parsed.secretSeed ? new Uint8Array(parsed.secretSeed) : void 0,
4241
+ accountSecret: parsed.accountSecret,
4242
+ provider: parsed.provider
4243
+ };
4244
+ }
4245
+ async setWithoutNotify(payload) {
4246
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4247
+ await kvStore.set(
4248
+ STORAGE_KEY,
4249
+ JSON.stringify({
4250
+ accountID: payload.accountID,
4251
+ secretSeed: payload.secretSeed ? Array.from(payload.secretSeed) : void 0,
4252
+ accountSecret: payload.accountSecret,
4253
+ provider: payload.provider
4254
+ })
4255
+ );
4256
+ }
4257
+ async set(payload) {
4258
+ this.setWithoutNotify(payload);
4259
+ this.emitUpdate(payload);
4260
+ }
4261
+ getIsAuthenticated(data) {
4262
+ if (!data) return false;
4263
+ return data.provider !== "anonymous";
4264
+ }
4265
+ onUpdate(handler) {
4266
+ this.listeners.add(handler);
4267
+ return () => {
4268
+ this.listeners.delete(handler);
4269
+ };
4270
+ }
4271
+ emitUpdate(data) {
4272
+ const isAuthenticated = this.getIsAuthenticated(data);
4273
+ if (this.isAuthenticated === isAuthenticated) return;
4274
+ this.isAuthenticated = isAuthenticated;
4275
+ for (const listener of this.listeners) {
4276
+ listener(this.isAuthenticated);
4277
+ }
4278
+ }
4279
+ async clearWithoutNotify() {
4280
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4281
+ await kvStore.delete(STORAGE_KEY);
4282
+ }
4283
+ async clear() {
4284
+ await this.clearWithoutNotify();
4285
+ this.emitUpdate(null);
4286
+ }
4287
+ };
4288
+
4289
+ // src/tools/auth/InMemoryKVStore.ts
4290
+ var InMemoryKVStore = class {
4291
+ constructor() {
4292
+ this.store = {};
4293
+ }
4294
+ async get(key) {
4295
+ const data = this.store[key];
4296
+ if (!data) return null;
4297
+ return data;
4298
+ }
4299
+ async set(key, value) {
4300
+ this.store[key] = value;
4301
+ }
4302
+ async delete(key) {
4303
+ delete this.store[key];
4304
+ }
4305
+ async clearAll() {
4306
+ this.store = {};
4307
+ }
4308
+ };
4309
+
4310
+ // src/tools/implementation/ContextManager.ts
4311
+ function getAnonymousFallback() {
4312
+ const context = createAnonymousJazzContext({
4313
+ peersToLoadFrom: [],
4314
+ crypto: new PureJSCrypto()
4315
+ });
4316
+ return {
4317
+ guest: context.agent,
4318
+ node: context.agent.node,
4319
+ done: () => {
4320
+ },
4321
+ logOut: async () => {
4322
+ },
4323
+ isAuthenticated: false,
4324
+ authenticate: async () => {
4325
+ },
4326
+ register: async () => {
4327
+ throw new Error("Not implemented");
4328
+ }
4329
+ };
4330
+ }
4331
+ var JazzContextManager = class {
4332
+ constructor(opts) {
4333
+ this.authSecretStorage = new AuthSecretStorage();
4334
+ this.keepContextOpen = false;
4335
+ this.logOut = async () => {
4336
+ if (!this.context || !this.props) {
4337
+ return;
4338
+ }
4339
+ await this.props.onLogOut?.();
4340
+ if (this.props.logOutReplacement) {
4341
+ await this.props.logOutReplacement();
4342
+ } else {
4343
+ await this.context.logOut();
4344
+ return this.createContext(this.props);
4345
+ }
4346
+ };
4347
+ this.done = () => {
4348
+ if (!this.context) {
4349
+ return;
4350
+ }
4351
+ this.context.done();
4352
+ };
4353
+ this.shouldMigrateAnonymousAccount = async () => {
4354
+ if (!this.props?.onAnonymousAccountDiscarded) {
4355
+ return false;
4356
+ }
4357
+ const prevCredentials = await this.authSecretStorage.get();
4358
+ const wasAnonymous = this.authSecretStorage.getIsAuthenticated(prevCredentials) === false;
4359
+ return wasAnonymous;
4360
+ };
4361
+ /**
4362
+ * Authenticates the user with the given credentials
4363
+ */
4364
+ this.authenticate = async (credentials) => {
4365
+ if (!this.props) {
4366
+ throw new Error("Props required");
4367
+ }
4368
+ const prevContext = this.context;
4369
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
4370
+ this.keepContextOpen = migratingAnonymousAccount;
4371
+ await this.createContext(this.props, { credentials }).finally(() => {
4372
+ this.keepContextOpen = false;
4373
+ });
4374
+ if (migratingAnonymousAccount) {
4375
+ await this.handleAnonymousAccountMigration(prevContext);
4376
+ }
4377
+ };
4378
+ this.register = async (accountSecret, creationProps) => {
4379
+ if (!this.props) {
4380
+ throw new Error("Props required");
4381
+ }
4382
+ const prevContext = this.context;
4383
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
4384
+ this.keepContextOpen = migratingAnonymousAccount;
4385
+ await this.createContext(this.props, {
4386
+ newAccountProps: {
4387
+ secret: accountSecret,
4388
+ creationProps
4389
+ }
4390
+ }).finally(() => {
4391
+ this.keepContextOpen = false;
4392
+ });
4393
+ if (migratingAnonymousAccount) {
4394
+ await this.handleAnonymousAccountMigration(prevContext);
4395
+ }
4396
+ if (this.context && "me" in this.context) {
4397
+ return this.context.me.id;
4398
+ }
4399
+ throw new Error("The registration hasn't created a new account");
4400
+ };
4401
+ this.listeners = /* @__PURE__ */ new Set();
4402
+ this.subscribe = (callback) => {
4403
+ this.listeners.add(callback);
4404
+ return () => {
4405
+ this.listeners.delete(callback);
4406
+ };
4407
+ };
4408
+ KvStoreContext.getInstance().initialize(this.getKvStore());
4409
+ if (opts?.useAnonymousFallback) {
4410
+ this.value = getAnonymousFallback();
4411
+ }
4412
+ }
4413
+ getKvStore() {
4414
+ return new InMemoryKVStore();
4415
+ }
4416
+ async createContext(props, authProps) {
4417
+ this.props = props;
4418
+ const { promise, resolve } = createResolvablePromise();
4419
+ const prevPromise = this.contextPromise;
4420
+ this.contextPromise = promise;
4421
+ await prevPromise;
4422
+ try {
4423
+ const result = await this.getNewContext(props, authProps);
4424
+ await this.updateContext(props, result, authProps);
4425
+ resolve();
4426
+ } catch (error) {
4427
+ resolve();
4428
+ throw error;
4429
+ }
4430
+ }
4431
+ async getNewContext(props, authProps) {
4432
+ props;
4433
+ authProps;
4434
+ throw new Error("Not implemented");
4435
+ }
4436
+ async updateContext(props, context, authProps) {
4437
+ if (!this.keepContextOpen) {
4438
+ this.context?.done();
4439
+ }
4440
+ this.context = context;
4441
+ this.props = props;
4442
+ this.value = {
4443
+ ...context,
4444
+ node: context.node,
4445
+ authenticate: this.authenticate,
4446
+ register: this.register,
4447
+ logOut: this.logOut
4448
+ };
4449
+ if (authProps?.credentials) {
4450
+ this.authSecretStorage.emitUpdate(authProps.credentials);
4451
+ } else {
4452
+ this.authSecretStorage.emitUpdate(await this.authSecretStorage.get());
4453
+ }
4454
+ this.notify();
4455
+ }
4456
+ propsChanged(props) {
4457
+ props;
4458
+ throw new Error("Not implemented");
4459
+ }
4460
+ getCurrentValue() {
4461
+ return this.value;
4462
+ }
4463
+ setCurrentValue(value) {
4464
+ this.value = value;
4465
+ }
4466
+ getAuthSecretStorage() {
4467
+ return this.authSecretStorage;
4468
+ }
4469
+ async handleAnonymousAccountMigration(prevContext) {
4470
+ if (!this.props) {
4471
+ throw new Error("Props required");
4472
+ }
4473
+ const currentContext = this.context;
4474
+ if (prevContext && currentContext && "me" in prevContext && "me" in currentContext) {
4475
+ const [prevAccountAsPeer, currentAccountAsPeer] = cojsonInternals4.connectedPeers(
4476
+ prevContext.me.id,
4477
+ currentContext.me.id,
4478
+ {
4479
+ peer1role: "client",
4480
+ peer2role: "server"
4481
+ }
4482
+ );
4483
+ prevContext.node.syncManager.addPeer(currentAccountAsPeer);
4484
+ currentContext.node.syncManager.addPeer(prevAccountAsPeer);
4485
+ try {
4486
+ await this.props.onAnonymousAccountDiscarded?.(prevContext.me);
4487
+ await prevContext.me.waitForAllCoValuesSync();
4488
+ } catch (error) {
4489
+ console.error("Error onAnonymousAccountDiscarded", error);
4490
+ }
4491
+ prevAccountAsPeer.outgoing.close();
4492
+ currentAccountAsPeer.outgoing.close();
4493
+ }
4494
+ prevContext?.done();
4495
+ }
4496
+ notify() {
4497
+ for (const listener of this.listeners) {
4498
+ listener();
4499
+ }
4500
+ }
4501
+ };
4502
+ function createResolvablePromise() {
4503
+ let resolve;
4504
+ const promise = new Promise((res) => {
4505
+ resolve = res;
4506
+ });
4507
+ return { promise, resolve };
4508
+ }
4509
+
4510
+ // src/tools/implementation/devtoolsFormatters.ts
4511
+ globalThis.devtoolsFormatters = [
4512
+ {
4513
+ header: (object2) => {
4514
+ if (object2._type === "CoMap") {
4515
+ return ["div", {}, ["span", {}, object2.constructor.name]];
4516
+ } else if (object2._type === "CoList") {
4517
+ return [
4518
+ "div",
4519
+ {},
4520
+ ["span", {}, object2.constructor.name + "(" + object2.length + ") "]
4521
+ ];
4522
+ } else if (object2._type === "Account") {
4523
+ return [
4524
+ "div",
4525
+ {},
4526
+ [
4527
+ "span",
4528
+ {},
4529
+ object2.constructor.name + "(" + object2._refs.profile.value?.name + (object2.isMe ? " ME" : "") + ")"
4530
+ ]
4531
+ ];
4532
+ } else {
4533
+ return null;
4534
+ }
4535
+ },
4536
+ hasBody: function() {
4537
+ return true;
4538
+ },
4539
+ body: function(object2) {
4540
+ if (object2._type === "CoMap" || object2._type === "Account") {
4541
+ return [
4542
+ "div",
4543
+ { style: "margin-left: 15px" },
4544
+ ["div", "id: ", ["object", { object: object2.id }]],
4545
+ ...Object.entries(object2).map(([k, v]) => [
4546
+ "div",
4547
+ { style: "white-space: nowrap;" },
4548
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, k, ": "],
4549
+ ["object", { object: v }],
4550
+ ...typeof object2._schema[k] === "function" ? v === null ? [
4551
+ [
4552
+ "span",
4553
+ { style: "opacity: 0.5" },
4554
+ ` (pending ${object2._schema[k].name} `,
4555
+ ["object", { object: object2._refs[k] }],
4556
+ ")"
4557
+ ]
4558
+ ] : [] : []
4559
+ ])
4560
+ ];
4561
+ } else if (object2._type === "CoList") {
4562
+ return [
4563
+ "div",
4564
+ { style: "margin-left: 15px" },
4565
+ ["div", "id: ", ["object", { object: object2.id }]],
4566
+ ...object2.map((v, i) => [
4567
+ "div",
4568
+ { style: "white-space: nowrap;" },
4569
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, i, ": "],
4570
+ ["object", { object: v }],
4571
+ ...typeof object2._schema[ItemsSym] === "function" ? v === null ? [
4572
+ [
4573
+ "span",
4574
+ { style: "opacity: 0.5" },
4575
+ ` (pending ${object2._schema[ItemsSym].name} `,
4576
+ ["object", { object: object2._refs[i] }],
4577
+ ")"
4578
+ ]
4579
+ ] : [] : []
4580
+ ])
4581
+ ];
4582
+ }
4583
+ }
4584
+ }
4585
+ ];
4586
+
4587
+ // src/tools/coValues/interfaces.ts
4588
+ function isCoValueClass(value) {
4589
+ return typeof value === "function" && value.fromRaw !== void 0;
4590
+ }
4591
+ function loadCoValueWithoutMe(cls, id, options) {
4592
+ return loadCoValue(cls, id, {
4593
+ ...options,
4594
+ loadAs: options?.loadAs ?? activeAccountContext.get()
4595
+ });
4596
+ }
4597
+ function loadCoValue(cls, id, options) {
4598
+ return new Promise((resolve) => {
4599
+ subscribeToCoValue(
4600
+ cls,
4601
+ id,
4602
+ {
4603
+ resolve: options.resolve,
4604
+ loadAs: options.loadAs,
4605
+ syncResolution: true,
4606
+ onUnavailable: () => {
4607
+ resolve(null);
4608
+ },
4609
+ onUnauthorized: () => {
4610
+ resolve(null);
4611
+ }
4612
+ },
4613
+ (value, unsubscribe) => {
4614
+ resolve(value);
4615
+ unsubscribe();
4616
+ }
4617
+ );
4618
+ });
4619
+ }
4620
+ async function ensureCoValueLoaded(existing, options) {
4621
+ const response = await loadCoValue(
4622
+ existing.constructor,
4623
+ existing.id,
4624
+ {
4625
+ loadAs: existing._loadedAs,
4626
+ resolve: options?.resolve
4627
+ }
4628
+ );
4629
+ if (!response) {
4630
+ throw new Error("Failed to deeply load CoValue " + existing.id);
4631
+ }
4632
+ return response;
4633
+ }
4634
+ function parseSubscribeRestArgs(args) {
4635
+ if (args.length === 2) {
4636
+ if (typeof args[0] === "object" && args[0] && typeof args[1] === "function") {
4637
+ return {
4638
+ options: {
4639
+ resolve: args[0].resolve,
4640
+ loadAs: args[0].loadAs,
4641
+ onUnauthorized: args[0].onUnauthorized,
4642
+ onUnavailable: args[0].onUnavailable
4643
+ },
4644
+ listener: args[1]
4645
+ };
4646
+ } else {
4647
+ throw new Error("Invalid arguments");
4648
+ }
4649
+ } else {
4650
+ if (typeof args[0] === "function") {
4651
+ return { options: {}, listener: args[0] };
4652
+ } else {
4653
+ throw new Error("Invalid arguments");
4654
+ }
4655
+ }
4656
+ }
4657
+ function subscribeToCoValueWithoutMe(cls, id, options, listener) {
4658
+ return subscribeToCoValue(
4659
+ cls,
4660
+ id,
4661
+ {
4662
+ ...options,
4663
+ loadAs: options.loadAs ?? activeAccountContext.get()
4664
+ },
4665
+ listener
4666
+ );
4667
+ }
4668
+ function subscribeToCoValue(cls, id, options, listener) {
4669
+ const loadAs = options.loadAs ?? activeAccountContext.get();
4670
+ const node = "node" in loadAs ? loadAs.node : loadAs._raw.core.node;
4671
+ const resolve = options.resolve ?? true;
4672
+ let unsubscribed = false;
4673
+ const rootNode = new SubscriptionScope(node, resolve, id, {
4674
+ ref: cls,
4675
+ optional: false
4676
+ });
4677
+ const handleUpdate = (value) => {
4678
+ if (unsubscribed) return;
4679
+ if (value.type === "unavailable") {
4680
+ options.onUnavailable?.();
4681
+ console.error(value.toString());
4682
+ } else if (value.type === "unauthorized") {
4683
+ options.onUnauthorized?.();
4684
+ console.error(value.toString());
4685
+ } else if (value.type === "loaded") {
4686
+ listener(value.value, unsubscribe);
4687
+ }
4688
+ };
4689
+ let shouldDefer = !options.syncResolution;
4690
+ rootNode.setListener((value) => {
4691
+ if (shouldDefer) {
4692
+ shouldDefer = false;
4693
+ Promise.resolve().then(() => {
4694
+ handleUpdate(value);
4695
+ });
4696
+ } else {
4697
+ handleUpdate(value);
4698
+ }
4699
+ });
4700
+ function unsubscribe() {
4701
+ unsubscribed = true;
4702
+ rootNode.destroy();
4703
+ }
4704
+ return unsubscribe;
4705
+ }
4706
+ function createCoValueObservable(initialValue = void 0) {
4707
+ let currentValue = initialValue;
4708
+ let subscriberCount = 0;
4709
+ function subscribe(cls, id, options, listener) {
4710
+ subscriberCount++;
4711
+ const unsubscribe = subscribeToCoValue(
4712
+ anySchemaToCoSchema(cls),
4713
+ id,
4714
+ {
4715
+ loadAs: options.loadAs,
4716
+ resolve: options.resolve,
4717
+ onUnavailable: () => {
4718
+ currentValue = null;
4719
+ options.onUnavailable?.();
4720
+ },
4721
+ onUnauthorized: () => {
4722
+ currentValue = null;
4723
+ options.onUnauthorized?.();
4724
+ },
4725
+ syncResolution: options.syncResolution
4726
+ },
4727
+ (value) => {
4728
+ currentValue = value;
4729
+ listener();
4730
+ }
4731
+ );
4732
+ return () => {
4733
+ unsubscribe();
4734
+ subscriberCount--;
4735
+ if (subscriberCount === 0) {
4736
+ currentValue = void 0;
4737
+ }
4738
+ };
4739
+ }
4740
+ const observable = {
4741
+ getCurrentValue: () => currentValue,
4742
+ subscribe
4743
+ };
4744
+ return observable;
4745
+ }
4746
+ function subscribeToExistingCoValue(existing, options, listener) {
4747
+ return subscribeToCoValue(
4748
+ existing.constructor,
4749
+ existing.id,
4750
+ {
4751
+ loadAs: existing._loadedAs,
4752
+ resolve: options?.resolve,
4753
+ onUnavailable: options?.onUnavailable,
4754
+ onUnauthorized: options?.onUnauthorized
4755
+ },
4756
+ listener
4757
+ );
4758
+ }
4759
+ function isAccountInstance(instance) {
4760
+ if (typeof instance !== "object" || instance === null) {
4761
+ return false;
4762
+ }
4763
+ return "_type" in instance && instance._type === "Account";
4764
+ }
4765
+ function parseCoValueCreateOptions(options) {
4766
+ const Group3 = RegisteredSchemas["Group"];
4767
+ if (!options) {
4768
+ return { owner: Group3.create(), uniqueness: void 0 };
4769
+ }
4770
+ if ("_type" in options) {
4771
+ if (options._type === "Account" || options._type === "Group") {
4772
+ return { owner: options, uniqueness: void 0 };
4773
+ }
4774
+ }
4775
+ const uniqueness = options.unique ? { uniqueness: options.unique } : void 0;
4776
+ return {
4777
+ owner: options.owner ?? Group3.create(),
4778
+ uniqueness
4779
+ };
4780
+ }
4781
+ function parseGroupCreateOptions(options) {
4782
+ if (!options) {
4783
+ return { owner: activeAccountContext.get() };
4784
+ }
4785
+ return "_type" in options && isAccountInstance(options) ? { owner: options } : { owner: options.owner ?? activeAccountContext.get() };
4786
+ }
4787
+
4788
+ export {
4789
+ zodReExport_exports,
4790
+ loadCoValue,
4791
+ subscribeToCoValue,
4792
+ createCoValueObservable,
4793
+ CoValueBase,
4794
+ CoMap,
4795
+ CoList,
4796
+ CoFeed,
4797
+ FileStream,
4798
+ Account,
4799
+ isControlledAccount,
4800
+ Group,
4801
+ Profile,
4802
+ Inbox,
4803
+ InboxSender,
4804
+ CoPlainText,
4805
+ CoRichText,
4806
+ SchemaUnion,
4807
+ AnonymousJazzAgent,
4808
+ activeAccountContext,
4809
+ Encoders,
4810
+ coField,
4811
+ SubscriptionScope,
4812
+ randomSessionProvider,
4813
+ createJazzContextFromExistingCredentials,
4814
+ createJazzContextForNewAccount,
4815
+ createJazzContext,
4816
+ createAnonymousJazzContext,
4817
+ coExport_exports,
4818
+ zodSchemaToCoSchema2 as zodSchemaToCoSchema,
4819
+ anySchemaToCoSchema,
4820
+ ImageDefinition,
4821
+ KvStoreContext,
4822
+ AuthSecretStorage,
4823
+ InMemoryKVStore,
4824
+ JazzContextManager
4825
+ };
4826
+ /* istanbul ignore file -- @preserve */
4827
+ //# sourceMappingURL=chunk-FSIM7N33.js.map