UNPKG

@visionfi/server-sdk

Version:

Server-side SDK for VisionFI API access using Google Service Account authentication

662 lines (661 loc) 26 kB
import { VisionFiConfig, AnalyzeDocumentOptions, AnalysisJob, AnalysisResult, AuthVerificationResult, AuthTokenResult, ClientInfoResponse, WorkflowsResponse, CreatePackageOptions, CreatePackageResponse, PackageInfo, ListPackagesOptions, ListPackagesResponse, PackageAuditHistoryResponse, AddDocumentsOptions, AddDocumentsResponse, DeleteDocumentResponse, ExternalReferencesOptions, ExternalReferencesResponse, ExecuteProcessingOptions, ExecuteProcessingResponse, ProcessingResultResponse, ProcessingHistoryResponse, ProcessingHistoryOptions, ProductTypesResponse, ProcessingViewOptions, ProcessingViewResponse } from './types/index.js'; import { DocuSignConfig, DocuSignConfigResponse, DocuSignAuthStatusUpdate, DocuSignAuthStatusResponse, DocuSignConnectWebhook, DocuSignConnectWebhooksResponse, DocuSignConnectWebhookResponse, DocuSignConnectWebhookDeleteResponse } from './integrations/docusign/types.js'; /** * Main client for interacting with the VisionFi platform API. * Handles authentication, document analysis, and results retrieval. * * @example * ```typescript * // With explicit service account credentials * const client = new VisionFi({ * serviceAccountPath: './service-account.json' * }); * * // Using Application Default Credentials (ADC) in GCP environments * const client = new VisionFi(); // Automatically uses ADC * * // Verify authentication * const authResult = await client.verifyAuth(); * * // Analyze a document * const job = await client.analyzeDocument(fileBuffer, { * fileName: 'document.pdf', * analysisType: 'auto_loan_abstract' * }); * * // Get results * const results = await client.getResults(job.uuid); * ``` */ export declare class VisionFi { /** Base URL for the VisionFi API */ private apiBaseUrl; /** Google Auth instance for authentication */ private auth; /** Axios instance for making HTTP requests */ private apiClient; /** DocuSign integration instance */ private docuSignIntegration; /** * Utility method to extract Authorization header from various header object types * @param headers - Headers object (could be Map, Headers, or plain object) * @returns Authorization header value or null if not found */ private getAuthorizationHeader; constructor(config?: VisionFiConfig); /** * Verifies authentication with the VisionFi API */ verifyAuth(): Promise<AuthVerificationResult>; /** * Retrieves the JWT authentication token to use with the VisionFi API * @returns A promise that resolves to an object containing the token * @example * ```typescript * const { token } = await client.getAuthToken(); * console.log('JWT Token:', token); * * // Can be used in other API clients or tools like Postman * // Example: Authorization: Bearer [token] * ``` */ getAuthToken(): Promise<AuthTokenResult>; /** * Retrieves client information from the VisionFi API * @returns A promise that resolves to client information and configuration * @example * ```typescript * const clientInfo = await client.getClientInfo(); * * if (clientInfo.success) { * console.log('Client name:', clientInfo.data.name); * * // Check for specific features * if (clientInfo.data.features?.includes('document-analysis')) { * // Enable document analysis features * } * } else { * console.error('Failed to get client info:', clientInfo.message); * } * ``` */ getClientInfo(): Promise<ClientInfoResponse>; /** * Retrieves available document analysis workflows from the VisionFi API * @returns A promise that resolves to the list of available workflows * @example * ```typescript * const workflowsResponse = await client.getWorkflows(); * * if (workflowsResponse.success) { * console.log('Available workflows:'); * workflowsResponse.data?.forEach(workflow => { * console.log(`- ${workflow.workflow_key}: ${workflow.description}`); * }); * } else { * console.error('Failed to get workflows:', workflowsResponse.message); * } * ``` */ getWorkflows(): Promise<WorkflowsResponse>; /** * Uploads and analyzes a document * @param fileBuffer The file buffer to upload * @param options Options for document analysis */ analyzeDocument(fileBuffer: Buffer, options: AnalyzeDocumentOptions): Promise<AnalysisJob>; /** * Retrieves the results of an analysis job * @param jobUuid The UUID of the analysis job * @param pollInterval Optional interval in ms to poll for results until completed * @param maxAttempts Optional maximum number of polling attempts * @param earlyCancelAttempts Optional number of attempts before emitting a "job likely invalid" warning */ getResults(jobUuid: string, pollInterval?: number, maxAttempts?: number, earlyCancelAttempts?: number): Promise<AnalysisResult>; private handleError; /** * Retrieves the current DocuSign integration configuration. * * @returns A promise that resolves to the DocuSign configuration response * * @example * ```typescript * const configResponse = await client.getDocuSignConfig(); * * if (configResponse.success) { * console.log('DocuSign configuration:', configResponse.data); * } else { * console.error('Failed to get DocuSign config:', configResponse.message); * } * ``` */ getDocuSignConfig(): Promise<DocuSignConfigResponse>; /** * Updates or creates the DocuSign integration configuration. * * @param config - The DocuSign configuration to update or create * @returns A promise that resolves to the DocuSign configuration response * * @example * ```typescript * const configResponse = await client.updateDocuSignConfig({ * userId: '12345678-1234-1234-1234-123456789012', * accountId: '98765432-9876-9876-9876-987654321098', * baseUri: 'https://demo.docusign.net/restapi', * name: 'Production DocuSign Integration', * enabled: true * }); * * if (configResponse.success) { * console.log('DocuSign configuration updated:', configResponse.data); * } else { * console.error('Failed to update DocuSign config:', configResponse.message); * } * ``` */ updateDocuSignConfig(config: DocuSignConfig): Promise<DocuSignConfigResponse>; /** * Updates only the authentication status of a DocuSign integration. * * @param statusUpdate - The authentication status update data * @returns A promise that resolves to the DocuSign authentication status response * * @example * ```typescript * const statusResponse = await client.updateDocuSignAuthStatus({ * authenticationStatus: 'authenticated', * lastAuthenticated: new Date().toISOString() * }); * * if (statusResponse.success) { * console.log('DocuSign auth status updated:', statusResponse.data); * } else { * console.error('Failed to update auth status:', statusResponse.message); * } * ``` */ updateDocuSignAuthStatus(statusUpdate: DocuSignAuthStatusUpdate): Promise<DocuSignAuthStatusResponse>; /** * Retrieves all webhook configurations for the client's DocuSign integration. * * @returns A promise that resolves to the list of webhook configurations * * @example * ```typescript * const webhooksResponse = await client.getDocuSignConnectWebhooks(); * * if (webhooksResponse.success) { * console.log('DocuSign webhooks:', webhooksResponse.data); * } else { * console.error('Failed to get webhooks:', webhooksResponse.message); * } * ``` */ getDocuSignConnectWebhooks(): Promise<DocuSignConnectWebhooksResponse>; /** * Retrieves a specific webhook configuration by its GUID. * * @param webhookGuid - The unique identifier for the webhook configuration * @returns A promise that resolves to the specific webhook configuration * * @example * ```typescript * const webhookGuid = 'd0381ee4-5b83-4d6b-9f37-177c2a6a79f2'; * const webhookResponse = await client.getDocuSignConnectWebhook(webhookGuid); * * if (webhookResponse.success) { * console.log('DocuSign webhook:', webhookResponse.data); * } else { * console.error('Failed to get webhook:', webhookResponse.message); * } * ``` */ getDocuSignConnectWebhook(webhookGuid: string): Promise<DocuSignConnectWebhookResponse>; /** * Creates a new DocuSign Connect webhook configuration. * * @param webhook - The webhook configuration to create * @returns A promise that resolves to the created webhook configuration * * @example * ```typescript * const newWebhook = { * webhookGuid: 'd0381ee4-5b83-4d6b-9f37-177c2a6a79f2', * hmacSecret: '89c3444a-f4c2-4fda-98b8-59dc2fe3ea29', * workflowId: 'electronic-signatures-workflow' * }; * * const webhookResponse = await client.addDocuSignConnectWebhook(newWebhook); * * if (webhookResponse.success) { * console.log('DocuSign webhook created:', webhookResponse.data); * } else { * console.error('Failed to create webhook:', webhookResponse.message); * } * ``` */ addDocuSignConnectWebhook(webhook: DocuSignConnectWebhook): Promise<DocuSignConnectWebhookResponse>; /** * Updates an existing DocuSign Connect webhook configuration. * * @param webhookGuid - The unique identifier for the webhook configuration * @param webhook - The partial webhook configuration to update * @returns A promise that resolves to the updated webhook configuration * * @example * ```typescript * const webhookGuid = 'd0381ee4-5b83-4d6b-9f37-177c2a6a79f2'; * const webhookUpdate = { * hmacSecret: 'updated-hmac-secret-value', * workflowId: 'updated-workflow-id' * }; * * const webhookResponse = await client.updateDocuSignConnectWebhook(webhookGuid, webhookUpdate); * * if (webhookResponse.success) { * console.log('DocuSign webhook updated:', webhookResponse.data); * } else { * console.error('Failed to update webhook:', webhookResponse.message); * } * ``` */ updateDocuSignConnectWebhook(webhookGuid: string, webhook: Partial<Omit<DocuSignConnectWebhook, 'webhookGuid'>>): Promise<DocuSignConnectWebhookResponse>; /** * Deletes a DocuSign Connect webhook configuration. * * @param webhookGuid - The unique identifier for the webhook configuration * @returns A promise that resolves to the deletion response * * @example * ```typescript * const webhookGuid = 'd0381ee4-5b83-4d6b-9f37-177c2a6a79f2'; * const deleteResponse = await client.deleteDocuSignConnectWebhook(webhookGuid); * * if (deleteResponse.success) { * console.log('DocuSign webhook deleted:', deleteResponse.message); * } else { * console.error('Failed to delete webhook:', deleteResponse.message); * } * ``` */ deleteDocuSignConnectWebhook(webhookGuid: string): Promise<DocuSignConnectWebhookDeleteResponse>; /** * Gets a DocuSign OAuth consent URL for tenant authorization * @param environment Which DocuSign environment to use ('prod' or 'dev') * @returns A promise that resolves to the consent URL * * @example * ```typescript * // Generate a consent URL for the production DocuSign environment * try { * const consentUrl = await client.getDocuSignConsentUrl('prod'); * console.log('DocuSign consent URL:', consentUrl); * * // Provide this URL to the user to authorize DocuSign integration * } catch (error) { * console.error('Error generating consent URL:', error); * } * ``` */ getDocuSignConsentUrl(environment: 'prod' | 'dev'): Promise<string>; /** * Builds the complete webhook URL for a specific DocuSign Connect webhook * * @param webhookGuid - The unique identifier for the webhook configuration * @returns A promise that resolves to the complete webhook URL that can be used in DocuSign Connect configuration * * @example * ```typescript * // Get the complete webhook URL for a specific webhook * try { * const webhookGuid = 'd0381ee4-5b83-4d6b-9f37-177c2a6a79f2'; * const webhookUrl = await client.getDocuSignWebhookUrl(webhookGuid); * * console.log('DocuSign Connect webhook URL:', webhookUrl); * // Example: https://platform.visionfi.ai/api/v1/webhooks/tenant123/docusign/d0381ee4-5b83-4d6b-9f37-177c2a6a79f2 * * // Use this URL in your DocuSign Connect configuration * } catch (error) { * console.error('Error generating webhook URL:', error.message); * } * ``` */ getDocuSignWebhookUrl(webhookGuid: string): Promise<string>; /** * Creates a new package for document processing. * * @param options - The package creation options * @returns A promise that resolves to the created package response * * @example * ```typescript * const packageResponse = await client.createPackage({ * description: 'Test vehicle loan application package', * productType: 'consumer_loan_vehicle_installment', * externalReferenceIds: ['APP-2024-001', 'LOCAL-ID-12345'] * }); * * console.log('Package created:', packageResponse.packageId); * ``` */ createPackage(options: CreatePackageOptions): Promise<CreatePackageResponse>; /** * Retrieves a list of packages with optional filtering. * * @param options - Optional filtering options * @returns A promise that resolves to the list of packages * * @example * ```typescript * // List all packages * const allPackages = await client.listPackages(); * * // List packages with filters * const filteredPackages = await client.listPackages({ * externalReferences: 'APP-2024-001,LOCAL-ID-12345', * productTypes: 'consumer_loan_vehicle_installment', * createdAfter: '2024-01-15T10:30:00Z' * }); * * if (filteredPackages.success) { * console.log('Found packages:', filteredPackages.data?.length); * } * ``` */ listPackages(options?: ListPackagesOptions): Promise<ListPackagesResponse>; /** * Retrieves a specific package by its ID. * * @param packageId - The unique identifier for the package * @returns A promise that resolves to the package information * * @example * ```typescript * const packageInfo = await client.getPackage('package-uuid-here'); * * console.log('Package status:', packageInfo.status); * console.log('Total files:', packageInfo.totalFiles); * console.log('External references:', packageInfo.externalReferenceIds); * ``` */ getPackage(packageId: string): Promise<PackageInfo>; /** * Gets audit history for a specific package. * * @param packageId - The unique identifier for the package * @param limit - Optional number of audit entries to return (default: 50, max: 200) * @returns A promise that resolves to the package audit history * * @example * ```typescript * const auditHistory = await client.getPackageAuditHistory('package-uuid-here'); * * console.log('Package audit history:', auditHistory.auditHistory); * console.log('Total entries:', auditHistory.total); * * // With custom limit * const limitedHistory = await client.getPackageAuditHistory('package-uuid-here', 100); * ``` */ getPackageAuditHistory(packageId: string, limit?: number): Promise<PackageAuditHistoryResponse>; /** * Adds one or more documents to an existing package. * * @param packageId - The unique identifier for the package * @param options - The documents to add * @returns A promise that resolves to the add documents response * * @example * ```typescript * // Add single document * const fileBuffer = fs.readFileSync('./document.pdf'); * const addResponse = await client.addDocumentsToPackage('package-uuid', { * files: [{ * fileName: 'drivers_license.pdf', * fileBase64: fileBuffer.toString('base64') * }] * }); * * console.log('Files added:', addResponse.filesAdded); * console.log('Total files:', addResponse.totalFiles); * ``` */ addDocumentsToPackage(packageId: string, options: AddDocumentsOptions): Promise<AddDocumentsResponse>; /** * Convenience method to add a single file buffer to a package. * * @param packageId - The unique identifier for the package * @param fileBuffer - The file buffer to add * @param fileName - The name of the file * @returns A promise that resolves to the add documents response * * @example * ```typescript * const fileBuffer = fs.readFileSync('./document.pdf'); * const addResponse = await client.addFileToPackage( * 'package-uuid', * fileBuffer, * 'document.pdf' * ); * * console.log('Files added:', addResponse.filesAdded); * console.log('Total files:', addResponse.totalFiles); * ``` */ addFileToPackage(packageId: string, fileBuffer: Buffer, fileName: string): Promise<AddDocumentsResponse>; /** * Soft deletes a document from a package. * * @param packageId - The unique identifier for the package * @param documentUuid - The unique identifier for the document * @returns A promise that resolves to the delete response * * @example * ```typescript * const deleteResponse = await client.deleteDocumentFromPackage( * 'package-uuid', * 'document-uuid' * ); * * if (deleteResponse.success) { * console.log('Document deleted:', deleteResponse.message); * } * ``` */ deleteDocumentFromPackage(packageId: string, documentUuid: string): Promise<DeleteDocumentResponse>; /** * Adds external reference IDs to a package. * * @param packageId - The unique identifier for the package * @param options - The reference IDs to add * @returns A promise that resolves to the add references response * * @example * ```typescript * const addRefsResponse = await client.addExternalReferences('package-uuid', { * referenceIds: ['NEW-REF-001', 'UPDATED-ID-456'] * }); * * if (addRefsResponse.success) { * console.log('References added:', addRefsResponse.message); * } * ``` */ addExternalReferences(packageId: string, options: ExternalReferencesOptions): Promise<ExternalReferencesResponse>; /** * Removes external reference IDs from a package. * * @param packageId - The unique identifier for the package * @param options - The reference IDs to remove * @returns A promise that resolves to the remove references response * * @example * ```typescript * const removeRefsResponse = await client.removeExternalReferences('package-uuid', { * referenceIds: ['LOCAL-ID-12345'] * }); * * if (removeRefsResponse.success) { * console.log('References removed:', removeRefsResponse.message); * } * ``` */ removeExternalReferences(packageId: string, options: ExternalReferencesOptions): Promise<ExternalReferencesResponse>; /** * Executes a specific prompt configuration on package documents. * * @param packageId - The unique identifier for the package * @param options - The processing execution options * @returns A promise that resolves to the execute processing response * * @example * ```typescript * const processingResponse = await client.executeProcessing('package-uuid', { * configId: 'vehicle-info-extraction', * documentUuids: [] // Optional: process specific documents only * }); * * console.log('Processing ID:', processingResponse.processingId); * console.log('Status:', processingResponse.status); // Always 'queued' initially * ``` */ executeProcessing(packageId: string, options: ExecuteProcessingOptions): Promise<ExecuteProcessingResponse>; /** * Retrieves all processing history for a package. * * @param packageId - The unique identifier for the package * @param options - Optional parameters for the request * @returns A promise that resolves to the processing history * * @example * ```typescript * const history = await client.getProcessingHistory('package-uuid-here'); * * if (history.success && history.data) { * console.log('Total processing attempts:', history.data.total); * history.data.processingHistory.forEach(entry => { * console.log(`Processing ${entry.processingId}: ${entry.status}`); * }); * } * * // Get history with results included * const historyWithResults = await client.getProcessingHistory('package-uuid-here', { * includeResults: true * }); * ``` */ getProcessingHistory(packageId: string, options?: ProcessingHistoryOptions): Promise<ProcessingHistoryResponse>; /** * Retrieves all processing history with results for a package. * This is a convenience method that automatically includes processing results. * * @param packageId - The unique identifier for the package * @returns A promise that resolves to the processing history with results * * @example * ```typescript * const results = await client.getProcessingWithResults('package-uuid-here'); * * if (results.success && results.data) { * results.data.processingHistory.forEach(entry => { * if (entry.status === 'completed' && entry.result) { * console.log('Processing result:', entry.result.data); * if (entry.result.confidence) { * console.log('Confidence:', entry.result.confidence); * } * } * }); * } * ``` */ getProcessingWithResults(packageId: string): Promise<ProcessingHistoryResponse>; /** * Retrieves the status and results of a prompt processing request. * * @param packageId - The unique identifier for the package * @param processingId - The unique identifier for the processing request * @param pollInterval - Optional interval in ms to poll for results until completed * @param maxAttempts - Optional maximum number of polling attempts * @returns A promise that resolves to the processing result * * @example * ```typescript * // Get processing result once * const result = await client.getProcessingResult('package-uuid', 'processing-uuid'); * * // Poll for completion (check every 3 seconds, max 20 attempts) * const result = await client.getProcessingResult( * 'package-uuid', * 'processing-uuid', * 3000, * 20 * ); * * if (result.success && result.data?.status === 'completed') { * console.log('Processing results:', result.data.result); * } * ``` */ getProcessingResult(packageId: string, processingId: string, pollInterval?: number, maxAttempts?: number): Promise<ProcessingResultResponse>; /** * Retrieves available product types. * * @returns A promise that resolves to the product types response * * @example * ```typescript * const productTypesResponse = await client.getProductTypes(); * * if (productTypesResponse.success) { * console.log('Available product types:'); * productTypesResponse.data?.forEach(productType => { * console.log(`- ${productType.id}: ${productType.name}`); * }); * } * ``` */ getProductTypes(): Promise<ProductTypesResponse>; /** * Retrieves a rendered HTML view for a completed processing result. * * Prerequisites: * - Processing status must be 'completed' * - `hasViews` must be true in the processing result * - `configCollectionId` and `configVersionId` must be present * - Processing result must contain artifacts with data * * @param packageId - The unique identifier for the package * @param processingId - The unique identifier for the processing request * @param options - Optional parameters including viewName * @returns A promise that resolves to the processing view response with base64-encoded HTML * * @example * ```typescript * // Assuming you've already checked that hasViews is true from getProcessingResult * // Get the default view * const viewResponse = await client.getProcessingView( * 'package-uuid', * 'processing-uuid' * ); * * if (viewResponse.success && viewResponse.view) { * // Decode the base64 HTML * const html = Buffer.from(viewResponse.view, 'base64').toString('utf-8'); * * // Save to file * fs.writeFileSync('result.html', html); * * // Or use in your application * console.log('HTML content retrieved successfully'); * } * * // Use a specific template * const viewResponse = await client.getProcessingView( * 'package-uuid', * 'processing-uuid', * { viewName: 'custom-template' } * ); * ``` */ getProcessingView(packageId: string, processingId: string, options?: ProcessingViewOptions): Promise<ProcessingViewResponse>; }