@classytic/mongokit 3.20.0 → 3.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PaginationEngine-DYpOD2wY.d.mts → PaginationEngine-CYRTLW6s.d.mts} +1 -1
- package/dist/{Repository-dbbgOGjK.mjs → Repository-CaDAJY98.mjs} +100 -14
- package/dist/actions/index.d.mts +1 -1
- package/dist/adapter/index.d.mts +17 -10
- package/dist/adapter/index.mjs +1 -1
- package/dist/{adapter-CW1EL0fF.mjs → adapter-rTPLUrAV.mjs} +2 -1
- package/dist/ai/index.d.mts +1 -1
- package/dist/better-auth/index.mjs +2 -2
- package/dist/{create-repository-CJATiAKX.mjs → create-repository-BFVYm48p.mjs} +2 -2
- package/dist/{create-repository-0TkQhcv-.d.mts → create-repository-DXa3nMG6.d.mts} +95 -4
- package/dist/{index-Cg3SWugF.d.mts → index-CENL7LRb.d.mts} +1 -1
- package/dist/index.d.mts +8 -8
- package/dist/index.mjs +7 -6
- package/dist/memory-cache-D3wyN_2w.mjs +98 -0
- package/dist/{mongooseToJsonSchema-khdzVo8x.mjs → mongooseToJsonSchema-CVnrKFDq.mjs} +1 -67
- package/dist/{mongooseToJsonSchema-D2CyAMIC.d.mts → mongooseToJsonSchema-ChFKfZts.d.mts} +31 -2
- package/dist/{multi-tenant.plugin-CTsWz0XK.d.mts → multi-tenant.plugin-CFzMOuZP.d.mts} +1 -1
- package/dist/pagination/PaginationEngine.d.mts +1 -1
- package/dist/plugins/index.d.mts +4 -4
- package/dist/plugins/index.mjs +3 -3
- package/dist/testkit/index.d.mts +1 -1
- package/dist/testkit/index.mjs +1 -1
- package/dist/{timestamp.plugin-nG9Z1JEk.mjs → timestamp.plugin-Ch0O6DPX.mjs} +1 -1
- package/dist/{types-DNFMofHy.d.mts → types-BnRqAJVa.d.mts} +8 -0
- package/dist/usage/index.d.mts +23 -0
- package/dist/usage/index.mjs +67 -0
- package/dist/utils/index.d.mts +2 -2
- package/dist/utils/index.mjs +3 -2
- package/dist/{validation-chain.plugin-buy3uvyk.d.mts → validation-chain.plugin-DDQeEyk5.d.mts} +63 -2
- package/dist/{validation-chain.plugin-Dn_wZYLA.mjs → validation-chain.plugin-RxOzGuQy.mjs} +221 -2
- package/package.json +178 -184
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as KeysetPaginationOptions, U as PaginationConfig, V as OffsetPaginationOptions, i as AnyDocument, n as AggregatePaginationOptions } from "./types-
|
|
1
|
+
import { A as KeysetPaginationOptions, U as PaginationConfig, V as OffsetPaginationOptions, i as AnyDocument, n as AggregatePaginationOptions } from "./types-BnRqAJVa.mjs";
|
|
2
2
|
import { Model } from "mongoose";
|
|
3
3
|
import { AggregatePaginationResult, KeysetPaginationResult, OffsetPaginationResult } from "@classytic/repo-core/pagination";
|
|
4
4
|
//#region src/pagination/PaginationEngine.d.ts
|
|
@@ -1743,20 +1743,6 @@ function changeEventTimestamp(change) {
|
|
|
1743
1743
|
* OBSERVABILITY=300, DEFAULT=500) and the two refs are reference-equal.
|
|
1744
1744
|
*/
|
|
1745
1745
|
const HOOK_PRIORITY$1 = HOOK_PRIORITY;
|
|
1746
|
-
/**
|
|
1747
|
-
* Production-grade repository for MongoDB.
|
|
1748
|
-
*
|
|
1749
|
-
* Extends `@classytic/repo-core/repository`'s `RepositoryBase` for the
|
|
1750
|
-
* driver-agnostic hook + plugin plumbing (context builder, priority-sorted
|
|
1751
|
-
* event engine, plugin-order validator) while layering every Mongo-specific
|
|
1752
|
-
* concern — populate, aggregate, lookup, keyset + cursor pagination, $near
|
|
1753
|
-
* rewriting — on top.
|
|
1754
|
-
*
|
|
1755
|
-
* Public surface is byte-stable with mongokit 3.9 (the `_hooks` property is
|
|
1756
|
-
* preserved as a live read-through getter; all CRUD, event, and plugin method
|
|
1757
|
-
* signatures unchanged). 3.10 is an internal re-plumbing release; consumers
|
|
1758
|
-
* upgrading from 3.9 need no code changes.
|
|
1759
|
-
*/
|
|
1760
1746
|
var Repository = class extends RepositoryBase {
|
|
1761
1747
|
/**
|
|
1762
1748
|
* Runtime capability descriptor required by `StandardRepo<TDoc>`
|
|
@@ -2998,6 +2984,106 @@ var Repository = class extends RepositoryBase {
|
|
|
2998
2984
|
});
|
|
2999
2985
|
}
|
|
3000
2986
|
/**
|
|
2987
|
+
* State-machine-backed CAS transition with status history — the
|
|
2988
|
+
* canonical domain-verb shape, promoted from the identical helper
|
|
2989
|
+
* every engine package hand-rolled (projects / manufacturing /
|
|
2990
|
+
* assets `claimTransition`).
|
|
2991
|
+
*
|
|
2992
|
+
* One call does the whole liturgy:
|
|
2993
|
+
*
|
|
2994
|
+
* 1. **Legality pre-flight** — `machine.assertTransition(id, from,
|
|
2995
|
+
* to)` for every source state (sync, throws the DOMAIN's typed
|
|
2996
|
+
* error via the machine's `errorFactory` — mongokit never
|
|
2997
|
+
* invents its own transition-error vocabulary).
|
|
2998
|
+
* 2. **Concurrency CAS** — delegates to {@link claim} (multi-source
|
|
2999
|
+
* `from` arrays compile to `$in`; `where` guards AND-merge;
|
|
3000
|
+
* tenant scope / soft-delete / cache / audit plugins all fire).
|
|
3001
|
+
* 3. **History append** — `$push`es `{ status: to, occurredAt, by?,
|
|
3002
|
+
* note? }` onto the history field (default `statusHistory`),
|
|
3003
|
+
* never read-modify-write on the array. Pass `history: false`
|
|
3004
|
+
* for models without a trail.
|
|
3005
|
+
* 4. **Race-loss diagnosis** — on CAS miss it re-reads the row and
|
|
3006
|
+
* throws the ACCURATE error: the machine's own error built from
|
|
3007
|
+
* the row's CURRENT state when that state makes the move illegal
|
|
3008
|
+
* (hand-rolled versions threw with the stale pre-read state), a
|
|
3009
|
+
* 404-shaped error when the row vanished, or a 409
|
|
3010
|
+
* `TRANSITION_RACE_LOST` when the move is still legal from the
|
|
3011
|
+
* current state (caller may re-read and retry).
|
|
3012
|
+
*
|
|
3013
|
+
* The `machine` parameter is STRUCTURAL (`{ name, assertTransition }`)
|
|
3014
|
+
* — `defineStateMachine()` from `@classytic/primitives/state-machine`
|
|
3015
|
+
* satisfies it without mongokit taking a primitives dependency, and
|
|
3016
|
+
* anything else with the same shape works too.
|
|
3017
|
+
*
|
|
3018
|
+
* @example The common verb tail (replaces ~40 lines of base-repo helper)
|
|
3019
|
+
* ```ts
|
|
3020
|
+
* const updated = await repo.applyTransition(id, WORK_ORDER_MACHINE, {
|
|
3021
|
+
* from: existing.status,
|
|
3022
|
+
* to: 'released',
|
|
3023
|
+
* set: { pendingStock: stamp },
|
|
3024
|
+
* by: ctx.actorId,
|
|
3025
|
+
* }, repoOptionsFromCtx(ctx));
|
|
3026
|
+
* ```
|
|
3027
|
+
*
|
|
3028
|
+
* @example Multi-source cancel via the machine's reverse lookup
|
|
3029
|
+
* ```ts
|
|
3030
|
+
* await repo.applyTransition(id, MACHINE, {
|
|
3031
|
+
* from: MACHINE.validSources('cancelled'),
|
|
3032
|
+
* to: 'cancelled',
|
|
3033
|
+
* note: reason,
|
|
3034
|
+
* }, opts);
|
|
3035
|
+
* ```
|
|
3036
|
+
*/
|
|
3037
|
+
async applyTransition(id, machine, args, options = {}) {
|
|
3038
|
+
const entityId = String(id);
|
|
3039
|
+
const sources = Array.isArray(args.from) ? args.from : [args.from];
|
|
3040
|
+
for (const from of sources) machine.assertTransition(entityId, from, args.to);
|
|
3041
|
+
const historyField = args.history === false ? null : args.history ?? "statusHistory";
|
|
3042
|
+
const pushSpec = { ...args.push ?? {} };
|
|
3043
|
+
if (historyField !== null) pushSpec[historyField] = {
|
|
3044
|
+
status: args.to,
|
|
3045
|
+
occurredAt: args.at ?? /* @__PURE__ */ new Date(),
|
|
3046
|
+
...args.by !== void 0 ? { by: args.by } : {},
|
|
3047
|
+
...args.note !== void 0 ? { note: args.note } : {}
|
|
3048
|
+
};
|
|
3049
|
+
const patch = {
|
|
3050
|
+
...args.set !== void 0 && Object.keys(args.set).length > 0 ? { $set: args.set } : {},
|
|
3051
|
+
...Object.keys(pushSpec).length > 0 ? { $push: pushSpec } : {},
|
|
3052
|
+
...args.inc !== void 0 && Object.keys(args.inc).length > 0 ? { $inc: args.inc } : {},
|
|
3053
|
+
...args.unset !== void 0 && Object.keys(args.unset).length > 0 ? { $unset: args.unset } : {}
|
|
3054
|
+
};
|
|
3055
|
+
const updated = await this.claim(id, {
|
|
3056
|
+
from: Array.isArray(args.from) ? args.from : args.from,
|
|
3057
|
+
to: args.to,
|
|
3058
|
+
...args.field !== void 0 ? { field: args.field } : {},
|
|
3059
|
+
...args.where !== void 0 ? { where: args.where } : {}
|
|
3060
|
+
}, patch, options);
|
|
3061
|
+
if (updated) return updated;
|
|
3062
|
+
const current = await this.getById(id, {
|
|
3063
|
+
...options,
|
|
3064
|
+
throwOnNotFound: false
|
|
3065
|
+
});
|
|
3066
|
+
if (!current) throw createError(404, `${machine.name} '${entityId}' not found`, {
|
|
3067
|
+
code: "TRANSITION_TARGET_MISSING",
|
|
3068
|
+
meta: {
|
|
3069
|
+
entityType: machine.name,
|
|
3070
|
+
entityId,
|
|
3071
|
+
to: args.to
|
|
3072
|
+
}
|
|
3073
|
+
});
|
|
3074
|
+
const currentState = (args.field ?? "status").split(".").reduce((acc, key) => acc?.[key], current);
|
|
3075
|
+
machine.assertTransition(entityId, String(currentState), args.to);
|
|
3076
|
+
throw createError(409, `${machine.name} '${entityId}' lost the transition race to '${args.to}' (currently '${String(currentState)}'); re-read and retry`, {
|
|
3077
|
+
code: "TRANSITION_RACE_LOST",
|
|
3078
|
+
meta: {
|
|
3079
|
+
entityType: machine.name,
|
|
3080
|
+
entityId,
|
|
3081
|
+
from: String(currentState),
|
|
3082
|
+
to: args.to
|
|
3083
|
+
}
|
|
3084
|
+
});
|
|
3085
|
+
}
|
|
3086
|
+
/**
|
|
3001
3087
|
* Optimistic-concurrency CAS via a version stamp.
|
|
3002
3088
|
*
|
|
3003
3089
|
* Sibling to `claim()` — distinct mental model:
|
package/dist/actions/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as create_d_exports, i as delete_d_exports, n as update_d_exports, o as aggregate_d_exports, r as read_d_exports } from "../index-
|
|
1
|
+
import { a as create_d_exports, i as delete_d_exports, n as update_d_exports, o as aggregate_d_exports, r as read_d_exports } from "../index-CENL7LRb.mjs";
|
|
2
2
|
export { aggregate_d_exports as aggregate, create_d_exports as create, delete_d_exports as deleteActions, read_d_exports as read, update_d_exports as update };
|
package/dist/adapter/index.d.mts
CHANGED
|
@@ -22,8 +22,18 @@ interface MongooseAdapterOptions<TDoc = unknown> {
|
|
|
22
22
|
*/
|
|
23
23
|
repository: AdapterRepositoryInput<TDoc>;
|
|
24
24
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* Schema generator for OpenAPI / introspection docs.
|
|
26
|
+
*
|
|
27
|
+
* **Defaults to mongokit's own `buildCrudSchemasFromModel`** (3.21) — the
|
|
28
|
+
* canonical Mongoose→JSON-Schema generator ships in this package, so
|
|
29
|
+
* omitting the option now means "use it" rather than "no schemas". An
|
|
30
|
+
* audit of a 68-resource production host found 28 adapters that omitted
|
|
31
|
+
* it by accident and silently shipped `null` OpenAPI bodies + empty MCP
|
|
32
|
+
* tool schemas — correct-by-default closes that failure class.
|
|
33
|
+
*
|
|
34
|
+
* Pass `false` to opt OUT of schema generation entirely (`generateSchemas`
|
|
35
|
+
* returns `null`, hosts fall back to permissive bodies). Pass your own
|
|
36
|
+
* `SchemaGenerator` to replace the default.
|
|
27
37
|
*
|
|
28
38
|
* **Model type is intentionally `Model<unknown>`, not `Model<TDoc>`**:
|
|
29
39
|
* schema generators introspect `.schema.paths` — they read metadata,
|
|
@@ -35,17 +45,14 @@ interface MongooseAdapterOptions<TDoc = unknown> {
|
|
|
35
45
|
*
|
|
36
46
|
* @example
|
|
37
47
|
* ```ts
|
|
38
|
-
*
|
|
39
|
-
*
|
|
48
|
+
* // Default — full OpenAPI/MCP schemas, zero config:
|
|
49
|
+
* createMongooseAdapter({ model: ProductModel, repository: productRepository });
|
|
40
50
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* repository: productRepository,
|
|
44
|
-
* schemaGenerator: buildCrudSchemasFromModel,
|
|
45
|
-
* });
|
|
51
|
+
* // Explicit opt-out (permissive bodies, no generated schemas):
|
|
52
|
+
* createMongooseAdapter({ model, repository, schemaGenerator: false });
|
|
46
53
|
* ```
|
|
47
54
|
*/
|
|
48
|
-
schemaGenerator?: SchemaGenerator<Model<unknown
|
|
55
|
+
schemaGenerator?: SchemaGenerator<Model<unknown>> | false;
|
|
49
56
|
}
|
|
50
57
|
/**
|
|
51
58
|
* Mongoose data adapter — implements the `DataAdapter<TDoc>` contract from
|
package/dist/adapter/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createMongooseAdapter, r as isMongooseModel, t as MongooseAdapter } from "../adapter-
|
|
1
|
+
import { n as createMongooseAdapter, r as isMongooseModel, t as MongooseAdapter } from "../adapter-rTPLUrAV.mjs";
|
|
2
2
|
export { MongooseAdapter, createMongooseAdapter, isMongooseModel };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { n as warn } from "./logger-K7dPmu2U.mjs";
|
|
2
|
+
import { t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-CVnrKFDq.mjs";
|
|
2
3
|
import { mergeFieldRuleConstraints } from "@classytic/repo-core/schema";
|
|
3
4
|
import { asRepositoryLike, isRepository } from "@classytic/repo-core/adapter";
|
|
4
5
|
//#region src/adapter/types.ts
|
|
@@ -77,7 +78,7 @@ var MongooseAdapter = class {
|
|
|
77
78
|
if (!isRepository(options.repository)) throw new TypeError(formatInvalidRepositoryError(options.repository, options.model));
|
|
78
79
|
this.model = options.model;
|
|
79
80
|
this.repository = asRepositoryLike(options.repository);
|
|
80
|
-
this.schemaGenerator = options.schemaGenerator;
|
|
81
|
+
this.schemaGenerator = options.schemaGenerator === false ? void 0 : options.schemaGenerator ?? buildCrudSchemasFromModel;
|
|
81
82
|
this.name = `MongooseAdapter<${options.model.modelName}>`;
|
|
82
83
|
}
|
|
83
84
|
/**
|
package/dist/ai/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as Repository } from "../Repository-
|
|
2
|
-
import { n as createMongooseAdapter } from "../adapter-
|
|
1
|
+
import { n as Repository } from "../Repository-CaDAJY98.mjs";
|
|
2
|
+
import { n as createMongooseAdapter } from "../adapter-rTPLUrAV.mjs";
|
|
3
3
|
import { pluralizeBetterAuthCollection, resolveBetterAuthCollections } from "@classytic/repo-core/better-auth";
|
|
4
4
|
//#region src/better-auth/index.ts
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as Repository } from "./Repository-
|
|
2
|
-
import { a as methodRegistryPlugin, d as cachePlugin, f as batchOperationsPlugin, h as auditLogPlugin, i as multiTenantPlugin, m as auditTrailPlugin, n as softDeletePlugin, o as customIdPlugin, t as timestampPlugin } from "./timestamp.plugin-
|
|
1
|
+
import { n as Repository } from "./Repository-CaDAJY98.mjs";
|
|
2
|
+
import { a as methodRegistryPlugin, d as cachePlugin, f as batchOperationsPlugin, h as auditLogPlugin, i as multiTenantPlugin, m as auditTrailPlugin, n as softDeletePlugin, o as customIdPlugin, t as timestampPlugin } from "./timestamp.plugin-Ch0O6DPX.mjs";
|
|
3
3
|
//#region src/create-repository.ts
|
|
4
4
|
function isLoggerAudit(value) {
|
|
5
5
|
const v = value;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as ObjectId, Dt as LookupOptions, Et as LookupBuilder, H as OperationOptions, J as PopulateSpec, M as LookupPopulateOptions, N as LookupPopulateResult, P as Middleware, Q as RepositoryContext, U as PaginationConfig, X as ReadOptions, Y as PrioritizedHook, Z as ReadPreferenceType, _ as DeleteManyResult, at as SessionOptions, c as CacheableOptions, d as CollationOptions, ft as UpdateManyResult, it as SelectSpec, j as Logger, n as AggregatePaginationOptions, nt as RepositoryOptions, p as CreateOptions, pt as UpdateOptions, q as PluginType, st as SoftDeleteOptions, t as AggregateOptions, ut as SortSpec$1, v as DeleteResult, w as FindOneAndUpdateOptions, xt as WithTransactionOptions } from "./types-
|
|
2
|
-
import { _ as RepositoryCachePluginOptions, i as CustomIdOptions, t as MultiTenantOptions, w as AuditTrailOptions } from "./multi-tenant.plugin-
|
|
3
|
-
import { t as PaginationEngine } from "./PaginationEngine-
|
|
1
|
+
import { B as ObjectId, Dt as LookupOptions, Et as LookupBuilder, H as OperationOptions, J as PopulateSpec, M as LookupPopulateOptions, N as LookupPopulateResult, P as Middleware, Q as RepositoryContext, U as PaginationConfig, X as ReadOptions, Y as PrioritizedHook, Z as ReadPreferenceType, _ as DeleteManyResult, at as SessionOptions, c as CacheableOptions, d as CollationOptions, ft as UpdateManyResult, it as SelectSpec, j as Logger, n as AggregatePaginationOptions, nt as RepositoryOptions, p as CreateOptions, pt as UpdateOptions, q as PluginType, st as SoftDeleteOptions, t as AggregateOptions, ut as SortSpec$1, v as DeleteResult, w as FindOneAndUpdateOptions, xt as WithTransactionOptions } from "./types-BnRqAJVa.mjs";
|
|
2
|
+
import { _ as RepositoryCachePluginOptions, i as CustomIdOptions, t as MultiTenantOptions, w as AuditTrailOptions } from "./multi-tenant.plugin-CFzMOuZP.mjs";
|
|
3
|
+
import { t as PaginationEngine } from "./PaginationEngine-CYRTLW6s.mjs";
|
|
4
4
|
import { AggPaginationRequest, AggRequest, AggResult, ArchiveOptions, ArchiveResult, ArchiveSink, ChangeEvent, FilterInput, KeysetAggPaginationResult, QueryOptions, RepoCapabilities, RepositoryBase, TenantPurgeOptions, TenantPurgeResult, TenantPurgeStrategy, WatchOptions } from "@classytic/repo-core/repository";
|
|
5
5
|
import { ClientSession, Expression, Model, PipelineStage, PopulateOptions } from "mongoose";
|
|
6
6
|
import { Filter } from "@classytic/repo-core/filter";
|
|
@@ -504,6 +504,19 @@ declare const HOOK_PRIORITY: {
|
|
|
504
504
|
* signatures unchanged). 3.10 is an internal re-plumbing release; consumers
|
|
505
505
|
* upgrading from 3.9 need no code changes.
|
|
506
506
|
*/
|
|
507
|
+
/**
|
|
508
|
+
* Structural contract {@link Repository.applyTransition} requires of a state
|
|
509
|
+
* machine. `defineStateMachine()` from
|
|
510
|
+
* `@classytic/primitives/state-machine` satisfies it as-is — mongokit
|
|
511
|
+
* deliberately does NOT import primitives; compatibility is structural,
|
|
512
|
+
* the same policy as the arc event-shape mirror. `assertTransition`
|
|
513
|
+
* MUST throw (the domain's typed error) on an illegal `from → to`.
|
|
514
|
+
*/
|
|
515
|
+
interface TransitionMachine {
|
|
516
|
+
/** Aggregate name — surfaces in race/missing error messages. */
|
|
517
|
+
readonly name: string;
|
|
518
|
+
assertTransition(entityId: string, from: string, to: string): void;
|
|
519
|
+
}
|
|
507
520
|
declare class Repository<TDoc = unknown> extends RepositoryBase {
|
|
508
521
|
/**
|
|
509
522
|
* Runtime capability descriptor required by `StandardRepo<TDoc>`
|
|
@@ -1200,6 +1213,84 @@ declare class Repository<TDoc = unknown> extends RepositoryBase {
|
|
|
1200
1213
|
idField?: string;
|
|
1201
1214
|
upsert?: boolean;
|
|
1202
1215
|
}): Promise<TDoc | null>;
|
|
1216
|
+
/**
|
|
1217
|
+
* State-machine-backed CAS transition with status history — the
|
|
1218
|
+
* canonical domain-verb shape, promoted from the identical helper
|
|
1219
|
+
* every engine package hand-rolled (projects / manufacturing /
|
|
1220
|
+
* assets `claimTransition`).
|
|
1221
|
+
*
|
|
1222
|
+
* One call does the whole liturgy:
|
|
1223
|
+
*
|
|
1224
|
+
* 1. **Legality pre-flight** — `machine.assertTransition(id, from,
|
|
1225
|
+
* to)` for every source state (sync, throws the DOMAIN's typed
|
|
1226
|
+
* error via the machine's `errorFactory` — mongokit never
|
|
1227
|
+
* invents its own transition-error vocabulary).
|
|
1228
|
+
* 2. **Concurrency CAS** — delegates to {@link claim} (multi-source
|
|
1229
|
+
* `from` arrays compile to `$in`; `where` guards AND-merge;
|
|
1230
|
+
* tenant scope / soft-delete / cache / audit plugins all fire).
|
|
1231
|
+
* 3. **History append** — `$push`es `{ status: to, occurredAt, by?,
|
|
1232
|
+
* note? }` onto the history field (default `statusHistory`),
|
|
1233
|
+
* never read-modify-write on the array. Pass `history: false`
|
|
1234
|
+
* for models without a trail.
|
|
1235
|
+
* 4. **Race-loss diagnosis** — on CAS miss it re-reads the row and
|
|
1236
|
+
* throws the ACCURATE error: the machine's own error built from
|
|
1237
|
+
* the row's CURRENT state when that state makes the move illegal
|
|
1238
|
+
* (hand-rolled versions threw with the stale pre-read state), a
|
|
1239
|
+
* 404-shaped error when the row vanished, or a 409
|
|
1240
|
+
* `TRANSITION_RACE_LOST` when the move is still legal from the
|
|
1241
|
+
* current state (caller may re-read and retry).
|
|
1242
|
+
*
|
|
1243
|
+
* The `machine` parameter is STRUCTURAL (`{ name, assertTransition }`)
|
|
1244
|
+
* — `defineStateMachine()` from `@classytic/primitives/state-machine`
|
|
1245
|
+
* satisfies it without mongokit taking a primitives dependency, and
|
|
1246
|
+
* anything else with the same shape works too.
|
|
1247
|
+
*
|
|
1248
|
+
* @example The common verb tail (replaces ~40 lines of base-repo helper)
|
|
1249
|
+
* ```ts
|
|
1250
|
+
* const updated = await repo.applyTransition(id, WORK_ORDER_MACHINE, {
|
|
1251
|
+
* from: existing.status,
|
|
1252
|
+
* to: 'released',
|
|
1253
|
+
* set: { pendingStock: stamp },
|
|
1254
|
+
* by: ctx.actorId,
|
|
1255
|
+
* }, repoOptionsFromCtx(ctx));
|
|
1256
|
+
* ```
|
|
1257
|
+
*
|
|
1258
|
+
* @example Multi-source cancel via the machine's reverse lookup
|
|
1259
|
+
* ```ts
|
|
1260
|
+
* await repo.applyTransition(id, MACHINE, {
|
|
1261
|
+
* from: MACHINE.validSources('cancelled'),
|
|
1262
|
+
* to: 'cancelled',
|
|
1263
|
+
* note: reason,
|
|
1264
|
+
* }, opts);
|
|
1265
|
+
* ```
|
|
1266
|
+
*/
|
|
1267
|
+
applyTransition(id: string | ObjectId, machine: TransitionMachine, args: {
|
|
1268
|
+
from: string | readonly string[];
|
|
1269
|
+
to: string;
|
|
1270
|
+
/** State field (dotted paths supported) — default `'status'`. */
|
|
1271
|
+
field?: string;
|
|
1272
|
+
/** `$set` payload applied alongside the state write. */
|
|
1273
|
+
set?: Record<string, unknown>;
|
|
1274
|
+
/** Extra `$push` entries merged beside the history append. */
|
|
1275
|
+
push?: Record<string, unknown>;
|
|
1276
|
+
/** `$inc` counters applied alongside the state write. */
|
|
1277
|
+
inc?: Record<string, number>;
|
|
1278
|
+
/** `$unset` paths cleared alongside the state write. */
|
|
1279
|
+
unset?: Record<string, unknown>;
|
|
1280
|
+
/** Additional CAS guards, AND-merged into the filter. */
|
|
1281
|
+
where?: Record<string, unknown>;
|
|
1282
|
+
by?: string;
|
|
1283
|
+
note?: string;
|
|
1284
|
+
/**
|
|
1285
|
+
* History field name (default `'statusHistory'`), or `false` to
|
|
1286
|
+
* skip the append entirely.
|
|
1287
|
+
*/
|
|
1288
|
+
history?: string | false;
|
|
1289
|
+
/** Timestamp for the history entry — default `new Date()`. */
|
|
1290
|
+
at?: Date;
|
|
1291
|
+
}, options?: SessionOptions & {
|
|
1292
|
+
idField?: string;
|
|
1293
|
+
}): Promise<TDoc>;
|
|
1203
1294
|
/**
|
|
1204
1295
|
* Optimistic-concurrency CAS via a version stamp.
|
|
1205
1296
|
*
|
|
@@ -1754,4 +1845,4 @@ interface CreateRepositoryConfig extends RepositoryOptions {
|
|
|
1754
1845
|
*/
|
|
1755
1846
|
declare function createRepository<TDoc>(model: Model<TDoc, any, any, any>, config?: CreateRepositoryConfig): Repository<TDoc>;
|
|
1756
1847
|
//#endregion
|
|
1757
|
-
export { Repository as a, HOOK_PRIORITY as i, CreateRepositoryConfig as n,
|
|
1848
|
+
export { Repository as a, HOOK_PRIORITY as i, CreateRepositoryConfig as n, TransitionMachine as o, createRepository as r, AggregationBuilder as s, AuditConfig as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as ObjectId, Dt as LookupOptions, H as OperationOptions, I as MinMaxResult, J as PopulateSpec, T as GroupResult, Z as ReadPreferenceType, ft as UpdateManyResult, ht as UpdateWithValidationResult, i as AnyDocument, it as SelectSpec, p as CreateOptions, pt as UpdateOptions, ut as SortSpec, v as DeleteResult, w as FindOneAndUpdateOptions } from "./types-
|
|
1
|
+
import { B as ObjectId, Dt as LookupOptions, H as OperationOptions, I as MinMaxResult, J as PopulateSpec, T as GroupResult, Z as ReadPreferenceType, ft as UpdateManyResult, ht as UpdateWithValidationResult, i as AnyDocument, it as SelectSpec, p as CreateOptions, pt as UpdateOptions, ut as SortSpec, v as DeleteResult, w as FindOneAndUpdateOptions } from "./types-BnRqAJVa.mjs";
|
|
2
2
|
import { Model, PipelineStage } from "mongoose";
|
|
3
3
|
declare namespace aggregate_d_exports {
|
|
4
4
|
export { aggregate, aggregatePaginate, average, countBy, distinct, facet, groupBy, lookup, minMax, sum, unwind };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { $ as RepositoryEvent, A as KeysetPaginationOptions, B as ObjectId, C as FieldPreset, Ct as IControllerResponse, D as InferDocument, Dt as LookupOptions, E as HookMode, Et as LookupBuilder, F as MiddlewareContext, G as Plugin, H as OperationOptions, I as MinMaxResult, J as PopulateSpec, K as PluginFunction, L as MinimalRepoView, M as LookupPopulateOptions, N as LookupPopulateResult, O as InferRawDoc, P as Middleware, Q as RepositoryContext, R as MongoOperatorUpdate, S as EventPhase, St as IController, T as GroupResult, Tt as IResponseFormatter, U as PaginationConfig, V as OffsetPaginationOptions, W as PartialBy, X as ReadOptions, Y as PrioritizedHook, Z as ReadPreferenceType, _t as ValidationChainOptions, a as AnyModel, at as SessionOptions, b as EventHandlers, bt as WithPlugins, c as CacheableOptions, ct as SoftDeleteRepository, d as CollationOptions, dt as Strict, et as RepositoryInstance, f as CreateInput, ft as UpdateManyResult, g as DeepPartial, gt as UserContext, h as DecodedCursor, ht as UpdateWithValidationResult, i as AnyDocument, it as SelectSpec, j as Logger, k as KeysOfType, l as CascadeOptions, lt as SortDirection, m as CursorPayload, mt as UpdatePatch, n as AggregatePaginationOptions, nt as RepositoryOptions, o as BasePaginationOptions, ot as SoftDeleteFilterMode, p as CreateOptions, pt as UpdateOptions, q as PluginType, r as AllPluginMethods, rt as RequiredBy, s as CacheOperationOptions, st as SoftDeleteOptions, t as AggregateOptions, tt as RepositoryOperation, u as CascadeRelation, ut as SortSpec, v as DeleteResult, vt as ValidatorDefinition, w as FindOneAndUpdateOptions, wt as IRequestContext, x as EventPayload, xt as WithTransactionOptions, y as DocField, yt as ValueType, z as NonNullableFields } from "./types-
|
|
2
|
-
import { t as index_d_exports } from "./index-
|
|
3
|
-
import { C as AuditTrailMethods, E as auditTrailPlugin, S as AuditQueryResult, T as AuditTrailQuery, _ as RepositoryCachePluginOptions, a as DateSequentialIdOptions, b as AuditOperation, c as SequentialIdOptions, d as getNextSequence, f as prefixedId, g as RepositoryCacheHandle, h as CacheOptions, i as CustomIdOptions, l as customIdPlugin, m as CacheAdapter, n as adminBypass, o as IdGenerator, p as sequentialId, r as multiTenantPlugin, s as PrefixedIdOptions, t as MultiTenantOptions, u as dateSequentialId, v as cachePlugin, w as AuditTrailOptions, x as AuditQueryOptions, y as AuditEntry } from "./multi-tenant.plugin-
|
|
4
|
-
import { t as PaginationEngine } from "./PaginationEngine-
|
|
5
|
-
import { a as Repository, i as HOOK_PRIORITY, n as CreateRepositoryConfig, o as
|
|
6
|
-
import { A as
|
|
1
|
+
import { $ as RepositoryEvent, A as KeysetPaginationOptions, B as ObjectId, C as FieldPreset, Ct as IControllerResponse, D as InferDocument, Dt as LookupOptions, E as HookMode, Et as LookupBuilder, F as MiddlewareContext, G as Plugin, H as OperationOptions, I as MinMaxResult, J as PopulateSpec, K as PluginFunction, L as MinimalRepoView, M as LookupPopulateOptions, N as LookupPopulateResult, O as InferRawDoc, P as Middleware, Q as RepositoryContext, R as MongoOperatorUpdate, S as EventPhase, St as IController, T as GroupResult, Tt as IResponseFormatter, U as PaginationConfig, V as OffsetPaginationOptions, W as PartialBy, X as ReadOptions, Y as PrioritizedHook, Z as ReadPreferenceType, _t as ValidationChainOptions, a as AnyModel, at as SessionOptions, b as EventHandlers, bt as WithPlugins, c as CacheableOptions, ct as SoftDeleteRepository, d as CollationOptions, dt as Strict, et as RepositoryInstance, f as CreateInput, ft as UpdateManyResult, g as DeepPartial, gt as UserContext, h as DecodedCursor, ht as UpdateWithValidationResult, i as AnyDocument, it as SelectSpec, j as Logger, k as KeysOfType, l as CascadeOptions, lt as SortDirection, m as CursorPayload, mt as UpdatePatch, n as AggregatePaginationOptions, nt as RepositoryOptions, o as BasePaginationOptions, ot as SoftDeleteFilterMode, p as CreateOptions, pt as UpdateOptions, q as PluginType, r as AllPluginMethods, rt as RequiredBy, s as CacheOperationOptions, st as SoftDeleteOptions, t as AggregateOptions, tt as RepositoryOperation, u as CascadeRelation, ut as SortSpec, v as DeleteResult, vt as ValidatorDefinition, w as FindOneAndUpdateOptions, wt as IRequestContext, x as EventPayload, xt as WithTransactionOptions, y as DocField, yt as ValueType, z as NonNullableFields } from "./types-BnRqAJVa.mjs";
|
|
2
|
+
import { t as index_d_exports } from "./index-CENL7LRb.mjs";
|
|
3
|
+
import { C as AuditTrailMethods, E as auditTrailPlugin, S as AuditQueryResult, T as AuditTrailQuery, _ as RepositoryCachePluginOptions, a as DateSequentialIdOptions, b as AuditOperation, c as SequentialIdOptions, d as getNextSequence, f as prefixedId, g as RepositoryCacheHandle, h as CacheOptions, i as CustomIdOptions, l as customIdPlugin, m as CacheAdapter, n as adminBypass, o as IdGenerator, p as sequentialId, r as multiTenantPlugin, s as PrefixedIdOptions, t as MultiTenantOptions, u as dateSequentialId, v as cachePlugin, w as AuditTrailOptions, x as AuditQueryOptions, y as AuditEntry } from "./multi-tenant.plugin-CFzMOuZP.mjs";
|
|
4
|
+
import { t as PaginationEngine } from "./PaginationEngine-CYRTLW6s.mjs";
|
|
5
|
+
import { a as Repository, i as HOOK_PRIORITY, n as CreateRepositoryConfig, o as TransitionMachine, r as createRepository, s as AggregationBuilder, t as AuditConfig } from "./create-repository-DXa3nMG6.mjs";
|
|
6
|
+
import { A as fieldFilterPlugin, C as MongoOperationsMethods, D as LeaseMethods, E as methodRegistryPlugin, F as BulkWriteResult, I as batchOperationsPlugin, L as auditLogPlugin, M as elasticSearchPlugin, N as cascadePlugin, O as LeasePluginOptions, P as BatchOperationsMethods, R as AggregateHelpersMethods, S as observabilityPlugin, _ as immutableStatesPlugin, a as uniqueField, b as ObservabilityOptions, c as TenantContext, d as SubdocumentMethods, f as subdocumentPlugin, g as ImmutableStatesPluginOptions, h as ImmutableClaimView, i as requireField, j as ElasticSearchOptions, k as leasePlugin, l as TenantStore, m as softDeletePlugin, n as blockIf, o as validationChainPlugin, p as SoftDeleteMethods, r as immutableField, s as timestampPlugin, t as autoInject, u as createTenantContext, v as AppendOnlyPluginOptions, w as mongoOperationsPlugin, x as OperationMetric, y as appendOnlyPlugin, z as aggregateHelpersPlugin } from "./validation-chain.plugin-DDQeEyk5.mjs";
|
|
7
7
|
import { n as SchemaPathsLike, t as FieldType$1 } from "./coercion-BjdPX3YF.mjs";
|
|
8
8
|
import { n as SchemaIndexes } from "./indexes-DIjMpYES.mjs";
|
|
9
|
-
import { d as
|
|
9
|
+
import { _ as parseDuplicateKeyError, a as configureLogger, c as idVariants, d as createFieldPreset, f as filterResponseData, g as isDuplicateKeyError, h as createError, i as toPlain, m as getMongooseProjection, n as buildCrudSchemasFromMongooseSchema, p as getFieldsForUser, r as createMemoryCache, t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-ChFKfZts.mjs";
|
|
10
10
|
import { RepoCapabilities } from "@classytic/repo-core/repository";
|
|
11
11
|
import { ClientSession, PipelineStage } from "mongoose";
|
|
12
12
|
//#region src/actions/cascade-references.d.ts
|
|
@@ -852,4 +852,4 @@ declare function createOptionsExtractor<TCtx extends Record<string, unknown>>(fi
|
|
|
852
852
|
*/
|
|
853
853
|
declare function systemContext(extra?: SessionOptions): SessionOptions;
|
|
854
854
|
//#endregion
|
|
855
|
-
export { ALL_OPERATIONS, type AggregateHelpersMethods, type AggregateOptions, type AggregatePaginationOptions, AggregationBuilder, type AllPluginMethods, type AnyDocument, type AnyModel, type AuditConfig, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailOptions, AuditTrailQuery, type BasePaginationOptions, type BatchOperationsMethods, type BulkWriteResult, type CacheAdapter, type CacheOperationOptions, type CacheOptions, type CacheableOptions, type CascadeOptions, type CascadePurgeReferencesOptions, type CascadeRelation, type CollationOptions, type CollectionRWLike, type CreateInput, type CreateOptions, type CreateRepositoryConfig, type CursorPayload, type CustomIdOptions, type DateSequentialIdOptions, type DecodedCursor, type DeepPartial, type DeleteResult, type DocField, type ElasticSearchOptions, type EventHandlers, type EventPayload, type EventPhase, type FieldPreset, type FieldType, type FilterQuery, type FindOneAndUpdateOptions, type GroupResult, HOOK_PRIORITY, type HookMode, type IController, type IControllerResponse, type IRequestContext, type IResponseFormatter, type IdGenerator, type InferDocument, type InferRawDoc, type KeysOfType, type KeysetPaginationOptions, type LeaseMethods, type LeasePluginOptions, type Logger, LookupBuilder, type LookupOptions, type LookupPopulateOptions, type LookupPopulateResult, MONGOKIT_CAPABILITIES, MUTATING_OPERATIONS, type Middleware, type MiddlewareContext, type MinMaxResult, type MinimalRepoView, type MongoOperationsMethods, type MongoOperatorUpdate, type MultiTenantOptions, type NonNullableFields, OP_REGISTRY, type ObjectId, type ObservabilityOptions, type OffsetPaginationOptions, type OperationDescriptor, type OperationMetric, type OperationOptions, type PaginationConfig, PaginationEngine, type ParsedQuery, type PartialBy, type Plugin, type PluginFunction, type PluginType, type PolicyKey, type PopulateOption, type PopulateSpec, type PrefixedIdOptions, type PrioritizedHook, type PurgeMode, type PurgeableRepoLike, QueryParser, type QueryParserOptions, READ_OPERATIONS, type ReadOptions, type ReadPreferenceType, type ReferencePurgeResult, type ReferenceRelation, Repository, Repository as default, type RepositoryCacheHandle, type RepositoryCachePluginOptions, type RepositoryContext, type RepositoryEvent, type RepositoryInstance, type RepositoryOperation, type RepositoryOptions, type RequiredBy, type SchemaLike, type SearchMode, type SelectSpec, type SequentialIdOptions, type SessionOptions, type SoftDeleteFilterMode, type SoftDeleteMethods, type SoftDeleteOptions, type SoftDeleteRepository, type SortDirection, type SortSpec, type Strict, type SubdocumentMethods, type TenantContext, type TenantStore, type UpdateManyResult, type UpdateOptions, type UpdatePatch, type UpdateWithValidationResult, type UserContext, type ValidationChainOptions, type ValidatorDefinition, type ValueType, type WithPlugins, type WithTransactionOptions, index_d_exports as actions, adminBypass, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, cascadePurgeReferences, compileFilterToMongo, configureLogger, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getMongooseProjection, getNextSequence, idVariants, immutableField, isDuplicateKeyError, isTransactionUnsupported, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, repoOptionsFromCtx, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, systemContext, timestampPlugin, uniqueField, validationChainPlugin, withTransaction };
|
|
855
|
+
export { ALL_OPERATIONS, type AggregateHelpersMethods, type AggregateOptions, type AggregatePaginationOptions, AggregationBuilder, type AllPluginMethods, type AnyDocument, type AnyModel, type AppendOnlyPluginOptions, type AuditConfig, type AuditEntry, type AuditOperation, type AuditQueryOptions, type AuditQueryResult, type AuditTrailMethods, type AuditTrailOptions, AuditTrailQuery, type BasePaginationOptions, type BatchOperationsMethods, type BulkWriteResult, type CacheAdapter, type CacheOperationOptions, type CacheOptions, type CacheableOptions, type CascadeOptions, type CascadePurgeReferencesOptions, type CascadeRelation, type CollationOptions, type CollectionRWLike, type CreateInput, type CreateOptions, type CreateRepositoryConfig, type CursorPayload, type CustomIdOptions, type DateSequentialIdOptions, type DecodedCursor, type DeepPartial, type DeleteResult, type DocField, type ElasticSearchOptions, type EventHandlers, type EventPayload, type EventPhase, type FieldPreset, type FieldType, type FilterQuery, type FindOneAndUpdateOptions, type GroupResult, HOOK_PRIORITY, type HookMode, type IController, type IControllerResponse, type IRequestContext, type IResponseFormatter, type IdGenerator, type ImmutableClaimView, type ImmutableStatesPluginOptions, type InferDocument, type InferRawDoc, type KeysOfType, type KeysetPaginationOptions, type LeaseMethods, type LeasePluginOptions, type Logger, LookupBuilder, type LookupOptions, type LookupPopulateOptions, type LookupPopulateResult, MONGOKIT_CAPABILITIES, MUTATING_OPERATIONS, type Middleware, type MiddlewareContext, type MinMaxResult, type MinimalRepoView, type MongoOperationsMethods, type MongoOperatorUpdate, type MultiTenantOptions, type NonNullableFields, OP_REGISTRY, type ObjectId, type ObservabilityOptions, type OffsetPaginationOptions, type OperationDescriptor, type OperationMetric, type OperationOptions, type PaginationConfig, PaginationEngine, type ParsedQuery, type PartialBy, type Plugin, type PluginFunction, type PluginType, type PolicyKey, type PopulateOption, type PopulateSpec, type PrefixedIdOptions, type PrioritizedHook, type PurgeMode, type PurgeableRepoLike, QueryParser, type QueryParserOptions, READ_OPERATIONS, type ReadOptions, type ReadPreferenceType, type ReferencePurgeResult, type ReferenceRelation, Repository, Repository as default, type RepositoryCacheHandle, type RepositoryCachePluginOptions, type RepositoryContext, type RepositoryEvent, type RepositoryInstance, type RepositoryOperation, type RepositoryOptions, type RequiredBy, type SchemaLike, type SearchMode, type SelectSpec, type SequentialIdOptions, type SessionOptions, type SoftDeleteFilterMode, type SoftDeleteMethods, type SoftDeleteOptions, type SoftDeleteRepository, type SortDirection, type SortSpec, type Strict, type SubdocumentMethods, type TenantContext, type TenantStore, type TransitionMachine, type UpdateManyResult, type UpdateOptions, type UpdatePatch, type UpdateWithValidationResult, type UserContext, type ValidationChainOptions, type ValidatorDefinition, type ValueType, type WithPlugins, type WithTransactionOptions, index_d_exports as actions, adminBypass, aggregateHelpersPlugin, appendOnlyPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, cascadePurgeReferences, compileFilterToMongo, configureLogger, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getMongooseProjection, getNextSequence, idVariants, immutableField, immutableStatesPlugin, isDuplicateKeyError, isTransactionUnsupported, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, repoOptionsFromCtx, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, systemContext, timestampPlugin, toPlain, uniqueField, validationChainPlugin, withTransaction };
|
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
import { n as idVariants } from "./id-resolution-P2OzcyRl.mjs";
|
|
2
|
-
import { a as withTransaction, c as MUTATING_OPERATIONS, d as operationsByPolicyKey, f as MONGOKIT_CAPABILITIES, i as isTransactionUnsupported, l as OP_REGISTRY, n as Repository, o as AggregationBuilder, p as createMongoPurgePort, r as batchTransaction, s as ALL_OPERATIONS, t as HOOK_PRIORITY, u as READ_OPERATIONS } from "./Repository-
|
|
2
|
+
import { a as withTransaction, c as MUTATING_OPERATIONS, d as operationsByPolicyKey, f as MONGOKIT_CAPABILITIES, i as isTransactionUnsupported, l as OP_REGISTRY, n as Repository, o as AggregationBuilder, p as createMongoPurgePort, r as batchTransaction, s as ALL_OPERATIONS, t as HOOK_PRIORITY, u as READ_OPERATIONS } from "./Repository-CaDAJY98.mjs";
|
|
3
3
|
import { b as LookupBuilder, x as compileFilterToMongo } from "./update-1Lq9OMD2.mjs";
|
|
4
4
|
import { n as warn, t as configureLogger } from "./logger-K7dPmu2U.mjs";
|
|
5
5
|
import { n as isDuplicateKeyError, r as parseDuplicateKeyError, t as createError } from "./error-BuByZwKU.mjs";
|
|
6
6
|
import { t as actions_exports } from "./actions/index.mjs";
|
|
7
|
-
import { a as methodRegistryPlugin, c as getNextSequence, d as cachePlugin, f as batchOperationsPlugin, h as auditLogPlugin, i as multiTenantPlugin, l as prefixedId, m as auditTrailPlugin, n as softDeletePlugin, o as customIdPlugin, p as AuditTrailQuery, r as adminBypass, s as dateSequentialId, t as timestampPlugin, u as sequentialId } from "./timestamp.plugin-
|
|
7
|
+
import { a as methodRegistryPlugin, c as getNextSequence, d as cachePlugin, f as batchOperationsPlugin, h as auditLogPlugin, i as multiTenantPlugin, l as prefixedId, m as auditTrailPlugin, n as softDeletePlugin, o as customIdPlugin, p as AuditTrailQuery, r as adminBypass, s as dateSequentialId, t as timestampPlugin, u as sequentialId } from "./timestamp.plugin-Ch0O6DPX.mjs";
|
|
8
8
|
import { t as PaginationEngine } from "./PaginationEngine-BT1ywu9k.mjs";
|
|
9
9
|
import { isGeoOperator, parseGeoFilter } from "./query/primitives/geo.mjs";
|
|
10
|
-
import { t as createRepository } from "./create-repository-
|
|
11
|
-
import { a as uniqueField, c as subdocumentPlugin, d as
|
|
10
|
+
import { t as createRepository } from "./create-repository-BFVYm48p.mjs";
|
|
11
|
+
import { _ as aggregateHelpersPlugin, a as uniqueField, c as subdocumentPlugin, d as observabilityPlugin, f as mongoOperationsPlugin, g as cascadePlugin, h as elasticSearchPlugin, i as requireField, l as immutableStatesPlugin, m as fieldFilterPlugin, n as blockIf, o as validationChainPlugin, p as leasePlugin, r as immutableField, s as createTenantContext, t as autoInject, u as appendOnlyPlugin } from "./validation-chain.plugin-RxOzGuQy.mjs";
|
|
12
12
|
import { i as getMongooseProjection, n as filterResponseData, r as getFieldsForUser, t as createFieldPreset } from "./field-selection-FSQFLpsU.mjs";
|
|
13
13
|
import { buildFieldTypeMap, coerceFieldValue, coerceHeuristic } from "./query/primitives/coercion.mjs";
|
|
14
14
|
import { extractSchemaIndexes } from "./query/primitives/indexes.mjs";
|
|
15
|
-
import { n as
|
|
15
|
+
import { n as toPlain, t as createMemoryCache } from "./memory-cache-D3wyN_2w.mjs";
|
|
16
|
+
import { n as buildCrudSchemasFromMongooseSchema, t as buildCrudSchemasFromModel } from "./mongooseToJsonSchema-CVnrKFDq.mjs";
|
|
16
17
|
import { runChunkedPurge } from "@classytic/repo-core/repository";
|
|
17
18
|
import { isControlParam } from "@classytic/repo-core/query-parser";
|
|
18
19
|
//#region src/actions/cascade-references.ts
|
|
@@ -1461,4 +1462,4 @@ function systemContext(extra) {
|
|
|
1461
1462
|
*/
|
|
1462
1463
|
var src_default = Repository;
|
|
1463
1464
|
//#endregion
|
|
1464
|
-
export { ALL_OPERATIONS, AggregationBuilder, AuditTrailQuery, HOOK_PRIORITY, LookupBuilder, MONGOKIT_CAPABILITIES, MUTATING_OPERATIONS, OP_REGISTRY, PaginationEngine, QueryParser, READ_OPERATIONS, Repository, actions_exports as actions, adminBypass, aggregateHelpersPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, cascadePurgeReferences, compileFilterToMongo, configureLogger, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, src_default as default, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getMongooseProjection, getNextSequence, idVariants, immutableField, isDuplicateKeyError, isTransactionUnsupported, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, repoOptionsFromCtx, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, systemContext, timestampPlugin, uniqueField, validationChainPlugin, withTransaction };
|
|
1465
|
+
export { ALL_OPERATIONS, AggregationBuilder, AuditTrailQuery, HOOK_PRIORITY, LookupBuilder, MONGOKIT_CAPABILITIES, MUTATING_OPERATIONS, OP_REGISTRY, PaginationEngine, QueryParser, READ_OPERATIONS, Repository, actions_exports as actions, adminBypass, aggregateHelpersPlugin, appendOnlyPlugin, auditLogPlugin, auditTrailPlugin, autoInject, batchOperationsPlugin, batchTransaction, blockIf, buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, cachePlugin, cascadePlugin, cascadePurgeReferences, compileFilterToMongo, configureLogger, createError, createFieldPreset, createMemoryCache, createOptionsExtractor, createRepository, createTenantContext, customIdPlugin, dateSequentialId, src_default as default, elasticSearchPlugin, fieldFilterPlugin, filterResponseData, getFieldsForUser, getMongooseProjection, getNextSequence, idVariants, immutableField, immutableStatesPlugin, isDuplicateKeyError, isTransactionUnsupported, leasePlugin, methodRegistryPlugin, mongoOperationsPlugin, multiTenantPlugin, observabilityPlugin, operationsByPolicyKey, parseDuplicateKeyError, prefixedId, repoOptionsFromCtx, requireField, sequentialId, softDeletePlugin, subdocumentPlugin, systemContext, timestampPlugin, toPlain, uniqueField, validationChainPlugin, withTransaction };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
//#region src/utils/to-plain.ts
|
|
2
|
+
/**
|
|
3
|
+
* Convert a hydrated Mongoose (sub)document to a plain object — the
|
|
4
|
+
* spread-safety primitive for domain verbs that rebuild embedded lines.
|
|
5
|
+
*
|
|
6
|
+
* **The footgun this closes:** spreading a hydrated subdocument
|
|
7
|
+
* (`{ ...line, consumedQuantity: x }`) spreads its Mongoose INTERNAL
|
|
8
|
+
* properties (`$__`, `_doc`, ...), not its schema fields. The rebuilt
|
|
9
|
+
* object then casts to garbage on write — required fields land
|
|
10
|
+
* `undefined`, and because `findOneAndUpdate` does not run validators
|
|
11
|
+
* by default, the corrupt lines persist silently. This has bitten every
|
|
12
|
+
* package that maps over embedded arrays (`components`, `operations`,
|
|
13
|
+
* `revisions`) to produce an updated copy.
|
|
14
|
+
*
|
|
15
|
+
* Rule of thumb: **any `{ ...subdoc }` in a repository verb goes
|
|
16
|
+
* through `toPlain` first.**
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* const updated = lines.map((line) => ({
|
|
20
|
+
* ...toPlain(line),
|
|
21
|
+
* reservedQuantity: reserved.get(line.itemSku) ?? 0,
|
|
22
|
+
* }));
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* Non-documents pass through unchanged, so it is safe to apply
|
|
26
|
+
* defensively over values that may or may not be hydrated.
|
|
27
|
+
*/
|
|
28
|
+
function toPlain(value) {
|
|
29
|
+
return value !== null && value !== void 0 && typeof value.toObject === "function" ? value.toObject() : value;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/utils/memory-cache.ts
|
|
33
|
+
/**
|
|
34
|
+
* Creates an in-memory cache adapter
|
|
35
|
+
*
|
|
36
|
+
* Features:
|
|
37
|
+
* - Automatic TTL expiration
|
|
38
|
+
* - Pattern-based clearing (simple glob with *)
|
|
39
|
+
* - Max entries limit to prevent memory leaks
|
|
40
|
+
*
|
|
41
|
+
* @param maxEntries - Maximum cache entries before oldest are evicted (default: 1000)
|
|
42
|
+
*/
|
|
43
|
+
function createMemoryCache(maxEntries = 1e3) {
|
|
44
|
+
const cache = /* @__PURE__ */ new Map();
|
|
45
|
+
let lastCleanup = Date.now();
|
|
46
|
+
const CLEANUP_INTERVAL_MS = 6e4;
|
|
47
|
+
function cleanupIfNeeded() {
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
|
50
|
+
lastCleanup = now;
|
|
51
|
+
for (const [key, entry] of cache) if (entry.expiresAt < now) cache.delete(key);
|
|
52
|
+
}
|
|
53
|
+
function evictOldest() {
|
|
54
|
+
while (cache.size >= maxEntries) {
|
|
55
|
+
const firstKey = cache.keys().next().value;
|
|
56
|
+
if (firstKey) cache.delete(firstKey);
|
|
57
|
+
else break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
async get(key) {
|
|
62
|
+
const entry = cache.get(key);
|
|
63
|
+
if (!entry) return null;
|
|
64
|
+
if (entry.expiresAt < Date.now()) {
|
|
65
|
+
cache.delete(key);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
cache.delete(key);
|
|
69
|
+
cache.set(key, entry);
|
|
70
|
+
return entry.value;
|
|
71
|
+
},
|
|
72
|
+
async set(key, value, ttl) {
|
|
73
|
+
cache.delete(key);
|
|
74
|
+
if (cache.size >= maxEntries) {
|
|
75
|
+
cleanupIfNeeded();
|
|
76
|
+
evictOldest();
|
|
77
|
+
}
|
|
78
|
+
cache.set(key, {
|
|
79
|
+
value,
|
|
80
|
+
expiresAt: Date.now() + ttl * 1e3
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
async delete(key) {
|
|
84
|
+
cache.delete(key);
|
|
85
|
+
},
|
|
86
|
+
async clear(pattern) {
|
|
87
|
+
if (!pattern) {
|
|
88
|
+
cache.clear();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
92
|
+
const regex = new RegExp(`^${escaped}$`);
|
|
93
|
+
for (const key of cache.keys()) if (regex.test(key)) cache.delete(key);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
//#endregion
|
|
98
|
+
export { toPlain as n, createMemoryCache as t };
|
|
@@ -1,72 +1,6 @@
|
|
|
1
1
|
import { r as isObjectIdInstance } from "./id-resolution-P2OzcyRl.mjs";
|
|
2
2
|
import mongoose from "mongoose";
|
|
3
3
|
import { applyFieldRules, collectFieldsToOmit } from "@classytic/repo-core/schema";
|
|
4
|
-
//#region src/utils/memory-cache.ts
|
|
5
|
-
/**
|
|
6
|
-
* Creates an in-memory cache adapter
|
|
7
|
-
*
|
|
8
|
-
* Features:
|
|
9
|
-
* - Automatic TTL expiration
|
|
10
|
-
* - Pattern-based clearing (simple glob with *)
|
|
11
|
-
* - Max entries limit to prevent memory leaks
|
|
12
|
-
*
|
|
13
|
-
* @param maxEntries - Maximum cache entries before oldest are evicted (default: 1000)
|
|
14
|
-
*/
|
|
15
|
-
function createMemoryCache(maxEntries = 1e3) {
|
|
16
|
-
const cache = /* @__PURE__ */ new Map();
|
|
17
|
-
let lastCleanup = Date.now();
|
|
18
|
-
const CLEANUP_INTERVAL_MS = 6e4;
|
|
19
|
-
function cleanupIfNeeded() {
|
|
20
|
-
const now = Date.now();
|
|
21
|
-
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
|
22
|
-
lastCleanup = now;
|
|
23
|
-
for (const [key, entry] of cache) if (entry.expiresAt < now) cache.delete(key);
|
|
24
|
-
}
|
|
25
|
-
function evictOldest() {
|
|
26
|
-
while (cache.size >= maxEntries) {
|
|
27
|
-
const firstKey = cache.keys().next().value;
|
|
28
|
-
if (firstKey) cache.delete(firstKey);
|
|
29
|
-
else break;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return {
|
|
33
|
-
async get(key) {
|
|
34
|
-
const entry = cache.get(key);
|
|
35
|
-
if (!entry) return null;
|
|
36
|
-
if (entry.expiresAt < Date.now()) {
|
|
37
|
-
cache.delete(key);
|
|
38
|
-
return null;
|
|
39
|
-
}
|
|
40
|
-
cache.delete(key);
|
|
41
|
-
cache.set(key, entry);
|
|
42
|
-
return entry.value;
|
|
43
|
-
},
|
|
44
|
-
async set(key, value, ttl) {
|
|
45
|
-
cache.delete(key);
|
|
46
|
-
if (cache.size >= maxEntries) {
|
|
47
|
-
cleanupIfNeeded();
|
|
48
|
-
evictOldest();
|
|
49
|
-
}
|
|
50
|
-
cache.set(key, {
|
|
51
|
-
value,
|
|
52
|
-
expiresAt: Date.now() + ttl * 1e3
|
|
53
|
-
});
|
|
54
|
-
},
|
|
55
|
-
async delete(key) {
|
|
56
|
-
cache.delete(key);
|
|
57
|
-
},
|
|
58
|
-
async clear(pattern) {
|
|
59
|
-
if (!pattern) {
|
|
60
|
-
cache.clear();
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
64
|
-
const regex = new RegExp(`^${escaped}$`);
|
|
65
|
-
for (const key of cache.keys()) if (regex.test(key)) cache.delete(key);
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
//#endregion
|
|
70
4
|
//#region src/utils/mongooseToJsonSchema.ts
|
|
71
5
|
/**
|
|
72
6
|
* Mongoose → JSON Schema converter.
|
|
@@ -624,4 +558,4 @@ function buildJsonSchemaForQuery(_tree, options) {
|
|
|
624
558
|
return basePagination;
|
|
625
559
|
}
|
|
626
560
|
//#endregion
|
|
627
|
-
export { buildCrudSchemasFromMongooseSchema as n,
|
|
561
|
+
export { buildCrudSchemasFromMongooseSchema as n, buildCrudSchemasFromModel as t };
|