@kikiutils/mongoose 9.0.2 → 9.0.4

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 (73) hide show
  1. package/dist/assertions.js.map +1 -1
  2. package/dist/plugins/assertions.js +4 -4
  3. package/dist/plugins/assertions.js.map +1 -1
  4. package/dist/plugins/lean-decimal128-to-string.d.ts +6 -2
  5. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -1
  6. package/dist/plugins/lean-decimal128-to-string.js +5 -4
  7. package/dist/plugins/lean-decimal128-to-string.js.map +1 -1
  8. package/dist/plugins/normalize.d.ts +3 -1
  9. package/dist/plugins/normalize.d.ts.map +1 -1
  10. package/dist/plugins/normalize.js +2 -1
  11. package/dist/plugins/normalize.js.map +1 -1
  12. package/dist/schema-builders/_internals.d.ts +18 -0
  13. package/dist/schema-builders/_internals.d.ts.map +1 -0
  14. package/dist/schema-builders/_internals.js +36 -0
  15. package/dist/schema-builders/_internals.js.map +1 -0
  16. package/dist/schema-builders/bigint.d.ts +5 -25
  17. package/dist/schema-builders/bigint.d.ts.map +1 -1
  18. package/dist/schema-builders/bigint.js +9 -19
  19. package/dist/schema-builders/bigint.js.map +1 -1
  20. package/dist/schema-builders/date.d.ts +4 -9
  21. package/dist/schema-builders/date.d.ts.map +1 -1
  22. package/dist/schema-builders/date.js.map +1 -1
  23. package/dist/schema-builders/decimal128.d.ts +6 -24
  24. package/dist/schema-builders/decimal128.d.ts.map +1 -1
  25. package/dist/schema-builders/decimal128.js +4 -6
  26. package/dist/schema-builders/decimal128.js.map +1 -1
  27. package/dist/schema-builders/double.d.ts +5 -25
  28. package/dist/schema-builders/double.d.ts.map +1 -1
  29. package/dist/schema-builders/double.js +9 -19
  30. package/dist/schema-builders/double.js.map +1 -1
  31. package/dist/schema-builders/int32.d.ts +5 -25
  32. package/dist/schema-builders/int32.d.ts.map +1 -1
  33. package/dist/schema-builders/int32.js +9 -19
  34. package/dist/schema-builders/int32.js.map +1 -1
  35. package/dist/schema-builders/number.d.ts +4 -9
  36. package/dist/schema-builders/number.d.ts.map +1 -1
  37. package/dist/schema-builders/number.js.map +1 -1
  38. package/dist/schema-builders/object-id.d.ts +2 -7
  39. package/dist/schema-builders/object-id.d.ts.map +1 -1
  40. package/dist/schema-builders/object-id.js.map +1 -1
  41. package/dist/schema-builders/ref.d.ts +2 -7
  42. package/dist/schema-builders/ref.d.ts.map +1 -1
  43. package/dist/schema-builders/ref.js.map +1 -1
  44. package/dist/schema-builders/string.d.ts +5 -10
  45. package/dist/schema-builders/string.d.ts.map +1 -1
  46. package/dist/schema-builders/string.js.map +1 -1
  47. package/dist/types/_internals.d.ts +22 -0
  48. package/dist/types/_internals.d.ts.map +1 -1
  49. package/dist/types/aggregate-paginate.d.ts +2 -1
  50. package/dist/types/aggregate-paginate.d.ts.map +1 -1
  51. package/dist/types/data.d.ts +3 -1
  52. package/dist/types/data.d.ts.map +1 -1
  53. package/dist/types/options.d.ts +6 -2
  54. package/dist/types/options.d.ts.map +1 -1
  55. package/package.json +23 -29
  56. package/src/assertions.ts +0 -1
  57. package/src/plugins/assertions.ts +4 -4
  58. package/src/plugins/lean-decimal128-to-string.ts +18 -7
  59. package/src/plugins/normalize.ts +5 -2
  60. package/src/schema-builders/_internals.ts +64 -0
  61. package/src/schema-builders/bigint.ts +33 -67
  62. package/src/schema-builders/date.ts +7 -7
  63. package/src/schema-builders/decimal128.ts +25 -41
  64. package/src/schema-builders/double.ts +35 -67
  65. package/src/schema-builders/int32.ts +33 -67
  66. package/src/schema-builders/number.ts +7 -7
  67. package/src/schema-builders/object-id.ts +2 -5
  68. package/src/schema-builders/ref.ts +2 -5
  69. package/src/schema-builders/string.ts +8 -8
  70. package/src/types/_internals.ts +26 -0
  71. package/src/types/aggregate-paginate.ts +2 -1
  72. package/src/types/data.ts +3 -1
  73. package/src/types/options.ts +6 -2
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type {\n Document,\n mongo,\n} from 'mongoose';\n\nexport async function assertMongooseUpdateSuccess<T extends Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n"],"mappings":";AAKA,eAAsB,4BAClB,eACA,wBAAwB,GAC1B;CACE,MAAM,eAAe,MAAM;CAC3B,IAAI,CAAC,aAAa,cAAc,MAAM,IAAI,MAAM,6BAA6B;CAC7E,IAAI,aAAa,gBAAgB,uBAE7B,MAAM,IAAI,MAAM,+BAA+B,sBAAsB,6BAA6B,aAAa,eAAe;AAEtI"}
1
+ {"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type {\n Document,\n mongo,\n} from 'mongoose';\n\nexport async function assertMongooseUpdateSuccess<T extends Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n"],"mappings":";AAKA,eAAsB,4BAClB,eACA,wBAAwB,GAC1B;CACE,MAAM,eAAe,MAAM;CAC3B,IAAI,CAAC,aAAa,cAAc,MAAM,IAAI,MAAM,6BAA6B;CAC7E,IAAI,aAAa,gBAAgB,uBAC7B,MAAM,IAAI,MAAM,+BAA+B,sBAAsB,6BAA6B,aAAa,eAAe;AAEtI"}
@@ -1,11 +1,11 @@
1
1
  import { assertMongooseUpdateSuccess } from "../assertions.js";
