@sfxcode/mongocamp-server-core 2.5.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -40,6 +40,7 @@ declare const ConfigKeys: {
40
40
  readonly WatchQueueMax: "WATCH_QUEUE_MAX";
41
41
  readonly ServerHeaderEnabled: "SERVER_HEADER_ENABLED";
42
42
  readonly ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL";
43
+ readonly UsersReadHideApiKey: "USERS_READ_HIDE_API_KEY";
43
44
  readonly ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS";
44
45
  readonly FilterTimeZone: "FILTER_TIME_ZONE";
45
46
  readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
@@ -154,6 +155,8 @@ declare class MongocampDatabase {
154
155
  db(name?: string): Db;
155
156
  /** Name of an internal collection, with the `AUTH_PREFIX` (`mc_users`, `mc_roles`, `mc_token_cache`, ...). */
156
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;
157
160
  close(): Promise<void>;
158
161
  }
159
162
 
@@ -178,13 +181,18 @@ declare class MongocampError extends Error {
178
181
  readonly additionalInfo: string;
179
182
  readonly issues?: ValidationIssue[] | undefined;
180
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>;
181
189
  constructor(message: string, status: number, code?: number, additionalInfo?: string, issues?: ValidationIssue[] | undefined, current?: Record<string, unknown> | undefined);
182
190
  get description(): ErrorDescription;
183
191
  static badRequest(message: string, code?: number): MongocampError;
184
192
  /** 400 for documents that are not valid, with the fields in `issues` (a schema, a before-hook). */
185
193
  static validation(issues: ValidationIssue[], message?: string, code?: number): MongocampError;
186
194
  /** 409 for a write based on an outdated version, with the stored document (as Extended JSON) for the client to show or merge. */
187
- static versionConflict(current: Record<string, unknown>): MongocampError;
195
+ static versionConflict(current: Record<string, unknown>, storedDocument?: Record<string, unknown>): MongocampError;
188
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. */
189
197
  static forbidden(message: string, code?: number): MongocampError;
190
198
  static unauthorized(message?: string, code?: number): MongocampError;
@@ -196,6 +204,11 @@ type ErrorLogger = (error: unknown, status: number) => void;
196
204
  interface ErrorResponseOptions {
197
205
  /** The message of an unexpected error in the answer (`ERRORS_EXPOSE_INTERNAL`, for development); by default only the log has it. */
198
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;
199
212
  }
200
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`). */
201
214
  declare const InternalErrorMessage = "internal server error, the log of the server has the details (x-request-id)";
@@ -666,6 +679,8 @@ interface ResolvedIndex {
666
679
  fingerprint: string;
667
680
  /** Declared, or added for a behaviour. */
668
681
  origin: 'declaration' | 'owner';
682
+ /** The partial filter was added by soft delete (2.6.0: told in the declaration answer). */
683
+ softDeleteFilter?: boolean;
669
684
  }
670
685
  /**
671
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
@@ -683,9 +698,13 @@ declare function resolveIndexes(declarations: readonly IndexDeclaration[] | unde
683
698
  * 'billing.accountId': 'crm:accounts', // a nested field, a collection of another database
684
699
  * }
685
700
  */
686
- /** 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
+ */
687
705
  type RefDeclaration = string | {
688
706
  readonly collection: string;
707
+ readonly many?: boolean;
689
708
  };
690
709
  interface ResolvedRef {
691
710
  /** The field path of the reference. */
@@ -825,6 +844,13 @@ interface DeclaredCollection {
825
844
  /** What the start did with the validator of MongoDB (`collections()` feature). */
826
845
  sync?: ValidatorSyncResult;
827
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
+ }
828
854
  /** The declarations of a server by database and collection; `context.collections`. */
829
855
  declare class CollectionRegistry {
830
856
  private readonly entries;
@@ -833,6 +859,13 @@ declare class CollectionRegistry {
833
859
  find(databaseName: string, name: string): DeclaredCollection | undefined;
834
860
  /** The declaration of a collection as the routes name it (`orders`, `otherdb:orders`). */
835
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[];
836
869
  get size(): number;
837
870
  all(): DeclaredCollection[];
838
871
  /** Adds declarations, all or none (a collection that is declared twice is an error); the returned function removes them. */
@@ -871,6 +904,26 @@ interface components {
871
904
  CapabilityLimits: {
872
905
  /** Format: int64 */
873
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;
874
927
  /** Format: int32 */
875
928
  grantDeniedStatus: number;
876
929
  };
@@ -1398,14 +1451,44 @@ interface components {
1398
1451
  [key: string]: unknown;
1399
1452
  };
1400
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;
1401
1475
  }[];
1402
1476
  /** @description The references of the declaration (2.4.0), the fields a read can expand (query parameter expand). */
1403
1477
  refs: {
1404
1478
  field: string;
1405
1479
  /** @description The target collection (name or database:name). */
1406
1480
  collection: string;
1407
- /** @description Whether the field holds an array of ids (from the schema); missing when the schema does not tell. */
1408
- 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;
1409
1492
  }[];
1410
1493
  timestamps?: {
1411
1494
  createdAt: string;
@@ -1791,6 +1874,12 @@ declare class ConfigPersistence {
1791
1874
  private persistentDefinitions;
1792
1875
  /** Registers the missing keys with their defaults (`registerConfig`) and reads the stored values; the refresh starts if wanted. */
1793
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;
1794
1883
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
1795
1884
  refresh(startup: boolean): Promise<void>;
1796
1885
  /** A configuration as answered by the API: the stored one, the one of the env, or a non persistent one. */
@@ -1803,6 +1892,11 @@ declare class ConfigPersistence {
1803
1892
  * in this instance, the other instances read it with their next refresh.
1804
1893
  */
1805
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>;
1806
1900
  close(): void;
1807
1901
  }
1808
1902
 
@@ -2410,6 +2504,12 @@ declare const ErrorCodes: {
2410
2504
  readonly changeStreamsUnsupported: 5011;
2411
2505
  readonly unauthorizedUser: 4011;
2412
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;
2413
2513
  readonly forbiddenStage: 4031;
2414
2514
  readonly forbiddenCollectionInStage: 4032;
2415
2515
  readonly jobAlreadyAdded: 4121;
@@ -2617,6 +2717,10 @@ declare class LuceneQueryError extends Error {
2617
2717
  * - ranges are `$gte`/`$gt`/`$lte`/`$lt`, `[* TO *]`, `field:*` and `_exists_:field` are `$exists`
2618
2718
  *
2619
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).
2620
2724
  */
2621
2725
  type Filter = Record<string, unknown>;
2622
2726
  interface ConvertOptions {
@@ -2625,6 +2729,8 @@ interface ConvertOptions {
2625
2729
  caseInsensitive?: boolean;
2626
2730
  /** The time zone of dates without offset (`FILTER_TIME_ZONE`), UTC by default. */
2627
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>;
2628
2734
  }
2629
2735
  declare function luceneQueryToFilter(query: LuceneQuery, options?: ConvertOptions): Filter;
2630
2736
 
package/dist/index.mjs CHANGED
@@ -148,6 +148,12 @@ const ErrorCodes = {
148
148
  changeStreamsUnsupported: 5011,
149
149
  unauthorizedUser: 4011,
150
150
  unauthorizedUserForOtherUser: 4012,
151
+ /** 413 (2.6.0): the body is greater than `BODY_MAX_BYTES`. */
152
+ bodyTooLarge: 4131,
153
+ /** 413 (2.6.0): the uploaded file is greater than `GRIDFS_UPLOAD_MAX_BYTES`. */
154
+ uploadTooLarge: 4132,
155
+ /** 413 (2.6.0): the import is greater than `IMPORT_MAX_BYTES`. */
156
+ importTooLarge: 4133,
151
157
  forbiddenStage: 4031,
152
158
  forbiddenCollectionInStage: 4032,
153
159
  jobAlreadyAdded: 4121,
@@ -424,6 +430,11 @@ class MongocampError extends Error {
424
430
  this.current = current;
425
431
  this.name = "MongocampError";
426
432
  }
433
+ /**
434
+ * 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
435
+ * JSON mode of the request (`currentIn`); `current` is relaxed.
436
+ */
437
+ storedDocument;
427
438
  get description() {
428
439
  const description = { code: this.code, msg: this.message, additionalInfo: this.additionalInfo };
429
440
  if (this.issues !== void 0) {
@@ -442,8 +453,12 @@ class MongocampError extends Error {
442
453
  return new MongocampError(message, 400, code, "", issues);
443
454
  }
444
455
  /** 409 for a write based on an outdated version, with the stored document (as Extended JSON) for the client to show or merge. */
445
- static versionConflict(current) {
446
- return new MongocampError("the document was changed in the meantime: read it again (current) and repeat the change", 409, ErrorCodes.versionConflict, "", void 0, current);
456
+ static versionConflict(current, storedDocument) {
457
+ const error = new MongocampError("the document was changed in the meantime: read it again (current) and repeat the change", 409, ErrorCodes.versionConflict, "", void 0, current);
458
+ if (storedDocument !== void 0) {
459
+ error.storedDocument = storedDocument;
460
+ }
461
+ return error;
447
462
  }
448
463
  /** 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. */
449
464
  static forbidden(message, code = -1) {
@@ -483,7 +498,11 @@ const InternalErrorMessage = "internal server error, the log of the server has t
483
498
  function toErrorResponse(error, log = defaultLogger, options = {}) {
484
499
  const cause = error instanceof HTTPError && error.cause instanceof Error ? error.cause : error;
485
500
  if (cause instanceof MongocampError) {
486
- return errorResponse(cause.status, cause.description);
501
+ const description = cause.description;
502
+ if (cause.storedDocument !== void 0 && options.currentIn !== void 0) {
503
+ description.current = options.currentIn(cause.storedDocument);
504
+ }
505
+ return errorResponse(cause.status, description);
487
506
  }
488
507
  const databaseError = findDatabaseError(cause);
489
508
  if (databaseError) {
@@ -900,6 +919,7 @@ const ConfigKeys = {
900
919
  // new in 2.5.0: what the answers of the server show (the `server` header, the messages of unexpected errors) and csv formula escaping
901
920
  ServerHeaderEnabled: "SERVER_HEADER_ENABLED",
902
921
  ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL",
922
+ UsersReadHideApiKey: "USERS_READ_HIDE_API_KEY",
903
923
  ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS",
904
924
  // new in 2.0.0: the time zone of dates without offset in Lucene filters
905
925
  FilterTimeZone: "FILTER_TIME_ZONE",
@@ -982,6 +1002,8 @@ const configDefinitions = [
982
1002
  define(K.WatchQueueMax, "Long", 1e3),
983
1003
  define(K.ServerHeaderEnabled, "Boolean", true),
984
1004
  define(K.ErrorsExposeInternal, "Boolean", false),
1005
+ // 2.6.0: the document routes leave out apiKey of the users collection too (default true in 3.0)
1006
+ define(K.UsersReadHideApiKey, "Boolean", false),
985
1007
  define(K.ExportCsvEscapeFormulas, "Boolean", false),
986
1008
  define(K.FilterTimeZone, "String", "UTC"),
987
1009
  define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
@@ -992,7 +1014,7 @@ const configDefinitions = [
992
1014
  define(K.FileHandler, "String", "gridfs", restart),
993
1015
  define(K.FileCacheAge, "String", "7776000"),
994
1016
  define(K.CorsHeadersAllowed, "List[String]", ["Authorization", "Content-Type", "X-Requested-With", "X-AUTH-APIKEY"]),
995
- define(K.CorsHeadersExposed, "List[String]", ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-pagination-next", "x-request-id"]),
1017
+ define(K.CorsHeadersExposed, "List[String]", ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-pagination-next", "x-request-id", "x-export-max-documents"]),
996
1018
  define(K.CorsOriginsAllowed, "List[String]", ["http://localhost:8080"]),
997
1019
  define(K.DocsSwagger, "Boolean", false, restart),
998
1020
  define(K.DocsOpenApi, "Boolean", true, restart),
@@ -1035,6 +1057,9 @@ function longQuery(params, name) {
1035
1057
  }
1036
1058
  return value;
1037
1059
  }
1060
+ function limitPaging(paging, maxRows) {
1061
+ return maxRows > 0 && (paging.rowsPerPage ?? 0) > maxRows ? { ...paging, rowsPerPage: maxRows } : paging;
1062
+ }
1038
1063
  function readPaging(params) {
1039
1064
  const paging = { rowsPerPage: longQuery(params, "rowsPerPage"), page: longQuery(params, "page") };
1040
1065
  if (params.has("after")) {
@@ -2000,6 +2025,7 @@ class ConfigPersistence {
2000
2025
  };
2001
2026
  await this.collection.updateOne({ key: definition.key }, { $setOnInsert: document }, { upsert: true });
2002
2027
  }
2028
+ await this.upgradeLegacyDefaults();
2003
2029
  await this.refresh(true);
2004
2030
  if (refreshMillis !== false) {
2005
2031
  this.timer = setInterval(() => {
@@ -2008,6 +2034,14 @@ class ConfigPersistence {
2008
2034
  this.timer.unref?.();
2009
2035
  }
2010
2036
  }
2037
+ /**
2038
+ * 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
2039
+ * 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
2040
+ * administrator who wants 401 patches it again (then it is marked and stays).
2041
+ */
2042
+ async upgradeLegacyDefaults() {
2043
+ await this.collection.updateOne({ key: "AUTH_GRANT_DENIED_STATUS", value: 401, changedAt: { $exists: false } }, { $set: { value: 403 } });
2044
+ }
2011
2045
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
2012
2046
  async refresh(startup) {
2013
2047
  const documents = await this.collection.find({}).toArray();
@@ -2067,7 +2101,7 @@ class ConfigPersistence {
2067
2101
  }
2068
2102
  const internal = valueForUpdate(definition, value);
2069
2103
  const stored = toStored(definition.type, internal);
2070
- const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored } });
2104
+ const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored, changedAt: /* @__PURE__ */ new Date() } });
2071
2105
  if (!before) {
2072
2106
  return false;
2073
2107
  }
@@ -2077,6 +2111,24 @@ class ConfigPersistence {
2077
2111
  }
2078
2112
  return true;
2079
2113
  }
2114
+ /**
2115
+ * 2.6.0: the default again (`DELETE /system/configurations/{key}`), at once in this instance for a key that needs no restart. The
2116
+ * reasons it is not possible are answered by the route (unknown, not persistent, set by the environment, a generated default).
2117
+ */
2118
+ async reset(key) {
2119
+ const definition = this.config.definition(key);
2120
+ if (!definition?.persistent || this.config.overrideOf(key) === "env" || typeof definition.defaultValue === "function") {
2121
+ return false;
2122
+ }
2123
+ const internal = definition.defaultValue;
2124
+ const stored = toStored(definition.type, internal);
2125
+ const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored, comment: "" }, $unset: { changedAt: "" } }, { upsert: true });
2126
+ this.events?.publish("config:update", { key, newValue: SecretKeys.has(key) ? SecretMask : stored, oldValue: SecretKeys.has(key) ? SecretMask : before?.value ?? null, callingMethod: "resetConfig" });
2127
+ if (!definition.needsRestartForActivation) {
2128
+ this.config.applyPersisted(key, internal);
2129
+ }
2130
+ return true;
2131
+ }
2080
2132
  close() {
2081
2133
  if (this.timer) {
2082
2134
  clearInterval(this.timer);
@@ -2120,6 +2172,10 @@ class MongocampDatabase {
2120
2172
  internalCollectionName(name) {
2121
2173
  return `${this.config.string(ConfigKeys.AuthPrefix)}${name}`;
2122
2174
  }
2175
+ /** `USERS_READ_HIDE_API_KEY` (2.6.0): the document routes leave out `apiKey` of the users collection too. */
2176
+ get hidesUserApiKeys() {
2177
+ return this.config.boolean(ConfigKeys.UsersReadHideApiKey);
2178
+ }
2123
2179
  async close() {
2124
2180
  if (this.ownsClient) {
2125
2181
  await this.client.close();
@@ -3027,6 +3083,7 @@ function resolveIndexes(declarations, behaviours) {
3027
3083
  }
3028
3084
  if (indexOptions.unique === true && behaviours.softDelete !== void 0 && indexOptions.partialFilterExpression === void 0) {
3029
3085
  indexOptions.partialFilterExpression = { [behaviours.softDelete.field]: null };
3086
+ return { ...resolved(key, indexOptions, options.name, "declaration"), softDeleteFilter: true };
3030
3087
  }
3031
3088
  return resolved(key, indexOptions, options.name, "declaration");
3032
3089
  });
@@ -3201,7 +3258,16 @@ function resolveRefs(refs, behaviours, jsonSchema) {
3201
3258
  if (throughArray) {
3202
3259
  throw new Error(`refs: ${field} goes through an array, only the last part of a reference may be an array`);
3203
3260
  }
3204
- return { field, collection, ...node !== void 0 ? { many: isArrayNode(node) } : {} };
3261
+ const declaredMany = typeof declaration === "object" && declaration !== null ? declaration.many : void 0;
3262
+ if (declaredMany !== void 0 && typeof declaredMany !== "boolean") {
3263
+ throw new Error(`refs: many of ${field} must be a boolean`);
3264
+ }
3265
+ const schemaMany = node !== void 0 ? isArrayNode(node) : void 0;
3266
+ if (declaredMany !== void 0 && schemaMany !== void 0 && declaredMany !== schemaMany) {
3267
+ throw new Error(`refs: ${field} is declared with many: ${declaredMany}, but the schema says ${schemaMany ? "an array" : "no array"}`);
3268
+ }
3269
+ const many = schemaMany ?? declaredMany;
3270
+ return { field, collection, ...many !== void 0 ? { many } : {} };
3205
3271
  });
3206
3272
  }
3207
3273
 
@@ -3900,7 +3966,7 @@ function dateValue(date, mode) {
3900
3966
  }
3901
3967
  return { $date: { $numberLong: String(millis) } };
3902
3968
  }
3903
- function extendedValue(value, mode) {
3969
+ function extendedValue$1(value, mode) {
3904
3970
  if (value === null) {
3905
3971
  return null;
3906
3972
  }
@@ -3921,7 +3987,7 @@ function extendedValue(value, mode) {
3921
3987
  return longValue(value, mode);
3922
3988
  }
3923
3989
  if (Array.isArray(value)) {
3924
- return value.map((entry) => extendedValue(entry, mode));
3990
+ return value.map((entry) => extendedValue$1(entry, mode));
3925
3991
  }
3926
3992
  if (value instanceof Date) {
3927
3993
  return dateValue(value, mode);
@@ -3976,7 +4042,7 @@ function extendedValue(value, mode) {
3976
4042
  return null;
3977
4043
  }
3978
4044
  function extendedDocument(document, mode) {
3979
- return Object.fromEntries(Object.entries(document).map(([key, value]) => [key, extendedValue(value, mode)]));
4045
+ return Object.fromEntries(Object.entries(document).map(([key, value]) => [key, extendedValue$1(value, mode)]));
3980
4046
  }
3981
4047
  function documentToJson(document, mode = DefaultExtendedJsonMode) {
3982
4048
  return mode === "plain" ? legacyDocument(document) : extendedDocument(document, mode);
@@ -4004,11 +4070,15 @@ function idToString(id) {
4004
4070
  }
4005
4071
 
4006
4072
  const SecretUserFields = ["password"];
4073
+ const SecretUserFieldsWithApiKey = ["password", "apiKey"];
4007
4074
  function secretFieldsOf(database, collection) {
4008
4075
  const name = parseCollectionName(collection);
4009
4076
  const defaultDatabase = database.db().databaseName;
4010
4077
  const inDefault = name.database === void 0 || name.database === defaultDatabase;
4011
- return inDefault && name.name === database.internalCollectionName("users") ? SecretUserFields : [];
4078
+ if (!inDefault || name.name !== database.internalCollectionName("users")) {
4079
+ return [];
4080
+ }
4081
+ return database.hidesUserApiKeys ? SecretUserFieldsWithApiKey : SecretUserFields;
4012
4082
  }
4013
4083
  function withoutSecrets(document, fields) {
4014
4084
  if (fields.length === 0 || !fields.some((field) => field in document)) {
@@ -4101,7 +4171,8 @@ function registerVersioned(context, own) {
4101
4171
  const conflictCheck = (collection, filter) => async () => {
4102
4172
  const stored = await collectionOf(context.database, collection).findOne(filter);
4103
4173
  if (stored !== null) {
4104
- throw MongocampError.versionConflict(withoutSecrets(documentToJson(stored), secretFieldsOf(context.database, collection)));
4174
+ const secrets = secretFieldsOf(context.database, collection);
4175
+ throw MongocampError.versionConflict(withoutSecrets(documentToJson(stored), secrets), withoutSecrets(stored, secrets));
4105
4176
  }
4106
4177
  };
4107
4178
  const removers = [
@@ -4391,6 +4462,22 @@ class CollectionRegistry {
4391
4462
  const name = parseCollectionName(collection);
4392
4463
  return this.find(databaseOf(context.database, name).databaseName, name.name);
4393
4464
  }
4465
+ /** 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. */
4466
+ refFields(context, collection) {
4467
+ return this.resolve(context, collection)?.refs.map((ref) => ref.field) ?? [];
4468
+ }
4469
+ /**
4470
+ * The references of the declared collections to a declaration (2.6.0, `referencedBy` of its answer), from the registry (no database
4471
+ * read). `collection` is the name as the routes take it (`database:name` when the declaration names its database).
4472
+ */
4473
+ referencesTo(context, target) {
4474
+ return this.all().flatMap((entry) => entry.refs.filter((ref) => this.resolve(context, ref.collection) === target).map((ref) => ({
4475
+ collection: entry.definition.database !== void 0 ? `${entry.definition.database}${CollectionSeparator}${entry.definition.name}` : entry.definition.name,
4476
+ database: entry.databaseName,
4477
+ field: ref.field,
4478
+ many: ref.many ?? false
4479
+ })));
4480
+ }
4394
4481
  get size() {
4395
4482
  return this.entries.size;
4396
4483
  }
@@ -4724,7 +4811,7 @@ async function readLines(collection, body, maxBytes, state, beforeBatch) {
4724
4811
  }
4725
4812
  bytes += value.byteLength;
4726
4813
  if (bytes > maxBytes) {
4727
- throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
4814
+ throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413, ErrorCodes.importTooLarge);
4728
4815
  }
4729
4816
  pending += decoder.decode(value, { stream: true });
4730
4817
  let newline = pending.indexOf("\n");
@@ -5137,8 +5224,7 @@ class DocumentService {
5137
5224
  /** The filter with the read scope of the caller. */
5138
5225
  /** 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. */
5139
5226
  limited(paging) {
5140
- const max = this.context.config.number(ConfigKeys.PagingMaxRows);
5141
- return max > 0 && (paging.rowsPerPage ?? 0) > max ? { ...paging, rowsPerPage: max } : paging;
5227
+ return limitPaging(paging, this.context.config.number(ConfigKeys.PagingMaxRows));
5142
5228
  }
5143
5229
  /** Refuses filters, projections and updates of the caller with an operator of `FILTER_OPERATORS_DENIED` (2.5.0). */
5144
5230
  checkOperators(...values) {
@@ -5806,8 +5892,9 @@ function parseDate(text, timeZone = "UTC") {
5806
5892
  return (FullIsoDate.test(text) ? parseJodaIso(text, timeZone) : void 0) ?? parseSimplePatterns(text, timeZone);
5807
5893
  }
5808
5894
 
5895
+ const ObjectIdHex = /^[0-9a-f]{24}$/i;
5809
5896
  function luceneQueryToFilter(query, options = {}) {
5810
- const settings = { both: options.searchWithValueAndString ?? false, caseInsensitive: options.caseInsensitive ?? false, timeZone: options.timeZone ?? "UTC" };
5897
+ const settings = { both: options.searchWithValueAndString ?? false, caseInsensitive: options.caseInsensitive ?? false, timeZone: options.timeZone ?? "UTC", idFields: new Set(options.idFields ?? []) };
5811
5898
  return searchMap(query, false, settings);
5812
5899
  }
5813
5900
  function searchMap(query, negated, settings) {
@@ -5913,6 +6000,10 @@ function appendTerm(negated, result, field, termText, settings, quoted = false)
5913
6000
  }
5914
6001
  const both = settings.both || quoted;
5915
6002
  const text = termText.includes("*") ? unescape(termText) : termText;
6003
+ if (settings.idFields.has(field) && ObjectIdHex.test(text)) {
6004
+ result[field] = { [negated ? "$nin" : "$in"]: [new ObjectId(text), text] };
6005
+ return;
6006
+ }
5916
6007
  const value = convertTermValue(text, settings.timeZone);
5917
6008
  const operator = negated ? "$ne" : "$eq";
5918
6009
  if (!both || value === text) {
@@ -6584,7 +6675,7 @@ function createServerCollection(context, name, options) {
6584
6675
  if (filter === void 0) {
6585
6676
  return {};
6586
6677
  }
6587
- return typeof filter === "string" ? filterParameter(filter, { timeZone: context.config.string(ConfigKeys.FilterTimeZone) }) : filter;
6678
+ return typeof filter === "string" ? filterParameter(filter, { timeZone: context.config.string(ConfigKeys.FilterTimeZone), idFields: context.collections.refFields(context, name) }) : filter;
6588
6679
  };
6589
6680
  const plain = (document) => plainNumbers(document);
6590
6681
  const decodedConflict = async (write) => {
@@ -6785,7 +6876,7 @@ const operations = [
6785
6876
  ["GET", "/auth/authenticated", "isAuthenticated", "Auth", "Check Authentication"],
6786
6877
  ["GET", "/admin/users", "listUsers", "Admin", "List Users"],
6787
6878
  ["PUT", "/admin/users", "addUser", "Admin", "Add User"],
6788
- ["PATCH", "/admin/users/:userId/apikey", "gnerateNewApiKeyForUser", "Admin", "Update ApiKey"],
6879
+ ["PATCH", "/admin/users/:userId/apikey", "generateNewApiKeyForUser", "Admin", "Update ApiKey"],
6789
6880
  ["PATCH", "/admin/users/:userId/password", "updatePasswordForUser", "Admin", "Update Password"],
6790
6881
  ["PATCH", "/admin/users/:userId/roles", "updateRolesForUser", "Admin", "Update User Roles"],
6791
6882
  ["GET", "/admin/users/:userId", "getUser", "Admin", "UserProfile for userId"],
@@ -6795,6 +6886,7 @@ const operations = [
6795
6886
  ["GET", "/admin/roles/:roleName", "getRole", "Admin", "Get Role"],
6796
6887
  ["DELETE", "/admin/roles/:roleName", "deleteRole", "Admin", "Delete Role"],
6797
6888
  ["PATCH", "/admin/roles/:roleName", "updateRole", "Admin", "Update Role"],
6889
+ ["POST", "/mongodb/buckets/:bucketName/files/search", "searchFiles", "File", "Search Files in Bucket"],
6798
6890
  ["GET", "/mongodb/buckets/:bucketName/files", "listFiles", "File", "Files in Bucket"],
6799
6891
  ["PUT", "/mongodb/buckets/:bucketName/files", "insertFile", "File", "Insert File"],
6800
6892
  ["POST", "/mongodb/buckets/:bucketName/files", "findFiles", "File", "Files in Bucket"],
@@ -6827,6 +6919,7 @@ const operations = [
6827
6919
  ["GET", "/system/configurations", "listConfigurations", "Application", "List Configurations"],
6828
6920
  ["GET", "/system/configurations/:configurationKey", "getConfig", "Application", "Configuration for configurationKey"],
6829
6921
  ["PATCH", "/system/configurations/:configurationKey", "updateConfiguration", "Application", "Update Configuration"],
6922
+ ["DELETE", "/system/configurations/:configurationKey", "resetConfiguration", "Application", "Reset Configuration"],
6830
6923
  ["DELETE", "/system", "shutdown", "Application", "Shutdown MongoCamp"],
6831
6924
  ["GET", "/mongodb/databases", "ListDatabases", "Database", "List of Databases"],
6832
6925
  ["GET", "/mongodb/databases/infos", "databaseInfos", "Database", "List of Database Infos"],
@@ -6996,7 +7089,7 @@ function optionalInteger$1(body, field) {
6996
7089
  function isStringList(value) {
6997
7090
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
6998
7091
  }
6999
- function stringList(value, field) {
7092
+ function stringList$1(value, field) {
7000
7093
  if (!isStringList(value)) {
7001
7094
  fail(field);
7002
7095
  }
@@ -7026,7 +7119,7 @@ function readUserInformation(body) {
7026
7119
  userId: requiredString(object, "userId"),
7027
7120
  password: requiredString(object, "password"),
7028
7121
  apiKey: optionalString(object, "apiKey") ?? null,
7029
- roles: object.roles === void 0 || object.roles === null ? [] : stringList(object.roles, "roles")
7122
+ roles: object.roles === void 0 || object.roles === null ? [] : stringList$1(object.roles, "roles")
7030
7123
  };
7031
7124
  }
7032
7125
  function readGrant(value, index) {
@@ -7055,7 +7148,7 @@ function readUpdateRole(body) {
7055
7148
  };
7056
7149
  }
7057
7150
  function readRoleNames(body) {
7058
- return stringList(body, "body");
7151
+ return stringList$1(body, "body");
7059
7152
  }
7060
7153
 
7061
7154
  function pathParam(event, name) {
@@ -7090,15 +7183,15 @@ function booleanQuery(params, name, defaultValue) {
7090
7183
  }
7091
7184
  return normalized === "true";
7092
7185
  }
7093
- function filterOptions(params, config) {
7186
+ function filterOptions(params, config, idFields = []) {
7094
7187
  const timeZone = config.string(ConfigKeys.FilterTimeZone);
7095
7188
  if (!isTimeZone(timeZone)) {
7096
7189
  throw new MongocampError(`${ConfigKeys.FilterTimeZone} is no time zone: ${timeZone}`, 500);
7097
7190
  }
7098
- return { caseInsensitive: booleanQuery(params, "filterCaseInsensitive", false), timeZone };
7191
+ return { caseInsensitive: booleanQuery(params, "filterCaseInsensitive", false), timeZone, idFields };
7099
7192
  }
7100
7193
  function tooLarge() {
7101
- return new MongocampError("the body of the request is greater than BODY_MAX_BYTES", 413);
7194
+ return new MongocampError("the body of the request is greater than BODY_MAX_BYTES", 413, ErrorCodes.bodyTooLarge);
7102
7195
  }
7103
7196
  async function readText(event) {
7104
7197
  const max = event.context.mongocampBodyMaxBytes ?? 0;
@@ -7278,7 +7371,7 @@ function registerAggregationRoutes(app, context) {
7278
7371
  if (queryFilter !== null && queryFilter.trim() !== "" && request.filter !== void 0 && request.filter.trim() !== "") {
7279
7372
  throw MongocampError.badRequest("send the filter in the query or in the body, not in both", ErrorCodes.ambiguousFilter);
7280
7373
  }
7281
- const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config)) : filterParameter(queryFilter, filterOptions(params, config));
7374
+ const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config, context.collections.refFields(context, collection))) : filterParameter(queryFilter, filterOptions(params, config, context.collections.refFields(context, collection)));
7282
7375
  checkPipeline(user, collection, request.pipeline, config.list(ConfigKeys.AggregationStagesDenied));
7283
7376
  const prefix = [];
7284
7377
  if (Object.keys(matchFilter).length > 0) {
@@ -7376,6 +7469,20 @@ function registerAuthRoutes(app, context) {
7376
7469
  });
7377
7470
  }
7378
7471
 
7472
+ function contentDisposition(disposition, filename) {
7473
+ if (/^[\x20-\x7E]*$/.test(filename)) {
7474
+ return `${disposition}; filename=${quoted(filename)}`;
7475
+ }
7476
+ const fallback = filename.normalize("NFKD").replace(/\p{M}/gu, "").replace(/[^\x20-\x7E]/g, "_");
7477
+ return `${disposition}; filename=${quoted(fallback)}; filename*=UTF-8''${extendedValue(filename)}`;
7478
+ }
7479
+ function quoted(text) {
7480
+ return `"${text.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
7481
+ }
7482
+ function extendedValue(text) {
7483
+ return encodeURIComponent(text).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
7484
+ }
7485
+
7379
7486
  function bucketOf(database, bucket) {
7380
7487
  const name = parseCollectionName(bucket);
7381
7488
  return { db: databaseOf(database, name), name: name.name };
@@ -7490,7 +7597,7 @@ async function uploadFile(bucket, request, fileNameOverride, maxBytes = 0) {
7490
7597
  await uploaded;
7491
7598
  if (truncated) {
7492
7599
  await deleteFile(bucket, id);
7493
- throw new MongocampError("the file is greater than GRIDFS_UPLOAD_MAX_BYTES", 413);
7600
+ throw new MongocampError("the file is greater than GRIDFS_UPLOAD_MAX_BYTES", 413, ErrorCodes.uploadTooLarge);
7494
7601
  }
7495
7602
  if (!metadataWithUpload && metadataText !== void 0) {
7496
7603
  await filesCollection(bucket).updateOne({ _id: id }, { $set: { metadata: uploadMetadata(metadataText) } });
@@ -7506,7 +7613,7 @@ function downloadResponse(bucket, document, cacheAge) {
7506
7613
  headers: {
7507
7614
  "content-type": contentType,
7508
7615
  "content-length": String(info.length),
7509
- "content-disposition": `${disposition}; filename="${info.filename.replaceAll('"', '\\"')}"`,
7616
+ "content-disposition": contentDisposition(disposition, info.filename),
7510
7617
  "cache-control": `max-age=${cacheAge}`
7511
7618
  }
7512
7619
  });
@@ -7540,6 +7647,16 @@ function mapField$1(body, field) {
7540
7647
  }
7541
7648
  return decodeAny(value);
7542
7649
  }
7650
+ function stringList(body, field) {
7651
+ const value = body[field];
7652
+ if (value === void 0 || value === null) {
7653
+ return [];
7654
+ }
7655
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
7656
+ throw MongocampError.decodeFailure("body", `field ${field}`);
7657
+ }
7658
+ return value;
7659
+ }
7543
7660
  function registerBucketRoutes(app, context) {
7544
7661
  const { auth, database, config, events } = context;
7545
7662
  const base = "/mongodb/buckets/:bucketName";
@@ -7587,7 +7704,7 @@ function registerBucketRoutes(app, context) {
7587
7704
  const filesResponse = (page) => jsonResponse(page.items, { headers: paginationHeaders(page.info) });
7588
7705
  const files = (bucket, request, params) => {
7589
7706
  checkDeniedFilterOperators([request.filter, request.projection], config.list(ConfigKeys.FilterOperatorsDenied));
7590
- return findFiles(bucket, request, readPaging(params), readCountMode(params));
7707
+ return findFiles(bucket, request, limitPaging(readPaging(params), config.number(ConfigKeys.PagingMaxRows)), readCountMode(params));
7591
7708
  };
7592
7709
  app.get(`${base}/files`, async (event) => {
7593
7710
  const { bucket } = await authorized(event, "read");
@@ -7602,6 +7719,17 @@ function registerBucketRoutes(app, context) {
7602
7719
  const params = queryParams(event);
7603
7720
  return filesResponse(await files(bucket, request, params));
7604
7721
  });
7722
+ app.post(`${base}/files/search`, async (event) => {
7723
+ const { bucket } = await authorized(event, "read");
7724
+ const params = queryParams(event);
7725
+ const body = asObject(await readJson(event));
7726
+ const request = {
7727
+ filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
7728
+ sort: sortFromList(stringList(body, "sort")),
7729
+ projection: projectionFromList(stringList(body, "projection"))
7730
+ };
7731
+ return filesResponse(await files(bucket, request, params));
7732
+ });
7605
7733
  app.put(`${base}/files`, async (event) => {
7606
7734
  const { bucket, name, user } = await authorized(event, "write");
7607
7735
  const id = await uploadFile(bucket, event.req, queryParams(event).get("fileName") ?? void 0, context.config.number(ConfigKeys.GridfsUploadMaxBytes));
@@ -8585,7 +8713,7 @@ function registerCollectionRoutes(app, context) {
8585
8713
  if (!await existsIn(source)) {
8586
8714
  throw new MongocampError(`the collection ${fullName(source)} does not exist`, 404, ErrorCodes.invalidCollectionName);
8587
8715
  }
8588
- const filter = bodyFilter(request.filter, filterOptions(queryParams(event), config));
8716
+ const filter = bodyFilter(request.filter, filterOptions(queryParams(event), config, context.collections.refFields(context, collection)));
8589
8717
  const targetExists = await checkTarget(user, target, request.dropTarget);
8590
8718
  const result = await copyCollection(database, source, target, filter, request.withIndexes, targetExists, systemPrefix());
8591
8719
  context.events.publish("collection:copy", { user: user.user, collectionName: fullName(source), newCollectionName: fullName(target) });
@@ -9265,7 +9393,7 @@ paths:
9265
9393
  - Admin
9266
9394
  summary: Update ApiKey
9267
9395
  description: Generate a new API key for the user
9268
- operationId: gnerateNewApiKeyForUser
9396
+ operationId: generateNewApiKeyForUser
9269
9397
  parameters:
9270
9398
  - name: userId
9271
9399
  in: path
@@ -9862,6 +9990,152 @@ paths:
9862
9990
  - httpAuth: []
9863
9991
  - httpAuth1: []
9864
9992
  - apiKeyAuth: []
9993
+ /mongodb/buckets/{bucketName}/files/search:
9994
+ post:
9995
+ tags:
9996
+ - File
9997
+ summary: Search Files in Bucket
9998
+ description: 'The files of the bucket with a Lucene filter (2.6.0), like the search of documents: filter, sort and projection in the request body (no URL limit), fields of the files collection (filename, length, uploadDate, metadata.*). The operators of FILTER_OPERATORS_DENIED are refused; PAGING_MAX_ROWS applies.'
9999
+ operationId: searchFiles
10000
+ parameters:
10001
+ - name: bucketName
10002
+ in: path
10003
+ description: The name of your MongoDb Collection
10004
+ required: true
10005
+ schema:
10006
+ type: string
10007
+ - name: rowsPerPage
10008
+ in: query
10009
+ description: Count elements per page
10010
+ required: false
10011
+ schema:
10012
+ type: integer
10013
+ format: int64
10014
+ example: 100
10015
+ - name: page
10016
+ in: query
10017
+ description: Requested page of the ResultSets
10018
+ required: false
10019
+ schema:
10020
+ type: integer
10021
+ format: int64
10022
+ example: 1
10023
+ - name: count
10024
+ in: query
10025
+ description: 'How the result is counted: exact (default) or none (no count headers, no count query)'
10026
+ required: false
10027
+ schema:
10028
+ type: string
10029
+ enum:
10030
+ - exact
10031
+ - none
10032
+ default: exact
10033
+ example: exact
10034
+ - name: after
10035
+ in: query
10036
+ description: 'Cursor paging: the x-pagination-next value of the previous page, empty for the first page. The sort always ends
10037
+ with _id; cannot be combined with page'
10038
+ required: false
10039
+ schema:
10040
+ type: string
10041
+ example: ''
10042
+ - name: filterCaseInsensitive
10043
+ in: query
10044
+ description: 'true: wildcards and prefixes of the Lucene filter ignore the case.'
10045
+ required: false
10046
+ schema:
10047
+ type: boolean
10048
+ default: false
10049
+ requestBody:
10050
+ content:
10051
+ application/json:
10052
+ schema:
10053
+ $ref: '#/components/schemas/SearchRequest'
10054
+ example:
10055
+ filter: filename:report* AND metadata.year:2024
10056
+ sort:
10057
+ - -uploadDate
10058
+ required: true
10059
+ responses:
10060
+ '200':
10061
+ description: ''
10062
+ headers:
10063
+ x-pagination-count-rows:
10064
+ description: count all elements
10065
+ required: false
10066
+ schema:
10067
+ type: integer
10068
+ format: int64
10069
+ example: 200
10070
+ x-pagination-rows-per-page:
10071
+ description: Count elements per page
10072
+ required: true
10073
+ schema:
10074
+ type: integer
10075
+ format: int64
10076
+ example: 20
10077
+ x-pagination-current-page:
10078
+ description: Current page
10079
+ required: true
10080
+ schema:
10081
+ type: integer
10082
+ format: int64
10083
+ example: 1
10084
+ x-pagination-count-pages:
10085
+ description: Count pages
10086
+ required: false
10087
+ schema:
10088
+ type: integer
10089
+ format: int64
10090
+ example: 10
10091
+ x-pagination-next:
10092
+ description: 'Cursor of the next page (only with the parameter after, missing on the last page)'
10093
+ required: false
10094
+ schema:
10095
+ type: string
10096
+ content:
10097
+ application/json:
10098
+ schema:
10099
+ type: array
10100
+ items:
10101
+ $ref: '#/components/schemas/FileInformation'
10102
+ '400':
10103
+ description: 'Invalid value for: query parameter rowsPerPage, Invalid value
10104
+ for: query parameter page'
10105
+ content:
10106
+ text/plain:
10107
+ schema:
10108
+ type: string
10109
+ default:
10110
+ description: ''
10111
+ headers:
10112
+ x-error-code:
10113
+ description: Error Code
10114
+ required: true
10115
+ schema:
10116
+ type: integer
10117
+ format: int32
10118
+ example: 100
10119
+ x-error-message:
10120
+ description: Message of the MongoCampException
10121
+ required: true
10122
+ schema:
10123
+ type: string
10124
+ example: Error Message
10125
+ x-error-additional-info:
10126
+ description: Additional information for the MongoCampException
10127
+ required: true
10128
+ schema:
10129
+ type: string
10130
+ example: Additional Error Info
10131
+ content:
10132
+ application/json:
10133
+ schema:
10134
+ $ref: '#/components/schemas/ErrorDescription'
10135
+ security:
10136
+ - httpAuth: []
10137
+ - httpAuth1: []
10138
+ - apiKeyAuth: []
9865
10139
  /mongodb/buckets/{bucketName}/files:
9866
10140
  get:
9867
10141
  tags:
@@ -12201,6 +12475,62 @@ paths:
12201
12475
  - httpAuth: []
12202
12476
  - httpAuth1: []
12203
12477
  - apiKeyAuth: []
12478
+ delete:
12479
+ tags:
12480
+ - Application
12481
+ summary: Reset Configuration
12482
+ description: 'Reset the Configuration to its default value (2.6.0), at once for a key that needs no restart. 404 for an unknown key, 400 for a key that is read at the start only, set by the environment or has a generated default (AUTH_SECRET).'
12483
+ operationId: resetConfiguration
12484
+ parameters:
12485
+ - name: configurationKey
12486
+ in: path
12487
+ description: configurationKey to reset
12488
+ required: true
12489
+ schema:
12490
+ type: string
12491
+ responses:
12492
+ '200':
12493
+ description: ''
12494
+ content:
12495
+ application/json:
12496
+ schema:
12497
+ $ref: '#/components/schemas/JsonValue_Boolean'
12498
+ '400':
12499
+ description: 'Invalid value for: path parameter configurationKey'
12500
+ content:
12501
+ text/plain:
12502
+ schema:
12503
+ type: string
12504
+ default:
12505
+ description: ''
12506
+ headers:
12507
+ x-error-code:
12508
+ description: Error Code
12509
+ required: true
12510
+ schema:
12511
+ type: integer
12512
+ format: int32
12513
+ example: 100
12514
+ x-error-message:
12515
+ description: Message of the MongoCampException
12516
+ required: true
12517
+ schema:
12518
+ type: string
12519
+ example: Error Message
12520
+ x-error-additional-info:
12521
+ description: Additional information for the MongoCampException
12522
+ required: true
12523
+ schema:
12524
+ type: string
12525
+ example: Additional Error Info
12526
+ content:
12527
+ application/json:
12528
+ schema:
12529
+ $ref: '#/components/schemas/ErrorDescription'
12530
+ security:
12531
+ - httpAuth: []
12532
+ - httpAuth1: []
12533
+ - apiKeyAuth: []
12204
12534
  /system:
12205
12535
  delete:
12206
12536
  tags:
@@ -15779,11 +16109,31 @@ components:
15779
16109
  type: object
15780
16110
  required:
15781
16111
  - importMaxBytes
16112
+ - bodyMaxBytes
16113
+ - pagingMaxRows
16114
+ - exportMaxDocuments
16115
+ - gridfsUploadMaxBytes
15782
16116
  - grantDeniedStatus
15783
16117
  properties:
15784
16118
  importMaxBytes:
15785
16119
  type: integer
15786
16120
  format: int64
16121
+ bodyMaxBytes:
16122
+ description: BODY_MAX_BYTES (2.6.0); 0 is no limit.
16123
+ type: integer
16124
+ format: int64
16125
+ pagingMaxRows:
16126
+ description: PAGING_MAX_ROWS (2.6.0); 0 is no limit.
16127
+ type: integer
16128
+ format: int64
16129
+ exportMaxDocuments:
16130
+ description: EXPORT_MAX_DOCUMENTS (2.6.0); 0 is no limit.
16131
+ type: integer
16132
+ format: int64
16133
+ gridfsUploadMaxBytes:
16134
+ description: GRIDFS_UPLOAD_MAX_BYTES (2.6.0); 0 is no limit.
16135
+ type: integer
16136
+ format: int64
15787
16137
  grantDeniedStatus:
15788
16138
  type: integer
15789
16139
  format: int32
@@ -16813,6 +17163,7 @@ components:
16813
17163
  - protectedFields
16814
17164
  - indexes
16815
17165
  - refs
17166
+ - referencedBy
16816
17167
  properties:
16817
17168
  name:
16818
17169
  type: string
@@ -16842,6 +17193,8 @@ components:
16842
17193
  - name
16843
17194
  - key
16844
17195
  - unique
17196
+ - sparse
17197
+ - origin
16845
17198
  properties:
16846
17199
  name:
16847
17200
  type: string
@@ -16850,6 +17203,28 @@ components:
16850
17203
  additionalProperties: true
16851
17204
  unique:
16852
17205
  type: boolean
17206
+ sparse:
17207
+ description: 2.6.0
17208
+ type: boolean
17209
+ origin:
17210
+ description: 'Declared, or added for a behaviour (owner = the index on the owner field), 2.6.0.'
17211
+ type: string
17212
+ enum:
17213
+ - declaration
17214
+ - owner
17215
+ partialFilterExpression:
17216
+ description: The partial filter as relaxed Extended JSON (2.6.0), as index details show it.
17217
+ type: object
17218
+ additionalProperties: true
17219
+ partialFilterFrom:
17220
+ description: softDelete when the soft delete behaviour added the partial filter to a unique index (2.6.0).
17221
+ type: string
17222
+ enum:
17223
+ - softDelete
17224
+ expireAfterSeconds:
17225
+ description: 2.6.0
17226
+ type: integer
17227
+ format: int64
16853
17228
  refs:
16854
17229
  description: The references of the declaration (2.4.0), the fields a read can expand (query parameter expand).
16855
17230
  type: array
@@ -16858,6 +17233,7 @@ components:
16858
17233
  required:
16859
17234
  - field
16860
17235
  - collection
17236
+ - many
16861
17237
  properties:
16862
17238
  field:
16863
17239
  type: string
@@ -16865,7 +17241,28 @@ components:
16865
17241
  description: The target collection (name or database:name).
16866
17242
  type: string
16867
17243
  many:
16868
- description: Whether the field holds an array of ids (from the schema); missing when the schema does not tell.
17244
+ 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).
17245
+ type: boolean
17246
+ referencedBy:
17247
+ description: The references of the declared collections to this collection (2.6.0), from the declarations of the server; empty when none.
17248
+ type: array
17249
+ items:
17250
+ type: object
17251
+ required:
17252
+ - collection
17253
+ - database
17254
+ - field
17255
+ - many
17256
+ properties:
17257
+ collection:
17258
+ description: The referencing collection as the routes name it (name or database:name).
17259
+ type: string
17260
+ database:
17261
+ type: string
17262
+ field:
17263
+ description: The field of the referencing collection that holds the id.
17264
+ type: string
17265
+ many:
16869
17266
  type: boolean
16870
17267
  timestamps:
16871
17268
  type: object
@@ -17238,7 +17635,7 @@ function registerDocsRoutes(app, context) {
17238
17635
  }
17239
17636
  }
17240
17637
 
17241
- function declarationInfo(declared) {
17638
+ function declarationInfo(declared, referencedBy = []) {
17242
17639
  const { behaviours } = declared;
17243
17640
  return {
17244
17641
  name: declared.definition.name,
@@ -17246,8 +17643,20 @@ function declarationInfo(declared) {
17246
17643
  validation: declared.validation,
17247
17644
  systemFields: systemFields(behaviours).map((entry) => entry.path),
17248
17645
  protectedFields: [...behaviours.protectedFields],
17249
- indexes: declared.indexes.map((index) => ({ name: index.name, key: { ...index.key }, unique: index.options.unique === true })),
17250
- refs: declared.refs.map((ref) => ({ ...ref })),
17646
+ // 2.6.0: the options as index details show them, and where the index comes from
17647
+ indexes: declared.indexes.map((index) => ({
17648
+ name: index.name,
17649
+ key: { ...index.key },
17650
+ unique: index.options.unique === true,
17651
+ sparse: index.options.sparse === true,
17652
+ origin: index.origin,
17653
+ ...index.options.partialFilterExpression !== void 0 ? { partialFilterExpression: documentToJson(index.options.partialFilterExpression, "relaxed") } : {},
17654
+ ...index.softDeleteFilter === true ? { partialFilterFrom: "softDelete" } : {},
17655
+ ...typeof index.options.expireAfterSeconds === "number" ? { expireAfterSeconds: index.options.expireAfterSeconds } : {}
17656
+ })),
17657
+ // 2.6.0: many is always given (false when neither the schema nor the declaration says an array), and the references to this collection
17658
+ refs: declared.refs.map((ref) => ({ ...ref, many: ref.many ?? false })),
17659
+ referencedBy: referencedBy.map((reference) => ({ ...reference })),
17251
17660
  ...behaviours.timestamps !== void 0 ? { timestamps: { ...behaviours.timestamps } } : {},
17252
17661
  ...behaviours.owner !== void 0 ? { owner: { field: behaviours.owner.field, read: typeof behaviours.owner.read === "function" ? "custom" : behaviours.owner.read } } : {},
17253
17662
  ...behaviours.softDelete !== void 0 ? { softDelete: { ...behaviours.softDelete } } : {},
@@ -17347,12 +17756,12 @@ async function* converted(cursor, mode, secrets = [], expand) {
17347
17756
  yield* flush();
17348
17757
  }
17349
17758
  }
17350
- function endMarker(format, count) {
17759
+ function endMarker(format, count, capped = false) {
17351
17760
  if (format === "ndjson") {
17352
- return `${stringifyJson({ $end: true, count })}
17761
+ return `${stringifyJson(capped ? { $end: true, count, capped: true } : { $end: true, count })}
17353
17762
  `;
17354
17763
  }
17355
- return format === "csv" ? `# end ${count}\r
17764
+ return format === "csv" ? `# end ${count}${capped ? " capped" : ""}\r
17356
17765
  ` : "";
17357
17766
  }
17358
17767
  function errorMarker(format, error) {
@@ -17364,11 +17773,23 @@ function errorMarker(format, error) {
17364
17773
  return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
17365
17774
  ` : "";
17366
17775
  }
17776
+ async function* upTo(cursor, cap, onCapped) {
17777
+ let count = 0;
17778
+ for await (const document of cursor) {
17779
+ if (cap !== void 0 && count >= cap) {
17780
+ onCapped();
17781
+ return;
17782
+ }
17783
+ count++;
17784
+ yield document;
17785
+ }
17786
+ }
17367
17787
  function exportStream(cursor, format, columns, options = {}) {
17368
17788
  const encoder = new TextEncoder();
17369
17789
  let count = 0;
17790
+ let capped = false;
17370
17791
  async function* counted() {
17371
- for await (const document of converted(cursor, options.mode, options.secrets, options.expand)) {
17792
+ for await (const document of converted(upTo(cursor, options.cap, () => capped = true), options.mode, options.secrets, options.expand)) {
17372
17793
  count++;
17373
17794
  yield document;
17374
17795
  }
@@ -17380,7 +17801,7 @@ function exportStream(cursor, format, columns, options = {}) {
17380
17801
  const { value, done } = await pieces.next();
17381
17802
  if (done) {
17382
17803
  if (options.trailer) {
17383
- const marker = endMarker(format, count);
17804
+ const marker = endMarker(format, count, capped);
17384
17805
  if (marker) {
17385
17806
  controller.enqueue(encoder.encode(marker));
17386
17807
  }
@@ -17466,12 +17887,13 @@ function registerDocumentRoutes(app, context) {
17466
17887
  const pageOf = (collection, result, mode) => pageResponse({ items: result.documents.map((document) => documentToJson(document, mode)), info: result.info }, secretFieldsOf(database, collection));
17467
17888
  const base = "/mongodb/collections/:collectionName/documents";
17468
17889
  const collectionParam = (event) => pathParam(event, "collectionName");
17890
+ const refFields = (collection) => context.collections.refFields(context, collection);
17469
17891
  app.get(base, async (event) => {
17470
17892
  const collection = collectionParam(event);
17471
17893
  const user = await auth.requireCollection(event.req, collection, "read");
17472
17894
  const params = queryParams(event);
17473
17895
  const request = {
17474
- filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config))),
17896
+ filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection)))),
17475
17897
  sort: sortFromList(params.getAll("sort")),
17476
17898
  projection: projectionFromList(params.getAll("projection"))
17477
17899
  };
@@ -17482,7 +17904,7 @@ function registerDocumentRoutes(app, context) {
17482
17904
  const collection = collectionParam(event);
17483
17905
  const user = await auth.requireCollection(event.req, collection, "read");
17484
17906
  const params = queryParams(event);
17485
- const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config)));
17907
+ const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection))));
17486
17908
  return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
17487
17909
  });
17488
17910
  app.post(`${base}/count`, async (event) => {
@@ -17490,7 +17912,7 @@ function registerDocumentRoutes(app, context) {
17490
17912
  const user = await auth.requireCollection(event.req, collection, "read");
17491
17913
  const params = queryParams(event);
17492
17914
  const body = asObject(await readJson(event));
17493
- const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config)));
17915
+ const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection))));
17494
17916
  return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
17495
17917
  });
17496
17918
  app.post(`${base}/search`, async (event) => {
@@ -17500,7 +17922,7 @@ function registerDocumentRoutes(app, context) {
17500
17922
  const mode = extendedJsonMode(params);
17501
17923
  const body = asObject(await readJson(event));
17502
17924
  const request = {
17503
- filter: convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config))),
17925
+ filter: convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection)))),
17504
17926
  sort: sortFromList(stringListField(body, "sort")),
17505
17927
  projection: projectionFromList(stringListField(body, "projection"))
17506
17928
  };
@@ -17568,11 +17990,13 @@ function registerDocumentRoutes(app, context) {
17568
17990
  }
17569
17991
  const scoped = await service.exportFilter(user, collection, convertFields(request.filter), withDeletedOf(params, user, collection));
17570
17992
  const maxDocuments = config.number(ConfigKeys.ExportMaxDocuments);
17993
+ const cap = maxDocuments > 0 && (request.limit === void 0 || request.limit > maxDocuments) ? maxDocuments : void 0;
17571
17994
  const query = {
17572
17995
  filter: scoped.filter,
17573
17996
  sort: sortFromList(request.sort),
17574
17997
  projection: projectionFromList(request.projection),
17575
- limit: maxDocuments > 0 ? Math.min(request.limit ?? maxDocuments, maxDocuments) : request.limit
17998
+ // 2.6.0: one more than the cap, so the end marker can tell that the cap cut the export
17999
+ limit: cap !== void 0 ? cap + 1 : request.limit
17576
18000
  };
17577
18001
  const target = collectionOf(database, collection);
17578
18002
  const secrets = secretFieldsOf(database, collection);
@@ -17586,10 +18010,12 @@ function registerDocumentRoutes(app, context) {
17586
18010
  }
17587
18011
  const trailer = booleanQuery(params, "trailer", false);
17588
18012
  const expand = refs.length > 0 ? (documents) => service.expand(user, documents, refs) : void 0;
17589
- return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand, escapeFormulas: config.boolean(ConfigKeys.ExportCsvEscapeFormulas) }), {
18013
+ return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand, escapeFormulas: config.boolean(ConfigKeys.ExportCsvEscapeFormulas), cap }), {
17590
18014
  headers: {
17591
18015
  "content-type": "text/plain; charset=UTF-8",
17592
- "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
18016
+ "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`,
18017
+ // 2.6.0: the cap before the body (a json array has no end marker)
18018
+ ...maxDocuments > 0 ? { "x-export-max-documents": String(maxDocuments) } : {}
17593
18019
  }
17594
18020
  });
17595
18021
  };
@@ -17597,7 +18023,7 @@ function registerDocumentRoutes(app, context) {
17597
18023
  const collection = collectionParam(event);
17598
18024
  const user = await auth.requireCollection(event.req, collection, "read");
17599
18025
  const params = queryParams(event);
17600
- const filter = filterParameter(params.get("filter"), filterOptions(params, config));
18026
+ const filter = filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection)));
17601
18027
  return exportResponse(user, collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit"), expand: expandOf(params) });
17602
18028
  });
17603
18029
  app.post(`${base}/export`, async (event) => {
@@ -17606,7 +18032,7 @@ function registerDocumentRoutes(app, context) {
17606
18032
  const params = queryParams(event);
17607
18033
  const body = asObject(await readJson(event));
17608
18034
  return exportResponse(user, collection, params, {
17609
- filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
18035
+ filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection))),
17610
18036
  sort: stringListField(body, "sort"),
17611
18037
  projection: stringListField(body, "projection"),
17612
18038
  limit: optionalInteger$1(body, "limit"),
@@ -17619,7 +18045,7 @@ function registerDocumentRoutes(app, context) {
17619
18045
  const maxBytes = context.config.number(ConfigKeys.ImportMaxBytes);
17620
18046
  const length = Number(event.req.headers.get("content-length") ?? Number.NaN);
17621
18047
  if (Number.isFinite(length) && length > maxBytes) {
17622
- throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
18048
+ throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413, ErrorCodes.importTooLarge);
17623
18049
  }
17624
18050
  const state = await service.import(user, collection, event.req.body, maxBytes);
17625
18051
  return jsonResponse(state.response);
@@ -17643,7 +18069,7 @@ function registerDocumentRoutes(app, context) {
17643
18069
  const body = asObject(await readJson(event));
17644
18070
  const document = mapField(body, "document", true);
17645
18071
  const params = queryParams(event);
17646
- const filter = manyFilter(params, mapField(body, "filter"), filterOptions(params, config));
18072
+ const filter = manyFilter(params, mapField(body, "filter"), filterOptions(params, config, refFields(collection)));
17647
18073
  return jsonResponse(await service.updateMany(user, collection, filter, convertToOperationMap(convertFields(document))));
17648
18074
  });
17649
18075
  app.delete(`${base}/many/delete`, async (event) => {
@@ -17652,7 +18078,7 @@ function registerDocumentRoutes(app, context) {
17652
18078
  const body = await readOptionalJson(event);
17653
18079
  const bodyMap = body === void 0 ? {} : decodeAnyObject(body);
17654
18080
  const params = queryParams(event);
17655
- return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config))));
18081
+ return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config, refFields(collection)))));
17656
18082
  });
17657
18083
  app.post(`${base}/:documentId/restore`, async (event) => {
17658
18084
  const collection = collectionParam(event);
@@ -17666,7 +18092,7 @@ function registerDocumentRoutes(app, context) {
17666
18092
  if (declared === void 0) {
17667
18093
  throw MongocampError.notFound(`the collection ${collection} is not declared`);
17668
18094
  }
17669
- return jsonResponse(declarationInfo(declared));
18095
+ return jsonResponse(declarationInfo(declared, context.collections.referencesTo(context, declared)));
17670
18096
  });
17671
18097
  const auditedOf = (collection) => {
17672
18098
  const declared = context.collections.resolve(context, collection);
@@ -18565,7 +18991,7 @@ function registerWatchRoutes(app, context) {
18565
18991
  }
18566
18992
  const params = queryParams(event);
18567
18993
  const refs = context.documents.refs(collection, params.getAll("expand").flatMap((value) => value.split(",")));
18568
- const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "watch");
18994
+ const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config, context.collections.refFields(context, collection)))), "watch");
18569
18995
  const target = collectionOf(database, collection);
18570
18996
  const secrets = secretFieldsOf(database, collection);
18571
18997
  const lastEventId = event.req.headers.get("last-event-id")?.trim() ?? "";
@@ -18770,6 +19196,11 @@ async function systemStats(admin) {
18770
19196
  function capabilityLimits(config) {
18771
19197
  return {
18772
19198
  importMaxBytes: config.number(ConfigKeys.ImportMaxBytes),
19199
+ // 2.6.0: the limits of 2.5 for every user, 0 is no limit
19200
+ bodyMaxBytes: config.number(ConfigKeys.BodyMaxBytes),
19201
+ pagingMaxRows: config.number(ConfigKeys.PagingMaxRows),
19202
+ exportMaxDocuments: config.number(ConfigKeys.ExportMaxDocuments),
19203
+ gridfsUploadMaxBytes: config.number(ConfigKeys.GridfsUploadMaxBytes),
18773
19204
  grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403
18774
19205
  };
18775
19206
  }
@@ -18838,6 +19269,24 @@ function registerConfigurationRoutes(app, context) {
18838
19269
  const updated = await configurations.update(key, decodeAny(body.value));
18839
19270
  return jsonResponse({ value: updated });
18840
19271
  });
