| 1 | import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments"; |
| 2 | import type { AtomCommand } from "@t3tools/client-runtime/state/runtime"; |
| 3 | import { |
| 4 | AuthOrchestrationOperateScope, |
| 5 | EnvironmentAuthorizationError, |
| 6 | type EnvironmentId, |
| 7 | } from "@t3tools/contracts"; |
| 8 | import * as Cause from "effect/Cause"; |
| 9 | import { AsyncResult } from "effect/reactivity"; |
| 10 | |
| 11 | import { connectionAtomRuntime } from "../connection/runtime"; |
| 12 | import { readEnvironmentScope } from "./session"; |
| 13 | |
| 14 | function requireAttachmentWriteAccess<W extends { readonly environmentId: EnvironmentId }, A, E>( |
| 15 | command: AtomCommand<W, A, E>, |
| 16 | ): AtomCommand<W, A, E | EnvironmentAuthorizationError> { |
| 17 | return { |
| 18 | ...command, |
| 19 | run: async (registry, input) => { |
| 20 | if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) { |
| 21 | return AsyncResult.failure( |
| 22 | Cause.fail( |
| 23 | new EnvironmentAuthorizationError({ |
| 24 | message: "This connection cannot change attachments.", |
| 25 | requiredScope: AuthOrchestrationOperateScope, |
| 26 | }), |
| 27 | ), |
| 28 | ); |
| 29 | } |
| 30 | return command.run(registry, input); |
| 31 | }, |
| 32 | }; |
| 33 | } |
| 34 | |
| 35 | const commands = createAttachmentEnvironmentAtoms(connectionAtomRuntime); |
| 36 | export const attachmentEnvironment = { |
| 37 | createUploadUrl: requireAttachmentWriteAccess(commands.createUploadUrl), |
| 38 | remove: requireAttachmentWriteAccess(commands.remove), |
| 39 | }; |