@kikiutils/mongoose 9.0.4 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/README.md +13 -25
  2. package/dist/_internals.d.ts +10 -1
  3. package/dist/_internals.d.ts.map +1 -1
  4. package/dist/_internals.js +20 -1
  5. package/dist/_internals.js.map +1 -1
  6. package/dist/assertions.d.ts +5 -2
  7. package/dist/assertions.d.ts.map +1 -1
  8. package/dist/assertions.js +10 -4
  9. package/dist/assertions.js.map +1 -1
  10. package/dist/builders.d.ts +9 -4
  11. package/dist/builders.d.ts.map +1 -1
  12. package/dist/builders.js +10 -10
  13. package/dist/builders.js.map +1 -1
  14. package/dist/connection.d.ts +3 -0
  15. package/dist/connection.d.ts.map +1 -1
  16. package/dist/connection.js +8 -2
  17. package/dist/connection.js.map +1 -1
  18. package/dist/documents.d.ts +8 -0
  19. package/dist/documents.d.ts.map +1 -0
  20. package/dist/documents.js +10 -0
  21. package/dist/documents.js.map +1 -0
  22. package/dist/errors/duplicate-key.d.ts +9 -0
  23. package/dist/errors/duplicate-key.d.ts.map +1 -0
  24. package/dist/errors/duplicate-key.js +15 -0
  25. package/dist/errors/duplicate-key.js.map +1 -0
  26. package/dist/errors/mongoose-update-conflict-error.d.ts +4 -0
  27. package/dist/errors/mongoose-update-conflict-error.d.ts.map +1 -0
  28. package/dist/errors/mongoose-update-conflict-error.js +7 -0
  29. package/dist/errors/mongoose-update-conflict-error.js.map +1 -0
  30. package/dist/options.d.ts +15 -1
  31. package/dist/options.d.ts.map +1 -1
  32. package/dist/options.js +19 -2
  33. package/dist/options.js.map +1 -1
  34. package/dist/plugins/assertions.d.ts +30 -9
  35. package/dist/plugins/assertions.d.ts.map +1 -1
  36. package/dist/plugins/assertions.js +32 -4
  37. package/dist/plugins/assertions.js.map +1 -1
  38. package/dist/plugins/lean-decimal128-to-string.d.ts +3 -15
  39. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -1
  40. package/dist/plugins/lean-decimal128-to-string.js +30 -23
  41. package/dist/plugins/lean-decimal128-to-string.js.map +1 -1
  42. package/dist/plugins/normalize.d.ts +3 -40
  43. package/dist/plugins/normalize.d.ts.map +1 -1
  44. package/dist/plugins/normalize.js +98 -44
  45. package/dist/plugins/normalize.js.map +1 -1
  46. package/dist/schema-builders/_internals/array.d.ts +9 -0
  47. package/dist/schema-builders/_internals/array.d.ts.map +1 -0
  48. package/dist/schema-builders/_internals/array.js +12 -0
  49. package/dist/schema-builders/_internals/array.js.map +1 -0
  50. package/dist/schema-builders/_internals/boolean.d.ts +8 -0
  51. package/dist/schema-builders/_internals/boolean.d.ts.map +1 -0
  52. package/dist/schema-builders/_internals/boolean.js +9 -0
  53. package/dist/schema-builders/_internals/boolean.js.map +1 -0
  54. package/dist/schema-builders/_internals/date.d.ts +8 -0
  55. package/dist/schema-builders/_internals/date.d.ts.map +1 -0
  56. package/dist/schema-builders/_internals/date.js +9 -0
  57. package/dist/schema-builders/_internals/date.js.map +1 -0
  58. package/dist/schema-builders/_internals/decimal128.d.ts +36 -0
  59. package/dist/schema-builders/_internals/decimal128.d.ts.map +1 -0
  60. package/dist/schema-builders/_internals/decimal128.js +38 -0
  61. package/dist/schema-builders/_internals/decimal128.js.map +1 -0
  62. package/dist/schema-builders/_internals/int32.d.ts +21 -0
  63. package/dist/schema-builders/_internals/int32.d.ts.map +1 -0
  64. package/dist/schema-builders/_internals/int32.js +29 -0
  65. package/dist/schema-builders/_internals/int32.js.map +1 -0
  66. package/dist/schema-builders/_internals/mixed.d.ts +9 -0
  67. package/dist/schema-builders/_internals/mixed.d.ts.map +1 -0
  68. package/dist/schema-builders/_internals/mixed.js +10 -0
  69. package/dist/schema-builders/_internals/mixed.js.map +1 -0
  70. package/dist/schema-builders/_internals/number.d.ts +21 -0
  71. package/dist/schema-builders/_internals/number.d.ts.map +1 -0
  72. package/dist/schema-builders/_internals/number.js +20 -0
  73. package/dist/schema-builders/_internals/number.js.map +1 -0
  74. package/dist/schema-builders/_internals/object-id.d.ts +9 -0
  75. package/dist/schema-builders/_internals/object-id.d.ts.map +1 -0
  76. package/dist/schema-builders/_internals/object-id.js +10 -0
  77. package/dist/schema-builders/_internals/object-id.js.map +1 -0
  78. package/dist/schema-builders/_internals/ref.d.ts +8 -0
  79. package/dist/schema-builders/_internals/ref.d.ts.map +1 -0
  80. package/dist/schema-builders/_internals/ref.js +13 -0
  81. package/dist/schema-builders/_internals/ref.js.map +1 -0
  82. package/dist/schema-builders/_internals/shared.d.ts +104 -0
  83. package/dist/schema-builders/_internals/shared.d.ts.map +1 -0
  84. package/dist/schema-builders/_internals/shared.js +128 -0
  85. package/dist/schema-builders/_internals/shared.js.map +1 -0
  86. package/dist/schema-builders/_internals/string.d.ts +37 -0
  87. package/dist/schema-builders/_internals/string.d.ts.map +1 -0
  88. package/dist/schema-builders/_internals/string.js +39 -0
  89. package/dist/schema-builders/_internals/string.js.map +1 -0
  90. package/dist/schema-builders/index.d.ts +12 -13
  91. package/dist/schema-builders/index.js +11 -13
  92. package/dist/transaction.d.ts +10 -0
  93. package/dist/transaction.d.ts.map +1 -0
  94. package/dist/transaction.js +9 -0
  95. package/dist/transaction.js.map +1 -0
  96. package/dist/types/data.d.ts +3 -5
  97. package/dist/types/data.d.ts.map +1 -1
  98. package/dist/types/index.d.ts +16 -12
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/paginate.d.ts +4 -19
  101. package/dist/types/paginate.d.ts.map +1 -1
  102. package/package.json +19 -21
  103. package/src/_internals.ts +31 -1
  104. package/src/assertions.ts +20 -11
  105. package/src/builders.ts +26 -18
  106. package/src/connection.ts +8 -2
  107. package/src/documents.ts +12 -0
  108. package/src/errors/duplicate-key.ts +14 -0
  109. package/src/errors/mongoose-update-conflict-error.ts +3 -0
  110. package/src/options.ts +31 -1
  111. package/src/plugins/assertions.ts +117 -49
  112. package/src/plugins/lean-decimal128-to-string.ts +47 -41
  113. package/src/plugins/normalize.ts +169 -99
  114. package/src/schema-builders/_internals/array.ts +15 -0
  115. package/src/schema-builders/_internals/boolean.ts +10 -0
  116. package/src/schema-builders/_internals/date.ts +11 -0
  117. package/src/schema-builders/_internals/decimal128.ts +79 -0
  118. package/src/schema-builders/_internals/int32.ts +58 -0
  119. package/src/schema-builders/_internals/mixed.ts +12 -0
  120. package/src/schema-builders/_internals/number.ts +71 -0
  121. package/src/schema-builders/_internals/object-id.ts +13 -0
  122. package/src/schema-builders/_internals/ref.ts +18 -0
  123. package/src/schema-builders/_internals/shared.ts +302 -0
  124. package/src/schema-builders/_internals/string.ts +113 -0
  125. package/src/schema-builders/index.ts +26 -35
  126. package/src/transaction.ts +22 -0
  127. package/src/types/data.ts +5 -10
  128. package/src/types/index.ts +32 -22
  129. package/src/types/paginate.ts +9 -24
  130. package/dist/schema-builders/_internals.d.ts +0 -18
  131. package/dist/schema-builders/_internals.d.ts.map +0 -1
  132. package/dist/schema-builders/_internals.js +0 -36
  133. package/dist/schema-builders/_internals.js.map +0 -1
  134. package/dist/schema-builders/base.d.ts +0 -5
  135. package/dist/schema-builders/base.d.ts.map +0 -1
  136. package/dist/schema-builders/base.js +0 -33
  137. package/dist/schema-builders/base.js.map +0 -1
  138. package/dist/schema-builders/bigint.d.ts +0 -39
  139. package/dist/schema-builders/bigint.d.ts.map +0 -1
  140. package/dist/schema-builders/bigint.js +0 -47
  141. package/dist/schema-builders/bigint.js.map +0 -1
  142. package/dist/schema-builders/boolean.d.ts +0 -33
  143. package/dist/schema-builders/boolean.d.ts.map +0 -1
  144. package/dist/schema-builders/boolean.js +0 -6
  145. package/dist/schema-builders/boolean.js.map +0 -1
  146. package/dist/schema-builders/date.d.ts +0 -49
  147. package/dist/schema-builders/date.d.ts.map +0 -1
  148. package/dist/schema-builders/date.js +0 -6
  149. package/dist/schema-builders/date.js.map +0 -1
  150. package/dist/schema-builders/decimal128.d.ts +0 -79
  151. package/dist/schema-builders/decimal128.d.ts.map +0 -1
  152. package/dist/schema-builders/decimal128.js +0 -47
  153. package/dist/schema-builders/decimal128.js.map +0 -1
  154. package/dist/schema-builders/double.d.ts +0 -39
  155. package/dist/schema-builders/double.d.ts.map +0 -1
  156. package/dist/schema-builders/double.js +0 -51
  157. package/dist/schema-builders/double.js.map +0 -1
  158. package/dist/schema-builders/int32.d.ts +0 -39
  159. package/dist/schema-builders/int32.d.ts.map +0 -1
  160. package/dist/schema-builders/int32.js +0 -47
  161. package/dist/schema-builders/int32.js.map +0 -1
  162. package/dist/schema-builders/mixed.d.ts +0 -33
  163. package/dist/schema-builders/mixed.d.ts.map +0 -1
  164. package/dist/schema-builders/mixed.js +0 -7
  165. package/dist/schema-builders/mixed.js.map +0 -1
  166. package/dist/schema-builders/number.d.ts +0 -49
  167. package/dist/schema-builders/number.d.ts.map +0 -1
  168. package/dist/schema-builders/number.js +0 -6
  169. package/dist/schema-builders/number.js.map +0 -1
  170. package/dist/schema-builders/object-id.d.ts +0 -43
  171. package/dist/schema-builders/object-id.d.ts.map +0 -1
  172. package/dist/schema-builders/object-id.js +0 -7
  173. package/dist/schema-builders/object-id.js.map +0 -1
  174. package/dist/schema-builders/ref.d.ts +0 -44
  175. package/dist/schema-builders/ref.d.ts.map +0 -1
  176. package/dist/schema-builders/ref.js +0 -10
  177. package/dist/schema-builders/ref.js.map +0 -1
  178. package/dist/schema-builders/string.d.ts +0 -138
  179. package/dist/schema-builders/string.d.ts.map +0 -1
  180. package/dist/schema-builders/string.js +0 -48
  181. package/dist/schema-builders/string.js.map +0 -1
  182. package/dist/schema-builders/uuid.d.ts +0 -33
  183. package/dist/schema-builders/uuid.d.ts.map +0 -1
  184. package/dist/schema-builders/uuid.js +0 -7
  185. package/dist/schema-builders/uuid.js.map +0 -1
  186. package/dist/types/_internals.d.ts +0 -24
  187. package/dist/types/_internals.d.ts.map +0 -1
  188. package/dist/types/_internals.js +0 -1
  189. package/dist/types/aggregate-paginate.d.ts +0 -82
  190. package/dist/types/aggregate-paginate.d.ts.map +0 -1
  191. package/dist/types/aggregate-paginate.js +0 -1
  192. package/dist/types/options.d.ts +0 -23
  193. package/dist/types/options.d.ts.map +0 -1
  194. package/dist/types/options.js +0 -1
  195. package/src/schema-builders/_internals.ts +0 -64
  196. package/src/schema-builders/base.ts +0 -57
  197. package/src/schema-builders/bigint.ts +0 -156
  198. package/src/schema-builders/boolean.ts +0 -45
  199. package/src/schema-builders/date.ts +0 -80
  200. package/src/schema-builders/decimal128.ts +0 -196
  201. package/src/schema-builders/double.ts +0 -166
  202. package/src/schema-builders/int32.ts +0 -157
  203. package/src/schema-builders/mixed.ts +0 -37
  204. package/src/schema-builders/number.ts +0 -80
  205. package/src/schema-builders/object-id.ts +0 -60
  206. package/src/schema-builders/ref.ts +0 -67
  207. package/src/schema-builders/string.ts +0 -258
  208. package/src/schema-builders/uuid.ts +0 -48
  209. package/src/types/_internals.ts +0 -27
  210. package/src/types/aggregate-paginate.ts +0 -115
  211. package/src/types/options.ts +0 -46
