Open History to see the last commit
1import type {
2 AtomCommand,
3 AtomCommandOptions,
4 AtomCommandResult,
5} from "@t3tools/client-runtime/state/runtime";
6import {
7 AuthOrchestrationOperateScope,
8 EnvironmentAuthorizationError,
9 type EnvironmentId,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import { AsyncResult } from "effect/reactivity";
13import { msg } from "gt-react";
14
15import { m } from "../i18n/messages";
16
17import { readEnvironmentScope, readEnvironmentScopeDenied } from "./session";
18import { useAtomCommand } from "./use-atom-command";
19
20const ORCHESTRATION_OPERATE_DENIED_MESSAGE = msg(
21 "This connection cannot change threads or projects.",
22);
23
24// Module scope: React Compiler cannot reorder an inline arrow used as a parameter default.
25function hasLiveOperateGrant(environmentId: EnvironmentId): boolean {
26 return readEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
27}
28
29/**
30 * The check for settle, snooze and their undo, which queue while the environment is offline:
31 * allowed until the host has answered without the scope. The server checks again when it syncs.
32 */
33export function threadTriagePermitted(environmentId: EnvironmentId): boolean {
34 return !readEnvironmentScopeDenied(environmentId, AuthOrchestrationOperateScope);
35}
36
37/** `permitted` runs on every call, like the default operate check it replaces. */
38export function useOrchestrationCommand<W extends { readonly environmentId: EnvironmentId }, A, E>(
39 command: AtomCommand<W, A, E>,
40 options?: string | AtomCommandOptions,
41 permitted: (environmentId: EnvironmentId) => boolean = hasLiveOperateGrant,
42): (value: W) => Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> {
43 const run = useAtomCommand(command, options);
44 return async (value: W): Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> => {
45 if (!permitted(value.environmentId)) {
46 return AsyncResult.failure(
47 Cause.fail(
48 new EnvironmentAuthorizationError({
49 requiredScope: AuthOrchestrationOperateScope,
50 message: m(ORCHESTRATION_OPERATE_DENIED_MESSAGE),
51 }),
52 ),
53 );
54 }
55 return run(value);
56 };
57}