2
2
  // src/plugins/assertions.ts
3
3
  function mongooseAssertionsPlugin(schema) {
4
- schema.method("assertUpdateSuccess", function(update, options, expectedModifiedCount) {
5
- return assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);
4
+ schema.method("assertUpdateSuccess", async function(update, options, expectedModifiedCount) {
5
+ return await assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);
6
6
  });
7
- schema.static("assertUpdateSuccess", function(filter, update, options, expectedModifiedCount = 1) {
8
- return assertMongooseUpdateSuccess(expectedModifiedCount === 1 ? this.updateOne(filter, update, options) : this.updateMany(filter, update, options), expectedModifiedCount);
7
+ schema.static("assertUpdateSuccess", async function(filter, update, options, expectedModifiedCount = 1) {
8
+ return await assertMongooseUpdateSuccess(expectedModifiedCount === 1 ? this.updateOne(filter, update, options) : this.updateMany(filter, update, options), expectedModifiedCount);
9
9
  });
10
10
  }
11
11
  export { mongooseAssertionsPlugin };
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\n\ndeclare module 'mongoose' {\n interface Document<\n T = Types.ObjectId,\n TQueryHelpers = any,\n DocType = any,\n TVirtuals = Record<string, any>,\n // eslint-disable-next-line ts/no-empty-object-type\n TSchemaOptions = {},\n > {\n assertUpdateSuccess: (\n update?:\n | UpdateQuery<Document<T, TQueryHelpers, DocType, TVirtuals, TSchemaOptions>>\n | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n\n interface Model<\n TRawDocType,\n // eslint-disable-next-line ts/no-empty-object-type\n TQueryHelpers = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TInstanceMethods = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TVirtuals = {},\n // eslint-disable-next-line unused-imports/no-unused-vars\n THydratedDocumentType = HydratedDocument<TRawDocType, TInstanceMethods & TVirtuals, TQueryHelpers, TVirtuals>,\n // eslint-disable-next-line unused-imports/no-unused-vars\n TSchema = any,\n > {\n assertUpdateSuccess: (\n filter: QueryFilter<TRawDocType>,\n update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n}\n\nexport function mongooseAssertionsPlugin<S extends Schema>(schema: S) {\n schema.method(\n 'assertUpdateSuccess',\n function (\n update?: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) {\n return assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);\n },\n );\n\n schema.static(\n 'assertUpdateSuccess',\n function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n expectedModifiedCount: number = 1,\n ) {\n return assertMongooseUpdateSuccess(\n expectedModifiedCount === 1\n ? this.updateOne(filter, update, options)\n : this.updateMany(filter, update, options),\n expectedModifiedCount,\n );\n },\n );\n}\n"],"mappings":";;AAoDA,SAAgB,yBAA2C,QAAW;CAClE,OAAO,OACH,uBACA,SACI,QACA,SACA,uBACF;EACE,OAAO,4BAA4B,KAAK,UAAU,QAAQ,OAAO,GAAG,qBAAqB;CAC7F,CACJ;CAEA,OAAO,OACH,uBACA,SACI,QACA,QACA,SACA,wBAAgC,GAClC;EACE,OAAO,4BACH,0BAA0B,IACpB,KAAK,UAAU,QAAQ,QAAQ,OAAO,IACtC,KAAK,WAAW,QAAQ,QAAQ,OAAO,GAC7C,qBACJ;CACJ,CACJ;AACJ"}
1
+ {"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\n\ndeclare module 'mongoose' {\n interface Document<\n T = Types.ObjectId,\n TQueryHelpers = any,\n DocType = any,\n TVirtuals = Record<string, any>,\n // eslint-disable-next-line ts/no-empty-object-type\n TSchemaOptions = {},\n > {\n assertUpdateSuccess: (\n update?:\n | UpdateQuery<Document<T, TQueryHelpers, DocType, TVirtuals, TSchemaOptions>>\n | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n\n interface Model<\n TRawDocType,\n // eslint-disable-next-line ts/no-empty-object-type\n TQueryHelpers = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TInstanceMethods = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TVirtuals = {},\n // eslint-disable-next-line unused-imports/no-unused-vars\n THydratedDocumentType = HydratedDocument<TRawDocType, TInstanceMethods & TVirtuals, TQueryHelpers, TVirtuals>,\n // eslint-disable-next-line unused-imports/no-unused-vars\n TSchema = any,\n > {\n assertUpdateSuccess: (\n filter: QueryFilter<TRawDocType>,\n update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n}\n\nexport function mongooseAssertionsPlugin<S extends Schema>(schema: S) {\n schema.method(\n 'assertUpdateSuccess',\n async function (\n update?: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) {\n return await assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);\n },\n );\n\n schema.static(\n 'assertUpdateSuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n expectedModifiedCount: number = 1,\n ) {\n return await assertMongooseUpdateSuccess(\n expectedModifiedCount === 1\n ? this.updateOne(filter, update, options)\n : this.updateMany(filter, update, options),\n expectedModifiedCount,\n );\n },\n );\n}\n"],"mappings":";;AAoDA,SAAgB,yBAA2C,QAAW;CAClE,OAAO,OACH,uBACA,eACI,QACA,SACA,uBACF;EACE,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,OAAO,GAAG,qBAAqB;CACnG,CACJ;CAEA,OAAO,OACH,uBACA,eACI,QACA,QACA,SACA,wBAAgC,GAClC;EACE,OAAO,MAAM,4BACT,0BAA0B,IACpB,KAAK,UAAU,QAAQ,QAAQ,OAAO,IACtC,KAAK,WAAW,QAAQ,QAAQ,OAAO,GAC7C,qBACJ;CACJ,CACJ;AACJ"}
@@ -1,12 +1,16 @@
1
1
  import { Schema } from "mongoose";
2
2
  declare module 'mongoose' {
3
3
  interface LeanOptions {
4
- /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
4
+ /**
5
+ * Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting.
6
+ */
5
7
  decimal128ToString?: boolean;
6
8
  }
7
9
  }
8
10
  export interface MongooseLeanDecimal128ToStringPluginOptions {
9
- /** Whether marked fields are converted on lean queries by default. Defaults to true. */
11
+ /**
12
+ * Whether marked fields are converted on lean queries by default. Defaults to true.
13
+ */
10
14
  enabledByDefault?: boolean;
11
15
  }
12
16
  /**
@@ -1 +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"}
1
+ {"version":3,"file":"lean-decimal128-to-string.d.ts","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"mappings":";;YAac;;;;IAIN;;;iBAMS;;;;EAIb;;;;;;;;;;;;;wBAuFY,qCACZ,QAAQ,QACR,gBAAgB"}
@@ -1,10 +1,11 @@
1
+ import { objectHasOwn, objectKeys, objectValues } from "ts-extras";
1
2
  // src/plugins/lean-decimal128-to-string.ts
2
3
  const registeredSchemas = /* @__PURE__ */ new WeakSet();
3
4
  const isNonNullObject = (value) => value !== null && typeof value === "object";
4
5
  function convertDocument(schema, value) {
5
6
  if (!isNonNullObject(value)) return;
6
7
  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
+ (objectValues(schema.discriminators ?? {}).find((childSchema) => childSchema.get("discriminatorKey") === discriminatorKey && childSchema.discriminatorMapping?.value === value[discriminatorKey]) ?? schema).eachPath((path, schemaType) => {
8
9
  const pathSegments = path.split(".");
9
10
  if (pathSegments.includes("$*")) return;
10
11
  convertPath(value, pathSegments, schemaType);
@@ -17,7 +18,7 @@ function convertPath(value, pathSegments, schemaType) {
17
18
  }
18
19
  if (!isNonNullObject(value)) return;
19
20
  const [key, ...remainingPathSegments] = pathSegments;
20
- if (key === void 0 || !Object.hasOwn(value, key)) return;
21
+ if (key === void 0 || !objectHasOwn(value, key)) return;
21
22
  if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
22
23
  else value[key] = convertValue(value[key], schemaType);
23
24
  }
@@ -25,12 +26,12 @@ function convertValue(value, schemaType) {
25
26
  if (value === null || value === void 0) return value;
26
27
  const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
27
28
  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
+ for (let i = 0; i < value.length; i++) if (objectHasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
29
30
  return value;
30
31
  }
31
32
  if (embeddedSchemaType && schemaType.instance === "Map") {
32
33
  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
+ else if (isNonNullObject(value)) for (const key of objectKeys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
34
35
  return value;
35
36
  }
36
37
  if (schemaType.schema) {
@@ -1 +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,kBAAkB,MAAM,oBACnD,YAAuE,sBAAsB,UAC7F,MAAM,iBAGyB,KAAK,OAAA,CAC/B,UAAU,MAAM,eAAe;EAE1C,MAAM,eAAe,KAAK,MAAM,GAAG;EACnC,IAAI,aAAa,SAAS,IAAI,GAAG;EACjC,YAAY,OAAO,cAAc,UAAU;CAC/C,CAAC;AACL;AAEA,SAAS,YAAY,OAAgB,cAAwB,YAAwB;CACjF,IAAI,MAAM,QAAQ,KAAK,GAAG;EACtB,MAAM,SAA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;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"}
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 Types,\n} from 'mongoose';\nimport {\n objectHasOwn,\n objectKeys,\n objectValues,\n} from 'ts-extras';\n\ndeclare module 'mongoose' {\n interface LeanOptions {\n /**\n * Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting.\n */\n decimal128ToString?: boolean;\n }\n}\n\ntype QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };\n\nexport interface MongooseLeanDecimal128ToStringPluginOptions {\n /**\n * Whether marked fields are converted on lean queries by default. Defaults to true.\n */\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 = objectValues(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 || !objectHasOwn(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 (objectHasOwn(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 objectKeys(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 as Types.Decimal128).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\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 convert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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"}
@@ -9,7 +9,9 @@ export interface MongooseNormalizePluginOptions {
9
9
  * @defaultValue `true`.
10
10
  */
11
11
  convertIdField?: boolean;
12
- /** Register normalization on child schemas too. Defaults to true. */
12
+ /**
13
+ * Register normalization on child schemas too. Defaults to true.
14
+ */
13
15
  recursive?: boolean;
14
16
  /**
15
17
  * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
@@ -1 +1 @@
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
+ {"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";iBASiB;;;;;;;;;EASb;;;;EAKA;;;;;;;;;EAUA;;;;;;;;;;;;;;;;;;;wBAyBY,wBAAwB,UAAU,QAC9C,QAAQ,GACR,gBAAgB"}
@@ -1,4 +1,5 @@
1
1
  import { Types } from "mongoose";
2
+ import { objectEntries } from "ts-extras";
2
3
  import { get, set, unset } from "es-toolkit/compat";
3
4
  // src/plugins/normalize.ts
4
5
  const registeredSchemas = /* @__PURE__ */ new WeakSet();
@@ -24,7 +25,7 @@ function mongooseNormalizePlugin(schema, pluginOptions) {
24
25
  registeredSchemas.add(schema);
25
26
  const decimalPaths = [];
26
27
  const privatePaths = [];
27
- for (const [path, schemaType] of Object.entries(schema.paths)) if (schemaType?.options?.private) privatePaths.push(path);
28
+ for (const [path, schemaType] of objectEntries(schema.paths)) if (schemaType?.options?.private) privatePaths.push(path);
28
29
  else if (schemaType?.instance === "Decimal128") decimalPaths.push(path);
29
30
  const toJson = schema.get("toJSON");
30
31
  const toJsonTransform = toJson?.transform;
@@ -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 /** 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"}
1
+ {"version":3,"file":"normalize.js","names":["unsetProp","getProp","setProp"],"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';\nimport { objectEntries } from 'ts-extras';\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 * Register normalization on child schemas too. Defaults to true.\n */\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 objectEntries(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":";;;;AAqCA,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,cAAc,OAAO,KAAK,GACvD,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,cAAcA,MAAU,WAAW,IAAI;GAG1D,KAAK,MAAM,QAAQ,cAAc;IAC7B,MAAM,QAAQC,IAAQ,WAAW,IAAI;IACrC,IAAI,OAAOC,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"}
@@ -0,0 +1,18 @@
1
+ import { EnumInput, ValidationSchema, ValueWithMessage } from "../types/_internals.js";
2
+ export declare const defaultEnumValidateMessage = "Path `{PATH}` ({VALUE}) is not a valid enum value.";
3
+ export declare const defaultLimitValidateMessages: {
4
+ max: string;
5
+ min: string;
6
+ };
7
+ export declare function hasSchemaValidator(schema: Partial<ValidationSchema<{
8
+ type: string;
9
+ }>>, type: string): boolean;
10
+ export declare function normalizeEnumValues<T>(value: EnumInput<T>): {
11
+ enumValues: T[];
12
+ message?: string;
13
+ };
14
+ export declare function normalizeValueWithMessage<T>(value: ValueWithMessage<T>): readonly [T, string | undefined];
15
+ export declare function setSchemaValidator<T extends {
16
+ type: string;
17
+ }>(schema: Partial<ValidationSchema<T>>, validator: T): void;
18
+ //# sourceMappingURL=_internals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_internals.d.ts","names":[],"sources":["../../src/schema-builders/_internals.ts"],"mappings":";qBAWa;qBACA;;;;wBAMG,mBAAmB,QAAQ,QAAQ;EAAmB;KAAkB;wBAgBxE,oBAAoB,GAAG,OAAO,UAAU;EAAO,YAAY;EAAK;;wBAYhE,0BAA0B,GAAG,OAAO,iBAAiB,eAAe;wBASpE,mBAAmB;EAAY;GAC3C,QAAQ,QAAQ,iBAAiB,KACjC,WAAW"}
@@ -0,0 +1,36 @@
1
+ import { objectValues } from "ts-extras";
2
+ // src/schema-builders/_internals.ts
3
+ const defaultEnumValidateMessage = "Path `{PATH}` ({VALUE}) is not a valid enum value.";
4
+ const defaultLimitValidateMessages = {
5
+ max: "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).",
6
+ min: "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN})."
7
+ };
8
+ function hasSchemaValidator(schema, type) {
9
+ return schema.validate?.some((validator) => validator.type === type) ?? false;
10
+ }
11
+ function isEnumArray(value) {
12
+ return Array.isArray(value);
13
+ }
14
+ function isEnumOptions(value) {
15
+ return "values" in value && Array.isArray(value.values);
16
+ }
17
+ function isValueMessageTuple(value) {
18
+ return Array.isArray(value);
19
+ }
20
+ function normalizeEnumValues(value) {
21
+ if (isEnumArray(value)) return { enumValues: [...value] };
22
+ if (isEnumOptions(value)) return {
23
+ enumValues: [...value.values],
24
+ message: typeof value.message === "string" ? value.message : void 0
25
+ };
26
+ return { enumValues: objectValues(value) };
27
+ }
28
+ function normalizeValueWithMessage(value) {
29
+ return isValueMessageTuple(value) ? value : [value, void 0];
30
+ }
31
+ function setSchemaValidator(schema, validator) {
32
+ schema.validate = [...(schema.validate ?? []).filter(({ type }) => type !== validator.type), validator];
33
+ }
34
+ export { defaultEnumValidateMessage, defaultLimitValidateMessages, hasSchemaValidator, normalizeEnumValues, normalizeValueWithMessage, setSchemaValidator };
35
+
36
+ //# sourceMappingURL=_internals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_internals.js","names":[],"sources":["../../src/schema-builders/_internals.ts"],"sourcesContent":["import { objectValues } from 'ts-extras';\n\nimport type {\n EnumInput,\n EnumOptions,\n Readonlyable,\n ValidationSchema,\n ValueWithMessage,\n} from '../types/_internals';\n\n// Constants/Variables\nexport const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';\nexport const defaultLimitValidateMessages = {\n max: 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).',\n min: 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).',\n};\n\n// Functions\nexport function hasSchemaValidator(schema: Partial<ValidationSchema<{ type: string }>>, type: string): boolean {\n return schema.validate?.some((validator) => validator.type === type) ?? false;\n}\n\nfunction isEnumArray<T>(value: EnumInput<T>): value is readonly T[] {\n return Array.isArray(value);\n}\n\nfunction isEnumOptions<T>(value: EnumOptions<T> | Record<string, T>): value is EnumOptions<T> {\n return 'values' in value && Array.isArray(value.values);\n}\n\nfunction isValueMessageTuple<T>(value: ValueWithMessage<T>): value is Readonlyable<[T, string]> {\n return Array.isArray(value);\n}\n\nexport function normalizeEnumValues<T>(value: EnumInput<T>): { enumValues: T[]; message?: string } {\n if (isEnumArray(value)) return { enumValues: [...value] };\n if (isEnumOptions(value)) {\n return {\n enumValues: [...value.values],\n message: typeof value.message === 'string' ? value.message : undefined,\n };\n }\n\n return { enumValues: objectValues(value) };\n}\n\nexport function normalizeValueWithMessage<T>(value: ValueWithMessage<T>): readonly [T, string | undefined] {\n return isValueMessageTuple(value)\n ? value\n : [\n value,\n undefined,\n ];\n}\n\nexport function setSchemaValidator<T extends { type: string }>(\n schema: Partial<ValidationSchema<T>>,\n validator: T,\n): void {\n schema.validate = [\n ...(schema.validate ?? []).filter(({ type }) => type !== validator.type),\n validator,\n ];\n}\n"],"mappings":";;AAWA,MAAa,6BAA6B;AAC1C,MAAa,+BAA+B;CACxC,KAAK;CACL,KAAK;AACT;AAGA,SAAgB,mBAAmB,QAAqD,MAAuB;CAC3G,OAAO,OAAO,UAAU,MAAM,cAAc,UAAU,SAAS,IAAI,KAAK;AAC5E;AAEA,SAAS,YAAe,OAA4C;CAChE,OAAO,MAAM,QAAQ,KAAK;AAC9B;AAEA,SAAS,cAAiB,OAAoE;CAC1F,OAAO,YAAY,SAAS,MAAM,QAAQ,MAAM,MAAM;AAC1D;AAEA,SAAS,oBAAuB,OAAgE;CAC5F,OAAO,MAAM,QAAQ,KAAK;AAC9B;AAEA,SAAgB,oBAAuB,OAA4D;CAC/F,IAAI,YAAY,KAAK,GAAG,OAAO,EAAE,YAAY,CAAC,GAAG,KAAK,EAAE;CACxD,IAAI,cAAc,KAAK,GACnB,OAAO;EACH,YAAY,CAAC,GAAG,MAAM,MAAM;EAC5B,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU,KAAA;CACjE;CAGJ,OAAO,EAAE,YAAY,aAAa,KAAK,EAAE;AAC7C;AAEA,SAAgB,0BAA6B,OAA8D;CACvG,OAAO,oBAAoB,KAAK,IAC1B,QACA,CACE,OACA,KAAA,CACJ;AACR;AAEA,SAAgB,mBACZ,QACA,WACI;CACJ,OAAO,WAAW,CACd,IAAI,OAAO,YAAY,CAAC,EAAA,CAAG,QAAQ,EAAE,WAAW,SAAS,UAAU,IAAI,GACvE,SACJ;AACJ"}
@@ -1,42 +1,25 @@
1
- import { Readonlyable } from "../types/_internals.js";
1
+ import { EnumInput, EnumValidator, LimitValidator, ValidationSchema, ValueWithMessage } from "../types/_internals.js";
2
2
  import { DefaultType, IndexDirection, IndexOptions, Schema } from "mongoose";
3
3
  import { Merge } from "type-fest";
4
4
  type BigIntLimit = bigint;
5
+ type BigIntValidationSchema = ValidationSchema<EnumValidator<bigint> | LimitValidator<bigint>>;
5
6
  type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string> = Omit<BigIntSchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;
6
7
  interface BaseProps {
7
8
  type: typeof Schema.Types.BigInt;
8
9
  }
9
- interface BigIntEnumValidator {
10
- enumValues: (bigint | null)[];
11
- message: string;
12
- type: 'enum';
13
- validator: (value: bigint | null | undefined) => boolean;
14
- }
15
- interface BigIntLimitValidator {
16
- max?: bigint;
17
- message: string;
18
- min?: bigint;
19
- type: 'max' | 'min';
20
- validator: (value: bigint | null | undefined) => boolean;
21
- }
22
10
  export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
23
11
  default: <T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined, D extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, {
24
12
  default: T;
25
13
  }>, ExtraOmitFields>;
26
- enum: <T extends Readonlyable<(N | null)[]> | {
27
- [path: string]: N | null;
28
- } | {
29
- message?: M;
30
- values: Readonlyable<(N | null)[]>;
31
- }, M extends string, N extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'enum' | ExtraOmitFields>;
14
+ enum: <T extends EnumInput<N | null, M>, M extends string, N extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'enum' | ExtraOmitFields>;
32
15
  immutable: ExtendSchemaBuilder<Merge<Props, {
33
16
  immutable: true;
34
17
  }>, ExtraOmitFields>;
35
18
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<Merge<Props, {
36
19
  index: T;
37
20
  }>, ExtraOmitFields>;
38
- max: <T extends L | Readonlyable<[L, S]>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'max' | ExtraOmitFields>;
39
- min: <T extends L | Readonlyable<[L, S]>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'min' | ExtraOmitFields>;
21
+ max: <T extends ValueWithMessage<L, S>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'max' | ExtraOmitFields>;
22
+ min: <T extends ValueWithMessage<L, S>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'min' | ExtraOmitFields>;
40
23
  nonRequired: Props;
41
24
  private: ExtendSchemaBuilder<Merge<Props, {
42
25
  private: true;
@@ -51,9 +34,6 @@ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
51
34
  unique: true;
52
35
  }>, ExtraOmitFields>;
53
36
  }
54
- interface BigIntValidationSchema {
55
- validate: (BigIntEnumValidator | BigIntLimitValidator)[];
56
- }
57
37
  export declare function bigintSchemaBuilder(): BigIntSchemaBuilder;
58
38
  export {};
59
39
  //# sourceMappingURL=bigint.d.ts.map
@@ -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,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
+ {"version":3,"file":"bigint.d.ts","names":[],"sources":["../../src/schema-builders/bigint.ts"],"mappings":";;;KA0BK;KACA,yBAAyB,iBAAiB,wBAAwB;KAElE,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;iBAGb,oBAAoB,cAAc,YAAY,WAAW;EACtE,UACI,YAAY,WAAW,aAAa,YAAY,yBAAyB,YAAY,uBACrF,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,OACI,UAAU,UAAU,UAAU,IAC9B,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,iBAAiB,GAAG,IAC9B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,MACI,UAAU,iBAAiB,GAAG,IAC9B,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;;wBAMhD,uBAyCP"}
@@ -1,49 +1,39 @@
1
+ import { defaultLimitValidateMessages, hasSchemaValidator, normalizeEnumValues, normalizeValueWithMessage, setSchemaValidator } from "./_internals.js";
1
2
  import { createBaseSchemaBuilderFactory } from "./base.js";
2
3
  import { Schema } from "mongoose";
3
4
  // src/schema-builders/bigint.ts
4
- const defaultEnumValidateMessage = "Path `{PATH}` ({VALUE}) is not a valid enum value.";
5
- const defaultMinValidateMessage = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";
6
- const defaultMaxValidateMessage = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";
7
5
  const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);
8
6
  function bigintSchemaBuilder() {
9
7
  const schema = {};
10
8
  const baseBuilder = baseBuilderFactory(schema);
11
9
  return new Proxy(baseBuilder, { get(target, key, receiver) {
12
10
  if (key === "enum") {
13
- if (schema.validate?.some(({ type }) => type === "enum")) throw new Error("Duplicate schema attribute: enum");
11
+ if (hasSchemaValidator(schema, "enum")) throw new Error("Duplicate schema attribute: enum");
14
12
  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);
13
+ const { enumValues, message } = normalizeEnumValues(value);
22
14
  const allowedValues = new Set(enumValues);
23
- const validator = {
15
+ setSchemaValidator(schema, {
24
16
  enumValues,
25
- message: message ?? defaultEnumValidateMessage,
17
+ message: message ?? "Path `{PATH}` ({VALUE}) is not a valid enum value.",
26
18
  type: "enum",
27
19
  validator: (value) => value === null || value === void 0 || allowedValues.has(value)
28
- };
29
- schema.validate = [...schema.validate ?? [], validator];
20
+ });
30
21
  return receiver;
31
22
  };
32
23
  }
33
24
  if (key === "max" || key === "min") return (value) => {
34
25
  const validator = createLimitValidator(key, value);
35
- const validators = Array.isArray(schema.validate) ? schema.validate : [];
36
- schema.validate = [...validators.filter(({ type }) => type !== key), validator];
26
+ setSchemaValidator(schema, validator);
37
27
  return receiver;
38
28
  };
39
29
  return Reflect.get(target, key, receiver);
40
30
  } });
41
31
  }
42
32
  function createLimitValidator(type, value) {
43
- const [limit, message] = Array.isArray(value) ? value : [value, void 0];
33
+ const [limit, message] = normalizeValueWithMessage(value);
44
34
  if (typeof limit !== "bigint") throw new TypeError(`BigInt ${type} limit must be a bigint`);
45
35
  return {
46
- message: message ?? (type === "min" ? defaultMinValidateMessage : defaultMaxValidateMessage),
36
+ message: message ?? defaultLimitValidateMessages[type],
47
37
  [type]: limit,
48
38
  type,
49
39
  validator: (value) => {
@@ -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 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' ? value >= limit : value <= limit;\n },\n };\n}\n"],"mappings":";;;AAiGA,MAAM,6BAA6B;AACnC,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,MAC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,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 {\n EnumInput,\n EnumValidator,\n LimitValidator,\n ValidationSchema,\n ValueWithMessage,\n} from '../types/_internals';\n\nimport {\n defaultEnumValidateMessage,\n defaultLimitValidateMessages,\n hasSchemaValidator,\n normalizeEnumValues,\n normalizeValueWithMessage,\n setSchemaValidator,\n} from './_internals';\nimport { createBaseSchemaBuilderFactory } from './base';\n\ntype BigIntLimit = bigint;\ntype BigIntValidationSchema = ValidationSchema<EnumValidator<bigint> | LimitValidator<bigint>>;\n\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\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 EnumInput<N | null, M>,\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 ValueWithMessage<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 ValueWithMessage<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\n// Functions\nconst baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);\n\nexport function bigintSchemaBuilder() {\n const schema: Partial<BigIntValidationSchema> & 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 (hasSchemaValidator(schema, 'enum')) {\n throw new Error('Duplicate schema attribute: enum');\n }\n\n return (value: EnumInput<bigint | null>) => {\n const { enumValues, message } = normalizeEnumValues(value);\n\n const allowedValues = new Set(enumValues);\n const validator: EnumValidator<bigint> = {\n enumValues,\n message: message ?? defaultEnumValidateMessage,\n type: 'enum',\n validator: (value) => value === null || value === undefined || allowedValues.has(value),\n };\n\n setSchemaValidator(schema, validator);\n\n return receiver;\n };\n }\n\n if (key === 'max' || key === 'min') {\n return (value: ValueWithMessage<BigIntLimit>) => {\n const validator = createLimitValidator(key, value);\n setSchemaValidator(schema, validator);\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: ValueWithMessage<BigIntLimit>,\n): LimitValidator<bigint> {\n const [limit, message] = normalizeValueWithMessage(value);\n\n if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);\n\n return {\n message: message ?? defaultLimitValidateMessages[type],\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":";;;;AA2FA,MAAM,qBAAqB,+BAA+B,OAAO,MAAM,MAAM;AAE7E,SAAgB,sBAAsB;CAClC,MAAM,SAAgE,CAAC;CACvE,MAAM,cAAc,mBAAmB,MAAM;CAC7C,OAAO,IAAI,MACP,aACA,EACI,IAAI,QAAQ,KAAK,UAAU;EACvB,IAAI,QAAQ,QAAQ;GAChB,IAAI,mBAAmB,QAAQ,MAAM,GACjC,MAAM,IAAI,MAAM,kCAAkC;GAGtD,QAAQ,UAAoC;IACxC,MAAM,EAAE,YAAY,YAAY,oBAAoB,KAAK;IAEzD,MAAM,gBAAgB,IAAI,IAAI,UAAU;IAQxC,mBAAmB,QAAQ;KANvB;KACA,SAAS,WAAA;KACT,MAAM;KACN,YAAY,UAAU,UAAU,QAAQ,UAAU,KAAA,KAAa,cAAc,IAAI,KAAK;IAGvD,CAAC;IAEpC,OAAO;GACX;EACJ;EAEA,IAAI,QAAQ,SAAS,QAAQ,OACzB,QAAQ,UAAyC;GAC7C,MAAM,YAAY,qBAAqB,KAAK,KAAK;GACjD,mBAAmB,QAAQ,SAAS;GAEpC,OAAO;EACX;EAGJ,OAAO,QAAQ,IAAI,QAAQ,KAAK,QAAQ;CAC5C,EACJ,CACJ;AACJ;AAEA,SAAS,qBACL,MACA,OACsB;CACtB,MAAM,CAAC,OAAO,WAAW,0BAA0B,KAAK;CAExD,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,UAAU,UAAU,KAAK,wBAAwB;CAE1F,OAAO;EACH,SAAS,WAAW,6BAA6B;GAChD,OAAO;EACR;EACA,YAAY,UAAU;GAClB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAElD,OAAO,SAAS,QAAQ,SAAS,QAAQ,SAAS;EACtD;CACJ;AACJ"}
@@ -1,4 +1,4 @@
1
- import { Readonlyable } from "../types/_internals.js";
1
+ import { EnumInput, ValueWithMessage } from "../types/_internals.js";
2
2
  import { DateSchemaDefinition, DefaultType, IndexDirection, IndexOptions } from "mongoose";
3
3
  import { Merge } from "type-fest";
4
4
  type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string> = Omit<DateSchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;
@@ -13,12 +13,7 @@ export interface DateSchemaBuilder<Props extends {
13
13
  default: <T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null, D extends NativeDate>(value: T) => ExtendSchemaBuilder<Merge<Props, {
14
14
  default: T;
15
15
  }>, ExtraOmitFields>;
16
- enum: <T extends Readonlyable<(D | null)[]> | {
17
- [path: string]: D | null;
18
- } | {
19
- message?: M;
20
- values: Readonlyable<(D | null)[]>;
21
- }, D extends NativeDate, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
16
+ enum: <T extends EnumInput<D | null, M>, D extends NativeDate, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
22
17
  enum: T;
23
18
  }>, ExtraOmitFields>;
24
19
  immutable: ExtendSchemaBuilder<Merge<Props, {
@@ -27,10 +22,10 @@ export interface DateSchemaBuilder<Props extends {
27
22
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<Merge<Props, {
28
23
  index: T;
29
24
  }>, ExtraOmitFields>;
30
- max: <T extends D | Readonlyable<[D, S]>, D extends NativeDate, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
25
+ max: <T extends ValueWithMessage<D, S>, D extends NativeDate, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
31
26
  max: T;
32
27
  }>, ExtraOmitFields>;
33
- min: <T extends D | Readonlyable<[D, S]>, D extends NativeDate, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
28
+ min: <T extends ValueWithMessage<D, S>, D extends NativeDate, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
34
29
  min: T;
35
30
  }>, ExtraOmitFields>;
36
31
  nonRequired: Props;
@@ -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,cAAc;KACX,eAAe;;IAChB,UAAU;IAAG,QAAQ,cAAc;KACvC,UAAU,YACV,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,KAC/B,UAAU,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
+ {"version":3,"file":"date.d.ts","names":[],"sources":["../../src/schema-builders/date.ts"],"mappings":";;;KAeK,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,UAAU,UAAU,UAAU,IAC9B,UAAU,YACV,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,iBAAiB,GAAG,IAC9B,UAAU,YACV,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,KAAK;MACpB;EAGJ,MACI,UAAU,iBAAiB,GAAG,IAC9B,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;EAnD6B,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<(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"}
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 {\n EnumInput,\n ValueWithMessage,\n} 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 EnumInput<D | null, M>,\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 ValueWithMessage<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 ValueWithMessage<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,35 +1,20 @@
1
- import { Readonlyable } from "../types/_internals.js";
1
+ import { EnumInput, LimitValidator, ValidationSchema, ValueWithMessage } from "../types/_internals.js";
2
2
  import { DefaultType, IndexDirection, IndexOptions, Schema, Types } from "mongoose";
3
3
  import { Decimal } from "decimal.js";
4
4
  import { Merge } from "type-fest";
5
5
  type Decimal128Limit = Decimal.Value | Types.Decimal128 | {
6
6
  toString: () => string;
7
7
  };
8
+ type Decimal128ValidationSchema = ValidationSchema<LimitValidator<string, Types.Decimal128>>;
8
9
  type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string> = Omit<Decimal128SchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;
9
10
  interface BaseProps {
10
11
  type: typeof Schema.Types.Decimal128;
11
12
  }
12
- interface Decimal128LimitValidator {
13
- max?: string;
14
- message: string;
15
- min?: string;
16
- type: 'max' | 'min';
17
- validator: (value: null | Types.Decimal128 | undefined) => boolean;
18
- }
19
- export interface Decimal128SchemaBuilder<Props extends {
20
- type: typeof Schema.Types.Decimal128;
21
- } = {
22
- type: typeof Schema.Types.Decimal128;
23
- }, ExtraOmitFields extends string = never> {
13
+ export interface Decimal128SchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
24
14
  default: <T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null, D extends Types.Decimal128>(value: T) => ExtendSchemaBuilder<Merge<Props, {
25
15
  default: T;
26
16
  }>, ExtraOmitFields>;
27
- enum: <T extends Readonlyable<(D | null)[]> | {
28
- [path: string]: D | null;
29
- } | {
30
- message?: M;
31
- values: Readonlyable<(D | null)[]>;
32
- }, D extends Types.Decimal128, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
17
+ enum: <T extends EnumInput<D | null, M>, D extends Types.Decimal128, M extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, {
33
18
  enum: T;
34
19
  }>, ExtraOmitFields>;
35
20
  immutable: ExtendSchemaBuilder<Merge<Props, {
@@ -38,8 +23,8 @@ export interface Decimal128SchemaBuilder<Props extends {
38
23
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<Merge<Props, {
39
24
  index: T;
40
25
  }>, ExtraOmitFields>;
41
- max: <T extends D | Readonlyable<[D, S]>, D extends Decimal128Limit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, Decimal128ValidationSchema>, 'max' | ExtraOmitFields>;
42
- min: <T extends D | Readonlyable<[D, S]>, D extends Decimal128Limit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, Decimal128ValidationSchema>, 'min' | ExtraOmitFields>;
26
+ max: <T extends ValueWithMessage<D, S>, D extends Decimal128Limit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, Decimal128ValidationSchema>, 'max' | ExtraOmitFields>;
27
+ min: <T extends ValueWithMessage<D, S>, D extends Decimal128Limit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, Decimal128ValidationSchema>, 'min' | ExtraOmitFields>;
43
28
  nonRequired: Props;
44
29
  private: ExtendSchemaBuilder<Merge<Props, {
45
30
  private: true;
@@ -80,9 +65,6 @@ export interface Decimal128SchemaBuilder<Props extends {
80
65
  unique: true;
81
66
  }>, ExtraOmitFields>;
82
67
  }
83
- interface Decimal128ValidationSchema {
84
- validate: Decimal128LimitValidator[];
85
- }
86
68
  interface ToStringGetterSchema {
87
69
  get: (value?: Types.Decimal128) => string | undefined;
88
70
  leanDecimal128ToString: true;
@@ -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,Y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