mongoose-utility-kit 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ # Changesets
2
+
3
+ Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4
+ with multi-package repos, or single-package repos to help you version and publish your code. You can
5
+ find the full documentation for it [in our repository](https://github.com/changesets/changesets)
6
+
7
+ We have a quick list of common questions to get you started engaging with this project in
8
+ [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
@@ -0,0 +1,11 @@
1
+ {
2
+ "$schema": "https://unpkg.com/@changesets/config@3.1.0/schema.json",
3
+ "changelog": "@changesets/cli/changelog",
4
+ "commit": true,
5
+ "fixed": [],
6
+ "linked": [],
7
+ "access": "public",
8
+ "baseBranch": "main",
9
+ "updateInternalDependencies": "patch",
10
+ "ignore": []
11
+ }
package/.eslintrc.cjs ADDED
@@ -0,0 +1,43 @@
1
+ module.exports = {
2
+ env: {
3
+ es2021: true,
4
+ node: true,
5
+ jest: true,
6
+ },
7
+ extends: ['airbnb-base'],
8
+ parser: '@typescript-eslint/parser',
9
+ parserOptions: {
10
+ ecmaVersion: 'latest',
11
+ sourceType: 'module',
12
+ },
13
+ settings: {
14
+ 'import/resolver': {
15
+ node: {
16
+ extensions: ['.js', '.jsx', '.ts', '.tsx'],
17
+ },
18
+ },
19
+ },
20
+ plugins: ['@typescript-eslint'],
21
+ rules: {
22
+ 'brace-style': [2, 'stroustrup'],
23
+ 'import/extensions': [
24
+ 'error',
25
+ 'always',
26
+ {
27
+ js: 'never',
28
+ jsx: 'never',
29
+ ts: 'never',
30
+ tsx: 'never',
31
+ },
32
+ ],
33
+ 'no-unused-vars': 'off',
34
+ '@typescript-eslint/no-unused-vars': ['warn'],
35
+ 'no-underscore-dangle': 'off',
36
+ 'no-shadow': 'off',
37
+ '@typescript-eslint/no-shadow': ['error'],
38
+ 'no-plusplus': 'off',
39
+ 'require-await': 'warn',
40
+ curly: ['warn', 'all'],
41
+ 'func-names': 'off',
42
+ },
43
+ };
@@ -0,0 +1,29 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches:
7
+ - main
8
+
9
+ concurrency:
10
+ group: ${{ github.workflow }}-${{ github.ref }}
11
+ cancel-in-progress: true
12
+
13
+ jobs:
14
+ ci:
15
+ runs-on: ubuntu-latest
16
+
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+
20
+ - name: Use Node.js
21
+ uses: actions/setup-node@v4
22
+ with:
23
+ node-version: "20"
24
+
25
+ - name: Install dependencies
26
+ run: yarn
27
+
28
+ - name: Run CI
29
+ run: yarn ci
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # mongoose-utility-kit
2
+
3
+ ## 0.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c44e2a0: Prepare for initial release
8
+
9
+ ## 0.0.1
10
+
11
+ ### Patch Changes
12
+
13
+ - ca2388e: added getPopulatedDocumentId, findOrReturnInstance and findOrReturnManyInstances functions
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nicolò Zandarin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # mongoose-utility-kit 🛠️
2
+
3
+ Utility functions to simplify common `mongoose` operations. Designed for `TypeScript` and `mongoose` projects with strict type safety.
4
+
5
+ ## Features
6
+
7
+ - **Type-safe**: Built with TypeScript for robust type checking.
8
+ - **Efficient**: Reduces redundant database queries.
9
+ - **Flexible**: Handles both document instances and ObjectIds seamlessly.
10
+ - **Population Ready**: Designed for mongoose documents with populated references.
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ npm install mongoose-utility-kit
16
+ ```
17
+
18
+ or
19
+
20
+ ```sh
21
+ yarn add mongoose-utility-kit
22
+ ```
23
+
24
+ ## TypeScript Usage Notes
25
+
26
+ These helpers are designed for mongoose projects using TypeScript with proper document typing. For best results:
27
+
28
+ 1. Define your hydrated document types using mongoose's `HydratedDocument`:
29
+ ```ts
30
+ // user.ts
31
+ import { HydratedDocument } from 'mongoose';
32
+
33
+ export interface IUser {
34
+ name: string;
35
+ email: string;
36
+ }
37
+
38
+ export interface IUserDocumentOverrides = { /* ... */ }
39
+
40
+ export interface IUserVirtuals = { /* ... */ }
41
+
42
+ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverrides & IUserVirtuals>;
43
+ ```
44
+
45
+ 2. Use `PopulatedDoc` for population references:
46
+ ```ts
47
+ // comment.ts
48
+ import { Types, PopulatedDoc } from 'mongoose';
49
+ import { UserHydratedDocument } from './user';
50
+
51
+ export interface IComment {
52
+ user: PopulatedDoc<UserHydratedDocument>;
53
+ text: string;
54
+ }
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ### 1. `getPopulatedDocumentId`
60
+ Handle both populated documents and ObjectIds safely:
61
+ ```ts
62
+ import { getPopulatedDocumentId } from 'mongoose-utility-kit';
63
+
64
+ // With ObjectId reference
65
+ const comment = await Comment
66
+ .findById(someId)
67
+ .orFail();
68
+ getPopulatedDocumentId(comment.user); // "507f191e810c19729de860ea"
69
+
70
+ // With populated document
71
+ const comment = await Comment
72
+ .findById(someId)
73
+ .populate<{ user: UserHydratedDocument }>('user')
74
+ .orFail();
75
+ getPopulatedDocumentId(comment.user); // "507f191e810c19729de860ea"
76
+ ```
77
+
78
+ ### 2. `findOrReturnInstance`
79
+ ```ts
80
+ // With ObjectId reference
81
+ const comment = await Comment
82
+ .findById(someId)
83
+ .orFail();
84
+ findOrReturnInstance(comment.user, UserModel);
85
+
86
+ // With populated document
87
+ const comment = await Comment
88
+ .findById(someId)
89
+ .populate<{ user: UserHydratedDocument }>('user')
90
+ .orFail();
91
+ findOrReturnInstance(comment.user, UserModel);
92
+ ```
93
+
94
+ ### 3. `findOrReturnManyInstances`
95
+ ```ts
96
+ const inputs: (UserHydratedDocument | Types.ObjectId)[] = [
97
+ existingUserDocument,
98
+ new Types.ObjectId()
99
+ ];
100
+
101
+ const users = await findOrReturnManyInstances(inputs, UserModel);
102
+ ```
103
+
104
+ ## API Documentation
105
+
106
+ ### `getPopulatedDocumentId`
107
+ ```ts
108
+ function getPopulatedDocumentId<HydratedDocType extends Document>(
109
+ populatedDocument: PopulatedDoc<HydratedDocType>
110
+ ): string
111
+ ```
112
+ **Handles:** Both populated documents and raw ObjectIds
113
+ **Throws:** If no valid ID found (`Error('document incorrect')`)
114
+
115
+ ### `findOrReturnInstance`
116
+ ```ts
117
+ async function findOrReturnInstance<HydratedDocType extends Document>(
118
+ docOrId: HydratedDocType | Types.ObjectId,
119
+ MongooseModel: Model<any, any, any, any, HydratedDocType>,
120
+ err?: Error | (() => Error)
121
+ ): Promise<HydratedDocType>
122
+ ```
123
+ **Throws:** Default error or custom error if document not found
124
+
125
+ ### `findOrReturnManyInstances`
126
+ ```ts
127
+ async function findOrReturnManyInstances<HydratedDocType extends Document>(
128
+ docOrIds: (HydratedDocType | Types.ObjectId)[],
129
+ MongooseModel: Model<any, any, any, any, HydratedDocType>
130
+ ): Promise<HydratedDocType[]>
131
+ ```
132
+
133
+ ## Development
134
+
135
+ ```sh
136
+ yarn test
137
+ ```
138
+ Tests use `mongodb-memory-server` for in-memory MongoDB testing.
139
+
140
+ ## Compatibility
141
+ - mongoose 6.x+
142
+ - TypeScript 4.5+
143
+ - Node.js 16+
144
+
145
+ ## License
146
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ findOrReturnInstance: () => findOrReturnInstance,
24
+ findOrReturnManyInstances: () => findOrReturnManyInstances,
25
+ getPopulatedDocumentId: () => getPopulatedDocumentId
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/populated/functions.ts
30
+ var import_mongoose = require("mongoose");
31
+ var getPopulatedDocumentId = (populatedDocument) => {
32
+ if (populatedDocument instanceof import_mongoose.Types.ObjectId) {
33
+ return populatedDocument.toString();
34
+ }
35
+ const id = populatedDocument?.id || populatedDocument?._id;
36
+ if (id) {
37
+ return id.toString();
38
+ }
39
+ throw new Error("document incorrect");
40
+ };
41
+ var findOrReturnInstance = async (docOrId, MongooseModel, err) => {
42
+ if (docOrId instanceof MongooseModel) {
43
+ return docOrId;
44
+ }
45
+ const result = await MongooseModel.findById(docOrId).orFail(err);
46
+ return result;
47
+ };
48
+ var findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
49
+ const [result, objectIds] = docOrIds.reduce((acc, docOrId) => {
50
+ if (docOrId instanceof MongooseModel) {
51
+ acc[0].push(docOrId);
52
+ } else if (docOrId instanceof import_mongoose.Types.ObjectId) {
53
+ acc[1].push(docOrId);
54
+ }
55
+ return acc;
56
+ }, [[], []]);
57
+ if (objectIds.length > 0) {
58
+ const docs = await MongooseModel.find({
59
+ _id: {
60
+ $in: objectIds
61
+ }
62
+ });
63
+ result.push(...docs);
64
+ }
65
+ return result;
66
+ };
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ findOrReturnInstance,
70
+ findOrReturnManyInstances,
71
+ getPopulatedDocumentId
72
+ });
@@ -0,0 +1,57 @@
1
+ import { Document, PopulatedDoc, Types, Model } from 'mongoose';
2
+
3
+ /**
4
+ * Extracts the ID from a populated Mongoose document.
5
+ *
6
+ * This function takes a populated document and returns its ID as a string.
7
+ * If the document is an instance of `ObjectId`, it directly returns its string representation.
8
+ * If the document has an `id` or `_id` property, it returns the corresponding value as a string.
9
+ * If none of these conditions are met, an exception is thrown.
10
+ *
11
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
12
+ * @param {PopulatedDoc<HydratedDocType>} populatedDocument
13
+ * - The populated document from which to extract the ID.
14
+ * @returns {string} The ID of the document as a string.
15
+ * @throws {Error} - Throws an error if the document is invalid or does not contain an ID.
16
+ */
17
+ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populatedDocument: PopulatedDoc<HydratedDocType>) => string;
18
+ /**
19
+ * Finds a Mongoose document by its ID or returns the provided instance.
20
+ *
21
+ * This asynchronous function takes either a document instance or an ObjectId.
22
+ * If the provided value is an instance of the specified Mongoose model, it returns that instance.
23
+ * Otherwise, it attempts to find the document by its ID using the provided Mongoose model.
24
+ * If the document is not found, it throws an error, which can be customized
25
+ * through the `err` parameter.
26
+ *
27
+ * @template HydratedDocType - The type of the hydrated document, extending `Document`.
28
+ * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
29
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
30
+ * - The Mongoose model used to query the database.
31
+ * @param {Error | (() => Error)} [err]
32
+ * - Optional error or a function that returns an error to throw if the document is not found.
33
+ * @returns {Promise<HydratedDocType>} A promise that resolves to the hydrated document instance.
34
+ * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
35
+ */
36
+ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
37
+ /**
38
+ * Finds multiple Mongoose documents by their IDs or returns the provided instances.
39
+ *
40
+ * This asynchronous function takes an array of document instances or ObjectIds.
41
+ * It returns an array containing the provided instances and any documents found by their IDs.
42
+ * If any of the provided values are instances of the specified Mongoose model,
43
+ * they are included in the result.
44
+ * The function queries the database for any ObjectIds
45
+ * that are not already represented by instances.
46
+ *
47
+ * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
48
+ * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
49
+ * - An array of document instances or ObjectIds to find.
50
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
51
+ * - The Mongoose model used to query the database.
52
+ * @returns {Promise<HydratedDocType[]>}
53
+ * A promise that resolves to an array of hydrated document instances.
54
+ */
55
+ declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
+
57
+ export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
@@ -0,0 +1,57 @@
1
+ import { Document, PopulatedDoc, Types, Model } from 'mongoose';
2
+
3
+ /**
4
+ * Extracts the ID from a populated Mongoose document.
5
+ *
6
+ * This function takes a populated document and returns its ID as a string.
7
+ * If the document is an instance of `ObjectId`, it directly returns its string representation.
8
+ * If the document has an `id` or `_id` property, it returns the corresponding value as a string.
9
+ * If none of these conditions are met, an exception is thrown.
10
+ *
11
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
12
+ * @param {PopulatedDoc<HydratedDocType>} populatedDocument
13
+ * - The populated document from which to extract the ID.
14
+ * @returns {string} The ID of the document as a string.
15
+ * @throws {Error} - Throws an error if the document is invalid or does not contain an ID.
16
+ */
17
+ declare const getPopulatedDocumentId: <HydratedDocType extends Document>(populatedDocument: PopulatedDoc<HydratedDocType>) => string;
18
+ /**
19
+ * Finds a Mongoose document by its ID or returns the provided instance.
20
+ *
21
+ * This asynchronous function takes either a document instance or an ObjectId.
22
+ * If the provided value is an instance of the specified Mongoose model, it returns that instance.
23
+ * Otherwise, it attempts to find the document by its ID using the provided Mongoose model.
24
+ * If the document is not found, it throws an error, which can be customized
25
+ * through the `err` parameter.
26
+ *
27
+ * @template HydratedDocType - The type of the hydrated document, extending `Document`.
28
+ * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
29
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
30
+ * - The Mongoose model used to query the database.
31
+ * @param {Error | (() => Error)} [err]
32
+ * - Optional error or a function that returns an error to throw if the document is not found.
33
+ * @returns {Promise<HydratedDocType>} A promise that resolves to the hydrated document instance.
34
+ * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
35
+ */
36
+ declare const findOrReturnInstance: <HydratedDocType extends Document>(docOrId: HydratedDocType | Types.ObjectId, MongooseModel: Model<any, any, any, any, HydratedDocType>, err?: Error | (() => Error)) => Promise<HydratedDocType>;
37
+ /**
38
+ * Finds multiple Mongoose documents by their IDs or returns the provided instances.
39
+ *
40
+ * This asynchronous function takes an array of document instances or ObjectIds.
41
+ * It returns an array containing the provided instances and any documents found by their IDs.
42
+ * If any of the provided values are instances of the specified Mongoose model,
43
+ * they are included in the result.
44
+ * The function queries the database for any ObjectIds
45
+ * that are not already represented by instances.
46
+ *
47
+ * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
48
+ * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
49
+ * - An array of document instances or ObjectIds to find.
50
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
51
+ * - The Mongoose model used to query the database.
52
+ * @returns {Promise<HydratedDocType[]>}
53
+ * A promise that resolves to an array of hydrated document instances.
54
+ */
55
+ declare const findOrReturnManyInstances: <HydratedDocType extends Document>(docOrIds: (HydratedDocType | Types.ObjectId)[], MongooseModel: Model<any, any, any, any, HydratedDocType>) => Promise<HydratedDocType[]>;
56
+
57
+ export { findOrReturnInstance, findOrReturnManyInstances, getPopulatedDocumentId };
package/dist/index.js ADDED
@@ -0,0 +1,47 @@
1
+ // src/populated/functions.ts
2
+ import {
3
+ Types,
4
+ } from 'mongoose';
5
+
6
+ const getPopulatedDocumentId = (populatedDocument) => {
7
+ if (populatedDocument instanceof Types.ObjectId) {
8
+ return populatedDocument.toString();
9
+ }
10
+ const id = populatedDocument?.id || populatedDocument?._id;
11
+ if (id) {
12
+ return id.toString();
13
+ }
14
+ throw new Error('document incorrect');
15
+ };
16
+ const findOrReturnInstance = async (docOrId, MongooseModel, err) => {
17
+ if (docOrId instanceof MongooseModel) {
18
+ return docOrId;
19
+ }
20
+ const result = await MongooseModel.findById(docOrId).orFail(err);
21
+ return result;
22
+ };
23
+ const findOrReturnManyInstances = async (docOrIds, MongooseModel) => {
24
+ const [result, objectIds] = docOrIds.reduce((acc, docOrId) => {
25
+ if (docOrId instanceof MongooseModel) {
26
+ acc[0].push(docOrId);
27
+ }
28
+ else if (docOrId instanceof Types.ObjectId) {
29
+ acc[1].push(docOrId);
30
+ }
31
+ return acc;
32
+ }, [[], []]);
33
+ if (objectIds.length > 0) {
34
+ const docs = await MongooseModel.find({
35
+ _id: {
36
+ $in: objectIds,
37
+ },
38
+ });
39
+ result.push(...docs);
40
+ }
41
+ return result;
42
+ };
43
+ export {
44
+ findOrReturnInstance,
45
+ findOrReturnManyInstances,
46
+ getPopulatedDocumentId,
47
+ };
@@ -0,0 +1,14 @@
1
+ module.exports = {
2
+ // [...]
3
+ setupFilesAfterEnv: ['./tests/initializers/setupTests.ts'],
4
+ transform: {
5
+ // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
6
+ // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
7
+ '^.+\\.tsx?$': [
8
+ 'ts-jest',
9
+ {
10
+ // ts-jest configuration goes here
11
+ },
12
+ ],
13
+ },
14
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "mongoose-utility-kit",
3
+ "version": "0.0.1",
4
+ "description": "A set of utility functions for the Mongoose library",
5
+ "keywords": [
6
+ "mongoose",
7
+ "helpers",
8
+ "utilities",
9
+ "typescript",
10
+ "populated"
11
+ ],
12
+ "main": "dist/index.js",
13
+ "type": "module",
14
+ "repository": "git@github.com:nikzanda/mongoose-utility-kit.git",
15
+ "author": "Nicolò Zandarin <nikzanda@hotmail.it>",
16
+ "license": "MIT",
17
+ "exports": {
18
+ "./package.json": "./package.json",
19
+ ".": {
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "test": "jest",
26
+ "build": "tsup",
27
+ "check-exports": "attw --pack .",
28
+ "lint": "eslint --fix .",
29
+ "ci": "yarn build && yarn check-exports && yarn lint && yarn test",
30
+ "local-release": "changeset version && changeset publish",
31
+ "prepublishOnly": "yarn ci"
32
+ },
33
+ "devDependencies": {
34
+ "@arethetypeswrong/cli": "^0.17.3",
35
+ "@changesets/cli": "^2.28.0",
36
+ "@types/jest": "^29.5.14",
37
+ "@typescript-eslint/eslint-plugin": "^8.24.1",
38
+ "@typescript-eslint/parser": "^8.24.1",
39
+ "eslint": "^8.2.0",
40
+ "eslint-config-airbnb-base": "^15.0.0",
41
+ "eslint-plugin-import": "^2.31.0",
42
+ "jest": "^29.7.0",
43
+ "mongodb-memory-server": "^10.1.4",
44
+ "mongoose": ">=8",
45
+ "ts-jest": "^29.2.5",
46
+ "tsup": "^8.3.6",
47
+ "typescript": "^5.7.3"
48
+ },
49
+ "peerDependencies": {
50
+ "mongoose": ">=8"
51
+ }
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './populated';
@@ -0,0 +1,111 @@
1
+ import {
2
+ Document,
3
+ Model,
4
+ PopulatedDoc,
5
+ Types,
6
+ } from 'mongoose';
7
+
8
+ /**
9
+ * Extracts the ID from a populated Mongoose document.
10
+ *
11
+ * This function takes a populated document and returns its ID as a string.
12
+ * If the document is an instance of `ObjectId`, it directly returns its string representation.
13
+ * If the document has an `id` or `_id` property, it returns the corresponding value as a string.
14
+ * If none of these conditions are met, an exception is thrown.
15
+ *
16
+ * @template HydratedDocType - The type of the populated document, extending `Document`.
17
+ * @param {PopulatedDoc<HydratedDocType>} populatedDocument
18
+ * - The populated document from which to extract the ID.
19
+ * @returns {string} The ID of the document as a string.
20
+ * @throws {Error} - Throws an error if the document is invalid or does not contain an ID.
21
+ */
22
+ export const getPopulatedDocumentId = <HydratedDocType extends Document>(
23
+ populatedDocument: PopulatedDoc<HydratedDocType>,
24
+ ): string => {
25
+ if (populatedDocument instanceof Types.ObjectId) {
26
+ return populatedDocument.toString();
27
+ }
28
+
29
+ const id = populatedDocument?.id || populatedDocument?._id;
30
+ if (id) {
31
+ return id.toString();
32
+ }
33
+
34
+ throw new Error('document incorrect');
35
+ };
36
+
37
+ /**
38
+ * Finds a Mongoose document by its ID or returns the provided instance.
39
+ *
40
+ * This asynchronous function takes either a document instance or an ObjectId.
41
+ * If the provided value is an instance of the specified Mongoose model, it returns that instance.
42
+ * Otherwise, it attempts to find the document by its ID using the provided Mongoose model.
43
+ * If the document is not found, it throws an error, which can be customized
44
+ * through the `err` parameter.
45
+ *
46
+ * @template HydratedDocType - The type of the hydrated document, extending `Document`.
47
+ * @param {HydratedDocType | Types.ObjectId} docOrId - The document instance or ObjectId to find.
48
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
49
+ * - The Mongoose model used to query the database.
50
+ * @param {Error | (() => Error)} [err]
51
+ * - Optional error or a function that returns an error to throw if the document is not found.
52
+ * @returns {Promise<HydratedDocType>} A promise that resolves to the hydrated document instance.
53
+ * @throws {Error} - Throws an error if the document is not found and no custom error is provided.
54
+ */
55
+ export const findOrReturnInstance = async <HydratedDocType extends Document>(
56
+ docOrId: HydratedDocType | Types.ObjectId,
57
+ MongooseModel: Model<any, any, any, any, HydratedDocType>,
58
+ err?: Error | (() => Error),
59
+ ): Promise<HydratedDocType> => {
60
+ if (docOrId instanceof MongooseModel) {
61
+ return docOrId;
62
+ }
63
+
64
+ const result = await MongooseModel
65
+ .findById(docOrId)
66
+ .orFail(err);
67
+ return result;
68
+ };
69
+
70
+ /**
71
+ * Finds multiple Mongoose documents by their IDs or returns the provided instances.
72
+ *
73
+ * This asynchronous function takes an array of document instances or ObjectIds.
74
+ * It returns an array containing the provided instances and any documents found by their IDs.
75
+ * If any of the provided values are instances of the specified Mongoose model,
76
+ * they are included in the result.
77
+ * The function queries the database for any ObjectIds
78
+ * that are not already represented by instances.
79
+ *
80
+ * @template HydratedDocType - The type of the hydrated documents, extending `Document`.
81
+ * @param {(HydratedDocType | Types.ObjectId)[]} docOrIds
82
+ * - An array of document instances or ObjectIds to find.
83
+ * @param {Model<any, any, any, any, HydratedDocType>} MongooseModel
84
+ * - The Mongoose model used to query the database.
85
+ * @returns {Promise<HydratedDocType[]>}
86
+ * A promise that resolves to an array of hydrated document instances.
87
+ */
88
+ export const findOrReturnManyInstances = async <HydratedDocType extends Document>(
89
+ docOrIds: (HydratedDocType | Types.ObjectId)[],
90
+ MongooseModel: Model<any, any, any, any, HydratedDocType>,
91
+ ): Promise<HydratedDocType[]> => {
92
+ const [result, objectIds] = docOrIds
93
+ .reduce((acc: [HydratedDocType[], Types.ObjectId[]], docOrId) => {
94
+ if (docOrId instanceof MongooseModel) {
95
+ acc[0].push(docOrId);
96
+ }
97
+ else if (docOrId instanceof Types.ObjectId) {
98
+ acc[1].push(docOrId);
99
+ }
100
+ return acc;
101
+ }, [[], []]);
102
+ if (objectIds.length > 0) {
103
+ const docs = await MongooseModel.find({
104
+ _id: {
105
+ $in: objectIds,
106
+ },
107
+ });
108
+ result.push(...docs);
109
+ }
110
+ return result;
111
+ };
@@ -0,0 +1 @@
1
+ export * from './functions';
@@ -0,0 +1,59 @@
1
+ import {
2
+ Schema,
3
+ Model,
4
+ SchemaTypes,
5
+ SchemaOptions,
6
+ Types,
7
+ HydratedDocument,
8
+ PopulatedDoc,
9
+ model,
10
+ } from 'mongoose';
11
+ import { UserHydratedDocument } from './user';
12
+
13
+ export interface IComment {
14
+ _id: Types.ObjectId;
15
+ user: PopulatedDoc<UserHydratedDocument>;
16
+ text: string;
17
+ createdAt: Date;
18
+ updatedAt: Date;
19
+ }
20
+
21
+ interface ICommentDocumentOverrides {}
22
+
23
+ interface ICommentVirtuals {
24
+ id: string;
25
+ }
26
+
27
+ export type CommentHydratedDocument = HydratedDocument<
28
+ IComment,
29
+ ICommentDocumentOverrides & ICommentVirtuals
30
+ >;
31
+
32
+ export type CommentModelType = Model<
33
+ IComment,
34
+ {},
35
+ ICommentDocumentOverrides,
36
+ ICommentVirtuals,
37
+ CommentHydratedDocument
38
+ >;
39
+
40
+ const options: SchemaOptions<IComment> = {
41
+ timestamps: true,
42
+ optimisticConcurrency: true,
43
+ };
44
+
45
+ const commentSchema = new Schema<IComment, CommentModelType>({
46
+ user: {
47
+ type: SchemaTypes.ObjectId,
48
+ ref: 'User',
49
+ required: true,
50
+ },
51
+ text: {
52
+ type: SchemaTypes.String,
53
+ trim: true,
54
+ },
55
+ }, options);
56
+
57
+ commentSchema.index({ user: 1 });
58
+
59
+ export default model<IComment, CommentModelType>('Comment', commentSchema);
@@ -0,0 +1,48 @@
1
+ import {
2
+ HydratedSingleSubdocument,
3
+ Model,
4
+ Schema,
5
+ SchemaOptions,
6
+ SchemaTypes,
7
+ } from 'mongoose';
8
+
9
+ export interface IAddress {
10
+ streetAddress?: string;
11
+ postalCode?: string;
12
+ city?: string;
13
+ province?: string;
14
+ country?: string;
15
+ }
16
+
17
+ export type AddressInstance = HydratedSingleSubdocument<IAddress>;
18
+
19
+ type AddressModelType = Model<IAddress, {}, {}, {}, AddressInstance>;
20
+
21
+ const options: SchemaOptions<IAddress> = {
22
+ _id: false,
23
+ };
24
+
25
+ const addressSchema = new Schema<IAddress, AddressModelType>({
26
+ streetAddress: {
27
+ type: SchemaTypes.String,
28
+ trim: true,
29
+ },
30
+ postalCode: {
31
+ type: SchemaTypes.String,
32
+ trim: true,
33
+ },
34
+ city: {
35
+ type: SchemaTypes.String,
36
+ trim: true,
37
+ },
38
+ province: {
39
+ type: SchemaTypes.String,
40
+ trim: true,
41
+ },
42
+ country: {
43
+ type: SchemaTypes.String,
44
+ trim: true,
45
+ },
46
+ }, options);
47
+
48
+ export default addressSchema;
@@ -0,0 +1,76 @@
1
+ import {
2
+ Schema,
3
+ Model,
4
+ SchemaTypes,
5
+ SchemaOptions,
6
+ Types,
7
+ HydratedDocument,
8
+ model,
9
+ } from 'mongoose';
10
+ import addressSchema, { AddressInstance, IAddress } from './embedded/address';
11
+
12
+ export interface IUser {
13
+ _id: Types.ObjectId;
14
+ name: string;
15
+ surname: string;
16
+ email: string;
17
+ password: string;
18
+ address: IAddress;
19
+ createdAt: Date;
20
+ updatedAt: Date;
21
+ }
22
+
23
+ interface IUserDocumentOverrides {
24
+ address: AddressInstance;
25
+ }
26
+
27
+ interface IUserVirtuals {
28
+ id: string;
29
+ fullName: string;
30
+ }
31
+
32
+ export type UserHydratedDocument = HydratedDocument<IUser, IUserDocumentOverrides & IUserVirtuals>;
33
+
34
+ export type UserModelType = Model<
35
+ IUser,
36
+ {},
37
+ IUserDocumentOverrides,
38
+ IUserVirtuals,
39
+ UserHydratedDocument
40
+ >;
41
+
42
+ const options: SchemaOptions<IUser> = {
43
+ timestamps: true,
44
+ optimisticConcurrency: true,
45
+ };
46
+
47
+ const userSchema = new Schema<IUser, UserModelType>({
48
+ name: {
49
+ type: SchemaTypes.String,
50
+ required: true,
51
+ trim: true,
52
+ },
53
+ email: {
54
+ type: SchemaTypes.String,
55
+ required: true,
56
+ unique: true,
57
+ trim: true,
58
+ },
59
+ password: {
60
+ type: SchemaTypes.String,
61
+ required: true,
62
+ },
63
+ address: {
64
+ type: addressSchema,
65
+ required: true,
66
+ },
67
+ }, options);
68
+
69
+ userSchema.index({ name: 1 });
70
+
71
+ userSchema.virtual('fullName')
72
+ .get(function () {
73
+ return `${this.name} ${this.surname}`;
74
+ });
75
+
76
+ export default model<IUser, UserModelType>('User', userSchema);
@@ -0,0 +1,15 @@
1
+ // eslint-disable-next-line import/no-extraneous-dependencies
2
+ import { MongoMemoryServer } from 'mongodb-memory-server';
3
+ import { connect, disconnect } from 'mongoose';
4
+
5
+ let mongod: MongoMemoryServer;
6
+
7
+ beforeAll(async () => {
8
+ mongod = await MongoMemoryServer.create();
9
+ await connect(mongod.getUri());
10
+ });
11
+
12
+ afterAll(async () => {
13
+ await disconnect();
14
+ await mongod.stop();
15
+ });
@@ -0,0 +1,95 @@
1
+ import { Types } from 'mongoose';
2
+ import { findOrReturnInstance, getPopulatedDocumentId } from '../src';
3
+ import User, { UserHydratedDocument } from './initializers/models/user';
4
+ import Comment, { IComment } from './initializers/models/comment';
5
+
6
+ let user: UserHydratedDocument;
7
+
8
+ beforeAll(async () => {
9
+ user = await User.create({
10
+ name: 'Nicolò',
11
+ surname: 'Zandarin',
12
+ email: 'nicolo.zandarin@email.com',
13
+ password: 'password',
14
+ address: {
15
+ streetAddress: '',
16
+ postalCode: '',
17
+ city: '',
18
+ province: '',
19
+ country: 'Italy',
20
+ },
21
+ });
22
+
23
+ await Comment.create({
24
+ user,
25
+ text: 'post comment',
26
+ });
27
+ });
28
+
29
+ const checkType = (u: any): u is UserHydratedDocument => u instanceof User;
30
+
31
+ describe('getPopulatedDocumentId', () => {
32
+ it('should return the string representation of a Types.ObjectId', async () => {
33
+ const comment = await Comment
34
+ .findOne()
35
+ .orFail();
36
+ const result = getPopulatedDocumentId(comment.user);
37
+ expect(result).toBe(user.id);
38
+ });
39
+
40
+ it('should return the id property if it exists', async () => {
41
+ const comment = await Comment
42
+ .findOne()
43
+ .populate<{ user: UserHydratedDocument }>('user')
44
+ .orFail();
45
+ const result = getPopulatedDocumentId(comment.user);
46
+ expect(result).toBe(user.id);
47
+ });
48
+
49
+ it('should return the _id property if id does not exist', async () => {
50
+ const comment = await Comment
51
+ .findOne()
52
+ .lean()
53
+ .populate<{ user: IComment['user'] }>('user')
54
+ .orFail();
55
+ const result = getPopulatedDocumentId(comment.user);
56
+ expect(result).toBe(user.id);
57
+ });
58
+
59
+ it('should handle null or undefined input gracefully', () => {
60
+ expect(() => getPopulatedDocumentId(null as any)).toThrow('document incorrect');
61
+ expect(() => getPopulatedDocumentId(undefined as any)).toThrow('document incorrect');
62
+ });
63
+ });
64
+
65
+ describe('findOrReturnInstance', () => {
66
+ it('should find a document by ID', async () => {
67
+ const comment = await Comment
68
+ .findOne()
69
+ .orFail();
70
+ const result = await findOrReturnInstance(comment.user!, User);
71
+ expect(result.id).toBe(user.id);
72
+ expect(result.name).toBe(user.name);
73
+ expect(result.fullName).toBe(user.fullName);
74
+ expect(result.address.country).toBe(user.address.country);
75
+ expect(checkType(result)).toBe(true);
76
+ });
77
+
78
+ it('return the extracted user instance', async () => {
79
+ const comment = await Comment
80
+ .findOne()
81
+ .populate<{ user: UserHydratedDocument }>('user')
82
+ .orFail();
83
+ const result = await findOrReturnInstance(comment.user, User);
84
+ expect(result.id).toBe(user.id);
85
+ expect(result.name).toBe(user.name);
86
+ expect(result.fullName).toBe(user.fullName);
87
+ expect(result.address.country).toBe(user.address.country);
88
+ expect(checkType(result)).toBe(true);
89
+ });
90
+
91
+ it('should throw an error if the document is not found', async () => {
92
+ const invalidId = new Types.ObjectId(); // Generate an invalid ID
93
+ await expect(findOrReturnInstance(invalidId, Comment)).rejects.toThrow();
94
+ });
95
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ "lib": ["es2022"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "Preserve", /* Specify what module code is generated. */
29
+ // "rootDir": "src", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
40
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
41
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
42
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
43
+ // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
44
+ // "resolveJsonModule": true, /* Enable importing .json files. */
45
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
46
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
47
+
48
+ /* JavaScript Support */
49
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
50
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
51
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
52
+
53
+ /* Emit */
54
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
55
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
56
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
57
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ "noEmit": true, /* Disable emitting files from a compilation. */
60
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
61
+ // "outDir": "dist", /* Specify an output folder for all emitted files. */
62
+ // "removeComments": true, /* Disable emitting comments. */
63
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
64
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
65
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
66
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
67
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
68
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
69
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
70
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
71
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
72
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
73
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
74
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
75
+
76
+ /* Interop Constraints */
77
+ "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
80
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
81
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
82
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
83
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
84
+
85
+ /* Type Checking */
86
+ "strict": true, /* Enable all strict type-checking options. */
87
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
88
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
89
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
90
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
91
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
92
+ // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
93
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
94
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
95
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
96
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
97
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
98
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
99
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
100
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
101
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
102
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
103
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
104
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
105
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
106
+
107
+ /* Completeness */
108
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
109
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
110
+ },
111
+ "exclude": ["dist", "tsup.config.ts"]
112
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entryPoints: ["src/index.ts"],
5
+ format: ["cjs", "esm"],
6
+ dts: true,
7
+ outDir: "dist",
8
+ clean: true,
9
+ });