@kikiutils/mongoose 8.0.0 → 9.0.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.
Files changed (65) hide show
  1. package/dist/builders.d.ts +1 -3
  2. package/dist/builders.d.ts.map +1 -1
  3. package/dist/builders.js +6 -6
  4. package/dist/builders.js.map +1 -1
  5. package/dist/plugins/lean-decimal128-to-string.d.ts +26 -0
  6. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -0
  7. package/dist/plugins/lean-decimal128-to-string.js +85 -0
  8. package/dist/plugins/lean-decimal128-to-string.js.map +1 -0
  9. package/dist/plugins/normalize.d.ts +5 -2
  10. package/dist/plugins/normalize.d.ts.map +1 -1
  11. package/dist/plugins/normalize.js +7 -2
  12. package/dist/plugins/normalize.js.map +1 -1
  13. package/dist/schema-builders/bigint.d.ts +13 -1
  14. package/dist/schema-builders/bigint.d.ts.map +1 -1
  15. package/dist/schema-builders/bigint.js +22 -0
  16. package/dist/schema-builders/bigint.js.map +1 -1
  17. package/dist/schema-builders/date.d.ts +2 -2
  18. package/dist/schema-builders/date.d.ts.map +1 -1
  19. package/dist/schema-builders/date.js.map +1 -1
  20. package/dist/schema-builders/decimal128.d.ts +4 -2
  21. package/dist/schema-builders/decimal128.d.ts.map +1 -1
  22. package/dist/schema-builders/decimal128.js +1 -0
  23. package/dist/schema-builders/decimal128.js.map +1 -1
  24. package/dist/schema-builders/double.d.ts +13 -1
  25. package/dist/schema-builders/double.d.ts.map +1 -1
  26. package/dist/schema-builders/double.js +25 -0
  27. package/dist/schema-builders/double.js.map +1 -1
  28. package/dist/schema-builders/int32.d.ts +13 -1
  29. package/dist/schema-builders/int32.d.ts.map +1 -1
  30. package/dist/schema-builders/int32.js +22 -0
  31. package/dist/schema-builders/int32.js.map +1 -1
  32. package/dist/schema-builders/number.d.ts +2 -2
  33. package/dist/schema-builders/number.d.ts.map +1 -1
  34. package/dist/schema-builders/number.js.map +1 -1
  35. package/dist/schema-builders/object-id.d.ts +2 -2
  36. package/dist/schema-builders/object-id.d.ts.map +1 -1
  37. package/dist/schema-builders/object-id.js.map +1 -1
  38. package/dist/schema-builders/ref.d.ts +2 -2
  39. package/dist/schema-builders/ref.d.ts.map +1 -1
  40. package/dist/schema-builders/ref.js.map +1 -1
  41. package/dist/schema-builders/string.d.ts +2 -2
  42. package/dist/schema-builders/string.d.ts.map +1 -1
  43. package/dist/schema-builders/string.js.map +1 -1
  44. package/dist/types/data.d.ts +2 -1
  45. package/dist/types/data.d.ts.map +1 -1
  46. package/dist/types/index.d.ts +7 -3
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/options.d.ts +7 -3
  49. package/dist/types/options.d.ts.map +1 -1
  50. package/package.json +4 -3
  51. package/src/builders.ts +16 -23
  52. package/src/plugins/lean-decimal128-to-string.ts +149 -0
  53. package/src/plugins/normalize.ts +18 -2
  54. package/src/schema-builders/bigint.ts +57 -1
  55. package/src/schema-builders/date.ts +2 -2
  56. package/src/schema-builders/decimal128.ts +5 -2
  57. package/src/schema-builders/double.ts +64 -1
  58. package/src/schema-builders/int32.ts +57 -1
  59. package/src/schema-builders/number.ts +2 -2
  60. package/src/schema-builders/object-id.ts +2 -2
  61. package/src/schema-builders/ref.ts +2 -2
  62. package/src/schema-builders/string.ts +2 -2
  63. package/src/types/data.ts +4 -1
  64. package/src/types/index.ts +16 -2
  65. package/src/types/options.ts +9 -3
@@ -1,11 +1,9 @@
1
- import { MongooseNormalizePluginOptions } from "./plugins/normalize.js";
2
1
  import { BaseMongoosePaginateModel } from "./types/index.js";
3
2
  import { BuildMongooseModelOptions } from "./types/options.js";
4
3
  import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
5
- import { Model, Schema } from "mongoose";
4
+ import { Schema } from "mongoose";
6
5
  //#region src/builders.d.ts
7
6
  export type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;
8
7
  export declare function buildMongooseModel<DocType, Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>, InstanceMethodsAndOverrides = object, QueryHelpers = object>(collection: string, name: string, schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>, options?: BuildMongooseModelOptions): Model;
9
- export declare function registerMongooseNormalizePlugin<DocType, Model$1 extends Model<DocType, QueryHelpers, InstanceMethodsAndOverrides>, InstanceMethodsAndOverrides = object, QueryHelpers = object>(schema: Schema<DocType, Model$1, InstanceMethodsAndOverrides, QueryHelpers>, recursive?: boolean, options?: MongooseNormalizePluginOptions): void;
10
8
  //#endregion
11
9
  //# sourceMappingURL=builders.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.d.ts","names":["MongooseModel","Model"],"sources":["../src/builders.ts"],"mappings":";;;;;;YAeY,kCAAkC;wBAE9B,mBACZ,SACA,cAAc,0BAA0B,SAAS,6BAA6B,eAC9E,sCACA,uBAEA,oBACA,cACA,QAAQ,OAAO,SAAS,OAAO,6BAA6B,eAC5D,UAAU,4BACX;wBAca,gCACZ,SACA,gBAAcA,MAAc,SAAS,cAAc,8BACnD,sCACA,uBAEA,QAAQ,OAAO,SAASC,SAAO,6BAA6B,eAC5D,qBACA,UAAU"}
1
+ {"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":";;;;;YAYY,kCAAkC;wBAE9B,mBACZ,SACA,cAAc,0BAA0B,SAAS,6BAA6B,eAC9E,sCACA,uBAEA,oBACA,cACA,QAAQ,OAAO,SAAS,OAAO,6BAA6B,eAC5D,UAAU,4BACX"}
package/dist/builders.js CHANGED
@@ -1,12 +1,16 @@
1
1
  import { customMongooseOptions } from "./_internals.js";
2
2
  import { getDefaultMongooseConnection } from "./connection.js";
3
3
  import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
4
+ import { mongooseLeanDecimal128ToStringPlugin } from "./plugins/lean-decimal128-to-string.js";
4
5
  import { mongooseNormalizePlugin } from "./plugins/normalize.js";
5
6
  import mongooseAggregatePaginate from "mongoose-aggregate-paginate-v2";
6
7
  import mongoosePaginate from "mongoose-paginate-v2";
7
8
  //#region src/builders.ts
8
9
  function buildMongooseModel(collection, name, schema, options) {
9
- if (options?.enableNormalizePlugin !== false) registerMongooseNormalizePlugin(schema, options?.normalizePluginRecursive, options?.normalizePluginOptions);
10
+ const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
11
+ if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin, typeof leanDecimal128ToStringPluginOptions === "object" ? leanDecimal128ToStringPluginOptions : void 0);
12
+ const normalizePluginOptions = options?.plugins?.normalize;
13
+ if (normalizePluginOptions !== false) schema.plugin(mongooseNormalizePlugin, typeof normalizePluginOptions === "object" ? normalizePluginOptions : void 0);
10
14
  schema.plugin(mongooseAggregatePaginate);
11
15
  schema.plugin(mongooseAssertionsPlugin);
12
16
  schema.plugin(mongoosePaginate);
@@ -14,11 +18,7 @@ function buildMongooseModel(collection, name, schema, options) {
14
18
  customMongooseOptions.beforeModelBuild?.(schema);
15
19
  return (options?.connection ?? getDefaultMongooseConnection()).model(name, schema, collection);
16
20
  }
17
- function registerMongooseNormalizePlugin(schema, recursive = true, options) {
18
- schema.plugin(mongooseNormalizePlugin, options);
19
- if (recursive) schema.childSchemas.forEach(({ schema }) => registerMongooseNormalizePlugin(schema, recursive, options));
20
- }
21
21
  //#endregion
22
- export { buildMongooseModel, registerMongooseNormalizePlugin };
22
+ export { buildMongooseModel };
23
23
 
24
24
  //# sourceMappingURL=builders.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type {\n Model as MongooseModel,\n Schema,\n} from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { MongooseNormalizePluginOptions } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;\n\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n): Model {\n if (options?.enableNormalizePlugin !== false) {\n registerMongooseNormalizePlugin(schema, options?.normalizePluginRecursive, options?.normalizePluginOptions);\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n const connection = options?.connection ?? getDefaultMongooseConnection();\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\nexport function registerMongooseNormalizePlugin<\n DocType,\n Model extends MongooseModel<DocType, QueryHelpers, InstanceMethodsAndOverrides>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n recursive: boolean = true,\n options?: MongooseNormalizePluginOptions,\n) {\n schema.plugin(mongooseNormalizePlugin, options);\n if (recursive) {\n schema.childSchemas.forEach(({ schema }) => registerMongooseNormalizePlugin(schema, recursive, options));\n }\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CACL,IAAI,SAAS,0BAA0B,OACnC,gCAAgC,QAAQ,SAAS,0BAA0B,SAAS,sBAAsB;CAG9G,OAAO,OAAO,yBAAyB;CACvC,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAC9B,OAAO,IAAI,cAAc,SAAS,cAAc,OAAO,IAAI,YAAY,KAAK,IAAI;CAChF,sBAAsB,mBAAmB,MAAM;CAE/C,QADmB,SAAS,cAAc,6BAA6B,EAAA,CACrD,MAAoC,MAAM,QAAQ,UAAU;AAClF;AAEA,SAAgB,gCAMZ,QACA,YAAqB,MACrB,SACF;CACE,OAAO,OAAO,yBAAyB,OAAO;CAC9C,IAAI,WACA,OAAO,aAAa,SAAS,EAAE,aAAa,gCAAgC,QAAQ,WAAW,OAAO,CAAC;AAE/G"}