@@ -1,28 +1,16 @@
1
1
  import { Schema } from "mongoose";
2
2
  declare module 'mongoose' {
3
3
  interface LeanOptions {
4
- /**
5
- * Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting.
6
- */
7
4
  decimal128ToString?: boolean;
8
5
  }
9
6
  }
10
7
  export interface MongooseLeanDecimal128ToStringPluginOptions {
11
- /**
12
- * Whether marked fields are converted on lean queries by default. Defaults to true.
13
- */
14
8
  enabledByDefault?: boolean;
15
9
  }
16
10
  /**
17
- * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
18
- *
19
- * @remarks
20
- * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
21
- * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
22
- * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
23
- * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
24
- * Registration is idempotent; the first registration's default options take precedence.
25
- * Runtime conversion does not override Mongoose's inferred lean result types.
11
+ * Converts paths marked by `s.decimal128().setToStringGetter()` on lean queries, except with
12
+ * `lean({ decimal128ToString: false })` and in aggregate results.
13
+ * Convertible paths are collected per schema on its first converted query; paths added later are ignored.
26
14
  */
27
15
  export declare function mongooseLeanDecimal128ToStringPlugin(schema: Schema, pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions): void;
28
16
  //# sourceMappingURL=lean-decimal128-to-string.d.ts.map
