import { z } from 'zod' import type { FaunosteoClient } from './client' import { Constants, type Enums, type Json } from './database.types' import { UUID_PATTERN } from './records' /** * Access layer for the official anatomical-sheet workflow (V1-2.1, M4/M5): * typed wrappers over the server RPCs and a closed set of failure kinds. The * server is the only authority: every RPC answers a closed code (SQLSTATE plus * a lowercase dotted message), never a value or free text. This module folds * those answers, the session and the network into one kind the UI phrases * (`sheet.failure.`), exactly as `records.ts` does for V1-1. No document * validation happens here: the Rust core (in the page) and the worker verdict * decide; the former client publication gate is gone (publication takes a * review id only). * * V1-2.1 shipped the workflow wrappers; V1-2.5 adds the administration reads * (M7), species, working copy, account lookup and the catalogue reads, with * shallow parsers of the JSON answers: a shape outside the contract is * `unavailable`, the business rules stay the server's. */ /** Every closed failure the sheet RPCs raise (contract §6.5, §6.7, §5.2, §5.7). */ export const SHEET_FAILURE_KINDS = [ // session and rights 'authentication_required', 'mfa_required', 'forbidden', 'self_target', 'rights.account', 'rights.capability', 'rights.mfa', 'rights.owner', 'rights.catalog', 'not_found', // platform roles (AR-1 B) 'role_active', 'role_inactive', 'last_owner', 'target_invalid', 'target_factor_missing', 'operator_path_only', // catalogue rights 'grant.active', 'grant.ineligible', 'grant.revoked', 'grant.target_invalid', // drafts and saving 'draft_conflict', 'draft.unchanged', 'draft.frozen', 'draft.not_a_draft', 'draft.exists', 'document.shape', 'document.schema_version', 'document.species', 'document.too_large', // sheet and species state 'sheet.inactive', 'sheet.state', 'sheet.no_source', 'sheet.published_history', 'sheet.historical_read_only', 'sheet.species_invalid', 'sheet.slug_taken', 'species.exists', 'species.not_active', 'species.not_inactive', // review rounds 'round.open', 'round.terminal', 'round.not_open', 'review.digest', 'review.uncoverable', 'review.separation', 'review.groups.uncovered', 'version.not_published', 'version.has_rounds', // verdict and publication 'verdict.missing', 'verdict.stale', 'verdict.fingerprint', 'publish.review.missing', 'publish.approval.invalid', 'publish.to_confirm.open', 'publish.inherited.present', 'publish.disclaimer.missing', 'publish.species.inactive', 'publish.species.other', 'publish.drawing.missing', 'publish.drawing.changed', 'view.asset.unknown', // uploads and working copy 'upload_missing', 'size_mismatch', 'upload.pending_other', 'asset.referenced', 'working_copy.source_invalid', 'working_copy.exists', 'working_copy.assets_missing', // shared 'invalid_input', 'rate_limited', 'conflict_retry', 'session_expired', 'network', 'unavailable', ] as const export type SheetFailureKind = (typeof SHEET_FAILURE_KINDS)[number] const KIND_SET: ReadonlySet = new Set(SHEET_FAILURE_KINDS) export class SheetFailure extends Error { readonly kind: SheetFailureKind constructor(kind: SheetFailureKind, cause?: unknown) { super(`sheet: ${kind}`, { cause }) this.name = 'SheetFailure' this.kind = kind } } interface PostgrestLikeError { code?: string | null message?: string } /** * Folds a PostgREST answer into a closed kind. The RPCs raise the closed code * as the message (SQLSTATE 42501, P0001, 55000, 23514 or P0002); a message * outside the closed set, a session error (401 / PGRST30x) and a dropped * request each map to their own kind. Fails closed on anything unknown. */ export function classifySheetError(error: unknown, status?: number): SheetFailureKind { if (error instanceof SheetFailure) return error.kind if (error instanceof TypeError) return 'network' const e = (error ?? {}) as PostgrestLikeError if (e.message && KIND_SET.has(e.message)) return e.message as SheetFailureKind // Deadlock (40P01) and serialization (40001) are retryable (contract §6.1). if (e.code === '40P01' || e.code === '40001') return 'conflict_retry' if (status === 401 || e.code?.startsWith('PGRST30')) return 'session_expired' if (status === 0) return 'network' return 'unavailable' } export function failSheet(error: unknown, status?: number): never { throw new SheetFailure(classifySheetError(error, status), error) } /** The RPC answer checked against its contract; a different shape is `unavailable`. */ function parseSheetAnswer(schema: z.ZodType, data: unknown): T { const result = schema.safeParse(data) if (!result.success) throw new SheetFailure('unavailable', result.error) return result.data } const { Enums: E } = Constants.public const LocalizedSchema = z.object({ fr: z.string(), en: z.string() }) /** An account as the admin answers name it (M7 `sheet_admin_person`). */ const PersonSchema = z.object({ user_id: z.string(), display_name: z.string().nullable() }) export type SheetAdminPerson = z.infer // --- Rights (owner, aal2) -------------------------------------------------- export async function grantCatalogRight( client: FaunosteoClient, args: { user_id: string kind: 'catalog_reader' | 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher' reason: string verification_note?: string expires_at?: string }, ): Promise { const { data, error, status } = await client.rpc('grant_catalog_right', args) if (error) failSheet(error, status) return data } export async function revokeCatalogRight( client: FaunosteoClient, grantId: string, reason: string, ): Promise { const { data, error, status } = await client.rpc('revoke_catalog_right', { grant_id: grantId, reason, }) if (error) failSheet(error, status) return data } const CatalogGrantSchema = z.object({ id: z.string(), user_id: z.string(), display_name: z.string().nullable(), email: z.string().nullable(), kind: z.enum(E.catalog_grant_kind), reason: z.string(), verification_note: z.string().nullable(), granted_by: z.string(), granted_by_name: z.string().nullable(), granted_at: z.string(), expires_at: z.string().nullable(), revoked_at: z.string().nullable(), revoked_by: z.string().nullable(), revocation_reason: z.string().nullable(), /** `expiring`: within 30 days (server clock). */ state: z.enum(['active', 'expiring', 'expired', 'revoked']), /** The right is in force now (grant_active: account confirmed and active, factor where needed). */ effective: z.boolean(), }) export type CatalogGrant = z.infer /** Every grant with its holder, state and reasons (owner, aal2). */ export async function listCatalogGrants(client: FaunosteoClient): Promise { const { data, error, status } = await client.rpc('list_catalog_grants') if (error) failSheet(error, status) return parseSheetAnswer(z.array(CatalogGrantSchema), data) } const CatalogAccountSchema = z.object({ user_id: z.string(), display_name: z.string().nullable(), active: z.boolean(), email_confirmed: z.boolean(), verified_totp: z.boolean(), platform_roles: z.array(z.enum(E.platform_role)), }) export type CatalogAccount = z.infer /** The account a right is granted to, by e-mail (owner, aal2); an unknown address is `not_found`. */ export async function lookupCatalogAccount( client: FaunosteoClient, email: string, ): Promise { const { data, error, status } = await client.rpc('lookup_catalog_account', { email }) if (error) failSheet(error, status) return parseSheetAnswer(CatalogAccountSchema, data) } // --- Sheets, drafts, review, publication ----------------------------------- export async function createOfficialSheet( client: FaunosteoClient, slug: string, document: Json, ): Promise { const { data, error, status } = await client.rpc('create_official_sheet', { slug, document }) if (error) failSheet(error, status) return data } export async function saveSheetDraft( client: FaunosteoClient, args: { version_id: string; expected_revision: number; document: Json; change_note?: string }, ): Promise { const { data, error, status } = await client.rpc('save_sheet_draft', args) if (error) failSheet(error, status) return data } /** The save answer `{ revision }` (M5): a positive integer, else `unavailable`. */ export function parseSaveAnswer(value: unknown): { revision: number } { const answer = z.object({ revision: z.number().int().positive() }).safeParse(value) if (!answer.success) throw new SheetFailure('unavailable', answer.error) return { revision: answer.data.revision } } export async function submitSheetReview( client: FaunosteoClient, args: { version_id: string; expected_revision: number; note?: string }, ): Promise { const { data, error, status } = await client.rpc('submit_sheet_review', args) if (error) failSheet(error, status) return data } export async function decideSheetReview( client: FaunosteoClient, args: { review_id: string; approve: boolean; note: string }, ): Promise { const { data, error, status } = await client.rpc('decide_sheet_review', args) if (error) failSheet(error, status) return data } /** Publishes an approved round. The gate is the server's: no client validation. */ export async function publishSheetVersion( client: FaunosteoClient, reviewId: string, ): Promise { const { data, error, status } = await client.rpc('publish_sheet_version', { review_id: reviewId }) if (error) failSheet(error, status) return data } export async function getSheetVersion(client: FaunosteoClient, versionId: string): Promise { const { data, error, status } = await client.rpc('get_sheet_version', { version_id: versionId }) if (error) failSheet(error, status) return data } export async function listOfficialCatalog(client: FaunosteoClient): Promise { const { data, error, status } = await client.rpc('list_official_catalog') if (error) failSheet(error, status) return data } // --- Species (contract §7.2) ----------------------------------------------- const CatalogSpeciesSchema = z.object({ id: z.string(), name_fr: z.string(), name_en: z.string(), sort_order: z.number(), active: z.boolean(), }) export type CatalogSpecies = z.infer /** Active and inactive species (capability holders or the owner, aal2). */ export async function listCatalogSpecies(client: FaunosteoClient): Promise { const { data, error, status } = await client.rpc('list_catalog_species') if (error) failSheet(error, status) return parseSheetAnswer(z.array(CatalogSpeciesSchema), data) } /** A new species, always inactive (sheet_editor, aal2). Resolves with its id. */ export async function createSpecies( client: FaunosteoClient, args: { id: string; name_fr: string; name_en: string; sort_order?: number }, ): Promise { const { data, error, status } = await client.rpc('create_species', args) if (error) failSheet(error, status) return data } /** Names and order of an inactive species (sheet_editor, aal2). */ export async function updateInactiveSpecies( client: FaunosteoClient, args: { id: string; name_fr: string; name_en: string; sort_order: number }, ): Promise { const { data, error, status } = await client.rpc('update_inactive_species', args) if (error) failSheet(error, status) return data } /** Owner, aal2. */ export async function activateSpecies(client: FaunosteoClient, id: string): Promise { const { data, error, status } = await client.rpc('activate_species', { id }) if (error) failSheet(error, status) return data } /** Names of an active species (owner, aal2). */ export async function renameSpecies( client: FaunosteoClient, args: { id: string; name_fr: string; name_en: string }, ): Promise { const { data, error, status } = await client.rpc('rename_species', args) if (error) failSheet(error, status) return data } // --- Working copy of the historical sheet (§14.3) -------------------------- /** A new official sheet drafted from a historical version (sheet_editor, aal2). Resolves with the sheet id. */ export async function createSheetWorkingCopy( client: FaunosteoClient, sourceVersionId: string, slug: string, ): Promise { const { data, error, status } = await client.rpc('create_sheet_working_copy', { source_version_id: sourceVersionId, slug, }) if (error) failSheet(error, status) return data } // --- Administration reads (M7, capability holders at aal2) ------------------ const VersionStatusSchema = z.enum(E.sheet_version_status) const RoundStatusSchema = z.enum(E.sheet_round_status) const OfficialSheetAdminSummarySchema = z.object({ sheet_id: z.string(), species_id: z.string(), slug: z.string(), status: z.enum(E.sheet_status), archived_at: z.string().nullable(), created_at: z.string(), updated_at: z.string(), name: LocalizedSchema, historical: z.boolean(), working_copy: z.boolean(), /** Set on the historical sheet only: a working copy is active (the single slot of §14.3). */ working_copy_active: z.boolean().nullable(), latest_version: z .object({ version_id: z.string(), version_number: z.number(), status: VersionStatusSchema, revision: z.number(), }) .nullable(), current_version: z .object({ version_id: z.string(), version_number: z.number(), published_at: z.string().nullable() }) .nullable(), draft_version: z .object({ version_id: z.string(), version_number: z.number(), revision: z.number() }) .nullable(), version_statuses: z.array(VersionStatusSchema), open_rounds: z.number(), latest_round: z .object({ review_id: z.string(), version_number: z.number(), round: z.number(), status: RoundStatusSchema, submitted_at: z.string().nullable(), }) .nullable(), }) export type OfficialSheetAdminSummary = z.infer const SheetAdminVersionSchema = z.object({ version_id: z.string(), version_number: z.number(), status: VersionStatusSchema, revision: z.number(), change_note: z.string().nullable(), created_at: z.string(), published_at: z.string().nullable(), deprecated_at: z.string().nullable(), source_version_number: z.number().nullable(), authors: z.array(PersonSchema), }) export type SheetAdminVersion = z.infer const SheetAdminRoundSchema = z.object({ review_id: z.string(), version_id: z.string(), version_number: z.number(), round: z.number(), revision: z.number(), status: RoundStatusSchema, submitted_by: PersonSchema.nullable(), submitted_at: z.string().nullable(), verified_at: z.string().nullable(), failure_outcome: z.enum(E.sheet_verification_outcome).nullable(), failure_code: z.string().nullable(), decided_by: PersonSchema.nullable(), decided_at: z.string().nullable(), withdrawn_at: z.string().nullable(), }) export type SheetAdminRound = z.infer const OfficialSheetAdminSchema = OfficialSheetAdminSummarySchema.extend({ working_copy_source: z.object({ version_id: z.string(), version_number: z.number() }).nullable(), /** Who saved the draft's current revision, null when no save wrote it (M8). */ draft_last_save: z .object({ revision: z.number(), saved_at: z.string(), saved_by: PersonSchema.nullable() }) .nullable(), versions: z.array(SheetAdminVersionSchema), rounds: z.array(SheetAdminRoundSchema), }) export type OfficialSheetAdmin = z.infer /** Every official sheet that is not deleted, one summary each. */ export async function listOfficialSheetsAdmin( client: FaunosteoClient, ): Promise { const { data, error, status } = await client.rpc('list_official_sheets_admin') if (error) failSheet(error, status) return parseSheetAnswer(z.array(OfficialSheetAdminSummarySchema), data) } /** One sheet's overview: summary, versions and rounds. Unknown and forbidden ids are `not_found`. */ export async function getOfficialSheetAdmin( client: FaunosteoClient, sheetId: string, ): Promise { if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found') const { data, error, status } = await client.rpc('get_official_sheet_admin', { sheet_id: sheetId }) if (error) failSheet(error, status) return parseSheetAnswer(OfficialSheetAdminSchema, data) } // --- Catalogue reads (readers, any assurance level) -------------------------- export interface CatalogVersionItem { id: string version_number: number status: 'published' | 'deprecated' published_at: string | null deprecated_at: string | null } /** * The published and deprecated versions of a sheet, newest first, through * the reader column grants of M4 and their RLS policy. An unknown or * unreadable sheet answers an empty list. */ export async function listSheetVersions( client: FaunosteoClient, sheetId: string, ): Promise { if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found') const { data, error, status } = await client .from('anatomical_sheet_versions') .select('id, version_number, status, published_at, deprecated_at') .eq('sheet_id', sheetId) .in('status', ['published', 'deprecated']) .order('version_number', { ascending: false }) if (error) failSheet(error, status) return (data ?? []) as CatalogVersionItem[] } export interface OwnCatalogGrant { kind: Enums<'catalog_grant_kind'> expires_at: string | null revoked_at: string | null } /** * The caller's own grant rows (the grants policy shows every account its * own), for the navigation hint of §5.3 only: never a control, the server * decides on every read. */ export async function listOwnCatalogGrants( client: FaunosteoClient, userId: string, ): Promise { const { data, error, status } = await client .from('anatomical_catalog_grants') .select('kind:grant_kind, expires_at, revoked_at') .eq('user_id', userId) if (error) failSheet(error, status) return data ?? [] } const SHA256_PATTERN = /^[0-9a-f]{64}$/ const DRAWING_BUCKET = 'anatomical-sheet-assets' interface StorageLikeError { name?: string status?: number statusCode?: string code?: string } /** * Folds a Storage answer: a missing object and a refused one are the same * `not_found` (Storage answers 400 or 404 for both); a request that never got * an answer is `network`. */ function classifyDrawingError(error: unknown): SheetFailureKind { const e = (error ?? {}) as StorageLikeError if (e.name === 'StorageUnknownError') return 'network' if (e.code === 'InvalidJWT' || e.status === 401) return 'session_expired' if (e.status === 429) return 'rate_limited' if (e.status === 400 || e.status === 404) return 'not_found' return 'unavailable' } /** * The bytes of one sheet drawing (`.svg`) under the Storage read * policy (§9.4). A malformed hash is refused before any request. The bytes * are untrusted: the core checks the hash and reads the SVG. */ export async function downloadSheetDrawing( client: FaunosteoClient, sha256: string, ): Promise { if (!SHA256_PATTERN.test(sha256)) throw new SheetFailure('invalid_input') const { data, error } = await client.storage.from(DRAWING_BUCKET).download(`${sha256}.svg`) if (error || !data) throw new SheetFailure(classifyDrawingError(error), error) return new Uint8Array(await data.arrayBuffer()) } // --- Drawing upload (editor, aal2; §9.2-§9.3) -------------------------------- /** Registers a drawing of a sheet; the row of the same hash is returned when it exists. */ export async function registerSheetAsset( client: FaunosteoClient, args: { sheet_id: string; sha256: string; byte_size: number; file_name: string }, ): Promise { const { data, error, status } = await client.rpc('register_sheet_asset', args) if (error) failSheet(error, status) return data } export interface SheetAssetRow { id: string sha256: string byte_size: number uploaded_at: string | null } /** The drawing rows of a sheet the caller can see; `uploaded_at` null is a pending row. */ export async function listSheetAssets( client: FaunosteoClient, sheetId: string, ): Promise { if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found') const { data, error, status } = await client .from('anatomical_sheet_assets') .select('id, sha256, byte_size, uploaded_at') .eq('sheet_id', sheetId) if (error) failSheet(error, status) return data ?? [] } /** The Storage code of a refusal: HTTP status, or body `statusCode` behind an HTTP 400 (LRN-113). */ function storageCode(error: StorageLikeError): string { const bodyCode = error.status === 400 ? error.statusCode : undefined return bodyCode ?? String(error.status) } /** * Uploads `.svg` without upsert. `present`: the object is already * there (409). A policy refusal (403: a pending row of another account) is * `upload.pending_other`; the caller then confirms once. The bytes are the * core's `stored`; no check here. */ export async function uploadSheetDrawing( client: FaunosteoClient, sha256: string, bytes: Uint8Array, ): Promise<'uploaded' | 'present'> { if (!SHA256_PATTERN.test(sha256)) throw new SheetFailure('invalid_input') const { error } = await client.storage .from(DRAWING_BUCKET) .upload(`${sha256}.svg`, bytes, { contentType: 'image/svg+xml', upsert: false }) if (!error) return 'uploaded' const code = storageCode(error) if (code === '409') return 'present' if (code === '403') throw new SheetFailure('upload.pending_other', error) throw new SheetFailure(classifyUploadError(error), error) } function classifyUploadError(error: StorageLikeError): SheetFailureKind { if (error.name === 'StorageUnknownError') return 'network' if (error.code === 'InvalidJWT' || error.status === 401) return 'session_expired' if (error.status === 429) return 'rate_limited' return 'unavailable' } /** Confirms the upload of a registered drawing (`upload_missing`, `size_mismatch`). */ export async function confirmSheetAssetUpload( client: FaunosteoClient, assetId: string, ): Promise { const { data, error, status } = await client.rpc('confirm_sheet_asset_upload', { asset_id: assetId, }) if (error) failSheet(error, status) return data }