jazz-tools 0.19.22 → 0.20.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 (201) hide show
  1. package/.svelte-kit/__package__/react.d.ts.map +1 -1
  2. package/.svelte-kit/__package__/react.tsx +5 -2
  3. package/.turbo/turbo-build.log +71 -83
  4. package/CHANGELOG.md +69 -0
  5. package/dist/better-auth/auth/react.d.ts.map +1 -1
  6. package/dist/better-auth/auth/react.js +5 -2
  7. package/dist/better-auth/auth/react.js.map +1 -1
  8. package/dist/browser/createBrowserContext.d.ts +1 -2
  9. package/dist/browser/createBrowserContext.d.ts.map +1 -1
  10. package/dist/browser/index.js +1 -8
  11. package/dist/browser/index.js.map +1 -1
  12. package/dist/browser/provideBrowserLockSession/SessionIDStorage.d.ts +1 -1
  13. package/dist/{chunk-QCTQH5RS.js → chunk-3CAPPS2F.js} +234 -101
  14. package/dist/chunk-3CAPPS2F.js.map +1 -0
  15. package/dist/{chunk-M2HGBOXS.js → chunk-K4D7IMFM.js} +3 -3
  16. package/dist/chunk-K4D7IMFM.js.map +1 -0
  17. package/dist/expo/auth/clerk/index.d.ts.map +1 -1
  18. package/dist/expo/index.js +5 -2
  19. package/dist/expo/index.js.map +1 -1
  20. package/dist/index.js +4 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/inspector/{chunk-YQNK5Y7B.js → chunk-MCTB5ZJC.js} +1 -1
  23. package/dist/inspector/chunk-MCTB5ZJC.js.map +1 -0
  24. package/dist/inspector/contexts/node.d.ts.map +1 -1
  25. package/dist/inspector/{custom-element-KYV64IOC.js → custom-element-5YWVZBWA.js} +1 -1
  26. package/dist/inspector/{custom-element-KYV64IOC.js.map → custom-element-5YWVZBWA.js.map} +1 -1
  27. package/dist/inspector/index.js +3 -3
  28. package/dist/inspector/index.js.map +1 -1
  29. package/dist/inspector/register-custom-element.js +1 -1
  30. package/dist/inspector/standalone.js +1 -1
  31. package/dist/react/auth/Clerk.d.ts.map +1 -1
  32. package/dist/react/hooks.d.ts +1 -1
  33. package/dist/react/hooks.d.ts.map +1 -1
  34. package/dist/react/index.js +61 -47
  35. package/dist/react/index.js.map +1 -1
  36. package/dist/react/provider.d.ts.map +1 -1
  37. package/dist/react/ssr.js +2 -2
  38. package/dist/react/ssr.js.map +1 -1
  39. package/dist/react-core/chunk-UOYH6JFJ.js +10 -0
  40. package/dist/react-core/chunk-UOYH6JFJ.js.map +1 -0
  41. package/dist/react-core/hooks.d.ts +3 -3
  42. package/dist/react-core/hooks.d.ts.map +1 -1
  43. package/dist/react-core/index.js +27 -25
  44. package/dist/react-core/index.js.map +1 -1
  45. package/dist/react-core/provider.d.ts +2 -3
  46. package/dist/react-core/provider.d.ts.map +1 -1
  47. package/dist/react-core/testing.d.ts.map +1 -1
  48. package/dist/react-core/testing.js +4 -10
  49. package/dist/react-core/testing.js.map +1 -1
  50. package/dist/react-native/index.js +61 -53
  51. package/dist/react-native/index.js.map +1 -1
  52. package/dist/react-native-core/ReactNativeContextManager.d.ts +0 -1
  53. package/dist/react-native-core/ReactNativeContextManager.d.ts.map +1 -1
  54. package/dist/react-native-core/hooks.d.ts +1 -1
  55. package/dist/react-native-core/hooks.d.ts.map +1 -1
  56. package/dist/react-native-core/index.js +58 -50
  57. package/dist/react-native-core/index.js.map +1 -1
  58. package/dist/react-native-core/platform.d.ts +0 -4
  59. package/dist/react-native-core/platform.d.ts.map +1 -1
  60. package/dist/react-native-core/provider.d.ts +2 -1
  61. package/dist/react-native-core/provider.d.ts.map +1 -1
  62. package/dist/svelte/jazz.class.svelte.d.ts.map +1 -1
  63. package/dist/svelte/jazz.class.svelte.js +2 -8
  64. package/dist/svelte/tests/AccountCoState.svelte.test.d.ts +2 -0
  65. package/dist/svelte/tests/AccountCoState.svelte.test.d.ts.map +1 -0
  66. package/dist/svelte/tests/AccountCoState.svelte.test.js +59 -0
  67. package/dist/svelte/tests/CoState.svelte.test.js +23 -0
  68. package/dist/svelte/tests/TestAccountCoStateWrapper.svelte +24 -0
  69. package/dist/svelte/tests/TestAccountCoStateWrapper.svelte.d.ts +11 -0
  70. package/dist/svelte/tests/TestAccountCoStateWrapper.svelte.d.ts.map +1 -0
  71. package/dist/testing.js +6 -6
  72. package/dist/testing.js.map +1 -1
  73. package/dist/tools/coValues/coList.d.ts +2 -2
  74. package/dist/tools/coValues/coList.d.ts.map +1 -1
  75. package/dist/tools/coValues/coMap.d.ts +2 -2
  76. package/dist/tools/coValues/deepLoading.d.ts +2 -2
  77. package/dist/tools/coValues/deepLoading.d.ts.map +1 -1
  78. package/dist/tools/coValues/interfaces.d.ts +32 -0
  79. package/dist/tools/coValues/interfaces.d.ts.map +1 -1
  80. package/dist/tools/exports.d.ts +1 -1
  81. package/dist/tools/exports.d.ts.map +1 -1
  82. package/dist/tools/implementation/ContextManager.d.ts.map +1 -1
  83. package/dist/tools/implementation/createContext.d.ts.map +1 -1
  84. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts +3 -2
  85. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +1 -1
  86. package/dist/tools/implementation/zodSchema/schemaTypes/CoDiscriminatedUnionSchema.d.ts +3 -2
  87. package/dist/tools/implementation/zodSchema/schemaTypes/CoDiscriminatedUnionSchema.d.ts.map +1 -1
  88. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts +3 -3
  89. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +1 -1
  90. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts +3 -2
  91. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +1 -1
  92. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts +5 -2
  93. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +1 -1
  94. package/dist/tools/implementation/zodSchema/zodCo.d.ts.map +1 -1
  95. package/dist/tools/ssr.js +1 -1
  96. package/dist/tools/subscribe/JazzError.d.ts +3 -3
  97. package/dist/tools/subscribe/JazzError.d.ts.map +1 -1
  98. package/dist/tools/subscribe/SubscriptionScope.d.ts.map +1 -1
  99. package/dist/tools/subscribe/types.d.ts +5 -1
  100. package/dist/tools/subscribe/types.d.ts.map +1 -1
  101. package/dist/tools/testing.d.ts +3 -3
  102. package/dist/tools/testing.d.ts.map +1 -1
  103. package/dist/tools/tests/deleteCoValues.test.d.ts +2 -0
  104. package/dist/tools/tests/deleteCoValues.test.d.ts.map +1 -0
  105. package/dist/tools/tests/deletedState.test.d.ts +2 -0
  106. package/dist/tools/tests/deletedState.test.d.ts.map +1 -0
  107. package/dist/worker/edge-wasm.js +2 -1
  108. package/dist/worker/edge-wasm.js.map +1 -1
  109. package/dist/worker/wasm.d.ts +2 -0
  110. package/dist/worker/wasm.d.ts.map +1 -0
  111. package/package.json +9 -28
  112. package/src/better-auth/auth/react.tsx +5 -2
  113. package/src/browser/createBrowserContext.ts +2 -5
  114. package/src/expo/auth/clerk/index.tsx +5 -2
  115. package/src/inspector/contexts/node.tsx +1 -2
  116. package/src/inspector/index.tsx +2 -2
  117. package/src/react/auth/Clerk.tsx +5 -2
  118. package/src/react/auth/PasskeyAuth.tsx +2 -2
  119. package/src/react/hooks.tsx +3 -2
  120. package/src/react/provider.tsx +45 -41
  121. package/src/react-core/auth/DemoAuth.tsx +2 -2
  122. package/src/react-core/auth/PassphraseAuth.tsx +2 -2
  123. package/src/react-core/hooks.ts +26 -27
  124. package/src/react-core/provider.tsx +1 -5
  125. package/src/react-core/testing.tsx +3 -11
  126. package/src/react-core/tests/useAccount.selector.test.ts +2 -3
  127. package/src/react-core/tests/useAccount.test.ts +57 -7
  128. package/src/react-core/tests/useCoState.test.ts +37 -0
  129. package/src/react-core/tests/useInboxSender.test.ts +2 -5
  130. package/src/react-core/tests/useSuspenseAccount.test.tsx +68 -0
  131. package/src/react-core/tests/useSuspenseCoState.test.tsx +44 -0
  132. package/src/react-native-core/ReactNativeContextManager.ts +0 -3
  133. package/src/react-native-core/auth/usePasskeyAuth.tsx +2 -2
  134. package/src/react-native-core/hooks.tsx +3 -3
  135. package/src/react-native-core/platform.ts +2 -6
  136. package/src/react-native-core/provider.tsx +47 -43
  137. package/src/svelte/jazz.class.svelte.ts +2 -8
  138. package/src/svelte/tests/AccountCoState.svelte.test.ts +79 -0
  139. package/src/svelte/tests/CoState.svelte.test.ts +36 -0
  140. package/src/svelte/tests/TestAccountCoStateWrapper.svelte +24 -0
  141. package/src/tools/coValues/deepLoading.ts +2 -0
  142. package/src/tools/coValues/interfaces.ts +170 -32
  143. package/src/tools/exports.ts +1 -0
  144. package/src/tools/implementation/ContextManager.ts +2 -2
  145. package/src/tools/implementation/createContext.ts +4 -0
  146. package/src/tools/implementation/zodSchema/schemaTypes/AccountSchema.ts +30 -6
  147. package/src/tools/implementation/zodSchema/schemaTypes/CoDiscriminatedUnionSchema.ts +55 -7
  148. package/src/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.ts +33 -14
  149. package/src/tools/implementation/zodSchema/schemaTypes/CoListSchema.ts +35 -6
  150. package/src/tools/implementation/zodSchema/schemaTypes/CoMapSchema.ts +35 -14
  151. package/src/tools/ssr/ssr.ts +2 -2
  152. package/src/tools/subscribe/CoValueCoreSubscription.ts +1 -0
  153. package/src/tools/subscribe/JazzError.ts +4 -1
  154. package/src/tools/subscribe/SubscriptionScope.ts +23 -0
  155. package/src/tools/subscribe/types.ts +5 -0
  156. package/src/tools/testing.ts +5 -5
  157. package/src/tools/tests/PassphraseAuth.test.ts +5 -5
  158. package/src/tools/tests/deleteCoValues.test.ts +231 -0
  159. package/src/tools/tests/deletedState.test.ts +110 -0
  160. package/src/tools/tests/request.test.ts +15 -2
  161. package/src/worker/edge-wasm.ts +2 -1
  162. package/src/worker/wasm.ts +1 -0
  163. package/tsup.config.ts +0 -4
  164. package/dist/browser/storageOptions.d.ts +0 -8
  165. package/dist/browser/storageOptions.d.ts.map +0 -1
  166. package/dist/browser/tests/storageOptions.test.d.ts +0 -2
  167. package/dist/browser/tests/storageOptions.test.d.ts.map +0 -1
  168. package/dist/chunk-M2HGBOXS.js.map +0 -1
  169. package/dist/chunk-QCTQH5RS.js.map +0 -1
  170. package/dist/expo/crypto.d.ts +0 -2
  171. package/dist/expo/crypto.d.ts.map +0 -1
  172. package/dist/expo/crypto.js +0 -6
  173. package/dist/expo/crypto.js.map +0 -1
  174. package/dist/inspector/chunk-YQNK5Y7B.js.map +0 -1
  175. package/dist/react-core/chunk-7DYMJ74I.js +0 -12
  176. package/dist/react-core/chunk-7DYMJ74I.js.map +0 -1
  177. package/dist/react-native/chunk-DGUM43GV.js +0 -11
  178. package/dist/react-native/chunk-DGUM43GV.js.map +0 -1
  179. package/dist/react-native/crypto.d.ts +0 -2
  180. package/dist/react-native/crypto.d.ts.map +0 -1
  181. package/dist/react-native/crypto.js +0 -8
  182. package/dist/react-native/crypto.js.map +0 -1
  183. package/dist/react-native-core/chunk-DGUM43GV.js +0 -11
  184. package/dist/react-native-core/chunk-DGUM43GV.js.map +0 -1
  185. package/dist/react-native-core/crypto/RNCrypto.d.ts +0 -2
  186. package/dist/react-native-core/crypto/RNCrypto.d.ts.map +0 -1
  187. package/dist/react-native-core/crypto/RNCrypto.js +0 -3
  188. package/dist/react-native-core/crypto/RNCrypto.js.map +0 -1
  189. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts +0 -17
  190. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts.map +0 -1
  191. package/dist/react-native-core/crypto/index.d.ts +0 -2
  192. package/dist/react-native-core/crypto/index.d.ts.map +0 -1
  193. package/dist/react-native-core/crypto.js +0 -89
  194. package/dist/react-native-core/crypto.js.map +0 -1
  195. package/src/browser/storageOptions.ts +0 -17
  196. package/src/browser/tests/storageOptions.test.ts +0 -33
  197. package/src/expo/crypto.ts +0 -1
  198. package/src/react-native/crypto.ts +0 -1
  199. package/src/react-native-core/crypto/RNCrypto.ts +0 -1
  200. package/src/react-native-core/crypto/RNQuickCrypto.ts +0 -122
  201. package/src/react-native-core/crypto/index.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react-core/hooks.ts","../../src/react-core/utils.ts","../../src/react-core/use.ts","../../src/react-core/subscription-provider.tsx","../../src/react-core/auth/DemoAuth.tsx","../../src/react-core/auth/PassphraseAuth.tsx"],"sourcesContent":["import { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector\";\nimport React, {\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport {\n Account,\n AccountClass,\n AnonymousJazzAgent,\n AnyAccountSchema,\n CoValue,\n CoValueClassOrSchema,\n CoValueLoadingState,\n ExportedCoValue,\n InboxSender,\n InstanceOfSchema,\n JazzContextManager,\n JazzContextType,\n Loaded,\n MaybeLoaded,\n NotLoaded,\n ResolveQuery,\n ResolveQueryStrict,\n SchemaResolveQuery,\n SubscriptionScope,\n importContentPieces,\n captureStack,\n getUnloadedCoValueWithoutId,\n type BranchDefinition,\n} from \"jazz-tools\";\nimport { JazzContext, JazzContextManagerContext } from \"./provider.js\";\nimport { getCurrentAccountFromContextManager } from \"./utils.js\";\nimport { CoValueSubscription } from \"./types.js\";\nimport { use } from \"./use.js\";\n\nexport function useJazzContext<Acc extends Account>() {\n const value = useContext(JazzContext) as JazzContextType<Acc>;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useJazzContextManager<Acc extends Account>() {\n const value = useContext(JazzContextManagerContext) as JazzContextManager<\n Acc,\n {}\n >;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useAuthSecretStorage() {\n const value = useContext(JazzContextManagerContext);\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this useAuthSecretStorage.\",\n );\n }\n\n return value.getAuthSecretStorage();\n}\n\nexport function useIsAuthenticated() {\n const authSecretStorage = useAuthSecretStorage();\n\n return useSyncExternalStore(\n useCallback(\n (callback) => {\n return authSecretStorage.onUpdate(callback);\n },\n [authSecretStorage],\n ),\n () => authSecretStorage.isAuthenticated,\n () => authSecretStorage.isAuthenticated,\n );\n}\n\nexport function useCoValueSubscription<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n>(\n Schema: S,\n id: string | undefined | null,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n): CoValueSubscription<S, R> | null {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptions = useCoValueSubscriptions(\n Schema,\n [id],\n resolve,\n options?.unstable_branch,\n );\n return (subscriptions[0] ?? null) as CoValueSubscription<S, R> | null;\n}\n\n/**\n * Tracked state for the entire subscriptions array.\n * If any of the dependencies change, the subscriptions are recreated.\n */\ninterface SubscriptionsState {\n subscriptions: (SubscriptionScope<CoValue> | null)[];\n schema: CoValueClassOrSchema;\n ids: readonly (string | undefined | null)[];\n resolve: ResolveQuery<any>;\n contextManager: ReturnType<typeof useJazzContextManager>;\n agent: AnonymousJazzAgent | Loaded<any, true>;\n branchName?: string;\n branchOwnerId?: string;\n}\n\n/**\n * Internal hook that manages an array of SubscriptionScope instances.\n *\n * - Uses a ref to track subscriptions by index\n * - Detects changes by comparing schema/ids/resolve/branch\n * - Creates new subscriptions via SubscriptionScopeCache.getOrCreate()\n * - Returns null for entries with undefined/null IDs or invalid branches\n */\nfunction useCoValueSubscriptions(\n schema: CoValueClassOrSchema,\n ids: readonly (string | undefined | null)[],\n resolve: ResolveQuery<any>,\n branch?: BranchDefinition,\n): (SubscriptionScope<CoValue> | null)[] {\n const contextManager = useJazzContextManager();\n const agent = useAgent();\n\n const callerStack = useMemo(() => captureStack(), []);\n\n const createAllSubscriptions = (): SubscriptionsState => {\n const node = contextManager.getCurrentValue()!.node;\n const cache = contextManager.getSubscriptionScopeCache();\n\n const subscriptions = ids.map((id) => {\n if (id === undefined || id === null) {\n return null;\n }\n\n const subscription = cache.getOrCreate(\n node,\n schema,\n id,\n resolve,\n false,\n false,\n branch,\n );\n\n if (callerStack) {\n subscription.callerStack = callerStack;\n }\n\n return subscription;\n });\n\n return {\n subscriptions,\n schema,\n ids,\n resolve,\n contextManager,\n agent,\n branchName: branch?.name,\n branchOwnerId: branch?.owner?.$jazz.id,\n };\n };\n\n const stateRef = React.useRef<SubscriptionsState | null>(null);\n const newSubscriptions = createAllSubscriptions();\n\n const state = stateRef.current;\n\n // Avoid recreating the subscriptions array if all subscriptions are already cached\n const anySubscriptionChanged =\n newSubscriptions.subscriptions.length !== state?.subscriptions.length ||\n newSubscriptions.subscriptions.some(\n (newSubscriptions, index) =>\n newSubscriptions !== state.subscriptions[index],\n );\n\n if (anySubscriptionChanged) {\n stateRef.current = newSubscriptions;\n }\n\n return stateRef.current!.subscriptions;\n}\n\nfunction useImportCoValueContent<V>(\n id: string | undefined | null,\n content?: ExportedCoValue<V>,\n) {\n const agent = useAgent();\n const preloadExecuted = useRef<typeof agent | null>(null);\n if (content && preloadExecuted.current !== agent && id) {\n if (content.id === id) {\n importContentPieces(content.contentPieces, agent);\n } else {\n console.warn(\"Preloaded value ID does not match the subscription ID\");\n }\n\n preloadExecuted.current = agent;\n }\n}\n\nfunction useGetCurrentValue<C extends CoValue>(\n subscription: SubscriptionScope<C> | null,\n) {\n return useCallback(() => {\n if (!subscription) {\n return getUnloadedCoValueWithoutId(CoValueLoadingState.UNAVAILABLE);\n }\n\n return subscription.getCurrentValue();\n }, [subscription]);\n}\n\n/**\n * React hook for subscribing to CoValues and handling loading states.\n *\n * This hook provides a convenient way to subscribe to CoValues and automatically\n * handles the subscription lifecycle (subscribe on mount, unsubscribe on unmount).\n * It also supports deep loading of nested CoValues through resolve queries.\n *\n * The {@param options.select} function allows returning only specific parts of the CoValue data,\n * which helps reduce unnecessary re-renders by narrowing down the returned data.\n * Additionally, you can provide a custom {@param options.equalityFn} to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * @returns The loaded CoValue, or an {@link NotLoaded} value. Use `$isLoaded` to check whether the\n * CoValue is loaded, or use {@link MaybeLoaded.$jazz.loadingState} to get the detailed loading state.\n * If a selector function is provided, returns the result of the selector function.\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const Project = co.map({\n * name: z.string(),\n * description: z.string(),\n * tasks: co.list(Task),\n * lastModified: z.date(),\n * });\n *\n * function ProjectTitle({ projectId }: { projectId: string }) {\n * // Only re-render when the project name changes, not other fields\n * const projectName = useCoState(\n * Project,\n * projectId,\n * {\n * select: (project) => !project.$isLoading ? project.name : \"Loading...\",\n * }\n * );\n *\n * return <h1>{projectName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * const Project = co.map({\n * name: z.string(),\n * tasks: co.list(Task),\n * owner: TeamMember,\n * });\n *\n * function ProjectView({ projectId }: { projectId: string }) {\n * const project = useCoState(Project, projectId, {\n * resolve: {\n * tasks: { $each: true },\n * owner: true,\n * },\n * });\n *\n * if (!project.$isLoaded) {\n * switch (project.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Project not accessible\";\n * case \"unavailable\":\n * return \"Project not found\";\n * case \"loading\":\n * return \"Loading project...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h1>{project.name}</h1>\n * <p>Owner: {project.owner.name}</p>\n * <ul>\n * {project.tasks.map((task) => (\n * <li key={task.id}>{task.title}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Using with optional references and error handling\n * const Task = co.map({\n * title: z.string(),\n * assignee: co.optional(TeamMember),\n * subtasks: co.list(Task),\n * });\n *\n * function TaskDetail({ taskId }: { taskId: string }) {\n * const task = useCoState(Task, taskId, {\n * resolve: {\n * assignee: true,\n * subtasks: { $each: { $onError: 'catch' } },\n * },\n * });\n *\n * if (!task.$isLoaded) {\n * switch (task.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Task not accessible\";\n * case \"unavailable\":\n * return \"Task not found\";\n * case \"loading\":\n * return \"Loading task...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h2>{task.title}</h2>\n * {task.assignee && <p>Assigned to: {task.assignee.name}</p>}\n * <ul>\n * {task.subtasks.map((subtask, index) => (\n * subtask.$isLoaded ? <li key={subtask.id}>{subtask.title}</li> : <li key={index}>Inaccessible subtask</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Use custom equality function for complex data structures\n * const TaskList = co.list(Task);\n *\n * function TaskCount({ listId }: { listId: string }) {\n * const taskStats = useCoState(\n * TaskList,\n * listId,\n * {\n * resolve: { $each: true },\n * select: (tasks) => {\n * if (!tasks.$isLoaded) return { total: 0, completed: 0 };\n * return {\n * total: tasks.length,\n * completed: tasks.filter(task => task.completed).length,\n * };\n * },\n * // Custom equality to prevent re-renders when stats haven't changed\n * equalityFn: (a, b) => a.total === b.total && a.completed === b.completed,\n * }\n * );\n *\n * return (\n * <div>\n * {taskStats.completed} of {taskStats.total} tasks completed\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoState<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = MaybeLoaded<Loaded<S, R>>,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns an `unavailable` value */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select?: (value: MaybeLoaded<Loaded<S, R>>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n preloaded?: ExportedCoValue<Loaded<S, R>>;\n },\n): TSelectorReturn {\n useImportCoValueContent(id, options?.preloaded);\n const subscription = useCoValueSubscription(Schema, id, options);\n return useSubscriptionSelector(subscription, options);\n}\n\nexport function useSuspenseCoState<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = Loaded<S, R>,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to */\n id: string,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n preloaded?: ExportedCoValue<Loaded<S, R>>;\n },\n): TSelectorReturn {\n useImportCoValueContent(id, options?.preloaded);\n\n const subscription = useCoValueSubscription(Schema, id, options);\n\n if (!subscription) {\n throw new Error(\"Subscription not found\");\n }\n\n use(subscription.getCachedPromise());\n\n return useSubscriptionSelector(subscription, options);\n}\n\n/**\n * Returns a subscription's current value.\n * Allows to optionally select a subset of the subscription's value.\n *\n * This is the single-value counterpart to {@link useSubscriptionsSelector}.\n * Keeping it separate for performance reasons.\n */\nexport function useSubscriptionSelector<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n // Selector input can be an already loaded or a maybe-loaded value,\n // depending on whether a suspense hook is used or not, respectively.\n TSelectorInput = MaybeLoaded<Loaded<S, R>>,\n TSelectorReturn = TSelectorInput,\n>(\n subscription: CoValueSubscription<S, R>,\n options?: {\n select?: (value: TSelectorInput) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n },\n): TSelectorReturn {\n const getCurrentValue = useGetCurrentValue(subscription);\n\n return useSyncExternalStoreWithSelector(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n getCurrentValue,\n getCurrentValue,\n options?.select ?? ((value) => value as unknown as TSelectorReturn),\n options?.equalityFn ?? Object.is,\n );\n}\n\nexport function useAccountSubscription<\n S extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n>(\n Schema: S,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContextManager();\n\n // Capture stack trace at hook call time\n const callerStack = useMemo(() => captureStack(), []);\n\n const createSubscription = () => {\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n if (agent.$type$ === \"Anonymous\") {\n return {\n subscription: null,\n contextManager,\n agent,\n };\n }\n\n const resolve = getResolveQuery(Schema, options?.resolve);\n\n const node = contextManager.getCurrentValue()!.node;\n const cache = contextManager.getSubscriptionScopeCache();\n const subscription = cache.getOrCreate(\n node,\n Schema,\n agent.$jazz.id,\n resolve,\n false,\n false,\n options?.unstable_branch,\n );\n\n // Set callerStack on returned subscription after retrieval\n if (callerStack) {\n subscription.callerStack = callerStack;\n }\n\n return {\n subscription,\n contextManager,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.Schema !== Schema ||\n subscription.branchName !== options?.unstable_branch?.name ||\n subscription.branchOwnerId !== options?.unstable_branch?.owner?.$jazz.id\n ) {\n // No need to manually destroy - cache handles cleanup via SubscriptionScope lifecycle\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n // No need to manually destroy - cache handles cleanup via SubscriptionScope lifecycle\n setSubscription(createSubscription());\n });\n }, [Schema, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription as CoValueSubscription<S, R>;\n}\n\n/**\n * React hook for accessing the current user's account.\n *\n * This hook provides access to the current user's account profile and root data.\n * It automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries.\n *\n * The {@param options.select} function allows returning only specific parts of the account data,\n * which helps reduce unnecessary re-renders by narrowing down the returned data.\n * Additionally, you can provide a custom {@param options.equalityFn} to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * @returns The account data, or an {@link NotLoaded} value. Use `$isLoaded` to check whether the\n * CoValue is loaded, or use {@link MaybeLoaded.$jazz.loadingState} to get the detailed loading state.\n * If a selector function is provided, returns the result of the selector function.\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const MyAppAccount = co.account({\n * profile: co.profile(),\n * root: co.map({\n * name: z.string(),\n * email: z.string(),\n * lastLogin: z.date(),\n * }),\n * });\n *\n * function UserProfile({ accountId }: { accountId: string }) {\n * // Only re-render when the profile name changes, not other fields\n * const profileName = useAccount(\n * MyAppAccount,\n * {\n * resolve: {\n * profile: true,\n * root: true,\n * },\n * select: (account) => account.$isLoaded ? account.profile.name : \"Loading...\",\n * }\n * );\n *\n * return <h1>{profileName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * function ProjectListWithDetails() {\n * const me = useAccount(MyAppAccount, {\n * resolve: {\n * profile: true,\n * root: {\n * myProjects: {\n * $each: {\n * tasks: true,\n * },\n * },\n * },\n * },\n * });\n *\n * if (!me.$isLoaded) {\n * switch (me.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Account not accessible\";\n * case \"unavailable\":\n * return \"Account not found\";\n * case \"loading\":\n * return \"Loading account...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h1>{me.profile.name}'s projects</h1>\n * <ul>\n * {me.root.myProjects.map((project) => (\n * <li key={project.id}>\n * {project.name} ({project.tasks.length} tasks)\n * </li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n */\nexport function useAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<A> = SchemaResolveQuery<A>,\n TSelectorReturn = MaybeLoaded<Loaded<A, R>>,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select?: (account: MaybeLoaded<Loaded<A, R>>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n return useSubscriptionSelector(subscription, options);\n}\n\nexport function useSuspenseAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<A> = SchemaResolveQuery<A>,\n TSelectorReturn = Loaded<A, R>,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select?: (account: Loaded<A, R>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n\n if (!subscription) {\n throw new Error(\n \"Subscription not found, are you using useSuspenseAccount in guest mode?\",\n );\n }\n\n use(subscription.getCachedPromise());\n\n return useSubscriptionSelector(subscription, options);\n}\n\n/**\n * Returns a function for logging out of the current account.\n */\nexport function useLogOut(): () => void {\n const contextManager = useJazzContextManager();\n return contextManager.logOut;\n}\n\n/**\n * React hook for accessing the current agent. An agent can either be:\n * - an Authenticated Account, if the user is logged in\n * - an Anonymous Account, if the user didn't log in\n * - or an anonymous agent, if in guest mode\n *\n * The agent can be used as the `loadAs` parameter for load and subscribe methods.\n */\nexport function useAgent<\n A extends AccountClass<Account> | AnyAccountSchema = typeof Account,\n>(): AnonymousJazzAgent | Loaded<A, true> {\n const contextManager = useJazzContextManager<InstanceOfSchema<A>>();\n\n const getCurrentValue = () =>\n getCurrentAccountFromContextManager(contextManager) as\n | AnonymousJazzAgent\n | Loaded<A, true>;\n\n return React.useSyncExternalStore(\n useCallback(\n (callback) => {\n return contextManager.subscribe(callback);\n },\n [contextManager],\n ),\n getCurrentValue,\n getCurrentValue,\n );\n}\n\nexport function experimental_useInboxSender<\n I extends CoValue,\n O extends CoValue | undefined,\n>(inboxOwnerID: string | undefined) {\n const context = useJazzContext();\n\n if (!(\"me\" in context)) {\n throw new Error(\n \"useInboxSender can't be used in a JazzProvider with auth === 'guest'.\",\n );\n }\n\n const me = context.me;\n const inboxRef = useRef<Promise<InboxSender<I, O>> | undefined>(undefined);\n\n const sendMessage = useCallback(\n async (message: I) => {\n if (!inboxOwnerID) throw new Error(\"Inbox owner ID is required\");\n\n if (!inboxRef.current) {\n const inbox = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = inbox;\n }\n\n let inbox = await inboxRef.current;\n\n // Regenerate the InboxSender if the inbox owner or current account changes\n if (inbox.owner.id !== inboxOwnerID || inbox.currentAccount !== me) {\n const req = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = req;\n inbox = await req;\n }\n\n return inbox.sendMessage(message);\n },\n [inboxOwnerID, me.$jazz.id],\n );\n\n return sendMessage;\n}\n\n/**\n * Hook that returns the current connection status to the Jazz sync server.\n *\n * @returns `true` when connected to the server, `false` when disconnected\n *\n * @remarks\n * On connection drop, this hook will return `false` only when Jazz detects the disconnection\n * after 5 seconds of not receiving a ping from the server.\n */\nexport function useSyncConnectionStatus() {\n const context = useJazzContext();\n\n const connected = useSyncExternalStore(\n useCallback(\n (callback) => {\n return context.addConnectionListener(callback);\n },\n [context],\n ),\n () => context.connected(),\n () => context.connected(),\n );\n\n return connected;\n}\n\nfunction getResolveQuery(\n Schema: CoValueClassOrSchema,\n // We don't need type validation here, since this is an internal API\n resolveQuery?: ResolveQuery<any>,\n): ResolveQuery<any> {\n if (resolveQuery) {\n return resolveQuery;\n }\n // Check the schema is a CoValue schema (and not a CoValue class)\n if (\"resolveQuery\" in Schema) {\n return Schema.resolveQuery;\n }\n return true;\n}\n\n/**\n * Internal hook that suspends until all values are loaded.\n *\n * - Creates a Promise.all from individual getCachedPromise() calls\n * - Returns Promise.resolve(null) for null subscriptions (undefined/null IDs)\n * - Suspends via the use() hook until all values are loaded\n */\nfunction useSuspendUntilLoaded(\n subscriptions: (SubscriptionScope<CoValue> | null)[],\n): void {\n const combinedPromise = useMemo(() => {\n const promises = subscriptions.map((sub) => {\n if (!sub) {\n // For null subscriptions (undefined/null IDs), resolve immediately with null\n return Promise.resolve(null);\n }\n return sub.getCachedPromise();\n });\n\n return Promise.all(promises);\n }, [subscriptions]);\n\n use(combinedPromise);\n}\n\n/**\n * Internal hook that uses useSyncExternalStore to subscribe to multiple SubscriptionScopes.\n *\n * - Creates a combined subscribe function that subscribes to all scopes\n * - Returns an array of current values from each scope\n * - Maintains stable references for unchanged values\n *\n * @param subscriptions - Array of SubscriptionScope instances (or null for skipped entries)\n * @returns Array of loaded CoValues (or null for skipped entries)\n */\nfunction useSubscriptionsSelector<\n T extends CoValue[] | MaybeLoaded<CoValue>[],\n // Selector input can be an already loaded or a maybe-loaded value,\n // depending on whether a suspense hook is used or not, respectively.\n TSelectorInput = T[number],\n TSelectorReturn = TSelectorInput,\n>(\n subscriptions: SubscriptionScope<CoValue>[],\n options?: {\n select?: (value: TSelectorInput) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n },\n): TSelectorReturn[] {\n // Combined subscribe function that subscribes to all scopes\n const subscribe = useCallback(\n (callback: () => void) => {\n const unsubscribes = subscriptions.map((sub) => sub.subscribe(callback));\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n },\n [subscriptions],\n );\n\n // Cache current values to avoid infinite loops\n const cachedCurrentValuesRef = useRef<T>([] as unknown as T);\n const getCurrentValues = useCallback(() => {\n const newValues = subscriptions.map((sub) => sub.getCurrentValue());\n\n // Check if values have changed by comparing each element\n const cached = cachedCurrentValuesRef.current;\n const hasChanged =\n cached.length !== newValues.length ||\n newValues.some((value, index) => value !== cached[index]);\n\n if (hasChanged) {\n cachedCurrentValuesRef.current = newValues as T;\n }\n\n return cachedCurrentValuesRef.current as unknown as TSelectorInput[];\n }, [subscriptions]);\n\n const selectFn = useMemo(() => {\n if (!options?.select) {\n return (values: TSelectorInput[]) =>\n values as unknown as TSelectorReturn[];\n }\n return (values: TSelectorInput[]) =>\n values.map((value) => options.select!(value));\n }, [options?.select]);\n\n const elementEqualityFn = useMemo(\n () => options?.equalityFn ?? Object.is,\n [options?.equalityFn],\n );\n const equalityFn = useMemo(() => {\n return (a: TSelectorReturn[], b: TSelectorReturn[]) =>\n a.length === b.length &&\n a.every((value, index) => elementEqualityFn(value, b[index]));\n }, [elementEqualityFn]);\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getCurrentValues,\n getCurrentValues,\n selectFn,\n equalityFn,\n );\n}\n\n/**\n * Subscribe to multiple CoValues with unified Suspense handling.\n *\n * This hook accepts a list of CoValue IDs and returns an array of loaded values,\n * suspending until all values are available.\n *\n * @param Schema - The CoValue schema or class constructor\n * @param ids - Array of CoValue IDs to subscribe to\n * @param options - Optional configuration, including resolve query\n * @returns An array of loaded CoValues in the same order as the input IDs\n */\nexport function useSuspenseCoStates<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = Loaded<S, R>,\n>(\n Schema: S,\n ids: readonly string[],\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return. Applies to each element individually. */\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n /** Equality function to determine if a selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn[] {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptionScopes = useCoValueSubscriptions(\n Schema,\n ids,\n resolve,\n options?.unstable_branch,\n ) as SubscriptionScope<CoValue>[];\n useSuspendUntilLoaded(subscriptionScopes);\n return useSubscriptionsSelector(subscriptionScopes, options);\n}\n\n/**\n * Subscribe to multiple CoValues without Suspense.\n *\n * This hook accepts a list of CoValue IDs and returns an array of maybe-loaded values.\n * Unlike `useSuspenseCoStates`, this hook does not suspend and returns loading/unavailable\n * states that can be checked via the `$isLoaded` property.\n *\n * @param Schema - The CoValue schema or class constructor\n * @param ids - Array of CoValue IDs to subscribe to\n * @param options - Optional configuration, including resolve query\n * @returns An array of MaybeLoaded CoValues in the same order as the input IDs\n *\n * @example\n * ```typescript\n * const [project1, project2] = useCoStates(\n * ProjectSchema,\n * [projectId1, projectId2],\n * { resolve: { assignee: true } }\n * );\n *\n * if (!project1.$isLoaded || !project2.$isLoaded) {\n * return <Loading />;\n * }\n * ```\n */\nexport function useCoStates<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = MaybeLoaded<Loaded<S, R>>,\n>(\n Schema: S,\n ids: readonly string[],\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return. Applies to each element individually. */\n select?: (value: MaybeLoaded<Loaded<S, R>>) => TSelectorReturn;\n /** Equality function to determine if a selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn[] {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptionScopes = useCoValueSubscriptions(\n Schema,\n ids,\n resolve,\n options?.unstable_branch,\n ) as SubscriptionScope<CoValue>[];\n return useSubscriptionsSelector(subscriptionScopes, options);\n}\n","import { Account, JazzContextManager } from \"jazz-tools\";\n\nexport function getCurrentAccountFromContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n) {\n const context = contextManager.getCurrentValue();\n\n if (!context) {\n throw new Error(\"No context found\");\n }\n\n return \"me\" in context ? context.me : context.guest;\n}\n\nexport function subscribeToContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n callback: () => () => void,\n) {\n let unsub = () => {};\n\n const handler = () => {\n unsub();\n unsub = callback();\n };\n\n handler();\n return contextManager.subscribe(handler);\n}\n","import React from \"react\";\n\n// shim from https://github.com/pmndrs/jotai/blob/f287c5d665a807e676bc731e83174c62c1fe1fc9/src/react/useAtomValue.ts#L13C1-L56C1\nconst attachPromiseStatus = <T>(\n promise: PromiseLike<T> & {\n status?: \"pending\" | \"fulfilled\" | \"rejected\";\n value?: T;\n reason?: unknown;\n },\n) => {\n if (!promise.status) {\n promise.status = \"pending\";\n promise.then(\n (v) => {\n promise.status = \"fulfilled\";\n promise.value = v;\n },\n (e) => {\n promise.status = \"rejected\";\n promise.reason = e;\n },\n );\n }\n};\n\nexport const use =\n React.use ||\n // A shim for older React versions\n (<T>(\n promise: PromiseLike<T> & {\n status?: \"pending\" | \"fulfilled\" | \"rejected\";\n value?: T;\n reason?: unknown;\n },\n ): T => {\n if (promise.status === \"pending\") {\n throw promise;\n } else if (promise.status === \"fulfilled\") {\n return promise.value as T;\n } else if (promise.status === \"rejected\") {\n throw promise.reason;\n } else {\n attachPromiseStatus(promise);\n throw promise;\n }\n });\n","import React from \"react\";\nimport {\n Account,\n AccountClass,\n AnyAccountSchema,\n CoValueClassOrSchema,\n CoValueLoadingState,\n Loaded,\n MaybeLoaded,\n ResolveQuery,\n ResolveQueryStrict,\n} from \"jazz-tools\";\nimport {\n useAccountSubscription,\n useCoValueSubscription,\n useSubscriptionSelector,\n} from \"./hooks.js\";\nimport type { CoValueSubscription } from \"./types.js\";\n\nexport function createCoValueSubscriptionContext<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S> = true,\n>(schema: S, resolve?: ResolveQueryStrict<S, R>) {\n const Context = React.createContext<CoValueSubscription<S, R>>(null);\n\n return {\n Provider: ({\n id,\n options,\n loadingFallback,\n unavailableFallback,\n children,\n }: React.PropsWithChildren<{\n id: string | undefined | null;\n options?: Omit<\n Parameters<typeof useCoValueSubscription<S, R>>[2],\n \"resolve\"\n >;\n loadingFallback?: React.ReactNode;\n unavailableFallback?: React.ReactNode;\n }>) => {\n const subscription = useCoValueSubscription(schema, id, {\n ...options,\n resolve: resolve,\n });\n\n const loadState = useSubscriptionSelector(subscription, {\n select: (value) => value.$jazz.loadingState,\n });\n\n if (loadState === CoValueLoadingState.LOADING) {\n return loadingFallback ?? null;\n }\n if (\n loadState === CoValueLoadingState.UNAUTHORIZED ||\n loadState === CoValueLoadingState.UNAVAILABLE\n ) {\n return unavailableFallback ?? null;\n }\n\n return (\n <Context.Provider value={subscription}>{children}</Context.Provider>\n );\n },\n useSelector: <TSelectorReturn = Loaded<S, R>>(options?: {\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n }) => {\n const subscription = React.useContext(Context);\n\n if (!subscription) {\n throw new Error(\n \"useSelector must be used within a coValue subscription provider\",\n );\n }\n\n return useSubscriptionSelector<S, R, TSelectorReturn>(\n subscription,\n options as Parameters<\n typeof useSubscriptionSelector<S, R, TSelectorReturn>\n >[1],\n );\n },\n };\n}\n\nexport function createAccountSubscriptionContext<\n A extends AccountClass<Account> | AnyAccountSchema,\n const R extends ResolveQuery<A> = true,\n>(schema: A, resolve?: ResolveQueryStrict<A, R>) {\n const Context = React.createContext<CoValueSubscription<A, R>>(null);\n\n return {\n Provider: ({\n options,\n loadingFallback,\n unavailableFallback,\n children,\n }: React.PropsWithChildren<{\n options?: Omit<\n Parameters<typeof useAccountSubscription<A, R>>[1],\n \"resolve\"\n >;\n loadingFallback?: React.ReactNode;\n unavailableFallback?: React.ReactNode;\n }>) => {\n const subscription = useAccountSubscription(schema, {\n ...options,\n resolve: resolve,\n });\n\n const loadState = useSubscriptionSelector(subscription, {\n select: (value) => value.$jazz.loadingState,\n });\n\n if (loadState === CoValueLoadingState.LOADING) {\n return loadingFallback ?? null;\n }\n\n if (\n loadState === CoValueLoadingState.UNAUTHORIZED ||\n loadState === CoValueLoadingState.UNAVAILABLE\n ) {\n return unavailableFallback ?? null;\n }\n\n return (\n <Context.Provider value={subscription}>{children}</Context.Provider>\n );\n },\n useSelector: <TSelectorReturn = Loaded<A, R>>(options?: {\n select?: (value: Loaded<A, R>) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n }) => {\n const subscription = React.useContext(Context);\n\n if (!subscription) {\n throw new Error(\n \"useSelector must be used within an account subscription provider\",\n );\n }\n\n return useSubscriptionSelector<A, R, TSelectorReturn>(\n subscription,\n options as Parameters<\n typeof useSubscriptionSelector<A, R, TSelectorReturn>\n >[1],\n );\n },\n };\n}\n","import { DemoAuth } from \"jazz-tools\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `useDemoAuth` is a hook that provides a `JazzAuth` object for demo authentication.\n *\n *\n * ```ts\n * const { state, logIn, signUp, existingUsers } = useDemoAuth();\n * ```\n *\n * @category Auth Providers\n */\nexport function useDemoAuth() {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Demo auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new DemoAuth(context.authenticate, authSecretStorage);\n }, []);\n\n const isAuthenticated = useIsAuthenticated();\n const [existingUsers, setExistingUsers] = useState<string[]>([]);\n\n useEffect(() => {\n authMethod.getExistingUsers().then(setExistingUsers);\n }, [authMethod]);\n\n function handleSignUp(username: string) {\n return authMethod.signUp(username).then(() => {\n setExistingUsers(existingUsers.concat([username]));\n });\n }\n\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: handleSignUp,\n existingUsers,\n } as const;\n}\n","import { PassphraseAuth } from \"jazz-tools\";\nimport { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `usePassphraseAuth` hook provides a `JazzAuth` object for passphrase authentication.\n *\n * @example\n * ```ts\n * const auth = usePassphraseAuth({ appName, appHostname, wordlist });\n * ```\n *\n * @category Auth Providers\n */\nexport function usePassphraseAuth({ wordlist }: { wordlist: string[] }) {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Passphrase auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new PassphraseAuth(\n context.node.crypto,\n context.authenticate,\n context.register,\n authSecretStorage,\n wordlist,\n );\n }, [wordlist]);\n\n const passphrase = useSyncExternalStore(\n useCallback(\n (callback) => {\n authMethod.loadCurrentAccountPassphrase();\n return authMethod.subscribe(callback);\n },\n [authMethod],\n ),\n () => authMethod.passphrase,\n );\n\n const isAuthenticated = useIsAuthenticated();\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: authMethod.signUp,\n registerNewAccount: authMethod.registerNewAccount,\n generateRandomPassphrase: authMethod.generateRandomPassphrase,\n passphrase,\n } as const;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,wCAAwC;AACjD,OAAOA;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAMA;AAAA,EAEA;AAAA,EAWA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;AC/BA,SAAS,oCACd,gBACA;AACA,QAAM,UAAU,eAAe,gBAAgB;AAE/C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kBAAkB;AAAA,EACpC;AA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AAC;AAAA,IACnD,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,OAAO,kBAAkB,aAAa;AAAA,IACtC,OAAO,WAAW;AAAA,IAClB,QAAQ;AAAA,IACR;AAAA,EACF;AACF;;;AC9CA,SAAS,sBAAsB;AAC/B,SAAS,eAAAC,cAAa,WAAAC,UAAS,wBAAAC,6BAA4B;AAcpD,SAAS,kBAAkB,EAAE,SAAS,GAA2B;AACtE,QAAM,UAAU,eAAe;AAC/B,QAAM,oBAAoB,qBAAqB;AAE/C,MAAI,WAAW,SAAS;AACtB,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEA,QAAM,aAAaC,SAAQ,MAAM;AAC/B,WAAO,IAAI;AAAA,MACT,QAAQ,KAAK;AAAA,MACb,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,QAAM,aAAaC;AAAA,IACjBC;AAAA,MACE,CAAC,aAAa;AACZ,mBAAW,6BAA6B;AACxC,eAAO,WAAW,UAAU,QAAQ;AAAA,MACtC;AAAA,MACA,CAAC,UAAU;AAAA,IACb;AAAA,IACA,MAAM,WAAW;AAAA,EACnB;AAEA,QAAM,kBAAkB,mBAAmB;AAC3C,SAAO;AAAA,IACL,OAAO,kBAAkB,aAAa;AAAA,IACtC,OAAO,WAAW;AAAA,IAClB,QAAQ,WAAW;AAAA,IACnB,oBAAoB,WAAW;AAAA,IAC/B,0BAA0B,WAAW;AAAA,IACrC;AAAA,EACF;AACF;","names":["React","React","newSubscriptions","subscription","inbox","React","CoValueLoadingState","React","CoValueLoadingState","useMemo","useMemo","useCallback","useMemo","useSyncExternalStore","useMemo","useSyncExternalStore","useCallback"]}
1
+ {"version":3,"sources":["../../src/react-core/hooks.ts","../../src/react-core/utils.ts","../../src/react-core/use.ts","../../src/react-core/subscription-provider.tsx","../../src/react-core/auth/DemoAuth.tsx","../../src/react-core/auth/PassphraseAuth.tsx"],"sourcesContent":["import { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector\";\nimport React, {\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport {\n Account,\n AccountClass,\n AnonymousJazzAgent,\n AnyAccountSchema,\n CoValue,\n CoValueClassOrSchema,\n CoValueLoadingState,\n ExportedCoValue,\n InboxSender,\n InstanceOfSchema,\n JazzContextManager,\n Loaded,\n MaybeLoaded,\n NotLoaded,\n ResolveQuery,\n ResolveQueryStrict,\n SchemaResolveQuery,\n SubscriptionScope,\n importContentPieces,\n captureStack,\n getUnloadedCoValueWithoutId,\n type BranchDefinition,\n} from \"jazz-tools\";\nimport { JazzContext } from \"./provider.js\";\nimport { getCurrentAccountFromContextManager } from \"./utils.js\";\nimport { CoValueSubscription } from \"./types.js\";\nimport { use } from \"./use.js\";\n\nexport function useJazzContext<Acc extends Account>() {\n const value = useContext(JazzContext) as JazzContextManager<Acc, {}>;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useJazzContextValue<Acc extends Account>() {\n const contextManager = useJazzContext<Acc>();\n\n const context = useSyncExternalStore(\n useCallback(\n (callback) => {\n return contextManager.subscribe(callback);\n },\n [contextManager],\n ),\n () => contextManager.getCurrentValue(),\n () => contextManager.getCurrentValue(),\n );\n\n if (!context) {\n throw new Error(\n \"The JazzProvider is not initialized yet. This looks like a bug, please report it.\",\n );\n }\n\n return context;\n}\n\nexport function useAuthSecretStorage() {\n return useJazzContext().getAuthSecretStorage();\n}\n\nexport function useIsAuthenticated() {\n const authSecretStorage = useAuthSecretStorage();\n\n return useSyncExternalStore(\n useCallback(\n (callback) => {\n return authSecretStorage.onUpdate(callback);\n },\n [authSecretStorage],\n ),\n () => authSecretStorage.isAuthenticated,\n () => authSecretStorage.isAuthenticated,\n );\n}\n\nexport function useCoValueSubscription<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n>(\n Schema: S,\n id: string | undefined | null,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n): CoValueSubscription<S, R> | null {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptions = useCoValueSubscriptions(\n Schema,\n [id],\n resolve,\n options?.unstable_branch,\n );\n return (subscriptions[0] ?? null) as CoValueSubscription<S, R> | null;\n}\n\n/**\n * Tracked state for the entire subscriptions array.\n * If any of the dependencies change, the subscriptions are recreated.\n */\ninterface SubscriptionsState {\n subscriptions: (SubscriptionScope<CoValue> | null)[];\n schema: CoValueClassOrSchema;\n ids: readonly (string | undefined | null)[];\n resolve: ResolveQuery<any>;\n contextManager: ReturnType<typeof useJazzContext>;\n agent: AnonymousJazzAgent | Loaded<any, true>;\n branchName?: string;\n branchOwnerId?: string;\n}\n\n/**\n * Internal hook that manages an array of SubscriptionScope instances.\n *\n * - Uses a ref to track subscriptions by index\n * - Detects changes by comparing schema/ids/resolve/branch\n * - Creates new subscriptions via SubscriptionScopeCache.getOrCreate()\n * - Returns null for entries with undefined/null IDs or invalid branches\n */\nfunction useCoValueSubscriptions(\n schema: CoValueClassOrSchema,\n ids: readonly (string | undefined | null)[],\n resolve: ResolveQuery<any>,\n branch?: BranchDefinition,\n): (SubscriptionScope<CoValue> | null)[] {\n const contextManager = useJazzContext();\n const agent = useAgent();\n\n const callerStack = useMemo(() => captureStack(), []);\n\n const createAllSubscriptions = (): SubscriptionsState => {\n const node = contextManager.getCurrentValue()!.node;\n const cache = contextManager.getSubscriptionScopeCache();\n\n const subscriptions = ids.map((id) => {\n if (id === undefined || id === null) {\n return null;\n }\n\n const subscription = cache.getOrCreate(\n node,\n schema,\n id,\n resolve,\n false,\n false,\n branch,\n );\n\n if (callerStack) {\n subscription.callerStack = callerStack;\n }\n\n return subscription;\n });\n\n return {\n subscriptions,\n schema,\n ids,\n resolve,\n contextManager,\n agent,\n branchName: branch?.name,\n branchOwnerId: branch?.owner?.$jazz.id,\n };\n };\n\n const stateRef = React.useRef<SubscriptionsState | null>(null);\n const newSubscriptions = createAllSubscriptions();\n\n const state = stateRef.current;\n\n // Avoid recreating the subscriptions array if all subscriptions are already cached\n const anySubscriptionChanged =\n newSubscriptions.subscriptions.length !== state?.subscriptions.length ||\n newSubscriptions.subscriptions.some(\n (newSubscriptions, index) =>\n newSubscriptions !== state.subscriptions[index],\n );\n\n if (anySubscriptionChanged) {\n stateRef.current = newSubscriptions;\n }\n\n return stateRef.current!.subscriptions;\n}\n\nfunction useImportCoValueContent<V>(\n id: string | undefined | null,\n content?: ExportedCoValue<V>,\n) {\n const agent = useAgent();\n const preloadExecuted = useRef<typeof agent | null>(null);\n if (content && preloadExecuted.current !== agent && id) {\n if (content.id === id) {\n importContentPieces(content.contentPieces, agent);\n } else {\n console.warn(\"Preloaded value ID does not match the subscription ID\");\n }\n\n preloadExecuted.current = agent;\n }\n}\n\nfunction useGetCurrentValue<C extends CoValue>(\n subscription: SubscriptionScope<C> | null,\n) {\n return useCallback(() => {\n if (!subscription) {\n return getUnloadedCoValueWithoutId(CoValueLoadingState.UNAVAILABLE);\n }\n\n return subscription.getCurrentValue();\n }, [subscription]);\n}\n\n/**\n * React hook for subscribing to CoValues and handling loading states.\n *\n * This hook provides a convenient way to subscribe to CoValues and automatically\n * handles the subscription lifecycle (subscribe on mount, unsubscribe on unmount).\n * It also supports deep loading of nested CoValues through resolve queries.\n *\n * The {@param options.select} function allows returning only specific parts of the CoValue data,\n * which helps reduce unnecessary re-renders by narrowing down the returned data.\n * Additionally, you can provide a custom {@param options.equalityFn} to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * @returns The loaded CoValue, or an {@link NotLoaded} value. Use `$isLoaded` to check whether the\n * CoValue is loaded, or use {@link MaybeLoaded.$jazz.loadingState} to get the detailed loading state.\n * If a selector function is provided, returns the result of the selector function.\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const Project = co.map({\n * name: z.string(),\n * description: z.string(),\n * tasks: co.list(Task),\n * lastModified: z.date(),\n * });\n *\n * function ProjectTitle({ projectId }: { projectId: string }) {\n * // Only re-render when the project name changes, not other fields\n * const projectName = useCoState(\n * Project,\n * projectId,\n * {\n * select: (project) => !project.$isLoading ? project.name : \"Loading...\",\n * }\n * );\n *\n * return <h1>{projectName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * const Project = co.map({\n * name: z.string(),\n * tasks: co.list(Task),\n * owner: TeamMember,\n * });\n *\n * function ProjectView({ projectId }: { projectId: string }) {\n * const project = useCoState(Project, projectId, {\n * resolve: {\n * tasks: { $each: true },\n * owner: true,\n * },\n * });\n *\n * if (!project.$isLoaded) {\n * switch (project.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Project not accessible\";\n * case \"unavailable\":\n * return \"Project not found\";\n * case \"loading\":\n * return \"Loading project...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h1>{project.name}</h1>\n * <p>Owner: {project.owner.name}</p>\n * <ul>\n * {project.tasks.map((task) => (\n * <li key={task.id}>{task.title}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Using with optional references and error handling\n * const Task = co.map({\n * title: z.string(),\n * assignee: co.optional(TeamMember),\n * subtasks: co.list(Task),\n * });\n *\n * function TaskDetail({ taskId }: { taskId: string }) {\n * const task = useCoState(Task, taskId, {\n * resolve: {\n * assignee: true,\n * subtasks: { $each: { $onError: 'catch' } },\n * },\n * });\n *\n * if (!task.$isLoaded) {\n * switch (task.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Task not accessible\";\n * case \"unavailable\":\n * return \"Task not found\";\n * case \"loading\":\n * return \"Loading task...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h2>{task.title}</h2>\n * {task.assignee && <p>Assigned to: {task.assignee.name}</p>}\n * <ul>\n * {task.subtasks.map((subtask, index) => (\n * subtask.$isLoaded ? <li key={subtask.id}>{subtask.title}</li> : <li key={index}>Inaccessible subtask</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Use custom equality function for complex data structures\n * const TaskList = co.list(Task);\n *\n * function TaskCount({ listId }: { listId: string }) {\n * const taskStats = useCoState(\n * TaskList,\n * listId,\n * {\n * resolve: { $each: true },\n * select: (tasks) => {\n * if (!tasks.$isLoaded) return { total: 0, completed: 0 };\n * return {\n * total: tasks.length,\n * completed: tasks.filter(task => task.completed).length,\n * };\n * },\n * // Custom equality to prevent re-renders when stats haven't changed\n * equalityFn: (a, b) => a.total === b.total && a.completed === b.completed,\n * }\n * );\n *\n * return (\n * <div>\n * {taskStats.completed} of {taskStats.total} tasks completed\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoState<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = MaybeLoaded<Loaded<S, R>>,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns an `unavailable` value */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select?: (value: MaybeLoaded<Loaded<S, R>>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n preloaded?: ExportedCoValue<Loaded<S, R>>;\n },\n): TSelectorReturn {\n useImportCoValueContent(id, options?.preloaded);\n const subscription = useCoValueSubscription(Schema, id, options);\n return useSubscriptionSelector(subscription, options);\n}\n\nexport function useSuspenseCoState<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = Loaded<S, R>,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to */\n id: string,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n preloaded?: ExportedCoValue<Loaded<S, R>>;\n },\n): TSelectorReturn {\n useImportCoValueContent(id, options?.preloaded);\n\n const subscription = useCoValueSubscription(Schema, id, options);\n\n if (!subscription) {\n throw new Error(\"Subscription not found\");\n }\n\n use(subscription.getCachedPromise());\n\n return useSubscriptionSelector(subscription, options);\n}\n\n/**\n * Returns a subscription's current value.\n * Allows to optionally select a subset of the subscription's value.\n *\n * This is the single-value counterpart to {@link useSubscriptionsSelector}.\n * Keeping it separate for performance reasons.\n */\nexport function useSubscriptionSelector<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n // Selector input can be an already loaded or a maybe-loaded value,\n // depending on whether a suspense hook is used or not, respectively.\n TSelectorInput = MaybeLoaded<Loaded<S, R>>,\n TSelectorReturn = TSelectorInput,\n>(\n subscription: CoValueSubscription<S, R>,\n options?: {\n select?: (value: TSelectorInput) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n },\n): TSelectorReturn {\n const getCurrentValue = useGetCurrentValue(subscription);\n\n return useSyncExternalStoreWithSelector(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n getCurrentValue,\n getCurrentValue,\n options?.select ?? ((value) => value as unknown as TSelectorReturn),\n options?.equalityFn ?? Object.is,\n );\n}\n\nexport function useAccountSubscription<\n S extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n>(\n Schema: S,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContext();\n\n // Capture stack trace at hook call time\n const callerStack = useMemo(() => captureStack(), []);\n\n const createSubscription = () => {\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n if (agent.$type$ === \"Anonymous\") {\n return {\n subscription: null,\n contextManager,\n agent,\n };\n }\n\n const resolve = getResolveQuery(Schema, options?.resolve);\n\n const node = contextManager.getCurrentValue()!.node;\n const cache = contextManager.getSubscriptionScopeCache();\n const subscription = cache.getOrCreate(\n node,\n Schema,\n agent.$jazz.id,\n resolve,\n false,\n false,\n options?.unstable_branch,\n );\n\n // Set callerStack on returned subscription after retrieval\n if (callerStack) {\n subscription.callerStack = callerStack;\n }\n\n return {\n subscription,\n contextManager,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.Schema !== Schema ||\n subscription.branchName !== options?.unstable_branch?.name ||\n subscription.branchOwnerId !== options?.unstable_branch?.owner?.$jazz.id\n ) {\n // No need to manually destroy - cache handles cleanup via SubscriptionScope lifecycle\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n // No need to manually destroy - cache handles cleanup via SubscriptionScope lifecycle\n setSubscription(createSubscription());\n });\n }, [Schema, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription as CoValueSubscription<S, R>;\n}\n\n/**\n * React hook for accessing the current user's account.\n *\n * This hook provides access to the current user's account profile and root data.\n * It automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries.\n *\n * The {@param options.select} function allows returning only specific parts of the account data,\n * which helps reduce unnecessary re-renders by narrowing down the returned data.\n * Additionally, you can provide a custom {@param options.equalityFn} to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * @returns The account data, or an {@link NotLoaded} value. Use `$isLoaded` to check whether the\n * CoValue is loaded, or use {@link MaybeLoaded.$jazz.loadingState} to get the detailed loading state.\n * If a selector function is provided, returns the result of the selector function.\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const MyAppAccount = co.account({\n * profile: co.profile(),\n * root: co.map({\n * name: z.string(),\n * email: z.string(),\n * lastLogin: z.date(),\n * }),\n * });\n *\n * function UserProfile({ accountId }: { accountId: string }) {\n * // Only re-render when the profile name changes, not other fields\n * const profileName = useAccount(\n * MyAppAccount,\n * {\n * resolve: {\n * profile: true,\n * root: true,\n * },\n * select: (account) => account.$isLoaded ? account.profile.name : \"Loading...\",\n * }\n * );\n *\n * return <h1>{profileName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * function ProjectListWithDetails() {\n * const me = useAccount(MyAppAccount, {\n * resolve: {\n * profile: true,\n * root: {\n * myProjects: {\n * $each: {\n * tasks: true,\n * },\n * },\n * },\n * },\n * });\n *\n * if (!me.$isLoaded) {\n * switch (me.$jazz.loadingState) {\n * case \"unauthorized\":\n * return \"Account not accessible\";\n * case \"unavailable\":\n * return \"Account not found\";\n * case \"loading\":\n * return \"Loading account...\";\n * }\n * }\n *\n * return (\n * <div>\n * <h1>{me.profile.name}'s projects</h1>\n * <ul>\n * {me.root.myProjects.map((project) => (\n * <li key={project.id}>\n * {project.name} ({project.tasks.length} tasks)\n * </li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n */\nexport function useAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<A> = SchemaResolveQuery<A>,\n TSelectorReturn = MaybeLoaded<Loaded<A, R>>,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select?: (account: MaybeLoaded<Loaded<A, R>>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n return useSubscriptionSelector(subscription, options);\n}\n\nexport function useSuspenseAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<A> = SchemaResolveQuery<A>,\n TSelectorReturn = Loaded<A, R>,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select?: (account: Loaded<A, R>) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n\n if (!subscription) {\n throw new Error(\n \"Subscription not found, are you using useSuspenseAccount in guest mode?\",\n );\n }\n\n use(subscription.getCachedPromise());\n\n return useSubscriptionSelector(subscription, options);\n}\n\n/**\n * Returns a function for logging out of the current account.\n */\nexport function useLogOut(): () => void {\n const contextManager = useJazzContext();\n return contextManager.logOut;\n}\n\n/**\n * React hook for accessing the current agent. An agent can either be:\n * - an Authenticated Account, if the user is logged in\n * - an Anonymous Account, if the user didn't log in\n * - or an anonymous agent, if in guest mode\n *\n * The agent can be used as the `loadAs` parameter for load and subscribe methods.\n */\nexport function useAgent<\n A extends AccountClass<Account> | AnyAccountSchema = typeof Account,\n>(): AnonymousJazzAgent | Loaded<A, true> {\n const contextManager = useJazzContext<InstanceOfSchema<A>>();\n\n const getCurrentValue = () =>\n getCurrentAccountFromContextManager(contextManager) as\n | AnonymousJazzAgent\n | Loaded<A, true>;\n\n return React.useSyncExternalStore(\n useCallback(\n (callback) => {\n return contextManager.subscribe(callback);\n },\n [contextManager],\n ),\n getCurrentValue,\n getCurrentValue,\n );\n}\n\nexport function experimental_useInboxSender<\n I extends CoValue,\n O extends CoValue | undefined,\n>(inboxOwnerID: string | undefined) {\n const context = useJazzContextValue();\n\n if (!(\"me\" in context)) {\n throw new Error(\n \"useInboxSender can't be used in a JazzProvider with auth === 'guest'.\",\n );\n }\n\n const me = context.me;\n const inboxRef = useRef<Promise<InboxSender<I, O>> | undefined>(undefined);\n\n const sendMessage = useCallback(\n async (message: I) => {\n if (!inboxOwnerID) throw new Error(\"Inbox owner ID is required\");\n\n if (!inboxRef.current) {\n const inbox = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = inbox;\n }\n\n let inbox = await inboxRef.current;\n\n // Regenerate the InboxSender if the inbox owner or current account changes\n if (inbox.owner.id !== inboxOwnerID || inbox.currentAccount !== me) {\n const req = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = req;\n inbox = await req;\n }\n\n return inbox.sendMessage(message);\n },\n [inboxOwnerID, me.$jazz.id],\n );\n\n return sendMessage;\n}\n\n/**\n * Hook that returns the current connection status to the Jazz sync server.\n *\n * @returns `true` when connected to the server, `false` when disconnected\n *\n * @remarks\n * On connection drop, this hook will return `false` only when Jazz detects the disconnection\n * after 5 seconds of not receiving a ping from the server.\n */\nexport function useSyncConnectionStatus() {\n const context = useJazzContextValue();\n\n const connected = useSyncExternalStore(\n useCallback(\n (callback) => {\n return context.addConnectionListener(callback);\n },\n [context],\n ),\n () => context.connected(),\n () => context.connected(),\n );\n\n return connected;\n}\n\nfunction getResolveQuery(\n Schema: CoValueClassOrSchema,\n // We don't need type validation here, since this is an internal API\n resolveQuery?: ResolveQuery<any>,\n): ResolveQuery<any> {\n if (resolveQuery) {\n return resolveQuery;\n }\n // Check the schema is a CoValue schema (and not a CoValue class)\n if (\"resolveQuery\" in Schema) {\n return Schema.resolveQuery;\n }\n return true;\n}\n\n/**\n * Internal hook that suspends until all values are loaded.\n *\n * - Creates a Promise.all from individual getCachedPromise() calls\n * - Returns Promise.resolve(null) for null subscriptions (undefined/null IDs)\n * - Suspends via the use() hook until all values are loaded\n */\nfunction useSuspendUntilLoaded(\n subscriptions: (SubscriptionScope<CoValue> | null)[],\n): void {\n const combinedPromise = useMemo(() => {\n const promises = subscriptions.map((sub) => {\n if (!sub) {\n // For null subscriptions (undefined/null IDs), resolve immediately with null\n return Promise.resolve(null);\n }\n return sub.getCachedPromise();\n });\n\n return Promise.all(promises);\n }, [subscriptions]);\n\n use(combinedPromise);\n}\n\n/**\n * Internal hook that uses useSyncExternalStore to subscribe to multiple SubscriptionScopes.\n *\n * - Creates a combined subscribe function that subscribes to all scopes\n * - Returns an array of current values from each scope\n * - Maintains stable references for unchanged values\n *\n * @param subscriptions - Array of SubscriptionScope instances (or null for skipped entries)\n * @returns Array of loaded CoValues (or null for skipped entries)\n */\nfunction useSubscriptionsSelector<\n T extends CoValue[] | MaybeLoaded<CoValue>[],\n // Selector input can be an already loaded or a maybe-loaded value,\n // depending on whether a suspense hook is used or not, respectively.\n TSelectorInput = T[number],\n TSelectorReturn = TSelectorInput,\n>(\n subscriptions: SubscriptionScope<CoValue>[],\n options?: {\n select?: (value: TSelectorInput) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n },\n): TSelectorReturn[] {\n // Combined subscribe function that subscribes to all scopes\n const subscribe = useCallback(\n (callback: () => void) => {\n const unsubscribes = subscriptions.map((sub) => sub.subscribe(callback));\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n },\n [subscriptions],\n );\n\n // Cache current values to avoid infinite loops\n const cachedCurrentValuesRef = useRef<T>([] as unknown as T);\n const getCurrentValues = useCallback(() => {\n const newValues = subscriptions.map((sub) => sub.getCurrentValue());\n\n // Check if values have changed by comparing each element\n const cached = cachedCurrentValuesRef.current;\n const hasChanged =\n cached.length !== newValues.length ||\n newValues.some((value, index) => value !== cached[index]);\n\n if (hasChanged) {\n cachedCurrentValuesRef.current = newValues as T;\n }\n\n return cachedCurrentValuesRef.current as unknown as TSelectorInput[];\n }, [subscriptions]);\n\n const selectFn = useMemo(() => {\n if (!options?.select) {\n return (values: TSelectorInput[]) =>\n values as unknown as TSelectorReturn[];\n }\n return (values: TSelectorInput[]) =>\n values.map((value) => options.select!(value));\n }, [options?.select]);\n\n const elementEqualityFn = useMemo(\n () => options?.equalityFn ?? Object.is,\n [options?.equalityFn],\n );\n const equalityFn = useMemo(() => {\n return (a: TSelectorReturn[], b: TSelectorReturn[]) =>\n a.length === b.length &&\n a.every((value, index) => elementEqualityFn(value, b[index]));\n }, [elementEqualityFn]);\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getCurrentValues,\n getCurrentValues,\n selectFn,\n equalityFn,\n );\n}\n\n/**\n * Subscribe to multiple CoValues with unified Suspense handling.\n *\n * This hook accepts a list of CoValue IDs and returns an array of loaded values,\n * suspending until all values are available.\n *\n * @param Schema - The CoValue schema or class constructor\n * @param ids - Array of CoValue IDs to subscribe to\n * @param options - Optional configuration, including resolve query\n * @returns An array of loaded CoValues in the same order as the input IDs\n */\nexport function useSuspenseCoStates<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = Loaded<S, R>,\n>(\n Schema: S,\n ids: readonly string[],\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return. Applies to each element individually. */\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n /** Equality function to determine if a selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn[] {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptionScopes = useCoValueSubscriptions(\n Schema,\n ids,\n resolve,\n options?.unstable_branch,\n ) as SubscriptionScope<CoValue>[];\n useSuspendUntilLoaded(subscriptionScopes);\n return useSubscriptionsSelector(subscriptionScopes, options);\n}\n\n/**\n * Subscribe to multiple CoValues without Suspense.\n *\n * This hook accepts a list of CoValue IDs and returns an array of maybe-loaded values.\n * Unlike `useSuspenseCoStates`, this hook does not suspend and returns loading/unavailable\n * states that can be checked via the `$isLoaded` property.\n *\n * @param Schema - The CoValue schema or class constructor\n * @param ids - Array of CoValue IDs to subscribe to\n * @param options - Optional configuration, including resolve query\n * @returns An array of MaybeLoaded CoValues in the same order as the input IDs\n *\n * @example\n * ```typescript\n * const [project1, project2] = useCoStates(\n * ProjectSchema,\n * [projectId1, projectId2],\n * { resolve: { assignee: true } }\n * );\n *\n * if (!project1.$isLoaded || !project2.$isLoaded) {\n * return <Loading />;\n * }\n * ```\n */\nexport function useCoStates<\n S extends CoValueClassOrSchema,\n // @ts-expect-error we can't statically enforce the schema's resolve query is a valid resolve query, but in practice it is\n const R extends ResolveQuery<S> = SchemaResolveQuery<S>,\n TSelectorReturn = MaybeLoaded<Loaded<S, R>>,\n>(\n Schema: S,\n ids: readonly string[],\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return. Applies to each element individually. */\n select?: (value: MaybeLoaded<Loaded<S, R>>) => TSelectorReturn;\n /** Equality function to determine if a selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn[] {\n const resolve = getResolveQuery(Schema, options?.resolve);\n const subscriptionScopes = useCoValueSubscriptions(\n Schema,\n ids,\n resolve,\n options?.unstable_branch,\n ) as SubscriptionScope<CoValue>[];\n return useSubscriptionsSelector(subscriptionScopes, options);\n}\n","import { Account, JazzContextManager } from \"jazz-tools\";\n\nexport function getCurrentAccountFromContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n) {\n const context = contextManager.getCurrentValue();\n\n if (!context) {\n throw new Error(\"No context found\");\n }\n\n return \"me\" in context ? context.me : context.guest;\n}\n\nexport function subscribeToContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n callback: () => () => void,\n) {\n let unsub = () => {};\n\n const handler = () => {\n unsub();\n unsub = callback();\n };\n\n handler();\n return contextManager.subscribe(handler);\n}\n","import React from \"react\";\n\n// shim from https://github.com/pmndrs/jotai/blob/f287c5d665a807e676bc731e83174c62c1fe1fc9/src/react/useAtomValue.ts#L13C1-L56C1\nconst attachPromiseStatus = <T>(\n promise: PromiseLike<T> & {\n status?: \"pending\" | \"fulfilled\" | \"rejected\";\n value?: T;\n reason?: unknown;\n },\n) => {\n if (!promise.status) {\n promise.status = \"pending\";\n promise.then(\n (v) => {\n promise.status = \"fulfilled\";\n promise.value = v;\n },\n (e) => {\n promise.status = \"rejected\";\n promise.reason = e;\n },\n );\n }\n};\n\nexport const use =\n React.use ||\n // A shim for older React versions\n (<T>(\n promise: PromiseLike<T> & {\n status?: \"pending\" | \"fulfilled\" | \"rejected\";\n value?: T;\n reason?: unknown;\n },\n ): T => {\n if (promise.status === \"pending\") {\n throw promise;\n } else if (promise.status === \"fulfilled\") {\n return promise.value as T;\n } else if (promise.status === \"rejected\") {\n throw promise.reason;\n } else {\n attachPromiseStatus(promise);\n throw promise;\n }\n });\n","import React from \"react\";\nimport {\n Account,\n AccountClass,\n AnyAccountSchema,\n CoValueClassOrSchema,\n CoValueLoadingState,\n Loaded,\n MaybeLoaded,\n ResolveQuery,\n ResolveQueryStrict,\n} from \"jazz-tools\";\nimport {\n useAccountSubscription,\n useCoValueSubscription,\n useSubscriptionSelector,\n} from \"./hooks.js\";\nimport type { CoValueSubscription } from \"./types.js\";\n\nexport function createCoValueSubscriptionContext<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S> = true,\n>(schema: S, resolve?: ResolveQueryStrict<S, R>) {\n const Context = React.createContext<CoValueSubscription<S, R>>(null);\n\n return {\n Provider: ({\n id,\n options,\n loadingFallback,\n unavailableFallback,\n children,\n }: React.PropsWithChildren<{\n id: string | undefined | null;\n options?: Omit<\n Parameters<typeof useCoValueSubscription<S, R>>[2],\n \"resolve\"\n >;\n loadingFallback?: React.ReactNode;\n unavailableFallback?: React.ReactNode;\n }>) => {\n const subscription = useCoValueSubscription(schema, id, {\n ...options,\n resolve: resolve,\n });\n\n const loadState = useSubscriptionSelector(subscription, {\n select: (value) => value.$jazz.loadingState,\n });\n\n if (loadState === CoValueLoadingState.LOADING) {\n return loadingFallback ?? null;\n }\n if (\n loadState === CoValueLoadingState.UNAUTHORIZED ||\n loadState === CoValueLoadingState.UNAVAILABLE\n ) {\n return unavailableFallback ?? null;\n }\n\n return (\n <Context.Provider value={subscription}>{children}</Context.Provider>\n );\n },\n useSelector: <TSelectorReturn = Loaded<S, R>>(options?: {\n select?: (value: Loaded<S, R>) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n }) => {\n const subscription = React.useContext(Context);\n\n if (!subscription) {\n throw new Error(\n \"useSelector must be used within a coValue subscription provider\",\n );\n }\n\n return useSubscriptionSelector<S, R, TSelectorReturn>(\n subscription,\n options as Parameters<\n typeof useSubscriptionSelector<S, R, TSelectorReturn>\n >[1],\n );\n },\n };\n}\n\nexport function createAccountSubscriptionContext<\n A extends AccountClass<Account> | AnyAccountSchema,\n const R extends ResolveQuery<A> = true,\n>(schema: A, resolve?: ResolveQueryStrict<A, R>) {\n const Context = React.createContext<CoValueSubscription<A, R>>(null);\n\n return {\n Provider: ({\n options,\n loadingFallback,\n unavailableFallback,\n children,\n }: React.PropsWithChildren<{\n options?: Omit<\n Parameters<typeof useAccountSubscription<A, R>>[1],\n \"resolve\"\n >;\n loadingFallback?: React.ReactNode;\n unavailableFallback?: React.ReactNode;\n }>) => {\n const subscription = useAccountSubscription(schema, {\n ...options,\n resolve: resolve,\n });\n\n const loadState = useSubscriptionSelector(subscription, {\n select: (value) => value.$jazz.loadingState,\n });\n\n if (loadState === CoValueLoadingState.LOADING) {\n return loadingFallback ?? null;\n }\n\n if (\n loadState === CoValueLoadingState.UNAUTHORIZED ||\n loadState === CoValueLoadingState.UNAVAILABLE\n ) {\n return unavailableFallback ?? null;\n }\n\n return (\n <Context.Provider value={subscription}>{children}</Context.Provider>\n );\n },\n useSelector: <TSelectorReturn = Loaded<A, R>>(options?: {\n select?: (value: Loaded<A, R>) => TSelectorReturn;\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n }) => {\n const subscription = React.useContext(Context);\n\n if (!subscription) {\n throw new Error(\n \"useSelector must be used within an account subscription provider\",\n );\n }\n\n return useSubscriptionSelector<A, R, TSelectorReturn>(\n subscription,\n options as Parameters<\n typeof useSubscriptionSelector<A, R, TSelectorReturn>\n >[1],\n );\n },\n };\n}\n","import { DemoAuth } from \"jazz-tools\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useAuthSecretStorage, useJazzContextValue } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `useDemoAuth` is a hook that provides a `JazzAuth` object for demo authentication.\n *\n *\n * ```ts\n * const { state, logIn, signUp, existingUsers } = useDemoAuth();\n * ```\n *\n * @category Auth Providers\n */\nexport function useDemoAuth() {\n const context = useJazzContextValue();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Demo auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new DemoAuth(context.authenticate, authSecretStorage);\n }, []);\n\n const isAuthenticated = useIsAuthenticated();\n const [existingUsers, setExistingUsers] = useState<string[]>([]);\n\n useEffect(() => {\n authMethod.getExistingUsers().then(setExistingUsers);\n }, [authMethod]);\n\n function handleSignUp(username: string) {\n return authMethod.signUp(username).then(() => {\n setExistingUsers(existingUsers.concat([username]));\n });\n }\n\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: handleSignUp,\n existingUsers,\n } as const;\n}\n","import { PassphraseAuth } from \"jazz-tools\";\nimport { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useAuthSecretStorage, useJazzContextValue } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `usePassphraseAuth` hook provides a `JazzAuth` object for passphrase authentication.\n *\n * @example\n * ```ts\n * const auth = usePassphraseAuth({ appName, appHostname, wordlist });\n * ```\n *\n * @category Auth Providers\n */\nexport function usePassphraseAuth({ wordlist }: { wordlist: string[] }) {\n const context = useJazzContextValue();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Passphrase auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new PassphraseAuth(\n context.node.crypto,\n context.authenticate,\n context.register,\n authSecretStorage,\n wordlist,\n );\n }, [wordlist]);\n\n const passphrase = useSyncExternalStore(\n useCallback(\n (callback) => {\n authMethod.loadCurrentAccountPassphrase();\n return authMethod.subscribe(callback);\n },\n [authMethod],\n ),\n () => authMethod.passphrase,\n );\n\n const isAuthenticated = useIsAuthenticated();\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: authMethod.signUp,\n registerNewAccount: authMethod.registerNewAccount,\n generateRandomPassphrase: authMethod.generateRandomPassphrase,\n passphrase,\n } as const;\n}\n"],"mappings":";;;;;;AAAA,SAAS,wCAAwC;AACjD,OAAOA;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAMA;AAAA,EAEA;AAAA,EAUA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;AC9BA,SAAS,oCACd,gBACA;AACA,QAAM,UAAU,eAAe,gBAAgB;AAE/C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kBAAkB;AAAA,EACpC;AAEA,SAAO,QAAQ,UAAU,QAAQ,KAAK,QAAQ;AAChD;;;ACZA,OAAO,WAAW;AAGlB,IAAM,sBAAsB,CAC1B,YAKG;AACH,MAAI,CAAC,QAAQ,QAAQ;AACnB,YAAQ,SAAS;AACjB,YAAQ;AAAA,MACN,CAAC,MAAM;AACL,gBAAQ,SAAS;AACj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Q;AAAA,IACR;AAAA,EACF;AACF;;;AC9CA,SAAS,sBAAsB;AAC/B,SAAS,eAAAC,cAAa,WAAAC,UAAS,wBAAAC,6BAA4B;AAcpD,SAAS,kBAAkB,EAAE,SAAS,GAA2B;AACtE,QAAM,UAAU,oBAAoB;AACpC,QAAM,oBAAoB,qBAAqB;AAE/C,MAAI,WAAW,SAAS;AACtB,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEA,QAAM,aAAaC,SAAQ,MAAM;AAC/B,WAAO,IAAI;AAAA,MACT,QAAQ,KAAK;AAAA,MACb,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,QAAM,aAAaC;AAAA,IACjBC;AAAA,MACE,CAAC,aAAa;AACZ,mBAAW,6BAA6B;AACxC,eAAO,WAAW,UAAU,QAAQ;AAAA,MACtC;AAAA,MACA,CAAC,UAAU;AAAA,IACb;AAAA,IACA,MAAM,WAAW;AAAA,EACnB;AAEA,QAAM,kBAAkB,mBAAmB;AAC3C,SAAO;AAAA,IACL,OAAO,kBAAkB,aAAa;AAAA,IACtC,OAAO,WAAW;AAAA,IAClB,QAAQ,WAAW;AAAA,IACnB,oBAAoB,WAAW;AAAA,IAC/B,0BAA0B,WAAW;AAAA,IACrC;AAAA,EACF;AACF;","names":["React","React","newSubscriptions","subscription","inbox","React","CoValueLoadingState","React","CoValueLoadingState","useMemo","useMemo","useCallback","useMemo","useSyncExternalStore","useMemo","useSyncExternalStore","useCallback"]}
@@ -1,5 +1,4 @@
1
1
  import React from "react";
2
- import { Account, JazzContextManager, JazzContextType } from "jazz-tools";
3
- export declare const JazzContext: React.Context<JazzContextType<Account> | undefined>;
4
- export declare const JazzContextManagerContext: React.Context<JazzContextManager<Account, {}> | undefined>;
2
+ import { Account, JazzContextManager } from "jazz-tools";
3
+ export declare const JazzContext: React.Context<JazzContextManager<Account, {}> | undefined>;
5
4
  //# sourceMappingURL=provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/react-core/provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE1E,eAAO,MAAM,WAAW,qDAEZ,CAAC;AAEb,eAAO,MAAM,yBAAyB,4DAE1B,CAAC"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/react-core/provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEzD,eAAO,MAAM,WAAW,4DAEZ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/react-core/testing.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAKzD,wBAAgB,gBAAgB,CAAC,GAAG,SAAS,OAAO,EAAE,EACpD,QAAQ,EACR,OAAO,EACP,eAAe,GAChB,EAAE;IACD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,OAAO,CAAC,EAAE,GAAG,GAAG;QAAE,KAAK,EAAE,kBAAkB,CAAA;KAAE,CAAC;IAC9C,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,2CAoBA;AAED,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/react-core/testing.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAKzD,wBAAgB,gBAAgB,CAAC,GAAG,SAAS,OAAO,EAAE,EACpD,QAAQ,EACR,OAAO,EACP,eAAe,GAChB,EAAE;IACD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,OAAO,CAAC,EAAE,GAAG,GAAG;QAAE,KAAK,EAAE,kBAAkB,CAAA;KAAE,CAAC;IAC9C,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,2CAYA;AAED,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC"}
@@ -1,12 +1,11 @@
1
1
  "use client";
2
2
  import {
3
- JazzContext,
4
- JazzContextManagerContext
5
- } from "./chunk-7DYMJ74I.js";
3
+ JazzContext
4
+ } from "./chunk-UOYH6JFJ.js";
6
5
 
7
6
  // src/react-core/testing.tsx
8
7
  import { TestJazzContextManager } from "jazz-tools/testing";
9
- import { useCallback, useState, useSyncExternalStore } from "react";
8
+ import { useState } from "react";
10
9
  import {
11
10
  createJazzTestAccount,
12
11
  createJazzTestGuest,
@@ -26,12 +25,7 @@ function JazzTestProvider({
26
25
  isAuthenticated
27
26
  });
28
27
  });
29
- const value = useSyncExternalStore(
30
- useCallback((callback) => contextManager.subscribe(callback), []),
31
- () => contextManager.getCurrentValue(),
32
- () => contextManager.getCurrentValue()
33
- );
34
- return /* @__PURE__ */ jsx(JazzContext.Provider, { value, children: /* @__PURE__ */ jsx(JazzContextManagerContext.Provider, { value: contextManager, children }) });
28
+ return /* @__PURE__ */ jsx(JazzContext.Provider, { value: contextManager, children });
35
29
  }
