import {z} from 'zod' export type SchemasEnrollmentKey = string; export type TokenType = 'merchant'; export type OpenapiComponentsSchemasPan4 = string; export type ComponentsSchemasExpiryMonth = number; export type OpenapiComponentsSchemasExpiryYear2 = number; export type OpenapiComponentsSchemasCvc = string; export type OpenapiComponentsSchemasHolderName2 = string; export type Email = string; export type SchemasPhoneNumber = string; export type OpenapiComponentsSchemasCountryCodeAlpha3 = string; export type OpenapiComponentsSchemasCountryCodeAlpha2 = string; export type OpenapiComponentsSchemasCountryCodeNumeric = string; export type SchemasCountryCodeInput = OpenapiComponentsSchemasCountryCodeAlpha3 | OpenapiComponentsSchemasCountryCodeAlpha2 | OpenapiComponentsSchemasCountryCodeNumeric; export type OpenapiComponentsSchemasStateOrProvince2 = string; export type OpenapiComponentsSchemasCity2 = string; export type OpenapiComponentsSchemasLine13 = string; export type OpenapiComponentsSchemasLine23 = string; export type OpenapiComponentsSchemasPostalCode2 = string; export type ComponentsSchemasAddressInput = {countryCode: SchemasCountryCodeInput, stateOrProvince?: OpenapiComponentsSchemasStateOrProvince2 | undefined, city: OpenapiComponentsSchemasCity2, line1: OpenapiComponentsSchemasLine13, line2?: OpenapiComponentsSchemasLine23 | undefined, postalCode: OpenapiComponentsSchemasPostalCode2}; export type CardHolderInput = {name?: OpenapiComponentsSchemasHolderName2 | undefined, email?: Email | undefined, phoneNumber?: SchemasPhoneNumber | undefined, billingAddress?: ComponentsSchemasAddressInput | undefined}; export type OpenapiComponentsSchemasCardInput = {number: OpenapiComponentsSchemasPan4, expiryMonth: ComponentsSchemasExpiryMonth, expiryYear: OpenapiComponentsSchemasExpiryYear2, cvc?: OpenapiComponentsSchemasCvc | undefined, holder?: CardHolderInput | undefined}; export type TokenCreate = {enrollmentKey: SchemasEnrollmentKey, type: TokenType, cardData: OpenapiComponentsSchemasCardInput}; export type CreateApiNetworkTokensArgs = {body: TokenCreate}; export type CreateApiNetworkTokensOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const networkTokenKey = z.string().min(5).max(120); export const tokenStatus = z.enum(["requested", "active", "suspended", "failed", "archivePending", "archived"]); export const tokenType = z.literal("merchant"); export const schemasNetwork = z.enum(["mastercard", "visa"]); export const tokenProvider = z.enum(["scof", "vts"]); export const schemasAgentKey = z.string().min(5).max(120); export const openapiComponentsSchemasMerchantKey2 = z.string().min(5).max(120); export const schemasEnrollmentKey = z.string().min(10).max(120); export const lastTokenRefresh = z.string(); export const tokenError = z.object({code: z.string(), detail: z.string()}); export const created = z.string(); export const lastModified = z.string(); export const openapiComponentsSchemasVersion3 = z.number().int().gte(0); export const token = z.object({key: networkTokenKey, status: tokenStatus, type: tokenType, network: schemasNetwork, provider: tokenProvider, agentKey: schemasAgentKey, merchantKey: openapiComponentsSchemasMerchantKey2, enrollmentKey: schemasEnrollmentKey, lastTokenRefresh: lastTokenRefresh.optional(), error: tokenError.optional(), created: created, lastModified: lastModified.optional(), version: openapiComponentsSchemasVersion3}); 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 }; /** * Create Network Token * * POST /networkTokens * * Also accepts auth: BearerToken */ export const createApiNetworkTokens = async (args: CreateApiNetworkTokensArgs, options?: CreateApiNetworkTokensOptions) => { const {baseUrl = "https://eu-west-1.api.silverflow.com/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/networkTokens${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(token, await res.json()) };