@depup/mongoose 9.1.3-depup.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 (295) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +397 -0
  3. package/SECURITY.md +1 -0
  4. package/eslint.config.mjs +198 -0
  5. package/index.js +64 -0
  6. package/lib/aggregate.js +1189 -0
  7. package/lib/cast/bigint.js +46 -0
  8. package/lib/cast/boolean.js +32 -0
  9. package/lib/cast/date.js +41 -0
  10. package/lib/cast/decimal128.js +39 -0
  11. package/lib/cast/double.js +50 -0
  12. package/lib/cast/int32.js +36 -0
  13. package/lib/cast/number.js +42 -0
  14. package/lib/cast/objectid.js +29 -0
  15. package/lib/cast/string.js +37 -0
  16. package/lib/cast/uuid.js +35 -0
  17. package/lib/cast.js +436 -0
  18. package/lib/collection.js +321 -0
  19. package/lib/connection.js +1855 -0
  20. package/lib/connectionState.js +26 -0
  21. package/lib/constants.js +73 -0
  22. package/lib/cursor/aggregationCursor.js +466 -0
  23. package/lib/cursor/changeStream.js +198 -0
  24. package/lib/cursor/queryCursor.js +622 -0
  25. package/lib/document.js +5521 -0
  26. package/lib/driver.js +15 -0
  27. package/lib/drivers/SPEC.md +4 -0
  28. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  29. package/lib/drivers/node-mongodb-native/collection.js +393 -0
  30. package/lib/drivers/node-mongodb-native/connection.js +506 -0
  31. package/lib/drivers/node-mongodb-native/index.js +10 -0
  32. package/lib/error/browserMissingSchema.js +29 -0
  33. package/lib/error/bulkSaveIncompleteError.js +44 -0
  34. package/lib/error/bulkWriteError.js +41 -0
  35. package/lib/error/cast.js +158 -0
  36. package/lib/error/createCollectionsError.js +26 -0
  37. package/lib/error/divergentArray.js +40 -0
  38. package/lib/error/eachAsyncMultiError.js +41 -0
  39. package/lib/error/index.js +237 -0
  40. package/lib/error/invalidSchemaOption.js +32 -0
  41. package/lib/error/messages.js +47 -0
  42. package/lib/error/missingSchema.js +33 -0
  43. package/lib/error/mongooseError.js +13 -0
  44. package/lib/error/notFound.js +47 -0
  45. package/lib/error/objectExpected.js +31 -0
  46. package/lib/error/objectParameter.js +31 -0
  47. package/lib/error/overwriteModel.js +31 -0
  48. package/lib/error/parallelSave.js +33 -0
  49. package/lib/error/parallelValidate.js +33 -0
  50. package/lib/error/serverSelection.js +62 -0
  51. package/lib/error/setOptionError.js +103 -0
  52. package/lib/error/strict.js +35 -0
  53. package/lib/error/strictPopulate.js +31 -0
  54. package/lib/error/syncIndexes.js +30 -0
  55. package/lib/error/validation.js +97 -0
  56. package/lib/error/validator.js +100 -0
  57. package/lib/error/version.js +38 -0
  58. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  59. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  60. package/lib/helpers/arrayDepth.js +33 -0
  61. package/lib/helpers/clone.js +204 -0
  62. package/lib/helpers/common.js +127 -0
  63. package/lib/helpers/createJSONSchemaTypeDefinition.js +24 -0
  64. package/lib/helpers/cursor/eachAsync.js +225 -0
  65. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  66. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  67. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  68. package/lib/helpers/discriminator/getConstructor.js +29 -0
  69. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  70. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  71. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +91 -0
  72. package/lib/helpers/document/applyDefaults.js +132 -0
  73. package/lib/helpers/document/applyTimestamps.js +106 -0
  74. package/lib/helpers/document/applyVirtuals.js +147 -0
  75. package/lib/helpers/document/cleanModifiedSubpaths.js +45 -0
  76. package/lib/helpers/document/compile.js +238 -0
  77. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  78. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +53 -0
  79. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  80. package/lib/helpers/each.js +25 -0
  81. package/lib/helpers/error/combinePathErrors.js +22 -0
  82. package/lib/helpers/firstKey.js +8 -0
  83. package/lib/helpers/get.js +65 -0
  84. package/lib/helpers/getConstructorName.js +16 -0
  85. package/lib/helpers/getDefaultBulkwriteResult.js +18 -0
  86. package/lib/helpers/getFunctionName.js +10 -0
  87. package/lib/helpers/immediate.js +16 -0
  88. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  89. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  90. package/lib/helpers/indexes/getRelatedIndexes.js +63 -0
  91. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  92. package/lib/helpers/indexes/isIndexEqual.js +95 -0
  93. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  94. package/lib/helpers/indexes/isTextIndex.js +16 -0
  95. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  96. package/lib/helpers/isAsyncFunction.js +9 -0
  97. package/lib/helpers/isBsonType.js +15 -0
  98. package/lib/helpers/isMongooseObject.js +22 -0
  99. package/lib/helpers/isObject.js +16 -0
  100. package/lib/helpers/isPOJO.js +12 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/minimize.js +41 -0
  104. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  105. package/lib/helpers/model/applyHooks.js +140 -0
  106. package/lib/helpers/model/applyMethods.js +70 -0
  107. package/lib/helpers/model/applyStaticHooks.js +33 -0
  108. package/lib/helpers/model/applyStatics.js +13 -0
  109. package/lib/helpers/model/castBulkWrite.js +316 -0
  110. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  111. package/lib/helpers/model/discriminator.js +265 -0
  112. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  113. package/lib/helpers/omitUndefined.js +20 -0
  114. package/lib/helpers/once.js +12 -0
  115. package/lib/helpers/parallelLimit.js +37 -0
  116. package/lib/helpers/path/parentPaths.js +18 -0
  117. package/lib/helpers/path/setDottedPath.js +33 -0
  118. package/lib/helpers/pluralize.js +95 -0
  119. package/lib/helpers/populate/assignRawDocsToIdStructure.js +129 -0
  120. package/lib/helpers/populate/assignVals.js +360 -0
  121. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  122. package/lib/helpers/populate/getModelsMapForPopulate.js +776 -0
  123. package/lib/helpers/populate/getSchemaTypes.js +228 -0
  124. package/lib/helpers/populate/getVirtual.js +103 -0
  125. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  126. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  127. package/lib/helpers/populate/markArraySubdocsPopulated.js +49 -0
  128. package/lib/helpers/populate/modelNamesFromRefPath.js +66 -0
  129. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  130. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  131. package/lib/helpers/populate/skipPopulateValue.js +10 -0
  132. package/lib/helpers/populate/validateRef.js +19 -0
  133. package/lib/helpers/printJestWarning.js +21 -0
  134. package/lib/helpers/processConnectionOptions.js +65 -0
  135. package/lib/helpers/projection/applyProjection.js +83 -0
  136. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  137. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  138. package/lib/helpers/projection/isExclusive.js +37 -0
  139. package/lib/helpers/projection/isInclusive.js +39 -0
  140. package/lib/helpers/projection/isNestedProjection.js +8 -0
  141. package/lib/helpers/projection/isPathExcluded.js +40 -0
  142. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  143. package/lib/helpers/projection/isSubpath.js +14 -0
  144. package/lib/helpers/projection/parseProjection.js +33 -0
  145. package/lib/helpers/query/applyGlobalOption.js +29 -0
  146. package/lib/helpers/query/cast$expr.js +287 -0
  147. package/lib/helpers/query/castFilterPath.js +54 -0
  148. package/lib/helpers/query/castUpdate.js +643 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +103 -0
  150. package/lib/helpers/query/handleImmutable.js +44 -0
  151. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  152. package/lib/helpers/query/hasDollarKeys.js +23 -0
  153. package/lib/helpers/query/isOperator.js +14 -0
  154. package/lib/helpers/query/sanitizeFilter.js +38 -0
  155. package/lib/helpers/query/sanitizeProjection.js +14 -0
  156. package/lib/helpers/query/selectPopulatedFields.js +62 -0
  157. package/lib/helpers/query/trusted.js +13 -0
  158. package/lib/helpers/query/validOps.js +3 -0
  159. package/lib/helpers/schema/addAutoId.js +7 -0
  160. package/lib/helpers/schema/applyBuiltinPlugins.js +12 -0
  161. package/lib/helpers/schema/applyPlugins.js +55 -0
  162. package/lib/helpers/schema/applyReadConcern.js +20 -0
  163. package/lib/helpers/schema/applyWriteConcern.js +39 -0
  164. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  165. package/lib/helpers/schema/getIndexes.js +171 -0
  166. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  167. package/lib/helpers/schema/getPath.js +43 -0
  168. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  169. package/lib/helpers/schema/handleIdOption.js +20 -0
  170. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  171. package/lib/helpers/schema/idGetter.js +34 -0
  172. package/lib/helpers/schema/merge.js +36 -0
  173. package/lib/helpers/schematype/handleImmutable.js +50 -0
  174. package/lib/helpers/setDefaultsOnInsert.js +158 -0
  175. package/lib/helpers/specialProperties.js +3 -0
  176. package/lib/helpers/symbols.js +20 -0
  177. package/lib/helpers/timers.js +3 -0
  178. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  179. package/lib/helpers/timestamps/setupTimestamps.js +116 -0
  180. package/lib/helpers/topology/allServersUnknown.js +12 -0
  181. package/lib/helpers/topology/isAtlas.js +31 -0
  182. package/lib/helpers/topology/isSSLError.js +16 -0
  183. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  184. package/lib/helpers/update/applyTimestampsToUpdate.js +131 -0
  185. package/lib/helpers/update/castArrayFilters.js +113 -0
  186. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  187. package/lib/helpers/update/modifiedPaths.js +33 -0
  188. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  189. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  190. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  191. package/lib/helpers/updateValidators.js +193 -0
  192. package/lib/index.js +17 -0
  193. package/lib/internal.js +46 -0
  194. package/lib/model.js +5010 -0
  195. package/lib/modifiedPathsSnapshot.js +9 -0
  196. package/lib/mongoose.js +1411 -0
  197. package/lib/options/populateOptions.js +36 -0
  198. package/lib/options/propertyOptions.js +8 -0
  199. package/lib/options/saveOptions.js +16 -0
  200. package/lib/options/schemaArrayOptions.js +78 -0
  201. package/lib/options/schemaBufferOptions.js +38 -0
  202. package/lib/options/schemaDateOptions.js +71 -0
  203. package/lib/options/schemaDocumentArrayOptions.js +68 -0
  204. package/lib/options/schemaMapOptions.js +43 -0
  205. package/lib/options/schemaNumberOptions.js +101 -0
  206. package/lib/options/schemaObjectIdOptions.js +64 -0
  207. package/lib/options/schemaStringOptions.js +138 -0
  208. package/lib/options/schemaSubdocumentOptions.js +66 -0
  209. package/lib/options/schemaTypeOptions.js +244 -0
  210. package/lib/options/schemaUnionOptions.js +32 -0
  211. package/lib/options/virtualOptions.js +164 -0
  212. package/lib/options.js +17 -0
  213. package/lib/plugins/index.js +6 -0
  214. package/lib/plugins/saveSubdocs.js +76 -0
  215. package/lib/plugins/sharding.js +84 -0
  216. package/lib/plugins/trackTransaction.js +84 -0
  217. package/lib/plugins/validateBeforeSave.js +41 -0
  218. package/lib/query.js +5673 -0
  219. package/lib/queryHelpers.js +387 -0
  220. package/lib/schema/array.js +699 -0
  221. package/lib/schema/bigint.js +282 -0
  222. package/lib/schema/boolean.js +332 -0
  223. package/lib/schema/buffer.js +343 -0
  224. package/lib/schema/date.js +467 -0
  225. package/lib/schema/decimal128.js +263 -0
  226. package/lib/schema/documentArray.js +656 -0
  227. package/lib/schema/documentArrayElement.js +137 -0
  228. package/lib/schema/double.js +246 -0
  229. package/lib/schema/index.js +32 -0
  230. package/lib/schema/int32.js +289 -0
  231. package/lib/schema/map.js +201 -0
  232. package/lib/schema/mixed.js +146 -0
  233. package/lib/schema/number.js +510 -0
  234. package/lib/schema/objectId.js +333 -0
  235. package/lib/schema/operators/bitwise.js +38 -0
  236. package/lib/schema/operators/exists.js +12 -0
  237. package/lib/schema/operators/geospatial.js +107 -0
  238. package/lib/schema/operators/helpers.js +32 -0
  239. package/lib/schema/operators/text.js +39 -0
  240. package/lib/schema/operators/type.js +20 -0
  241. package/lib/schema/string.js +733 -0
  242. package/lib/schema/subdocument.js +436 -0
  243. package/lib/schema/symbols.js +5 -0
  244. package/lib/schema/union.js +113 -0
  245. package/lib/schema/uuid.js +305 -0
  246. package/lib/schema.js +3226 -0
  247. package/lib/schemaType.js +1835 -0
  248. package/lib/stateMachine.js +232 -0
  249. package/lib/types/array/index.js +119 -0
  250. package/lib/types/array/isMongooseArray.js +5 -0
  251. package/lib/types/array/methods/index.js +1095 -0
  252. package/lib/types/arraySubdocument.js +207 -0
  253. package/lib/types/buffer.js +294 -0
  254. package/lib/types/decimal128.js +13 -0
  255. package/lib/types/documentArray/index.js +113 -0
  256. package/lib/types/documentArray/isMongooseDocumentArray.js +5 -0
  257. package/lib/types/documentArray/methods/index.js +415 -0
  258. package/lib/types/double.js +13 -0
  259. package/lib/types/index.js +23 -0
  260. package/lib/types/map.js +419 -0
  261. package/lib/types/objectid.js +41 -0
  262. package/lib/types/subdocument.js +464 -0
  263. package/lib/types/uuid.js +13 -0
  264. package/lib/utils.js +1054 -0
  265. package/lib/validOptions.js +42 -0
  266. package/lib/virtualType.js +204 -0
  267. package/package.json +148 -0
  268. package/types/aggregate.d.ts +180 -0
  269. package/types/augmentations.d.ts +9 -0
  270. package/types/callback.d.ts +8 -0
  271. package/types/collection.d.ts +49 -0
  272. package/types/connection.d.ts +297 -0
  273. package/types/cursor.d.ts +67 -0
  274. package/types/document.d.ts +374 -0
  275. package/types/error.d.ts +143 -0
  276. package/types/expressions.d.ts +3053 -0
  277. package/types/helpers.d.ts +32 -0
  278. package/types/index.d.ts +1056 -0
  279. package/types/indexes.d.ts +97 -0
  280. package/types/inferhydrateddoctype.d.ts +115 -0
  281. package/types/inferrawdoctype.d.ts +135 -0
  282. package/types/inferschematype.d.ts +337 -0
  283. package/types/middlewares.d.ts +59 -0
  284. package/types/models.d.ts +1306 -0
  285. package/types/mongooseoptions.d.ts +228 -0
  286. package/types/pipelinestage.d.ts +333 -0
  287. package/types/populate.d.ts +53 -0
  288. package/types/query.d.ts +934 -0
  289. package/types/schemaoptions.d.ts +282 -0
  290. package/types/schematypes.d.ts +654 -0
  291. package/types/session.d.ts +32 -0
  292. package/types/types.d.ts +109 -0
  293. package/types/utility.d.ts +175 -0
  294. package/types/validation.d.ts +39 -0
  295. package/types/virtuals.d.ts +14 -0