19272
+ app.delete("/system/configurations/:configurationKey", async (event) => {
19273
+ await auth.requireAdmin(event.req);
19274
+ const key = pathParam(event, "configurationKey");
19275
+ const definition = config.definition(key);
19276
+ if (!definition) {
19277
+ throw MongocampError.notFound("configuration not found");
19278
+ }
19279
+ if (!definition.persistent) {
19280
+ throw MongocampError.badRequest(`${key} cannot be changed at runtime, it is read at the start only`);
19281
+ }
19282
+ if (config.overrideOf(key) === "env") {
19283
+ throw MongocampError.badRequest(`${key} is set by the environment and cannot be changed`);
19284
+ }
19285
+ if (typeof definition.defaultValue === "function") {
19286
+ throw MongocampError.badRequest(`${key} has a generated default and cannot be reset`);
19287
+ }
19288
+ return jsonResponse({ value: await configurations.reset(key) });
19289
+ });
18841
19290
  app.delete("/system", async (event) => {
18842
19291
  await auth.requireAdmin(event.req);
18843
19292
  const shutdown = context.shutdown;
@@ -18894,11 +19343,19 @@ const routeGroups = [
18894
19343
  registerIndexRoutes,
18895
19344
  registerBucketRoutes
18896
19345
  ];
19346
+ function errorOptions(config, url) {
19347
+ let mode = DefaultExtendedJsonMode;
19348
+ try {
19349
+ mode = parseExtendedJsonMode(url.searchParams.get("extendedJson")) ?? DefaultExtendedJsonMode;
19350
+ } catch {
19351
+ }
19352
+ return { exposeInternal: config.boolean(ConfigKeys.ErrorsExposeInternal), currentIn: (document) => documentToJson(document, mode) };
19353
+ }
18897
19354
  function createApp(context) {
18898
19355
  const app = new H3({
18899
19356
  // errors are answered and logged (5xx) by toErrorResponse
18900
19357
  silent: true,
18901
- onError: (error) => toErrorResponse(error, errorLogger(context.logger), { exposeInternal: context.config.boolean(ConfigKeys.ErrorsExposeInternal) })
19358
+ onError: (error, event) => toErrorResponse(error, errorLogger(context.logger), errorOptions(context.config, event.url))
18902
19359
  });
18903
19360
  app.use((event) => {
18904
19361
  event.context.mongocampBodyMaxBytes = context.config.number(ConfigKeys.BodyMaxBytes);
@@ -19009,7 +19466,7 @@ async function createMongocampServer(options = {}) {
19009
19466
  try {
19010
19467
  response = await app.fetch(request);
19011
19468
  } catch (error) {
19012
- response = toErrorResponse(error, errorLogger(logger), { exposeInternal: config.boolean(ConfigKeys.ErrorsExposeInternal) });
19469
+ response = toErrorResponse(error, errorLogger(logger), errorOptions(config, new URL(request.url)));
19013
19470
  }
19014
19471
  requestEvents.completed(start, response);
19015
19472
  if (fetchOptions.log) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/mongocamp-server-core",
3
- "version": "2.5.0",
3
+ "version": "2.6.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {