jazz-tools 0.19.20 → 0.19.22

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 (105) hide show
  1. package/.svelte-kit/__package__/server.d.ts.map +1 -1
  2. package/.svelte-kit/__package__/server.js +9 -7
  3. package/.turbo/turbo-build.log +56 -56
  4. package/CHANGELOG.md +15 -0
  5. package/dist/better-auth/auth/server.d.ts.map +1 -1
  6. package/dist/better-auth/auth/server.js +4 -4
  7. package/dist/better-auth/auth/server.js.map +1 -1
  8. package/dist/better-auth/database-adapter/index.js.map +1 -1
  9. package/dist/better-auth/database-adapter/repository/generic.d.ts +3 -3
  10. package/dist/better-auth/database-adapter/repository/session.d.ts +2 -2
  11. package/dist/better-auth/database-adapter/schema.d.ts +3 -3
  12. package/dist/better-auth/database-adapter/schema.d.ts.map +1 -1
  13. package/dist/{chunk-MI24YFCY.js → chunk-QCTQH5RS.js} +1 -1
  14. package/dist/chunk-QCTQH5RS.js.map +1 -0
  15. package/dist/index.js +36 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/media/{chunk-3LKBM3G3.js → chunk-IRL3KNPO.js} +2 -2
  18. package/dist/media/{chunk-3LKBM3G3.js.map → chunk-IRL3KNPO.js.map} +1 -1
  19. package/dist/media/create-image/react-native.d.ts +1 -1
  20. package/dist/media/create-image/react-native.d.ts.map +1 -1
  21. package/dist/media/index.browser.js +1 -1
  22. package/dist/media/index.js +1 -1
  23. package/dist/media/index.native.js +5 -5
  24. package/dist/media/index.native.js.map +1 -1
  25. package/dist/media/index.server.js +1 -1
  26. package/dist/react/hooks.d.ts +1 -2
  27. package/dist/react/hooks.d.ts.map +1 -1
  28. package/dist/react/index.js +7 -2
  29. package/dist/react/index.js.map +1 -1
  30. package/dist/react-core/hooks.d.ts +92 -1
  31. package/dist/react-core/hooks.d.ts.map +1 -1
  32. package/dist/react-core/index.js +126 -57
  33. package/dist/react-core/index.js.map +1 -1
  34. package/dist/react-core/tests/useCoStates.test.d.ts +2 -0
  35. package/dist/react-core/tests/useCoStates.test.d.ts.map +1 -0
  36. package/dist/react-native/index.js +4 -0
  37. package/dist/react-native/index.js.map +1 -1
  38. package/dist/react-native-core/hooks.d.ts +1 -1
  39. package/dist/react-native-core/hooks.d.ts.map +1 -1
  40. package/dist/react-native-core/index.js +4 -0
  41. package/dist/react-native-core/index.js.map +1 -1
  42. package/dist/svelte/auth/ClerkAuth.svelte.d.ts +38 -0
  43. package/dist/svelte/auth/ClerkAuth.svelte.d.ts.map +1 -0
  44. package/dist/svelte/auth/ClerkAuth.svelte.js +47 -0
  45. package/dist/svelte/auth/JazzSvelteProviderWithClerk.svelte +156 -0
  46. package/dist/svelte/auth/JazzSvelteProviderWithClerk.svelte.d.ts +67 -0
  47. package/dist/svelte/auth/JazzSvelteProviderWithClerk.svelte.d.ts.map +1 -0
  48. package/dist/svelte/auth/RegisterClerkAuth.svelte +27 -0
  49. package/dist/svelte/auth/RegisterClerkAuth.svelte.d.ts +17 -0
  50. package/dist/svelte/auth/RegisterClerkAuth.svelte.d.ts.map +1 -0
  51. package/dist/svelte/auth/index.d.ts +2 -0
  52. package/dist/svelte/auth/index.d.ts.map +1 -1
  53. package/dist/svelte/auth/index.js +2 -0
  54. package/dist/svelte/tests/ClerkAuth.svelte.test.d.ts +2 -0
  55. package/dist/svelte/tests/ClerkAuth.svelte.test.d.ts.map +1 -0
  56. package/dist/svelte/tests/ClerkAuth.svelte.test.js +202 -0
  57. package/dist/svelte/tests/TestClerkAuthWrapper.svelte +16 -0
  58. package/dist/svelte/tests/TestClerkAuthWrapper.svelte.d.ts +8 -0
  59. package/dist/svelte/tests/TestClerkAuthWrapper.svelte.d.ts.map +1 -0
  60. package/dist/svelte/tests/testUtils.d.ts +1 -0
  61. package/dist/svelte/tests/testUtils.d.ts.map +1 -1
  62. package/dist/svelte/tests/testUtils.js +3 -1
  63. package/dist/testing.js +1 -1
  64. package/dist/tools/auth/clerk/index.d.ts +1 -1
  65. package/dist/tools/auth/clerk/types.d.ts +1 -1
  66. package/dist/tools/auth/clerk/types.d.ts.map +1 -1
  67. package/dist/tools/exports.d.ts +1 -0
  68. package/dist/tools/exports.d.ts.map +1 -1
  69. package/dist/tools/subscribe/types.d.ts +1 -1
  70. package/dist/tools/subscribe/types.d.ts.map +1 -1
  71. package/dist/worker/JazzMessageChannel.d.ts +36 -0
  72. package/dist/worker/JazzMessageChannel.d.ts.map +1 -0
  73. package/dist/worker/index.d.ts +7 -1
  74. package/dist/worker/index.d.ts.map +1 -1
  75. package/dist/worker/index.js +28 -17
  76. package/dist/worker/index.js.map +1 -1
  77. package/package.json +4 -4
  78. package/src/better-auth/auth/server.ts +9 -7
  79. package/src/better-auth/database-adapter/repository/generic.ts +3 -3
  80. package/src/better-auth/database-adapter/repository/session.ts +2 -2
  81. package/src/better-auth/database-adapter/schema.ts +5 -5
  82. package/src/media/create-image/react-native.ts +9 -7
  83. package/src/media/create-image-factory.test.ts +1 -1
  84. package/src/media/create-image-factory.ts +1 -1
  85. package/src/react/hooks.tsx +4 -2
  86. package/src/react-core/hooks.ts +321 -76
  87. package/src/react-core/tests/testUtils.tsx +2 -2
  88. package/src/react-core/tests/useCoState.selector.test.ts +309 -22
  89. package/src/react-core/tests/useCoStates.test.tsx +414 -0
  90. package/src/react-native-core/hooks.tsx +2 -0
  91. package/src/svelte/auth/ClerkAuth.svelte.ts +67 -0
  92. package/src/svelte/auth/JazzSvelteProviderWithClerk.svelte +156 -0
  93. package/src/svelte/auth/RegisterClerkAuth.svelte +27 -0
  94. package/src/svelte/auth/index.ts +2 -0
  95. package/src/svelte/tests/ClerkAuth.svelte.test.ts +305 -0
  96. package/src/svelte/tests/TestClerkAuthWrapper.svelte +16 -0
  97. package/src/svelte/tests/testUtils.ts +4 -1
  98. package/src/tools/auth/clerk/types.ts +1 -1
  99. package/src/tools/exports.ts +5 -0
  100. package/src/tools/subscribe/types.ts +1 -1
  101. package/src/tools/tests/inbox.test.ts +7 -7
  102. package/src/tools/tests/testStorage.ts +2 -2
  103. package/src/worker/JazzMessageChannel.ts +73 -0
  104. package/src/worker/index.ts +36 -17
  105. package/dist/chunk-MI24YFCY.js.map +0 -1