@@ -0,0 +1,97 @@
1
+ declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
3
+
4
+ /**
5
+ * Makes the indexes in MongoDB match the indexes defined in every model's
6
+ * schema. This function will drop any indexes that are not defined in
7
+ * the model's schema except the `_id` index, and build any indexes that
8
+ * are in your schema but not in MongoDB.
9
+ */
10
+ function syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
11
+
12
+ interface IndexManager {
13
+ /* Deletes all indexes that aren't defined in this model's schema. Used by `syncIndexes()`. Returns list of dropped index names. */
14
+ cleanIndexes(options?: { toDrop?: string[], hideIndexes?: boolean }): Promise<string[]>;
15
+
16
+ /**
17
+ * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#createIndex)
18
+ * function.
19
+ */
20
+ createIndexes(options?: mongodb.CreateIndexesOptions): Promise<void>;
21
+
22
+ /**
23
+ * Does a dry-run of Model.syncIndexes(), meaning that
24
+ * the result of this function would be the result of
25
+ * Model.syncIndexes().
26
+ */
27
+ diffIndexes(options?: Record<string, unknown>): Promise<IndexesDiff>
28
+
29
+ /**
30
+ * Sends `createIndex` commands to mongo for each index declared in the schema.
31
+ * The `createIndex` commands are sent in series.
32
+ */
33
+ ensureIndexes(options?: mongodb.CreateIndexesOptions): Promise<void>;
34
+
35
+ /**
36
+ * Lists the indexes currently defined in MongoDB. This may or may not be
37
+ * the same as the indexes defined in your schema depending on whether you
38
+ * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
39
+ * build indexes manually.
40
+ */
41
+ listIndexes(): Promise<Array<any>>;
42
+
43
+ /**
44
+ * Makes the indexes in MongoDB match the indexes defined in this model's
45
+ * schema. This function will drop any indexes that are not defined in
46
+ * the model's schema except the `_id` index, and build any indexes that
47
+ * are in your schema but not in MongoDB.
48
+ */
49
+ syncIndexes(options?: SyncIndexesOptions): Promise<Array<string>>;
50
+ }
51
+
52
+ interface IndexesDiff {
53
+ /** Indexes that would be created in mongodb. */
54
+ toCreate: Array<any>
55
+ /** Indexes that would be dropped in mongodb. */
56
+ toDrop: Array<any>
57
+ }
58
+
59
+ type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text' | 'ascending' | 'asc' | 'descending' | 'desc';
60
+ type IndexDefinition = Record<string, IndexDirection>;
61
+
62
+ interface SyncIndexesOptions extends mongodb.CreateIndexesOptions {
63
+ continueOnError?: boolean;
64
+ hideIndexes?: boolean;
65
+ }
66
+ type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
67
+ type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
68
+
69
+ type IndexOptions = Omit<mongodb.CreateIndexesOptions, 'expires' | 'weights' | 'unique'> & {
70
+ /**
71
+ * `expires` utilizes the `ms` module from [vercel](https://github.com/vercel/ms) allowing us to use a friendlier syntax:
72
+ *
73
+ * @example
74
+ * ```js
75
+ * const schema = new Schema({ prop1: Date });
76
+ *
77
+ * // expire in 24 hours
78
+ * schema.index({ prop1: 1 }, { expires: 60*60*24 })
79
+ *
80
+ * // expire in 24 hours
81
+ * schema.index({ prop1: 1 }, { expires: '24h' })
82
+ *
83
+ * // expire in 1.5 hours
84
+ * schema.index({ prop1: 1 }, { expires: '1.5h' })
85
+ *
86
+ * // expire in 7 days
87
+ * schema.index({ prop1: 1 }, { expires: '7d' })
88
+ * ```
89
+ */
90
+ expires?: number | string;
91
+ weights?: Record<string, number>;
92
+
93
+ unique?: boolean | [true, string]
94
+ };
95
+
96
+ type SearchIndexDescription = mongodb.SearchIndexDescription;
97
+ }
@@ -0,0 +1,115 @@
1
+ import {
2
+ IsPathRequired,
3
+ IsSchemaTypeFromBuiltinClass,
4
+ RequiredPaths,
5
+ OptionalPaths,
6
+ PathEnumOrString
7
+ } from './inferschematype';
8
+ import { UUID } from 'mongodb';
9
+
10
+ declare module 'mongoose' {
11
+ export type InferHydratedDocTypeFromSchema<TSchema extends Schema<any>> = ObtainSchemaGeneric<TSchema, 'THydratedDocumentType'>;
12
+
13
+ /**
14
+ * Given a schema definition, returns the hydrated document type from the schema definition.
15
+ */
16
+ export type InferHydratedDocType<
17
+ DocDefinition,
18
+ TSchemaOptions extends Record<any, any> = DefaultSchemaOptions
19
+ > = Require_id<ApplySchemaOptions<{
20
+ [
21
+ K in keyof (RequiredPaths<DocDefinition, TSchemaOptions['typeKey']> &
22
+ OptionalPaths<DocDefinition, TSchemaOptions['typeKey']>)
23
+ ]: IsPathRequired<DocDefinition[K], TSchemaOptions['typeKey']> extends true
24
+ ? ObtainHydratedDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']>
25
+ : ObtainHydratedDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']> | null;
26
+ }, TSchemaOptions>>;
27
+
28
+ /**
29
+ * @summary Obtains schema Path type.
30
+ * @description Obtains Path type by separating path type from other options and calling {@link ResolveHydratedPathType}
31
+ * @param {PathValueType} PathValueType Document definition path type.
32
+ * @param {TypeKey} TypeKey A generic refers to document definition.
33
+ */
34
+ type ObtainHydratedDocumentPathType<
35
+ PathValueType,
36
+ TypeKey extends string = DefaultTypeKey
37
+ > = ResolveHydratedPathType<
38
+ TypeKey extends keyof PathValueType
39
+ ? TypeKey extends keyof PathValueType[TypeKey]
40
+ ? PathValueType
41
+ : PathValueType[TypeKey]
42
+ : PathValueType,
43
+ TypeKey extends keyof PathValueType
44
+ ? TypeKey extends keyof PathValueType[TypeKey]
45
+ ? {}
46
+ : Omit<PathValueType, TypeKey>
47
+ : {},
48
+ TypeKey,
49
+ HydratedDocTypeHint<PathValueType>
50
+ >;
51
+
52
+ /**
53
+ * @summary Allows users to optionally choose their own type for a schema field for stronger typing.
54
+ */
55
+ type HydratedDocTypeHint<T> = T extends { __hydratedDocTypeHint: infer U } ? U: never;
56
+
57
+ /**
58
+ * Same as inferSchemaType, except:
59
+ *
60
+ * 1. Replace `Types.DocumentArray` and `Types.Array` with vanilla `Array`
61
+ * 2. Replace `ObtainDocumentPathType` with `ObtainHydratedDocumentPathType`
62
+ * 3. Replace `ResolvePathType` with `ResolveHydratedPathType`
63
+ *
64
+ * @summary Resolve path type by returning the corresponding type.
65
+ * @param {PathValueType} PathValueType Document definition path type.
66
+ * @param {Options} Options Document definition path options except path type.
67
+ * @param {TypeKey} TypeKey A generic of literal string type. Refers to the property used for path type definition.
68
+ * @returns Type
69
+ */
70
+ type ResolveHydratedPathType<PathValueType, Options extends SchemaTypeOptions<PathValueType> = {}, TypeKey extends string = DefaultSchemaOptions['typeKey'], TypeHint = never> =
71
+ IsNotNever<TypeHint> extends true ? TypeHint
72
+ : PathValueType extends Schema<any, any, any, any, any, any, any, any, infer THydratedDocumentType> ?
73
+ THydratedDocumentType :
74
+ PathValueType extends AnyArray<infer Item> ?
75
+ IfEquals<Item, never, any[], Item extends Schema<infer EmbeddedRawDocType, any, any, any, any, any, any, any, infer EmbeddedHydratedDocType extends AnyObject, infer TSchemaDefition> ?
76
+ IsItRecordAndNotAny<EmbeddedRawDocType> extends true ?
77
+ Types.DocumentArray<EmbeddedRawDocType, Types.Subdocument<EmbeddedHydratedDocType['_id'], unknown, EmbeddedHydratedDocType> & EmbeddedHydratedDocType> :
78
+ Types.DocumentArray<InferRawDocType<TSchemaDefition>, Types.Subdocument<InferHydratedDocType<TSchemaDefition>['_id'], unknown, InferHydratedDocType<TSchemaDefition>> & InferHydratedDocType<TSchemaDefition>> :
79
+ Item extends Record<TypeKey, any> ?
80
+ Item[TypeKey] extends Function | String ?
81
+ Types.Array<ObtainHydratedDocumentPathType<Item, TypeKey>> :
82
+ Types.DocumentArray<
83
+ InferRawDocType<Item>,
84
+ Types.Subdocument<InferHydratedDocType<Item>['_id'], unknown, InferHydratedDocType<Item>> & InferHydratedDocType<Item>
85
+ >:
86
+ IsSchemaTypeFromBuiltinClass<Item> extends true ?
87
+ Types.Array<ResolveHydratedPathType<Item, { enum: Options['enum'] }, TypeKey>> :
88
+ IsItRecordAndNotAny<Item> extends true ?
89
+ Item extends Record<string, never> ?
90
+ Types.Array<ObtainHydratedDocumentPathType<Item, TypeKey>> :
91
+ Types.DocumentArray<
92
+ InferRawDocType<Item>,
93
+ Types.Subdocument<InferHydratedDocType<Item>['_id'], unknown, InferHydratedDocType<Item>> & InferHydratedDocType<Item>
94
+ > :
95
+ Types.Array<ObtainHydratedDocumentPathType<Item, TypeKey>>
96
+ >
97
+ : PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']>
98
+ : IfEquals<PathValueType, String> extends true ? PathEnumOrString<Options['enum']>
99
+ : PathValueType extends NumberSchemaDefinition ? Options['enum'] extends ReadonlyArray<any> ? Options['enum'][number] : number
100
+ : PathValueType extends DateSchemaDefinition ? NativeDate
101
+ : PathValueType extends BufferSchemaDefinition ? Buffer
102
+ : PathValueType extends BooleanSchemaDefinition ? boolean
103
+ : PathValueType extends ObjectIdSchemaDefinition ? Types.ObjectId
104
+ : PathValueType extends Decimal128SchemaDefinition ? Types.Decimal128
105
+ : PathValueType extends BigintSchemaDefinition ? bigint
106
+ : PathValueType extends UuidSchemaDefinition ? UUID
107
+ : PathValueType extends DoubleSchemaDefinition ? Types.Double
108
+ : PathValueType extends typeof Schema.Types.Mixed ? any
109
+ : PathValueType extends MapSchemaDefinition ? Map<string, ObtainHydratedDocumentPathType<Options['of']>>
110
+ : IfEquals<PathValueType, ObjectConstructor> extends true ? any
111
+ : PathValueType extends typeof SchemaType ? PathValueType['prototype']
112
+ : PathValueType extends ArrayConstructor ? Types.Array<any>
113
+ : PathValueType extends Record<string, any> ? InferHydratedDocType<PathValueType, { typeKey: TypeKey }>
114
+ : unknown;
115
+ }
@@ -0,0 +1,135 @@
1
+ import {
2
+ IsSchemaTypeFromBuiltinClass,
3
+ PathEnumOrString,
4
+ OptionalPaths,
5
+ RequiredPaths,
6
+ IsPathRequired
7
+ } from './inferschematype';
8
+ import { Binary, UUID } from 'mongodb';
9
+
10
+ declare module 'mongoose' {
11
+ export type InferRawDocTypeFromSchema<TSchema extends Schema<any>> = IsItRecordAndNotAny<ObtainSchemaGeneric<TSchema, 'EnforcedDocType'>> extends true
12
+ ? ObtainSchemaGeneric<TSchema, 'EnforcedDocType'>
13
+ : FlattenMaps<SubdocsToPOJOs<ObtainSchemaGeneric<TSchema, 'DocType'>>>;
14
+
15
+ export type InferRawDocTypeWithout_id<
16
+ SchemaDefinition,
17
+ TSchemaOptions extends Record<any, any> = DefaultSchemaOptions,
18
+ TTransformOptions = { bufferToBinary: false }
19
+ > = ApplySchemaOptions<{
20
+ [
21
+ K in keyof (RequiredPaths<SchemaDefinition, TSchemaOptions['typeKey']> &
22
+ OptionalPaths<SchemaDefinition, TSchemaOptions['typeKey']>)
23
+ ]: IsPathRequired<SchemaDefinition[K], TSchemaOptions['typeKey']> extends true
24
+ ? ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions>
25
+ : ObtainRawDocumentPathType<SchemaDefinition[K], TSchemaOptions['typeKey'], TTransformOptions> | null;
26
+ }, TSchemaOptions>;
27
+
28
+ export type InferRawDocType<
29
+ SchemaDefinition,
30
+ TSchemaOptions extends Record<any, any> = DefaultSchemaOptions,
31
+ TTransformOptions = { bufferToBinary: false }
32
+ > = Require_id<InferRawDocTypeWithout_id<SchemaDefinition, TSchemaOptions, TTransformOptions>>;
33
+
34
+ /**
35
+ * @summary Allows users to optionally choose their own type for a schema field for stronger typing.
36
+ * Make sure to check for `any` because `T extends { __rawDocTypeHint: infer U }` will infer `unknown` if T is `any`.
37
+ */
38
+ type RawDocTypeHint<T> = IsAny<T> extends true ? never
39
+ : T extends { __rawDocTypeHint: infer U } ? U: never;
40
+
41
+ /**
42
+ * @summary Obtains schema Path type.
43
+ * @description Obtains Path type by separating path type from other options and calling {@link ResolveRawPathType}
44
+ * @param {PathValueType} PathValueType Document definition path type.
45
+ * @param {TypeKey} TypeKey A generic refers to document definition.
46
+ */
47
+ type ObtainRawDocumentPathType<
48
+ PathValueType,
49
+ TypeKey extends string = DefaultTypeKey,
50
+ TTransformOptions = { bufferToBinary: false }
51
+ > = ResolveRawPathType<
52
+ TypeKey extends keyof PathValueType ?
53
+ TypeKey extends keyof PathValueType[TypeKey] ?
54
+ PathValueType
55
+ : PathValueType[TypeKey]
56
+ : PathValueType,
57
+ TypeKey extends keyof PathValueType ?
58
+ TypeKey extends keyof PathValueType[TypeKey] ?
59
+ {}
60
+ : Omit<PathValueType, TypeKey>
61
+ : {},
62
+ TypeKey,
63
+ TTransformOptions,
64
+ RawDocTypeHint<PathValueType>
65
+ >;
66
+
67
+ type neverOrAny = ' ~neverOrAny~';
68
+
69
+ /**
70
+ * Same as inferSchemaType, except:
71
+ *
72
+ * 1. Replace `Types.DocumentArray` and `Types.Array` with vanilla `Array`
73
+ * 2. Replace `ObtainDocumentPathType` with `ObtainRawDocumentPathType`
74
+ * 3. Replace `ResolvePathType` with `ResolveRawPathType`
75
+ *
76
+ * @summary Resolve path type by returning the corresponding type.
77
+ * @param {PathValueType} PathValueType Document definition path type.
78
+ * @param {Options} Options Document definition path options except path type.
79
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
80
+ * @returns Number, "Number" or "number" will be resolved to number type.
81
+ */
82
+ type ResolveRawPathType<
83
+ PathValueType,
84
+ Options extends SchemaTypeOptions<PathValueType> = {},
85
+ TypeKey extends string = DefaultSchemaOptions['typeKey'],
86
+ TTransformOptions = { bufferToBinary: false },
87
+ TypeHint = never
88
+ > =
89
+ IsNotNever<TypeHint> extends true ? TypeHint
90
+ : [PathValueType] extends [neverOrAny] ? PathValueType
91
+ : PathValueType extends Schema<infer RawDocType, any, any, any, any, any, any, any, any, infer TSchemaDefinition> ? IsItRecordAndNotAny<RawDocType> extends true ? RawDocType : InferRawDocType<TSchemaDefinition, DefaultSchemaOptions, TTransformOptions>
92
+ : PathValueType extends ReadonlyArray<infer Item> ?
93
+ IfEquals<Item, never> extends true ? any[]
94
+ : Item extends Schema<infer RawDocType, any, any, any, any, any, any, any, any, infer TSchemaDefinition> ?
95
+ // If Item is a schema, infer its type.
96
+ Array<IsItRecordAndNotAny<RawDocType> extends true ? RawDocType : InferRawDocType<TSchemaDefinition, DefaultSchemaOptions, TTransformOptions>>
97
+ : TypeKey extends keyof Item ?
98
+ Item[TypeKey] extends Function | String ?
99
+ // If Item has a type key that's a string or a callable, it must be a scalar,
100
+ // so we can directly obtain its path type.
101
+ ObtainRawDocumentPathType<Item, TypeKey, TTransformOptions>[]
102
+ : // If the type key isn't callable, then this is an array of objects, in which case
103
+ // we need to call InferRawDocType to correctly infer its type.
104
+ Array<InferRawDocType<Item, DefaultSchemaOptions, TTransformOptions>>
105
+ : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolveRawPathType<Item, { enum: Options['enum'] }, TypeKey, TTransformOptions>[]
106
+ : IsItRecordAndNotAny<Item> extends true ?
107
+ Item extends Record<string, never> ?
108
+ ObtainRawDocumentPathType<Item, TypeKey, TTransformOptions>[]
109
+ : Array<InferRawDocType<Item, DefaultSchemaOptions, TTransformOptions>>
110
+ : ObtainRawDocumentPathType<Item, TypeKey, TTransformOptions>[]
111
+ : PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']>
112
+ : IfEquals<PathValueType, String> extends true ? PathEnumOrString<Options['enum']>
113
+ : PathValueType extends NumberSchemaDefinition ?
114
+ Options['enum'] extends ReadonlyArray<any> ?
115
+ Options['enum'][number]
116
+ : number
117
+ : PathValueType extends DateSchemaDefinition ? NativeDate
118
+ : PathValueType extends BufferSchemaDefinition ? (TTransformOptions extends { bufferToBinary: true } ? Binary : Buffer)
119
+ : PathValueType extends BooleanSchemaDefinition ? boolean
120
+ : PathValueType extends ObjectIdSchemaDefinition ? Types.ObjectId
121
+ : PathValueType extends Decimal128SchemaDefinition ? Types.Decimal128
122
+ : PathValueType extends BigintSchemaDefinition ? bigint
123
+ : PathValueType extends UuidSchemaDefinition ? Types.UUID
124
+ : PathValueType extends MapSchemaDefinition ? Record<string, ObtainRawDocumentPathType<Options['of'], TypeKey, TTransformOptions>>
125
+ : PathValueType extends DoubleSchemaDefinition ? Types.Double
126
+ : PathValueType extends UnionSchemaDefinition ?
127
+ ResolveRawPathType<Options['of'] extends ReadonlyArray<infer Item> ? Item : never>
128
+ : PathValueType extends ArrayConstructor ? any[]
129
+ : PathValueType extends typeof Schema.Types.Mixed ? any
130
+ : IfEquals<PathValueType, ObjectConstructor> extends true ? any
131
+ : IfEquals<PathValueType, {}> extends true ? any
132
+ : PathValueType extends typeof SchemaType ? PathValueType['prototype']
133
+ : PathValueType extends Record<string, any> ? InferRawDocType<PathValueType>
134
+ : unknown;
135
+ }
@@ -0,0 +1,337 @@
1
+ import {
2
+ AnyArray,
3
+ BooleanSchemaDefinition,
4
+ BigintSchemaDefinition,
5
+ BufferSchemaDefinition,
6
+ DateSchemaDefinition,
7
+ Decimal128SchemaDefinition,
8
+ DefaultSchemaOptions,
9
+ DefaultTypeKey,
10
+ DoubleSchemaDefinition,
11
+ IfEquals,
12
+ InferSchemaType,
13
+ IsItRecordAndNotAny,
14
+ MapSchemaDefinition,
15
+ NumberSchemaDefinition,
16
+ ObjectIdSchemaDefinition,
17
+ ObtainDocumentType,
18
+ Schema,
19
+ SchemaType,
20
+ SchemaTypeOptions,
21
+ StringSchemaDefinition,
22
+ Types,
23
+ UnionSchemaDefinition,
24
+ UuidSchemaDefinition
25
+ } from 'mongoose';
26
+
27
+ declare module 'mongoose' {
28
+ /**
29
+ * @summary Obtains document schema type.
30
+ * @description Obtains document schema type from document Definition OR returns enforced schema type if it's provided.
31
+ * @param {DocDefinition} DocDefinition A generic equals to the type of document definition "provided in as first parameter in Schema constructor".
32
+ * @param {EnforcedDocType} EnforcedDocType A generic type enforced by user "provided before schema constructor".
33
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
34
+ */
35
+ type ObtainDocumentType<
36
+ DocDefinition,
37
+ EnforcedDocType = any,
38
+ TSchemaOptions extends Record<any, any> = DefaultSchemaOptions
39
+ > =
40
+ IsItRecordAndNotAny<EnforcedDocType> extends true ? EnforcedDocType
41
+ : {
42
+ [K in keyof (RequiredPaths<DocDefinition, TSchemaOptions['typeKey']> &
43
+ OptionalPaths<DocDefinition, TSchemaOptions['typeKey']>)]: IsPathRequired<
44
+ DocDefinition[K],
45
+ TSchemaOptions['typeKey']
46
+ > extends true ?
47
+ ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']>
48
+ : ObtainDocumentPathType<DocDefinition[K], TSchemaOptions['typeKey']> | null;
49
+ };
50
+
51
+ /**
52
+ * @summary Obtains document schema type from Schema instance.
53
+ * @param {Schema} TSchema `typeof` a schema instance.
54
+ * @example
55
+ * const userSchema = new Schema({userName:String});
56
+ * type UserType = InferSchemaType<typeof userSchema>;
57
+ * // result
58
+ * type UserType = {userName?: string}
59
+ */
60
+ export type InferSchemaType<TSchema> = IfAny<TSchema, any, ObtainSchemaGeneric<TSchema, 'DocType'>>;
61
+
62
+ export type DefaultIdVirtual = { id: string };
63
+ export type AddDefaultId<DocType, TVirtuals, TSchemaOptions> = (DocType extends { id: any } ? TVirtuals : TSchemaOptions extends { id: false } ? TVirtuals : TVirtuals & { id: string });
64
+
65
+ /**
66
+ * @summary Obtains schema Generic type by using generic alias.
67
+ * @param {TSchema} TSchema A generic of schema type instance.
68
+ * @param {alias} alias Targeted generic alias.
69
+ */
70
+ type ObtainSchemaGeneric<
71
+ TSchema,
72
+ alias extends
73
+ | 'EnforcedDocType'
74
+ | 'M'
75
+ | 'TInstanceMethods'
76
+ | 'TQueryHelpers'
77
+ | 'TVirtuals'
78
+ | 'TStaticMethods'
79
+ | 'TSchemaOptions'
80
+ | 'DocType'
81
+ | 'THydratedDocumentType'
82
+ | 'TSchemaDefinition'
83
+ | 'TLeanResultType'
84
+ > =
85
+ TSchema extends (
86
+ Schema<
87
+ infer EnforcedDocType,
88
+ infer M,
89
+ infer TInstanceMethods,
90
+ infer TQueryHelpers,
91
+ infer TVirtuals,
92
+ infer TStaticMethods,
93
+ infer TSchemaOptions,
94
+ infer DocType,
95
+ infer THydratedDocumentType,
96
+ infer TSchemaDefinition,
97
+ infer TLeanResultType
98
+ >
99
+ ) ?
100
+ {
101
+ EnforcedDocType: EnforcedDocType;
102
+ M: M;
103
+ TInstanceMethods: IfEquals<TInstanceMethods, {}, TSchemaOptions extends { methods: infer M } ? M : {}, TInstanceMethods>;
104
+ TQueryHelpers: IfEquals<TQueryHelpers, {}, TSchemaOptions extends { query: infer Q } ? Q : {}, TQueryHelpers>;
105
+ TVirtuals: AddDefaultId<DocType, IfEquals<TVirtuals, {}, TSchemaOptions extends { virtuals: infer V } ? V : {}, TVirtuals>, TSchemaOptions>;
106
+ TStaticMethods: IfEquals<TStaticMethods, {}, TSchemaOptions extends { statics: infer S } ? S : {}, TStaticMethods>;
107
+ TSchemaOptions: TSchemaOptions;
108
+ DocType: DocType;
109
+ THydratedDocumentType: THydratedDocumentType;
110
+ TSchemaDefinition: TSchemaDefinition;
111
+ TLeanResultType: TLeanResultType;
112
+ }[alias]
113
+ : unknown;
114
+
115
+ type ResolveSchemaOptions<T> = MergeType<DefaultSchemaOptions, T>;
116
+
117
+ type ApplySchemaOptions<T, O = DefaultSchemaOptions> = ResolveTimestamps<T, O>;
118
+
119
+ type DefaultTimestampProps = {
120
+ createdAt: NativeDate;
121
+ updatedAt: NativeDate;
122
+ };
123
+
124
+ type ResolveTimestamps<T, O> =
125
+ O extends { timestamps?: false } ? T
126
+ : O extends { timestamps: infer TimestampOptions } ?
127
+ TimestampOptions extends true ? T & DefaultTimestampProps
128
+ : TimestampOptions extends SchemaTimestampsConfig ?
129
+ Show<
130
+ T & {
131
+ [K in keyof TimestampOptions & keyof DefaultTimestampProps as TimestampOptions[K] extends true ? K
132
+ : TimestampOptions[K] & string]: NativeDate;
133
+ }
134
+ >
135
+ : T
136
+ : T;
137
+ }
138
+
139
+ type RequiredPropertyDefinition =
140
+ | {
141
+ required: true | string | [true, string | undefined] | { isRequired: true };
142
+ }
143
+ | ArrayConstructor
144
+ | any[];
145
+
146
+ /**
147
+ * @summary Checks if a document path is required or optional.
148
+ * @param {P} P Document path.
149
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
150
+ */
151
+ type IsPathRequired<P, TypeKey extends string = DefaultTypeKey> =
152
+ P extends RequiredPropertyDefinition ? true
153
+ : P extends { required: boolean } ?
154
+ P extends { required: false } ?
155
+ false
156
+ : true
157
+ : P extends { default: undefined | null | ((...args: any[]) => undefined) | ((...args: any[]) => null) } ? false
158
+ : P extends { default: any } ? true
159
+ : P extends Record<TypeKey, ArrayConstructor | any[]> ? true
160
+ : false;
161
+
162
+ // Internal type used to efficiently check for never or any types
163
+ // can be efficiently checked like:
164
+ // `[T] extends [neverOrAny] ? T : ...`
165
+ // to avoid edge cases
166
+ type neverOrAny = ' ~neverOrAny~';
167
+
168
+ /**
169
+ * @summary A Utility to obtain schema's required path keys.
170
+ * @param {T} T A generic refers to document definition.
171
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
172
+ * @returns required paths keys of document definition.
173
+ */
174
+ type RequiredPathKeys<T, TypeKey extends string = DefaultTypeKey> = Exclude<keyof T, OptionalPathKeys<T, TypeKey>>;
175
+
176
+ /**
177
+ * @summary A Utility to obtain schema's required paths.
178
+ * @param {T} T A generic refers to document definition.
179
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
180
+ * @returns a record contains required paths with the corresponding type.
181
+ */
182
+ type RequiredPaths<T, TypeKey extends string = DefaultTypeKey> = Pick<
183
+ { -readonly [K in keyof T]: T[K] },
184
+ RequiredPathKeys<T, TypeKey>
185
+ >;
186
+
187
+ /**
188
+ * @summary A Utility to obtain schema's optional path keys.
189
+ * @param {T} T A generic refers to document definition.
190
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
191
+ * @returns optional paths keys of document definition.
192
+ */
193
+ type OptionalPathKeys<T, TypeKey extends string = DefaultTypeKey> = {
194
+ [K in keyof T]: IsPathRequired<T[K], TypeKey> extends true ? never : K;
195
+ }[keyof T];
196
+
197
+ /**
198
+ * @summary A Utility to obtain schema's optional paths.
199
+ * @param {T} T A generic refers to document definition.
200
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
201
+ * @returns a record contains optional paths with the corresponding type.
202
+ */
203
+ type OptionalPaths<T, TypeKey extends string = DefaultTypeKey> = Pick<
204
+ { -readonly [K in keyof T]?: T[K] },
205
+ OptionalPathKeys<T, TypeKey>
206
+ >;
207
+
208
+ /**
209
+ * @summary Allows users to optionally choose their own type for a schema field for stronger typing.
210
+ */
211
+ type TypeHint<T> = T extends { __typehint: infer U } ? U : never;
212
+
213
+ /**
214
+ * @summary Obtains schema Path type.
215
+ * @description Obtains Path type by separating path type from other options and calling {@link ResolvePathType}
216
+ * @param {PathValueType} PathValueType Document definition path type.
217
+ * @param {TypeKey} TypeKey A generic refers to document definition.
218
+ */
219
+ type ObtainDocumentPathType<PathValueType, TypeKey extends string = DefaultTypeKey> = ResolvePathType<
220
+ TypeKey extends keyof PathValueType ?
221
+ TypeKey extends keyof PathValueType[TypeKey] ?
222
+ PathValueType
223
+ : PathValueType[TypeKey]
224
+ : PathValueType,
225
+ TypeKey extends keyof PathValueType ?
226
+ TypeKey extends keyof PathValueType[TypeKey] ?
227
+ {}
228
+ : Omit<PathValueType, TypeKey>
229
+ : {},
230
+ TypeKey,
231
+ TypeHint<PathValueType>
232
+ >;
233
+
234
+ /**
235
+ * @param {T} T A generic refers to string path enums.
236
+ * @returns Path enum values type as literal strings or string.
237
+ */
238
+ type PathEnumOrString<T extends SchemaTypeOptions<string>['enum']> =
239
+ T extends ReadonlyArray<infer E> ? E
240
+ : T extends { values: any } ? PathEnumOrString<T['values']>
241
+ : T extends Record<string, infer V> ? V
242
+ : string;
243
+
244
+ type UnionToType<T extends readonly any[]> = T[number] extends infer U
245
+ ? ResolvePathType<U>
246
+ : never;
247
+
248
+ type IsSchemaTypeFromBuiltinClass<T> =
249
+ T extends typeof String ? true
250
+ : unknown extends Buffer ? false
251
+ : T extends typeof Number ? true
252
+ : T extends typeof Boolean ? true
253
+ : T extends typeof Buffer ? true
254
+ : T extends typeof Schema.Types.ObjectId ? true
255
+ : T extends typeof Schema.Types.UUID ? true
256
+ : T extends typeof Schema.Types.Decimal128 ? true
257
+ : T extends typeof Schema.Types.Int32 ? true
258
+ : T extends typeof Schema.Types.String ? true
259
+ : T extends typeof Schema.Types.Number ? true
260
+ : T extends typeof Schema.Types.Date ? true
261
+ : T extends typeof Schema.Types.Double ? true
262
+ : T extends typeof Schema.Types.Boolean ? true
263
+ : T extends Types.ObjectId ? true
264
+ : T extends Types.Decimal128 ? true
265
+ : T extends NativeDate ? true
266
+ : T extends typeof Schema.Types.Mixed ? true
267
+ : T extends Types.UUID ? true
268
+ : T extends Buffer ? true
269
+ : false;
270
+
271
+ /**
272
+ * @summary Resolve path type by returning the corresponding type.
273
+ * @param {PathValueType} PathValueType Document definition path type.
274
+ * @param {Options} Options Document definition path options except path type.
275
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
276
+ * @returns Number, "Number" or "number" will be resolved to number type.
277
+ */
278
+ type ResolvePathType<
279
+ PathValueType,
280
+ Options extends SchemaTypeOptions<PathValueType> = {},
281
+ TypeKey extends string = DefaultSchemaOptions['typeKey'],
282
+ TypeHint = never
283
+ > = [TypeHint] extends [never]
284
+ ? PathValueType extends Schema ? InferSchemaType<PathValueType>
285
+ : PathValueType extends AnyArray<infer Item> ?
286
+ [Item] extends [never]
287
+ ? any[]
288
+ : Item extends Schema ?
289
+ // If Item is a schema, infer its type.
290
+ Types.DocumentArray<InferSchemaType<Item>>
291
+ : Item extends Record<TypeKey, any> ?
292
+ Item[TypeKey] extends Function | String ?
293
+ // If Item has a type key that's a string or a callable, it must be a scalar,
294
+ // so we can directly obtain its path type.
295
+ ObtainDocumentPathType<Item, TypeKey>[]
296
+ : // If the type key isn't callable, then this is an array of objects, in which case
297
+ // we need to call ObtainDocumentType to correctly infer its type.
298
+ Types.DocumentArray<ObtainDocumentType<Item, any, { typeKey: TypeKey }>>
299
+ : IsSchemaTypeFromBuiltinClass<Item> extends true ? ResolvePathType<Item, { enum: Options['enum'] }, TypeKey>[]
300
+ : IsItRecordAndNotAny<Item> extends true ?
301
+ Item extends Record<string, never> ?
302
+ ObtainDocumentPathType<Item, TypeKey>[]
303
+ : Types.DocumentArray<ObtainDocumentType<Item, any, { typeKey: TypeKey }>>
304
+ : ObtainDocumentPathType<Item, TypeKey>[]
305
+ : PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']>
306
+ : IfEquals<PathValueType, String> extends true ? PathEnumOrString<Options['enum']>
307
+ : PathValueType extends NumberSchemaDefinition ?
308
+ Options['enum'] extends ReadonlyArray<any> ?
309
+ Options['enum'][number]
310
+ : number
311
+ : PathValueType extends DateSchemaDefinition ? NativeDate
312
+ : PathValueType extends UuidSchemaDefinition ? Types.UUID
313
+ : PathValueType extends BufferSchemaDefinition ? Buffer
314
+ : PathValueType extends BooleanSchemaDefinition ? boolean
315
+ : PathValueType extends ObjectIdSchemaDefinition ? Types.ObjectId
316
+ : PathValueType extends Decimal128SchemaDefinition ? Types.Decimal128
317
+ : PathValueType extends BigintSchemaDefinition ? bigint
318
+ : PathValueType extends DoubleSchemaDefinition ? Types.Double
319
+ : PathValueType extends MapSchemaDefinition ? Map<string, ObtainDocumentPathType<Options['of']>>
320
+ : PathValueType extends UnionSchemaDefinition ?
321
+ Options['of'] extends AnyArray<infer U> ? ResolvePathType<U>
322
+ : never
323
+ : PathValueType extends ArrayConstructor ? any[]
324
+ : PathValueType extends typeof Schema.Types.Mixed ? any
325
+ : PathValueType extends ObjectConstructor ? any
326
+ : IfEquals<PathValueType, {}> extends true ? any
327
+ : PathValueType extends typeof SchemaType ? PathValueType['prototype']
328
+ : PathValueType extends Record<string, any> ?
329
+ ObtainDocumentType<
330
+ PathValueType,
331
+ any,
332
+ {
333
+ typeKey: TypeKey;
334
+ }
335
+ >
336
+ : unknown
337
+ : TypeHint;