Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session";
3import {
4 type AuthEnvironmentScope,
5 type AuthSessionState,
6 type EnvironmentId,
7 sessionGrantsScope,
8} from "@t3tools/contracts";
9import * as Option from "effect/Option";
10import { AsyncResult, Atom } from "effect/reactivity";
11
12import { connectionAtomRuntime } from "../connection/runtime";
13import { appAtomRegistry } from "../rpc/atomRegistry";
14import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
15
16export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);
17export const environmentSessionStatesAtom = environmentAtomList(
18 "web-environment-session-states",
19 environmentSession.sessionStateAtom,
20);
21
22const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
23
24export function useEnvironmentScope(
25 environmentId: EnvironmentId | null,
26 scope: AuthEnvironmentScope,
27): boolean {
28 const result = useAtomValue(
29 environmentId === null
30 ? EMPTY_SESSION_STATE_ATOM
31 : environmentSession.sessionStateAtom(environmentId),
32 );
33 return sessionHasScope(result, scope);
34}
35
36/** True until the environment's session has answered once, so grants are unknown. */
37export function useEnvironmentSessionPending(environmentId: EnvironmentId | null): boolean {
38 const result = useAtomValue(
39 environmentId === null
40 ? EMPTY_SESSION_STATE_ATOM
41 : environmentSession.sessionStateAtom(environmentId),
42 );
43 return result._tag !== "Failure" && Option.isNone(AsyncResult.value(result));
44}
45
46function sessionHasScope(
47 result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
48 scope: AuthEnvironmentScope,
49): boolean {
50 const session = Option.getOrNull(AsyncResult.value(result));
51 return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
52}
53
54// Keyed by scope and ids so callers get one Set per session change, not one per render.
55const environmentsWithScopeAtom = Atom.family((key: string) => {
56 const [scope, idsKey = ""] = key.split(/\n(.*)/s) as [AuthEnvironmentScope, string?];
57 const ids = idsKey === "" ? [] : (idsKey.split("\n") as EnvironmentId[]);
58 const statesAtom = environmentSessionStatesAtom(idsKey);
59 return Atom.make((get) => {
60 const states = get(statesAtom);
61 return new Set(ids.filter((_, index) => sessionHasScope(states[index]!, scope)));
62 }).pipe(Atom.withLabel(`web-environments-with-scope:${key}`));
63});
64
65export function useEnvironmentsWithScope(
66 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
67 scope: AuthEnvironmentScope,
68): ReadonlySet<EnvironmentId> {
69 return useAtomValue(
70 environmentsWithScopeAtom(
71 `${scope}\n${environmentIdsKey(environments.map(({ environmentId }) => environmentId))}`,
72 ),
73 );
74}
75
76export function readEnvironmentScope(
77 environmentId: EnvironmentId,
78 scope: AuthEnvironmentScope,
79): boolean {
80 return sessionHasScope(
81 appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)),
82 scope,
83 );
84}
85
86const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe(
87 Atom.withLabel("web-prepared-connection:empty"),
88);
89
90export function usePreparedConnection(environmentId: EnvironmentId | null) {
91 return useAtomValue(
92 environmentId === null
93 ? EMPTY_PREPARED_CONNECTION_ATOM
94 : environmentSession.preparedConnectionValueAtom(environmentId),
95 );
96}
97
98export function readPreparedConnection(environmentId: EnvironmentId) {
99 return Option.getOrNull(
100 appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)),
101 );
102}
103
104/**
105 * `data` stays populated across SWR revalidations; `isPending` is only
106 * meaningful before the first resolve.
107 */
108export function useEnvironmentSessionState(environmentId: EnvironmentId) {
109 const result = useAtomValue(environmentSession.sessionStateAtom(environmentId));
110 return {
111 data: Option.getOrNull(AsyncResult.value(result)),
112 hasError: result._tag === "Failure",
113 isPending: result.waiting,
114 };
115}