@@ -9,6 +9,7 @@ import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/w
9
9
  import React2, {
10
10
  useCallback,
11
11
  useContext,
12
+ useMemo,
12
13
  useRef,
13
14
  useSyncExternalStore
14
15
  } from "react";
@@ -103,66 +104,61 @@ function useIsAuthenticated() {
103
104
  );
104
105
  }
105
106
  function useCoValueSubscription(Schema, id, options) {
107
+ const resolve = getResolveQuery(Schema, options?.resolve);
108
+ const subscriptions = useCoValueSubscriptions(
109
+ Schema,
110
+ [id],
111
+ resolve,
112
+ options?.unstable_branch
113
+ );
114
+ return subscriptions[0] ?? null;
115
+ }
116
+ function useCoValueSubscriptions(schema, ids, resolve, branch) {
106
117
  const contextManager = useJazzContextManager();
107
118
  const agent = useAgent();
108
- const callerStack = React2.useRef(void 0);
109
- if (!callerStack.current) {
110
- callerStack.current = captureStack();
111
- }
112
- const createSubscription = () => {
113
- if (!id) {
114
- return {
115
- subscription: null,
116
- contextManager,
117
- id,
118
- Schema
119
- };
120
- }
121
- if (options?.unstable_branch?.owner === null) {
122
- return {
123
- subscription: null,
124
- contextManager,
125
- id,
126
- Schema
127
- };
128
- }
129
- const resolve = getResolveQuery(Schema, options?.resolve);
119
+ const callerStack = useMemo(() => captureStack(), []);
120
+ const createAllSubscriptions = () => {
130
121
  const node = contextManager.getCurrentValue().node;
131
122
  const cache = contextManager.getSubscriptionScopeCache();
132
- const subscription2 = cache.getOrCreate(
133
- node,
134
- Schema,
135
- id,
136
- resolve,
137
- false,
138
- false,
139
- options?.unstable_branch
140
- );
141
- if (callerStack.current) {
142
- subscription2.callerStack = callerStack.current;
143
- }
123
+ const subscriptions = ids.map((id) => {
124
+ if (id === void 0 || id === null) {
125
+ return null;
126
+ }
127
+ const subscription = cache.getOrCreate(
128
+ node,
129
+ schema,
130
+ id,
131
+ resolve,
132
+ false,
133
+ false,
134
+ branch
135
+ );
136
+ if (callerStack) {
137
+ subscription.callerStack = callerStack;
138
+ }
139
+ return subscription;
140
+ });
144
141
  return {
145
- value: subscription2,
142
+ subscriptions,
143
+ schema,
144
+ ids,
145
+ resolve,
146
146
  contextManager,
147
- id,
148
- Schema,
149
- branchName: options?.unstable_branch?.name,
150
- branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,
151
- agent
147
+ agent,
148
+ branchName: branch?.name,
149
+ branchOwnerId: branch?.owner?.$jazz.id
152
150
  };
153
151
  };
154
- const subscriptionRef = React2.useRef(null);
155
- if (!subscriptionRef.current) {
156
- subscriptionRef.current = createSubscription();
157
- }
158
- const branchName = options?.unstable_branch?.name;
159
- const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;
160
- let subscription = subscriptionRef.current;
161
- if (subscription.contextManager !== contextManager || subscription.id !== id || subscription.Schema !== Schema || subscription.branchName !== branchName || subscription.branchOwnerId !== branchOwnerId || subscription.agent !== agent) {
162
- subscriptionRef.current = createSubscription();
163
- subscription = subscriptionRef.current;
152
+ const stateRef = React2.useRef(null);
153
+ const newSubscriptions = createAllSubscriptions();
154
+ const state = stateRef.current;
155
+ const anySubscriptionChanged = newSubscriptions.subscriptions.length !== state?.subscriptions.length || newSubscriptions.subscriptions.some(
156
+ (newSubscriptions2, index) => newSubscriptions2 !== state.subscriptions[index]
157
+ );
158
+ if (anySubscriptionChanged) {
159
+ stateRef.current = newSubscriptions;
164
160
  }
165
- return subscription.value;
161
+ return stateRef.current.subscriptions;
166
162
  }
167
163
  function useImportCoValueContent(id, content) {
168
164
  const agent = useAgent();
@@ -219,10 +215,7 @@ function useSubscriptionSelector(subscription, options) {
219
215
  }
220
216
  function useAccountSubscription(Schema, options) {
221
217
  const contextManager = useJazzContextManager();
222
- const callerStack = React2.useRef(void 0);
223
- if (!callerStack.current) {
224
- callerStack.current = captureStack();
225
- }
218
+ const callerStack = useMemo(() => captureStack(), []);
226
219
  const createSubscription = () => {
227
220
  const agent = getCurrentAccountFromContextManager(contextManager);
228
221
  if (agent.$type$ === "Anonymous") {
@@ -244,8 +237,8 @@ function useAccountSubscription(Schema, options) {
244
237
  false,
245
238
  options?.unstable_branch
246
239
  );
247
- if (callerStack.current) {
248
- subscription2.callerStack = callerStack.current;
240
+ if (callerStack) {
241
+ subscription2.callerStack = callerStack;
249
242
  }
250
243
  return {
251
244
  subscription: subscription2,
@@ -351,6 +344,80 @@ function getResolveQuery(Schema, resolveQuery) {
351
344
  }
352
345
  return true;
353
346
  }
347
+ function useSuspendUntilLoaded(subscriptions) {
348
+ const combinedPromise = useMemo(() => {
349
+ const promises = subscriptions.map((sub) => {
350
+ if (!sub) {
351
+ return Promise.resolve(null);
352
+ }
353
+ return sub.getCachedPromise();
354
+ });
355
+ return Promise.all(promises);
356
+ }, [subscriptions]);
357
+ use(combinedPromise);
358
+ }
359
+ function useSubscriptionsSelector(subscriptions, options) {
360
+ const subscribe = useCallback(
361
+ (callback) => {
362
+ const unsubscribes = subscriptions.map((sub) => sub.subscribe(callback));
363
+ return () => {
364
+ unsubscribes.forEach((unsub) => unsub());
365
+ };
366
+ },
367
+ [subscriptions]
368
+ );
369
+ const cachedCurrentValuesRef = useRef([]);
370
+ const getCurrentValues = useCallback(() => {
371
+ const newValues = subscriptions.map((sub) => sub.getCurrentValue());
372
+ const cached = cachedCurrentValuesRef.current;
373
+ const hasChanged = cached.length !== newValues.length || newValues.some((value, index) => value !== cached[index]);
374
+ if (hasChanged) {
375
+ cachedCurrentValuesRef.current = newValues;
376
+ }
377
+ return cachedCurrentValuesRef.current;
378
+ }, [subscriptions]);
379
+ const selectFn = useMemo(() => {
380
+ if (!options?.select) {
381
+ return (values) => values;
382
+ }
383
+ return (values) => values.map((value) => options.select(value));
384
+ }, [options?.select]);
385
+ const elementEqualityFn = useMemo(
386
+ () => options?.equalityFn ?? Object.is,
387
+ [options?.equalityFn]
388
+ );
389
+ const equalityFn = useMemo(() => {
390
+ return (a, b) => a.length === b.length && a.every((value, index) => elementEqualityFn(value, b[index]));
391
+ }, [elementEqualityFn]);
392
+ return useSyncExternalStoreWithSelector(
393
+ subscribe,
394
+ getCurrentValues,
395
+ getCurrentValues,
396
+ selectFn,
397
+ equalityFn
398
+ );
399
+ }
400
+ function useSuspenseCoStates(Schema, ids, options) {
401
+ const resolve = getResolveQuery(Schema, options?.resolve);
402
+ const subscriptionScopes = useCoValueSubscriptions(
403
+ Schema,
404
+ ids,
405
+ resolve,
406
+ options?.unstable_branch
407
+ );
408
+ useSuspendUntilLoaded(subscriptionScopes);
409
+ return useSubscriptionsSelector(subscriptionScopes, options);
410
+ }
411
+ function useCoStates(Schema, ids, options) {
412
+ const resolve = getResolveQuery(Schema, options?.resolve);
413
+ const subscriptionScopes = useCoValueSubscriptions(
414
+ Schema,
415
+ ids,
416
+ resolve,
417
+ options?.unstable_branch
418
+ );
419
+ return useSubscriptionsSelector(subscriptionScopes, options);
420
+ }
354
421
 
355
422
  // src/react-core/subscription-provider.tsx
356
423
  import React3 from "react";
@@ -515,6 +582,7 @@ export {
515
582
  useAgent,
516
583
  useAuthSecretStorage,
517
584
  useCoState,
585
+ useCoStates,
518
586
  useCoValueSubscription,
519
587
  useDemoAuth,
520
588
  useIsAuthenticated,
@@ -525,6 +593,7 @@ export {
525
593
  useSubscriptionSelector,
526
594
  useSuspenseAccount,
527
595
  useSuspenseCoState,
596
+ useSuspenseCoStates,
528
597
  useSyncConnectionStatus
529
598
  };
530
599
  //# sourceMappingURL=index.js.map
@@ -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 RefsToResolve,\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) {\n const contextManager = useJazzContextManager();\n const agent = useAgent();\n\n const callerStack = React.useRef<Error | undefined>(undefined);\n\n if (!callerStack.current) {\n callerStack.current = captureStack();\n }\n\n const createSubscription = () => {\n if (!id) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\n };\n }\n\n if (options?.unstable_branch?.owner === null) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\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 id,\n resolve,\n false,\n false,\n options?.unstable_branch,\n );\n\n // Set callerStack on returned subscription after retrieval\n if (callerStack.current) {\n subscription.callerStack = callerStack.current;\n }\n\n return {\n value: subscription,\n contextManager,\n id,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n agent,\n };\n };\n\n const subscriptionRef = React.useRef<null | ReturnType<\n typeof createSubscription\n >>(null);\n\n if (!subscriptionRef.current) {\n subscriptionRef.current = createSubscription();\n }\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n let subscription = subscriptionRef.current;\n\n // Check if the subscription needs to be updated\n // because one of the dependencies has changed\n if (\n subscription.contextManager !== contextManager ||\n subscription.id !== id ||\n subscription.Schema !== Schema ||\n subscription.branchName !== branchName ||\n subscription.branchOwnerId !== branchOwnerId ||\n subscription.agent !== agent\n ) {\n subscriptionRef.current = createSubscription();\n subscription = subscriptionRef.current;\n }\n\n // Subscribe to the context manager to react to auth changes\n return subscription.value as CoValueSubscription<S, R>;\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\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<TSelectorInput, TSelectorReturn>(\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 = React.useRef<Error | undefined>(undefined);\n if (!callerStack.current) {\n callerStack.current = captureStack();\n }\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.current) {\n subscription.callerStack = callerStack.current;\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","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,EAEA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAMA;AAAA,EAEA;AAAA,EAYA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;AChCA,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;AA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E,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","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 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;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;AACjB,gBAAQ,QAAQ;AAAA,MAClB;AAAA,MACA,CAAC,MAAM;AACL,gBAAQ,SAAS;AACjB,gBAAQ,SAAS;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,MACX,MAAM;AAAA,CAEL,CACC,YAKM;AACN,MAAI,QAAQ,WAAW,WAAW;AAChC,UAAM;AAAA,EACR,WAAW,QAAQ,WAAW,aAAa;AACzC,WAAO,QAAQ;AAAA,EACjB,WAAW,QAAQ,WAAW,YAAY;AACxC,UAAM,QAAQ;AAAA,EAChB,OAAO;AACL,wBAAoB,OAAO;AAC3B,UAAM;AAAA,EACR;AACF;;;AFNK,SAAS,iBAAsC;AACpD,QAAM,QAAQ,WAAW,WAAW;AAEpC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,wBAA6C;AAC3D,QAAM,QAAQ,WAAW,yBAAyB;AAKlD,MAAI,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kB,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"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=useCoStates.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCoStates.test.d.ts","sourceRoot":"","sources":["../../../src/react-core/tests/useCoStates.test.tsx"],"names":[],"mappings":""}
@@ -744,6 +744,7 @@ import { useJazzContext as useJazzContext2 } from "jazz-tools/react-core";
744
744
  import { Linking } from "react-native";
745
745
  import {
746
746
  useCoState,
747
+ useCoStates,
747
748
  experimental_useInboxSender,
748
749
  useDemoAuth,
749
750
  usePassphraseAuth,
@@ -758,6 +759,7 @@ import {
758
759
  useAccountSubscription,
759
760
  useSubscriptionSelector,
760
761
  useSuspenseCoState,
762
+ useSuspenseCoStates,
761
763
  useSuspenseAccount
762
764
  } from "jazz-tools/react-core";
763
765
  function useAcceptInviteNative({
@@ -1364,6 +1366,7 @@ export {
1364
1366
  useAgent,
1365
1367
  useAuthSecretStorage2 as useAuthSecretStorage,
1366
1368
  useCoState,
1369
+ useCoStates,
1367
1370
  useCoValueSubscription,
1368
1371
  useDemoAuth,
1369
1372
  useIsAuthenticated2 as useIsAuthenticated,
@@ -1374,6 +1377,7 @@ export {
1374
1377
  useSubscriptionSelector,
1375
1378
  useSuspenseAccount,
1376
1379
  useSuspenseCoState,
1380
+ useSuspenseCoStates,
1377
1381
  useSyncConnectionStatus
1378
1382
  };
1379
1383
  //# sourceMappingURL=index.js.map