Skip to content

Utilities

Additional utilities including configuration management and error classes.

Configuration

Default Configuration

The library provides sensible defaults for all configuration options:

const defaultConfig = {
  ipfs: {
    gateway: 'https://ipfs.io',
    pinningService: 'https://api.pinata.cloud',
    pinningKey: process.env.IPFS_PINNING_KEY || '',
    timeout: 30000,
    retryOptions: {
      retries: 5,
      factor: 2,
      minTimeout: 1000,
      maxTimeout: 15000,
      randomize: true
    }
  },
  logging: {
    level: process.env.LOG_LEVEL || 'info',
    console: true,
    file: false
  },
  temp: {
    dir: process.env.TEMP_DIR || './tmp'
  }
};

Environment Variables

The following environment variables are automatically recognized:

Variable Description Default
IPFS_PINNING_KEY Pinata API key for IPFS pinning ''
LOG_LEVEL Logging level 'info'
TEMP_DIR Temporary directory for file operations './tmp'

Configuration Merging

Configuration objects are deeply merged with defaults:

const { createClient } = require('@verdikta/common');

const client = createClient({
  ipfs: {
    timeout: 60000,  // Override timeout
    // Other IPFS settings remain default
  },
  logging: {
    level: 'debug'   // Override log level
    // console: true remains default
  }
});

IPFS Configuration Options

Gateway Settings

const ipfsConfig = {
  gateway: 'https://cloudflare-ipfs.com',
  pinningService: 'https://api.pinata.cloud',
  pinningKey: 'your-api-key'
};

Retry Configuration

const retryConfig = {
  retries: 10,          // Maximum retry attempts
  factor: 2,            // Exponential backoff factor
  minTimeout: 1000,     // Minimum delay between retries (ms)
  maxTimeout: 30000,    // Maximum delay between retries (ms)
  randomize: true       // Add randomness to delays
};

Logging Configuration

Console Logging

const loggingConfig = {
  level: 'debug',       // debug | info | warn | error
  console: true,        // Enable console output
  file: false          // Disable file output
};

File Logging

const loggingConfig = {
  level: 'info',
  console: false,       // Disable console output
  file: true,          // Enable file output
  filename: '/var/log/verdikta-common.log'
};

Combined Logging

const loggingConfig = {
  level: 'warn',
  console: true,        // Log to console
  file: true,          // Also log to file
  filename: './app.log'
};

Temporary Directory Configuration

const tempConfig = {
  dir: '/tmp/verdikta-processing'  // Custom temp directory
};

Error Classes

The library defines custom error classes for different failure scenarios.

ValidationError

Thrown when schema validation fails.

const { ValidationError } = require('@verdikta/common');

class ValidationError extends Error {
  constructor(message, details) {
    super(message);
    this.name = 'ValidationError';
    this.details = details;  // Object with field-specific errors
  }
}

Usage:

try {
  await validator.validateManifest(invalidManifest);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.details);
    // error.details contains field-specific error messages
  }
}

IPFSError

Thrown when IPFS operations fail.

const { IPFSError } = require('@verdikta/common');

class IPFSError extends Error {
  constructor(message, cid, statusCode) {
    super(message);
    this.name = 'IPFSError';
    this.cid = cid;           // The CID that failed
    this.statusCode = statusCode;  // HTTP status code if applicable
  }
}

Usage:

try {
  const content = await ipfsClient.fetchFromIPFS('QmInvalidCID');
} catch (error) {
  if (error instanceof IPFSError) {
    console.error(`IPFS fetch failed for ${error.cid}: ${error.message}`);
    console.error('Status code:', error.statusCode);
  }
}

ArchiveError

Thrown when archive processing fails.

const { ArchiveError } = require('@verdikta/common');

class ArchiveError extends Error {
  constructor(message, archivePath, cause) {
    super(message);
    this.name = 'ArchiveError';
    this.archivePath = archivePath;  // Path that failed
    this.cause = cause;              // Original error if any
  }
}

Usage:

try {
  const extracted = await archiveService.extractArchive(data, './temp');
} catch (error) {
  if (error instanceof ArchiveError) {
    console.error(`Archive extraction failed at ${error.archivePath}`);
    console.error('Original error:', error.cause);
  }
}

ConfigurationError

Thrown when configuration is invalid.

const { ConfigurationError } = require('@verdikta/common');

class ConfigurationError extends Error {
  constructor(message, configPath) {
    super(message);
    this.name = 'ConfigurationError';
    this.configPath = configPath;  // Config field that failed
  }
}

