import {z} from 'zod' export type SimulateRuleDefinition = {config: {[key: string]: unknown}, type: string}; export type SimulateMatchRequest = {contextId: string, rule?: SimulateRuleDefinition | undefined, ruleId?: string | undefined, sampleLimit?: number | undefined}; export type CreateApiV1MatchingSimulateArgs = {body: SimulateMatchRequest}; export type CreateApiV1MatchingSimulateOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const candidateTransactionView = z.object({amount: z.string(), baseAmount: z.string().optional(), currency: z.string(), date: z.string(), externalId: z.string().optional(), id: z.string(), sourceId: z.string()}); export const candidateMatchedKey = z.object({agreed: z.boolean(), field: z.string()}); export const candidateWhy = z.object({amountMatch: z.boolean(), currencyMatch: z.boolean(), dateMatch: z.boolean(), matchedKeys: z.array(candidateMatchedKey).nullable().optional(), referenceScore: z.number().gte(0).lte(1)}); export const simulateMatchPairResponse = z.object({amountDelta: z.string(), dateDeltaDays: z.number().int(), left: candidateTransactionView, right: candidateTransactionView, score: z.number().int().gte(0).lte(100), why: candidateWhy}); export const simulateMatchResponse = z.object({matchedGroups: z.number().int().gte(0), ruleId: z.string().optional(), ruleType: z.string(), sample: z.array(simulateMatchPairResponse).nullable(), sampleTruncated: z.boolean(), unmatchedLeft: z.number().int().gte(0), unmatchedRight: z.number().int().gte(0)}); 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 }; /** * Simulate a match rule against a context (read-only dry run) * * POST /v1/matching/simulate */ export const createApiV1MatchingSimulate = async (args: CreateApiV1MatchingSimulateArgs, options?: CreateApiV1MatchingSimulateOptions) => { const {baseUrl = "https://identity.sandbox.lerian.net", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/matching/simulate${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(simulateMatchResponse, await res.json()) };