@sfxcode/mongocamp-server-core 2.1.0 → 2.3.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/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
- import { MongoClient, Db, Collection } from 'mongodb';
1
+ import { MongoClient, Db, Collection, Document as Document$2 } from 'mongodb';
2
+ import { StandardSchemaV1 } from '@standard-schema/spec';
3
+ export { StandardSchemaV1 } from '@standard-schema/spec';
2
4
  import * as hookable from 'hookable';
3
5
  import * as _prometheus_io_client from '@prometheus-io/client';
4
6
  import { Registry } from '@prometheus-io/client';
@@ -21,12 +23,6 @@ declare const ConfigKeys: {
21
23
  readonly ServerInterface: "SERVER_INTERFACE";
22
24
  readonly ServerPort: "SERVER_PORT";
23
25
  readonly AggregationStagesDenied: "AGGREGATION_STAGES_DENIED";
24
- readonly PluginsIgnored: "PLUGINS_IGNORED";
25
- readonly PluginsDirectory: "PLUGINS_DIRECTORY";
26
- readonly PluginsUrls: "PLUGINS_URLS";
27
- readonly PluginsModules: "PLUGINS_MODULES";
28
- readonly PluginsMavenRepositories: "PLUGINS_MAVEN_REPOSITORIES";
29
- readonly HttpClientHeaders: "HTTP_CLIENT_HEADERS";
30
26
  readonly AuthHandler: "AUTH_HANDLER";
31
27
  readonly AuthSecret: "AUTH_SECRET";
32
28
  readonly AuthApiKeyLength: "AUTH_APIKEYLENGTH";
@@ -35,6 +31,7 @@ declare const ConfigKeys: {
35
31
  readonly AuthRefreshGraceDuration: "AUTH_REFRESH_GRACE_DURATION";
36
32
  readonly AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS";
37
33
  readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
34
+ readonly WatchMaxStreams: "WATCH_MAX_STREAMS";
38
35
  readonly FilterTimeZone: "FILTER_TIME_ZONE";
39
36
  readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
40
37
  readonly JobsEnabled: "JOBS_ENABLED";
@@ -68,6 +65,7 @@ declare const ConfigKeys: {
68
65
  readonly MetricsMongoDbCommand: "METRICS_MONGODB_COMMAND";
69
66
  readonly MetricsMongoDbConnectionPool: "METRICS_MONGODB_CONNECTIONPOOL";
70
67
  readonly LoggingMetricsStep: "LOGGING_METRICS_MONGODB_STEP";
68
+ readonly LoggingMetricsRuntime: "LOGGING_METRICS_MONGODB_RUNTIME";
71
69
  readonly LoggingMetricsJvm: "LOGGING_METRICS_MONGODB_JVM";
72
70
  readonly LoggingMetricsSystem: "LOGGING_METRICS_MONGODB_SYSTEM";
73
71
  readonly LoggingMetricsMongo: "LOGGING_METRICS_MONGODB_MONGO";
@@ -150,20 +148,34 @@ declare class MongocampDatabase {
150
148
  close(): Promise<void>;
151
149
  }
152
150
 
153
- /** Body of every error response (`exception/ErrorDescription.scala`). */
151
+ /** One field of a document that is not valid: `path` in dot notation (`items.0.qty`, empty for the whole document), `[3].qty` for the fourth document of a request with several. */
152
+ interface ValidationIssue {
153
+ path: string;
154
+ message: string;
155
+ }
156
+ /** Body of every error response (`exception/ErrorDescription.scala`); `issues` only for documents that are not valid (2.3.0). */
154
157
  interface ErrorDescription {
155
158
  code: number;
156
159
  msg: string;
157
160
  additionalInfo: string;
161
+ issues?: ValidationIssue[];
162
+ /** The stored document of a version conflict (409, code 4092), as Extended JSON. */
163
+ current?: Record<string, unknown>;
158
164
  }
159
165
  /** Counterpart of `MongoCampException`: a status code plus the error code, message and additional info for the client. */
160
166
  declare class MongocampError extends Error {
161
167
  readonly status: number;
162
168
  readonly code: number;
163
169
  readonly additionalInfo: string;
164
- constructor(message: string, status: number, code?: number, additionalInfo?: string);
170
+ readonly issues?: ValidationIssue[] | undefined;
171
+ readonly current?: Record<string, unknown> | undefined;
172
+ constructor(message: string, status: number, code?: number, additionalInfo?: string, issues?: ValidationIssue[] | undefined, current?: Record<string, unknown> | undefined);
165
173
  get description(): ErrorDescription;
166
174
  static badRequest(message: string, code?: number): MongocampError;
175
+ /** 400 for documents that are not valid, with the fields in `issues` (a schema, a before-hook). */
176
+ static validation(issues: ValidationIssue[], message?: string, code?: number): MongocampError;
177
+ /** 409 for a write based on an outdated version, with the stored document (as Extended JSON) for the client to show or merge. */
178
+ static versionConflict(current: Record<string, unknown>): MongocampError;
167
179
  /** 403 and not 401: a client such as the UI clears its session on 401, but the session is fine, only this request is refused. */
168
180
  static forbidden(message: string, code?: number): MongocampError;
169
181
  static unauthorized(message?: string, code?: number): MongocampError;
@@ -410,6 +422,259 @@ declare class AuthService {
410
422
  refresh(user: UserInformation, bearer: string | undefined): Promise<LoginResult>;
411
423
  }
412
424
 
425
+ /**
426
+ * An optional part of the server that a host switches on with `server.use(...)`, typically from a Nitro plugin on the hook
427
+ * `mongocamp:ready`. `setup` starts it and answers the function that stops it (called by `server.close()`).
428
+ */
429
+ interface MongocampFeature {
430
+ name: string;
431
+ setup: (context: MongocampContext) => Promise<() => void | Promise<void>> | (() => void | Promise<void>);
432
+ }
433
+ /** Every request as a document of `<AUTH_PREFIX>request_logging`. */
434
+ declare function requestLogging(): MongocampFeature;
435
+ /** `/system/monitoring/{runtime,system,mongodb,events,prometheus}` and the snapshots of `LOGGING_METRICS_MONGODB_*`. */
436
+ declare function metrics(): MongocampFeature;
437
+
438
+ /**
439
+ * Behaviours of declared collections (2.4.0): one flag each in `defineMongocampCollection`, with working defaults; an options object
440
+ * renames the fields (dot paths for nested fields, e.g. `metaData.created`).
441
+ *
442
+ * defineMongocampCollection({ name: 'orders', schema, timestamps: true, owner: true, softDelete: true, versioned: true, audit: true })
443
+ *
444
+ * The fields a behaviour writes ("system fields") are not part of the schema: the server writes them, clients cannot, and the document
445
+ * types and the validator of MongoDB get them added.
446
+ */
447
+ /** `true` for the default name of a field, or its (dot) path. */
448
+ type FieldOption = true | string;
449
+ interface TimestampsOptions {
450
+ /** Default `createdAt`. */
451
+ createdAt?: FieldOption;
452
+ /** Default `updatedAt`. */
453
+ updatedAt?: FieldOption;
454
+ /** The user who created the document (`true`: `createdBy`); not written unless set. */
455
+ createdBy?: FieldOption;
456
+ /** The user of the last change (`true`: `updatedBy`); not written unless set. */
457
+ updatedBy?: FieldOption;
458
+ }
459
+ /** The documents a user may read when the read rule is a function: a filter combined with every read (it can only narrow). */
460
+ type ReadScope = (context: {
461
+ user: UserInformation;
462
+ collectionName: string;
463
+ }) => Document$2 | Promise<Document$2>;
464
+ interface OwnerOptions {
465
+ /** The field with the user id of the owner; default the `createdBy` field of `timestamps`, else `owner`. */
466
+ field?: string;
467
+ /** Who reads: `own` (default) the owner only, `all` everybody with the read grant, or a function. Writes are always the owner's. */
468
+ read?: 'own' | 'all' | ReadScope;
469
+ /** Administrators read and write every document (default true). */
470
+ adminBypass?: boolean;
471
+ }
472
+ interface SoftDeleteOptions {
473
+ /** Default `deletedAt`. */
474
+ field?: string;
475
+ /** Deletes soft-deleted documents for good after this many days (a TTL index); default never. */
476
+ purgeAfterDays?: number;
477
+ }
478
+ interface VersionedOptions {
479
+ /** `counter` (default): a number `_v` that every write increases; `timestamp`: the `updatedAt` field of `timestamps` is the version. */
480
+ mode?: 'counter' | 'timestamp';
481
+ /** The counter field (mode `counter`), default `_v`. */
482
+ field?: string;
483
+ /** A replace or partial update without version is refused (428) instead of overwriting (default false). */
484
+ required?: boolean;
485
+ }
486
+ interface AuditOptions {
487
+ /** How long the audit records are kept, default 365 days. */
488
+ retentionDays?: number;
489
+ }
490
+ /** The behaviour flags of a declaration. */
491
+ interface BehaviourFlags {
492
+ timestamps?: boolean | TimestampsOptions;
493
+ owner?: boolean | OwnerOptions;
494
+ softDelete?: boolean | SoftDeleteOptions;
495
+ versioned?: boolean | VersionedOptions;
496
+ audit?: boolean | AuditOptions;
497
+ /** Fields clients cannot write (server code and before-hooks can); a replace keeps their stored values. */
498
+ protectedFields?: readonly string[];
499
+ }
500
+ interface ResolvedBehaviours {
501
+ timestamps?: {
502
+ createdAt: string;
503
+ updatedAt: string;
504
+ createdBy?: string;
505
+ updatedBy?: string;
506
+ };
507
+ owner?: {
508
+ field: string;
509
+ read: 'own' | 'all' | ReadScope;
510
+ adminBypass: boolean;
511
+ };
512
+ softDelete?: {
513
+ field: string;
514
+ purgeAfterDays?: number;
515
+ };
516
+ versioned?: {
517
+ mode: 'counter' | 'timestamp';
518
+ field: string;
519
+ required: boolean;
520
+ };
521
+ audit?: {
522
+ retentionDays: number;
523
+ };
524
+ protectedFields: string[];
525
+ }
526
+ declare const BehaviourDefaults: {
527
+ readonly createdAt: "createdAt";
528
+ readonly updatedAt: "updatedAt";
529
+ readonly createdBy: "createdBy";
530
+ readonly updatedBy: "updatedBy";
531
+ readonly owner: "owner";
532
+ readonly deletedAt: "deletedAt";
533
+ readonly version: "_v";
534
+ readonly auditRetentionDays: 365;
535
+ };
536
+ /** Resolves and checks the behaviour flags of a declaration: defaults, paths, combinations. */
537
+ declare function resolveBehaviours(flags: BehaviourFlags): ResolvedBehaviours;
538
+ /** The fields the behaviours write, with the behaviour that writes them (the version of mode `timestamp` is the updatedAt field). */
539
+ declare function systemFields(behaviours: ResolvedBehaviours): Array<{
540
+ path: string;
541
+ by: string;
542
+ }>;
543
+ type NameOf<O, K extends string, D extends string> = O extends Record<K, infer V> ? (V extends string ? V : D) : D;
544
+ type OptionalNameOf<O, K extends string, D extends string> = O extends Record<K, infer V> ? (V extends string ? V : V extends true ? D : never) : never;
545
+ type Enabled<F> = F extends true ? Record<never, never> : F extends object ? F : never;
546
+ /** `{ a: { b: V } }` for the path `a.b`. */
547
+ type AtPath<P extends string, V> = P extends `${infer Head}.${infer Rest}` ? {
548
+ [K in Head]: AtPath<Rest, V>;
549
+ } : {
550
+ [K in P]: V;
551
+ };
552
+ /** `{ a: { b?: V } }` for the path `a.b`. */
553
+ type AtOptionalPath<P extends string, V> = P extends `${infer Head}.${infer Rest}` ? {
554
+ [K in Head]: AtOptionalPath<Rest, V>;
555
+ } : {
556
+ [K in P]?: V;
557
+ };
558
+ type TimestampFields<F> = [Enabled<F>] extends [never] ? unknown : AtPath<NameOf<Enabled<F>, 'createdAt', 'createdAt'>, Date> & AtPath<NameOf<Enabled<F>, 'updatedAt', 'updatedAt'>, Date> & ([OptionalNameOf<Enabled<F>, 'createdBy', 'createdBy'>] extends [never] ? unknown : AtPath<OptionalNameOf<Enabled<F>, 'createdBy', 'createdBy'>, string>) & ([OptionalNameOf<Enabled<F>, 'updatedBy', 'updatedBy'>] extends [never] ? unknown : AtPath<OptionalNameOf<Enabled<F>, 'updatedBy', 'updatedBy'>, string>);
559
+ type OwnerField<F, T> = [Enabled<F>] extends [never] ? unknown : Enabled<F> extends {
560
+ field: infer P extends string;
561
+ } ? AtPath<P, string> : [OptionalNameOf<Enabled<T>, 'createdBy', 'createdBy'>] extends [never] ? AtPath<'owner', string> : unknown;
562
+ type SoftDeleteField<F> = [Enabled<F>] extends [never] ? unknown : AtOptionalPath<NameOf<Enabled<F>, 'field', 'deletedAt'>, Date>;
563
+ type VersionField<F> = [Enabled<F>] extends [never] ? unknown : Enabled<F> extends {
564
+ mode: 'timestamp';
565
+ } ? unknown : AtPath<NameOf<Enabled<F>, 'field', '_v'>, number>;
566
+ /** The fields the behaviours of a declaration add to its documents (`unknown` without behaviours). */
567
+ type SystemFields<D> = D extends BehaviourFlags ? TimestampFields<D['timestamps']> & OwnerField<D['owner'], D['timestamps']> & SoftDeleteField<D['softDelete']> & VersionField<D['versioned']> : unknown;
568
+ /** Objects merged and shown as one type (also nested), other values as they are. */
569
+ type Merge<T> = T extends Date | ((...args: never[]) => unknown) | readonly unknown[] ? T : T extends object ? {
570
+ [K in keyof T]: Merge<T[K]>;
571
+ } : T;
572
+ /** Every field optional, also nested. */
573
+ type DeepPartial<T> = T extends Date | readonly unknown[] ? T : T extends object ? {
574
+ [K in keyof T]?: DeepPartial<T[K]>;
575
+ } : T;
576
+
577
+ /**
578
+ * The validator of MongoDB for the declared collections (2.3.0), set when the declarations are registered. The validator of a declared
579
+ * collection belongs to its declaration:
580
+ *
581
+ * - mode `off` never touches the collection;
582
+ * - a missing collection is created with the validator, an existing one gets it by `collMod` only when validator, level or action differ
583
+ * (every instance of an application runs the sync at its start, the second one changes nothing);
584
+ * - the level is `moderate`: documents that were stored before and do not match can still be changed; the action is the mode (`warn`
585
+ * logs in MongoDB, `error` refuses);
586
+ * - the validator carries a hash of its content in the `description` of its root (`[mongocamp <hash>]`): a validator whose content no
587
+ * longer matches its hash, or one without hash, was changed outside the declaration (`PATCH …/options`, the shell) and is replaced and
588
+ * reported as drift; a validator that matches its hash but not the declaration is from an older version of the declaration;
589
+ * - a failure (missing `collMod` right, a view) is logged and does not stop the start.
590
+ */
591
+ type ValidatorSyncAction = 'created' | 'unchanged' | 'replaced' | 'skipped' | 'failed';
592
+ interface ValidatorSyncResult {
593
+ collection: string;
594
+ action: ValidatorSyncAction;
595
+ /** Conversion warnings, drift and failures, also logged. */
596
+ warnings: string[];
597
+ }
598
+ declare const SyncValidationLevel = "moderate";
599
+ declare function sameValidator(a: unknown, b: unknown): boolean;
600
+ /** Sets the validator of one declared collection; never throws. */
601
+ declare function syncValidator(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<ValidatorSyncResult>;
602
+
603
+ /**
604
+ * Declared collections (2.3.0): a collection with a schema of any Standard Schema library (Zod 4, Valibot, ArkType, ...). One declaration
605
+ * gives the TypeScript type of its documents, the validation of the documents written through the API and the validator of MongoDB
606
+ * (`validation`). A host registers its declarations with `server.use(collections([...]))`; the Nuxt module does that for the files in
607
+ * `server/mongocamp/`.
608
+ *
609
+ * export default defineMongocampCollection({
610
+ * name: 'orders',
611
+ * schema: z.object({ customer: z.string(), qty: z.int().min(1) }),
612
+ * })
613
+ */
614
+ /**
615
+ * What a declaration does with documents that do not match its schema: `off` nothing, `warn` logs them but writes them (and the validator
616
+ * of MongoDB only warns), `error` refuses them (400, and MongoDB refuses them from every other client too).
617
+ */
618
+ type ValidationMode = 'off' | 'warn' | 'error';
619
+ declare const DefaultValidationMode: ValidationMode;
620
+ /**
621
+ * A declared collection. Behaviours (2.4.0) are flags of the same object: `timestamps`, `owner`, `softDelete`, `versioned`, `audit`,
622
+ * `protectedFields` (see `BehaviourFlags`).
623
+ */
624
+ interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSchemaV1> extends BehaviourFlags {
625
+ /** The name of the collection, without database. */
626
+ name: string;
627
+ /** The database of the collection, the default database of the server when omitted. */
628
+ database?: string;
629
+ /** The schema of the documents as they are stored, with the values of the driver (`ObjectId`, `Date`, ...). */
630
+ schema: S;
631
+ /** Default `warn`. */
632
+ validation?: ValidationMode;
633
+ /** A `$jsonSchema` validator for MongoDB that replaces the one converted from the schema (for schemas without JSON Schema form). */
634
+ validator?: Document$2;
635
+ /** Where the declaration comes from (a file), for the messages; set by the Nuxt module. */
636
+ source?: string;
637
+ }
638
+ /** The type of the documents of a declaration, with the fields of its behaviours: `InferDocument<typeof orders>`. */
639
+ type InferDocument<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferOutput<D['schema']> : Merge<StandardSchemaV1.InferOutput<D['schema']> & SystemFields<D>>;
640
+ /**
641
+ * The input type of the documents of a declaration (before defaults and transforms of the schema). The fields of behaviours are optional:
642
+ * the server writes them and ignores what a client sends, so a document that was read can be sent back as it is.
643
+ */
644
+ type InferDocumentInput<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferInput<D['schema']> : Merge<StandardSchemaV1.InferInput<D['schema']> & DeepPartial<SystemFields<D>>>;
645
+ /** Declares a collection; checks the declaration and keeps the types of its schema and its behaviours for `InferDocument`. */
646
+ declare function defineMongocampCollection<const D extends MongocampCollectionDefinition>(definition: D): D;
647
+ /** A registered declaration with its database resolved. */
648
+ interface DeclaredCollection {
649
+ definition: MongocampCollectionDefinition;
650
+ databaseName: string;
651
+ validation: ValidationMode;
652
+ /** The behaviours of the declaration with their defaults (2.4.0). */
653
+ behaviours: ResolvedBehaviours;
654
+ /** What the start did with the validator of MongoDB (`collections()` feature). */
655
+ sync?: ValidatorSyncResult;
656
+ }
657
+ /** The declarations of a server by database and collection; `context.collections`. */
658
+ declare class CollectionRegistry {
659
+ private readonly entries;
660
+ private static key;
661
+ /** The declaration of a collection, by its database and name. */
662
+ find(databaseName: string, name: string): DeclaredCollection | undefined;
663
+ /** The declaration of a collection as the routes name it (`orders`, `otherdb:orders`). */
664
+ resolve(context: Pick<MongocampContext, 'database'>, collection: string): DeclaredCollection | undefined;
665
+ get size(): number;
666
+ all(): DeclaredCollection[];
667
+ /** Adds declarations, all or none (a collection that is declared twice is an error); the returned function removes them. */
668
+ add(declared: DeclaredCollection[]): () => void;
669
+ }
670
+ /**
671
+ * Registers declared collections in the server (`server.use(collections([orders, customers]))`), sets their validator in MongoDB
672
+ * (`syncValidator`, awaited) and validates the documents written to them through the API (see `ValidationMode`). Several calls with
673
+ * different declarations add up; a collection declared twice stops the feature. Stopped by `server.close()`, which removes the
674
+ * declarations and their validation (the validators stay in MongoDB).
675
+ */
676
+ declare function collections(definitions: MongocampCollectionDefinition[]): MongocampFeature;
677
+
413
678
  interface components {
414
679
  schemas: {
415
680
  /** BucketInformation */
@@ -588,6 +853,18 @@ interface components {
588
853
  code: number;
589
854
  msg: string;
590
855
  additionalInfo: string;
856
+ /** @description The fields of a document that is not valid (a schema, a before-hook or the validator of the collection). Only set for these errors. */
857
+ issues?: components["schemas"]["ValidationIssue"][];
858
+ /** @description The stored document of a version conflict (409, code 4092, 2.4.0), as Extended JSON: show it or merge with it, then send the change again with its version. */
859
+ current?: {
860
+ [key: string]: unknown;
861
+ };
862
+ };
863
+ /** ValidationIssue */
864
+ ValidationIssue: {
865
+ /** @description The field in dot notation (`items.0.qty`), empty for the whole document; `[3].qty` for the fourth document of a request with several. */
866
+ path: string;
867
+ message: string;
591
868
  };
592
869
  /** FieldInfo */
593
870
  FieldInfo: {
@@ -624,7 +901,8 @@ interface components {
624
901
  read: boolean;
625
902
  write: boolean;
626
903
  administrate: boolean;
627
- grantType: string;
904
+ /** @enum {string} */
905
+ grantType: "COLLECTION" | "BUCKET" | "BUCKET_META";
628
906
  };
629
907
  /** ImportResponse */
630
908
  ImportResponse: {
@@ -803,6 +1081,8 @@ interface components {
803
1081
  MongoAggregateRequest: {
804
1082
  pipeline?: components["schemas"]["PipelineStage"][];
805
1083
  allowDiskUse: boolean;
1084
+ /** @description 2.1.0: the Lucene filter of the list as first stage, like the query parameter filter (send one of both; no URL limit in the body) */
1085
+ filter?: string;
806
1086
  };
807
1087
  /** MongoCampConfiguration */
808
1088
  MongoCampConfiguration: {
@@ -884,6 +1164,85 @@ interface components {
884
1164
  isAdmin: boolean;
885
1165
  collectionGrants?: components["schemas"]["Grant"][];
886
1166
  };
1167
+ /** SuggestedValidator */
1168
+ SuggestedValidator: {
1169
+ /** @description The validator: an object with the key $jsonSchema. */
1170
+ validator: {
1171
+ [key: string]: unknown;
1172
+ };
1173
+ /**
1174
+ * Format: int64
1175
+ * @description The number of documents of the collection.
1176
+ */
1177
+ count: number;
1178
+ /**
1179
+ * Format: int64
1180
+ * @description The number of documents the suggestion is made of.
1181
+ */
1182
+ sample: number;
1183
+ warnings: string[];
1184
+ };
1185
+ /** AuditEntry */
1186
+ AuditEntry: {
1187
+ collection: string;
1188
+ database: string;
1189
+ /** @description The _id of the document; absent on a summary record. */
1190
+ documentId?: unknown;
1191
+ /** @enum {string} */
1192
+ operation: "insert" | "replace" | "update" | "delete" | "softDelete" | "restore";
1193
+ user: string;
1194
+ /** @description The time (Extended JSON date). */
1195
+ at: {
1196
+ [key: string]: unknown;
1197
+ };
1198
+ before?: {
1199
+ [key: string]: unknown;
1200
+ };
1201
+ after?: {
1202
+ [key: string]: unknown;
1203
+ };
1204
+ /** @description A write of many documents: count and recorded. */
1205
+ summary?: {
1206
+ [key: string]: unknown;
1207
+ };
1208
+ expiresAt?: {
1209
+ [key: string]: unknown;
1210
+ };
1211
+ };
1212
+ /** CollectionDeclaration */
1213
+ CollectionDeclaration: {
1214
+ name: string;
1215
+ database: string;
1216
+ /** @enum {string} */
1217
+ validation: "off" | "warn" | "error";
1218
+ /** @description The fields the server writes (timestamps, owner, version, deleted mark); clients do not send them. */
1219
+ systemFields: string[];
1220
+ protectedFields: string[];
1221
+ timestamps?: {
1222
+ createdAt: string;
1223
+ updatedAt: string;
1224
+ createdBy?: string;
1225
+ updatedBy?: string;
1226
+ };
1227
+ owner?: {
1228
+ field: string;
1229
+ /** @enum {string} */
1230
+ read: "own" | "all" | "custom";
1231
+ };
1232
+ softDelete?: {
1233
+ field: string;
1234
+ purgeAfterDays?: number;
1235
+ };
1236
+ versioned?: {
1237
+ /** @enum {string} */
1238
+ mode: "counter" | "timestamp";
1239
+ field: string;
1240
+ required: boolean;
1241
+ };
1242
+ audit?: {
1243
+ retentionDays: number;
1244
+ };
1245
+ };
887
1246
  /** SchemaAnalysis */
888
1247
  SchemaAnalysis: {
889
1248
  /** Format: int64 */
@@ -913,6 +1272,20 @@ interface components {
913
1272
  /** Format: double */
914
1273
  percentageOfParent: number;
915
1274
  };
1275
+ /** ExportRequest */
1276
+ ExportRequest: {
1277
+ /** @description Lucene filter like on the list of documents, by default all documents */
1278
+ filter?: string;
1279
+ sort?: string[];
1280
+ projection?: string[];
1281
+ /** Format: int32 */
1282
+ limit?: number;
1283
+ };
1284
+ /** CountRequest */
1285
+ CountRequest: {
1286
+ /** @description Lucene filter like on the list of documents, by default all documents */
1287
+ filter?: string;
1288
+ };
916
1289
  /** SearchRequest */
917
1290
  SearchRequest: {
918
1291
  filter?: string;
@@ -921,17 +1294,6 @@ interface components {
921
1294
  };
922
1295
  /** SettingsResponse */
923
1296
  SettingsResponse: {
924
- routesPlugins?: string[];
925
- /**
926
- * @deprecated
927
- * @description Deprecated: plugin system of the Scala server, always [GridFsFileAdapter]
928
- */
929
- filePlugins?: string[];
930
- /**
931
- * @deprecated
932
- * @description Deprecated: plugin system of the Scala server, the value of PLUGINS_IGNORED
933
- */
934
- ignoredPlugins?: string[];
935
1297
  configurations: components["schemas"]["Map_Any"];
936
1298
  };
937
1299
  /** SystemInfo */
@@ -953,8 +1315,8 @@ interface components {
953
1315
  filename?: string;
954
1316
  metadata?: components["schemas"]["Map_Any"];
955
1317
  };
956
- /** UpdateRequest */
957
- UpdateRequest: {
1318
+ /** UpdateManyRequest */
1319
+ UpdateManyRequest: {
958
1320
  document: components["schemas"]["Map_Any"];
959
1321
  filter: components["schemas"]["Map_Any"];
960
1322
  };
@@ -1022,7 +1384,7 @@ interface EventBase {
1022
1384
  type ByUser<T = object> = {
1023
1385
  user: UserInformation;
1024
1386
  } & T;
1025
- type Document = Record<string, unknown>;
1387
+ type Document$1 = Record<string, unknown>;
1026
1388
  /** The fields of `HttpRequestStartEvent` / `HttpRequestCompletedEvent`. */
1027
1389
  interface HttpRequestFields {
1028
1390
  requestId: string;
@@ -1101,20 +1463,32 @@ interface MongocampEvents {
1101
1463
  collectionName: string;
1102
1464
  newCollectionName: string;
1103
1465
  }>;
1466
+ /** `documents` (2.4.0): the inserted documents of an insert or insertMany (not of an import), read only by listeners that need them. */
1104
1467
  'document:create': ByUser<{
1105
1468
  collectionName: string;
1106
1469
  insertResponse: Schemas['InsertResponse'];
1470
+ documents?: Document$1[];
1107
1471
  }>;
1108
1472
  /** `oldValues` are read only when a listener is registered for the hook. */
1473
+ /** `source` (2.4.0): a replace, a partial update or an update of many documents. */
1109
1474
  'document:update': ByUser<{
1110
1475
  collectionName: string;
1111
1476
  updateResponse: Schemas['UpdateResponse'];
1112
- oldValues: Document[];
1477
+ oldValues: Document$1[];
1478
+ source?: 'replace' | 'update' | 'updateMany';
1113
1479
  }>;
1480
+ /** `softDeleted` (2.4.0): a before-hook turned the delete into an update (`instead`), the documents are still stored. */
1114
1481
  'document:delete': ByUser<{
1115
1482
  collectionName: string;
1116
1483
  deleteResponse: Schemas['DeleteResponse'];
1117
- oldValues: Document[];
1484
+ oldValues: Document$1[];
1485
+ softDeleted?: boolean;
1486
+ }>;
1487
+ /** A soft-deleted document was restored (2.4.0); `oldValues` as for updates. */
1488
+ 'document:restore': ByUser<{
1489
+ collectionName: string;
1490
+ updateResponse: Schemas['UpdateResponse'];
1491
+ oldValues: Document$1[];
1118
1492
  }>;
1119
1493
  'bucket:drop': ByUser<{
1120
1494
  bucketName: string;
@@ -1163,18 +1537,38 @@ type HookMap = {
1163
1537
  };
1164
1538
  /** Sees every published event, also without a listener; it does not count as listener, so no expensive payload is read for it. */
1165
1539
  type EventObserver = (name: EventName, payload: MongocampEvents[EventName]) => void;
1540
+ /**
1541
+ * A hook system of the host that receives the events, e.g. the hooks of a Nitro app (`mongocamp:document:update`). `listens` tells whether
1542
+ * the host has a listener for an event, so that its expensive parts are only read when somebody waits for them.
1543
+ */
1544
+ interface EventTarget {
1545
+ listens: (name: EventName) => boolean;
1546
+ call: (name: EventName, event: MongocampEvent<EventName>) => unknown;
1547
+ }
1166
1548
  declare class EventBus {
1167
1549
  private readonly log;
1168
1550
  readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
1169
1551
  private readonly listeners;
1552
+ /** Listeners for some collections only (2.4.0): they make expensive payloads be read for these collections only. */
1553
+ private readonly scoped;
1170
1554
  private readonly observers;
1555
+ private readonly targets;
1171
1556
  constructor(log?: (message: string, error: unknown) => void);
1172
- /** Registers a listener; the returned function removes it. */
1173
- on<N extends EventName>(name: N, listener: EventListener<N>): () => void;
1557
+ /**
1558
+ * Registers a listener; the returned function removes it. With `collections` (2.4.0) it only gets the events of the collections the
1559
+ * function accepts, and the expensive parts of an event (old values) are only read for them.
1560
+ */
1561
+ on<N extends EventName>(name: N, listener: EventListener<N>, options?: {
1562
+ collections?: (collectionName: string) => boolean;
1563
+ }): () => void;
1564
+ private hasListener;
1174
1565
  /** Registers an observer (metrics); the returned function removes it. */
1175
1566
  observe(observer: EventObserver): () => void;
1567
+ /** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
1568
+ forward(target: EventTarget): () => void;
1569
+ private targetsFor;
1176
1570
  /** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
1177
- has(name: EventName): boolean;
1571
+ has(name: EventName, collectionName?: string): boolean;
1178
1572
  /** Sends an event without waiting for the listeners; a failure of a listener is logged. */
1179
1573
  publish<N extends EventName>(name: N, payload: MongocampEvents[N]): void;
1180
1574
  }
@@ -1219,6 +1613,116 @@ declare class ConfigPersistence {
1219
1613
  close(): void;
1220
1614
  }
1221
1615
 
1616
+ /**
1617
+ * Before-hooks of the document writes. Unlike the events of the `EventBus` (notifications after a write, not awaited, failures only logged),
1618
+ * an interceptor runs before the write, is awaited, and may change the write or refuse it:
1619
+ *
1620
+ * - the listeners run one after another in the order they were registered, each one sees the changes of the ones before;
1621
+ * - a listener changes the write in place on the payload (`event.documents.push(...)`, `event.filter = {...}`); the route reads the payload
1622
+ * back after all listeners ran;
1623
+ * - a listener refuses the write by throwing: a `MongocampError` is answered with its status (e.g. `MongocampError.badRequest(...)`), any
1624
+ * other error with 500 (and logged). Nothing is written then;
1625
+ * - the stages (`InterceptorStage`) order the interceptors of different purposes: `guard` → `change` → hooks of the host → `validate` →
1626
+ * `system`; within a stage the order of registration counts.
1627
+ */
1628
+ type Document = Record<string, unknown>;
1629
+ /** The fields of every interceptor payload. */
1630
+ interface InterceptorBase {
1631
+ user: UserInformation;
1632
+ /** The collection as given in the path (`orders`, or `otherdb:orders` for another database). */
1633
+ collectionName: string;
1634
+ /** The database of the collection, resolved (the default database when the path names none). */
1635
+ databaseName: string;
1636
+ /** The user has an administrator role (2.4.0; set by the routes, absent in payloads built elsewhere). */
1637
+ isAdmin?: boolean;
1638
+ }
1639
+ interface WriteInterceptorPayloads {
1640
+ /** Documents to insert: one for `PUT …/documents`, all of the request for `insertMany`, one batch for an import. */
1641
+ 'document:beforeInsert': InterceptorBase & {
1642
+ documents: Document[];
1643
+ source: 'insert' | 'insertMany' | 'import';
1644
+ /** For an import the line numbers of the documents (1-based); not set for the other sources, where the position is the index. */
1645
+ lines?: number[];
1646
+ };
1647
+ /**
1648
+ * A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.4.0): called by the route when the
1649
+ * write matched nothing, before it answers 404 — a hook that narrowed the filter (e.g. by a version) can explain why by throwing (409).
1650
+ */
1651
+ 'document:beforeReplace': InterceptorBase & {
1652
+ filter: Document;
1653
+ document: Document;
1654
+ onNoMatch?: () => void | Promise<void>;
1655
+ };
1656
+ /** An operator update (`$set`, ...) for the documents matched by `filter`; `many` for `updateMany`. `onNoMatch` as for a replace (single). */
1657
+ 'document:beforeUpdate': InterceptorBase & {
1658
+ filter: Document;
1659
+ update: Document;
1660
+ many: boolean;
1661
+ onNoMatch?: () => void | Promise<void>;
1662
+ };
1663
+ /**
1664
+ * A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.4.0) turns the delete into this
1665
+ * update (e.g. a deleted mark); the request is answered as a delete with the number of matched documents.
1666
+ */
1667
+ 'document:beforeDelete': InterceptorBase & {
1668
+ filter: Document;
1669
+ many: boolean;
1670
+ instead?: {
1671
+ update: Document;
1672
+ };
1673
+ };
1674
+ /**
1675
+ * Every read of documents (2.4.0) and the target of every update, replace and delete: a hook narrows what the request may see by pushing
1676
+ * conditions to `scopes` (`event.scopes.push({ tenant: 'a' })`); they are combined with the filter of the client by `$and`, so no client
1677
+ * filter widens them. `filter` is the filter of the client (to look at, changing it has no effect). `withDeleted`: an administrator asked
1678
+ * for soft-deleted documents too (`withDeleted=true`).
1679
+ */
1680
+ 'document:beforeRead': InterceptorBase & {
1681
+ filter: Document;
1682
+ operation: ReadOperation;
1683
+ scopes: Document[];
1684
+ withDeleted: boolean;
1685
+ };
1686
+ }
1687
+ /** The kind of request a `document:beforeRead` scopes; `write` for the target of an update, replace or delete. */
1688
+ type ReadOperation = 'list' | 'search' | 'count' | 'get' | 'export' | 'distinct' | 'aggregate' | 'schema' | 'write' | 'restore' | 'watch';
1689
+ type InterceptorName = keyof WriteInterceptorPayloads;
1690
+ type WriteInterceptor<N extends InterceptorName> = (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
1691
+ /**
1692
+ * The order of the interceptors of one write: `guard` (the server's own checks of what a client may write, e.g. protected fields), `change`
1693
+ * (default: hooks that change or refuse the write), then the hooks of the host (Nitro), `validate` (the schemas of declared collections)
1694
+ * and `system` (fields that the server writes after the validation, e.g. timestamps).
1695
+ */
1696
+ type InterceptorStage = 'guard' | 'change' | 'validate' | 'system';
1697
+ /**
1698
+ * A hook system of the host that runs the interceptors too, e.g. the hooks of a Nitro app (`mongocamp:document:beforeInsert`). `listens`
1699
+ * is asked on every write, so hooks that the host adds later count right away; `call` is awaited.
1700
+ */
1701
+ interface InterceptorTarget {
1702
+ listens: (name: InterceptorName) => boolean;
1703
+ call: (name: InterceptorName, payload: WriteInterceptorPayloads[InterceptorName]) => unknown;
1704
+ }
1705
+ declare class WriteInterceptors {
1706
+ private readonly stages;
1707
+ private readonly targets;
1708
+ /** Registers an interceptor (stage `change` unless given); the returned function removes it. */
1709
+ on<N extends InterceptorName>(name: N, interceptor: WriteInterceptor<N>, options?: {
1710
+ stage?: InterceptorStage;
1711
+ }): () => void;
1712
+ /** Runs the interceptors in a hook system of the host as well (`connectHooks`), after the stages `guard` and `change`; the returned function stops it. */
1713
+ forward(target: InterceptorTarget): () => void;
1714
+ private targetsFor;
1715
+ private registered;
1716
+ /** Whether an interceptor is registered (here or in a host), so that a route builds no payload when nobody waits for it. */
1717
+ has(name: InterceptorName): boolean;
1718
+ private runStage;
1719
+ /**
1720
+ * Runs the interceptors stage by stage, one after another, and answers the payload with their changes. Rejects with the error of the first
1721
+ * interceptor that throws; the later ones do not run.
1722
+ */
1723
+ run<N extends InterceptorName>(name: N, payload: WriteInterceptorPayloads[N]): Promise<WriteInterceptorPayloads[N]>;
1724
+ }
1725
+
1222
1726
  /**
1223
1727
  * Jobs (`JobPlugin.scala`, `JobRoutes.scala`) on croner. A job is a document `JobConfig` in `<AUTH_PREFIX>jobs`; its `className` names a
1224
1728
  * handler of the registry (the Scala server loaded JVM classes). Cron expressions use the syntax of croner: 5, 6 or 7 fields (seconds and
@@ -1283,12 +1787,13 @@ declare class JobScheduler {
1283
1787
 
1284
1788
  /**
1285
1789
  * `mongocamp-plugin-micrometer` on `@prometheus-io/client` (the successor of prom-client): four categories with the endpoints
1286
- * `/system/monitoring/{jvm,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1790
+ * `/system/monitoring/{runtime,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1287
1791
  * snapshots in the collections `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` (the document shape of micrometer-mongodb).
1288
1792
  *
1289
- * The category `jvm` keeps its name for the clients and holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles.
1793
+ * The category `runtime` holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles. Until 2.1.0 it was named `jvm`;
1794
+ * `/system/monitoring/jvm` and `LOGGING_METRICS_MONGODB_JVM` stay as deprecated aliases until 3.0.
1290
1795
  */
1291
- type MetricCategory = 'jvm' | 'system' | 'mongodb' | 'events';
1796
+ type MetricCategory = 'runtime' | 'system' | 'mongodb' | 'events';
1292
1797
  interface Measurement {
1293
1798
  statisticType: string;
1294
1799
  value: number;
@@ -1356,6 +1861,10 @@ interface MongocampContext {
1356
1861
  auth: AuthService;
1357
1862
  configurations: ConfigPersistence;
1358
1863
  events: EventBus;
1864
+ /** The before-hooks of the document writes (awaited, may change or refuse a write). */
1865
+ interceptors: WriteInterceptors;
1866
+ /** The declared collections (`server.use(collections([...]))`), empty without. */
1867
+ collections: CollectionRegistry;
1359
1868
  jobs: JobScheduler;
1360
1869
  /** The metrics, with `METRICS_ENABLED` only. */
1361
1870
  metrics?: MongocampMetrics;
@@ -1363,8 +1872,6 @@ interface MongocampContext {
1363
1872
  systemInfo: InfoCache<SystemInfo>;
1364
1873
  /** Stops the process (`DELETE /system`); not set when the server is embedded in an application. */
1365
1874
  shutdown?: (force: boolean) => void | Promise<void>;
1366
- /** The names of the route groups (`SettingsResponse.routesPlugins`). */
1367
- routeGroups: string[];
1368
1875
  }
1369
1876
 
1370
1877
  interface MongocampServerOptions extends DatabaseOptions {
@@ -1381,12 +1888,21 @@ interface MongocampServerOptions extends DatabaseOptions {
1381
1888
  shutdown?: (force: boolean) => void | Promise<void>;
1382
1889
  /** Interval in milliseconds to read configuration changes of other instances, `false` for none. Default one minute. */
1383
1890
  configRefresh?: number | false;
1891
+ /**
1892
+ * Deprecated (removed in 3.0): switches request logging and metrics on from `REQUESTLOGGING_ENABLED` / `METRICS_ENABLED` (default true).
1893
+ * A host that adds them itself with `server.use(requestLogging())` / `server.use(metrics())` passes false.
1894
+ */
1895
+ featureSwitches?: boolean;
1384
1896
  /** The log of the server (start, failed jobs and writes, 5xx errors); `console` when omitted. */
1385
1897
  logger?: MongocampLogger;
1386
1898
  /** Listeners of the events, registered before the start (`server:started`); later ones with `server.events.on(...)`. */
1387
1899
  on?: {
1388
1900
  [N in EventName]?: EventListener<N>;
1389
1901
  };
1902
+ /** Before-hooks of the document writes, registered before the start; later ones with `server.interceptors.on(...)`. */
1903
+ intercept?: {
1904
+ [N in InterceptorName]?: WriteInterceptor<N>;
1905
+ };
1390
1906
  /**
1391
1907
  * The jobs: `false` keeps the scheduler of this instance from running the jobs on their schedule (several instances of an application
1392
1908
  * need only one that runs them; the configuration `JOBS_ENABLED=false` does the same); `handlers` adds job handlers by class name (later
@@ -1417,11 +1933,21 @@ interface MongocampServer {
1417
1933
  routes: () => string[];
1418
1934
  /** The events of the server (`hookable`): `server.events.on('document:create', event => ...)`. */
1419
1935
  events: EventBus;
1936
+ /**
1937
+ * The before-hooks of the document writes, awaited and able to change or refuse a write:
1938
+ * `server.interceptors.on('document:beforeInsert', ({ documents }) => ...)`.
1939
+ */
1940
+ interceptors: WriteInterceptors;
1420
1941
  /**
1421
1942
  * Adds a job handler after the start: the stored jobs with this `className` are scheduled right away. Returns a function that removes the
1422
1943
  * handler again. A Nuxt application registers its handlers this way in a Nitro plugin (`(await useMongocampCore()).registerJobHandler(...)`).
1423
1944
  */
1424
1945
  registerJobHandler: (className: string, handler: JobHandler) => () => void;
1946
+ /**
1947
+ * Switches an optional part on (`requestLogging()`, `metrics()`), typically from a Nitro plugin on `mongocamp:ready`. A feature with the
1948
+ * same name is used once; it is stopped by `close`.
1949
+ */
1950
+ use: (feature: MongocampFeature) => Promise<void>;
1425
1951
  close: () => Promise<void>;
1426
1952
  }
1427
1953
  /** Creates and connects a MongoCamp server. */
@@ -1458,11 +1984,19 @@ declare const ErrorCodes: {
1458
1984
  readonly invalidCollectionName: 4007;
1459
1985
  readonly invalidImportLine: 4008;
1460
1986
  readonly invalidCollectionOptions: 4009;
1987
+ /** A document that a schema or a before-hook refuses; `ErrorDescription.issues` names the fields (the validator of MongoDB answers 121). */
1988
+ readonly validationFailed: 4010;
1461
1989
  readonly collectionExists: 4091;
1990
+ /** A write based on an outdated version of a versioned document (2.4.0); `ErrorDescription.current` is the stored document. */
1991
+ readonly versionConflict: 4092;
1992
+ /** A versioned collection with `required: true` got a write without version (2.4.0). */
1993
+ readonly versionRequired: 4281;
1462
1994
  readonly badInsertRequest: 4401;
1463
1995
  readonly idMissingForReplace: 4402;
1464
1996
  readonly authMethodNotImplemented: 5001;
1465
1997
  readonly mvnRepositoryConfigurationInvalid: 5002;
1998
+ /** Live updates need change streams: a replica set or a sharded cluster (2.4.0). */
1999
+ readonly changeStreamsUnsupported: 5011;
1466
2000
  readonly unauthorizedUser: 4011;
1467
2001
  readonly unauthorizedUserForOtherUser: 4012;
1468
2002
  readonly forbiddenStage: 4031;
@@ -1543,6 +2077,7 @@ type LuceneQuery = {
1543
2077
  type: 'term';
1544
2078
  field: string;
1545
2079
  text: string;
2080
+ quoted?: boolean;
1546
2081
  } | {
1547
2082
  type: 'range';
1548
2083
  field: string;
@@ -1611,5 +2146,267 @@ declare function luceneToFilter(input: string, defaultField: string, options?: C
1611
2146
  */
1612
2147
  declare function filterParameter(input: string | null | undefined, options?: ConvertOptions, parameter?: string): Record<string, unknown>;
1613
2148
 
1614
- export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, stringifyJson };
1615
- export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, ExtendedJsonMode, FetchOptions, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, RequestLog, VersionInfo };
2149
+ /**
2150
+ * The `$jsonSchema` validator of MongoDB for a declared collection (2.3.0), converted from the JSON Schema that its Standard Schema library
2151
+ * exports (Standard JSON Schema, `~standard.jsonSchema.output`): the stored shape of the documents.
2152
+ *
2153
+ * MongoDB knows draft 4 with `bsonType` and without some keywords, and the documents hold BSON values:
2154
+ * - `integer` is `int`, `long` or a whole `double` (the API stores whole numbers as `long`, the driver writes the numbers of a schema as
2155
+ * `int`, or as `double` outside the int32 range), `number` any of `double`, `int`, `long`, `decimal`;
2156
+ * - dates and ObjectIds have no JSON Schema form: the libraries are asked to mark them (`x-bsonType`, Zod `override`, ArkType `fallback`),
2157
+ * Zod is asked not to throw on other values without JSON form (`unrepresentable: 'any'`, no constraint then);
2158
+ * - `$ref`s are inlined, `const` becomes `enum`, the numeric `exclusiveMinimum` of newer drafts the boolean of draft 4, `prefixItems` the
2159
+ * `items` list; annotations (`$schema`, `default`, `format`, `examples`, ...) are dropped, other keywords MongoDB does not know are
2160
+ * dropped with a warning (the validator is then looser than the schema);
2161
+ * - `_id` is always allowed, also with `additionalProperties: false`.
2162
+ *
2163
+ * A declaration with `validator` uses that instead; a schema without JSON Schema export (e.g. Valibot without its converter) gets none.
2164
+ */
2165
+ interface ConversionResult {
2166
+ /** The `$jsonSchema` (the value, without the `$jsonSchema` key); undefined when the schema has no JSON Schema form. */
2167
+ jsonSchema: Document$2 | undefined;
2168
+ warnings: string[];
2169
+ }
2170
+ type Schema = Record<string, unknown>;
2171
+ interface ZodOverrideContext {
2172
+ zodSchema?: {
2173
+ _zod?: {
2174
+ def?: {
2175
+ type?: string;
2176
+ };
2177
+ bag?: {
2178
+ Class?: {
2179
+ name?: string;
2180
+ };
2181
+ };
2182
+ };
2183
+ };
2184
+ jsonSchema: Schema;
2185
+ }
2186
+ interface ArkTypeFallbackContext {
2187
+ code?: string;
2188
+ base?: Schema;
2189
+ proto?: {
2190
+ name?: string;
2191
+ };
2192
+ }
2193
+ /** The options of the libraries that mark the BSON values without JSON form; every library reads only its own. */
2194
+ declare const bsonMarkerOptions: {
2195
+ unrepresentable: string;
2196
+ override: (context: ZodOverrideContext) => void;
2197
+ fallback: (context: ArkTypeFallbackContext) => Schema;
2198
+ };
2199
+ /**
2200
+ * The `$jsonSchema` of a declaration: its `validator`, else converted from the JSON Schema of its schema; with the fields of its behaviours
2201
+ * added (2.4.0, see `withSystemFields`) unless `systemFields: false`.
2202
+ */
2203
+ declare function validatorOf(definition: MongocampCollectionDefinition, options?: {
2204
+ systemFields?: boolean;
2205
+ }): ConversionResult;
2206
+ /**
2207
+ * A copy of a `$jsonSchema` with the fields of the behaviours as typed properties (nested objects for dot paths), so a validator with
2208
+ * `additionalProperties: false` lets them through and refuses wrong types. They are not required: documents stored before the behaviour was
2209
+ * switched on stay valid.
2210
+ */
2211
+ declare function withSystemFields(jsonSchema: Document$2, behaviours: ResolvedBehaviours): Document$2;
2212
+ /** Converts a JSON Schema (draft 2020-12 or 07) of the documents to a `$jsonSchema` of MongoDB. */
2213
+ declare function toMongoJsonSchema(root: Record<string, unknown>): ConversionResult;
2214
+
2215
+ /**
2216
+ * What clients may not write (2.4.0): the fields of behaviours (timestamps, owner, version, deleted mark) and the `protectedFields` of a
2217
+ * declaration. The guard runs first (stage `guard`), so before-hooks and Nitro hooks of the application can still set protected fields;
2218
+ * writes with the driver (`useMongocampCore()`, scripts) are not checked at all.
2219
+ *
2220
+ * - inserts: the fields are removed from the documents;
2221
+ * - replaces: the stored values are kept (protected fields at once, so the schema sees them; fields of behaviours again after the
2222
+ * validation, which may strip fields the schema does not know);
2223
+ * - updates: operators on the fields or inside them are removed; an object set on a parent of a field of a behaviour is set field by field
2224
+ * (`metaData: {...}` → `metaData.tags`, ...), so the fields of the behaviour stay.
2225
+ */
2226
+ /** The paths of a declaration that clients cannot write: fields of behaviours first, then the protected fields. */
2227
+ declare function guardedPaths(behaviours: ResolvedBehaviours): {
2228
+ system: string[];
2229
+ protected: string[];
2230
+ };
2231
+ /** A copy of a document without the guarded paths (nested objects copied where a path goes through them). */
2232
+ declare function stripDocument(document: Document$2, paths: readonly string[]): Document$2;
2233
+ /**
2234
+ * An update without the guarded paths: keys at or below a guarded path are removed; a `$set` of an object on a parent of a field of a
2235
+ * behaviour is set field by field, without the guarded fields; other operators on such a parent are removed.
2236
+ */
2237
+ declare function stripUpdate(update: Document$2, guarded: readonly string[], system: readonly string[]): Document$2;
2238
+
2239
+ /**
2240
+ * The scope of a read (2.4.0): the conditions of the `document:beforeRead` hooks (soft delete, owner, tenancy of an application) combined
2241
+ * with the filter of the client. Every route that reads documents, and every update, replace and delete for its target, goes through it;
2242
+ * without a hook nothing is done.
2243
+ */
2244
+ /** The filter with the scopes, combined by `$and`; empty parts are left out. */
2245
+ declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]): Document$2;
2246
+ /** The filter of a request with the scopes of the hooks. */
2247
+ declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
2248
+ interface ScopeOptions {
2249
+ /** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
2250
+ withDeleted?: boolean;
2251
+ }
2252
+ /** `withDeleted=true` of a read route (2.4.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
2253
+ declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
2254
+
2255
+ /**
2256
+ * The behaviour `softDelete` (2.4.0): a delete sets the deleted mark (`deletedAt`) instead of removing the document, every read hides
2257
+ * marked documents (`document:beforeRead`), an administrator sees them with `withDeleted=true`, `POST …/documents/{id}/restore` removes
2258
+ * the mark, and `purgeAfterDays` removes marked documents for good (a TTL index).
2259
+ */
2260
+ type SoftDelete = NonNullable<ResolvedBehaviours['softDelete']>;
2261
+ /** The condition of the documents that are not deleted. */
2262
+ declare function notDeleted(softDelete: SoftDelete): Document$2;
2263
+ /** The update that restores a document: the mark removed, the change fields of `timestamps` set. */
2264
+ declare function restoreUpdate(behaviours: ResolvedBehaviours, stamp: {
2265
+ now: Date;
2266
+ userId: string;
2267
+ }): Document$2;
2268
+ /** The name of the TTL index of `purgeAfterDays`. */
2269
+ declare function purgeIndexName(softDelete: SoftDelete): string;
2270
+ /**
2271
+ * The TTL index of `purgeAfterDays`: created, changed (`collMod`) when the days differ, dropped when the option is gone. Never throws, a
2272
+ * failure is logged.
2273
+ */
2274
+ declare function syncPurgeIndex(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<'created' | 'changed' | 'dropped' | 'unchanged' | 'failed'>;
2275
+
2276
+ /**
2277
+ * The behaviour `owner` (2.4.0): every document belongs to the user who created it. Only the owner changes, replaces, deletes and restores
2278
+ * it; reads follow `read` — `own` (default) the owner only, `all` everybody with the read grant, or a function of the application.
2279
+ * A document of someone else is answered like a missing one (404), so nobody learns which ids exist. Administrators read and write every
2280
+ * document (`adminBypass`, default true). The collection grants still apply first: owner rules narrow them, never widen them.
2281
+ *
2282
+ * The owner field is the `createdBy` field of `timestamps` when set (written there), else `owner` (written here, on insert).
2283
+ */
2284
+ type Owner = NonNullable<ResolvedBehaviours['owner']>;
2285
+ /** The condition of the documents of a user. */
2286
+ declare function ownedBy(owner: Owner, userId: string): Document$2;
2287
+
2288
+ /**
2289
+ * The behaviour `audit` (2.4.0): every write to the collection leaves a record with the operation, the user, the time and the document
2290
+ * before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
2291
+ *
2292
+ * Built on the events, so it is best effort like them: written after the request is answered, a failure is logged and does not fail the
2293
+ * write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
2294
+ * ids of the documents only.
2295
+ */
2296
+ type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
2297
+ interface AuditRecord {
2298
+ collection: string;
2299
+ database: string;
2300
+ /** The `_id` of the document; absent on a summary record. */
2301
+ documentId?: unknown;
2302
+ operation: AuditOperation;
2303
+ user: string;
2304
+ at: Date;
2305
+ before?: Document$2;
2306
+ after?: Document$2;
2307
+ /** A summary of a write of many documents: the number of documents and how many of them have a record. */
2308
+ summary?: {
2309
+ count: number;
2310
+ recorded: number;
2311
+ };
2312
+ /** When MongoDB deletes the record (TTL). */
2313
+ expiresAt: Date;
2314
+ }
2315
+ declare const AuditCollection = "audit";
2316
+ /** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
2317
+ declare function auditCollectionOf(context: Pick<MongocampContext, 'database'>): Collection<AuditRecord>;
2318
+ /** The records of one write. */
2319
+ declare function auditRecords(input: {
2320
+ declared: DeclaredCollection;
2321
+ operation: AuditOperation;
2322
+ user: string;
2323
+ at: Date;
2324
+ documents: Array<{
2325
+ before?: Document$2;
2326
+ after?: Document$2;
2327
+ }>;
2328
+ count?: number;
2329
+ }): AuditRecord[];
2330
+ /** Creates the indexes of the audit records (history per document, TTL); idempotent. */
2331
+ declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
2332
+
2333
+ /**
2334
+ * The behaviour `versioned` (2.4.0): a replace or partial update that sends the version of the document it is based on only succeeds when
2335
+ * the document still has that version; otherwise it answers 409 with the stored document (`current`) instead of overwriting the change of
2336
+ * someone else. In the same write, no read-then-write race.
2337
+ *
2338
+ * - mode `counter`: a number (`_v`), 0 on insert, increased by every write (also updateMany, soft delete and restore);
2339
+ * - mode `timestamp`: the `updatedAt` field of `timestamps` is the version (no extra field);
2340
+ * - without version in the request the write is not checked (last write wins) — unless `required`, then 428.
2341
+ *
2342
+ * The version a client sends is taken before the guard removes it (it is never stored as sent).
2343
+ */
2344
+ type Versioned = NonNullable<ResolvedBehaviours['versioned']>;
2345
+ /** The version in a replacing document. */
2346
+ declare function versionInDocument(document: Document$2, versioned: Versioned): unknown;
2347
+ /** The version in an update (`$set` of the path, or of an object above it). */
2348
+ declare function versionInUpdate(update: Document$2, versioned: Versioned): unknown;
2349
+ /** The filter with the version condition. */
2350
+ declare function withVersion(filter: Document$2, versioned: Versioned, version: unknown): Document$2;
2351
+ /** An update with the increase of the counter (mode `counter`; the timestamp mode needs nothing, timestamps writes the new version). */
2352
+ declare function withIncrement(update: Document$2, versioned: Versioned): Document$2;
2353
+
2354
+ /**
2355
+ * The behaviour `timestamps` (2.4.0): the server writes the creation and change time and, when configured, the user of the request
2356
+ * (`createdBy`, `updatedBy`) on every write path. Runs in the stage `system`, after the validation, and after the guard put the stored
2357
+ * values of a replace back — so the creation values survive every later write. Clients cannot send these fields (guard).
2358
+ */
2359
+ type Timestamps = NonNullable<ResolvedBehaviours['timestamps']>;
2360
+ /** The values of a write: one time for all documents of a request (or a batch of an import) and the user of the request. */
2361
+ interface WriteStamp {
2362
+ now: Date;
2363
+ userId: string;
2364
+ }
2365
+ /** Sets the creation and change fields of a new document. */
2366
+ declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2367
+ /**
2368
+ * Sets the change fields of a replacing document; the creation fields stay as stored (put back by the guard), a document without them
2369
+ * (stored before the behaviour was switched on) gets the values of this write.
2370
+ */
2371
+ declare function stampReplace(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2372
+ /** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
2373
+ declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
2374
+
2375
+ /**
2376
+ * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
2377
+ * the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
2378
+ * payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
2379
+ *
2380
+ * export default definePlugin((nitroApp) => {
2381
+ * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
2382
+ * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
2383
+ * nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
2384
+ * })
2385
+ */
2386
+ type MongocampHooks = {
2387
+ 'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
2388
+ } & {
2389
+ [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
2390
+ } & {
2391
+ [N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
2392
+ };
2393
+ /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
2394
+ interface HookSystem {
2395
+ callHook(name: string, ...args: unknown[]): unknown;
2396
+ }
2397
+ declare const HookPrefix = "mongocamp:";
2398
+ /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
2399
+ declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
2400
+ /**
2401
+ * Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
2402
+ * hooks with a listener cost anything. The returned function stops it.
2403
+ */
2404
+ declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
2405
+ /**
2406
+ * Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
2407
+ * features that the plugins switch on are active before the first request is answered).
2408
+ */
2409
+ declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
2410
+
2411
+ export { AuditCollection, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, SyncValidationLevel, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, requestFields, requestLogging, resolveBehaviours, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncPurgeIndex, syncValidator, systemFields, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2412
+ export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, EventListener, EventName, EventTarget, ExtendedJsonMode, FetchOptions, HookSystem, InferDocument, InferDocumentInput, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RequestLog, ResolvedBehaviours, ScopeOptions, SoftDeleteOptions, SystemFields, TimestampsOptions, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };