@dc41/core-services
v0.0.701
Published
Independent core modules for React Native applications
Maintainers
Readme
@dc41/core-services
A comprehensive, independent core services library for React Native applications. This package provides essential utilities with zero external dependencies required - each module works standalone with built-in fallback implementations.
📦 Installation
npm install @dc41/core-services
# or
yarn add @dc41/core-services🚀 Quick Start
import {
defaultLogger,
storage,
secureStorage,
httpService,
queryClient,
GlobalEventBus
} from '@dc41/core-services';
// Start using immediately - no configuration needed!
defaultLogger('App initialized');📚 Available Modules
1. Logger
Independent logging system with timestamps and environment-aware output.
Features:
- Timestamp formatting with timezone
- Environment-aware logging (development/production)
- Configurable prefixes
- No external dependencies
Usage:
import { createLogger, defaultLogger } from '@dc41/core-services';
// Use default logger
defaultLogger('Application started');
defaultLogger('User action', { userId: 123, action: 'login' });
// Create custom logger
const logger = createLogger({
enabled: true,
prefix: 'MY_APP'
});
logger('Custom event', { data: 'value' });Output Format:
[CORE][2026-03-04 17:14:45.123 (GMT+7)] Application started
[MY_APP][2026-03-04 17:14:45.124 (GMT+7)] Custom event { data: 'value' }2. Storage
Cross-platform key-value storage with automatic JSON serialization.
Features:
- AsyncStorage support (when available)
- In-memory fallback (always works)
- Type-safe operations
- Automatic JSON serialization/deserialization
Usage:
import { storage } from '@dc41/core-services';
// Store data
await storage.set('user', { name: 'John', age: 30 });
await storage.set('settings', { theme: 'dark', notifications: true });
// Retrieve data
const user = await storage.get<{ name: string; age: number }>('user');
console.log(user?.name); // 'John'
// Remove data
await storage.remove('user');
// Clear all data
await storage.removeAllData();Type Safety:
interface User {
id: string;
name: string;
email: string;
}
// Type-safe storage operations
await storage.set<User>('currentUser', userData);
const user = await storage.get<User>('currentUser');3. Secure Storage
Secure storage with biometric authentication support.
Features:
- Keychain/Keystore support (when available)
- In-memory fallback for development
- Biometric authentication integration
- Secure data handling
Usage:
import { secureStorage } from '@dc41/core-services';
// Store sensitive data
await secureStorage.set('authToken', 'eyJhbGciOiJIUzI1NiIs...');
await secureStorage.set('refreshToken', 'refresh_token_here');
// Store with biometric protection
await secureStorage.set('secureKey', 'sensitive-data', {
requiresBiometric: true,
authPrompt: 'Authenticate to access secure data'
});
// Retrieve data
const token = await secureStorage.get<string>('authToken');
// Retrieve with biometric verification
const secureData = await secureStorage.get<string>('secureKey', {
requiresBiometric: true,
authPrompt: 'Verify your identity'
});
// Remove data
await secureStorage.remove('authToken');
// Clear all secure data
await secureStorage.removeAll();4. HTTP Service
HTTP client with fetch fallback and optional Axios support.
Features:
- Fetch API support (always available)
- Axios support (when available)
- Request/response interceptors
- Timeout support
- Error handling
Usage:
import { httpService } from '@dc41/core-services';
// GET request
const users = await httpService.request<User[]>({
method: 'GET',
url: '/api/users',
headers: {
'Authorization': 'Bearer token'
}
});
// POST request
const newUser = await httpService.request<User>({
method: 'POST',
url: '/api/users',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]'
})
});
// With timeout
const response = await httpService.request<Data>({
method: 'GET',
url: '/api/data',
timeout: 5000 // 5 seconds
});Custom HTTP Service:
import { FetchHttpService, AxiosHttpService } from '@dc41/core-services';
// Use Fetch implementation explicitly
const fetchService = new FetchHttpService();
// Use Axios implementation (if axios is installed)
const axiosService = new AxiosHttpService();5. Query Client
Lightweight query client with caching and stale data handling.
Features:
- In-memory caching
- Stale data management
- Query invalidation
- Development logging
- No external dependencies
Usage:
import { queryClient } from '@dc41/core-services';
// Set query data
queryClient.setQueryData('users', [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]);
// Get query data
const users = queryClient.getQueryData<User[]>('users');
// Invalidate queries (marks as stale)
queryClient.invalidateQueries('users');
// Log query tree (development)
import { logTree } from '@dc41/core-services';
logTree(); // Shows all cached queriesWith React Query Integration:
import { QueryClient } from '@dc41/core-services';
// Create custom query client
const customQueryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes
cacheTime: 10 * 60 * 1000, // 10 minutes
}
}
});6. Event System
Type-safe event emitter for module communication.
Features:
- Type-safe events
- Event registration and cleanup
- Development logging
- No external dependencies
Usage:
import { GlobalEventBus } from '@dc41/core-services';
// Define event types
interface AppEvents {
'user:login': { userId: string; timestamp: number };
'user:logout': { reason: string };
'app:ready': undefined;
}
// Listen to events
const unsubscribe = GlobalEventBus.on('user:login', (data) => {
console.log('User logged in:', data.userId);
});
// Emit events
GlobalEventBus.emit('user:login', {
userId: '123',
timestamp: Date.now()
});
// Cleanup
unsubscribe();
// Remove all listeners
GlobalEventBus.off('user:login');7. Theme System
Comprehensive theming solution for React Native apps.
Features:
- Light/Dark mode support
- Responsive design tokens
- Component-level theming
- TypeScript support
Usage:
import { ThemeProvider, useTheme } from '@dc41/core-services';
// Wrap your app
function App() {
return (
<ThemeProvider>
<YourApp />
</ThemeProvider>
);
}
// Use in components
function MyComponent() {
const { theme, isDark, toggleTheme } = useTheme();
return (
<View style={{ backgroundColor: theme.colors.background }}>
<Text style={{ color: theme.colors.text }}>
Hello World
</Text>
<Button onPress={toggleTheme}>
Toggle Theme
</Button>
</View>
);
}Theme Configuration:
import { createThemeConfig } from '@dc41/core-services';
const customTheme = createThemeConfig({
light: {
colors: {
primary: '#007AFF',
background: '#FFFFFF',
text: '#000000'
}
},
dark: {
colors: {
primary: '#0A84FF',
background: '#000000',
text: '#FFFFFF'
}
}
});8. Dependencies Logger
Advanced logging and tracking for dependency operations.
Features:
- Singleton pattern
- Operation tracking
- Storage monitoring
- Development warnings
Usage:
import {
DependenciesLogger,
defaultStorage,
defaultSecureStorage,
defaultStateStore
} from '@dc41/core-services';
// Get logger instance
const logger = DependenciesLogger.getInstance();
// Enable logging (auto-enabled in development)
logger.enable();
// Basic logging
logger.info('Operation started', { operation: 'fetch' });
logger.warn('Low memory warning');
logger.error('Operation failed', { error: 'Network timeout' });
// Track storage operations
await defaultStorage.set('key', 'value');
// Automatically logs: [DEPENDENCIES] Storage set { key: 'key', success: true }
// Track secure storage
await defaultSecureStorage.set('token', 'secret', {
requiresBiometric: true
});
// Logs biometric warning in development
// Track state operations
const state = defaultStateStore.create({ count: 0 });
state.set({ count: 1 });
// Logs state changes
// Get all logs
const logs = logger.getLogs();
// Clear logs
logger.clearLogs();
// Disable logging
logger.disable();9. App Configuration
Centralized application configuration management.
Usage:
import { appConfig } from '@dc41/core-services';
// Access configuration
console.log(appConfig.api.baseUrl);
console.log(appConfig.features.darkMode);🔧 Advanced Usage
Custom Storage Implementation
import { IStorage } from '@dc41/core-services';
class EncryptedStorage implements IStorage {
async set<T>(key: string, data: T): Promise<boolean> {
const encrypted = encrypt(JSON.stringify(data));
// Store encrypted data
return true;
}
async get<T>(key: string): Promise<T | null> {
const encrypted = await retrieveData(key);
if (!encrypted) return null;
return JSON.parse(decrypt(encrypted)) as T;
}
async remove(key: string): Promise<boolean> {
// Remove data
return true;
}
async removeAllData(): Promise<boolean> {
// Clear all data
return true;
}
}Custom HTTP Interceptor
import { httpService } from '@dc41/core-services';
// Add request interceptor
const originalRequest = httpService.request.bind(httpService);
httpService.request = async (config) => {
// Add auth token
const token = await secureStorage.get('authToken');
if (token) {
config.headers = {
...config.headers,
'Authorization': `Bearer ${token}`
};
}
// Call original request
return originalRequest(config);
};Event-Driven Architecture
import { GlobalEventBus } from '@dc41/core-services';
// Analytics service
GlobalEventBus.on('user:login', (data) => {
analytics.track('user_login', data);
});
// Notification service
GlobalEventBus.on('user:login', (data) => {
notifications.scheduleWelcome(data.userId);
});
// Cache service
GlobalEventBus.on('user:logout', () => {
queryClient.invalidateQueries('user');
storage.remove('userData');
});🧪 Testing Infrastructure
The core package uses a standalone Vitest testing environment. This allows for near-instant feedback when testing business logic without needing the full React Native runtime or the main application setup.
Standalone Philosophy
- Isolated Mocks: Essential native modules (
react-native,async-storage,keychain) are mocked within thecorepackage's__tests__/mocksdirectory. - Fast Execution: Uses JSDOM and Vitest for sub-second test execution.
- Zero App Dependency: Core tests do not require the root
node_modulesor configuration.
Running Tests
All commands should be run from within the core/ directory:
# Run all tests once
npm test
# Run tests in watch mode for development
npm run test:watch
# Generate coverage reports
npm run test:coverageAdding New Tests
- Place your test files alongside the source code using the
*.test.tsnaming convention. - For shared mocks of external dependencies, add them to
core/__tests__/mocks/. - Use the global
viobject for Vitest-specific mocking and spying.
🧪 Testing
# From the core/ directory:
npm test # Run vitest run
npm run test:watch # Run vitest (watch mode)
npm run test:coverage # Run vitest with coverage reporting📦 Building
# Build for production
npm run build
# Development mode with watch
npm run dev🔍 Module Exports
The package provides multiple entry points for tree-shaking:
// Main entry - imports everything
import { storage, httpService } from '@dc41/core-services';
// Individual modules
import { storage } from '@dc41/core-services/storage';
import { httpService } from '@dc41/core-services/http';
import { queryClient } from '@dc41/core-services/query';
import { GlobalEventBus } from '@dc41/core-services/events';🌍 Environment Compatibility
| Environment | Status | |-------------|--------| | React Native | ✅ Full support | | Web | ✅ Full support | | Node.js | ✅ Full support | | Expo | ✅ Full support |
📋 Peer Dependencies
All peer dependencies are optional. The package works without them using fallback implementations:
| Dependency | Required | Purpose |
|------------|----------|---------|
| react | Yes | Core React functionality |
| react-native | Yes | React Native environment |
| @react-native-async-storage/async-storage | No | Persistent storage |
| react-native-keychain | No | Secure storage |
| react-native-biometrics | No | Biometric authentication |
| @tanstack/react-query | No | Advanced query management |
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built with ❤️ for the React Native community
- Inspired by the need for zero-dependency core utilities
- Thanks to all contributors
**Made with ❤️ by Jeff
