v1 to v2
2.0.0
Applies to: Upgrading from any v1.x version (1.0.0 - 1.x.x)
This is a major version release with significant architectural improvements, new builder patterns, and enhanced modularity.
🎯 Quick Summary
Should I upgrade? Yes! v2.x brings powerful new features like DateBuilder and UrlBuilder, better tree-shaking, and performance improvements.
Breaking changes? Minimal. Mostly type renames and import pattern improvements. Most existing code remains compatible.
Estimated migration time: 15-30 minutes for typical projects.
What's New:
- 🎯 New
DateBuilderandUrlBuilderfluent APIs for elegant date/URL manipulation - 📦 Better tree-shaking support with modular imports
- 🔒 Enhanced crypto utilities with secure random functions
- ⚡ 30+ new array utility functions with optimized algorithms
- 🛡️ Improved type safety and error handling across all modules
⚠️ BREAKING CHANGES
Module Structure Reorganization
-
Migrated from monolithic utils to modular submodules (optional)
// Old (v1.x)
import { formatDate } from '@catbee/utils';
// New (v2.x) - Option 1: Module-level import (tree-shakable)
import { formatDate } from '@catbee/utils/date';
// or Option 2: Root-level import (convenient)
import { formatDate } from '@catbee/utils';
Import Pattern Changes
- New flexible import patterns
- Root-level imports:
import { ... } from '@catbee/utils'- Access everything - Module-level imports:
import { ... } from '@catbee/utils/date'- Scoped to specific modules - Both patterns are tree-shakable and fully supported
- Root-level imports:
Server Type Interface Renames
-
ServerConfig->CatbeeServerConfigimport type { ServerConfig } from '@catbee/utils';
import type { CatbeeServerConfig } from '@catbee/utils/types'; -
ServerHooks->CatbeeServerHooksimport type { ServerHooks } from '@catbee/utils';
import type { CatbeeServerHooks } from '@catbee/utils/types';
Config Module Changes
-
New server configuration types
- Added
GlobalServerAddonsinterface for additional server options - Added
CatbeeGlobalServerConfigtype combiningCatbeeServerConfig&GlobalServerAddons
// New (v2.x)
interface GlobalServerAddons {
skipHealthzChecksValidation: boolean;
}
type CatbeeGlobalServerConfig = CatbeeServerConfig & GlobalServerAddons; - Added
-
Server global config property renamed:
skipHealthz->skipHealthzChecksValidation// Old (v1.x)
interface ServerConfig {
skipHealthz: boolean; // Was part of main config
}
// New (v2.x) - Moved to GlobalServerAddons
interface GlobalServerAddons {
skipHealthzChecksValidation: boolean;
}
// Use the combined type
type CatbeeGlobalServerConfig = CatbeeServerConfig & GlobalServerAddons; -
Server global config: Now you can set all server config options using
setCatbeeGlobalConfig()orsetCatbeeServerGlobalConfig()import { setCatbeeGlobalConfig, setCatbeeServerGlobalConfig } from '@catbee/utils/config';
// Option 1: Set full global config
setCatbeeGlobalConfig({
server: {
port: 4000,
cors: true,
skipHealthzChecksValidation: true
}
});
// Option 2: Set only server config
setCatbeeServerGlobalConfig({
port: 4000,
cors: true,
skipHealthzChecksValidation: true
}); -
Environment variable renamed
SERVER_SKIP_HEALTHZ=true
SERVER_SKIP_HEALTHZ_CHECKS_VALIDATION=true
Validation API Changes
-
isURL()signature changed - Now accepts allowed protocols parameter// code-block-diff-red
isURL(str: string): boolean
// code-block-diff-green
isURL(str: string, allowedProtocols: string[] = ['http', 'https', 'ws', 'wss']): boolean- Impact: If you were calling
isURL()with a single argument, it remains compatible - New optional parameter allows protocol validation
- Impact: If you were calling
Env Utilities Changes
-
Cache visibility changed:
class Env {
private static cache: Map<string, any> = new Map();
private static readonly cache: Map<string, any> = new Map();
}- Internal implementation change for better immutability
- No API impact but if you were extending the
Envclass, this may affect you
-
Added new dependencies:
Envnow depends on:parseDurationfrom@catbee/utils/dateisEmailfrom@catbee/utils/validation
✅ Migration Checklist
| Task | Status | Impact |
|---|---|---|
Replace ServerConfig with CatbeeServerConfig | Required if used | 🔴 |
Replace ServerHooks with CatbeeServerHooks | Required if used | 🔴 |
Update healthz property skipHealthz → skipHealthzChecksValidation | Required if used | 🔴 |
Update env var SERVER_SKIP_HEALTHZ → SERVER_SKIP_HEALTHZ_CHECKS_VALIDATION | Required if used | 🔴 |
Update config accessors getConfig/setConfig → getCatbeeGlobalConfig/setCatbeeGlobalConfig | Optional (deprecated) | 🟡 |
Update logger addRedactFields() → addSensitiveFields() | Optional (deprecated) | 🟡 |
Use DateBuilder and UrlBuilder where applicable | New recommended pattern | 🟢 |
Update isURL() calls to include allowed protocols if needed | Optional | 🟢 |
- 🔴 High Impact: Must fix immediately - will cause runtime errors or type errors
- 🟡 Medium Impact: Should fix soon - deprecated but still works (will be removed in v3.0.0)
- 🟢 Low Impact: Nice to have - enhances your codebase but not required
📦 Deprecations
The following functions/methods are deprecated and will be removed in v3.0.0:
Config Module (@catbee/utils/config)
-
getConfig()-> UsegetCatbeeGlobalConfig()insteadimport { getConfig } from '@catbee/utils';
const config = getConfig();
import { getCatbeeGlobalConfig } from '@catbee/utils/config';
const config = getCatbeeGlobalConfig(); -
setConfig()-> UsesetCatbeeGlobalConfig()insteadimport { setConfig } from '@catbee/utils';
setConfig({ server: { port: 4000 } });
import { setCatbeeGlobalConfig } from '@catbee/utils/config';
setCatbeeGlobalConfig({ server: { port: 4000 } });
Logger Module (@catbee/utils/logger)
-
addRedactFields()-> UseaddSensitiveFields()insteadimport { addRedactFields } from '@catbee/utils';
addRedactFields(['ssn', 'creditCard']);
import { addSensitiveFields } from '@catbee/utils/logger';
addSensitiveFields(['ssn', 'creditCard']);
Note: All deprecated functions are still available in v2.x but will display deprecation warnings. They will be removed in v3.0.0.
🐛 Bug Fixes & Improvements
- Enhanced type safety: Improved type definitions across all modules
- Better error handling: More robust error messages and validation
- Performance optimizations: Improved algorithm efficiency in array and object utilities
- Code quality: Reduced complexity and improved maintainability
✨ New Features
getCatbeeServerGlobalConfig and setCatbeeServerGlobalConfig Functions
Added new functions to get and set global server configuration:
import { getCatbeeServerGlobalConfig, setCatbeeServerGlobalConfig } from '@catbee/utils/config';
// Get current global server config
const currentConfig = getCatbeeServerGlobalConfig();
// Update global server config
setCatbeeServerGlobalConfig({ port: 8080, cors: true });
or
import { getCatbeeGlobalConfig, setCatbeeGlobalConfig } from '@catbee/utils/config';
// Get current global config
const currentConfig = getCatbeeGlobalConfig();
// Update global config
setCatbeeGlobalConfig({ server: { port: 8080, cors: true } });
🗓️ DateBuilder Class
Added a comprehensive fluent API for date manipulation similar to Java's date builders:
import { DateBuilder } from '@catbee/utils/date';
// Create dates with fluent API
const date = new DateBuilder()
.year(2024)
.month(5)
.day(15)
.hour(14)
.minute(30)
.build();
// Chain operations
const nextWeek = DateBuilder.now()
.addDays(7)
.startOfDay()
.build();
// Manipulate existing dates
const modified = DateBuilder.from(new Date())
.addMonths(2)
.endOfMonth()
.format('yyyy-MM-dd');
Key Features:
- Factory methods:
now(),from(),of(),parse(),fromDuration() - Setters:
year(),month(),day(),hour(),minute(),second(),millisecond() - Addition/subtraction:
addYears(),addMonths(),addDays(),subtractYears(), etc. - Start/end of period:
startOfDay(),startOfWeek(),endOfMonth(),endOfYear(), etc. - Comparisons:
isBefore(),isAfter(),isSame(),isBetween(),isToday(),isFuture(),isPast(),isWeekend(),isLeapYear() - Formatting:
format(),formatRelative(),toISOString(),toUTCString(), etc. - Immutable: All methods return new instances
For more details, see the DateBuilder documentation.
🔗 UrlBuilder Class
Added a comprehensive fluent API for URL construction and manipulation:
import { UrlBuilder } from '@catbee/utils/url';
// Build URLs from scratch
const url = new UrlBuilder()
.https()
.host('api.example.com')
.port(8080)
.appendPath('v1', 'users', '123')
.queryParam('page', 1)
.queryParam('limit', 10)
.hash('profile')
.build();
// Modify existing URLs
const modified = UrlBuilder.from('https://example.com/old')
.path('/new')
.addQueryParams({ active: true, sort: 'name' })
.toString();
Key Features:
- Factory methods:
from(),http(),https() - Protocol:
protocol(),http(),https() - Host/Domain:
host(),hostname(),port(),subdomain(),removePort() - Path:
path(),appendPath(),prependPath(),replacePathSegment() - Query params:
queryParam(),addQueryParams(),setQueryParams(),removeQueryParam(),clearQueryParams(),appendQueryParam() - Hash:
hash(),removeHash() - Authentication:
username(),password(),auth(),removeAuth() - Validation:
isValid(),isHttps(),isHttp(),hasQueryParam(),hasHash(),hasAuth() - Transformation:
normalize(),sanitize(),lowercaseHost() - Immutable: All methods return new instances
For more details, see the UrlBuilder documentation.
🔧 Improvements
Array Utilities (@catbee/utils/array)
- Complete rewrite with 30+ utility functions including:
- Chunking & Grouping:
chunk(),groupBy(),chunkBy(),partition() - Uniqueness:
unique()with optional key function - Array Operations:
flattenDeep(),shuffle(),zip(),compact(),toggle() - Selection:
take(),takeWhile(),drop(),dropWhile(),random(),pluck() - Set Operations:
difference(),intersect(),remove() - Searching:
findLast(),findLastIndex(),headOfArr(),lastOfArr() - Sorting & Analysis:
mergeSort(),isSorted(),maxBy(),minBy() - Analysis:
countBy() - Utilities:
range(),secureIndex()(cryptographically secure random index)
- Chunking & Grouping:
- Enhanced performance with optimized algorithms
- Comprehensive type safety with proper TypeScript generics
Async Utilities
- Improved promise helpers and concurrency utilities
- Better error handling for async operations
Crypto Utilities (@catbee/utils/crypto)
- New secure random functions:
generateNonce()- Generate cryptographically secure nonces with configurable encodingsecureRandomInt()- Generate secure random integers within a range
- Enhanced hashing and encryption utilities
- Improved token generation functions
- Better cryptographic security with secure random number generation
Date Utilities (@catbee/utils/date)
-
New date check functions:
isWeekend()- Check if a date falls on weekendisToday()- Check if a date is todayisFuture()- Check if a date is in the futureisPast()- Check if a date is in the past
-
New date manipulation functions:
addDays()- Add days to a dateaddMonths()- Add months to a dateaddYears()- Add years to a datequarterOf()- Get the quarter of a date (1-4)weekOfYear()- Get the ISO week number of a date
-
Duration utilities:
formatDuration()- Convert milliseconds to human-readable format (e.g., "2h 30m 15s")parseDuration()- Parse duration strings to milliseconds (e.g., "2h" -> 7200000)getDateFromDuration()- Create date from duration string
-
Added date constants for common operations
-
Enhanced existing date formatting and manipulation functions
-
Better timezone handling
-
Improved date parsing with fallback support
Environment Utilities
- Improved environment variable parsing
- Better type safety for environment configurations
File System Utilities (@catbee/utils/fs)
- Complete rewrite with comprehensive file operations:
- File operations:
readFile(),readFileSync(),writeFile(),safeReadFile(),deleteFile() - JSON operations:
readJSON(),readJSONOrDefault(),writeJSON() - Directory operations:
ensureDir(),pathExists() - Path utilities:
getFileExtension(),changeFileExtension(),getFileNameWithoutExt() - Validation:
isReadableFile(),isWritableFile()
- File operations:
- Better error handling with safe read/write operations
- Support for both async and sync operations
- Type-safe JSON reading and writing
Object Utilities (@catbee/utils/object)
- Enhanced
deepClone()function with comprehensive type support:- Added DataView cloning support with proper buffer handling
- Simplified TypedArray cloning (Int8Array, Uint8Array, Float32Array, etc.)
- Added accessor descriptor preservation (getters/setters)
- Maintains property descriptors (writable, enumerable, configurable)
- Improved circular reference handling with WeakMap
- Preserves object prototypes correctly
- Improved
deepObjMerge():- Better circular reference detection and handling
- Enhanced support for special objects (Date, Map, Set, RegExp, ArrayBuffer)
- Prototype preservation during merge operations
- More efficient cloning using improved deepClone
- Enhanced object manipulation:
- All utility functions now handle edge cases better
- Improved type safety across all functions
- Better null/undefined handling
Server Utilities (@catbee/utils/server)
- Enhanced dependency error messages -
DependencyErrorsobject with helpful install commands - Improved error handling and messaging
- Better type safety for server configuration
Stream Utilities
- Improved stream conversion and manipulation
- Better error handling for stream operations
String Utilities (@catbee/utils/string)
- New string functions:
escapeRegex()- Escape special regex characters in stringsunescapeHtml()- Unescape HTML entities to plain textisBlank()- Check if string is empty or whitespace-onlyellipsis()- Truncate strings with customizable suffix
- Enhanced string formatting and manipulation
- Better Unicode support
- Improved string validation and sanitization
Type Utilities (@catbee/utils/type)
- New type checking functions:
isIterable()- Check if a value is iterableisAsyncIterable()- Check if a value is async iterableassertType()- Assert value matches expected type with runtime validation
- Improved type checking and conversion
- Better type guards and validation
- Enhanced type safety with assertion utilities
URL Utilities (@catbee/utils/url)
- New URL manipulation functions:
updateQueryParam()- Update a single query parameter in a URLgetSubdomain()- Extract subdomain from a URLisRelativeUrl()- Check if URL is relativetoAbsoluteUrl()- Convert relative URL to absolute with base URLsanitizeUrl()- Sanitize URLs with protocol validation
- Enhanced URL parsing and manipulation
- Better URL validation and security
- Improved query string handling
Validation Utilities (@catbee/utils/validation)
- Enhanced input validation functions
- Better error messages
- Improved validation for various data types
⚠️ Common Pitfalls
Mixing old and new config functions
Problem: Using both deprecated and new config functions in the same project can cause inconsistent state.
// ❌ Don't mix old and new
import { setConfig } from '@catbee/utils';
import { setCatbeeGlobalConfig } from '@catbee/utils/config';
setConfig({ server: { port: 3000 } }); // Deprecated
setCatbeeGlobalConfig({ server: { port: 4000 } }); // New
Solution: Use only the new functions consistently:
// ✅ Use new functions only
import { setCatbeeGlobalConfig } from '@catbee/utils/config';
setCatbeeGlobalConfig({ server: { port: 4000 } });
Type errors not caught during migration
Problem: If you use any or @ts-ignore, TypeScript won't catch renamed types.
// ❌ Bad - type error hidden
import { ServerConfigBuilder } from '@catbee/utils';
const config: any = new ServerConfigBuilder().build();
Solution: Use proper types:
// ✅ Good - proper type checking
import { ServerConfigBuilder } from '@catbee/utils/server';
import type { CatbeeServerConfig } from '@catbee/utils/types';
const config: CatbeeServerConfig = new ServerConfigBuilder().build();
Forgetting to update environment variables
Problem: Renaming environment variables requires updates in multiple places.
Files to check:
.env.env.example.env.production- CI/CD configs (GitHub Actions, GitLab CI, etc.)
- Docker files
- Kubernetes configs
- Deployment documentation
# .env
- SERVER_SKIP_HEALTHZ=true
+ SERVER_SKIP_HEALTHZ_CHECKS_VALIDATION=true
Not taking advantage of new features
Problem: Missing out on powerful new utilities like DateBuilder and UrlBuilder.
Before (manual date manipulation):
const date = new Date();
date.setDate(date.getDate() + 7);
date.setHours(0, 0, 0, 0);
After (using DateBuilder):
const date = DateBuilder.now().addDays(7).startOfDay().build();
Tip: Review the New Features section and consider refactoring to use new utilities where appropriate.
Tree-shaking not working as expected
Problem: Still importing from root when modular imports would be better for bundle size.
// ⚠️ Works but imports more than needed
import { formatDate, capitalize, deepClone } from '@catbee/utils';
Better for tree-shaking:
// ✅ More explicit, better tree-shaking
import { formatDate } from '@catbee/utils/date';
import { capitalize } from '@catbee/utils/string';
import { deepClone } from '@catbee/utils/object';
Note: Both patterns work in v2.x, but modular imports can result in smaller bundles.
🎉 Thank You
Thank you for updating to v2.x! For any questions or issues, please visit our GitHub Discussions.
Additional Resources: