import {z} from 'zod' export type GetApiReportsCasesIdArgs = {id: string, format?: ('json' | 'pdf') | undefined}; export type GetApiReportsCasesIdOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const appliedDecisionControls = z.object({governanceRevision: z.number().int().gte(1), organizationApproval: z.object({requireSecondReview: z.boolean(), secondReviewFor: z.array(z.enum(["same_identity", "allow", "restrict", "escalate"])), approverRoles: z.array(z.enum(["owner", "admin", "analyst"]))}), restrictedRoles: z.object({approval: z.array(z.enum(["analyst", "developer", "viewer"])), production: z.array(z.enum(["analyst", "developer", "viewer"]))}), screeningPolicy: z.object({id: z.string(), version: z.number().int().gte(1), review: z.object({requireSecondReview: z.boolean(), secondReviewFor: z.array(z.enum(["same_identity", "allow", "restrict", "escalate"])), approverRoles: z.array(z.enum(["owner", "admin", "analyst"]))})}).nullable()}); export const subject = z.object({name: z.string().min(2).max(300), entityType: z.enum(["person", "organization", "vessel", "aircraft", "other"]).optional(), identifiers: z.array(z.object({type: z.string().min(1).max(80), value: z.string().min(1).max(160), issuer: z.string().min(1).max(100).optional()})).optional(), birthDate: z.union([z.string(), z.string()]).optional(), country: z.string().min(2).max(100).optional()}); export const sourceProvenance = z.object({sourceId: z.string(), recordId: z.string(), field: z.string(), rawValue: z.string().optional()}); export const sourceRecord = z.object({id: z.string(), sourceId: z.string(), authority: z.string(), list: z.string(), sourceUrl: z.string(), entityType: z.enum(["person", "organization", "vessel", "aircraft", "other"]), names: z.array(z.object({value: z.string(), kind: z.enum(["primary", "alias"]), quality: z.enum(["strong", "weak", "unknown"]).optional(), script: z.string().optional(), provenance: sourceProvenance.optional()})), identifiers: z.array(z.object({type: z.string(), value: z.string(), issuer: z.string().optional(), provenance: sourceProvenance.optional()})), birthDates: z.array(z.object({value: z.string(), precision: z.enum(["day", "month", "year", "range", "unknown"]), original: z.string()})), addresses: z.array(z.object({text: z.string().optional(), country: z.string().optional(), provenance: sourceProvenance.optional()})), nationalities: z.array(z.string()), designations: z.array(z.object({category: z.enum(["financial_sanctions", "export_control", "debarment", "other"]), programs: z.array(z.string()), legalReferences: z.array(z.string()), wording: z.string().optional(), effectiveDate: z.string().optional()})), dataThrough: z.string().optional(), screeningPeriods: z.array(z.object({from: z.string().optional(), through: z.string().optional()})).optional(), publicContext: z.array(z.object({label: z.string().max(100), value: z.string().max(2000)})).optional(), extensions: z.record(z.string(), z.unknown())}); export const matchAssessment = z.object({name: z.object({similarity: z.number().int().gte(0).lte(100), method: z.string(), aliasKind: z.enum(["primary", "alias"]), aliasQuality: z.enum(["strong", "weak", "unknown"])}).nullable(), identifiers: z.object({status: z.enum(["agreement", "conflict", "not_supplied", "unavailable", "not_comparable"]), matched: z.number().int().gte(0).lte(9007199254740991), issuerAgreements: z.number().int().gte(0).lte(9007199254740991), issuerUnknown: z.number().int().gte(0).lte(9007199254740991), conflicts: z.number().int().gte(0).lte(9007199254740991)}), birthDate: z.object({status: z.enum(["agreement", "conflict", "not_supplied", "unavailable", "not_comparable"]), precision: z.enum(["year", "month", "day"]).optional()}), country: z.object({status: z.enum(["agreement", "conflict", "not_supplied", "unavailable", "not_comparable"])}), entityType: z.object({status: z.enum(["agreement", "conflict", "not_supplied", "unavailable", "not_comparable"])}), reviewTier: z.enum(["identifier", "corroborated", "conflicting", "name_only"]), alertBasis: z.enum(["identifier", "name", "name_and_birth_date", "partial_name"]), hasConflicts: z.boolean(), sameNameCandidates: z.number().int().gte(0).lte(9007199254740991)}); export const sourceNotice = z.object({text: z.string(), sourceUrl: z.string(), termsUrl: z.string(), licenseUrl: z.string().optional(), databaseDownloadUrl: z.string().optional()}); export const coverage = z.object({sourceId: z.string(), version: z.string(), retrievedAt: z.string(), publishedAt: z.union([z.string(), z.string()]).optional(), fresh: z.boolean(), sourceNotice: sourceNotice.optional()}); export const screeningPolicySnapshot = z.object({name: z.string().min(2).max(120), purpose: z.string().min(3).max(1000), jurisdictions: z.array(z.string().min(2).max(100)), matching: z.object({profile: z.enum(["standard", "focused"]), partialNames: z.enum(["review", "exclude"]).optional()}).optional(), requiredSources: z.record(z.string(), z.array(z.string().min(1).max(80))), optionalSources: z.record(z.string(), z.array(z.string().min(1).max(80))), exclusions: z.array(z.string().min(3).max(500)), externalChecks: z.array(z.string().min(3).max(200)), externalCheckGuidance: z.array(z.object({label: z.string().min(3).max(200), instructions: z.string().min(3).max(2000), evidenceExample: z.string().min(3).max(1000).optional()})).optional(), review: z.object({requireSecondReview: z.boolean().optional(), secondReviewFor: z.array(z.enum(["same_identity", "allow", "restrict", "escalate"])).optional(), approverRoles: z.array(z.enum(["owner", "admin", "analyst"])).optional()}), monitoringIntervalHours: z.union([z.literal(6), z.literal(24), z.literal(168)]), retentionTrigger: z.enum(["review_completed", "relationship_ended", "business_event"]), id: z.string(), version: z.number().int().gte(0), environment: z.enum(["sandbox", "production"]), createdAt: z.string()}); export const appliedMatchingPolicy = z.object({version: z.string(), profile: z.enum(["standard", "focused"]), nameThreshold: z.number().int().gte(0).lte(100), corroboratedNameThreshold: z.number().int().gte(0).lte(100), retrievalVersion: z.string(), partialNames: z.enum(["review", "exclude"]).optional()}); export const screeningResult = z.object({id: z.string(), environment: z.enum(["sandbox", "production"]), status: z.enum(["potential_match", "no_match"]), createdAt: z.string(), matches: z.array(z.object({record: sourceRecord, score: z.number().gte(0).lte(100), assessment: matchAssessment.optional(), evidence: z.array(z.object({field: z.string(), queryValue: z.string(), sourceValue: z.string(), method: z.string(), contribution: z.number(), explanation: z.string()})), conflicts: z.array(z.string())})), coverage: z.array(coverage), versions: z.object({dataset: z.string(), matchingEngine: z.string(), policy: z.string(), package: z.string().optional()}), disclaimer: z.string(), policySnapshot: screeningPolicySnapshot.optional(), matching: appliedMatchingPolicy.optional(), warnings: z.array(z.object({code: z.literal("limited_name_information"), message: z.string()})).optional()}); export const auditPacket = z.object({format: z.literal("sanctionskit-case-audit@1"), generatedAt: z.string(), environment: z.enum(["sandbox", "production"]), investigation: z.object({id: z.string(), screeningId: z.string(), counterpartyId: z.string().nullable(), decision: z.enum(["open", "confirmed", "dismissed"]), revision: z.number().int().gte(0), assigneeId: z.string().nullable(), priority: z.string(), dueAt: z.string().nullable(), escalatedAt: z.string().nullable(), requiresSecondReview: z.boolean(), reviewState: z.enum(["open", "pending_approval", "approved", "superseded"]), businessDisposition: z.enum(["pending", "allow", "restrict", "escalate"]), reviewStartedAt: z.string(), supersededByScreeningId: z.string().nullable(), supersededByCaseId: z.string().nullable(), approvalRequiredByPolicy: z.boolean(), approvalRequiredForActions: z.array(z.string()), approverRoles: z.array(z.string()), reviewConcern: z.string().nullable(), policyContext: z.object({id: z.string(), version: z.number().int().gte(0), name: z.string(), purpose: z.string(), exclusions: z.array(z.string())}).nullable(), decisionHistory: z.array(z.object({id: z.string(), screeningId: z.string().nullable(), decision: z.enum(["open", "confirmed", "dismissed"]), businessDisposition: z.enum(["pending", "allow", "restrict", "escalate"]).nullable(), rationale: z.string().nullable(), actorId: z.string(), actorLabel: z.string().nullable(), createdAt: z.string(), appliedControls: appliedDecisionControls.nullable()})), decisionHistoryTruncated: z.boolean(), checks: z.array(z.object({label: z.string(), instructions: z.string().optional(), evidenceExample: z.string().optional(), reviewConcern: z.string().optional(), status: z.enum(["outstanding", "completed_externally", "not_applicable"]), evidenceReference: z.string(), rationale: z.string(), actorId: z.string().nullable(), updatedAt: z.string().nullable()})), checkHistory: z.array(z.object({id: z.string(), screeningId: z.string(), label: z.string(), status: z.enum(["outstanding", "completed_externally", "not_applicable"]), evidenceReference: z.string(), rationale: z.string(), actorId: z.string(), updatedAt: z.string(), expiresAt: z.string().nullable()})), reuseChallenges: z.array(z.object({ruleId: z.string(), originCaseId: z.string(), challengedByCaseId: z.string(), actorId: z.string(), revokedAt: z.string(), affectedCaseIds: z.array(z.string())})), submittedBy: z.string().nullable(), approvedBy: z.string().nullable(), matches: z.array(z.object({id: z.string(), screeningId: z.string(), sourceId: z.string(), recordId: z.string(), identityDecision: z.string(), businessDecision: z.string(), rationale: z.string(), reusableUntil: z.string().nullable(), reusedRuleId: z.string().nullable(), actorId: z.string(), updatedAt: z.string()})), subject: subject.nullable(), originCorrection: z.object({caseId: z.string(), screeningId: z.string()}).nullable(), evidence: z.array(z.object({id: z.string(), screeningId: z.string(), sourceId: z.string(), recordId: z.string(), field: z.string(), value: z.string(), sourceReference: z.string(), verification: z.enum(["unverified", "verified"]), comparison: z.enum(["agrees", "conflicts", "unknown"]), notes: z.string(), content: z.string(), actorId: z.string(), createdAt: z.string(), expiresAt: z.string().nullable()})), corrections: z.array(z.object({id: z.string(), screeningId: z.string(), resultScreeningId: z.string(), resultCaseId: z.string().nullable(), before: subject, after: subject, reason: z.string(), actorId: z.string(), createdAt: z.string(), expiresAt: z.string().nullable()})), reviewHistory: z.array(z.object({id: z.string(), screeningId: z.string(), sourceId: z.string(), recordId: z.string(), review: z.object({id: z.string(), screeningId: z.string(), sourceId: z.string(), recordId: z.string(), identityDecision: z.string(), businessDecision: z.string(), rationale: z.string(), reusableUntil: z.string().nullable(), reusedRuleId: z.string().nullable(), actorId: z.string(), updatedAt: z.string()}), replacedBy: z.string(), reason: z.enum(["decision_updated", "evidence_added", "subject_corrected", "rule_challenged"]), createdAt: z.string(), expiresAt: z.string().nullable()})), comments: z.array(z.object({id: z.string(), body: z.string(), actorId: z.string(), createdAt: z.string()})), attachments: z.array(z.object({id: z.string(), title: z.string(), sha256: z.string(), size: z.number().int().gte(0), actorId: z.string(), createdAt: z.string(), expiresAt: z.string().nullable()}))}), evidence: z.array(z.object({id: z.string(), createdAt: z.string(), expiresAt: z.string().nullable(), expired: z.boolean(), subject: subject.nullable(), result: screeningResult.nullable()})), decisions: z.array(z.object({id: z.string(), actorId: z.string(), decision: z.string(), businessDisposition: z.enum(["pending", "allow", "restrict", "escalate"]), appliedControls: appliedDecisionControls.nullable(), notes: z.string().nullable(), createdAt: z.string(), screeningId: z.string().nullable(), evidenceExpired: z.boolean()})), attachments: z.array(z.object({id: z.string(), title: z.string(), sha256: z.string(), content: z.string(), createdAt: z.string()})), documents: z.array(z.object({id: z.string(), title: z.string(), url: z.string(), repository: z.string(), documentVersion: z.string(), sha256: z.string().nullable(), provenance: z.string(), verification: z.enum(["unverified", "reviewer_verified"]), verifiedAt: z.string().nullable(), actorId: z.string(), createdAt: z.string()})), holds: z.array(z.object({id: z.string(), reason: z.string(), until: z.string().nullable(), releasedAt: z.string().nullable(), releasedBy: z.string().nullable().optional(), releaseReason: z.string().nullable().optional()})), limitations: z.array(z.string())}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Download a bounded case audit packet in JSON or PDF * * GET /reports/cases/{id} */ export const getApiReportsCasesId = async (args: GetApiReportsCasesIdArgs, options: GetApiReportsCasesIdOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.format != null) query.append("format", String(args.format)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/reports/cases/${encodeURIComponent(String(args.id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(auditPacket, await res.json()) };