1
+ {"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type { Schema } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;\n\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n): Model {\n const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;\n if (leanDecimal128ToStringPluginOptions !== false) {\n schema.plugin(\n mongooseLeanDecimal128ToStringPlugin,\n typeof leanDecimal128ToStringPluginOptions === 'object' ? leanDecimal128ToStringPluginOptions : undefined,\n );\n }\n\n const normalizePluginOptions = options?.plugins?.normalize;\n if (normalizePluginOptions !== false) {\n schema.plugin(\n mongooseNormalizePlugin,\n typeof normalizePluginOptions === 'object' ? normalizePluginOptions : undefined,\n );\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n const connection = options?.connection ?? getDefaultMongooseConnection();\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CACL,MAAM,sCAAsC,SAAS,SAAS;CAC9D,IAAI,wCAAwC,OACxC,OAAO,OACH,sCACA,OAAO,wCAAwC,WAAW,sCAAsC,KAAA,CACpG;CAGJ,MAAM,yBAAyB,SAAS,SAAS;CACjD,IAAI,2BAA2B,OAC3B,OAAO,OACH,yBACA,OAAO,2BAA2B,WAAW,yBAAyB,KAAA,CAC1E;CAGJ,OAAO,OAAO,yBAAyB;CACvC,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAC9B,OAAO,IAAI,cAAc,SAAS,cAAc,OAAO,IAAI,YAAY,KAAK,IAAI;CAChF,sBAAsB,mBAAmB,MAAM;CAE/C,QADmB,SAAS,cAAc,6BAA6B,EAAA,CACrD,MAAoC,MAAM,QAAQ,UAAU;AAClF"}
@@ -0,0 +1,26 @@
1
+ import { Schema } from "mongoose";
2
+ //#region src/plugins/lean-decimal128-to-string.d.ts
3
+ declare module 'mongoose' {
4
+ interface LeanOptions {
5
+ /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
6
+ decimal128ToString?: boolean;
7
+ }
8
+ }
9
+ export interface MongooseLeanDecimal128ToStringPluginOptions {
10
+ /** Whether marked fields are converted on lean queries by default. Defaults to true. */
11
+ enabledByDefault?: boolean;
12
+ }
13
+ /**
14
+ * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
15
+ *
16
+ * @remarks
17
+ * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
18
+ * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
19
+ * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
20
+ * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
21
+ * Registration is idempotent; the first registration's default options take precedence.
22
+ * Runtime conversion does not override Mongoose's inferred lean result types.
23
+ */
24
+ export declare function mongooseLeanDecimal128ToStringPlugin(schema: Schema, pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions): void;
25
+ //#endregion
26
+ //# sourceMappingURL=lean-decimal128-to-string.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lean-decimal128-to-string.d.ts","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"mappings":";;;YAOc;;IAEN;;;iBAMS;;EAEb;;;;;;;;;;;;;wBAuFY,qCACZ,QAAQ,QACR,gBAAgB"}
@@ -0,0 +1,85 @@
1
+ //#region src/plugins/lean-decimal128-to-string.ts
2
+ const registeredSchemas = /* @__PURE__ */ new WeakSet();
3
+ const isNonNullObject = (value) => value !== null && typeof value === "object";
4
+ function convertDocument(schema, value) {
5
+ if (!isNonNullObject(value)) return;
6
+ const discriminatorKey = schema.get("discriminatorKey") ?? "__t";
7
+ (Object.values(schema.discriminators ?? {}).find((childSchema) => childSchema.get("discriminatorKey") === discriminatorKey && childSchema.discriminatorMapping?.value === value[discriminatorKey]) ?? schema).eachPath((path, schemaType) => {
8
+ const pathSegments = path.split(".");
9
+ if (pathSegments.includes("$*")) return;
10
+ convertPath(value, pathSegments, schemaType);
11
+ });
12
+ }
13
+ function convertPath(value, pathSegments, schemaType) {
14
+ if (Array.isArray(value)) {
15
+ value.forEach((item) => convertPath(item, pathSegments, schemaType));
16
+ return;
17
+ }
18
+ if (!isNonNullObject(value)) return;
19
+ const [key, ...remainingPathSegments] = pathSegments;
20
+ if (key === void 0 || !Object.hasOwn(value, key)) return;
21
+ if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
22
+ else value[key] = convertValue(value[key], schemaType);
23
+ }
24
+ function convertValue(value, schemaType) {
25
+ if (value === null || value === void 0) return value;
26
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
27
+ if (embeddedSchemaType && Array.isArray(value)) {
28
+ for (let i = 0; i < value.length; i++) if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
29
+ return value;
30
+ }
31
+ if (embeddedSchemaType && schemaType.instance === "Map") {
32
+ if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));
33
+ else if (isNonNullObject(value)) for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
34
+ return value;
35
+ }
36
+ if (schemaType.schema) {
37
+ convertDocument(schemaType.schema, value);
38
+ return value;
39
+ }
40
+ if (schemaType.instance === "Decimal128" && schemaType.options.leanDecimal128ToString === true && isNonNullObject(value) && value._bsontype === "Decimal128" && typeof value.toString === "function") return value.toString();
41
+ return value;
42
+ }
43
+ /**
44
+ * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
45
+ *
46
+ * @remarks
47
+ * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
48
+ * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
49
+ * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
50
+ * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
51
+ * Registration is idempotent; the first registration's default options take precedence.
52
+ * Runtime conversion does not override Mongoose's inferred lean result types.
53
+ */
54
+ function mongooseLeanDecimal128ToStringPlugin(schema, pluginOptions) {
55
+ if (registeredSchemas.has(schema)) return;
56
+ registeredSchemas.add(schema);
57
+ function convertResult(query, result) {
58
+ const leanOptions = query.mongooseOptions().lean;
59
+ if (!leanOptions) return result;
60
+ if (!(typeof leanOptions === "object" ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true : pluginOptions?.enabledByDefault ?? true)) return result;
61
+ const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;
62
+ const querySchema = query.model.schema;
63
+ if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));
64
+ else convertDocument(querySchema, document);
65
+ return result;
66
+ }
67
+ schema.pre("find", function() {
68
+ const transform = (result) => convertResult(this, result);
69
+ if (typeof this.map === "function") this.map(transform);
70
+ else if (typeof this.transform === "function") this.transform(transform);
71
+ else this.setOptions({ transform });
72
+ });
73
+ schema.post([
74
+ "findOne",
75
+ "findOneAndUpdate",
76
+ "findOneAndDelete",
77
+ "findOneAndReplace"
78
+ ], function(result) {
79
+ convertResult(this, result);
80
+ });
81
+ }
82
+ //#endregion
83
+ export { mongooseLeanDecimal128ToStringPlugin };
84
+
85
+ //# sourceMappingURL=lean-decimal128-to-string.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lean-decimal128-to-string.js","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"sourcesContent":["import type {\n Query,\n Schema,\n SchemaType,\n} from 'mongoose';\n\ndeclare module 'mongoose' {\n interface LeanOptions {\n /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */\n decimal128ToString?: boolean;\n }\n}\n\ntype QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };\n\nexport interface MongooseLeanDecimal128ToStringPluginOptions {\n /** Whether marked fields are converted on lean queries by default. Defaults to true. */\n enabledByDefault?: boolean;\n}\n\n// Constants/Variables\nconst registeredSchemas = new WeakSet<Schema>();\n\n// Functions\nconst isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';\n\nfunction convertDocument(schema: Schema, value: unknown) {\n if (!isNonNullObject(value)) return;\n const discriminatorKey = schema.get('discriminatorKey') ?? '__t';\n const discriminatorSchema = Object.values(schema.discriminators ?? {}).find(\n (childSchema) => childSchema.get('discriminatorKey') === discriminatorKey\n && (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value\n === value[discriminatorKey],\n );\n\n const documentSchema = discriminatorSchema ?? schema;\n documentSchema.eachPath((path, schemaType) => {\n // Maps are handled through their embedded schema type, not their synthetic $* path.\n const pathSegments = path.split('.');\n if (pathSegments.includes('$*')) return;\n convertPath(value, pathSegments, schemaType);\n });\n}\n\nfunction convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {\n if (Array.isArray(value)) {\n value.forEach((item) => convertPath(item, pathSegments, schemaType));\n return;\n }\n\n if (!isNonNullObject(value)) return;\n const [key, ...remainingPathSegments] = pathSegments;\n if (key === undefined || !Object.hasOwn(value, key)) return;\n if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);\n else value[key] = convertValue(value[key], schemaType);\n}\n\nfunction convertValue(value: unknown, schemaType: SchemaType): unknown {\n if (value === null || value === undefined) return value;\n const embeddedSchemaType = schemaType.getEmbeddedSchemaType();\n if (embeddedSchemaType && Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);\n }\n\n return value;\n }\n\n if (embeddedSchemaType && schemaType.instance === 'Map') {\n if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));\n else if (isNonNullObject(value)) {\n for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);\n }\n\n return value;\n }\n\n if (schemaType.schema) {\n convertDocument(schemaType.schema, value);\n return value;\n }\n\n if (\n schemaType.instance === 'Decimal128'\n && schemaType.options.leanDecimal128ToString === true\n && isNonNullObject(value)\n && value._bsontype === 'Decimal128'\n && typeof value.toString === 'function'\n ) return value.toString();\n\n return value;\n}\n\n/**\n * Converts marked Decimal128 fields to strings on lean queries without invoking getters.\n *\n * @remarks\n * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.\n * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.\n * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.\n * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.\n * Registration is idempotent; the first registration's default options take precedence.\n * Runtime conversion does not override Mongoose's inferred lean result types.\n */\nexport function mongooseLeanDecimal128ToStringPlugin(\n schema: Schema,\n pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions,\n) {\n if (registeredSchemas.has(schema)) return;\n registeredSchemas.add(schema);\n\n function convertResult(query: QueryWithOptionalMap, result: unknown) {\n const leanOptions = query.mongooseOptions().lean;\n if (!leanOptions) return result;\n const conversionEnabled = typeof leanOptions === 'object'\n ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true\n : pluginOptions?.enabledByDefault ?? true;\n\n if (!conversionEnabled) return result;\n const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;\n const querySchema = query.model.schema;\n if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));\n else convertDocument(querySchema, document);\n return result;\n }\n\n // Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.\n schema.pre(\n 'find',\n function (this: QueryWithOptionalMap) {\n const transform = (result: unknown) => convertResult(this, result);\n if (typeof this.map === 'function') this.map(transform);\n else if (typeof this.transform === 'function') this.transform(transform);\n else this.setOptions({ transform });\n },\n );\n\n schema.post(\n [\n 'findOne',\n 'findOneAndUpdate',\n 'findOneAndDelete',\n 'findOneAndReplace',\n ],\n function (this: QueryWithOptionalMap, result: unknown) {\n convertResult(this, result);\n },\n );\n}\n"],"mappings":";AAqBA,MAAM,oCAAoB,IAAI,QAAgB;AAG9C,MAAM,mBAAmB,UAAiD,UAAU,QAAQ,OAAO,UAAU;AAE7G,SAAS,gBAAgB,QAAgB,OAAgB;CACrD,IAAI,CAAC,gBAAgB,KAAK,GAAG;CAC7B,MAAM,mBAAmB,OAAO,IAAI,kBAAkB,KAAK;CAQ3D,CAP4B,OAAO,OAAO,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,MAClE,gBAAgB,YAAY,IAAI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B,gBAAgB,WAAW,QAAQ,KAAK;EACxC,OAAO;CACX;CAEA,IACI,WAAW,aAAa,gBACrB,WAAW,QAAQ,2BAA2B,QAC9C,gBAAgB,KAAK,KACrB,MAAM,cAAc,gBACpB,OAAO,MAAM,aAAa,YAC/B,OAAO,MAAM,SAAS;CAExB,OAAO;AACX;;;;;;;;;;;;AAaA,SAAgB,qCACZ,QACA,eACF;CACE,IAAI,kBAAkB,IAAI,MAAM,GAAG;CACnC,kBAAkB,IAAI,MAAM;CAE5B,SAAS,cAAc,OAA6B,QAAiB;EACjE,MAAM,cAAc,MAAM,gBAAgB,CAAC,CAAC;EAC5C,IAAI,CAAC,aAAa,OAAO;EAKzB,IAAI,EAJsB,OAAO,gBAAgB,WAC3C,YAAY,sBAAsB,eAAe,oBAAoB,OACrE,eAAe,oBAAoB,OAEjB,OAAO;EAC/B,MAAM,WAAW,MAAM,WAAW,CAAC,CAAC,yBAAyB,gBAAgB,MAAM,IAAI,OAAO,QAAQ;EACtG,MAAM,cAAc,MAAM,MAAM;EAChC,IAAI,MAAM,QAAQ,QAAQ,GAAG,SAAS,SAAS,UAAU,gBAAgB,aAAa,KAAK,CAAC;OACvF,gBAAgB,aAAa,QAAQ;EAC1C,OAAO;CACX;CAGA,OAAO,IACH,QACA,WAAsC;EAClC,MAAM,aAAa,WAAoB,cAAc,MAAM,MAAM;EACjE,IAAI,OAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,SAAS;OACjD,IAAI,OAAO,KAAK,cAAc,YAAY,KAAK,UAAU,SAAS;OAClE,KAAK,WAAW,EAAE,UAAU,CAAC;CACtC,CACJ;CAEA,OAAO,KACH;EACI;EACA;EACA;EACA;CACJ,GACA,SAAsC,QAAiB;EACnD,cAAc,MAAM,MAAM;CAC9B,CACJ;AACJ"}
@@ -10,6 +10,8 @@ export interface MongooseNormalizePluginOptions {
10
10
  * @defaultValue `true`.
11
11
  */
12
12
  convertIdField?: boolean;
13
+ /** Register normalization on child schemas too. Defaults to true. */
14
+ recursive?: boolean;
13
15
  /**
14
16
  * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
15
17
  *
@@ -31,10 +33,11 @@ export interface MongooseNormalizePluginOptions {
31
33
  * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
32
34
  * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
33
35
  * That transform can change the normalized output, and its errors propagate during serialization.
34
- * This plugin does not configure `toObject` or recursively register itself on child schemas.
36
+ * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
37
+ * Registration is idempotent per schema; the first registration's options take precedence.
35
38
  *
36
39
  * @param schema - The schema whose JSON serialization configuration is modified.
37
- * @param pluginOptions - The identifier normalization options; omitted options use their documented defaults.
40
+ * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
38
41
  */
39
42
  export declare function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions): void;
40
43
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";;iBAQiB;;;;;;;;;EASb;;;;;;;;;EAUA;;;;;;;;;;;;;;;;;;wBAmBY,wBAAwB,UAAU,QAC9C,QAAQ,GACR,gBAAgB"}
1
+ {"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";;iBAQiB;;;;;;;;;EASb;;EAGA;;;;;;;;;EAUA;;;;;;;;;;;;;;;;;;;wBAyBY,wBAAwB,UAAU,QAC9C,QAAQ,GACR,gBAAgB"}
@@ -1,6 +1,7 @@
1
1
  import { Types } from "mongoose";
2
2
  import { get, set, unset } from "es-toolkit/compat";
3
3
  //#region src/plugins/normalize.ts
4
+ const registeredSchemas = /* @__PURE__ */ new WeakSet();
4
5
  /**
5
6
  * Registers JSON normalization on a Mongoose schema.
6
7
  *
@@ -12,12 +13,15 @@ import { get, set, unset } from "es-toolkit/compat";
12
13
  * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
13
14
  * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
14
15
  * That transform can change the normalized output, and its errors propagate during serialization.
15
- * This plugin does not configure `toObject` or recursively register itself on child schemas.
16
+ * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
17
+ * Registration is idempotent per schema; the first registration's options take precedence.
16
18
  *
17
19
  * @param schema - The schema whose JSON serialization configuration is modified.
18
- * @param pluginOptions - The identifier normalization options; omitted options use their documented defaults.
20
+ * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
19
21
  */
20
22
  function mongooseNormalizePlugin(schema, pluginOptions) {
23
+ if (registeredSchemas.has(schema)) return;
24
+ registeredSchemas.add(schema);
21
25
  const decimalPaths = [];
22
26
  const privatePaths = [];
23
27
  for (const [path, schemaType] of Object.entries(schema.paths)) if (schemaType?.options?.private) privatePaths.push(path);
@@ -48,6 +52,7 @@ function mongooseNormalizePlugin(schema, pluginOptions) {
48
52
  return copiedRet;
49
53
  }
50
54
  });
55
+ if (pluginOptions?.recursive !== false) schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
51
56
  }
52
57
  //#endregion
53
58
  export { mongooseNormalizePlugin };
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.js","names":["getProp"],"sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import {\n get as getProp,\n set as setProp,\n unset as unsetProp,\n} from 'es-toolkit/compat';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to move the serialized `_id` value to `id`.\n *\n * @remarks\n * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.\n *\n * @defaultValue `true`.\n */\n convertIdField?: boolean;\n\n /**\n * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.\n *\n * @remarks\n * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.\n *\n * @defaultValue `true`.\n */\n toHexIdIfObjectId?: boolean;\n}\n\n/**\n * Registers JSON normalization on a Mongoose schema.\n *\n * @remarks\n * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,\n * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts\n * truthy serialized values at registered `Decimal128` paths to strings.\n *\n * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,\n * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.\n * That transform can change the normalized output, and its errors propagate during serialization.\n * This plugin does not configure `toObject` or recursively register itself on child schemas.\n *\n * @param schema - The schema whose JSON serialization configuration is modified.\n * @param pluginOptions - The identifier normalization options; omitted options use their documented defaults.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(\n schema: S,\n pluginOptions?: MongooseNormalizePluginOptions,\n) {\n // Collect special paths (Decimal128 & private)\n const decimalPaths: string[] = [];\n const privatePaths: string[] = [];\n for (const [path, schemaType] of Object.entries(schema.paths)) {\n if (schemaType?.options?.private) privatePaths.push(path);\n else if (schemaType?.instance === 'Decimal128') decimalPaths.push(path);\n }\n\n // Get original toJSON configuration\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n\n // Override toJSON with custom transform\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // Copy object and remove __v\n const copiedRet = { ...ret };\n // @ts-expect-error Ignore this error\n delete copiedRet.__v;\n\n // Normalize _id (convert to hex and/or move to id)\n let _id = copiedRet._id;\n delete copiedRet._id;\n if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) {\n _id = _id.toHexString();\n }\n\n if (_id !== undefined) {\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n }\n\n // Remove private fields\n for (const path of privatePaths) unsetProp(copiedRet, path);\n\n // Convert Decimal128 fields to string\n for (const path of decimalPaths) {\n const value = getProp(copiedRet, path) as Types.Decimal128 | undefined;\n if (value) setProp(copiedRet, path, value.toString());\n }\n\n // Run original toJSON transform\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);\n return transformed === undefined ? copiedRet : transformed;\n }\n\n // Return normalized object\n return copiedRet;\n },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,wBACZ,QACA,eACF;CAEE,MAAM,eAAyB,CAAC;CAChC,MAAM,eAAyB,CAAC;CAChC,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,OAAO,KAAK,GACxD,IAAI,YAAY,SAAS,SAAS,aAAa,KAAK,IAAI;MACnD,IAAI,YAAY,aAAa,cAAc,aAAa,KAAK,IAAI;CAI1E,MAAM,SAAS,OAAO,IAAI,QAAQ;CAClC,MAAM,kBAAkB,QAAQ;CAGhC,OAAO,IACH,UACA;EACI,GAAG;EACH,UAAU,KAAK,KAAK,SAAS;GAEzB,MAAM,YAAY,EAAE,GAAG,IAAI;GAE3B,OAAO,UAAU;GAGjB,IAAI,MAAM,UAAU;GACpB,OAAO,UAAU;GACjB,IAAI,eAAe,sBAAsB,SAAS,eAAe,MAAM,UACnE,MAAM,IAAI,YAAY;GAG1B,IAAI,QAAQ,KAAA,GAAW;IACnB,IAAI,eAAe,mBAAmB,OAAO,UAAU,KAAK;SACvD,UAAU,MAAM;GACzB;GAGA,KAAK,MAAM,QAAQ,cAAc,MAAU,WAAW,IAAI;GAG1D,KAAK,MAAM,QAAQ,cAAc;IAC7B,MAAM,QAAQA,IAAQ,WAAW,IAAI;IACrC,IAAI,OAAO,IAAQ,WAAW,MAAM,MAAM,SAAS,CAAC;GACxD;GAGA,IAAI,mBAAmB,OAAO,oBAAoB,WAAW;IACzD,MAAM,cAAc,gBAAgB,KAAY,WAAkB,OAAc;IAChF,OAAO,gBAAgB,KAAA,IAAY,YAAY;GACnD;GAGA,OAAO;EACX;CACJ,CACJ;AACJ"}
1
+ {"version":3,"file":"normalize.js","names":["getProp"],"sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import {\n get as getProp,\n set as setProp,\n unset as unsetProp,\n} from 'es-toolkit/compat';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to move the serialized `_id` value to `id`.\n *\n * @remarks\n * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.\n *\n * @defaultValue `true`.\n */\n convertIdField?: boolean;\n\n /** Register normalization on child schemas too. Defaults to true. */\n recursive?: boolean;\n\n /**\n * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.\n *\n * @remarks\n * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.\n *\n * @defaultValue `true`.\n */\n toHexIdIfObjectId?: boolean;\n}\n\n// Constants/Variables\nconst registeredSchemas = new WeakSet<Schema>();\n\n// Functions\n\n/**\n * Registers JSON normalization on a Mongoose schema.\n *\n * @remarks\n * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,\n * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts\n * truthy serialized values at registered `Decimal128` paths to strings.\n *\n * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,\n * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.\n * That transform can change the normalized output, and its errors propagate during serialization.\n * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.\n * Registration is idempotent per schema; the first registration's options take precedence.\n *\n * @param schema - The schema whose JSON serialization configuration is modified.\n * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(\n schema: S,\n pluginOptions?: MongooseNormalizePluginOptions,\n) {\n if (registeredSchemas.has(schema)) return;\n registeredSchemas.add(schema);\n\n // Collect special paths (Decimal128 & private)\n const decimalPaths: string[] = [];\n const privatePaths: string[] = [];\n for (const [path, schemaType] of Object.entries(schema.paths)) {\n if (schemaType?.options?.private) privatePaths.push(path);\n else if (schemaType?.instance === 'Decimal128') decimalPaths.push(path);\n }\n\n // Get original toJSON configuration\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n\n // Override toJSON with custom transform\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // Copy object and remove __v\n const copiedRet = { ...ret };\n // @ts-expect-error Ignore this error\n delete copiedRet.__v;\n\n // Normalize _id (convert to hex and/or move to id)\n let _id = copiedRet._id;\n delete copiedRet._id;\n if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) {\n _id = _id.toHexString();\n }\n\n if (_id !== undefined) {\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n }\n\n // Remove private fields\n for (const path of privatePaths) unsetProp(copiedRet, path);\n\n // Convert Decimal128 fields to string\n for (const path of decimalPaths) {\n const value = getProp(copiedRet, path) as Types.Decimal128 | undefined;\n if (value) setProp(copiedRet, path, value.toString());\n }\n\n // Run original toJSON transform\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);\n return transformed === undefined ? copiedRet : transformed;\n }\n\n // Return normalized object\n return copiedRet;\n },\n },\n );\n\n if (pluginOptions?.recursive !== false) {\n schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));\n }\n}\n"],"mappings":";;;AAkCA,MAAM,oCAAoB,IAAI,QAAgB;;;;;;;;;;;;;;;;;;AAqB9C,SAAgB,wBACZ,QACA,eACF;CACE,IAAI,kBAAkB,IAAI,MAAM,GAAG;CACnC,kBAAkB,IAAI,MAAM;CAG5B,MAAM,eAAyB,CAAC;CAChC,MAAM,eAAyB,CAAC;CAChC,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,OAAO,KAAK,GACxD,IAAI,YAAY,SAAS,SAAS,aAAa,KAAK,IAAI;MACnD,IAAI,YAAY,aAAa,cAAc,aAAa,KAAK,IAAI;CAI1E,MAAM,SAAS,OAAO,IAAI,QAAQ;CAClC,MAAM,kBAAkB,QAAQ;CAGhC,OAAO,IACH,UACA;EACI,GAAG;EACH,UAAU,KAAK,KAAK,SAAS;GAEzB,MAAM,YAAY,EAAE,GAAG,IAAI;GAE3B,OAAO,UAAU;GAGjB,IAAI,MAAM,UAAU;GACpB,OAAO,UAAU;GACjB,IAAI,eAAe,sBAAsB,SAAS,eAAe,MAAM,UACnE,MAAM,IAAI,YAAY;GAG1B,IAAI,QAAQ,KAAA,GAAW;IACnB,IAAI,eAAe,mBAAmB,OAAO,UAAU,KAAK;SACvD,UAAU,MAAM;GACzB;GAGA,KAAK,MAAM,QAAQ,cAAc,MAAU,WAAW,IAAI;GAG1D,KAAK,MAAM,QAAQ,cAAc;IAC7B,MAAM,QAAQA,IAAQ,WAAW,IAAI;IACrC,IAAI,OAAO,IAAQ,WAAW,MAAM,MAAM,SAAS,CAAC;GACxD;GAGA,IAAI,mBAAmB,OAAO,oBAAoB,WAAW;IACzD,MAAM,cAAc,gBAAgB,KAAY,WAAkB,OAAc;IAChF,OAAO,gBAAgB,KAAA,IAAY,YAAY;GACnD;GAGA,OAAO;EACX;CACJ,CACJ;CAEA,IAAI,eAAe,cAAc,OAC7B,OAAO,aAAa,SAAS,EAAE,QAAQ,YAAY,MAAM,OAAO,yBAAyB,aAAa,CAAC;AAE/G"}
@@ -7,6 +7,12 @@ type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string
7
7
  interface BaseProps {
8
8
  type: typeof Schema.Types.BigInt;
9
9
  }
10
+ interface BigIntEnumValidator {
11
+ enumValues: (bigint | null)[];
12
+ message: string;
13
+ type: 'enum';
14
+ validator: (value: bigint | null | undefined) => boolean;
15
+ }
10
16
  interface BigIntLimitValidator {
11
17
  max?: bigint;
12
18
  message: string;
@@ -18,6 +24,12 @@ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
18
24
  default: <T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined, D extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, {
19
25
  default: T;
20
26
  }>, ExtraOmitFields>;
27
+ enum: <T extends Readonlyable<(N | null)[]> | {
28
+ [path: string]: N | null;
29
+ } | {
30
+ message?: M;
31
+ values: Readonlyable<(N | null)[]>;
32
+ }, M extends string, N extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'enum' | ExtraOmitFields>;
21
33
  immutable: ExtendSchemaBuilder<Merge<Props, {
22
34
  immutable: true;
23
35
  }>, ExtraOmitFields>;
@@ -41,7 +53,7 @@ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
41
53
  }>, ExtraOmitFields>;
42
54
  }
43
55
  interface BigIntValidationSchema {
44
- validate: BigIntLimitValidator[];
56
+ validate: (BigIntEnumValidator | BigIntLimitValidator)[];
45
57
  }
46
58
  export declare function bigintSchemaBuilder(): BigIntSchemaBuilder;
47
59
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"bigint.d.ts","names":[],"sources":["../../src/schema-builders/bigint.ts"],"mappings":";;;;KAYK;KACA,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN;EACA;EACA;EACA;EACA,YAAY;;iBAGC,oBAAoB,cAAc,YAAY,WAAW;EACtE,UACI,YAAY,WAAW,aAAa,YAAY,yBAAyB,YAAY,uBACrF,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,WAAW,oBAAoB,MAAM;IAAS;MAAoB;EAClE,QAAQ,oBAAoB,iBAAiB,cAAc,OAAO,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;EACzB,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;UAGtD;EACN,UAAU;;wBAUE,uBAuBP"}
1
+ {"version":3,"file":"bigint.d.ts","names":[],"sources":["../../src/schema-builders/bigint.ts"],"mappings":";;;;KAYK;KACA,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN;EACA;EACA;EACA,YAAY;;UAGN;EACN;EACA;EACA;EACA;EACA,YAAY;;iBAGC,oBAAoB,cAAc,YAAY,WAAW;EACtE,UACI,YAAY,WAAW,aAAa,YAAY,yBAAyB,YAAY,uBACrF,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,OACI,UACE,cAAc;KACX,eAAe;;IAChB,UAAU;IAAG,QAAQ,cAAc;KACvC,kBACA,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,kCACJ;EAGb,WAAW,oBAAoB,MAAM;IAAS;MAAoB;EAClE,QAAQ,oBAAoB,iBAAiB,cAAc,OAAO,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;EACzB,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;UAGtD;EACN,WAAW,sBAAsB;;wBAWrB,uBA2DP"}
@@ -1,6 +1,7 @@
1
1
  import { createBaseSchemaBuilderFactory } from "./base.js";
2
2
  import { Schema } from "mongoose";
3
3
  //#region src/schema-builders/bigint.ts
4
+ const defaultEnumValidateMessage = "Path `{PATH}` ({VALUE}) is not a valid enum value.";
4
5
  const defaultMinValidateMessage = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";
5
6
  const defaultMaxValidateMessage = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";
6
7
  const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);
@@ -8,6 +9,27 @@ function bigintSchemaBuilder() {
8
9
  const schema = {};
9
10
  const baseBuilder = baseBuilderFactory(schema);
10
11
  return new Proxy(baseBuilder, { get(target, key, receiver) {
12
+ if (key === "enum") {
13
+ if (schema.validate?.some(({ type }) => type === "enum")) throw new Error("Duplicate schema attribute: enum");
14
+ return (value) => {
15
+ let enumValues;
16
+ let message;
17
+ if (Array.isArray(value)) enumValues = [...value];
18
+ else if ("values" in value && Array.isArray(value.values)) {
19
+ enumValues = [...value.values];
20
+ if ("message" in value && typeof value.message === "string") message = value.message;
21
+ } else enumValues = Object.values(value);
22
+ const allowedValues = new Set(enumValues);
23
+ const validator = {
24
+ enumValues,
25
+ message: message ?? defaultEnumValidateMessage,
26
+ type: "enum",
27
+ validator: (value) => value === null || value === void 0 || allowedValues.has(value)
28
+ };
29
+ schema.validate = [...schema.validate ?? [], validator];
30
+ return receiver;
31
+ };
32
+ }
11
33
  if (key === "max" || key === "min") return (value) => {
12
34
  const validator = createLimitValidator(key, value);
13
35
  const validators = Array.isArray(schema.validate) ? schema.validate : [];
@@ -1 +1 @@
1
- {"version":3,"file":"bigint.js","names":[],"sources":["../../src/schema-builders/bigint.ts"],"sourcesContent":["import { Schema } from 'mongoose';\nimport type {\n DefaultType,\n IndexDirection,\n IndexOptions,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype BigIntLimit = bigint;\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n BigIntSchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: typeof Schema.Types.BigInt;\n}\n\ninterface BigIntLimitValidator {\n max?: bigint;\n message: string;\n min?: bigint;\n type: 'max' | 'min';\n validator: (value: bigint | null | undefined) => boolean;\n}\n\nexport interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined,\n D extends bigint,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends L | Readonlyable<[L, S]>,\n L extends BigIntLimit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, BigIntValidationSchema>,\n 'max' | ExtraOmitFields\n >;\n\n min: <\n T extends L | Readonlyable<[L, S]>,\n L extends BigIntLimit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, BigIntValidationSchema>,\n 'min' | ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\ninterface BigIntValidationSchema {\n validate: BigIntLimitValidator[];\n}\n\n// Constants/Variables\nconst defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';\nconst defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';\n\n// Functions\nconst baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);\n\nexport function bigintSchemaBuilder() {\n const schema: Record<string, any> = {};\n const baseBuilder = baseBuilderFactory(schema);\n return new Proxy(\n baseBuilder,\n {\n get(target, key, receiver) {\n if (key === 'max' || key === 'min') {\n return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {\n const validator = createLimitValidator(key, value);\n const validators = Array.isArray(schema.validate) ? schema.validate : [];\n schema.validate = [\n ...validators.filter(({ type }) => type !== key),\n validator,\n ];\n\n return receiver;\n };\n }\n\n return Reflect.get(target, key, receiver);\n },\n },\n ) as BigIntSchemaBuilder;\n}\n\nfunction createLimitValidator(\n type: 'max' | 'min',\n value: BigIntLimit | Readonlyable<[BigIntLimit, string]>,\n): BigIntLimitValidator {\n const [limit, message] = Array.isArray(value)\n ? value as Readonly<[BigIntLimit, string]>\n : [\n value as BigIntLimit,\n undefined,\n ];\n\n if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);\n\n return {\n message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),\n [type]: limit,\n type,\n validator: (value) => {\n if (value === null || value === undefined) return true;\n\n return type === 'min' ? value >= limit : value <= limit;\n },\n };\n}\n"],"mappings":";;;AA8EA,MAAM,4BAA4B;AAClC,MAAM,4BAA4B;AAGlC,MAAM,qBAAqB,+BAA+B,OAAO,MAAM,MAAM;AAE7E,SAAgB,sBAAsB;CAClC,MAAM,SAA8B,CAAC;CACrC,MAAM,cAAc,mBAAmB,MAAM;CAC7C,OAAO,IAAI,MACP,aACA,EACI,IAAI,QAAQ,KAAK,UAAU;EACvB,IAAI,QAAQ,SAAS,QAAQ,OACzB,QAAQ,UAA6D;GACjE,MAAM,YAAY,qBAAqB,KAAK,KAAK;GACjD,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,IAAI,OAAO,WAAW,CAAC;GACvE,OAAO,WAAW,CACd,GAAG,WAAW,QAAQ,EAAE,WAAW,SAAS,GAAG,GAC/C,SACJ;GAEA,OAAO;EACX;EAGJ,OAAO,QAAQ,IAAI,QAAQ,KAAK,QAAQ;CAC5C,EACJ,CACJ;AACJ;AAEA,SAAS,qBACL,MACA,OACoB;CACpB,MAAM,CAAC,OAAO,WAAW,MAAM,QAAQ,KAAK,IACtC,QACA,CACE,OACA,KAAA,CACJ;CAEJ,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,UAAU,UAAU,KAAK,wBAAwB;CAE1F,OAAO;EACH,SAAS,YAAY,SAAS,QAAQ,4BAA4B;GACjE,OAAO;EACR;EACA,YAAY,UAAU;GAClB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAElD,OAAO,SAAS,QAAQ,SAAS,QAAQ,SAAS;EACtD;CACJ;AACJ"}
1
+ {"version":3,"file":"bigint.js","names":[],"sources":["../../src/schema-builders/bigint.ts"],"sourcesContent":["import { Schema } from 'mongoose';\nimport type {\n DefaultType,\n IndexDirection,\n IndexOptions,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype BigIntLimit = bigint;\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n BigIntSchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: typeof Schema.Types.BigInt;\n}\n\ninterface BigIntEnumValidator {\n enumValues: (bigint | null)[];\n message: string;\n type: 'enum';\n validator: (value: bigint | null | undefined) => boolean;\n}\n\ninterface BigIntLimitValidator {\n max?: bigint;\n message: string;\n min?: bigint;\n type: 'max' | 'min';\n validator: (value: bigint | null | undefined) => boolean;\n}\n\nexport interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined,\n D extends bigint,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n enum: <\n T extends\n | Readonlyable<(N | null)[]>\n | { [path: string]: N | null }\n | { message?: M; values: Readonlyable<(N | null)[]> },\n M extends string,\n N extends bigint,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, BigIntValidationSchema>,\n 'enum' | ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends L | Readonlyable<[L, S]>,\n L extends BigIntLimit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, BigIntValidationSchema>,\n 'max' | ExtraOmitFields\n >;\n\n min: <\n T extends L | Readonlyable<[L, S]>,\n L extends BigIntLimit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, BigIntValidationSchema>,\n 'min' | ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\ninterface BigIntValidationSchema {\n validate: (BigIntEnumValidator | BigIntLimitValidator)[];\n}\n\n// Constants/Variables\nconst defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';\nconst defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';\nconst defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';\n\n// Functions\nconst baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);\n\nexport function bigintSchemaBuilder() {\n const schema: Record<string, any> = {};\n const baseBuilder = baseBuilderFactory(schema);\n return new Proxy(\n baseBuilder,\n {\n get(target, key, receiver) {\n if (key === 'enum') {\n if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {\n throw new Error('Duplicate schema attribute: enum');\n }\n\n return (\n value: Readonlyable<(bigint | null)[]>\n | { [path: string]: bigint | null }\n | { message?: string; values: Readonlyable<(bigint | null)[]> },\n ) => {\n let enumValues: (bigint | null)[];\n let message: string | undefined;\n\n if (Array.isArray(value)) enumValues = [...value];\n else if ('values' in value && Array.isArray(value.values)) {\n enumValues = [...value.values];\n if ('message' in value && typeof value.message === 'string') message = value.message;\n } else enumValues = Object.values(value);\n\n const allowedValues = new Set(enumValues);\n const validator: BigIntEnumValidator = {\n enumValues,\n message: message ?? defaultEnumValidateMessage,\n type: 'enum',\n validator: (value) => value === null || value === undefined || allowedValues.has(value),\n };\n\n schema.validate = [\n ...schema.validate ?? [],\n validator,\n ];\n\n return receiver;\n };\n }\n\n if (key === 'max' || key === 'min') {\n return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {\n const validator = createLimitValidator(key, value);\n const validators = Array.isArray(schema.validate) ? schema.validate : [];\n schema.validate = [\n ...validators.filter(({ type }) => type !== key),\n validator,\n ];\n\n return receiver;\n };\n }\n\n return Reflect.get(target, key, receiver);\n },\n },\n ) as BigIntSchemaBuilder;\n}\n\nfunction createLimitValidator(\n type: 'max' | 'min',\n value: BigIntLimit | Readonlyable<[BigIntLimit, string]>,\n): BigIntLimitValidator {\n const [limit, message] = Array.isArray(value)\n ? value as Readonly<[BigIntLimit, string]>\n : [\n value as BigIntLimit,\n undefined,\n ];\n\n if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);\n\n return {\n message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),\n [type]: limit,\n type,\n validator: (value) => {\n if (value === null || value === undefined) return true;\n\n return type === 'min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,QAAQ,KAAK,QAAQ;CAC5C,EACJ,CACJ;AACJ;AAEA,SAAS,qBACL,MACA,OACoB;CACpB,MAAM,CAAC,OAAO,WAAW,MAAM,QAAQ,KAAK,IACtC,QACA,CACE,OACA,KAAA,CACJ;CAEJ,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,UAAU,UAAU,KAAK,wBAAwB;CAE1F,OAAO;EACH,SAAS,YAAY,SAAS,QAAQ,4BAA4B;GACjE,OAAO;EACR;EACA,YAAY,UAAU;GAClB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAElD,OAAO,SAAS,QAAQ,SAAS,QAAQ,SAAS;EACtD;CACJ;AACJ"}
@@ -14,11 +14,11 @@ export interface DateSchemaBuilder<Props extends {
14
14
  default: <T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null, D extends NativeDate>(value: T) => ExtendSchemaBuilder<Merge<Props, {
15
15
  default: T;
16
16
  }>, ExtraOmitFields>;
17
- enum: <T extends Readonlyable<Array<D | null>> | {
17
+ enum: <T extends Readonlyable<(D | null)[]> | {
18
18
  [path: string]: D | null;
19
19
  } | {
20
20
  message?: M;
21
- values: Readonlyable<Array<D | null>>;
21
+ values: Readonlyable<(D | null)[]>;
22
22
  }, D extends NativeDate, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
23
23
  enum: T;
24
24
  }>, ExtraOmitFields>;
@@ -1 +1 @@
1
- {"version":3,"file":"date.d.ts","names":[],"sources":["../../src/schema-builders/date.ts"],"mappings":";;;;KAYK,oBACD,cAAc,WACd,kCACA,KACA,kBAAkB,OAAO,kBACzB,wBAAwB;UAGlB;EACN,MAAM;;iBAGO,kBACb;EAAgB,MAAM;;EAA2B,MAAM;GACvD;EAEA,UACI,YAAY,WAAW,aAAa,YAAY,MAAM,YAAY,WAClE,UAAU,YACZ,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,OACI,UACE,aAAa,MAAM;KAChB,eAAe;;IAChB,U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U,YACV,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,KAAK;MACpB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,YACV,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,KAAK;MACpB;EAGJ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;EACzB,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;qBAGnD,oBAAiB,SAAA,wBAAA;EAtD6B,MAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"date.js","names":[],"sources":["../../src/schema-builders/date.ts"],"sourcesContent":["import type {\n DateSchemaDefinition,\n DefaultType,\n IndexDirection,\n IndexOptions,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n DateSchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: DateSchemaDefinition;\n}\n\nexport interface DateSchemaBuilder<\n Props extends { type: DateSchemaDefinition } = { type: DateSchemaDefinition },\n ExtraOmitFields extends string = never,\n> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,\n D extends NativeDate,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n enum: <\n T extends\n | Readonlyable<Array<D | null>>\n | { [path: string]: D | null }\n | { message?: M; values: Readonlyable<Array<D | null>> },\n D extends NativeDate,\n M extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { enum: T }>,\n ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends D | Readonlyable<[D, S]>,\n D extends NativeDate,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { max: T }>,\n ExtraOmitFields\n >;\n\n min: <\n T extends D | Readonlyable<[D, S]>,\n D extends NativeDate,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { min: T }>,\n ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\nexport const dateSchemaBuilder = createBaseSchemaBuilderFactory<DateSchemaBuilder>(Date);\n"],"mappings":";;AA+EA,MAAa,oBAAoB,+BAAkD,IAAI"}
1
+ {"version":3,"file":"date.js","names":[],"sources":["../../src/schema-builders/date.ts"],"sourcesContent":["import type {\n DateSchemaDefinition,\n DefaultType,\n IndexDirection,\n IndexOptions,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n DateSchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: DateSchemaDefinition;\n}\n\nexport interface DateSchemaBuilder<\n Props extends { type: DateSchemaDefinition } = { type: DateSchemaDefinition },\n ExtraOmitFields extends string = never,\n> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,\n D extends NativeDate,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n enum: <\n T extends\n | Readonlyable<(D | null)[]>\n | { [path: string]: D | null }\n | { message?: M; values: Readonlyable<(D | null)[]> },\n D extends NativeDate,\n M extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { enum: T }>,\n ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends D | Readonlyable<[D, S]>,\n D extends NativeDate,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { max: T }>,\n ExtraOmitFields\n >;\n\n min: <\n T extends D | Readonlyable<[D, S]>,\n D extends NativeDate,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { min: T }>,\n ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\nexport const dateSchemaBuilder = createBaseSchemaBuilderFactory<DateSchemaBuilder>(Date);\n"],"mappings":";;AA+EA,MAAa,oBAAoB,+BAAkD,IAAI"}
@@ -25,11 +25,11 @@ export interface Decimal128SchemaBuilder<Props extends {
25
25
  default: <T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null, D extends Types.Decimal128>(value: T) => ExtendSchemaBuilder<Merge<Props, {
26
26
  default: T;
27
27
  }>, ExtraOmitFields>;
28
- enum: <T extends Readonlyable<Array<D | null>> | {
28
+ enum: <T extends Readonlyable<(D | null)[]> | {
29
29
  [path: string]: D | null;
30
30
  } | {
31
31
  message?: M;
32
- values: Readonlyable<Array<D | null>>;
32
+ values: Readonlyable<(D | null)[]>;
33
33
  }, D extends Types.Decimal128, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
34
34
  enum: T;
35
35
  }>, ExtraOmitFields>;
@@ -69,6 +69,7 @@ export interface Decimal128SchemaBuilder<Props extends {
69
69
  * @remarks
70
70
  * Replaces the configured getter on this builder. The getter returns the value's string representation,
71
71
  * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.
72
+ * Marks this path for the lean Decimal128-to-string plugin; the plugin does not invoke this getter.
72
73
  *
73
74
  * @returns This instance for chaining.
74
75
  */
@@ -85,6 +86,7 @@ interface Decimal128ValidationSchema {
85
86
  }
86
87
  interface ToStringGetterSchema {
87
88
  get: (value?: Types.Decimal128) => string | undefined;
89
+ leanDecimal128ToString: true;
88
90
  }
89
91
  interface ToStringSetterSchema {
90
92
  set: (value?: {
@@ -1 +1 @@
1
- {"version":3,"file":"decimal128.d.ts","names":[],"sources":["../../src/schema-builders/decimal128.ts"],"mappings":";;;;;KAcK,kBAAkB,QAAQ,QAAQ,MAAM;EAAe;;KACvD,oBACD,cAAc,WACd,kCACA,KACA,wBAAwB,OAAO,kBAC/B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN;EACA;EACA;EACA;EACA,YAAY,cAAc,MAAM;;iBAGnB,wBACb;EAAgB,aAAa,OAAO,MAAM;;EAAiB,aAAa,OAAO,MAAM;GACrF;EAEA,UACI,YAAY,WAAW,aAAa,YAAY,MAAM,YAAY,WAClE,UAAU,MAAM,YAClB,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,OACI,UACE,aAAa,MAAM;KAChB,eAAe;;IAChB,UAAU;IAAG,QAAQ,aAAa,MAAM;KAC5C,UAAU,MAAM,YAChB,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,MAAM;MACrB;EAGJ,WAAW,oBAAoB,MAAM;IAAS;MAAoB;EAClE,QAAQ,oBAAoB,iBAAiB,cAAc,OAAO,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG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,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,iBACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,qCACL;EAGZ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,iBACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,qCACL;EAGZ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;;;;;;;;;;;;;;;EAgBzB,2BAA2B,iBAAiB,WAAW,QAAQ,aAAa,oBACxE,MAAM,OAAO,oDACgB;;;;;;;;;;;EAajC,mBAAmB,oBAAoB,MAAM,OAAO,6CAA6C;EACjG,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;UAGtD;EACN,UAAU;;UAGJ;EACN,MAAM,QAAQ,MAAM;EACpB;;UAGM;EACN,MAAM;IAAU;;;wBAqCJ,2BA0CP"}
@@ -38,6 +38,7 @@ function decimal128SchemaBuilder() {
38
38
  };
39
39
  if (key === "setToStringGetter") {
40
40
  schema.get = (value) => value?.toString();
41
+ schema.leanDecimal128ToString = true;
41
42
  return receiver;
42
43
  }
43
44
  return Reflect.get(target, key, receiver);
@@ -1 +1 @@
1
- {"version":3,"file":"decimal128.js","names":[],"sources":["../../src/schema-builders/decimal128.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\nimport { Schema } from 'mongoose';\nimport type {\n DefaultType,\n IndexDirection,\n IndexOptions,\n Types,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype Decimal128Limit = Decimal.Value | Types.Decimal128 | { toString: () => string };\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n Decimal128SchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: typeof Schema.Types.Decimal128;\n}\n\ninterface Decimal128LimitValidator {\n max?: string;\n message: string;\n min?: string;\n type: 'max' | 'min';\n validator: (value: null | Types.Decimal128 | undefined) => boolean;\n}\n\nexport interface Decimal128SchemaBuilder<\n Props extends { type: typeof Schema.Types.Decimal128 } = { type: typeof Schema.Types.Decimal128 },\n ExtraOmitFields extends string = never,\n> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,\n D extends Types.Decimal128,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n enum: <\n T extends\n | Readonlyable<Array<D | null>>\n | { [path: string]: D | null }\n | { message?: M; values: Readonlyable<Array<D | null>> },\n D extends Types.Decimal128,\n M extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { enum: T }>,\n ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends D | Readonlyable<[D, S]>,\n D extends Decimal128Limit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, Decimal128ValidationSchema>,\n 'max' | ExtraOmitFields\n >;\n\n min: <\n T extends D | Readonlyable<[D, S]>,\n D extends Decimal128Limit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, Decimal128ValidationSchema>,\n 'min' | ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n\n /**\n * Configures a setter that rounds decimal values and formats them with a fixed number of decimal places.\n *\n * @remarks\n * Replaces the configured setter on this builder. The setter converts non-nullish values through Decimal.js\n * and returns a decimal string for Mongoose to cast to `Decimal128`. It returns `undefined` for `null` or\n * `undefined`. Decimal.js validates conversion and formatting when the setter processes a value,\n * not when the setter is configured.\n *\n * @param places - The non-negative integer number of decimal places. Defaults to `2`.\n * @param rounding - The Decimal.js rounding mode. Defaults to `Decimal.ROUND_DOWN`, which rounds toward zero.\n *\n * @returns This instance for chaining.\n */\n setRoundAndToFixedSetter: (places?: number, rounding?: Decimal.Rounding) => ExtendSchemaBuilder<\n Merge<Props, ToStringSetterSchema>,\n 'setRoundAndToFixedSetter' | ExtraOmitFields\n >;\n\n /**\n * Configures a getter that converts decimal values to strings.\n *\n * @remarks\n * Replaces the configured getter on this builder. The getter returns the value's string representation,\n * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.\n *\n * @returns This instance for chaining.\n */\n setToStringGetter: ExtendSchemaBuilder<Merge<Props, ToStringGetterSchema>, 'setToStringGetter' | ExtraOmitFields>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\ninterface Decimal128ValidationSchema {\n validate: Decimal128LimitValidator[];\n}\n\ninterface ToStringGetterSchema {\n get: (value?: Types.Decimal128) => string | undefined;\n}\n\ninterface ToStringSetterSchema {\n set: (value?: { toString: () => string }) => string | undefined;\n}\n\n// Constants/Variables\nconst defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';\nconst defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';\n\n// Functions\nconst baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.Decimal128);\n\nfunction createLimitValidator(\n type: 'max' | 'min',\n value: Decimal128Limit | Readonlyable<[Decimal128Limit, string]>,\n): Decimal128LimitValidator {\n const [limit, message] = Array.isArray(value)\n ? value as Readonly<[Decimal128Limit, string]>\n : [\n value,\n undefined,\n ];\n\n const decimalLimit = new Decimal(limit.toString());\n if (!decimalLimit.isFinite()) throw new RangeError(`Decimal128 ${type} limit must be finite`);\n\n return {\n message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),\n [type]: decimalLimit.toString(),\n type,\n validator: (value) => {\n if (value === null || value === undefined) return true;\n\n const decimalValue = new Decimal(value.toString());\n return type === 'min' ? decimalValue.gte(decimalLimit) : decimalValue.lte(decimalLimit);\n },\n };\n}\n\nexport function decimal128SchemaBuilder() {\n const schema: Record<string, any> = {};\n const baseBuilder = baseBuilderFactory(schema);\n return new Proxy(\n baseBuilder,\n {\n get(target, key, receiver) {\n if (key === 'max' || key === 'min') {\n return (value: Decimal128Limit | Readonlyable<[Decimal128Limit, string]>) => {\n const validator = createLimitValidator(key, value);\n const validators = Array.isArray(schema.validate) ? schema.validate : [];\n schema.validate = [\n ...validators.filter(({ type }) => type !== key),\n validator,\n ];\n\n return receiver;\n };\n }\n\n if (key === 'setRoundAndToFixedSetter') {\n return (places: number = 2, rounding: Decimal.Rounding = Decimal.ROUND_DOWN) => {\n schema.set = (value?: { toString: () => string }) => {\n if (value !== undefined && value !== null) {\n const decimal = Decimal.isDecimal(value) ? value : new Decimal(value.toString());\n return decimal.toFixed(places, rounding);\n }\n };\n\n return receiver;\n };\n }\n\n if (key === 'setToStringGetter') {\n schema.get = (value?: Types.Decimal128) => value?.toString();\n return receiver;\n }\n\n return Reflect.get(target, key, receiver);\n },\n },\n ) as Decimal128SchemaBuilder;\n}\n"],"mappings":";;;;AAqIA,MAAM,4BAA4B;AAClC,MAAM,4BAA4B;AAGlC,MAAM,qBAAqB,+BAA+B,OAAO,MAAM,UAAU;AAEjF,SAAS,qBACL,MACA,OACwB;CACxB,MAAM,CAAC,OAAO,WAAW,MAAM,QAAQ,KAAK,IACtC,QACA,CACE,OACA,KAAA,CACJ;CAEJ,MAAM,eAAe,IAAI,QAAQ,MAAM,SAAS,CAAC;CACjD,IAAI,CAAC,aAAa,SAAS,GAAG,MAAM,IAAI,WAAW,cAAc,KAAK,sBAAsB;CAE5F,OAAO;EACH,SAAS,YAAY,SAAS,QAAQ,4BAA4B;GACjE,OAAO,aAAa,SAAS;EAC9B;EACA,YAAY,UAAU;GAClB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAElD,MAAM,eAAe,IAAI,QAAQ,MAAM,SAAS,CAAC;GACjD,OAAO,SAAS,QAAQ,aAAa,IAAI,YAAY,IAAI,aAAa,IAAI,YAAY;EAC1F;CACJ;AACJ;AAEA,SAAgB,0BAA0B;CACtC,MAAM,SAA8B,CAAC;CACrC,MAAM,cAAc,mBAAmB,MAAM;CAC7C,OAAO,IAAI,MACP,aACA,EACI,IAAI,QAAQ,KAAK,UAAU;EACvB,IAAI,QAAQ,SAAS,QAAQ,OACzB,QAAQ,UAAqE;GACzE,MAAM,YAAY,qBAAqB,KAAK,KAAK;GACjD,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,IAAI,OAAO,WAAW,CAAC;GACvE,OAAO,WAAW,CACd,GAAG,WAAW,QAAQ,EAAE,WAAW,SAAS,GAAG,GAC/C,SACJ;GAEA,OAAO;EACX;EAGJ,IAAI,QAAQ,4BACR,QAAQ,SAAiB,GAAG,WAA6B,QAAQ,eAAe;GAC5E,OAAO,OAAO,UAAuC;IACjD,IAAI,UAAU,KAAA,KAAa,UAAU,MAEjC,QADgB,QAAQ,UAAU,KAAK,IAAI,QAAQ,IAAI,QAAQ,MAAM,SAAS,CAAC,EAAA,CAChE,QAAQ,QAAQ,QAAQ;GAE/C;GAEA,OAAO;EACX;EAGJ,IAAI,QAAQ,qBAAqB;GAC7B,OAAO,OAAO,UAA6B,OAAO,SAAS;GAC3D,OAAO;EACX;EAEA,OAAO,QAAQ,IAAI,QAAQ,KAAK,QAAQ;CAC5C,EACJ,CACJ;AACJ"}
1
+ {"version":3,"file":"decimal128.js","names":[],"sources":["../../src/schema-builders/decimal128.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\nimport { Schema } from 'mongoose';\nimport type {\n DefaultType,\n IndexDirection,\n IndexOptions,\n Types,\n} from 'mongoose';\nimport type { Merge } from 'type-fest';\n\nimport type { Readonlyable } from '../types/_internals';\n\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype Decimal128Limit = Decimal.Value | Types.Decimal128 | { toString: () => string };\ntype ExtendSchemaBuilder<\n Props extends BaseProps,\n ExtraOmitFields extends string,\n> = Omit<\n Decimal128SchemaBuilder<Props, ExtraOmitFields>,\n ExtraOmitFields | keyof Props\n>;\n\ninterface BaseProps {\n type: typeof Schema.Types.Decimal128;\n}\n\ninterface Decimal128LimitValidator {\n max?: string;\n message: string;\n min?: string;\n type: 'max' | 'min';\n validator: (value: null | Types.Decimal128 | undefined) => boolean;\n}\n\nexport interface Decimal128SchemaBuilder<\n Props extends { type: typeof Schema.Types.Decimal128 } = { type: typeof Schema.Types.Decimal128 },\n ExtraOmitFields extends string = never,\n> {\n default: <\n T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,\n D extends Types.Decimal128,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { default: T }>,\n ExtraOmitFields\n >;\n\n enum: <\n T extends\n | Readonlyable<(D | null)[]>\n | { [path: string]: D | null }\n | { message?: M; values: Readonlyable<(D | null)[]> },\n D extends Types.Decimal128,\n M extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, { enum: T }>,\n ExtraOmitFields\n >;\n\n immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;\n index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<\n Merge<Props, { index: T }>,\n ExtraOmitFields\n >;\n\n max: <\n T extends D | Readonlyable<[D, S]>,\n D extends Decimal128Limit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, Decimal128ValidationSchema>,\n 'max' | ExtraOmitFields\n >;\n\n min: <\n T extends D | Readonlyable<[D, S]>,\n D extends Decimal128Limit,\n S extends string,\n >(value: T) => ExtendSchemaBuilder<\n Merge<Props, Decimal128ValidationSchema>,\n 'min' | ExtraOmitFields\n >;\n\n nonRequired: Props;\n private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;\n required: Merge<Props, { required: true }>;\n\n /**\n * Configures a setter that rounds decimal values and formats them with a fixed number of decimal places.\n *\n * @remarks\n * Replaces the configured setter on this builder. The setter converts non-nullish values through Decimal.js\n * and returns a decimal string for Mongoose to cast to `Decimal128`. It returns `undefined` for `null` or\n * `undefined`. Decimal.js validates conversion and formatting when the setter processes a value,\n * not when the setter is configured.\n *\n * @param places - The non-negative integer number of decimal places. Defaults to `2`.\n * @param rounding - The Decimal.js rounding mode. Defaults to `Decimal.ROUND_DOWN`, which rounds toward zero.\n *\n * @returns This instance for chaining.\n */\n setRoundAndToFixedSetter: (places?: number, rounding?: Decimal.Rounding) => ExtendSchemaBuilder<\n Merge<Props, ToStringSetterSchema>,\n 'setRoundAndToFixedSetter' | ExtraOmitFields\n >;\n\n /**\n * Configures a getter that converts decimal values to strings.\n *\n * @remarks\n * Replaces the configured getter on this builder. The getter returns the value's string representation,\n * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.\n * Marks this path for the lean Decimal128-to-string plugin; the plugin does not invoke this getter.\n *\n * @returns This instance for chaining.\n */\n setToStringGetter: ExtendSchemaBuilder<Merge<Props, ToStringGetterSchema>, 'setToStringGetter' | ExtraOmitFields>;\n sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;\n unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;\n}\n\ninterface Decimal128ValidationSchema {\n validate: Decimal128LimitValidator[];\n}\n\ninterface ToStringGetterSchema {\n get: (value?: Types.Decimal128) => string | undefined;\n leanDecimal128ToString: true;\n}\n\ninterface ToStringSetterSchema {\n set: (value?: { toString: () => string }) => string | undefined;\n}\n\n// Constants/Variables\nconst defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';\nconst defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';\n\n// Functions\nconst baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.Decimal128);\n\nfunction createLimitValidator(\n type: 'max' | 'min',\n value: Decimal128Limit | Readonlyable<[Decimal128Limit, string]>,\n): Decimal128LimitValidator {\n const [limit, message] = Array.isArray(value)\n ? value as Readonly<[Decimal128Limit, string]>\n : [\n value,\n undefined,\n ];\n\n const decimalLimit = new Decimal(limit.toString());\n if (!decimalLimit.isFinite()) throw new RangeError(`Decimal128 ${type} limit must be finite`);\n\n return {\n message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),\n [type]: decimalLimit.toString(),\n type,\n validator: (value) => {\n if (value === null || value === undefined) return true;\n\n const decimalValue = new Decimal(value.toString());\n return type === 'min' ? decimalValue.gte(decimalLimit) : decimalValue.lte(decimalLimit);\n },\n };\n}\n\nexport function decimal128SchemaBuilder() {\n const schema: Record<string, any> = {};\n const baseBuilder = baseBuilderFactory(schema);\n return new Proxy(\n baseBuilder,\n {\n get(target, key, receiver) {\n if (key === 'max' || key === 'min') {\n return (value: Decimal128Limit | Readonlyable<[Decimal128Limit, string]>) => {\n const validator = createLimitValidator(key, value);\n const validators = Array.isArray(schema.validate) ? schema.validate : [];\n schema.validate = [\n ...validators.filter(({ type }) => type !== key),\n validator,\n ];\n\n return receiver;\n };\n }\n\n if (key === 'setRoundAndToFixedSetter') {\n return (places: number = 2, rounding: Decimal.Rounding = Decimal.ROUND_DOWN) => {\n schema.set = (value?: { toString: () => string }) => {\n if (value !== undefined && value !== null) {\n const decimal = Decimal.isDecimal(value) ? value : new Decimal(value.toString());\n return decimal.toFixed(places, rounding);\n }\n };\n\n return receiver;\n };\n }\n\n if (key === 'setToStringGetter') {\n schema.get = (value?: Types.Decimal128) => value?.toString();\n schema.leanDecimal128ToString = true;\n return receiver;\n }\n\n return Reflect.get(target, key, receiver);\n },\n },\n ) as Decimal128SchemaBuilder;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,EAAA,CAChE,QAAQ,QAAQ,QAAQ;GAE/C;GAEA,OAAO;EACX;EAGJ,IAAI,QAAQ,qBAAqB;GAC7B,OAAO,OAAO,UAA6B,OAAO,SAAS;GAC3D,OAAO,yBAAyB;GAChC,OAAO;EACX;EAEA,OAAO,QAAQ,IAAI,QAAQ,KAAK,QAAQ;CAC5C,EACJ,CACJ;AACJ"}
@@ -7,6 +7,12 @@ type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string
7
7
  interface BaseProps {
8
8
  type: typeof Schema.Types.Double;
9
9
  }
10
+ interface DoubleEnumValidator {
11
+ enumValues: (null | number | Types.Double)[];
12
+ message: string;
13
+ type: 'enum';
14
+ validator: (value: null | Types.Double | undefined) => boolean;
15
+ }
10
16
  interface DoubleLimitValidator {
11
17
  max?: number;
12
18
  message: string;
@@ -18,6 +24,12 @@ export interface DoubleSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
18
24
  default: <T extends ((this: any, doc: any) => D | null | undefined) | D | null | undefined, D extends Types.Double>(value: T) => ExtendSchemaBuilder<Merge<Props, {
19
25
  default: T;
20
26
  }>, ExtraOmitFields>;
27
+ enum: <T extends Readonlyable<(N | null)[]> | {
28
+ [path: string]: N | null;
29
+ } | {
30
+ message?: M;
31
+ values: Readonlyable<(N | null)[]>;
32
+ }, M extends string, N extends number | Types.Double>(value: T) => ExtendSchemaBuilder<Merge<Props, DoubleValidationSchema>, 'enum' | ExtraOmitFields>;
21
33
  immutable: ExtendSchemaBuilder<Merge<Props, {
22
34
  immutable: true;
23
35
  }>, ExtraOmitFields>;
@@ -41,7 +53,7 @@ export interface DoubleSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
41
53
  }>, ExtraOmitFields>;
42
54
  }
43
55
  interface DoubleValidationSchema {
44
- validate: DoubleLimitValidator[];
56
+ validate: (DoubleEnumValidator | DoubleLimitValidator)[];
45
57
  }
46
58
  export declare function doubleSchemaBuilder(): DoubleSchemaBuilder;
47
59
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"double.d.ts","names":[],"sources":["../../src/schema-builders/double.ts"],"mappings":";;;;KAYK,uBAAuB,MAAM;KAC7B,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN;EACA;EACA;EACA;EACA,YAAY,cAAc,MAAM;;iBAGnB,oBAAoB,cAAc,YAAY,WAAW;EACtE,UACI,YAAY,WAAW,aAAa,wBAAwB,sBAC5D,UAAU,MAAM,QAClB,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,WAAW,oBAAoB,MAAM;IAAS;MAAoB;EAClE,QAAQ,oBAAoB,iBAAiB,cAAc,OAAO,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;EACzB,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;UAGtD;EACN,UAAU;;wBAoCE,uBAuBP"}
1
+ {"version":3,"file":"double.d.ts","names":[],"sources":["../../src/schema-builders/double.ts"],"mappings":";;;;KAYK,uBAAuB,MAAM;KAC7B,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN,6BAA6B,MAAM;EACnC;EACA;EACA,YAAY,cAAc,MAAM;;UAG1B;EACN;EACA;EACA;EACA;EACA,YAAY,cAAc,MAAM;;iBAGnB,oBAAoB,cAAc,YAAY,WAAW;E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