36
30
  export {
37
31
  JazzTestProvider,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react-core/testing.tsx"],"sourcesContent":["import { Account, AnonymousJazzAgent } from \"jazz-tools\";\nimport { TestJazzContextManager } from \"jazz-tools/testing\";\nimport { useCallback, useState, useSyncExternalStore } from \"react\";\nimport { JazzContext, JazzContextManagerContext } from \"./provider.js\";\n\nexport function JazzTestProvider<Acc extends Account>({\n children,\n account,\n isAuthenticated,\n}: {\n children: React.ReactNode;\n account?: Acc | { guest: AnonymousJazzAgent };\n isAuthenticated?: boolean;\n}) {\n const [contextManager] = useState(() => {\n return TestJazzContextManager.fromAccountOrGuest<Acc>(account, {\n isAuthenticated,\n });\n });\n\n const value = useSyncExternalStore(\n useCallback((callback) => contextManager.subscribe(callback), []),\n () => contextManager.getCurrentValue(),\n () => contextManager.getCurrentValue(),\n );\n\n return (\n <JazzContext.Provider value={value}>\n <JazzContextManagerContext.Provider value={contextManager}>\n {children}\n </JazzContextManagerContext.Provider>\n </JazzContext.Provider>\n );\n}\n\nexport {\n createJazzTestAccount,\n createJazzTestGuest,\n linkAccounts,\n setActiveAccount,\n setupJazzTestSync,\n MockConnectionStatus,\n} from \"jazz-tools/testing\";\n"],"mappings":";;;;;;;AACA,SAAS,8BAA8B;AACvC,SAAS,aAAa,UAAU,4BAA4B;AAiC5D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAdD;AAvBC,SAAS,iBAAsC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,CAAC,cAAc,IAAI,SAAS,MAAM;AACtC,WAAO,uBAAuB,mBAAwB,SAAS;AAAA,MAC7D;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,QAAM,QAAQ;AAAA,IACZ,YAAY,CAAC,aAAa,eAAe,UAAU,QAAQ,GAAG,CAAC,CAAC;AAAA,IAChE,MAAM,eAAe,gBAAgB;AAAA,IACrC,MAAM,eAAe,gBAAgB;AAAA,EACvC;AAEA,SACE,oBAAC,YAAY,UAAZ,EAAqB,OACpB,8BAAC,0BAA0B,UAA1B,EAAmC,OAAO,gBACxC,UACH,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/react-core/testing.tsx"],"sourcesContent":["import { Account, AnonymousJazzAgent } from \"jazz-tools\";\nimport { TestJazzContextManager } from \"jazz-tools/testing\";\nimport { useCallback, useState, useSyncExternalStore } from \"react\";\nimport { JazzContext } from \"./provider.js\";\n\nexport function JazzTestProvider<Acc extends Account>({\n children,\n account,\n isAuthenticated,\n}: {\n children: React.ReactNode;\n account?: Acc | { guest: AnonymousJazzAgent };\n isAuthenticated?: boolean;\n}) {\n const [contextManager] = useState(() => {\n return TestJazzContextManager.fromAccountOrGuest<Acc>(account, {\n isAuthenticated,\n });\n });\n\n return (\n <JazzContext.Provider value={contextManager}>\n {children}\n </JazzContext.Provider>\n );\n}\n\nexport {\n createJazzTestAccount,\n createJazzTestGuest,\n linkAccounts,\n setActiveAccount,\n setupJazzTestSync,\n MockConnectionStatus,\n} from \"jazz-tools/testing\";\n"],"mappings":";;;;;;AACA,SAAS,8BAA8B;AACvC,SAAsB,gBAAsC;AAyB5D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAbH;AAhBG,SAAS,iBAAsC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,CAAC,cAAc,IAAI,SAAS,MAAM;AACtC,WAAO,uBAAuB,mBAAwB,SAAS;AAAA,MAC7D;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SACE,oBAAC,YAAY,UAAZ,EAAqB,OAAO,gBAC1B,UACH;AAEJ;","names":[]}
