A TypeScript client library for interacting with the Midaz API. This SDK provides a robust interface for accessing Midaz's financial ledger services with full TypeScript type safety.
The Midaz SDK enables seamless integration with Midaz's financial services platform. It offers a comprehensive set of tools for managing organizations, ledgers, accounts, transactions, and other financial entities with a clean, intuitive interface.
- Type-Safe API: Full TypeScript support with accurate type definitions
- Builder Pattern: Fluent interfaces for constructing complex objects
- Comprehensive Error Handling: Sophisticated error handling with recovery mechanisms
- Observability: Built-in tracing, metrics, and logging capabilities
- Layered Architecture: Clear separation between client, entities, API, and model layers
- Automatic Retries: Configurable retry policies for transient failures
- Concurrency Controls: Utilities for managing parallel operations with controlled throughput
- Caching: In-memory caching mechanisms for improved performance
- Validation: Extensive input validation with clear error messages
- API Versioning: Support for multiple API versions with version transformers
- Abort Control: Support for cancellable requests using AbortController
- Access Manager: Plugin-based authentication with external identity providers
- Comprehensive Examples: Detailed examples for all major features
npm install midaz-sdk
# or
yarn add midaz-sdkIf you're contributing to the SDK or running it from source:
# Clone the repository
git clone https://github.com/LerianStudio/midaz-sdk-typescript.git
cd midaz-sdk-typescript
# Install all dependencies (including dev dependencies)
npm run setup
# Build the SDK
npm run buildimport { MidazClient, createClientConfigWithAccessManager } from 'midaz-sdk';
// Initialize the client with PluginAccessManager
const client = new MidazClient(
createClientConfigWithAccessManager({
address: 'https://auth.example.com', // Plugin Auth address
clientId: 'your-client-id', // OAuth client ID
clientSecret: 'your-client-secret', // OAuth client secret
})
.withEnvironment('sandbox') // Options: 'development', 'sandbox', 'production'
);
// Create an asset using the builder pattern
import { createAssetBuilder } from 'midaz-sdk';
const assetInput = createAssetBuilder('US Dollar', 'USD')
.withType('currency')
.withMetadata({ precision: 2, symbol: '$' })
.build();
const asset = await client.entities.assets.createAsset('org_123', 'ledger_456', assetInput);
// Create an account
import { createAccountBuilder } from 'midaz-sdk';
const accountInput = createAccountBuilder('Savings Account', 'USD')
.withType('savings')
.withAlias('personal-savings')
.build();
const account = await client.entities.accounts.createAccount('org_123', 'ledger_456', accountInput);
// Create a transaction
import { createTransactionBuilder } from 'midaz-sdk';
const transactionInput = createTransactionBuilder()
.withCode('payment_001')
.withOperations([
{
accountId: 'source_account_id',
assetCode: 'USD',
amount: 100 * 100, // $100.00
type: 'debit',
},
{
accountId: 'destination_account_id',
assetCode: 'USD',
amount: 100 * 100, // $100.00
type: 'credit',
},
])
.withMetadata({ purpose: 'Monthly payment' })
.build();
// Use enhanced error recovery for critical operations
import { withEnhancedRecovery } from 'midaz-sdk/util/error';
const result = await withEnhancedRecovery(
() => client.entities.transactions.createTransaction('org_123', 'ledger_456', transactionInput),
{
maxRetries: 3,
enableSmartRecovery: true,
}
);
// Clean up resources when done
client.close();For applications that need to integrate with external identity providers, the SDK provides a PluginAccessManager:
import { createClientConfigWithAccessManager, MidazClient } from 'midaz-sdk';
// Initialize the client with Access Manager authentication
const client = new MidazClient(
createClientConfigWithAccessManager({
address: 'https://auth.example.com', // Identity provider address
clientId: 'your-client-id', // OAuth client ID
clientSecret: 'your-client-secret', // OAuth client secret
tokenEndpoint: '/oauth/token', // Optional, defaults to '/oauth/token'
refreshThresholdSeconds: 300, // Optional, defaults to 300 (5 minutes)
})
.withEnvironment('sandbox')
.withApiVersion('v1')
);
// The SDK will automatically handle token acquisition and renewal
// You can now use the client as normal
const organizations = await client.entities.organizations.listOrganizations();
// For environment-specific configurations with Access Manager
const sandboxClient = new MidazClient(
createSandboxConfigWithAccessManager({
address: 'https://auth.example.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
})
);
// Clean up resources when done
client.close();The SDK uses PluginAccessManager for authentication with external identity providers:
The SDK integrates with external identity providers using OAuth through the PluginAccessManager:
import { MidazClient, createClientConfigWithAccessManager } from 'midaz-sdk';
const client = new MidazClient(
createClientConfigWithAccessManager({
address: 'https://auth.example.com', // Plugin Auth address
clientId: 'your-client-id', // OAuth client ID
clientSecret: 'your-client-secret', // OAuth client secret
tokenEndpoint: '/oauth/token', // Optional, defaults to '/oauth/token'
refreshThresholdSeconds: 300, // Optional, defaults to 300 (5 minutes)
})
.withEnvironment('sandbox')
);The PluginAccessManager automatically handles token acquisition, caching, and renewal, eliminating the need to manage authentication tokens manually.
For detailed documentation, see the SDK Documentation which includes:
- Overview - High-level architecture overview and design principles
- Service Layer - Service layer design and patterns
- Error Handling - Error handling architecture and recovery mechanisms
- Data Modeling - Data modeling approach and validation
- Client Interface - Client interface design and usage
- Builder Pattern - How to use builders for creating complex objects
- Error Handling - Error handling and recovery strategies
- Assets - Working with assets (currencies, commodities, etc.)
- Accounts - Working with accounts
- Transactions - Creating and managing transactions
- Organizations - Working with organizations
- Ledgers - Managing ledgers
- Asset Rates - Managing exchange rates between assets
- Balances - Working with account balances
- Operations - Managing operations that make up transactions
- Portfolios - Working with portfolios
- Segments - Managing segments for analytics and grouping
- Account Helpers - Helper functions for account operations
- Cache - Caching mechanisms for improved performance
- Concurrency - Utilities for managing concurrent operations
- Config - Configuration management
- Data - Data formatting and pagination utilities
- Error Handling - Error handling utilities and enhanced recovery
- HTTP Client - Low-level HTTP client for API communication
- Network - High-level networking utilities and retry mechanisms
- Observability - Tracing, metrics, and logging utilities
- Pagination - Utilities for handling paginated responses
- Validation - Data validation utilities
The Midaz SDK is written in TypeScript and provides full type definitions for all APIs. It requires TypeScript 5.8 or later.
The SDK includes a comprehensive set of npm scripts with automatic dependency checking. If you run a command that requires development dependencies that aren't installed, the script will automatically guide you through the installation process.
# Install all development dependencies
npm run setupnpm run build # Build all targets (CommonJS, ESM, and TypeScript definitions)
npm run build:cjs # Build CommonJS module
npm run build:esm # Build ES module
npm run build:types # Build TypeScript type definitions
npm run build:watch # Watch mode for development
npm run dev # Alias for build:watch
npm run clean # Clean build artifactsnpm run test # Run all tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
npm run test:ci # Run tests in CI modenpm run lint # Check code style with ESLint
npm run lint:fix # Fix auto-fixable linting issues
npm run format # Format code with Prettier
npm run format:check # Check if code is formatted
npm run typecheck # Type-check without buildingnpm run docs # Generate API documentation
npm run docs:serve # Generate and serve documentation locallynpm run size # Check bundle size
npm run examples # Run example scriptsAll scripts include automatic dependency checking. For example:
- Running
npm run buildwithout TypeScript installed will prompt you to install it - Running
npm run testwithout Jest installed will guide you through the setup - Running
npm run lintwithout ESLint will help you get it installed
This ensures you never encounter cryptic "command not found" errors!
If you encounter any issues:
- First Time Setup: Run
npm run setupto install all development dependencies - Build Errors: Run
npm run cleanthennpm run build - Test Failures: Ensure you have the latest dependencies with
npm run setup - Linting Issues: Use
npm run lint:fixto automatically fix common issues
The SDK is designed to work in both Node.js and browser environments:
- Pure TypeScript implementation with no Node.js-specific runtime dependencies
- Uses Web Crypto API for cryptographic operations
- Provides both CommonJS and ESM builds
- Fully tree-shakeable for optimal bundle sizes
This project uses GitHub Actions for continuous integration and delivery:
- Automated testing across multiple Node.js versions
- Code quality checks with ESLint and Prettier
- Automated dependency updates via Dependabot
- Automated release process with semantic versioning
- Automated changelog generation
Contributions are welcome! Please see our Contributing Guide for details on how to contribute to the Midaz SDK.
- Fork and clone the repository
- Run
npm run setupto install all dependencies - Make your changes
- Run
npm run testto ensure tests pass - Run
npm run lint:fixto fix code style - Submit a pull request
For more detailed development information, see our Developer Guide.
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.