arkos 1.0.17 → 1.0.19-beta
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.
- package/dist/cjs/app.js +1 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/exports/utils/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.controller.js +8 -12
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +4 -4
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js +4 -8
- package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
- package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js +19 -0
- package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js.map +1 -0
- package/dist/cjs/modules/base/base.middlewares.js +6 -1
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.helpers.js +183 -0
- package/dist/cjs/modules/base/utils/helpers/base.helpers.js.map +1 -0
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +5 -5
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/file-uploader/file-uploader.service.js +3 -3
- package/dist/cjs/modules/file-uploader/file-uploader.service.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/cjs/types/prisma-model-router-config.js +3 -0
- package/dist/cjs/types/prisma-model-router-config.js.map +1 -0
- package/dist/cjs/utils/features/api.features.js +2 -2
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/api.features.helpers.js +4 -3
- package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/change-case.helpers.js +2 -2
- package/dist/cjs/utils/helpers/change-case.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js +14 -45
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +27 -27
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +5 -3
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/scripts/export-prisma-types.js +3 -3
- package/dist/cjs/utils/scripts/export-prisma-types.js.map +1 -1
- package/dist/cjs/utils/scripts/generate-zod-schemas.js +4 -3
- package/dist/cjs/utils/scripts/generate-zod-schemas.js.map +1 -1
- package/dist/es2020/app.js +1 -1
- package/dist/es2020/app.js.map +1 -1
- package/dist/es2020/exports/utils/index.js.map +1 -1
- package/dist/es2020/modules/auth/auth.controller.js +8 -12
- package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
- package/dist/es2020/modules/auth/auth.service.js +4 -4
- package/dist/es2020/modules/auth/auth.service.js.map +1 -1
- package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js +4 -8
- package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
- package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js +12 -0
- package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js.map +1 -0
- package/dist/es2020/modules/base/base.middlewares.js +6 -1
- package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.helpers.js +177 -0
- package/dist/es2020/modules/base/utils/helpers/base.helpers.js.map +1 -0
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js +5 -5
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/es2020/modules/file-uploader/file-uploader.service.js +3 -3
- package/dist/es2020/modules/file-uploader/file-uploader.service.js.map +1 -1
- package/dist/es2020/types/arkos-config.js.map +1 -1
- package/dist/es2020/types/prisma-model-router-config.js +2 -0
- package/dist/es2020/types/prisma-model-router-config.js.map +1 -0
- package/dist/es2020/utils/features/api.features.js +2 -2
- package/dist/es2020/utils/features/api.features.js.map +1 -1
- package/dist/es2020/utils/helpers/api.features.helpers.js +4 -3
- package/dist/es2020/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/change-case.helpers.js +2 -2
- package/dist/es2020/utils/helpers/change-case.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/fs.helpers.js +13 -44
- package/dist/es2020/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +28 -28
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/prisma.helpers.js +6 -4
- package/dist/es2020/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/es2020/utils/scripts/export-prisma-types.js +3 -3
- package/dist/es2020/utils/scripts/export-prisma-types.js.map +1 -1
- package/dist/es2020/utils/scripts/generate-zod-schemas.js +4 -3
- package/dist/es2020/utils/scripts/generate-zod-schemas.js.map +1 -1
- package/dist/types/exports/utils/index.d.ts +1 -0
- package/dist/types/modules/auth/utils/helpers/auth.helpers.d.ts +2 -0
- package/dist/types/modules/base/utils/helpers/base.helpers.d.ts +5 -0
- package/dist/types/types/arkos-config.d.ts +5 -0
- package/dist/types/types/prisma-model-router-config.d.ts +18 -0
- package/dist/types/utils/helpers/fs.helpers.d.ts +2 -2
- package/package.json +46 -34
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { SignOptions } from \"jsonwebtoken\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_EXPIRES_IN`: Defaults to 90 (used for calculating cookie expiration).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prisma-model-router-config.js","sourceRoot":"","sources":["../../../src/types/prisma-model-router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type AvailableEndpoints =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"udpateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [www.arkosjs.com/docs/advanced-guide/customizing-generated-routers#generated-routers-configuration](https://www.arkosjs.com/docs/advanced-guide/customizing-generated-routers#generated-routers-configuration)\n */\nexport type PrismaModelRouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [www.arkosjs.com/docs/advanced-guide/customizing-generated-routers](https://www.arkosjs.com/docs/advanced-guide/customizing-generated-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n referenceField?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | AvailableEndpoints | AvailableEndpoints[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
|
|
@@ -65,8 +65,8 @@ class APIFeatures {
|
|
|
65
65
|
key !== "id" &&
|
|
66
66
|
key !== "password" &&
|
|
67
67
|
!field.isList &&
|
|
68
|
-
!key.includes("Id") &&
|
|
69
|
-
!key.includes("ID")) {
|
|
68
|
+
!(key === null || key === void 0 ? void 0 : key.includes("Id")) &&
|
|
69
|
+
!(key === null || key === void 0 ? void 0 : key.includes("ID"))) {
|
|
70
70
|
searchableFields.push({
|
|
71
71
|
[`${key}`]: {
|
|
72
72
|
contains: this.searchParams.search,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAI9D,MAAqB,WAAW;IAsB9B,YACE,GAAY,EACZ,SAAoB,EACpB,cAAwC;QArB1C,YAAO,GAAQ,EAAE,CAAC;QAGlB,mBAAc,GAAG;YACf,MAAM;YACN,MAAM;YACN,OAAO;YACP,QAAQ;YACR,WAAW;YACX,cAAc;YACd,QAAQ;YACR,SAAS;YACT,YAAY;YACZ,OAAO;YACP,oBAAoB;YACpB,eAAe;SAChB,CAAC;QAOA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,IAAA,oDAA6B,EAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC7D,IAAI,CAAC,OAAO,qBAAQ,IAAI,CAAC,OAAO,CAAE,CAAC;QAEnC,IAAI,cAAc;YAAE,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,cAAc,CAAC;QACzD,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI,EAAE,CAAC;IAC7C,CAAC;IAED,MAAM;;QACJ,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C;IACd,CAAC;IAED,QAAQ;QACN,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;QACvD,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC;QAC1D,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;QAEhC,IAAI,CAAC,OAAO,mCACP,IAAI,CAAC,OAAO,KACf,IAAI,EACJ,IAAI,EAAE,KAAK,GACZ,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAEK,IAAI;;YACR,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;YACnC,OAAO,MAAO,MAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,CAAC;KAAA;CACF;AA5RD,8BA4RC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: Request;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key.includes(\"Id\") &&\n !key.includes(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const parsedQueryOptions =\n typeof this.req.query?.prismaQueryOptions === \"string\"\n ? JSON.parse(this.req.query?.prismaQueryOptions)\n : {};\n\n this.filters = deepmerge(\n {\n where: whereOptions,\n },\n parsedQueryOptions,\n this.filters\n );\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAI9D,MAAqB,WAAW;IAsB9B,YACE,GAAY,EACZ,SAAoB,EACpB,cAAwC;QArB1C,YAAO,GAAQ,EAAE,CAAC;QAG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E,CAAC;KAAA;CACF;AA5RD,8BA4RC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: Request;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key?.includes(\"Id\") &&\n !key?.includes(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const parsedQueryOptions =\n typeof this.req.query?.prismaQueryOptions === \"string\"\n ? JSON.parse(this.req.query?.prismaQueryOptions)\n : {};\n\n this.filters = deepmerge(\n {\n where: whereOptions,\n },\n parsedQueryOptions,\n this.filters\n );\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
|
|
@@ -93,13 +93,14 @@ function parseQueryParamsWithModifiers(query, fieldConfig = DEFAULT_FIELD_CONFIG
|
|
|
93
93
|
}, {});
|
|
94
94
|
}
|
|
95
95
|
function convertValue(value, fieldName, config) {
|
|
96
|
-
|
|
96
|
+
var _a, _b, _c;
|
|
97
|
+
if (((_a = config.dateFields) === null || _a === void 0 ? void 0 : _a.includes(fieldName)) && value) {
|
|
97
98
|
return new Date(value);
|
|
98
99
|
}
|
|
99
|
-
if (config.booleanFields.includes(fieldName) && value) {
|
|
100
|
+
if (((_b = config.booleanFields) === null || _b === void 0 ? void 0 : _b.includes(fieldName)) && value) {
|
|
100
101
|
return value.toLowerCase() === "true";
|
|
101
102
|
}
|
|
102
|
-
if (config.numericFields.includes(fieldName) && value) {
|
|
103
|
+
if (((_c = config.numericFields) === null || _c === void 0 ? void 0 : _c.includes(fieldName)) && value) {
|
|
103
104
|
return Number(value);
|
|
104
105
|
}
|
|
105
106
|
return value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.features.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/api.features.helpers.ts"],"names":[],"mappings":";;AAiDA,sEAiHC;AA7ID,MAAM,oBAAoB,GAAgB;IACxC,UAAU,EAAE,CAAC,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC;IAC3D,aAAa,EAAE,CAAC,U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AC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;iBAC9D,CAAC;gBACF,MAAM;YAER;gBACE,YAAY,CAAC,UAAU,CAAC,GAAG;oBACzB,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC,WAAW,EAAE,SAAS,EAAE,WAAW,CAAC;iBAClE,CAAC;QACN,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAkB,CACnB,CAAC;AACJ,CAAC;AAqBD,SAAS,YAAY,CACnB,KAAa,EACb,SAAiB,EACjB,MAAmB;;IAGnB,IAAI,CAAA,MAAA,MAAM,CAAC,UAAU,0CAAE,QAAQ,CAAC,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACpD,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IAGD,IAAI,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,CAAC,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACvD,OAAO,KAAK,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxC,CAAC;IAGD,IAAI,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,CAAC,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * Configuration types for field type mapping\n */\ninterface FieldConfig {\n dateFields: string[];\n booleanFields: string[];\n numericFields: string[];\n}\n\n/**\n * Type for the structured filter object returned by the parser\n */\ntype ParsedFilter = {\n [key: string]: any;\n orderBy?: Record<string, \"asc\" | \"desc\">;\n OR?: Record<string, any>[];\n};\n\n/**\n * Default configuration for field types\n */\nconst DEFAULT_FIELD_CONFIG: FieldConfig = {\n dateFields: [\"createdAt\", \"updatedAt\", \"deletedAt\", \"date\"],\n booleanFields: [\"isActive\", \"isDeleted\", \"isPublished\", \"isArchived\"],\n numericFields: [\"age\", \"price\", \"quantity\", \"amount\", \"rating\"],\n};\n\n/**\n * Parses query parameters into a structured filter object compatible with Prisma queries.\n * Supports various operators and data type conversions.\n *\n * @param query - Object containing query parameters\n * @param fieldConfig - Optional configuration for field type mapping\n * @returns Structured filter object for database queries\n *\n * @example\n * // Basic usage\n * parseQueryParamsWithModifiers({ name__contains: 'john' })\n * // => { name: { contains: 'john', mode: 'sensitive' } }\n *\n * @example\n * // Complex query\n * parseQueryParamsWithModifiers({\n * name__not__equals: 'john',\n * age__gt: '25',\n * tags__in: 'tag1,tag2',\n * orderBy__createdAt: 'desc'\n * })\n */\nexport function parseQueryParamsWithModifiers(\n query: Record<string, any>,\n // excludedFields: string[],\n fieldConfig: FieldConfig = DEFAULT_FIELD_CONFIG\n): ParsedFilter {\n return Object.entries(JSON.parse(JSON.stringify(query))).reduce(\n (acc, [key, value]) => {\n const parts = key.split(\"__\");\n if (!value && value !== false && value !== \"false\" && parts.length < 2)\n return acc;\n\n // Convert value to string if it's not already\n const stringValue = Array.isArray(value) ? value[0]?.toString() : value;\n\n if (parts.length < 2) {\n acc[key] =\n typeof value === \"string\" && !Number.isNaN(value)\n ? convertValue(stringValue, parts[0], fieldConfig)\n : value;\n return acc;\n }\n const fieldName = parts[0];\n\n // Handle ordering\n if (fieldName === \"orderBy\" && parts.length === 2) {\n if (!acc.orderBy) acc.orderBy = {};\n acc.orderBy[parts[1]] = stringValue as \"asc\" | \"desc\";\n return acc;\n }\n\n // Handle simple equals case\n if (parts.length === 1) {\n acc[fieldName] = {\n equals: convertValue(stringValue, fieldName, fieldConfig),\n };\n return acc;\n }\n\n let currentLevel = acc;\n let currentKey = fieldName;\n\n // Build nested structure\n for (let i = 1; i < parts.length - 1; i++) {\n if (!currentLevel[currentKey]) {\n currentLevel[currentKey] = {};\n }\n currentLevel = currentLevel[currentKey];\n currentKey = parts[i];\n }\n\n const lastOperator = parts[parts.length - 1];\n\n // Handle special operators\n switch (lastOperator) {\n case \"icontains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"insensitive\",\n };\n break;\n\n case \"contains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"sensitive\",\n };\n break;\n\n case \"in\":\n case \"notIn\":\n currentLevel[currentKey] = {\n [lastOperator]: stringValue\n .split(\",\")\n .map((v: string) =>\n convertValue(v.trim(), fieldName, fieldConfig)\n ),\n };\n break;\n\n case \"or\":\n const values: string[] = stringValue.split(\",\");\n if (!acc.OR) acc.OR = [];\n acc.OR.push(\n ...values.map((val) => ({\n [fieldName]: {\n equals: convertValue(val.trim(), fieldName, fieldConfig),\n },\n }))\n );\n break;\n\n case \"isNull\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? null : undefined,\n };\n break;\n\n case \"isEmpty\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? \"\" : undefined,\n };\n break;\n\n default:\n currentLevel[currentKey] = {\n [lastOperator]: convertValue(stringValue, fieldName, fieldConfig),\n };\n }\n\n return acc;\n },\n {} as ParsedFilter\n );\n}\n\n/**\n * Converts string values to appropriate types based on field configuration\n * \n * // Example usage:\n/*\n const query = {\n name__not__equals: 'uanela',\n email__contains: 'example.com',\n description__icontains: 'test',\n age__gt: '25',\n status: 'active',\n tags__in: 'tag1,tag2,tag3',\n createdAt__gt: '2024-01-01',\n isActive: 'true',\n orderBy__createdAt: 'desc'\n };\n \n const result = parseQueryParamsWithModifiers(query);\n */\nfunction convertValue(\n value: string,\n fieldName: string,\n config: FieldConfig\n): any {\n // Handle date fields\n if (config.dateFields?.includes(fieldName) && value) {\n return new Date(value);\n }\n\n // Handle boolean fields\n if (config.booleanFields?.includes(fieldName) && value) {\n return value.toLowerCase() === \"true\";\n }\n\n // Handle numeric fields\n if (config.numericFields?.includes(fieldName) && value) {\n return Number(value);\n }\n\n return value;\n}\n"]}
|
|
@@ -165,14 +165,14 @@ function splitPrefixSuffix(input, options = {}) {
|
|
|
165
165
|
let suffixIndex = input.length;
|
|
166
166
|
while (prefixIndex < input.length) {
|
|
167
167
|
const char = input.charAt(prefixIndex);
|
|
168
|
-
if (!prefixCharacters.includes(char))
|
|
168
|
+
if (!(prefixCharacters === null || prefixCharacters === void 0 ? void 0 : prefixCharacters.includes(char)))
|
|
169
169
|
break;
|
|
170
170
|
prefixIndex++;
|
|
171
171
|
}
|
|
172
172
|
while (suffixIndex > prefixIndex) {
|
|
173
173
|
const index = suffixIndex - 1;
|
|
174
174
|
const char = input.charAt(index);
|
|
175
|
-
if (!suffixCharacters.includes(char))
|
|
175
|
+
if (!(suffixCharacters === null || suffixCharacters === void 0 ? void 0 : suffixCharacters.includes(char)))
|
|
176
176
|
break;
|
|
177
177
|
suffixIndex = index;
|
|
178
178
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"change-case.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/change-case.helpers.ts"],"names":[],"mappings":";;AA6CA,sBAkBC;AAKD,oDAWC;AAKD,wBAOC;AAKD,8BAiBC;AAKD,gCAQC;AAKD,0CAEC;AAKD,kCAWC;AAKD,oCAOC;AAKD,0BAEC;AAKD,8BAEC;AAKD,4BAEC;AAKD,oCAeC;AAKD,8BAEC;AAKD,8BAEC;AAvND,MAAM,oBAAoB,GAAG,wBAAwB,CAAC;AACtD,MAAM,oBAAoB,GAAG,8BAA8B,CAAC;AAG5D,MAAM,wBAAwB,GAAG,uBAAuB,CAAC;AAGzD,MAAM,oBAAoB,GAAG,gBAAgB,CAAC;AAG9C,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AAGrC,MAAM,gCAAgC,GAAG,EAAE,CAAC;AA+B5C,SAAgB,KAAK,CAAC,KAAa;IACjC,IAAI,MAAM,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAE1B,MAAM,GAAG,MAAM;SACZ,OAAO,CAAC,oBAAoB,EAAE,mBAAmB,CAAC;SAClD,OAAO,CAAC,oBAAoB,EAAE,mBAAmB,CAAC,CAAC;IAEtD,MAA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AC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,MAAM;QAC5C,WAAW,EAAE,CAAC;IAChB,CAAC;IAED,OAAO,WAAW,GAAG,WAAW,EAAE,CAAC;QACjC,MAAM,KAAK,GAAG,WAAW,GAAG,CAAC,CAAC;QAC9B,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACjC,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,MAAM;QAC5C,WAAW,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,WAAW,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;QAC9C,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC;KACzB,CAAC;AACJ,CAAC","sourcesContent":["// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {}\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"change-case.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/change-case.helpers.ts"],"names":[],"mappings":";;AA6CA,sBAkBC;AAKD,oDAWC;AAKD,wBAOC;AAKD,8BAiBC;AAKD,gCAQC;AAKD,0CAEC;AAKD,kCAWC;AAKD,oCAOC;AAKD,0BAEC;AAKD,8BAEC;AAKD,4BAEC;AAKD,oCAeC;AAKD,8BAEC;AAKD,8BAEC;AAvND,MAAM,oBAAoB,GAAG,wBAAwB,CAAC;AACtD,MAAM,oBAAoB,GAAG,8BAA8B,CAAC;AAG5D,MAAM,wBAAwB,GAAG,uBAAuB,CAAC;AAGzD,MAAM,oBAAoB,GAAG,gBAAgB,CAAC;AAG9C,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AAGrC,MAAM,gCAAgC,GAAG,EAAE,CAAC;AA+B5C,SAAgB,KAAK,CAAC,KAAa;IACjC,IAAI,MAAM,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAE1B,MAAM,GAAG,MAAM;SACZ,OAAO,CAAC,oBAAoB,EAAE,mBAAmB,CAAC;SAClD,OAAO,CAAC,oBAAoB,EAAE,mBAAmB,CAAC,CAAC;IAEtD,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAEpD,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC;IAGxB,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI;QAAE,KAAK,EAAE,CAAC;IAC9C,IAAI,KAAK,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAC7B,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,IAAI;QAAE,GAAG,EAAE,CAAC;IAE9C,OAAO,MA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AAM;QAC7C,WAAW,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,WAAW,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;QAC9C,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC;KACzB,CAAC;AACJ,CAAC","sourcesContent":["// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {}\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters?.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters?.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n"]}
|
|
@@ -3,57 +3,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.getUserFileExtension = exports.userFileExtension = exports.mkdirAsync = exports.accessAsync = exports.statAsync = void 0;
|
|
7
7
|
const util_1 = require("util");
|
|
8
8
|
const fs_1 = __importDefault(require("fs"));
|
|
9
9
|
exports.statAsync = (0, util_1.promisify)(fs_1.default.stat);
|
|
10
10
|
exports.accessAsync = (0, util_1.promisify)(fs_1.default.access);
|
|
11
11
|
exports.mkdirAsync = (0, util_1.promisify)(fs_1.default.mkdir);
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
try {
|
|
16
|
-
if (typeof process !== "undefined" && process.env) {
|
|
17
|
-
currentFile = __filename || "";
|
|
18
|
-
}
|
|
19
|
-
else {
|
|
20
|
-
if (typeof (global === null || global === void 0 ? void 0 : global.document) === "undefined") {
|
|
21
|
-
currentFile = new Function("return typeof import.meta !== 'undefined' ? import.meta.url : ''")();
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
catch (e) {
|
|
26
|
-
}
|
|
27
|
-
if (currentFile.endsWith(".ts") || currentFile.endsWith(".tsx")) {
|
|
28
|
-
return "ts";
|
|
29
|
-
}
|
|
30
|
-
try {
|
|
31
|
-
const globalObj = globalThis;
|
|
32
|
-
if (typeof globalObj.Deno !== "undefined" && globalObj.Deno.emit) {
|
|
33
|
-
return "ts";
|
|
34
|
-
}
|
|
35
|
-
if (typeof globalObj.Bun !== "undefined") {
|
|
36
|
-
return "ts";
|
|
37
|
-
}
|
|
38
|
-
if (typeof process !== "undefined" &&
|
|
39
|
-
process.versions &&
|
|
40
|
-
parseInt(process.versions.node.split(".")[0]) >= 18) {
|
|
41
|
-
const isUsingTypeScript = (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.includes(".ts:");
|
|
42
|
-
if (isUsingTypeScript)
|
|
43
|
-
return "ts";
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
catch (e) {
|
|
47
|
-
}
|
|
48
|
-
return "js";
|
|
49
|
-
})();
|
|
50
|
-
exports.userFileExtension = (() => {
|
|
12
|
+
const getUserFileExtension = () => {
|
|
13
|
+
if (exports.userFileExtension)
|
|
14
|
+
return exports.userFileExtension;
|
|
51
15
|
try {
|
|
52
16
|
const fs = require("fs");
|
|
53
17
|
const path = require("path");
|
|
54
18
|
const projectRoot = process.cwd();
|
|
55
19
|
if (fs.existsSync(path.join(projectRoot, "tsconfig.json"))) {
|
|
56
|
-
|
|
20
|
+
exports.userFileExtension = "ts";
|
|
21
|
+
return exports.userFileExtension;
|
|
57
22
|
}
|
|
58
23
|
const srcDirs = ["src", "source", "app", "lib"]
|
|
59
24
|
.map((dir) => path.join(projectRoot, dir))
|
|
@@ -62,13 +27,17 @@ exports.userFileExtension = (() => {
|
|
|
62
27
|
for (const dir of srcDirs) {
|
|
63
28
|
const files = fs.readdirSync(dir);
|
|
64
29
|
if (files.some((file) => file.endsWith(".ts") || file.endsWith(".tsx"))) {
|
|
65
|
-
|
|
30
|
+
exports.userFileExtension = "ts";
|
|
31
|
+
return exports.userFileExtension;
|
|
66
32
|
}
|
|
67
33
|
}
|
|
68
|
-
|
|
34
|
+
exports.userFileExtension = "js";
|
|
35
|
+
return exports.userFileExtension;
|
|
69
36
|
}
|
|
70
37
|
catch (e) {
|
|
71
|
-
|
|
38
|
+
exports.userFileExtension = "js";
|
|
39
|
+
return exports.userFileExtension;
|
|
72
40
|
}
|
|
73
|
-
}
|
|
41
|
+
};
|
|
42
|
+
exports.getUserFileExtension = getUserFileExtension;
|
|
74
43
|
//# sourceMappingURL=fs.helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/fs.helpers.ts"],"names":[],"mappings":";;;;;;AAAA,+BAAiC;AACjC,4CAAoB;AAEP,QAAA,SAAS,GAAG,IAAA,gBAAS,EAAC,YAAE,CAAC,IAAI,CAAC,CAAC;AAC/B,QAAA,WAAW,GAAG,IAAA,gBAAS,EAAC,YAAE,CAAC,MAAM,CAAC,CAAC;AACnC,QAAA,UAAU,GAAG,IAAA,gBAA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B,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;YAC1B,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;YAClC,IACE,KAAK,CAAC,IAAI,CAAC,CAAC,IAAS,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EACxE,CAAC;gBACD,yBAAiB,GAAG,IAAI,CAAC;gBACzB,OAAO,yBAAiB,CAAC;YAC3B,CAAC;QACH,CAAC;QAGD,yBAAiB,GAAG,IAAI,CAAC;QACzB,OAAO,yBAAiB,CAAC;IAC3B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QAEX,yBAAiB,GAAG,IAAI,CAAC;QACzB,OAAO,yBAAiB,CAAC;IAC3B,CAAC;AACH,CAAC,CAAC;AA5CW,QAAA,oBAAoB,wBA4C/B","sourcesContent":["import { promisify } from \"util\";\nimport fs from \"fs\";\n\nexport const statAsync = promisify(fs.stat);\nexport const accessAsync = promisify(fs.access);\nexport const mkdirAsync = promisify(fs.mkdir);\n\n// // Runtime-agnostic approach with proper TypeScript support\n// export const extension = (() => {\n// // Safely detect environment without direct import.meta reference\n// let currentFile = \"\";\n\n// // Try to determine the current file using environment-specific approaches\n// try {\n// if (typeof process !== \"undefined\" && process.env) {\n// // Node.js environment - use __filename\n// currentFile = __filename || \"\";\n// } else {\n// // Handle other environments (browser, Deno, etc.)\n// // This branch won't be reached in CommonJS builds\n// if (typeof (global as any)?.document === \"undefined\") {\n// // Non-browser environment that might support import.meta\n// // We'll use eval to prevent direct parsing of import.meta\n// currentFile = new Function(\n// \"return typeof import.meta !== 'undefined' ? import.meta.url : ''\"\n// )();\n// }\n// }\n// } catch (e) {\n// // Ignore errors during detection\n// }\n\n// // Check file extension\n// if (currentFile.endsWith(\".ts\") || currentFile.endsWith(\".tsx\")) {\n// return \"ts\";\n// }\n\n// // Use \"any\" type and conditional checks to avoid TypeScript errors\n// try {\n// // Check for Deno\n// const globalObj = globalThis as any;\n// if (typeof globalObj.Deno !== \"undefined\" && globalObj.Deno.emit) {\n// return \"ts\";\n// }\n\n// // Check for Bun\n// if (typeof globalObj.Bun !== \"undefined\") {\n// return \"ts\";\n// }\n\n// // Check for newer Node with TS support\n// if (\n// typeof process !== \"undefined\" &&\n// process.versions &&\n// parseInt((process.versions as any).node.split(\".\")[0]) >= 18\n// ) {\n// const isUsingTypeScript = new Error().stack?.includes(\".ts:\");\n// if (isUsingTypeScript) return \"ts\";\n// }\n// } catch (e) {\n// // Ignore errors during detection\n// }\n\n// return \"js\";\n// })();\n\nexport let userFileExtension: \"ts\" | \"js\" | undefined;\n\n/**\n * Immediately detects if the user's project uses TypeScript or JavaScript\n * @returns 'ts' | 'js'\n */\nexport const getUserFileExtension = (): \"ts\" | \"js\" => {\n if (userFileExtension) return userFileExtension;\n\n try {\n // Only works in Node.js environment\n const fs = require(\"fs\");\n const path = require(\"path\");\n\n // Get the project root\n const projectRoot = process.cwd();\n\n // Check for tsconfig.json in project root as the fastest check\n if (fs.existsSync(path.join(projectRoot, \"tsconfig.json\"))) {\n userFileExtension = \"ts\";\n return userFileExtension;\n }\n\n // Check common src directories\n const srcDirs = [\"src\", \"source\", \"app\", \"lib\"]\n .map((dir) => path.join(projectRoot, dir))\n .filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory());\n\n // Add project root to directories to check\n srcDirs.push(projectRoot);\n\n // Check each directory for .ts files\n for (const dir of srcDirs) {\n const files = fs.readdirSync(dir);\n if (\n files.some((file: any) => file.endsWith(\".ts\") || file.endsWith(\".tsx\"))\n ) {\n userFileExtension = \"ts\";\n return userFileExtension;\n }\n }\n\n // Default to js if no TypeScript indicators found\n userFileExtension = \"js\";\n return userFileExtension;\n } catch (e) {\n // Fallback to js if any errors occur\n userFileExtension = \"js\";\n return userFileExtension;\n }\n};\n"]}
|