@@ -1 +1 @@
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
+ {"version":3,"file":"lean-decimal128-to-string.d.ts","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"mappings":";;YAec;IACN;;;iBAIS;EACb;;;;;;;wBAsGY,qCACZ,QAAQ,QACR,gBAAgB"}
@@ -1,25 +1,30 @@
1
1
  import { objectHasOwn, objectKeys, objectValues } from "ts-extras";
2
+ import { decimal128ToPlainString } from "../_internals.js";
2
3
  // src/plugins/lean-decimal128-to-string.ts
4
+ const conversionPathsCache = /* @__PURE__ */ new WeakMap();
3
5
  const registeredSchemas = /* @__PURE__ */ new WeakSet();
4
6
  const isNonNullObject = (value) => value !== null && typeof value === "object";
7
+ function canContainMarkedDecimal128(schemaType) {
8
+ if (schemaType.schema) return true;
9
+ if (schemaType.instance === "Decimal128") return schemaType.options.leanDecimal128ToString === true;
10
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
11
+ return !!embeddedSchemaType && canContainMarkedDecimal128(embeddedSchemaType);
12
+ }
5
13
  function convertDocument(schema, value) {
6
14
  if (!isNonNullObject(value)) return;
7
15
  const discriminatorKey = schema.get("discriminatorKey") ?? "__t";
8
- (objectValues(schema.discriminators ?? {}).find((childSchema) => childSchema.get("discriminatorKey") === discriminatorKey && childSchema.discriminatorMapping?.value === value[discriminatorKey]) ?? schema).eachPath((path, schemaType) => {
9
- const pathSegments = path.split(".");
10
- if (pathSegments.includes("$*")) return;
11
- convertPath(value, pathSegments, schemaType);
12
- });
16
+ const discriminatorSchema = schema.discriminators && objectValues(schema.discriminators).find((childSchema) => childSchema.get("discriminatorKey") === discriminatorKey && childSchema.discriminatorMapping?.value === value[discriminatorKey]);
17
+ for (const [pathSegments, schemaType] of getConversionPaths(discriminatorSchema ?? schema)) convertPath(value, pathSegments, 0, schemaType);
13
18
  }
14
- function convertPath(value, pathSegments, schemaType) {
19
+ function convertPath(value, pathSegments, index, schemaType) {
15
20
  if (Array.isArray(value)) {
16
- value.forEach((item) => convertPath(item, pathSegments, schemaType));
21
+ value.forEach((item) => convertPath(item, pathSegments, index, schemaType));
17
22
  return;
18
23
  }
19
24
  if (!isNonNullObject(value)) return;
20
- const [key, ...remainingPathSegments] = pathSegments;
25
+ const key = pathSegments[index];
21
26
  if (key === void 0 || !objectHasOwn(value, key)) return;
22
- if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
27
+ if (index < pathSegments.length - 1) convertPath(value[key], pathSegments, index + 1, schemaType);
23
28
  else value[key] = convertValue(value[key], schemaType);
24
29
  }
25
30
  function convertValue(value, schemaType) {
@@ -38,19 +43,24 @@ function convertValue(value, schemaType) {
38
43
  convertDocument(schemaType.schema, value);
39
44
  return value;
40
45
  }
41
- if (schemaType.instance === "Decimal128" && schemaType.options.leanDecimal128ToString === true && isNonNullObject(value) && value._bsontype === "Decimal128" && typeof value.toString === "function") return value.toString();
46
+ if (schemaType.instance === "Decimal128" && schemaType.options.leanDecimal128ToString === true && isNonNullObject(value) && value._bsontype === "Decimal128") return decimal128ToPlainString(value);
42
47
  return value;
43
48
  }
49
+ function getConversionPaths(schema) {
50
+ let conversionPaths = conversionPathsCache.get(schema);
51
+ if (conversionPaths) return conversionPaths;
52
+ conversionPaths = [];
53
+ schema.eachPath((path, schemaType) => {
54
+ const pathSegments = path.split(".");
55
+ if (!pathSegments.includes("$*") && canContainMarkedDecimal128(schemaType)) conversionPaths.push([pathSegments, schemaType]);
56
+ });
57
+ conversionPathsCache.set(schema, conversionPaths);
58
+ return conversionPaths;
59
+ }
44
60
  /**
45
- * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
46
- *
47
- * @remarks
48
- * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
49
- * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
50
- * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
51
- * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
52
- * Registration is idempotent; the first registration's default options take precedence.
53
- * Runtime conversion does not override Mongoose's inferred lean result types.
61
+ * Converts paths marked by `s.decimal128().setToStringGetter()` on lean queries, except with
62
+ * `lean({ decimal128ToString: false })` and in aggregate results.
63
+ * Convertible paths are collected per schema on its first converted query; paths added later are ignored.
54
64
  */
55
65
  function mongooseLeanDecimal128ToStringPlugin(schema, pluginOptions) {
56
66
  if (registeredSchemas.has(schema)) return;
@@ -66,10 +76,7 @@ function mongooseLeanDecimal128ToStringPlugin(schema, pluginOptions) {
66
76
  return result;
67
77
  }
68
78
  schema.pre("find", function() {
69
- const transform = (result) => convertResult(this, result);
70
- if (typeof this.map === "function") this.map(transform);
71
- else if (typeof this.transform === "function") this.transform(transform);
72
- else this.setOptions({ transform });
79
+ this.transform((result) => convertResult(this, result));
73
80
  });
74
81
  schema.post([
75
82
  "findOne",
@@ -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 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 convertResult(this, result);\n },\n );\n}\n"],"mappings":";;AA+BA,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,aAAa,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,MACjE,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,SAAS,SAAS,YAAY,MAAM,cAAc,UAAU,CAAC;EACnE;CACJ;CAEA,IAAI,CAAC,gBAAgB,KAAK,GAAG;CAC7B,MAAM,CAAC,KAAK,GAAG,yBAAyB;CACxC,IAAI,QAAQ,KAAA,KAAa,CAAC,aAAa,OAAO,GAAG,GAAG;CACpD,IAAI,sBAAsB,QAAQ,YAAY,MAAM,MAAM,uBAAuB,UAAU;MACtF,MAAM,OAAO,aAAa,MAAM,MAAM,UAAU;AACzD;AAEA,SAAS,aAAa,OAAgB,YAAiC;CACnE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,MAAM,qBAAqB,WAAW,sBAAsB;CAC5D,IAAI,sBAAsB,MAAM,QAAQ,KAAK,GAAG;EAC5C,KAAK,IAAI,IAAI,GAAG,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AAoB,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\nimport { decimal128ToPlainString } from '../_internals';\n\ndeclare module 'mongoose' {\n interface LeanOptions {\n decimal128ToString?: boolean;\n }\n}\n\nexport interface MongooseLeanDecimal128ToStringPluginOptions {\n enabledByDefault?: boolean;\n}\n\nconst conversionPathsCache = new WeakMap<Schema, Array<[pathSegments: string[], schemaType: SchemaType]>>();\nconst registeredSchemas = new WeakSet<Schema>();\n\nconst isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';\n\nfunction canContainMarkedDecimal128(schemaType: SchemaType): boolean {\n // Subdocument schemas are filtered by their own cached paths when converted.\n if (schemaType.schema) return true;\n if (schemaType.instance === 'Decimal128') return schemaType.options.leanDecimal128ToString === true;\n const embeddedSchemaType = schemaType.getEmbeddedSchemaType();\n return !!embeddedSchemaType && canContainMarkedDecimal128(embeddedSchemaType);\n}\n\nfunction convertDocument(schema: Schema, value: unknown) {\n if (!isNonNullObject(value)) return;\n const discriminatorKey = schema.get('discriminatorKey') ?? '__t';\n const discriminatorSchema = schema.discriminators && 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 for (const [pathSegments, schemaType] of getConversionPaths(discriminatorSchema ?? schema)) {\n convertPath(value, pathSegments, 0, schemaType);\n }\n}\n\nfunction convertPath(value: unknown, pathSegments: string[], index: number, schemaType: SchemaType) {\n if (Array.isArray(value)) {\n value.forEach((item) => convertPath(item, pathSegments, index, schemaType));\n return;\n }\n\n if (!isNonNullObject(value)) return;\n const key = pathSegments[index];\n if (key === undefined || !objectHasOwn(value, key)) return;\n if (index < pathSegments.length - 1) convertPath(value[key], pathSegments, index + 1, 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 ) return decimal128ToPlainString(value as Types.Decimal128);\n\n return value;\n}\n\nfunction getConversionPaths(schema: Schema) {\n let conversionPaths = conversionPathsCache.get(schema);\n if (conversionPaths) return conversionPaths;\n conversionPaths = [];\n schema.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('$*') && canContainMarkedDecimal128(schemaType)) {\n conversionPaths.push([\n pathSegments,\n schemaType,\n ]);\n }\n });\n\n conversionPathsCache.set(schema, conversionPaths);\n return conversionPaths;\n}\n\n/**\n * Converts paths marked by `s.decimal128().setToStringGetter()` on lean queries, except with\n * `lean({ decimal128ToString: false })` and in aggregate results.\n * Convertible paths are collected per schema on its first converted query; paths added later are ignored.\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: Query<unknown, unknown>, 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 // `Query#transform` also applies to cursors, which do not run post('find') hooks.\n schema.pre(\n 'find',\n function (this: Query<unknown, unknown>) {\n this.transform((result) => convertResult(this, result));\n },\n );\n\n schema.post(\n [\n 'findOne',\n 'findOneAndUpdate',\n 'findOneAndDelete',\n 'findOneAndReplace',\n ],\n function (this: Query<unknown, unknown>, result: unknown) {\n convertResult(this, result);\n },\n );\n}\n"],"mappings":";;;AAwBA,MAAM,uCAAuB,IAAI,QAAyE;AAC1G,MAAM,oCAAoB,IAAI,QAAgB;AAE9C,MAAM,mBAAmB,UAAiD,UAAU,QAAQ,OAAO,UAAU;AAE7G,SAAS,2BAA2B,YAAiC;CAEjE,IAAI,WAAW,QAAQ,OAAO;CAC9B,IAAI,WAAW,aAAa,cAAc,OAAO,WAAW,QAAQ,2BAA2B;CAC/F,MAAM,qBAAqB,WAAW,sBAAsB;CAC5D,OAAO,CAAC,CAAC,sBAAsB,2BAA2B,kBAAkB;AAChF;AAEA,SAAS,gBAAgB,QAAgB,OAAgB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AAyC;EACrC,KAAK,WAAW,WAAW,cAAc,MAAM,MAAM,CAAC;CAC1D,CACJ;CAEA,OAAO,KACH;EACI;EACA;EACA;EACA;CACJ,GACA,SAAyC,QAAiB;EACtD,cAAc,MAAM,MAAM;CAC9B,CACJ;AACJ"}
@@ -1,44 +1,7 @@
1
1
  import { Schema } from "mongoose";
2
- export interface MongooseNormalizePluginOptions {
3
- /**
4
- * Whether to move the serialized `_id` value to `id`.
5
- *
6
- * @remarks
7
- * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
8
- *
9
- * @defaultValue `true`.
10
- */
11
- convertIdField?: boolean;
12
- /**
13
- * Register normalization on child schemas too. Defaults to true.
14
- */
15
- recursive?: boolean;
16
- /**
17
- * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
18
- *
19
- * @remarks
20
- * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
21
- *
22
- * @defaultValue `true`.
23
- */
24
- toHexIdIfObjectId?: boolean;
25
- }
26
2
  /**
27
- * Registers JSON normalization on a Mongoose schema.
28
- *
29
- * @remarks
30
- * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
31
- * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
32
- * truthy serialized values at registered `Decimal128` paths to strings.
33
- *
34
- * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
35
- * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
36
- * That transform can change the normalized output, and its errors propagate during serialization.
37
- * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
38
- * Registration is idempotent per schema; the first registration's options take precedence.
39
- *
40
- * @param schema - The schema whose JSON serialization configuration is modified.
41
- * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
3
+ * Child and discriminator schemas are registered too, so register after the schema's paths are defined.
4
+ * `toJSON` options cannot be changed afterwards.
42
5
  */
43
- export declare function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions): void;
6
+ export declare function mongooseNormalizePlugin(schema: Schema): void;
44
7
  //# sourceMappingURL=normalize.d.ts.map
@@ -1 +1 @@
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
+ {"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";;;;;wBA4GgB,wBAAwB,QAAQ"}
@@ -1,59 +1,113 @@
1
- import { Types } from "mongoose";
2
- import { objectEntries } from "ts-extras";
3
1
  import { get, set, unset } from "es-toolkit/compat";
2
+ import { Model, Schema, Types } from "mongoose";
3
+ import { objectEntries, objectFromEntries, objectValues } from "ts-extras";
4
+ import { decimal128ToPlainString } from "../_internals.js";
4
5
  // src/plugins/normalize.ts
6
+ const normalizedPathsCache = /* @__PURE__ */ new WeakMap();
7
+ const normalizeTransforms = /* @__PURE__ */ new WeakSet();
5
8
  const registeredSchemas = /* @__PURE__ */ new WeakSet();
9
+ const isNonNullObject = (value) => value !== null && typeof value === "object";
10
+ function containsDecimal128(schemaType) {
11
+ if (schemaType.instance === "Decimal128") return true;
12
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
13
+ return !!embeddedSchemaType && !embeddedSchemaType.schema && containsDecimal128(embeddedSchemaType);
14
+ }
15
+ function decimal128ToString(value, schemaType) {
16
+ if (schemaType.instance === "Decimal128") {
17
+ if (isNonNullObject(value)) {
18
+ if (value._bsontype === "Decimal128") return decimal128ToPlainString(value);
19
+ return typeof value.$numberDecimal === "string" ? decimal128ToPlainString(value.$numberDecimal) : value;
20
+ }
21
+ return typeof value === "bigint" || typeof value === "number" ? String(value) : value;
22
+ }
23
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
24
+ if (!embeddedSchemaType) return value;
25
+ if (Array.isArray(value)) return value.map((item) => decimal128ToString(item, embeddedSchemaType));
26
+ if (schemaType.instance !== "Map") return value;
27
+ if (value instanceof Map) return new Map(Array.from(value, ([key, item]) => [key, decimal128ToString(item, embeddedSchemaType)]));
28
+ if (isNonNullObject(value)) return objectFromEntries(objectEntries(value).map(([key, item]) => [key, decimal128ToString(item, embeddedSchemaType)]));
29
+ return value;
30
+ }
31
+ function getNormalizedPaths(schema) {
32
+ let normalizedPaths = normalizedPathsCache.get(schema);
33
+ if (normalizedPaths) return normalizedPaths;
34
+ normalizedPaths = {
35
+ decimal128Paths: [],
36
+ privatePaths: []
37
+ };
38
+ for (const [path, schemaType] of objectEntries(schema.paths)) {
39
+ if (path.split(".").includes("$*")) continue;
40
+ if (schemaType.options?.private) normalizedPaths.privatePaths.push(path);
41
+ else if (containsDecimal128(schemaType)) normalizedPaths.decimal128Paths.push([path, schemaType]);
42
+ }
43
+ normalizedPathsCache.set(schema, normalizedPaths);
44
+ return normalizedPaths;
45
+ }
6
46
  /**
7
- * Registers JSON normalization on a Mongoose schema.
8
- *
9
- * @remarks
10
- * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
11
- * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
12
- * truthy serialized values at registered `Decimal128` paths to strings.
13
- *
14
- * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
15
- * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
16
- * That transform can change the normalized output, and its errors propagate during serialization.
17
- * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
18
- * Registration is idempotent per schema; the first registration's options take precedence.
19
- *
20
- * @param schema - The schema whose JSON serialization configuration is modified.
21
- * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
47
+ * Child and discriminator schemas are registered too, so register after the schema's paths are defined.
48
+ * `toJSON` options cannot be changed afterwards.
22
49
  */
23
- function mongooseNormalizePlugin(schema, pluginOptions) {
50
+ function mongooseNormalizePlugin(schema) {
24
51
  if (registeredSchemas.has(schema)) return;
25
52
  registeredSchemas.add(schema);
26
- const decimalPaths = [];
27
- const privatePaths = [];
28
- for (const [path, schemaType] of objectEntries(schema.paths)) if (schemaType?.options?.private) privatePaths.push(path);
29
- else if (schemaType?.instance === "Decimal128") decimalPaths.push(path);
30
53
  const toJson = schema.get("toJSON");
31
54
  const toJsonTransform = toJson?.transform;
32
- schema.set("toJSON", {
33
- ...toJson,
34
- transform(doc, ret, options) {
35
- const copiedRet = { ...ret };
36
- delete copiedRet.__v;
37
- let _id = copiedRet._id;
38
- delete copiedRet._id;
39
- if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) _id = _id.toHexString();
40
- if (_id !== void 0) {
41
- if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
42
- else copiedRet._id = _id;
55
+ if (typeof toJsonTransform !== "function" || !normalizeTransforms.has(toJsonTransform)) {
56
+ schema.options.toJSON = {
57
+ ...toJson,
58
+ transform(doc, ret, options) {
59
+ normalize(doc, ret);
60
+ if (typeof toJsonTransform !== "function") return ret;
61
+ const transformed = toJsonTransform(doc, ret, options);
62
+ return transformed === void 0 ? ret : transformed;
43
63
  }
44
- for (const path of privatePaths) unset(copiedRet, path);
45
- for (const path of decimalPaths) {
46
- const value = get(copiedRet, path);
47
- if (value) set(copiedRet, path, value.toString());
64
+ };
65
+ const transform = schema.options.toJSON.transform;
66
+ if (typeof transform === "function") normalizeTransforms.add(transform);
67
+ }
68
+ const childSchemas = new Set(schema.childSchemas.map(({ schema: child }) => child));
69
+ objectValues(schema.discriminators ?? {}).forEach((child) => childSchemas.add(child));
70
+ for (const pathSchemaType of objectValues(schema.paths)) {
71
+ let schemaType = pathSchemaType;
72
+ while (schemaType) {
73
+ const embedded = schemaType;
74
+ if (embedded.schema) {
75
+ childSchemas.add(embedded.schema);
76
+ if (typeof embedded.discriminator === "function") embedded.discriminator = registerAfterDiscriminator(embedded.discriminator);
48
77
  }
49
- if (toJsonTransform && typeof toJsonTransform !== "boolean") {
50
- const transformed = toJsonTransform(doc, copiedRet, options);
51
- return transformed === void 0 ? copiedRet : transformed;
52
- }
53
- return copiedRet;
78
+ objectValues(embedded.Constructor?.discriminators ?? {}).forEach((child) => childSchemas.add(child.schema));
79
+ schemaType = schemaType.getEmbeddedSchemaType();
54
80
  }
55
- });
56
- if (pluginOptions?.recursive !== false) schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
81
+ }
82
+ childSchemas.forEach((child) => child.plugin(mongooseNormalizePlugin));
83
+ schema.static("discriminator", registerAfterDiscriminator(Model.discriminator));
84
+ const set = schema.set;
85
+ schema.set = function(...args) {
86
+ if (args[0] === "toJSON" && args.length > 1) throw new Error("toJSON options cannot be changed after mongooseNormalizePlugin is registered.");
87
+ return set.apply(this, args);
88
+ };
89
+ }
90
+ function normalize(doc, ret) {
91
+ const schema = doc.constructor.schema ?? doc.schema;
92
+ const { decimal128Paths, privatePaths } = getNormalizedPaths(schema);
93
+ const versionKey = schema.get("versionKey");
94
+ if (typeof versionKey === "string") unset(ret, versionKey);
95
+ const _id = ret._id;
96
+ delete ret._id;
97
+ if (_id !== void 0) ret.id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
98
+ for (const path of privatePaths) unset(ret, path);
99
+ for (const [path, schemaType] of decimal128Paths) {
100
+ const value = get(ret, path);
101
+ if (value !== void 0) set(ret, path, decimal128ToString(value, schemaType));
102
+ }
103
+ }
104
+ function registerAfterDiscriminator(discriminator) {
105
+ return function(...args) {
106
+ const result = discriminator.apply(this, args);
107
+ const { schema } = result;
108
+ if (schema instanceof Schema) schema.plugin(mongooseNormalizePlugin);
109
+ return result;
110
+ };
57
111
  }
58
112
  export { mongooseNormalizePlugin };
59
113
 
@@ -1 +1 @@
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"}
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 {\n Model,\n Schema,\n Types,\n} from 'mongoose';\nimport type {\n Document,\n SchemaType,\n} from 'mongoose';\nimport {\n objectEntries,\n objectFromEntries,\n objectValues,\n} from 'ts-extras';\n\nimport { decimal128ToPlainString } from '../_internals';\n\ntype DiscriminatorFunction = (name: unknown, schema: unknown, ...args: unknown[]) => unknown;\ntype DiscriminatorMap = Record<string, { schema: Schema }>;\n\ninterface NormalizedPaths {\n decimal128Paths: Array<[path: string, schemaType: SchemaType]>;\n privatePaths: string[];\n}\n\nconst normalizedPathsCache = new WeakMap<Schema, NormalizedPaths>();\nconst normalizeTransforms = new WeakSet<object>();\nconst registeredSchemas = new WeakSet<Schema>();\n\nconst isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';\n\nfunction containsDecimal128(schemaType: SchemaType): boolean {\n if (schemaType.instance === 'Decimal128') return true;\n const embeddedSchemaType = schemaType.getEmbeddedSchemaType();\n // Subdocuments are normalized by their own schema's transform.\n return !!embeddedSchemaType && !embeddedSchemaType.schema && containsDecimal128(embeddedSchemaType);\n}\n\nfunction decimal128ToString(value: unknown, schemaType: SchemaType): unknown {\n if (schemaType.instance === 'Decimal128') {\n // `flattenDecimals` serializes to `{ $numberDecimal }`; getters may return plain values.\n if (isNonNullObject(value)) {\n if (value._bsontype === 'Decimal128') return decimal128ToPlainString(value as Types.Decimal128);\n return typeof value.$numberDecimal === 'string' ? decimal128ToPlainString(value.$numberDecimal) : value;\n }\n\n return typeof value === 'bigint' || typeof value === 'number' ? String(value) : value;\n }\n\n const embeddedSchemaType = schemaType.getEmbeddedSchemaType();\n if (!embeddedSchemaType) return value;\n if (Array.isArray(value)) return value.map((item) => decimal128ToString(item, embeddedSchemaType));\n if (schemaType.instance !== 'Map') return value;\n if (value instanceof Map) {\n return new Map(Array.from(\n value,\n ([key, item]) => [\n key,\n decimal128ToString(item, embeddedSchemaType),\n ],\n ));\n }\n\n if (isNonNullObject(value)) {\n return objectFromEntries(\n objectEntries(value).map(([key, item]) => [\n key,\n decimal128ToString(item, embeddedSchemaType),\n ]),\n );\n }\n\n return value;\n}\n\nfunction getNormalizedPaths(schema: Schema) {\n let normalizedPaths = normalizedPathsCache.get(schema);\n if (normalizedPaths) return normalizedPaths;\n normalizedPaths = {\n decimal128Paths: [],\n privatePaths: [],\n };\n\n for (const [path, schemaType] of objectEntries(schema.paths)) {\n // Map values are handled through the map path's embedded schema type, not the synthetic `$*` path.\n if (path.split('.').includes('$*')) continue;\n if (schemaType.options?.private) normalizedPaths.privatePaths.push(path);\n else if (containsDecimal128(schemaType)) {\n normalizedPaths.decimal128Paths.push([\n path,\n schemaType,\n ]);\n }\n }\n\n normalizedPathsCache.set(schema, normalizedPaths);\n return normalizedPaths;\n}\n\n/**\n * Child and discriminator schemas are registered too, so register after the schema's paths are defined.\n * `toJSON` options cannot be changed afterwards.\n */\nexport function mongooseNormalizePlugin(schema: Schema) {\n if (registeredSchemas.has(schema)) return;\n registeredSchemas.add(schema);\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n // Discriminator schemas may inherit the base transform, which already uses each document's own schema.\n if (typeof toJsonTransform !== 'function' || !normalizeTransforms.has(toJsonTransform)) {\n // Not `Schema#set`: it copies the options minus the transform onto implicitly created child schemas, which may\n // already be registered and shared with a discriminator's base schema.\n schema.options.toJSON = {\n ...toJson,\n transform(doc, ret, options) {\n normalize(doc, ret);\n if (typeof toJsonTransform !== 'function') return ret;\n const transformed = toJsonTransform(doc, ret, options);\n return transformed === undefined ? ret : transformed;\n },\n };\n\n const transform = schema.options.toJSON.transform;\n if (typeof transform === 'function') normalizeTransforms.add(transform);\n }\n\n const childSchemas = new Set<Schema>(schema.childSchemas.map(({ schema: child }) => child));\n objectValues(schema.discriminators ?? {}).forEach((child) => childSchemas.add(child));\n for (const pathSchemaType of objectValues(schema.paths)) {\n // `childSchemas` omits subdocuments nested in arrays of arrays or maps of arrays.\n let schemaType: SchemaType | undefined = pathSchemaType;\n while (schemaType) {\n const embedded = schemaType as SchemaType & {\n Constructor?: { discriminators?: DiscriminatorMap };\n discriminator?: DiscriminatorFunction;\n };\n\n if (embedded.schema) {\n childSchemas.add(embedded.schema);\n if (typeof embedded.discriminator === 'function') {\n embedded.discriminator = registerAfterDiscriminator(embedded.discriminator);\n }\n }\n\n // Embedded discriminators live on the path's constructor; `schema.discriminators` is keyed by name only,\n // so paths sharing a schema overwrite each other there.\n objectValues(embedded.Constructor?.discriminators ?? {}).forEach((child) => childSchemas.add(child.schema));\n schemaType = schemaType.getEmbeddedSchemaType();\n }\n }\n\n childSchemas.forEach((child) => child.plugin(mongooseNormalizePlugin));\n schema.static('discriminator', registerAfterDiscriminator(Model.discriminator));\n // `Schema#set` replaces the whole `toJSON` object, which would drop the normalize transform.\n const set = schema.set;\n schema.set = function (this: Schema, ...args: Parameters<Schema['set']>) {\n if (args[0] === 'toJSON' && args.length > 1) {\n throw new Error('toJSON options cannot be changed after mongooseNormalizePlugin is registered.');\n }\n\n return set.apply(this, args);\n } as Schema['set'];\n}\n\nfunction normalize(doc: Document<unknown>, ret: Record<string, any>) {\n // A data field named `schema` shadows `Document#schema`; the constructor holds the schema Mongoose serializes with.\n const schema = (doc.constructor as { schema?: Schema }).schema ?? doc.schema;\n const { decimal128Paths, privatePaths } = getNormalizedPaths(schema);\n const versionKey = schema.get('versionKey');\n if (typeof versionKey === 'string') unsetProp(ret, versionKey);\n const _id = ret._id;\n delete ret._id;\n if (_id !== undefined) ret.id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;\n for (const path of privatePaths) unsetProp(ret, path);\n for (const [path, schemaType] of decimal128Paths) {\n const value = getProp(ret, path);\n if (value !== undefined) setProp(ret, path, decimal128ToString(value, schemaType));\n }\n}\n\n// Mongoose clones and merges the discriminator schema, so register on the schema it actually uses. Registering before\n// the merge would give a schema without its own `toJSON` one, which replaces the inherited options.\nfunction registerAfterDiscriminator<T extends (...args: any[]) => any>(discriminator: T) {\n return function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const result = discriminator.apply(this, args);\n const { schema } = result as { schema?: unknown };\n if (schema instanceof Schema) schema.plugin(mongooseNormalizePlugin);\n return result;\n };\n}\n"],"mappings":";;;;;AA8BA,MAAM,uCAAuB,IAAI,QAAiC;AAClE,MAAM,sCAAsB,IAAI,QAAgB;AAChD,MAAM,oCAAoB,IAAI,QAAgB;AAE9C,MAAM,mBAAmB,UAAiD,UAAU,QAAQ,OAAO,UAAU;AAE7G,SAAS,mBAAmB,YAAiC;CACzD,IAAI,WAAW,aAAa,cAAc,OAAO;CACjD,MAAM,qBAAqB,WAAW,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OAAO,uBAAuB,CAAC;CACrE,OAAO,OAAO,iBAAiB,2BAA2B,MAAM,aAAa,CAAC;CAE9E,MAAM,MAAM,OAAO;CACnB,OAAO,MAAM,SAAwB,GAAG,MAAiC;EACrE,IAAI,KAAK,OAAO,YAAY,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,+EAA+E;EAGnG,OAAO,IAAI,MAAM,MAAM,IAAI;CAC/B;AACJ;AAEA,SAAS,UAAU,KAAwB,KAA0B;CAEjE,MAAM,SAAU,IAAI,YAAoC,UAAU,IAAI;CACtE,MAAM,EAAE,iBAAiB,iBAAiB,mBAAmB,MAAM;CACnE,MAAM,aAAa,OAAO,IAAI,YAAY;CAC1C,IAAI,OAAO,eAAe,UAAUA,MAAU,KAAK,UAAU;CAC7D,MAAM,MAAM,IAAI;CAChB,OAAO,IAAI;CACX,IAAI,QAAQ,KAAA,GAAW,IAAI,KAAK,eAAe,MAAM,WAAW,IAAI,YAAY,IAAI;CACpF,KAAK,MAAM,QAAQ,cAAcA,MAAU,KAAK,IAAI;CACpD,KAAK,MAAM,CAAC,MAAM,eAAe,iBAAiB;EAC9C,MAAM,QAAQC,IAAQ,KAAK,IAAI;EAC/B,IAAI,UAAU,KAAA,GAAWC,IAAQ,KAAK,MAAM,mBAAmB,OAAO,UAAU,CAAC;CACrF;AACJ;AAIA,SAAS,2BAA8D,eAAkB;CACrF,OAAO,SAAyB,GAAG,MAAoC;EACnE,MAAM,SAAS,cAAc,MAAM,MAAM,IAAI;EAC7C,MAAM,EAAE,WAAW;EACnB,IAAI,kBAAkB,QAAQ,OAAO,OAAO,uBAAuB;EACnE,OAAO;CACX;AACJ"}
@@ -0,0 +1,9 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ export declare class ArraySchemaBuilder<Props, Used extends string = never> extends SchemaBuilder<'array', Props, Used, unknown[]> {}
3
+ /**
4
+ * Mongoose initializes array paths to `[]`, so no default is needed for an empty array.
5
+ */
6
+ export declare function array<const T>(item: T): ArraySchemaBuilder<{
7
+ type: T[];
8
+ }, never>;
9
+ //# sourceMappingURL=array.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"array.d.ts","names":[],"sources":["../../../src/schema-builders/_internals/array.ts"],"mappings":";qBAEa,mBAAmB,OAAO,qCAAqC,uBAExE,OACA;;;;wBAOY,YAAY,GAAG,MAAM,IAAC;EACI,MAAA"}
@@ -0,0 +1,12 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ // src/schema-builders/_internals/array.ts
3
+ var ArraySchemaBuilder = class extends SchemaBuilder {};
4
+ /**
5
+ * Mongoose initializes array paths to `[]`, so no default is needed for an empty array.
6
+ */
7
+ function array(item) {
8
+ return new ArraySchemaBuilder({ type: [item] });
9
+ }
10
+ export { ArraySchemaBuilder, array };
11
+
12
+ //# sourceMappingURL=array.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"array.js","names":[],"sources":["../../../src/schema-builders/_internals/array.ts"],"sourcesContent":["import { SchemaBuilder } from './shared';\n\nexport class ArraySchemaBuilder<Props, Used extends string = never> extends SchemaBuilder<\n 'array',\n Props,\n Used,\n unknown[]\n> {}\n\n/**\n * Mongoose initializes array paths to `[]`, so no default is needed for an empty array.\n */\nexport function array<const T>(item: T) {\n return new ArraySchemaBuilder<{ type: T[] }>({ type: [item] });\n}\n"],"mappings":";;AAEA,IAAa,qBAAb,cAA4E,cAK1E,CAAC;;;;AAKH,SAAgB,MAAe,MAAS;CACpC,OAAO,IAAI,mBAAkC,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;AACjE"}
@@ -0,0 +1,8 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ export declare class BooleanSchemaBuilder<Props = {
3
+ type: BooleanConstructor;
4
+ }, Used extends string = never> extends SchemaBuilder<'boolean', Props, Used, boolean> {}
5
+ export declare function boolean(): BooleanSchemaBuilder<{
6
+ type: BooleanConstructor;
7
+ }, never>;
8
+ //# sourceMappingURL=boolean.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boolean.d.ts","names":[],"sources":["../../../src/schema-builders/_internals/boolean.ts"],"mappings":";qBAEa,qBACT;EAAU,MAAM;GAChB,qCACM,yBAAyB,OAAO;wBAE1B,WAAO;EAJH,MAAA"}
@@ -0,0 +1,9 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ // src/schema-builders/_internals/boolean.ts
3
+ var BooleanSchemaBuilder = class extends SchemaBuilder {};
4
+ function boolean() {
5
+ return new BooleanSchemaBuilder({ type: Boolean });
6
+ }
7
+ export { BooleanSchemaBuilder, boolean };
8
+
9
+ //# sourceMappingURL=boolean.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boolean.js","names":[],"sources":["../../../src/schema-builders/_internals/boolean.ts"],"sourcesContent":["import { SchemaBuilder } from './shared';\n\nexport class BooleanSchemaBuilder<\n Props = { type: BooleanConstructor },\n Used extends string = never,\n> extends SchemaBuilder<'boolean', Props, Used, boolean> {}\n\nexport function boolean() {\n return new BooleanSchemaBuilder({ type: Boolean });\n}\n"],"mappings":";;AAEA,IAAa,uBAAb,cAGU,cAA+C,CAAC;AAE1D,SAAgB,UAAU;CACtB,OAAO,IAAI,qBAAqB,EAAE,MAAM,QAAQ,CAAC;AACrD"}
@@ -0,0 +1,8 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ export declare class DateSchemaBuilder<Props = {
3
+ type: DateConstructor;
4
+ }, Used extends string = never> extends SchemaBuilder<'date', Props, Used, NativeDate | number, NativeDate> {}
5
+ export declare function date(): DateSchemaBuilder<{
6
+ type: DateConstructor;
7
+ }, never>;
8
+ //# sourceMappingURL=date.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.d.ts","names":[],"sources":["../../../src/schema-builders/_internals/date.ts"],"mappings":";qBAEa,kBACT;EAAU,MAAM;GAChB,qCAEM,sBAAsB,OAAO,MAAM,qBAAqB;wBAElD,QAAI;EALA,MAAA"}
@@ -0,0 +1,9 @@
1
+ import { SchemaBuilder } from "./shared.js";
2
+ // src/schema-builders/_internals/date.ts
3
+ var DateSchemaBuilder = class extends SchemaBuilder {};
4
+ function date() {
5
+ return new DateSchemaBuilder({ type: Date });
6
+ }
7
+ export { DateSchemaBuilder, date };
8
+
9
+ //# sourceMappingURL=date.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.js","names":[],"sources":["../../../src/schema-builders/_internals/date.ts"],"sourcesContent":["import { SchemaBuilder } from './shared';\n\nexport class DateSchemaBuilder<\n Props = { type: DateConstructor },\n Used extends string = never,\n// A number default such as `Date.now` is cast to a date by Mongoose.\n> extends SchemaBuilder<'date', Props, Used, NativeDate | number, NativeDate> {}\n\nexport function date() {\n return new DateSchemaBuilder({ type: Date });\n}\n"],"mappings":";;AAEA,IAAa,oBAAb,cAIU,cAAoE,CAAC;AAE/E,SAAgB,OAAO;CACnB,OAAO,IAAI,kBAAkB,EAAE,MAAM,KAAK,CAAC;AAC/C"}
@@ -0,0 +1,36 @@
1
+ import { Decimal } from "decimal.js";
2
+ import { Schema, Types } from "mongoose";
3
+ import { NextSchemaBuilder, OptionGuard, SchemaBuilder } from "./shared.js";
4
+ type This<Props, Used extends string, Option extends string> = Decimal128SchemaBuilder<Props, Used> & OptionGuard<Used, Option>;
5
+ export declare class Decimal128SchemaBuilder<Props = {
6
+ type: typeof Schema.Types.Decimal128;
7
+ }, Used extends string = never> extends SchemaBuilder<'decimal128', Props, Used, number | string | Types.Decimal128, Types.Decimal128> {
8
+ /**
9
+ * Reads the value as a plain-notation string and marks the path for the lean Decimal128 plugin, which converts
10
+ * lean results without invoking this getter.
11
+ *
12
+ * @remarks
13
+ * The definition's `type` is typed as `String` so inferred and declared document types use `string`, while the
14
+ * stored type stays Decimal128. Reads that skip both the getter and the plugins still return Decimal128, such as
15
+ * `get(path, null, { getters: false })`, `toObject()` without getters, and `toJSON()` without getters or the
16
+ * normalize transform.
17
+ */
18
+ setToStringGetter(this: This<Props, Used, 'setToStringGetter'>): Decimal128SchemaBuilder<Omit<Props, 'type'> & {
19
+ get: (value?: null | Types.Decimal128) => string | undefined;
20
+ leanDecimal128ToString: true;
21
+ type: StringConstructor;
22
+ }, 'setToStringGetter' | Used>;
23
+ /**
24
+ * Decimal.js validates `places` and `rounding` when a value is set, not here.
25
+ */
26
+ toFixedOnSet(this: This<Props, Used, 'toFixedOnSet'>, places?: number, rounding?: Decimal.Rounding): NextSchemaBuilder<'decimal128', Props, Used, 'toFixedOnSet', {
27
+ set: (value?: null | {
28
+ toString: () => string;
29
+ }) => string | undefined;
30
+ }>;
31
+ }
32
+ export declare function decimal128(): Decimal128SchemaBuilder<{
33
+ type: typeof Schema.Types.Decimal128;
34
+ }, never>;
35
+ export {};
36
+ //# sourceMappingURL=decimal128.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decimal128.d.ts","names":[],"sources":["../../../src/schema-builders/_internals/decimal128.ts"],"mappings":";;;KAYK,KAAK,OAAO,qBAAqB,yBAClC,wBAAwB,OAAO,QAC/B,YAAY,MAAM;qBAET,wBACT;EAAU,aAAa,OAAO,MAAM;GACpC,qCACM,4BAA4B,OAAO,wBAAwB,MAAM,YAAY,MAAM;;;;;;;;;;;EAWzF,kBAAkB,MAAM,KAAK,OAAO,6BAA6B,wBAC7D,KAAK;IAEH,MAAM,eAAe,MAAM;IAC3B;IACA,MAAM;2BAEc;;;;EAgB1B,aACI,MAAM,KAAK,OAAO,uBAClB,iBACA,WAAU,QAAQ,WACnB,gCAEC,OACA;IAEE,MAAM;MAAiB;;;;wBAcjB,cAAU;EA3DN,aAAO,OAAO,MAAM"}
@@ -0,0 +1,38 @@
1
+ import { Decimal } from "decimal.js";
2
+ import { Schema } from "mongoose";
3
+ import { decimal128ToPlainString } from "../../_internals.js";
4
+ import { SchemaBuilder } from "./shared.js";
5
+ // src/schema-builders/_internals/decimal128.ts
6
+ var Decimal128SchemaBuilder = class extends SchemaBuilder {
7
+ /**
8
+ * Reads the value as a plain-notation string and marks the path for the lean Decimal128 plugin, which converts
9
+ * lean results without invoking this getter.
10
+ *
11
+ * @remarks
12
+ * The definition's `type` is typed as `String` so inferred and declared document types use `string`, while the
13
+ * stored type stays Decimal128. Reads that skip both the getter and the plugins still return Decimal128, such as
14
+ * `get(path, null, { getters: false })`, `toObject()` without getters, and `toJSON()` without getters or the
15
+ * normalize transform.
16
+ */
17
+ setToStringGetter() {
18
+ return this.with("setToStringGetter", {
19
+ get: (value) => value === null || value === void 0 ? void 0 : decimal128ToPlainString(value),
20
+ leanDecimal128ToString: true
21
+ });
22
+ }
23
+ /**
24
+ * Decimal.js validates `places` and `rounding` when a value is set, not here.
25
+ */
26
+ toFixedOnSet(places = 2, rounding = Decimal.ROUND_DOWN) {
27
+ return this.with("toFixedOnSet", { set: (value) => {
28
+ if (value === null || value === void 0) return void 0;
29
+ return (Decimal.isDecimal(value) ? value : new Decimal(value.toString())).toFixed(places, rounding);
30
+ } });
31
+ }
32
+ };
33
+ function decimal128() {
34
+ return new Decimal128SchemaBuilder({ type: Schema.Types.Decimal128 });
35
+ }
36
+ export { Decimal128SchemaBuilder, decimal128 };
37
+
38
+ //# sourceMappingURL=decimal128.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decimal128.js","names":[],"sources":["../../../src/schema-builders/_internals/decimal128.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\nimport { Schema } from 'mongoose';\nimport type { Types } from 'mongoose';\n\nimport { decimal128ToPlainString } from '../../_internals';\n\nimport type {\n NextSchemaBuilder,\n OptionGuard,\n} from './shared';\nimport { SchemaBuilder } from './shared';\n\ntype This<Props, Used extends string, Option extends string> =\n & Decimal128SchemaBuilder<Props, Used>\n & OptionGuard<Used, Option>;\n\nexport class Decimal128SchemaBuilder<\n Props = { type: typeof Schema.Types.Decimal128 },\n Used extends string = never,\n> extends SchemaBuilder<'decimal128', Props, Used, number | string | Types.Decimal128, Types.Decimal128> {\n /**\n * Reads the value as a plain-notation string and marks the path for the lean Decimal128 plugin, which converts\n * lean results without invoking this getter.\n *\n * @remarks\n * The definition's `type` is typed as `String` so inferred and declared document types use `string`, while the\n * stored type stays Decimal128. Reads that skip both the getter and the plugins still return Decimal128, such as\n * `get(path, null, { getters: false })`, `toObject()` without getters, and `toJSON()` without getters or the\n * normalize transform.\n */\n setToStringGetter(this: This<Props, Used, 'setToStringGetter'>): Decimal128SchemaBuilder<\n & Omit<Props, 'type'>\n & {\n get: (value?: null | Types.Decimal128) => string | undefined;\n leanDecimal128ToString: true;\n type: StringConstructor;\n },\n 'setToStringGetter' | Used\n > {\n return this.with(\n 'setToStringGetter',\n {\n get: (value?: null | Types.Decimal128) => value === null || value === undefined\n ? undefined\n : decimal128ToPlainString(value),\n leanDecimal128ToString: true,\n },\n );\n }\n\n /**\n * Decimal.js validates `places` and `rounding` when a value is set, not here.\n */\n toFixedOnSet(\n this: This<Props, Used, 'toFixedOnSet'>,\n places = 2,\n rounding: Decimal.Rounding = Decimal.ROUND_DOWN,\n ): NextSchemaBuilder<\n 'decimal128',\n Props,\n Used,\n 'toFixedOnSet',\n { set: (value?: null | { toString: () => string }) => string | undefined }\n > {\n return this.with(\n 'toFixedOnSet',\n {\n set: (value?: null | { toString: () => string }) => {\n if (value === null || value === undefined) return undefined;\n return (Decimal.isDecimal(value) ? value : new Decimal(value.toString())).toFixed(places, rounding);\n },\n },\n );\n }\n}\n\nexport function decimal128() {\n return new Decimal128SchemaBuilder({ type: Schema.Types.Decimal128 });\n}\n"],"mappings":";;;;;AAgBA,IAAa,0BAAb,cAGU,cAA+F;;;;;;;;;;;CAWrG,oBAQE;EACE,OAAO,KAAK,KACR,qBACA;GACI,MAAM,UAAoC,UAAU,QAAQ,UAAU,KAAA,IAChE,KAAA,IACA,wBAAwB,KAAK;GACnC,wBAAwB;EAC5B,CACJ;CACJ;;;;CAKA,aAEI,SAAS,GACT,WAA6B,QAAQ,YAOvC;EACE,OAAO,KAAK,KACR,gBACA,EACI,MAAM,UAA8C;GAChD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO,KAAA;GAClD,QAAQ,QAAQ,UAAU,KAAK,IAAI,QAAQ,IAAI,QAAQ,MAAM,SAAS,CAAC,EAAA,CAAG,QAAQ,QAAQ,QAAQ;EACtG,EACJ,CACJ;CACJ;AACJ;AAEA,SAAgB,aAAa;CACzB,OAAO,IAAI,wBAAwB,EAAE,MAAM,OAAO,MAAM,WAAW,CAAC;AACxE"}