1import {
2 AuthDiagnosticsReadScope,
3 type AuthSessionState,
4 sessionGrantsScope,
5 type SessionGrantInput,
6} from "@t3tools/contracts";
7
8import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
9
10export function resolveUsageAccess(input: {
11 readonly connectionPhase: EnvironmentConnectionPhase;
12 readonly session: SessionGrantInput | null;
13 readonly hasSessionError: boolean;
14}) {
15 if (input.hasSessionError) {
16 return {
17 canReadDiagnostics: false,
18 isPending: false,
19 error: "Could not check this connection's access to diagnostics and usage.",
20 };
21 }
22 if (input.session === null) {
23 // An unprepared offline connection cannot finish its session check. Keep
24 // it out of pending totals until the connection starts another attempt.
25 const isPending =
26 input.connectionPhase === "connected" ||
27 input.connectionPhase === "connecting" ||
28 input.connectionPhase === "reconnecting";
29 return {
30 canReadDiagnostics: false,
31 isPending,
32 error: isPending ? null : "This environment is not connected.",
33 };
34 }
35 const canReadDiagnostics = sessionGrantsScope(input.session, AuthDiagnosticsReadScope);
36 return {
37 canReadDiagnostics,
38 isPending: false,
39 error: canReadDiagnostics
40 ? null
41 : "This connection does not have access to diagnostics and usage.",
42 };
43}