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