Usage:

try {
  const client = createClient(invalidConfig);
} catch (error) {
  if (error instanceof ConfigurationError) {
    console.error(`Configuration error in ${error.configPath}: ${error.message}`);
  }
}

NetworkError

Thrown when network operations fail.

const { NetworkError } = require('@verdikta/common');

class NetworkError extends Error {
  constructor(message, url, statusCode) {
    super(message);
    this.name = 'NetworkError';
    this.url = url;                  // URL that failed
    this.statusCode = statusCode;    // HTTP status code
  }
}

Usage:

try {
  const response = await fetch(url);
} catch (error) {
  if (error instanceof NetworkError) {
    console.error(`Network request failed for ${error.url}`);
    console.error('Status:', error.statusCode);
  }
}


Helper Functions

mergeConfig(defaultConfig, userConfig)

Deeply merge configuration objects.

const { mergeConfig } = require('@verdikta/common');

const merged = mergeConfig(defaultConfig, userConfig);

validateCID(cid)

Validate IPFS Content Identifier format.

const { validateCID } = require('@verdikta/common');

const isValid = validateCID('QmYourCIDHere');
// Returns: boolean

sanitizeFilename(filename)

Sanitize filenames for safe filesystem operations.

const { sanitizeFilename } = require('@verdikta/common');

const safe = sanitizeFilename('unsafe/file..name');
// Returns: 'unsafe_file_name'

createTempDir(prefix)

Create a temporary directory with optional prefix.

const { createTempDir } = require('@verdikta/common');

const tempPath = await createTempDir('verdikta-');
// Returns: '/tmp/verdikta-abc123'

ensureDirectory(path)

Ensure a directory exists, creating it if necessary.

const { ensureDirectory } = require('@verdikta/common');

await ensureDirectory('./some/nested/path');

Constants

Supported File Types

const { SUPPORTED_FILE_TYPES } = require('@verdikta/common');

console.log(SUPPORTED_FILE_TYPES);
// Output:
{
  images: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
  documents: ['text/plain', 'application/pdf', 'application/rtf'],
  data: ['text/csv', 'application/json', 'text/markdown'],
  archives: ['application/zip', 'application/x-tar', 'application/gzip']
}

Default Retry Options

const { DEFAULT_RETRY_OPTIONS } = require('@verdikta/common');

console.log(DEFAULT_RETRY_OPTIONS);
// Output:
{
  retries: 5,
  factor: 2,
  minTimeout: 1000,
  maxTimeout: 15000,
  randomize: true
}

IPFS Gateways

const { IPFS_GATEWAYS } = require('@verdikta/common');

console.log(IPFS_GATEWAYS);
// Output:
[
  'https://ipfs.io',
  'https://cloudflare-ipfs.com',
  'https://gateway.pinata.cloud',
  'https://dweb.link'
]

Performance Utilities

measureTime(operation)

Measure execution time of async operations.

const { measureTime } = require('@verdikta/common');

const { result, duration } = await measureTime(async () => {
  return await someExpensiveOperation();
});

console.log(`Operation took ${duration}ms`);

rateLimitedFunction(fn, maxCalls, timeWindow)

Create a rate-limited version of a function.

const { rateLimitedFunction } = require('@verdikta/common');

const limitedFetch = rateLimitedFunction(
  fetchFromIPFS,
  10,      // Max 10 calls
  60000    // Per 60 seconds
);

cacheFunction(fn, ttl)

Create a cached version of a function.

const { cacheFunction } = require('@verdikta/common');

const cachedParser = cacheFunction(parseManifest, 300000); // 5 minute cache

Development Utilities

enableDebugMode()

Enable detailed debug logging and additional error information.

const { enableDebugMode } = require('@verdikta/common');

enableDebugMode();
// Now all operations will have detailed debug output

getSystemInfo()

Get system information for debugging.

const { getSystemInfo } = require('@verdikta/common');

const info = getSystemInfo();
console.log(info);
// Output:
{
  node: '18.17.0',
  platform: 'darwin',
  arch: 'x64',
  memory: { total: 16777216, free: 8388608 },
  versions: { ... }
}

validateEnvironment()

Validate that the environment meets requirements.

const { validateEnvironment } = require('@verdikta/common');

const issues = validateEnvironment();
if (issues.length > 0) {
  console.error('Environment issues:', issues);
}

These utilities provide additional functionality for configuration management, error handling, and development support. For usage examples, see the Examples documentation.