@@ -1,6 +1,9 @@
1
- import {
2
- __require
3
- } from "./chunk-DGUM43GV.js";
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
4
7
 
5
8
  // src/react-native-core/storage/kv-store-context.ts
6
9
  var KvStoreContext = class _KvStoreContext {
@@ -434,14 +437,14 @@ ReactNativePasskeyAuth.id = "passkey";
434
437
  import {
435
438
  useAuthSecretStorage,
436
439
  useIsAuthenticated,
437
- useJazzContext
440
+ useJazzContextValue
438
441
  } from "jazz-tools/react-core";
439
442
  import { useMemo } from "react";
440
443
  function usePasskeyAuth({
441
444
  appName,
442
445
  rpId
443
446
  }) {
444
- const context = useJazzContext();
447
+ const context = useJazzContextValue();
445
448
  const authSecretStorage = useAuthSecretStorage();
446
449
  if ("guest" in context) {
447
450
  throw new Error("Passkey auth is not supported in guest mode");
@@ -740,7 +743,7 @@ function clearUserCredentials() {
740
743
  // src/react-native-core/hooks.tsx
741
744
  import { useEffect } from "react";
742
745
  import { parseInviteLink } from "jazz-tools";
743
- import { useJazzContext as useJazzContext2 } from "jazz-tools/react-core";
746
+ import { useJazzContextValue as useJazzContextValue2 } from "jazz-tools/react-core";
744
747
  import { Linking } from "react-native";
745
748
  import {
746
749
  useCoState,
@@ -748,7 +751,7 @@ import {
748
751
  experimental_useInboxSender,
749
752
  useDemoAuth,
750
753
  usePassphraseAuth,
751
- useJazzContext as useJazzContext3,
754
+ useJazzContextValue as useJazzContextValue3,
752
755
  useAuthSecretStorage as useAuthSecretStorage2,
753
756
  useIsAuthenticated as useIsAuthenticated2,
754
757
  useAccount,
@@ -767,7 +770,7 @@ function useAcceptInviteNative({
767
770
  onAccept,
768
771
  forValueHint
769
772
  }) {
770
- const context = useJazzContext2();
773
+ const context = useJazzContextValue2();
771
774
  if (!("me" in context)) {
772
775
  throw new Error(
773
776
  "useAcceptInviteNative can't be used in a JazzProvider with auth === 'guest'."
@@ -799,8 +802,15 @@ function useAcceptInviteNative({
799
802
  }
800
803
 
801
804
  // src/react-native-core/provider.tsx
802
- import { JazzContext, JazzContextManagerContext } from "jazz-tools/react-core";
803
- import React3, { useEffect as useEffect2, useRef } from "react";
805
+ import { JazzContext } from "jazz-tools/react-core";
806
+ import React3, {
807
+ useCallback,
808
+ useContext,
809
+ useEffect as useEffect2,
810
+ useMemo as useMemo2,
811
+ useRef,
812
+ useSyncExternalStore
813
+ } from "react";
804
814
 
805
815
  // src/react-native-core/ReactNativeContextManager.ts
806
816
  import {
@@ -810,7 +820,6 @@ import {
810
820
  // src/react-native-core/platform.ts
811
821
  import NetInfo from "@react-native-community/netinfo";
812
822
  import { getSqliteStorageAsync } from "cojson";
813
- import { PureJSCrypto } from "cojson/dist/crypto/PureJSCrypto";
814
823
  import {
815
824
  createInviteLink as baseCreateInviteLink,
816
825
  createAnonymousJazzContext,
@@ -875,6 +884,7 @@ var ReactNativeSessionProvider = class {
875
884
 
876
885
  // src/react-native-core/platform.ts
877
886
  import { WebSocketPeerWithReconnection } from "cojson-transport-ws";
887
+ import { RNCrypto } from "cojson/crypto/RNCrypto";
878
888
  var ReactNativeWebSocketPeerWithReconnection = class extends WebSocketPeerWithReconnection {
879
889
  onNetworkChange(callback) {
880
890
  return NetInfo.addEventListener(
@@ -883,8 +893,7 @@ var ReactNativeWebSocketPeerWithReconnection = class extends WebSocketPeerWithRe
883
893
  }
884
894
  };
885
895
  async function setupPeers(options) {
886
- const CryptoProvider3 = options.CryptoProvider || PureJSCrypto;
887
- const crypto = await CryptoProvider3.create();
896
+ const crypto = await RNCrypto.create();
888
897
  let node = void 0;
889
898
  const peers = [];
890
899
  const storage2 = options.storage && options.storage !== "disabled" ? await getSqliteStorageAsync(options.storage) : void 0;
@@ -1056,8 +1065,7 @@ var ReactNativeContextManager = class extends JazzContextManager {
1056
1065
  return createJazzReactNativeGuestContext({
1057
1066
  sync: props.sync,
1058
1067
  storage: props.storage,
1059
- authSecretStorage: this.authSecretStorage,
1060
- CryptoProvider: props.CryptoProvider
1068
+ authSecretStorage: this.authSecretStorage
1061
1069
  });
1062
1070
  } else {
1063
1071
  return createJazzReactNativeContext({
@@ -1067,8 +1075,7 @@ var ReactNativeContextManager = class extends JazzContextManager {
1067
1075
  credentials: authProps?.credentials,
1068
1076
  newAccountProps: authProps?.newAccountProps,
1069
1077
  defaultProfileName: props.defaultProfileName,
1070
- authSecretStorage: this.authSecretStorage,
1071
- CryptoProvider: props.CryptoProvider
1078
+ authSecretStorage: this.authSecretStorage
1072
1079
  });
1073
1080
  }
1074
1081
  }
@@ -1096,9 +1103,14 @@ function JazzProviderCore({
1096
1103
  logOutReplacement,
1097
1104
  onAnonymousAccountDiscarded,
1098
1105
  kvStore,
1099
- CryptoProvider: CryptoProvider3,
1100
- authSecretStorageKey
1106
+ authSecretStorageKey,
1107
+ fallback = null
1101
1108
  }) {
1109
+ if (useContext(JazzContext)) {
1110
+ throw new Error(
1111
+ "You can't nest a JazzProvider inside another JazzProvider."
1112
+ );
1113
+ }
1102
1114
  setupKvStore(kvStore);
1103
1115
  const [contextManager] = React3.useState(
1104
1116
  () => new ReactNativeContextManager({ authSecretStorageKey })
@@ -1108,37 +1120,33 @@ function JazzProviderCore({
1108
1120
  const onAnonymousAccountDiscardedRefCallback = useRefCallback(
1109
1121
  onAnonymousAccountDiscarded
1110
1122
  );
1111
- const logoutReplacementActiveRef = useRef(false);
1112
- logoutReplacementActiveRef.current = Boolean(logOutReplacement);
1113
- const onAnonymousAccountDiscardedEnabled = Boolean(
1114
- onAnonymousAccountDiscarded
1115
- );
1116
- const value = React3.useSyncExternalStore(
1117
- React3.useCallback(
1123
+ const props = useMemo2(() => {
1124
+ return {
1125
+ AccountSchema,
1126
+ guestMode,
1127
+ sync,
1128
+ storage: storage2,
1129
+ defaultProfileName,
1130
+ onLogOut: onLogOutRefCallback,
1131
+ logOutReplacement: logOutReplacement ? logOutReplacementRefCallback : void 0,
1132
+ onAnonymousAccountDiscarded: onAnonymousAccountDiscarded ? onAnonymousAccountDiscardedRefCallback : void 0
1133
+ };
1134
+ }, [guestMode, sync.peer, sync.when, storage2]);
1135
+ if (contextManager.propsChanged(props)) {
1136
+ contextManager.createContext(props).catch((error) => {
1137
+ console.log(error.stack);
1138
+ console.error("Error creating Jazz React Native context:", error);
1139
+ });
1140
+ }
1141
+ const isReady = useSyncExternalStore(
1142
+ useCallback(
1118
1143
  (callback) => {
1119
- const props = {
1120
- AccountSchema,
1121
- guestMode,
1122
- sync,
1123
- storage: storage2,
1124
- defaultProfileName,
1125
- onLogOut: onLogOutRefCallback,
1126
- logOutReplacement: logoutReplacementActiveRef.current ? logOutReplacementRefCallback : void 0,
1127
- onAnonymousAccountDiscarded: onAnonymousAccountDiscardedEnabled ? onAnonymousAccountDiscardedRefCallback : void 0,
1128
- CryptoProvider: CryptoProvider3
1129
- };
1130
- if (contextManager.propsChanged(props)) {
1131
- contextManager.createContext(props).catch((error) => {
1132
- console.log(error.stack);
1133
- console.error("Error creating Jazz React Native context:", error);
1134
- });
1135
- }
1136
1144
  return contextManager.subscribe(callback);
1137
1145
  },
1138
- [sync, guestMode].concat(storage2)
1146
+ [contextManager]
1139
1147
  ),
1140
- () => contextManager.getCurrentValue(),
1141
- () => contextManager.getCurrentValue()
1148
+ () => Boolean(contextManager.getCurrentValue()),
1149
+ () => Boolean(contextManager.getCurrentValue())
1142
1150
  );
1143
1151
  useEffect2(() => {
1144
1152
  if (process.env.NODE_ENV === "development") return;
@@ -1146,7 +1154,7 @@ function JazzProviderCore({
1146
1154
  contextManager.done();
1147
1155
  };
1148
1156
  }, []);
1149
- return /* @__PURE__ */ jsx3(JazzContext.Provider, { value, children: /* @__PURE__ */ jsx3(JazzContextManagerContext.Provider, { value: contextManager, children: value && children }) });
1157
+ return /* @__PURE__ */ jsx3(JazzContext.Provider, { value: contextManager, children: isReady ? children : fallback });
1150
1158
  }
1151
1159
  function useRefCallback(callback) {
1152
1160
  const callbackRef = React3.useRef(callback);
@@ -1159,7 +1167,7 @@ function useRefCallback(callback) {
1159
1167
  // src/react-native-core/media/image.tsx
1160
1168
  import { ImageDefinition } from "jazz-tools";
1161
1169
  import { highestResAvailable } from "jazz-tools/media";
1162
- import { forwardRef, useEffect as useEffect3, useMemo as useMemo2, useState as useState3 } from "react";
1170
+ import { forwardRef, useEffect as useEffect3, useMemo as useMemo3, useState as useState3 } from "react";
1163
1171
  import { Image as RNImage } from "react-native";
1164
1172
  import { jsx as jsx4 } from "react/jsx-runtime";
1165
1173
  var Image = forwardRef(function Image2({ imageId, width, height, placeholder, ...props }, ref) {
@@ -1169,7 +1177,7 @@ var Image = forwardRef(function Image2({ imageId, width, height, placeholder, ..
1169
1177
  const [src, setSrc] = useState3(
1170
1178
  image?.placeholderDataURL ?? "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
1171
1179
  );
1172
- const dimensions = useMemo2(() => {
1180
+ const dimensions = useMemo3(() => {
1173
1181
  const originalWidth = image?.originalSize?.[0];
1174
1182
  const originalHeight = image?.originalSize?.[1];
1175
1183
  if (width === "original" && height === "original") {
@@ -1248,7 +1256,7 @@ import { parseInviteLink as parseInviteLink2 } from "jazz-tools";
1248
1256
  import {
1249
1257
  JazzProviderCore as JazzProviderCore2
1250
1258
  } from "jazz-tools/react-native-core";
1251
- import { useMemo as useMemo3 } from "react";
1259
+ import { useMemo as useMemo4 } from "react";
1252
1260
 
1253
1261
  // src/react-native/storage/mmkv-store-adapter.ts
1254
1262
  import { MMKV } from "react-native-mmkv";
@@ -1330,10 +1338,10 @@ var OPSQLiteAdapter = class {
1330
1338
  // src/react-native/provider.tsx
1331
1339
  import { jsx as jsx5 } from "react/jsx-runtime";
1332
1340
  function JazzReactNativeProvider(props) {
1333
- const storage2 = useMemo3(() => {
1341
+ const storage2 = useMemo4(() => {
1334
1342
  return props.storage ?? new OPSQLiteAdapter();
1335
1343
  }, [props.storage]);
1336
- const kvStore = useMemo3(() => {
1344
+ const kvStore = useMemo4(() => {
1337
1345
  return props.kvStore ?? new MMKVStore();
1338
1346
  }, [props.kvStore]);
1339
1347
  return /* @__PURE__ */ jsx5(JazzProviderCore2, { ...props, storage: storage2, kvStore });
@@ -1370,7 +1378,7 @@ export {
1370
1378
  useCoValueSubscription,
1371
1379
  useDemoAuth,
1372
1380
  useIsAuthenticated2 as useIsAuthenticated,
1373
- useJazzContext3 as useJazzContext,
1381
+ useJazzContextValue3 as useJazzContextValue,
1374
1382
  useLogOut,
1375
1383
  usePasskeyAuth,
1376
1384
  usePassphraseAuth,