@sfxcode/mongocamp-server-core 2.3.0 → 2.4.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 +440 -61
- package/dist/index.mjs +1808 -1074
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MongoClient, Db, Collection, Document as Document$2 } from 'mongodb';
|
|
1
|
+
import { MongoClient, Db, Collection, Document as Document$2, ObjectId } from 'mongodb';
|
|
2
2
|
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
3
3
|
export { StandardSchemaV1 } from '@standard-schema/spec';
|
|
4
4
|
import * as hookable from 'hookable';
|
|
@@ -183,6 +183,12 @@ declare class MongocampError extends Error {
|
|
|
183
183
|
/** A request that cannot be decoded (`MongoCampDefaultDecodeFailureHandler`): `what` names the input, e.g. `body` or `query parameter page`. */
|
|
184
184
|
static decodeFailure(what: string, additionalInfo?: string): MongocampError;
|
|
185
185
|
}
|
|
186
|
+
type ErrorLogger = (error: unknown, status: number) => void;
|
|
187
|
+
/**
|
|
188
|
+
* 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.
|
|
190
|
+
*/
|
|
191
|
+
declare function toErrorResponse(error: unknown, log?: ErrorLogger): Response;
|
|
186
192
|
|
|
187
193
|
/** Pagination of list routes (`PagingFunctions.scala`, `MongoPaginatedFilter.scala`): 1-based pages, 100 rows per page by default. */
|
|
188
194
|
declare const DefaultRowsPerPage = 100;
|
|
@@ -199,6 +205,8 @@ interface Paging {
|
|
|
199
205
|
page?: number;
|
|
200
206
|
after?: string;
|
|
201
207
|
}
|
|
208
|
+
/** Query parameter `count`: `exact` (default) counts the matching documents, `none` skips the count and its headers. */
|
|
209
|
+
type CountMode = 'exact' | 'none';
|
|
202
210
|
/**
|
|
203
211
|
* `allCount` and `pagesCount` are missing when the count was skipped (`count=none`), `page` with cursor paging; `next` is the cursor of the
|
|
204
212
|
* next page, missing when the page is the last one.
|
|
@@ -400,6 +408,8 @@ declare class AuthService {
|
|
|
400
408
|
*/
|
|
401
409
|
authenticateUser(credentials: Credentials): Promise<UserInformation>;
|
|
402
410
|
/** The logged in user of a request with the current roles. */
|
|
411
|
+
/** A user by id with its roles (2.4.0, the server collection acting for a user); 401 for a user that does not exist. */
|
|
412
|
+
authorizedUser(userId: string): Promise<AuthorizedUser>;
|
|
403
413
|
authenticate(request: Request): Promise<AuthorizedUser>;
|
|
404
414
|
/** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
|
|
405
415
|
userOf(request: Request): string | undefined;
|
|
@@ -407,6 +417,8 @@ declare class AuthService {
|
|
|
407
417
|
grantDenied(message: string): MongocampError;
|
|
408
418
|
requireAdmin(request: Request): Promise<AuthorizedUser>;
|
|
409
419
|
requireCollection(request: Request, collection: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
|
|
420
|
+
/** The grant of an authenticated user for a collection (the routes and the document service, 2.4.0). */
|
|
421
|
+
requireRight(user: AuthorizedUser, collection: string, right: 'read' | 'write' | 'administrate'): void;
|
|
410
422
|
requireBucket(request: Request, bucket: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
|
|
411
423
|
profileOf(user: UserInformation): Promise<UserProfile>;
|
|
412
424
|
/** A new token for the user (`AuthHolder.generateLoginResult`), valid for `AUTH_EXPIRING_DURATION`. */
|
|
@@ -436,7 +448,7 @@ declare function requestLogging(): MongocampFeature;
|
|
|
436
448
|
declare function metrics(): MongocampFeature;
|
|
437
449
|
|
|
438
450
|
/**
|
|
439
|
-
* Behaviours of declared collections (2.
|
|
451
|
+
* Behaviours of declared collections (2.3.0): one flag each in `defineMongocampCollection`, with working defaults; an options object
|
|
440
452
|
* renames the fields (dot paths for nested fields, e.g. `metaData.created`).
|
|
441
453
|
*
|
|
442
454
|
* defineMongocampCollection({ name: 'orders', schema, timestamps: true, owner: true, softDelete: true, versioned: true, audit: true })
|
|
@@ -574,6 +586,139 @@ type DeepPartial<T> = T extends Date | readonly unknown[] ? T : T extends object
|
|
|
574
586
|
[K in keyof T]?: DeepPartial<T[K]>;
|
|
575
587
|
} : T;
|
|
576
588
|
|
|
589
|
+
/**
|
|
590
|
+
* The indexes of a declared collection at the start (2.4.0). The sync only manages its **own** indexes (names `mongocamp_idx_*`):
|
|
591
|
+
*
|
|
592
|
+
* - a missing one is created (all missing ones in one `createIndexes`);
|
|
593
|
+
* - one whose key or options changed is dropped and created again — MongoDB cannot change most index options; only the seconds of a TTL
|
|
594
|
+
* index are changed in place (`collMod`);
|
|
595
|
+
* - an own index that is no longer declared is dropped;
|
|
596
|
+
* - an index of someone else (made by hand, by another tool, `_id_`) is never touched, only reported;
|
|
597
|
+
* - a failure (e.g. duplicate values for a unique index) is logged; the start goes on, the other indexes are synced.
|
|
598
|
+
*
|
|
599
|
+
* Every instance runs it; the second one changes nothing.
|
|
600
|
+
*/
|
|
601
|
+
interface IndexSyncResult {
|
|
602
|
+
collection: string;
|
|
603
|
+
created: string[];
|
|
604
|
+
replaced: string[];
|
|
605
|
+
dropped: string[];
|
|
606
|
+
unchanged: string[];
|
|
607
|
+
/** Indexes that are not own ones (left alone). */
|
|
608
|
+
foreign: string[];
|
|
609
|
+
/** Indexes that could not be created or changed, with the reason. */
|
|
610
|
+
failed: Array<{
|
|
611
|
+
name: string;
|
|
612
|
+
reason: string;
|
|
613
|
+
}>;
|
|
614
|
+
}
|
|
615
|
+
/** Syncs the indexes of one declared collection; never throws (an unexpected failure is reported in `failed`). */
|
|
616
|
+
declare function syncIndexes(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<IndexSyncResult>;
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Indexes of declared collections (2.4.0): the shortest form that says what is needed, the indexes the behaviours need added by
|
|
620
|
+
* themselves. The sync at the start (`index-sync.ts`) creates them; it only manages its own indexes (names `mongocamp_idx_*`).
|
|
621
|
+
*
|
|
622
|
+
* indexes: [
|
|
623
|
+
* 'status', // { status: 1 }
|
|
624
|
+
* '-createdAt', // { createdAt: -1 }
|
|
625
|
+
* ['customerId', '-createdAt'], // compound
|
|
626
|
+
* { fields: { number: 1 }, unique: true }, // with options
|
|
627
|
+
* { fields: { text: 'text' } }, // text index
|
|
628
|
+
* { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL
|
|
629
|
+
* ]
|
|
630
|
+
*/
|
|
631
|
+
type IndexDirection = 1 | -1 | 'text';
|
|
632
|
+
interface IndexOptions {
|
|
633
|
+
fields: Record<string, IndexDirection>;
|
|
634
|
+
unique?: boolean;
|
|
635
|
+
sparse?: boolean;
|
|
636
|
+
/** TTL: documents expire this many seconds after the date in the (single) field. */
|
|
637
|
+
expireAfterSeconds?: number;
|
|
638
|
+
partialFilterExpression?: Document$2;
|
|
639
|
+
collation?: Document$2;
|
|
640
|
+
/** A name of your own (prefixed with `mongocamp_idx_`); default made of the fields. */
|
|
641
|
+
name?: string;
|
|
642
|
+
}
|
|
643
|
+
/** A field (`'status'`, `'-createdAt'`), fields of a compound index, or an index with options. */
|
|
644
|
+
type IndexDeclaration = string | readonly string[] | IndexOptions;
|
|
645
|
+
declare const OwnIndexPrefix = "mongocamp_idx_";
|
|
646
|
+
interface ResolvedIndex {
|
|
647
|
+
name: string;
|
|
648
|
+
key: Record<string, IndexDirection>;
|
|
649
|
+
options: Document$2;
|
|
650
|
+
/** Key and options, to see whether a stored index is still the declared one. */
|
|
651
|
+
fingerprint: string;
|
|
652
|
+
/** Declared, or added for a behaviour. */
|
|
653
|
+
origin: 'declaration' | 'owner';
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* The indexes of a declaration: the declared ones and the ones of its behaviours (an index on the owner field; with soft delete, unique
|
|
657
|
+
* indexes count only documents that are not deleted, so a deleted value can be used again).
|
|
658
|
+
*/
|
|
659
|
+
declare function resolveIndexes(declarations: readonly IndexDeclaration[] | undefined, behaviours: ResolvedBehaviours): ResolvedIndex[];
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* References of declared collections (2.4.0): which fields hold the `_id` of a document of another collection. A read with
|
|
663
|
+
* `expand=customerId` replaces the id by the document — read with the grants and the scope of the target, never more than a direct read.
|
|
664
|
+
*
|
|
665
|
+
* refs: {
|
|
666
|
+
* customerId: 'customers', // one id
|
|
667
|
+
* tagIds: 'tags', // an array of ids (from the schema, or the value)
|
|
668
|
+
* 'billing.accountId': 'crm:accounts', // a nested field, a collection of another database
|
|
669
|
+
* }
|
|
670
|
+
*/
|
|
671
|
+
/** The target collection (`name` or `database:name`), or an object with it. */
|
|
672
|
+
type RefDeclaration = string | {
|
|
673
|
+
readonly collection: string;
|
|
674
|
+
};
|
|
675
|
+
interface ResolvedRef {
|
|
676
|
+
/** The field path of the reference. */
|
|
677
|
+
field: string;
|
|
678
|
+
/** The target collection as the API names it (`name` or `database:name`). */
|
|
679
|
+
collection: string;
|
|
680
|
+
/** An array of ids (from the schema); `undefined` when the schema does not tell, then the value decides. */
|
|
681
|
+
many?: boolean;
|
|
682
|
+
}
|
|
683
|
+
/** At most this many references are expanded by one read. */
|
|
684
|
+
declare const MaxExpands = 5;
|
|
685
|
+
/**
|
|
686
|
+
* The references of a declaration. `jsonSchema` is the schema of the documents (MongoDB form) when the schema has one: it tells which
|
|
687
|
+
* references are arrays. Refused: `_id`, a field a behaviour writes, a path through an array, an empty or invalid target.
|
|
688
|
+
*/
|
|
689
|
+
declare function resolveRefs(refs: Readonly<Record<string, RefDeclaration>> | undefined, behaviours: ResolvedBehaviours, jsonSchema?: Document$2): ResolvedRef[];
|
|
690
|
+
/** The target collection names of a refs declaration: `{ customerId: 'customers' }`. */
|
|
691
|
+
type RefTargets<R> = {
|
|
692
|
+
-readonly [K in keyof R]: R[K] extends string ? R[K] : R[K] extends {
|
|
693
|
+
collection: infer C extends string;
|
|
694
|
+
} ? C : never;
|
|
695
|
+
};
|
|
696
|
+
/** The refs of a declaration as field → target collection name (`{}` without refs). */
|
|
697
|
+
type InferRefs<D> = D extends {
|
|
698
|
+
refs: infer R;
|
|
699
|
+
} ? RefTargets<R> : Record<never, never>;
|
|
700
|
+
type Simplify<T> = {
|
|
701
|
+
[K in keyof T]: T[K];
|
|
702
|
+
} & {};
|
|
703
|
+
/** The value an expanded reference becomes: the target document or `null`; an array of ids becomes an array of documents. */
|
|
704
|
+
type ExpandedValue<V, Target> = NonNullable<V> extends readonly unknown[] ? Target[] : Target | null;
|
|
705
|
+
/** `T` with the value at the dot path `P` expanded to `Target` (optional fields stay optional). */
|
|
706
|
+
type ExpandAt<T, P extends string, Target> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? {
|
|
707
|
+
[K in keyof T]: K extends Head ? ExpandAt<NonNullable<T[K]>, Rest, Target> | Extract<T[K], null | undefined> : T[K];
|
|
708
|
+
} : T : P extends keyof T ? {
|
|
709
|
+
[K in keyof T]: K extends P ? ExpandedValue<T[K], Target> : T[K];
|
|
710
|
+
} : Simplify<T & {
|
|
711
|
+
[K in P]?: Target | Target[] | null;
|
|
712
|
+
}>;
|
|
713
|
+
type ExpandAll<T, Refs, Keys, Collections> = Keys extends readonly [infer First extends string, ...infer Rest] ? ExpandAll<ExpandAt<T, First, First extends keyof Refs ? (Refs[First] extends keyof Collections ? Collections[Refs[First]] : Record<string, unknown>) : Record<string, unknown>>, Refs, Rest, Collections> : T;
|
|
714
|
+
type UnionToTuple<U, Last = LastOf<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, Last>>, Last];
|
|
715
|
+
type LastOf<U> = ((U extends unknown ? (value: () => U) => void : never) extends (value: infer I) => void ? I : never) extends () => infer L ? L : never;
|
|
716
|
+
/**
|
|
717
|
+
* A document with the references `K` expanded: `ExpandedDocument<Order, { customerId: 'customers' }, 'customerId', { customers: Customer }>`
|
|
718
|
+
* has `customerId: Customer | null`. A target without a known type is `Record<string, unknown>`.
|
|
719
|
+
*/
|
|
720
|
+
type ExpandedDocument<T, Refs, K extends keyof Refs & string, Collections = Record<never, never>> = ExpandAll<T, Refs, UnionToTuple<K>, Collections>;
|
|
721
|
+
|
|
577
722
|
/**
|
|
578
723
|
* The validator of MongoDB for the declared collections (2.3.0), set when the declarations are registered. The validator of a declared
|
|
579
724
|
* collection belongs to its declaration:
|
|
@@ -618,7 +763,7 @@ declare function syncValidator(db: Db, declared: DeclaredCollection, logger: Mon
|
|
|
618
763
|
type ValidationMode = 'off' | 'warn' | 'error';
|
|
619
764
|
declare const DefaultValidationMode: ValidationMode;
|
|
620
765
|
/**
|
|
621
|
-
* A declared collection. Behaviours (2.
|
|
766
|
+
* A declared collection. Behaviours (2.3.0) are flags of the same object: `timestamps`, `owner`, `softDelete`, `versioned`, `audit`,
|
|
622
767
|
* `protectedFields` (see `BehaviourFlags`).
|
|
623
768
|
*/
|
|
624
769
|
interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSchemaV1> extends BehaviourFlags {
|
|
@@ -632,6 +777,10 @@ interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSch
|
|
|
632
777
|
validation?: ValidationMode;
|
|
633
778
|
/** A `$jsonSchema` validator for MongoDB that replaces the one converted from the schema (for schemas without JSON Schema form). */
|
|
634
779
|
validator?: Document$2;
|
|
780
|
+
/** Indexes (2.4.0): `'status'`, `'-createdAt'`, `['a', '-b']` or `{ fields, unique, ... }`; synced at the start (own indexes only). */
|
|
781
|
+
indexes?: readonly IndexDeclaration[];
|
|
782
|
+
/** References (2.4.0): field → target collection (`'customers'`, `'db:customers'`), for `expand` on reads. */
|
|
783
|
+
refs?: Readonly<Record<string, RefDeclaration>>;
|
|
635
784
|
/** Where the declaration comes from (a file), for the messages; set by the Nuxt module. */
|
|
636
785
|
source?: string;
|
|
637
786
|
}
|
|
@@ -644,13 +793,20 @@ type InferDocument<D extends MongocampCollectionDefinition> = unknown extends Sy
|
|
|
644
793
|
type InferDocumentInput<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferInput<D['schema']> : Merge<StandardSchemaV1.InferInput<D['schema']> & DeepPartial<SystemFields<D>>>;
|
|
645
794
|
/** Declares a collection; checks the declaration and keeps the types of its schema and its behaviours for `InferDocument`. */
|
|
646
795
|
declare function defineMongocampCollection<const D extends MongocampCollectionDefinition>(definition: D): D;
|
|
647
|
-
/**
|
|
796
|
+
/** The resolved references of a declaration; errors name the collection and the source. */
|
|
797
|
+
declare function refsOf(definition: MongocampCollectionDefinition, behaviours?: ResolvedBehaviours): ResolvedRef[];
|
|
648
798
|
interface DeclaredCollection {
|
|
649
799
|
definition: MongocampCollectionDefinition;
|
|
650
800
|
databaseName: string;
|
|
651
801
|
validation: ValidationMode;
|
|
652
|
-
/** The behaviours of the declaration with their defaults (2.
|
|
802
|
+
/** The behaviours of the declaration with their defaults (2.3.0). */
|
|
653
803
|
behaviours: ResolvedBehaviours;
|
|
804
|
+
/** The indexes of the declaration and its behaviours (2.4.0); empty when there are none. */
|
|
805
|
+
indexes: ResolvedIndex[];
|
|
806
|
+
/** The references of the declaration (2.4.0); empty when there are none. */
|
|
807
|
+
refs: ResolvedRef[];
|
|
808
|
+
/** What the start did with the indexes (2.4.0). */
|
|
809
|
+
indexSync?: IndexSyncResult;
|
|
654
810
|
/** What the start did with the validator of MongoDB (`collections()` feature). */
|
|
655
811
|
sync?: ValidatorSyncResult;
|
|
656
812
|
}
|
|
@@ -855,7 +1011,7 @@ interface components {
|
|
|
855
1011
|
additionalInfo: string;
|
|
856
1012
|
/** @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
1013
|
issues?: components["schemas"]["ValidationIssue"][];
|
|
858
|
-
/** @description The stored document of a version conflict (409, code 4092, 2.
|
|
1014
|
+
/** @description The stored document of a version conflict (409, code 4092, 2.3.0), as Extended JSON: show it or merge with it, then send the change again with its version. */
|
|
859
1015
|
current?: {
|
|
860
1016
|
[key: string]: unknown;
|
|
861
1017
|
};
|
|
@@ -1097,6 +1253,8 @@ interface components {
|
|
|
1097
1253
|
filter: components["schemas"]["Map_Any"];
|
|
1098
1254
|
sort: components["schemas"]["Map_Any"];
|
|
1099
1255
|
projection: components["schemas"]["Map_Any"];
|
|
1256
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1257
|
+
expand?: string[];
|
|
1100
1258
|
};
|
|
1101
1259
|
/** MongoIndex */
|
|
1102
1260
|
MongoIndex: {
|
|
@@ -1218,6 +1376,22 @@ interface components {
|
|
|
1218
1376
|
/** @description The fields the server writes (timestamps, owner, version, deleted mark); clients do not send them. */
|
|
1219
1377
|
systemFields: string[];
|
|
1220
1378
|
protectedFields: string[];
|
|
1379
|
+
/** @description The indexes of the declaration and its behaviours (2.4.0), synced at the start. */
|
|
1380
|
+
indexes: {
|
|
1381
|
+
name: string;
|
|
1382
|
+
key: {
|
|
1383
|
+
[key: string]: unknown;
|
|
1384
|
+
};
|
|
1385
|
+
unique: boolean;
|
|
1386
|
+
}[];
|
|
1387
|
+
/** @description The references of the declaration (2.4.0), the fields a read can expand (query parameter expand). */
|
|
1388
|
+
refs: {
|
|
1389
|
+
field: string;
|
|
1390
|
+
/** @description The target collection (name or database:name). */
|
|
1391
|
+
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;
|
|
1394
|
+
}[];
|
|
1221
1395
|
timestamps?: {
|
|
1222
1396
|
createdAt: string;
|
|
1223
1397
|
updatedAt: string;
|
|
@@ -1280,6 +1454,8 @@ interface components {
|
|
|
1280
1454
|
projection?: string[];
|
|
1281
1455
|
/** Format: int32 */
|
|
1282
1456
|
limit?: number;
|
|
1457
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1458
|
+
expand?: string[];
|
|
1283
1459
|
};
|
|
1284
1460
|
/** CountRequest */
|
|
1285
1461
|
CountRequest: {
|
|
@@ -1291,6 +1467,8 @@ interface components {
|
|
|
1291
1467
|
filter?: string;
|
|
1292
1468
|
sort?: string[];
|
|
1293
1469
|
projection?: string[];
|
|
1470
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1471
|
+
expand?: string[];
|
|
1294
1472
|
};
|
|
1295
1473
|
/** SettingsResponse */
|
|
1296
1474
|
SettingsResponse: {
|
|
@@ -1463,28 +1641,28 @@ interface MongocampEvents {
|
|
|
1463
1641
|
collectionName: string;
|
|
1464
1642
|
newCollectionName: string;
|
|
1465
1643
|
}>;
|
|
1466
|
-
/** `documents` (2.
|
|
1644
|
+
/** `documents` (2.3.0): the inserted documents of an insert or insertMany (not of an import), read only by listeners that need them. */
|
|
1467
1645
|
'document:create': ByUser<{
|
|
1468
1646
|
collectionName: string;
|
|
1469
1647
|
insertResponse: Schemas['InsertResponse'];
|
|
1470
1648
|
documents?: Document$1[];
|
|
1471
1649
|
}>;
|
|
1472
1650
|
/** `oldValues` are read only when a listener is registered for the hook. */
|
|
1473
|
-
/** `source` (2.
|
|
1651
|
+
/** `source` (2.3.0): a replace, a partial update or an update of many documents. */
|
|
1474
1652
|
'document:update': ByUser<{
|
|
1475
1653
|
collectionName: string;
|
|
1476
1654
|
updateResponse: Schemas['UpdateResponse'];
|
|
1477
1655
|
oldValues: Document$1[];
|
|
1478
1656
|
source?: 'replace' | 'update' | 'updateMany';
|
|
1479
1657
|
}>;
|
|
1480
|
-
/** `softDeleted` (2.
|
|
1658
|
+
/** `softDeleted` (2.3.0): a before-hook turned the delete into an update (`instead`), the documents are still stored. */
|
|
1481
1659
|
'document:delete': ByUser<{
|
|
1482
1660
|
collectionName: string;
|
|
1483
1661
|
deleteResponse: Schemas['DeleteResponse'];
|
|
1484
1662
|
oldValues: Document$1[];
|
|
1485
1663
|
softDeleted?: boolean;
|
|
1486
1664
|
}>;
|
|
1487
|
-
/** A soft-deleted document was restored (2.
|
|
1665
|
+
/** A soft-deleted document was restored (2.3.0); `oldValues` as for updates. */
|
|
1488
1666
|
'document:restore': ByUser<{
|
|
1489
1667
|
collectionName: string;
|
|
1490
1668
|
updateResponse: Schemas['UpdateResponse'];
|
|
@@ -1549,13 +1727,13 @@ declare class EventBus {
|
|
|
1549
1727
|
private readonly log;
|
|
1550
1728
|
readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
|
|
1551
1729
|
private readonly listeners;
|
|
1552
|
-
/** Listeners for some collections only (2.
|
|
1730
|
+
/** Listeners for some collections only (2.3.0): they make expensive payloads be read for these collections only. */
|
|
1553
1731
|
private readonly scoped;
|
|
1554
1732
|
private readonly observers;
|
|
1555
1733
|
private readonly targets;
|
|
1556
1734
|
constructor(log?: (message: string, error: unknown) => void);
|
|
1557
1735
|
/**
|
|
1558
|
-
* Registers a listener; the returned function removes it. With `collections` (2.
|
|
1736
|
+
* Registers a listener; the returned function removes it. With `collections` (2.3.0) it only gets the events of the collections the
|
|
1559
1737
|
* function accepts, and the expensive parts of an event (old values) are only read for them.
|
|
1560
1738
|
*/
|
|
1561
1739
|
on<N extends EventName>(name: N, listener: EventListener<N>, options?: {
|
|
@@ -1633,7 +1811,7 @@ interface InterceptorBase {
|
|
|
1633
1811
|
collectionName: string;
|
|
1634
1812
|
/** The database of the collection, resolved (the default database when the path names none). */
|
|
1635
1813
|
databaseName: string;
|
|
1636
|
-
/** The user has an administrator role (2.
|
|
1814
|
+
/** The user has an administrator role (2.3.0; set by the routes, absent in payloads built elsewhere). */
|
|
1637
1815
|
isAdmin?: boolean;
|
|
1638
1816
|
}
|
|
1639
1817
|
interface WriteInterceptorPayloads {
|
|
@@ -1645,7 +1823,7 @@ interface WriteInterceptorPayloads {
|
|
|
1645
1823
|
lines?: number[];
|
|
1646
1824
|
};
|
|
1647
1825
|
/**
|
|
1648
|
-
* A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.
|
|
1826
|
+
* A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.3.0): called by the route when the
|
|
1649
1827
|
* 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
1828
|
*/
|
|
1651
1829
|
'document:beforeReplace': InterceptorBase & {
|
|
@@ -1661,7 +1839,7 @@ interface WriteInterceptorPayloads {
|
|
|
1661
1839
|
onNoMatch?: () => void | Promise<void>;
|
|
1662
1840
|
};
|
|
1663
1841
|
/**
|
|
1664
|
-
* A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.
|
|
1842
|
+
* A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.3.0) turns the delete into this
|
|
1665
1843
|
* update (e.g. a deleted mark); the request is answered as a delete with the number of matched documents.
|
|
1666
1844
|
*/
|
|
1667
1845
|
'document:beforeDelete': InterceptorBase & {
|
|
@@ -1672,7 +1850,7 @@ interface WriteInterceptorPayloads {
|
|
|
1672
1850
|
};
|
|
1673
1851
|
};
|
|
1674
1852
|
/**
|
|
1675
|
-
* Every read of documents (2.
|
|
1853
|
+
* Every read of documents (2.3.0) and the target of every update, replace and delete: a hook narrows what the request may see by pushing
|
|
1676
1854
|
* conditions to `scopes` (`event.scopes.push({ tenant: 'a' })`); they are combined with the filter of the client by `$and`, so no client
|
|
1677
1855
|
* filter widens them. `filter` is the filter of the client (to look at, changing it has no effect). `withDeleted`: an administrator asked
|
|
1678
1856
|
* for soft-deleted documents too (`withDeleted=true`).
|
|
@@ -1684,8 +1862,11 @@ interface WriteInterceptorPayloads {
|
|
|
1684
1862
|
withDeleted: boolean;
|
|
1685
1863
|
};
|
|
1686
1864
|
}
|
|
1687
|
-
/**
|
|
1688
|
-
|
|
1865
|
+
/**
|
|
1866
|
+
* The kind of request a `document:beforeRead` scopes; `write` for the target of an update, replace or delete; `expand` (2.4.0) for the
|
|
1867
|
+
* documents a reference of another collection is expanded to.
|
|
1868
|
+
*/
|
|
1869
|
+
type ReadOperation = 'list' | 'search' | 'count' | 'get' | 'export' | 'distinct' | 'aggregate' | 'schema' | 'write' | 'restore' | 'watch' | 'expand';
|
|
1689
1870
|
type InterceptorName = keyof WriteInterceptorPayloads;
|
|
1690
1871
|
type WriteInterceptor<N extends InterceptorName> = (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
|
|
1691
1872
|
/**
|
|
@@ -1723,6 +1904,156 @@ declare class WriteInterceptors {
|
|
|
1723
1904
|
run<N extends InterceptorName>(name: N, payload: WriteInterceptorPayloads[N]): Promise<WriteInterceptorPayloads[N]>;
|
|
1724
1905
|
}
|
|
1725
1906
|
|
|
1907
|
+
interface InsertError {
|
|
1908
|
+
index: number;
|
|
1909
|
+
code: number;
|
|
1910
|
+
message: string;
|
|
1911
|
+
}
|
|
1912
|
+
interface ImportResponse {
|
|
1913
|
+
read: number;
|
|
1914
|
+
inserted: number;
|
|
1915
|
+
failed: number;
|
|
1916
|
+
errors: InsertError[];
|
|
1917
|
+
errorsTruncated: boolean;
|
|
1918
|
+
}
|
|
1919
|
+
declare class ImportState {
|
|
1920
|
+
read: number;
|
|
1921
|
+
inserted: number;
|
|
1922
|
+
failed: number;
|
|
1923
|
+
errors: InsertError[];
|
|
1924
|
+
errorsTruncated: boolean;
|
|
1925
|
+
/** The ids of the documents that were stored, as stored (for the compensation). */
|
|
1926
|
+
storedIds: unknown[];
|
|
1927
|
+
/** The ids as text, for the events of the caller. */
|
|
1928
|
+
get storedIdTexts(): string[];
|
|
1929
|
+
addErrors(errors: InsertError[]): void;
|
|
1930
|
+
get response(): ImportResponse;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
/**
|
|
1934
|
+
* How documents are written in responses (query parameter `extendedJson`).
|
|
1935
|
+
*
|
|
1936
|
+
* - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
|
|
1937
|
+
* decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
|
|
1938
|
+
* A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
|
|
1939
|
+
* - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
|
|
1940
|
+
* ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
|
|
1941
|
+
*/
|
|
1942
|
+
type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
|
|
1943
|
+
/** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
|
|
1944
|
+
declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
|
|
1945
|
+
/** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
|
|
1946
|
+
declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
|
|
1947
|
+
|
|
1948
|
+
interface FindRequest {
|
|
1949
|
+
filter: Record<string, unknown>;
|
|
1950
|
+
sort: Record<string, unknown>;
|
|
1951
|
+
projection: Record<string, unknown>;
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
/**
|
|
1955
|
+
* The scope of a read (2.3.0): the conditions of the `document:beforeRead` hooks (soft delete, owner, tenancy of an application) combined
|
|
1956
|
+
* with the filter of the client. Every route that reads documents, and every update, replace and delete for its target, goes through it;
|
|
1957
|
+
* without a hook nothing is done.
|
|
1958
|
+
*/
|
|
1959
|
+
/** The filter with the scopes, combined by `$and`; empty parts are left out. */
|
|
1960
|
+
declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]): Document$2;
|
|
1961
|
+
/** The filter of a request with the scopes of the hooks. */
|
|
1962
|
+
declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
|
|
1963
|
+
interface ScopeOptions {
|
|
1964
|
+
/** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
|
|
1965
|
+
withDeleted?: boolean;
|
|
1966
|
+
}
|
|
1967
|
+
/** `withDeleted=true` of a read route (2.3.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
|
|
1968
|
+
declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
|
|
1969
|
+
|
|
1970
|
+
interface ReadOptions extends ScopeOptions {
|
|
1971
|
+
/** The kind of request for the hooks of `document:beforeRead` (default by operation). */
|
|
1972
|
+
operation?: ReadOperation;
|
|
1973
|
+
/** References to expand (2.4.0): declared ref fields of the collection, at most `MaxExpands`. */
|
|
1974
|
+
expand?: readonly string[];
|
|
1975
|
+
}
|
|
1976
|
+
interface PageResult {
|
|
1977
|
+
documents: Document$2[];
|
|
1978
|
+
info: PaginationInfo;
|
|
1979
|
+
}
|
|
1980
|
+
declare class DocumentService {
|
|
1981
|
+
private readonly context;
|
|
1982
|
+
constructor(context: MongocampContext);
|
|
1983
|
+
/** The collection of a name as the routes take it (`orders`, `otherdb:orders`). */
|
|
1984
|
+
collection(name: string): Collection;
|
|
1985
|
+
/** The grant of the caller; `withDeleted` only for the administrators of the collection. */
|
|
1986
|
+
private require;
|
|
1987
|
+
/** The filter with the read scope of the caller. */
|
|
1988
|
+
scope(user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
|
|
1989
|
+
/**
|
|
1990
|
+
* The declared references of `fields` (2.4.0); 400 for a name that is no reference of the collection and for more than `MaxExpands`.
|
|
1991
|
+
* Checked before anything is read.
|
|
1992
|
+
*/
|
|
1993
|
+
refs(collection: string, fields: readonly string[] | undefined): ResolvedRef[];
|
|
1994
|
+
/**
|
|
1995
|
+
* Replaces the references of the documents by the documents they point to (2.4.0). Each target is read once per reference (`$in` of the
|
|
1996
|
+
* ids) with the grant and the read scope of the **target** for the same user, without its secret fields: a reference the user cannot
|
|
1997
|
+
* read directly becomes `null` (an array leaves it out), so an expansion never shows more than a direct read.
|
|
1998
|
+
*/
|
|
1999
|
+
expand(user: AuthorizedUser, documents: Document$2[], refs: readonly ResolvedRef[]): Promise<Document$2[]>;
|
|
2000
|
+
/** A page of documents (list, find, search), with the references of `options.expand` expanded. */
|
|
2001
|
+
page(user: AuthorizedUser, collection: string, request: FindRequest, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2002
|
+
/** The number of documents of a filter. */
|
|
2003
|
+
count(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<number>;
|
|
2004
|
+
/** One document by the id of the path (any type of id), `null` when it is missing or not in the scope of the caller. */
|
|
2005
|
+
get(user: AuthorizedUser, collection: string, id: string, options?: ReadOptions): Promise<Document$2 | null>;
|
|
2006
|
+
/** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
|
|
2007
|
+
exportFilter(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<{
|
|
2008
|
+
filter: Document$2;
|
|
2009
|
+
scope: Document$2;
|
|
2010
|
+
}>;
|
|
2011
|
+
/** The distinct values of a field, as aggregation results `{ _id, field }`. */
|
|
2012
|
+
distinct(user: AuthorizedUser, collection: string, field: string, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2013
|
+
/**
|
|
2014
|
+
* An aggregation: `prefix` (the client's filter, the unset of secrets) and the stages of the client, after the scope of the caller as
|
|
2015
|
+
* first `$match`. The checks of the pipeline (denied stages) are the route's.
|
|
2016
|
+
*/
|
|
2017
|
+
aggregate(user: AuthorizedUser, collection: string, prefix: Document$2[], stages: Document$2[], allowDiskUse: boolean, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2018
|
+
/**
|
|
2019
|
+
* Runs the before-hooks of a write (after auth and decoding, before the old values are read and the write is done) and answers the
|
|
2020
|
+
* payload with their changes. A hook that refuses the write throws.
|
|
2021
|
+
*/
|
|
2022
|
+
private intercept;
|
|
2023
|
+
/**
|
|
2024
|
+
* The insert hooks: they may change the documents, but not their number (the errors of an insert and of an import name the documents by
|
|
2025
|
+
* their position). A hook that does not want a document refuses the write.
|
|
2026
|
+
*/
|
|
2027
|
+
private interceptInsert;
|
|
2028
|
+
/** The documents before a change, read only when a listener waits for them; at most `MaxOldValues`. */
|
|
2029
|
+
private oldValues;
|
|
2030
|
+
/** Deletes the documents of the filter, or applies the update of a before-hook instead (soft delete); answers the number of documents. */
|
|
2031
|
+
private deleteOrInstead;
|
|
2032
|
+
private inserted;
|
|
2033
|
+
private updated;
|
|
2034
|
+
private deleted;
|
|
2035
|
+
/** Inserts one document (decoded). */
|
|
2036
|
+
insert(user: AuthorizedUser, collection: string, document: Document$2): Promise<Schemas['InsertResponse']>;
|
|
2037
|
+
/** Inserts documents; `ordered: false` stores the ones that can be stored and reports the others in `errors`. */
|
|
2038
|
+
insertMany(user: AuthorizedUser, collection: string, input: Document$2[], ordered?: boolean): Promise<Schemas['InsertResponse']>;
|
|
2039
|
+
/** Imports the lines of a body stream (all or nothing); the hooks see the valid documents of each batch. */
|
|
2040
|
+
import(user: AuthorizedUser, collection: string, body: ReadableStream<Uint8Array> | null, maxBytes: number): Promise<ImportState>;
|
|
2041
|
+
/** Replaces the document of the path id (decoded body); 404 when it is missing or not in the scope, 409 of a version check. */
|
|
2042
|
+
replace(user: AuthorizedUser, collection: string, id: string, body: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2043
|
+
/** Changes the document of the path id with an operator update (`$set`, ...). */
|
|
2044
|
+
update(user: AuthorizedUser, collection: string, id: string, operators: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2045
|
+
/** Changes the documents of a filter (checked by the caller: not empty unless intended). */
|
|
2046
|
+
updateMany(user: AuthorizedUser, collection: string, filter: Document$2, operators: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2047
|
+
/** Deletes the document of the path id (or marks it, soft delete); 404 when it is missing or not in the scope. */
|
|
2048
|
+
remove(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['DeleteResponse']>;
|
|
2049
|
+
/** Deletes the documents of a filter (checked by the caller). */
|
|
2050
|
+
removeMany(user: AuthorizedUser, collection: string, filter: Document$2): Promise<Schemas['DeleteResponse']>;
|
|
2051
|
+
/** Brings a soft-deleted document back (collections declared with softDelete). */
|
|
2052
|
+
restore(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['UpdateResponse']>;
|
|
2053
|
+
/** The audit records of a filter (a document or the collection), newest first. */
|
|
2054
|
+
auditRecords(filter: Document$2, paging: Paging, count?: CountMode): Promise<PageResult>;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
1726
2057
|
/**
|
|
1727
2058
|
* Jobs (`JobPlugin.scala`, `JobRoutes.scala`) on croner. A job is a document `JobConfig` in `<AUTH_PREFIX>jobs`; its `className` names a
|
|
1728
2059
|
* handler of the registry (the Scala server loaded JVM classes). Cron expressions use the syntax of croner: 5, 6 or 7 fields (seconds and
|
|
@@ -1863,6 +2194,8 @@ interface MongocampContext {
|
|
|
1863
2194
|
events: EventBus;
|
|
1864
2195
|
/** The before-hooks of the document writes (awaited, may change or refuse a write). */
|
|
1865
2196
|
interceptors: WriteInterceptors;
|
|
2197
|
+
/** The documents of the collections for one caller, without HTTP (2.4.0): the routes and the server collection use it. */
|
|
2198
|
+
documents: DocumentService;
|
|
1866
2199
|
/** The declared collections (`server.use(collections([...]))`), empty without. */
|
|
1867
2200
|
collections: CollectionRegistry;
|
|
1868
2201
|
jobs: JobScheduler;
|
|
@@ -1874,6 +2207,78 @@ interface MongocampContext {
|
|
|
1874
2207
|
shutdown?: (force: boolean) => void | Promise<void>;
|
|
1875
2208
|
}
|
|
1876
2209
|
|
|
2210
|
+
/**
|
|
2211
|
+
* The documents of a collection in server code (2.4.0): `server.collection('orders', { user })` — the same operations as the API
|
|
2212
|
+
* (`DocumentService`), so grants, the read scope (owner, soft delete, hooks), validation, the behaviours (timestamps, version, audit) and
|
|
2213
|
+
* the events are the same as for a request of that user. No HTTP, no JSON: documents come and go as driver values (`ObjectId`, `Date`;
|
|
2214
|
+
* numbers as JavaScript numbers).
|
|
2215
|
+
*
|
|
2216
|
+
* For writes that must not go through the rules (migrations, bulk scripts) use the driver (`server.context.database`).
|
|
2217
|
+
*/
|
|
2218
|
+
/**
|
|
2219
|
+
* Who works with the collection: a user id, an authorized user, a `Request` (its credentials; in Nitro the request of the event), or
|
|
2220
|
+
* `'system'` — an administrator without grant checks and owner rules, for jobs and seeds.
|
|
2221
|
+
*/
|
|
2222
|
+
type ServerCollectionUser = string | AuthorizedUser | Request | 'system';
|
|
2223
|
+
interface ServerCollectionOptions {
|
|
2224
|
+
user: ServerCollectionUser;
|
|
2225
|
+
}
|
|
2226
|
+
interface ServerFindOptions {
|
|
2227
|
+
/** A MongoDB filter, or a Lucene filter as text (`status:open AND qty:[1 TO 5]`). */
|
|
2228
|
+
filter?: Document$2 | string;
|
|
2229
|
+
/** `{ field: 1 | -1 }` or fields with `-` for descending. */
|
|
2230
|
+
sort?: Document$2 | string[];
|
|
2231
|
+
projection?: Document$2 | string[];
|
|
2232
|
+
page?: number;
|
|
2233
|
+
rowsPerPage?: number;
|
|
2234
|
+
count?: CountMode;
|
|
2235
|
+
/** Soft-deleted documents too (administrators of the collection). */
|
|
2236
|
+
withDeleted?: boolean;
|
|
2237
|
+
/** References to expand (2.4.0): declared ref fields, read with the grant and scope of their collection. */
|
|
2238
|
+
expand?: readonly string[];
|
|
2239
|
+
}
|
|
2240
|
+
interface ServerPage<T> {
|
|
2241
|
+
documents: T[];
|
|
2242
|
+
page: number;
|
|
2243
|
+
rowsPerPage: number;
|
|
2244
|
+
countRows?: number;
|
|
2245
|
+
countPages?: number;
|
|
2246
|
+
}
|
|
2247
|
+
/** A document that was read (with `_id`), or its id. */
|
|
2248
|
+
type ServerDocumentIdentity = string | number | ObjectId | {
|
|
2249
|
+
_id: unknown;
|
|
2250
|
+
};
|
|
2251
|
+
interface ServerCollection<T, I = T> {
|
|
2252
|
+
readonly name: string;
|
|
2253
|
+
find: (options?: ServerFindOptions) => Promise<T[]>;
|
|
2254
|
+
findPage: (options?: ServerFindOptions) => Promise<ServerPage<T>>;
|
|
2255
|
+
/** The document, `null` when it is missing or not in the scope of the user. */
|
|
2256
|
+
findById: (id: ServerDocumentIdentity, options?: {
|
|
2257
|
+
withDeleted?: boolean;
|
|
2258
|
+
expand?: readonly string[];
|
|
2259
|
+
}) => Promise<T | null>;
|
|
2260
|
+
count: (filter?: Document$2 | string, options?: {
|
|
2261
|
+
withDeleted?: boolean;
|
|
2262
|
+
}) => Promise<number>;
|
|
2263
|
+
insert: (document: I) => Promise<Schemas['InsertResponse']>;
|
|
2264
|
+
insertMany: (documents: I[], options?: {
|
|
2265
|
+
ordered?: boolean;
|
|
2266
|
+
}) => Promise<Schemas['InsertResponse']>;
|
|
2267
|
+
/** Replaces the document; given the document that was read, its version is checked (409 when someone changed it in between). */
|
|
2268
|
+
replace: (target: ServerDocumentIdentity, document: I) => Promise<Schemas['UpdateResponse']>;
|
|
2269
|
+
/** Sets the given fields (`null` removes one); given the document that was read, its version is checked. */
|
|
2270
|
+
update: (target: ServerDocumentIdentity, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
|
|
2271
|
+
updateMany: (filter: Document$2 | string, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
|
|
2272
|
+
remove: (target: ServerDocumentIdentity) => Promise<Schemas['DeleteResponse']>;
|
|
2273
|
+
removeMany: (filter: Document$2 | string) => Promise<Schemas['DeleteResponse']>;
|
|
2274
|
+
restore: (target: ServerDocumentIdentity) => Promise<Schemas['UpdateResponse']>;
|
|
2275
|
+
/** The audit records of the document, newest first (collections declared with `audit`). */
|
|
2276
|
+
history: (target: ServerDocumentIdentity) => Promise<Document$2[]>;
|
|
2277
|
+
}
|
|
2278
|
+
/** The administrator of server code: every grant, no owner rule (`adminBypass`). */
|
|
2279
|
+
declare const SystemUser: AuthorizedUser;
|
|
2280
|
+
declare function createServerCollection<T = Document$2, I = T>(context: MongocampContext, name: string, options: ServerCollectionOptions): ServerCollection<T, I>;
|
|
2281
|
+
|
|
1877
2282
|
interface MongocampServerOptions extends DatabaseOptions {
|
|
1878
2283
|
/** Environment variables, `process.env` when omitted. */
|
|
1879
2284
|
env?: ConfigSources['env'];
|
|
@@ -1948,6 +2353,11 @@ interface MongocampServer {
|
|
|
1948
2353
|
* same name is used once; it is stopped by `close`.
|
|
1949
2354
|
*/
|
|
1950
2355
|
use: (feature: MongocampFeature) => Promise<void>;
|
|
2356
|
+
/**
|
|
2357
|
+
* The documents of a collection for a user in server code (2.4.0): the same grants, scope, validation, behaviours and events as the API.
|
|
2358
|
+
* `user`: an id, an authorized user, a request (its credentials) or `'system'`.
|
|
2359
|
+
*/
|
|
2360
|
+
collection: <T = Record<string, unknown>, I = T>(name: string, options: ServerCollectionOptions) => ServerCollection<T, I>;
|
|
1951
2361
|
close: () => Promise<void>;
|
|
1952
2362
|
}
|
|
1953
2363
|
/** Creates and connects a MongoCamp server. */
|
|
@@ -1987,15 +2397,15 @@ declare const ErrorCodes: {
|
|
|
1987
2397
|
/** A document that a schema or a before-hook refuses; `ErrorDescription.issues` names the fields (the validator of MongoDB answers 121). */
|
|
1988
2398
|
readonly validationFailed: 4010;
|
|
1989
2399
|
readonly collectionExists: 4091;
|
|
1990
|
-
/** A write based on an outdated version of a versioned document (2.
|
|
2400
|
+
/** A write based on an outdated version of a versioned document (2.3.0); `ErrorDescription.current` is the stored document. */
|
|
1991
2401
|
readonly versionConflict: 4092;
|
|
1992
|
-
/** A versioned collection with `required: true` got a write without version (2.
|
|
2402
|
+
/** A versioned collection with `required: true` got a write without version (2.3.0). */
|
|
1993
2403
|
readonly versionRequired: 4281;
|
|
1994
2404
|
readonly badInsertRequest: 4401;
|
|
1995
2405
|
readonly idMissingForReplace: 4402;
|
|
1996
2406
|
readonly authMethodNotImplemented: 5001;
|
|
1997
2407
|
readonly mvnRepositoryConfigurationInvalid: 5002;
|
|
1998
|
-
/** Live updates need change streams: a replica set or a sharded cluster (2.
|
|
2408
|
+
/** Live updates need change streams: a replica set or a sharded cluster (2.3.0). */
|
|
1999
2409
|
readonly changeStreamsUnsupported: 5011;
|
|
2000
2410
|
readonly unauthorizedUser: 4011;
|
|
2001
2411
|
readonly unauthorizedUserForOtherUser: 4012;
|
|
@@ -2046,21 +2456,6 @@ declare function convertIdValue(id: unknown): unknown;
|
|
|
2046
2456
|
*/
|
|
2047
2457
|
declare function pathIdFilter(id: string): PlainObject;
|
|
2048
2458
|
|
|
2049
|
-
/**
|
|
2050
|
-
* How documents are written in responses (query parameter `extendedJson`).
|
|
2051
|
-
*
|
|
2052
|
-
* - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
|
|
2053
|
-
* decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
|
|
2054
|
-
* A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
|
|
2055
|
-
* - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
|
|
2056
|
-
* ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
|
|
2057
|
-
*/
|
|
2058
|
-
type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
|
|
2059
|
-
/** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
|
|
2060
|
-
declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
|
|
2061
|
-
/** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
|
|
2062
|
-
declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
|
|
2063
|
-
|
|
2064
2459
|
/**
|
|
2065
2460
|
* The queries that the Lucene parser produces (the subset of `org.apache.lucene.search.Query` that `LuceneQueryConverter` knows),
|
|
2066
2461
|
* plus the kinds it does not support, which fail in the converter like in the Scala driver.
|
|
@@ -2198,7 +2593,7 @@ declare const bsonMarkerOptions: {
|
|
|
2198
2593
|
};
|
|
2199
2594
|
/**
|
|
2200
2595
|
* 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.
|
|
2596
|
+
* added (2.3.0, see `withSystemFields`) unless `systemFields: false`.
|
|
2202
2597
|
*/
|
|
2203
2598
|
declare function validatorOf(definition: MongocampCollectionDefinition, options?: {
|
|
2204
2599
|
systemFields?: boolean;
|
|
@@ -2213,7 +2608,7 @@ declare function withSystemFields(jsonSchema: Document$2, behaviours: ResolvedBe
|
|
|
2213
2608
|
declare function toMongoJsonSchema(root: Record<string, unknown>): ConversionResult;
|
|
2214
2609
|
|
|
2215
2610
|
/**
|
|
2216
|
-
* What clients may not write (2.
|
|
2611
|
+
* What clients may not write (2.3.0): the fields of behaviours (timestamps, owner, version, deleted mark) and the `protectedFields` of a
|
|
2217
2612
|
* declaration. The guard runs first (stage `guard`), so before-hooks and Nitro hooks of the application can still set protected fields;
|
|
2218
2613
|
* writes with the driver (`useMongocampCore()`, scripts) are not checked at all.
|
|
2219
2614
|
*
|
|
@@ -2237,23 +2632,7 @@ declare function stripDocument(document: Document$2, paths: readonly string[]):
|
|
|
2237
2632
|
declare function stripUpdate(update: Document$2, guarded: readonly string[], system: readonly string[]): Document$2;
|
|
2238
2633
|
|
|
2239
2634
|
/**
|
|
2240
|
-
* The
|
|
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
|
|
2635
|
+
* The behaviour `softDelete` (2.3.0): a delete sets the deleted mark (`deletedAt`) instead of removing the document, every read hides
|
|
2257
2636
|
* marked documents (`document:beforeRead`), an administrator sees them with `withDeleted=true`, `POST …/documents/{id}/restore` removes
|
|
2258
2637
|
* the mark, and `purgeAfterDays` removes marked documents for good (a TTL index).
|
|
2259
2638
|
*/
|
|
@@ -2274,7 +2653,7 @@ declare function purgeIndexName(softDelete: SoftDelete): string;
|
|
|
2274
2653
|
declare function syncPurgeIndex(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<'created' | 'changed' | 'dropped' | 'unchanged' | 'failed'>;
|
|
2275
2654
|
|
|
2276
2655
|
/**
|
|
2277
|
-
* The behaviour `owner` (2.
|
|
2656
|
+
* The behaviour `owner` (2.3.0): every document belongs to the user who created it. Only the owner changes, replaces, deletes and restores
|
|
2278
2657
|
* it; reads follow `read` — `own` (default) the owner only, `all` everybody with the read grant, or a function of the application.
|
|
2279
2658
|
* A document of someone else is answered like a missing one (404), so nobody learns which ids exist. Administrators read and write every
|
|
2280
2659
|
* document (`adminBypass`, default true). The collection grants still apply first: owner rules narrow them, never widen them.
|
|
@@ -2286,7 +2665,7 @@ type Owner = NonNullable<ResolvedBehaviours['owner']>;
|
|
|
2286
2665
|
declare function ownedBy(owner: Owner, userId: string): Document$2;
|
|
2287
2666
|
|
|
2288
2667
|
/**
|
|
2289
|
-
* The behaviour `audit` (2.
|
|
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
|
|
2290
2669
|
* before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
|
|
2291
2670
|
*
|
|
2292
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
|
|
@@ -2331,7 +2710,7 @@ declare function auditRecords(input: {
|
|
|
2331
2710
|
declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
|
|
2332
2711
|
|
|
2333
2712
|
/**
|
|
2334
|
-
* The behaviour `versioned` (2.
|
|
2713
|
+
* 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
|
|
2335
2714
|
* the document still has that version; otherwise it answers 409 with the stored document (`current`) instead of overwriting the change of
|
|
2336
2715
|
* someone else. In the same write, no read-then-write race.
|
|
2337
2716
|
*
|
|
@@ -2352,7 +2731,7 @@ declare function withVersion(filter: Document$2, versioned: Versioned, version:
|
|
|
2352
2731
|
declare function withIncrement(update: Document$2, versioned: Versioned): Document$2;
|
|
2353
2732
|
|
|
2354
2733
|
/**
|
|
2355
|
-
* The behaviour `timestamps` (2.
|
|
2734
|
+
* The behaviour `timestamps` (2.3.0): the server writes the creation and change time and, when configured, the user of the request
|
|
2356
2735
|
* (`createdBy`, `updatedBy`) on every write path. Runs in the stage `system`, after the validation, and after the guard put the stored
|
|
2357
2736
|
* values of a replace back — so the creation values survive every later write. Clients cannot send these fields (guard).
|
|
2358
2737
|
*/
|
|
@@ -2408,5 +2787,5 @@ declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'inter
|
|
|
2408
2787
|
*/
|
|
2409
2788
|
declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
|
|
2410
2789
|
|
|
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 };
|
|
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 };
|