v2.0.0 is a full TypeScript rewrite of monSQLize. The public API is preserved — existing v1 code requires only minor configuration adjustments to run on v2.
| Layer | Change |
|---|---|
| Source language | JavaScript → TypeScript (strict mode) |
| Cache engine | Internal implementation → cache-hub |
| Internal structure | Flat modules → capability layers + adapter bridge |
| Type declarations | Hand-maintained .d.ts → generated from source (single source of truth) |
SagaResult now exposes the runtime fields and the restored v1/v2 alias fields:
{
executionId: string; // primary v1 field
sagaId?: string; // v2 alias, optional for v1 fixtures
sagaName?: string;
success: boolean;
result?: unknown;
error?: Error;
errorMessage?: string;
completedSteps: string[];
completedStepCount?: number;
completedStepNames?: string[];
compensatedSteps: string[];
duration: number;
compensation?: { success: boolean; results: [...] };
}The internal transaction state still uses 'active', but Transaction#getInfo().status maps it back to 'started' for v1 callers. Public values are 'pending' | 'started' | 'committed' | 'aborted'.
// v1 — array
getPoolStats(): PoolStats[]
getPoolHealth(): PoolHealthStatus[]
// v2 — keyed by pool name
getPoolStats(): Record<string, PoolStats>
getPoolHealth(): Record<string, PoolHealthStatus>PoolStats now includes connections, available, waiting, and status fields that were absent in v1 type declarations (but present in the runtime).
// v1
getCache(): MemoryCache
// v2
getCache(): CacheLike // MemoryCache | MultiLevelCache | custom adapterThis is a widening: MemoryCache is still the default; the return type is broader to accommodate the two new cache modes.
const msq = new MonSQLize({
type: 'mongodb',
cache: {
multiLevel: true,
local: { maxEntries: 5000 },
remote: MonSQLize.createRedisCacheAdapter('redis://localhost:6379'),
policy: { writePolicy: 'local-first-async-remote', backfillLocalOnRemoteHit: true },
},
});Connect to MongoDB through a bastion host with no code changes required:
const msq = new MonSQLize({
type: 'mongodb',
config: {
uri: 'mongodb://mongo.internal:27017/mydb',
ssh: {
host: 'bastion.example.com',
username: 'deploy',
privateKeyPath: '~/.ssh/id_rsa',
},
},
});Historical v2.0.0 note: SSH tunneling originally expected ssh2 to be present separately. In current v2.0.2+ packages, ssh2 is installed with monsqlize.
Passing a custom CacheLike instance (e.g. a Redis adapter) directly as cache is now supported:
const msq = new MonSQLize({
type: 'mongodb',
cache: MonSQLize.createRedisCacheAdapter('redis://localhost:6379'),
});In v1 this silently fell back to a default MemoryCache. In v2 it is used directly.
health() now returns driver: { connected: boolean } alongside the existing fields.
findOneOnlyDeleted, countWithDeleted, countOnlyDeleted, insertBatch, updateBatch are now declared in the public type surface (they existed at runtime in v1 but were not typed).
| v1 option | v2 equivalent | Status |
|---|---|---|
cache.maxSize |
cache.maxEntries |
✅ auto-mapped |
cache.ttl |
cache.defaultTtl |
✅ auto-mapped |
cache.autoInvalidate |
cacheAutoInvalidate (top-level) |
✅ both accepted |
cache: CacheLike |
cache: CacheLike |
✅ pass-through |
cache: MultiLevelCacheOptions |
cache: { multiLevel: true, ... } |
✅ fully supported |
options.database |
options.databaseName |
✅ alias preserved |
SagaResult.sagaId |
SagaResult.sagaId + executionId alias |
✅ |
ctx.sagaId in Saga steps |
ctx.executionId + ctx.sagaId alias |
✅ alias preserved |
All public API surface now carries complete English JSDoc:
types/collection.d.ts— 49 Collection / DbAccessor / AdminAccessor methodstypes/model.d.ts— 44 ModelInstance methodstypes/monsqlize.d.ts— 43 MonSQLize interface methodstypes/lock.d.ts— Lock / LockManagertypes/saga.d.ts— SagaOrchestrator / SagaContext / SagaSteptypes/transaction.d.ts— Transaction / TransactionManager / CacheLockManagertypes/runtime.d.ts— MemoryCache / MultiLevelCache / FunctionCache
findAndCount: return value includesdocumentsas a backward-compat alias fordata({ data, total, documents })findOneById/findByIds:options.cachenow restores v1-style read-through TTL caching.- Runtime query defaults: built-in defaults now match v1 (
maxTimeMS=2000,findLimit=10,slowQueryMs=500,findPageMaxLimit=500). LockManagerTTL: explicit lock TTL values are no longer silently capped bymaxDuration.withCache(fn): default behavior now matches v1 (ttl=60000,namespace='fn',enableStats=true).adaptLegacyCacheLike: exported as both a named import andMonSQLize.adaptLegacyCacheLikeMultiLevelCache: exported as both a named import andMonSQLize.MultiLevelCache- Error messages:
createValidationErrordefault message参数校验失败;createCursorErrordefault游标无效 FunctionCache.defaultTTL: v1 optiondefaultTTLnow accepted as an alias forttl; v1 code usingnew FunctionCache(db, { defaultTTL: 60000 })works without changes- Read query meta wrapper:
find/findOne/count/aggregate/distinctnow restore the v1{ data, meta }result shape whenoptions.metais enabled. FunctionCachedefaults and stats:new FunctionCache()is supported, the default namespace is restored toaction, and stats includetotalTime/avgTime.- Batch writes:
insertBatch/deleteBatchretry defaults are restored to3attempts and1000ms;updateBatchnow supportsonError='retry',retryAttempts,retryDelay, andonRetry. - Model hooks: flat hooks support
beforeInsert/afterInsertaliases and now cover bulk/upsert/findOneAnd* write paths.
FindAndCountResult: includesdocuments?: TSchema[]optional backward-compat aliasSagaResult: includescompletedStepNames?: string[](ordered step names, v1 compat) anderrorCause?: unknownCachedFunction: exposesgetCacheStats()as a v1 shim overstats()- Query meta overloads: public collection types now expose
ResultWithMeta<T>overloads for meta-enabled read APIs. - Collection management methods: public collection types now declare
stats,renameCollection,collMod,convertToCapped, validator setters, andgetValidator. ModelInstancehelpers: public model types now declaregetRelations()andgetEnums().Model hooks:beforeInsert/afterInsertare declared as flat hook aliases.- Batch options: public batch option types now expose retry and progress options consistently.
- Workspace smooth-upgrade bridge: legacy-wide
Model/Collectionpublic contracts accept v1 consumer fixture shapes without source changes, including object schema definitions,validate:trueoperation overrides,validate()response data, array-formpopulate(), document-levelpopulate(), Transaction stats, Saga metadata/return contracts, FunctionCache registration, Mongo connection aliases, package metadata exports, sync transform overloads, top-levelFindPageOptions.comment, and optional v2-only counter aliases. - Root and static export parity: ESM named exports and default
MonSQLizestatics are aligned with the CJS surface, including advanced capabilities and package metadata. - Remaining v1 operation contracts:
MonSQLize#scopedCollection()pool scoping,ConnectionPoolManager#selectPool()string operations, chainableModelDocument#populate(), synchronouslistSagas(), and requiredSagaResult.compensatedStepsare restored for v1-compatible consumers. - Collection
find()overload: the v1 three-argumentfind(query, projection, options)form is restored at runtime and in public types. - Redis adapter errors: legacy invalid-argument and missing-
ioredismessages are preserved while keeping structured monSQLize error codes.
- Verified zero-business-code upgrade paths for workspace consumers
chat,payment,user,admin,search,vext, andpermission-coreby overlaying only the local monSQLize package candidate and running each service's TypeScript/test gate. - Additional workspace declarations were classified in
requirements/平滑升级支持/06-工作区依赖覆盖矩阵.md; historical/spec assets and credential-bearing scripts are static-only exclusions from the default release gate until they are sanitized.
src/entry/runtime-core.tsreduced from 852 to 769 lines; cache normalizer extracted toruntime-cache-normalizer.tsnode --test --test-concurrency=1applied to all integration test scripts to prevent parallel mongod startup hangs on WindowswithCache()performance validation ledgers now align with the current benchmark source and document that v1 transaction benchmarks are not directly comparable to the v2 function-cache hot-path baseline.- The transaction/cache-lock unit test was stabilized, and release preflight now runs the default
npm testgate before pack dry-run. - Runtime dependency
schema-dslnow follows npmlatestTypeScript line^2.0.3; deprecated mistake releases in the2.3.xrange are explicitly excluded from the upgrade target. - Project licensing is now Apache-2.0, and the package README is published in English for npm and GitHub users.
- npm package artifacts are limited to runtime CJS / ESM bundles, public
.d.tsdeclarations, and release documentation. Source maps are disabled by default and excluded from the package boundary even when generated locally. - GitHub Actions publish flow now runs
release:preflightonce beforenpm publish --ignore-scripts, avoiding duplicateprepublishOnlylifecycle execution inside the final publish step while preserving rawnpm publishsafeguards.
Most v1 applications will run without modification. The steps below apply only if you hit one of the breaking changes.
getPoolStats()/getPoolHealth()— if you iterate the result as an array, switch toObject.values(msq.getPoolStats()).Saga context— replacectx.sagaIdwithctx.executionIdinside step handlers.getCache()narrowing — if you assigned the result to aMemoryCachetyped variable, widen the type toCacheLike.cache.maxSize— still works transparently; rename tomaxEntriesat your convenience.slow-query-log queryHash— v2 now normalizes the hash from stable identity fields (database|db、collection|coll、operation|op、queryShape|query) and stores a 16-character digest. Historical slow-query-log records remain readable, but new and old aggregation keys are not guaranteed to stay continuous. This release does not include an automatic migration script; if your downstream analytics depend on historical key continuity, migrate those records explicitly before or during rollout.