@sfxcode/mongocamp-server-core 2.4.0 → 2.6.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.
Files changed (3) hide show
  1. package/dist/index.d.mts +247 -121
  2. package/dist/index.mjs +866 -235
  3. package/package.json +8 -2
package/dist/index.d.mts CHANGED
@@ -23,6 +23,7 @@ declare const ConfigKeys: {
23
23
  readonly ServerInterface: "SERVER_INTERFACE";
24
24
  readonly ServerPort: "SERVER_PORT";
25
25
  readonly AggregationStagesDenied: "AGGREGATION_STAGES_DENIED";
26
+ readonly FilterOperatorsDenied: "FILTER_OPERATORS_DENIED";
26
27
  readonly AuthHandler: "AUTH_HANDLER";
27
28
  readonly AuthSecret: "AUTH_SECRET";
28
29
  readonly AuthApiKeyLength: "AUTH_APIKEYLENGTH";
@@ -32,6 +33,15 @@ declare const ConfigKeys: {
32
33
  readonly AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS";
33
34
  readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
34
35
  readonly WatchMaxStreams: "WATCH_MAX_STREAMS";
36
+ readonly BodyMaxBytes: "BODY_MAX_BYTES";
37
+ readonly PagingMaxRows: "PAGING_MAX_ROWS";
38
+ readonly ExportMaxDocuments: "EXPORT_MAX_DOCUMENTS";
39
+ readonly GridfsUploadMaxBytes: "GRIDFS_UPLOAD_MAX_BYTES";
40
+ readonly WatchQueueMax: "WATCH_QUEUE_MAX";
41
+ readonly ServerHeaderEnabled: "SERVER_HEADER_ENABLED";
42
+ readonly ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL";
43
+ readonly UsersReadHideApiKey: "USERS_READ_HIDE_API_KEY";
44
+ readonly ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS";
35
45
  readonly FilterTimeZone: "FILTER_TIME_ZONE";
36
46
  readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
37
47
  readonly JobsEnabled: "JOBS_ENABLED";
@@ -81,9 +91,9 @@ declare class ConfigurationError extends Error {
81
91
  type ConfigEnv = Record<string, string | undefined>;
82
92
  interface ConfigSources {
83
93
  /** Environment variables, `process.env` when omitted. */
84
- env?: ConfigEnv;
94
+ env?: ConfigEnv | undefined;
85
95
  /** Programmatic values (e.g. from Nuxt runtimeConfig). Strings are parsed like env values, other values are taken as they are. */
86
- values?: Partial<Record<ConfigKey, unknown>>;
96
+ values?: Partial<Record<ConfigKey, unknown>> | undefined;
87
97
  }
88
98
  /**
89
99
  * In-memory view of all configurations. Precedence: definition default < programmatic values < env.
@@ -145,6 +155,8 @@ declare class MongocampDatabase {
145
155
  db(name?: string): Db;
146
156
  /** Name of an internal collection, with the `AUTH_PREFIX` (`mc_users`, `mc_roles`, `mc_token_cache`, ...). */
147
157
  internalCollectionName(name: string): string;
158
+ /** `USERS_READ_HIDE_API_KEY` (2.6.0): the document routes leave out `apiKey` of the users collection too. */
159
+ get hidesUserApiKeys(): boolean;
148
160
  close(): Promise<void>;
149
161
  }
150
162
 
@@ -169,13 +181,18 @@ declare class MongocampError extends Error {
169
181
  readonly additionalInfo: string;
170
182
  readonly issues?: ValidationIssue[] | undefined;
171
183
  readonly current?: Record<string, unknown> | undefined;
184
+ /**
185
+ * 2.6.0: the stored document of a version conflict with the values of the driver (without secrets), so the answer can use the Extended
186
+ * JSON mode of the request (`currentIn`); `current` is relaxed.
187
+ */
188
+ storedDocument?: Record<string, unknown>;
172
189
  constructor(message: string, status: number, code?: number, additionalInfo?: string, issues?: ValidationIssue[] | undefined, current?: Record<string, unknown> | undefined);
173
190
  get description(): ErrorDescription;
174
191
  static badRequest(message: string, code?: number): MongocampError;
175
192
  /** 400 for documents that are not valid, with the fields in `issues` (a schema, a before-hook). */
176
193
  static validation(issues: ValidationIssue[], message?: string, code?: number): MongocampError;
177
194
  /** 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;
195
+ static versionConflict(current: Record<string, unknown>, storedDocument?: Record<string, unknown>): MongocampError;
179
196
  /** 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. */
180
197
  static forbidden(message: string, code?: number): MongocampError;
181
198
  static unauthorized(message?: string, code?: number): MongocampError;
@@ -184,11 +201,23 @@ declare class MongocampError extends Error {
184
201
  static decodeFailure(what: string, additionalInfo?: string): MongocampError;
185
202
  }
186
203
  type ErrorLogger = (error: unknown, status: number) => void;
204
+ interface ErrorResponseOptions {
205
+ /** The message of an unexpected error in the answer (`ERRORS_EXPOSE_INTERNAL`, for development); by default only the log has it. */
206
+ exposeInternal?: boolean | undefined;
207
+ /**
208
+ * 2.6.0: the `current` document of a version conflict in the Extended JSON mode of the request (query parameter `extendedJson`);
209
+ * relaxed without.
210
+ */
211
+ currentIn?: ((document: Record<string, unknown>) => Record<string, unknown>) | undefined;
212
+ }
213
+ /** The message of an unexpected error (2.5.0): its text stays in the log, the client gets the request id (header `x-request-id`). */
214
+ declare const InternalErrorMessage = "internal server error, the log of the server has the details (x-request-id)";
187
215
  /**
188
216
  * Maps anything thrown in a handler to the error response of the Scala server (`MongoCampExceptionHandler`): a `MongocampError` as it is,
189
- * a database error with the status for its code and a message without internal names, everything else as 500 with code -1.
217
+ * a database error with the status for its code and a message without internal names, everything else as 500 with code -1 and a generic
218
+ * message (2.5.0; before, the message of the error, which can name internals).
190
219
  */
191
- declare function toErrorResponse(error: unknown, log?: ErrorLogger): Response;
220
+ declare function toErrorResponse(error: unknown, log?: ErrorLogger, options?: ErrorResponseOptions): Response;
192
221
 
193
222
  /** Pagination of list routes (`PagingFunctions.scala`, `MongoPaginatedFilter.scala`): 1-based pages, 100 rows per page by default. */
194
223
  declare const DefaultRowsPerPage = 100;
@@ -201,9 +230,9 @@ declare const PaginationHeaders: {
201
230
  };
202
231
  /** `after` switches to cursor paging (`http/cursor.ts`): the token of the previous page, or empty for the first page. */
203
232
  interface Paging {
204
- rowsPerPage?: number;
205
- page?: number;
206
- after?: string;
233
+ rowsPerPage?: number | undefined;
234
+ page?: number | undefined;
235
+ after?: string | undefined;
207
236
  }
208
237
  /** Query parameter `count`: `exact` (default) counts the matching documents, `none` skips the count and its headers. */
209
238
  type CountMode = 'exact' | 'none';
@@ -388,7 +417,6 @@ interface LoginResult {
388
417
  expirationDate: string;
389
418
  }
390
419
  declare class AuthService {
391
- private readonly database;
392
420
  private readonly config;
393
421
  private readonly version;
394
422
  readonly holder: AuthHolder;
@@ -651,6 +679,8 @@ interface ResolvedIndex {
651
679
  fingerprint: string;
652
680
  /** Declared, or added for a behaviour. */
653
681
  origin: 'declaration' | 'owner';
682
+ /** The partial filter was added by soft delete (2.6.0: told in the declaration answer). */
683
+ softDeleteFilter?: boolean;
654
684
  }
655
685
  /**
656
686
  * The indexes of a declaration: the declared ones and the ones of its behaviours (an index on the owner field; with soft delete, unique
@@ -668,9 +698,13 @@ declare function resolveIndexes(declarations: readonly IndexDeclaration[] | unde
668
698
  * 'billing.accountId': 'crm:accounts', // a nested field, a collection of another database
669
699
  * }
670
700
  */
671
- /** The target collection (`name` or `database:name`), or an object with it. */
701
+ /**
702
+ * The target collection (`name` or `database:name`), or an object with it. `many` (2.6.0) says that the field holds an array of ids when
703
+ * the schema cannot tell (no schema of the field, a loose object); a schema that tells otherwise is an error.
704
+ */
672
705
  type RefDeclaration = string | {
673
706
  readonly collection: string;
707
+ readonly many?: boolean;
674
708
  };
675
709
  interface ResolvedRef {
676
710
  /** The field path of the reference. */
@@ -776,7 +810,7 @@ interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSch
776
810
  /** Default `warn`. */
777
811
  validation?: ValidationMode;
778
812
  /** A `$jsonSchema` validator for MongoDB that replaces the one converted from the schema (for schemas without JSON Schema form). */
779
- validator?: Document$2;
813
+ validator?: Document$2 | undefined;
780
814
  /** Indexes (2.4.0): `'status'`, `'-createdAt'`, `['a', '-b']` or `{ fields, unique, ... }`; synced at the start (own indexes only). */
781
815
  indexes?: readonly IndexDeclaration[];
782
816
  /** References (2.4.0): field → target collection (`'customers'`, `'db:customers'`), for `expand` on reads. */
@@ -810,6 +844,13 @@ interface DeclaredCollection {
810
844
  /** What the start did with the validator of MongoDB (`collections()` feature). */
811
845
  sync?: ValidatorSyncResult;
812
846
  }
847
+ /** A reference of a declared collection to another one (2.6.0, `referencedBy` of the declaration answer). */
848
+ interface ReferenceTo {
849
+ collection: string;
850
+ database: string;
851
+ field: string;
852
+ many: boolean;
853
+ }
813
854
  /** The declarations of a server by database and collection; `context.collections`. */
814
855
  declare class CollectionRegistry {
815
856
  private readonly entries;
@@ -818,6 +859,13 @@ declare class CollectionRegistry {
818
859
  find(databaseName: string, name: string): DeclaredCollection | undefined;
819
860
  /** The declaration of a collection as the routes name it (`orders`, `otherdb:orders`). */
820
861
  resolve(context: Pick<MongocampContext, 'database'>, collection: string): DeclaredCollection | undefined;
862
+ /** The fields of the declared refs of a collection (2.6.0: a Lucene term with an id matches their `ObjectId`); empty without a declaration. */
863
+ refFields(context: Pick<MongocampContext, 'database'>, collection: string): string[];
864
+ /**
865
+ * The references of the declared collections to a declaration (2.6.0, `referencedBy` of its answer), from the registry (no database
866
+ * read). `collection` is the name as the routes take it (`database:name` when the declaration names its database).
867
+ */
868
+ referencesTo(context: Pick<MongocampContext, 'database'>, target: DeclaredCollection): ReferenceTo[];
821
869
  get size(): number;
822
870
  all(): DeclaredCollection[];
823
871
  /** Adds declarations, all or none (a collection that is declared twice is an error); the returned function removes them. */
@@ -856,6 +904,26 @@ interface components {
856
904
  CapabilityLimits: {
857
905
  /** Format: int64 */
858
906
  importMaxBytes: number;
907
+ /**
908
+ * Format: int64
909
+ * @description BODY_MAX_BYTES (2.6.0); 0 is no limit.
910
+ */
911
+ bodyMaxBytes: number;
912
+ /**
913
+ * Format: int64
914
+ * @description PAGING_MAX_ROWS (2.6.0); 0 is no limit.
915
+ */
916
+ pagingMaxRows: number;
917
+ /**
918
+ * Format: int64
919
+ * @description EXPORT_MAX_DOCUMENTS (2.6.0); 0 is no limit.
920
+ */
921
+ exportMaxDocuments: number;
922
+ /**
923
+ * Format: int64
924
+ * @description GRIDFS_UPLOAD_MAX_BYTES (2.6.0); 0 is no limit.
925
+ */
926
+ gridfsUploadMaxBytes: number;
859
927
  /** Format: int32 */
860
928
  grantDeniedStatus: number;
861
929
  };
@@ -1383,14 +1451,44 @@ interface components {
1383
1451
  [key: string]: unknown;
1384
1452
  };
1385
1453
  unique: boolean;
1454
+ /** @description 2.6.0 */
1455
+ sparse: boolean;
1456
+ /**
1457
+ * @description Declared, or added for a behaviour (owner = the index on the owner field), 2.6.0.
1458
+ * @enum {string}
1459
+ */
1460
+ origin: "declaration" | "owner";
1461
+ /** @description The partial filter as relaxed Extended JSON (2.6.0), as index details show it. */
1462
+ partialFilterExpression?: {
1463
+ [key: string]: unknown;
1464
+ };
1465
+ /**
1466
+ * @description softDelete when the soft delete behaviour added the partial filter to a unique index (2.6.0).
1467
+ * @enum {string}
1468
+ */
1469
+ partialFilterFrom?: "softDelete";
1470
+ /**
1471
+ * Format: int64
1472
+ * @description 2.6.0
1473
+ */
1474
+ expireAfterSeconds?: number;
1386
1475
  }[];
1387
1476
  /** @description The references of the declaration (2.4.0), the fields a read can expand (query parameter expand). */
1388
1477
  refs: {
1389
1478
  field: string;
1390
1479
  /** @description The target collection (name or database:name). */
1391
1480
  collection: string;
1392
- /** @description Whether the field holds an array of ids (from the schema); missing when the schema does not tell. */
1393
- many?: boolean;
1481
+ /** @description Whether the field holds an array of ids (from the schema or the declaration); false when neither tells (2.6.0, before it was missing then). */
1482
+ many: boolean;
1483
+ }[];
1484
+ /** @description The references of the declared collections to this collection (2.6.0), from the declarations of the server; empty when none. */
1485
+ referencedBy: {
1486
+ /** @description The referencing collection as the routes name it (name or database:name). */
1487
+ collection: string;
1488
+ database: string;
1489
+ /** @description The field of the referencing collection that holds the id. */
1490
+ field: string;
1491
+ many: boolean;
1394
1492
  }[];
1395
1493
  timestamps?: {
1396
1494
  createdAt: string;
@@ -1776,6 +1874,12 @@ declare class ConfigPersistence {
1776
1874
  private persistentDefinitions;
1777
1875
  /** Registers the missing keys with their defaults (`registerConfig`) and reads the stored values; the refresh starts if wanted. */
1778
1876
  initialize(refreshMillis?: number | false): Promise<void>;
1877
+ /**
1878
+ * 2.6.0: a database created before 2.2.0 stored the old default 401 of `AUTH_GRANT_DENIED_STATUS` at its first start, and kept answering
1879
+ * 401 for a missing grant. A stored 401 that no update set (no `changedAt`, written since 2.6.0) becomes the default 403 once; an
1880
+ * administrator who wants 401 patches it again (then it is marked and stays).
1881
+ */
1882
+ private upgradeLegacyDefaults;
1779
1883
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
1780
1884
  refresh(startup: boolean): Promise<void>;
1781
1885
  /** A configuration as answered by the API: the stored one, the one of the env, or a non persistent one. */
@@ -1788,6 +1892,11 @@ declare class ConfigPersistence {
1788
1892
  * in this instance, the other instances read it with their next refresh.
1789
1893
  */
1790
1894
  update(key: string, value: unknown): Promise<boolean>;
1895
+ /**
1896
+ * 2.6.0: the default again (`DELETE /system/configurations/{key}`), at once in this instance for a key that needs no restart. The
1897
+ * reasons it is not possible are answered by the route (unknown, not persistent, set by the environment, a generated default).
1898
+ */
1899
+ reset(key: string): Promise<boolean>;
1791
1900
  close(): void;
1792
1901
  }
1793
1902
 
@@ -1962,16 +2071,16 @@ declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]
1962
2071
  declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
1963
2072
  interface ScopeOptions {
1964
2073
  /** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
1965
- withDeleted?: boolean;
2074
+ withDeleted?: boolean | undefined;
1966
2075
  }
1967
2076
  /** `withDeleted=true` of a read route (2.3.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
1968
2077
  declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
1969
2078
 
1970
2079
  interface ReadOptions extends ScopeOptions {
1971
2080
  /** The kind of request for the hooks of `document:beforeRead` (default by operation). */
1972
- operation?: ReadOperation;
2081
+ operation?: ReadOperation | undefined;
1973
2082
  /** References to expand (2.4.0): declared ref fields of the collection, at most `MaxExpands`. */
1974
- expand?: readonly string[];
2083
+ expand?: readonly string[] | undefined;
1975
2084
  }
1976
2085
  interface PageResult {
1977
2086
  documents: Document$2[];
@@ -1985,6 +2094,10 @@ declare class DocumentService {
1985
2094
  /** The grant of the caller; `withDeleted` only for the administrators of the collection. */
1986
2095
  private require;
1987
2096
  /** The filter with the read scope of the caller. */
2097
+ /** The paging of a read with `rowsPerPage` at most `PAGING_MAX_ROWS` (2.5.0, 0: no limit); the page headers show the rows used. */
2098
+ private limited;
2099
+ /** Refuses filters, projections and updates of the caller with an operator of `FILTER_OPERATORS_DENIED` (2.5.0). */
2100
+ private checkOperators;
1988
2101
  scope(user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
1989
2102
  /**
1990
2103
  * The declared references of `fields` (2.4.0); 400 for a name that is no reference of the collection and for more than `MaxExpands`.
@@ -2200,11 +2313,11 @@ interface MongocampContext {
2200
2313
  collections: CollectionRegistry;
2201
2314
  jobs: JobScheduler;
2202
2315
  /** The metrics, with `METRICS_ENABLED` only. */
2203
- metrics?: MongocampMetrics;
2316
+ metrics?: MongocampMetrics | undefined;
2204
2317
  /** The answer of `buildInfo`, kept for an hour. */
2205
2318
  systemInfo: InfoCache<SystemInfo>;
2206
2319
  /** Stops the process (`DELETE /system`); not set when the server is embedded in an application. */
2207
- shutdown?: (force: boolean) => void | Promise<void>;
2320
+ shutdown?: ((force: boolean) => void | Promise<void>) | undefined;
2208
2321
  }
2209
2322
 
2210
2323
  /**
@@ -2245,8 +2358,9 @@ interface ServerPage<T> {
2245
2358
  countPages?: number;
2246
2359
  }
2247
2360
  /** A document that was read (with `_id`), or its id. */
2361
+ /** An id, or a document that was read (its `_id`; the schema type of a declared collection has an optional `_id`). */
2248
2362
  type ServerDocumentIdentity = string | number | ObjectId | {
2249
- _id: unknown;
2363
+ _id?: unknown;
2250
2364
  };
2251
2365
  interface ServerCollection<T, I = T> {
2252
2366
  readonly name: string;
@@ -2363,25 +2477,6 @@ interface MongocampServer {
2363
2477
  /** Creates and connects a MongoCamp server. */
2364
2478
  declare function createMongocampServer(options?: MongocampServerOptions): Promise<MongocampServer>;
2365
2479
 
2366
- /** The fields of the server in the wide event of a request (key `mongocamp`). */
2367
- interface MongocampRequestFields {
2368
- requestId: string;
2369
- /** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
2370
- operation: string;
2371
- controller: string;
2372
- /** The user the request was authenticated as; missing for public routes and invalid credentials. */
2373
- user?: string;
2374
- database?: string;
2375
- collection?: string;
2376
- bucket?: string;
2377
- /** All matching rows of a paged list (`x-pagination-count-rows`). */
2378
- rows?: number;
2379
- /** `x-error-code` and `x-error-message` of an error response. */
2380
- errorCode?: string;
2381
- errorMessage?: string;
2382
- }
2383
- declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
2384
-
2385
2480
  /** Error codes of the API (`mongocamp-library/.../exception/ErrorCodes.scala`), sent in `ErrorDescription.code` and `x-error-code`. */
2386
2481
  declare const ErrorCodes: {
2387
2482
  /** A request that could not be decoded (body, query or header with an invalid value). */
@@ -2409,6 +2504,12 @@ declare const ErrorCodes: {
2409
2504
  readonly changeStreamsUnsupported: 5011;
2410
2505
  readonly unauthorizedUser: 4011;
2411
2506
  readonly unauthorizedUserForOtherUser: 4012;
2507
+ /** 413 (2.6.0): the body is greater than `BODY_MAX_BYTES`. */
2508
+ readonly bodyTooLarge: 4131;
2509
+ /** 413 (2.6.0): the uploaded file is greater than `GRIDFS_UPLOAD_MAX_BYTES`. */
2510
+ readonly uploadTooLarge: 4132;
2511
+ /** 413 (2.6.0): the import is greater than `IMPORT_MAX_BYTES`. */
2512
+ readonly importTooLarge: 4133;
2412
2513
  readonly forbiddenStage: 4031;
2413
2514
  readonly forbiddenCollectionInStage: 4032;
2414
2515
  readonly jobAlreadyAdded: 4121;
@@ -2417,6 +2518,106 @@ declare const ErrorCodes: {
2417
2518
  readonly jobClassNotFound: 4042;
2418
2519
  };
2419
2520
 
2521
+ /**
2522
+ * The behaviour `audit` (2.3.0): every write to the collection leaves a record with the operation, the user, the time and the document
2523
+ * before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
2524
+ *
2525
+ * 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
2526
+ * write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
2527
+ * ids of the documents only.
2528
+ */
2529
+ type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
2530
+ interface AuditRecord {
2531
+ collection: string;
2532
+ database: string;
2533
+ /** The `_id` of the document; absent on a summary record. */
2534
+ documentId?: unknown;
2535
+ operation: AuditOperation;
2536
+ user: string;
2537
+ at: Date;
2538
+ before?: Document$2;
2539
+ after?: Document$2;
2540
+ /** A summary of a write of many documents: the number of documents and how many of them have a record. */
2541
+ summary?: {
2542
+ count: number;
2543
+ recorded: number;
2544
+ };
2545
+ /** When MongoDB deletes the record (TTL). */
2546
+ expiresAt: Date;
2547
+ }
2548
+ declare const AuditCollection = "audit";
2549
+ /** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
2550
+ declare function auditCollectionOf<T extends Document$2 = AuditRecord>(context: Pick<MongocampContext, 'database'>): Collection<T>;
2551
+ /** The records of one write. */
2552
+ declare function auditRecords(input: {
2553
+ declared: DeclaredCollection;
2554
+ operation: AuditOperation;
2555
+ user: string;
2556
+ at: Date;
2557
+ documents: Array<{
2558
+ before?: Document$2 | undefined;
2559
+ after?: Document$2 | undefined;
2560
+ }>;
2561
+ count?: number;
2562
+ }): AuditRecord[];
2563
+ /** Creates the indexes of the audit records (history per document, TTL); idempotent. */
2564
+ declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
2565
+
2566
+ /**
2567
+ * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
2568
+ * the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
2569
+ * payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
2570
+ *
2571
+ * export default definePlugin((nitroApp) => {
2572
+ * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
2573
+ * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
2574
+ * nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
2575
+ * })
2576
+ */
2577
+ type MongocampHooks = {
2578
+ 'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
2579
+ } & {
2580
+ [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
2581
+ } & {
2582
+ [N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
2583
+ };
2584
+ /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
2585
+ interface HookSystem {
2586
+ callHook(name: string, ...args: unknown[]): unknown;
2587
+ }
2588
+ declare const HookPrefix = "mongocamp:";
2589
+ /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
2590
+ declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
2591
+ /**
2592
+ * Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
2593
+ * hooks with a listener cost anything. The returned function stops it.
2594
+ */
2595
+ declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
2596
+ /**
2597
+ * Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
2598
+ * features that the plugins switch on are active before the first request is answered).
2599
+ */
2600
+ declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
2601
+
2602
+ /** The fields of the server in the wide event of a request (key `mongocamp`). */
2603
+ interface MongocampRequestFields {
2604
+ requestId: string;
2605
+ /** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
2606
+ operation: string;
2607
+ controller: string;
2608
+ /** The user the request was authenticated as; missing for public routes and invalid credentials. */
2609
+ user?: string;
2610
+ database?: string;
2611
+ collection?: string;
2612
+ bucket?: string;
2613
+ /** All matching rows of a paged list (`x-pagination-count-rows`). */
2614
+ rows?: number;
2615
+ /** `x-error-code` and `x-error-message` of an error response. */
2616
+ errorCode?: string;
2617
+ errorMessage?: string;
2618
+ }
2619
+ declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
2620
+
2420
2621
  /** The key of the wrapper `{"$string": "..."}`: a text that looks like a date stays a text (`CirceSchema.TextMarker`). */
2421
2622
  declare const TextMarker = "$string";
2422
2623
  /**
@@ -2516,6 +2717,10 @@ declare class LuceneQueryError extends Error {
2516
2717
  * - ranges are `$gte`/`$gt`/`$lte`/`$lt`, `[* TO *]`, `field:*` and `_exists_:field` are `$exists`
2517
2718
  *
2518
2719
  * With `searchWithValueAndString` a value that converts (e.g. the number `123`) is also searched as the text (`"123"`).
2720
+ *
2721
+ * 2.6.0: a term with 24 hex characters on a field of `idFields` (the declared refs of the collection) matches the `ObjectId` and the text
2722
+ * (`$in` / `$nin`), so `customerId:<hex>` finds the orders of a customer; an array ref matches when one element is the id. Only declared
2723
+ * refs: a 24-hex text on any other field stays a plain term (no other filter changes its results).
2519
2724
  */
2520
2725
  type Filter = Record<string, unknown>;
2521
2726
  interface ConvertOptions {
@@ -2524,6 +2729,8 @@ interface ConvertOptions {
2524
2729
  caseInsensitive?: boolean;
2525
2730
  /** The time zone of dates without offset (`FILTER_TIME_ZONE`), UTC by default. */
2526
2731
  timeZone?: string;
2732
+ /** Fields whose 24-hex terms also match the `ObjectId` (2.6.0: the declared refs of the collection). */
2733
+ idFields?: Iterable<string>;
2527
2734
  }
2528
2735
  declare function luceneQueryToFilter(query: LuceneQuery, options?: ConvertOptions): Filter;
2529
2736
 
@@ -2664,51 +2871,6 @@ type Owner = NonNullable<ResolvedBehaviours['owner']>;
2664
2871
  /** The condition of the documents of a user. */
2665
2872
  declare function ownedBy(owner: Owner, userId: string): Document$2;
2666
2873
 
2667
- /**
2668
- * The behaviour `audit` (2.3.0): every write to the collection leaves a record with the operation, the user, the time and the document
2669
- * before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
2670
- *
2671
- * 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
2672
- * write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
2673
- * ids of the documents only.
2674
- */
2675
- type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
2676
- interface AuditRecord {
2677
- collection: string;
2678
- database: string;
2679
- /** The `_id` of the document; absent on a summary record. */
2680
- documentId?: unknown;
2681
- operation: AuditOperation;
2682
- user: string;
2683
- at: Date;
2684
- before?: Document$2;
2685
- after?: Document$2;
2686
- /** A summary of a write of many documents: the number of documents and how many of them have a record. */
2687
- summary?: {
2688
- count: number;
2689
- recorded: number;
2690
- };
2691
- /** When MongoDB deletes the record (TTL). */
2692
- expiresAt: Date;
2693
- }
2694
- declare const AuditCollection = "audit";
2695
- /** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
2696
- declare function auditCollectionOf(context: Pick<MongocampContext, 'database'>): Collection<AuditRecord>;
2697
- /** The records of one write. */
2698
- declare function auditRecords(input: {
2699
- declared: DeclaredCollection;
2700
- operation: AuditOperation;
2701
- user: string;
2702
- at: Date;
2703
- documents: Array<{
2704
- before?: Document$2;
2705
- after?: Document$2;
2706
- }>;
2707
- count?: number;
2708
- }): AuditRecord[];
2709
- /** Creates the indexes of the audit records (history per document, TTL); idempotent. */
2710
- declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
2711
-
2712
2874
  /**
2713
2875
  * The behaviour `versioned` (2.3.0): a replace or partial update that sends the version of the document it is based on only succeeds when
2714
2876
  * the document still has that version; otherwise it answers 409 with the stored document (`current`) instead of overwriting the change of
@@ -2751,41 +2913,5 @@ declare function stampReplace(document: Document$2, timestamps: Timestamps, stam
2751
2913
  /** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
2752
2914
  declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
2753
2915
 
2754
- /**
2755
- * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
2756
- * the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
2757
- * payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
2758
- *
2759
- * export default definePlugin((nitroApp) => {
2760
- * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
2761
- * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
2762
- * nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
2763
- * })
2764
- */
2765
- type MongocampHooks = {
2766
- 'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
2767
- } & {
2768
- [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
2769
- } & {
2770
- [N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
2771
- };
2772
- /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
2773
- interface HookSystem {
2774
- callHook(name: string, ...args: unknown[]): unknown;
2775
- }
2776
- declare const HookPrefix = "mongocamp:";
2777
- /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
2778
- declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
2779
- /**
2780
- * Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
2781
- * hooks with a listener cost anything. The returned function stops it.
2782
- */
2783
- declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
2784
- /**
2785
- * Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
2786
- * features that the plugins switch on are active before the first request is answered).
2787
- */
2788
- declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
2789
-
2790
- export { AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2791
- export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, EventListener, EventName, EventTarget, ExpandedDocument, ExtendedJsonMode, FetchOptions, Grant, HookSystem, IndexDeclaration, IndexDirection, IndexOptions, IndexSyncResult, InferDocument, InferDocumentInput, InferRefs, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RefDeclaration, RefTargets, RequestLog, ResolvedBehaviours, ResolvedIndex, ResolvedRef, Role, ScopeOptions, ServerCollection, ServerCollectionOptions, ServerCollectionUser, ServerDocumentIdentity, ServerFindOptions, ServerPage, SoftDeleteOptions, SystemFields, TimestampsOptions, UserInformation, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };
2916
+ export { AuditCollection, AuthService, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigPersistence, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InfoCache, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampDatabase, MongocampError, MongocampMetrics, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2917
+ export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, ErrorResponseOptions, EventListener, EventName, EventTarget, ExpandedDocument, ExtendedJsonMode, FetchOptions, Grant, HookSystem, IndexDeclaration, IndexDirection, IndexOptions, IndexSyncResult, InferDocument, InferDocumentInput, InferRefs, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RefDeclaration, RefTargets, RequestLog, ResolvedBehaviours, ResolvedIndex, ResolvedRef, Role, ScopeOptions, ServerCollection, ServerCollectionOptions, ServerCollectionUser, ServerDocumentIdentity, ServerFindOptions, ServerPage, SoftDeleteOptions, SystemFields, SystemInfo, TimestampsOptions, UserInformation, ValidationIssue, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };