fiberx-backend-toolkit 0.1.21 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +207 -139
  2. package/dist/code_templates/email_enqueue_code_template.js +2 -2
  3. package/dist/code_templates/sequelize_code_template.d.ts +1 -1
  4. package/dist/code_templates/sequelize_code_template.js +131 -78
  5. package/dist/config/constants.d.ts +1 -0
  6. package/dist/config/constants.js +82 -15
  7. package/dist/database/connectors/sequelize_connector.d.ts +2 -0
  8. package/dist/database/connectors/sequelize_connector.js +43 -21
  9. package/dist/database/main.d.ts +3 -2
  10. package/dist/database/main.js +4 -2
  11. package/dist/database/schema/schema_diff_util.d.ts +0 -1
  12. package/dist/database/schema/schema_diff_util.js +7 -15
  13. package/dist/database/scripts/create_schema_script.js +6 -3
  14. package/dist/database/scripts/make_migrations_script.js +17 -10
  15. package/dist/database/scripts/migration_runner_script.d.ts +3 -1
  16. package/dist/database/scripts/migration_runner_script.js +58 -23
  17. package/dist/database/scripts/seeder_runner_script.d.ts +3 -1
  18. package/dist/database/scripts/seeder_runner_script.js +49 -17
  19. package/dist/database/scripts/sequelize_model_generator_script.d.ts +2 -2
  20. package/dist/database/scripts/sequelize_model_generator_script.js +11 -5
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +7 -0
  23. package/dist/mailer/main.d.ts +1 -1
  24. package/dist/mailer/processors/email_delivery_processor.js +45 -13
  25. package/dist/mailer/processors/email_enqueue_processor.js +23 -7
  26. package/dist/mailer/utils/mailer_data_loader_util.d.ts +4 -4
  27. package/dist/mailer/utils/mailer_data_loader_util.js +5 -5
  28. package/dist/middle_ware/authentication_middle_ware.d.ts +3 -3
  29. package/dist/middle_ware/authentication_middle_ware.js +27 -25
  30. package/dist/middle_ware/cookie_manager_middle_ware.js +1 -1
  31. package/dist/middle_ware/main.d.ts +3 -2
  32. package/dist/middle_ware/main.js +4 -2
  33. package/dist/middle_ware/rate_limiter_middle_ware.js +0 -1
  34. package/dist/middle_ware/request_logger_middle_ware.js +2 -1
  35. package/dist/middle_ware/response_formatter_middle_ware.js +5 -4
  36. package/dist/middle_ware/secure_headers_middle_ware.js +2 -1
  37. package/dist/rbac/rbac_loader_util.js +2 -2
  38. package/dist/storage/drivers/gcs_storage_driver.js +5 -5
  39. package/dist/storage/drivers/local_storage_driver.js +2 -2
  40. package/dist/storage/main.d.ts +1 -1
  41. package/dist/storage/processors/file_upload_processor.js +4 -4
  42. package/dist/storage/utils/storage_driver_util.d.ts +1 -1
  43. package/dist/storage/utils/storage_driver_util.js +12 -10
  44. package/dist/types/express_decelaration.d.ts +1 -1
  45. package/dist/types/express_decelaration.js +0 -1
  46. package/dist/types/middle_ware_type.d.ts +14 -12
  47. package/dist/types/middle_ware_type.js +0 -2
  48. package/dist/types/schema_type.js +0 -1
  49. package/dist/types/util_type.js +0 -1
  50. package/dist/utils/content_manager_util.js +11 -9
  51. package/dist/utils/crypto_key_util.js +9 -10
  52. package/dist/utils/encryptor_decryptor_util.js +19 -9
  53. package/dist/utils/env_manager_util.d.ts +1 -0
  54. package/dist/utils/env_manager_util.js +10 -2
  55. package/dist/utils/fs_actions_util.js +1 -1
  56. package/dist/utils/input_transformer_util.js +11 -25
  57. package/dist/utils/input_validator_util.d.ts +1 -1
  58. package/dist/utils/input_validator_util.js +75 -27
  59. package/dist/utils/logger_util.d.ts +2 -2
  60. package/dist/utils/logger_util.js +23 -9
  61. package/dist/utils/main.d.ts +1 -1
  62. package/dist/utils/safe_execute_util.js +21 -11
  63. package/dist/utils/sql_formatter_util.js +1 -5
  64. package/dist/utils/totp_service_util.js +3 -7
  65. package/dist/utils/uuid_gen_util.js +6 -2
  66. package/dist/validators/file_validator_util.js +2 -2
  67. package/dist/validators/query_validator_util.js +3 -3
  68. package/package.json +68 -2
package/README.md CHANGED
@@ -1,23 +1,13 @@
1
1
  # FiberX Backend Toolkit
2
2
 
3
- A comprehensive TypeScript backend toolkit providing shared domain logic, infrastructure helpers, and utilities for FiberX server-side applications and services.
3
+ Shared TypeScript backend utilities for FiberX services. The package includes Sequelize connection helpers, schema-driven migration generation, migration and seeder runners, Express middleware, storage helpers, mailer processors, RBAC loading, validators, and common utilities.
4
4
 
5
- ## Overview
6
-
7
- The FiberX Backend Toolkit is a centralized library designed to streamline backend development across FiberX services. It provides database abstraction layers, migration management, utilities for common operations, and TypeScript type definitions for consistency across the ecosystem.
8
-
9
- ## Features
5
+ ## Requirements
10
6
 
11
- - **Database Management**: Multi-connector support with Sequelize integration for ORM operations
12
- - **Schema Migration System**: Automated schema management, migration generation, and execution
13
- - **Seeding Support**: Database seeder generation and execution tools
14
- - **Utility Functions**:
15
- - Input validation and transformation
16
- - Environment variable management
17
- - SQL formatting and query building
18
- - Structured logging with file persistence
19
- - **TypeScript Support**: Fully typed exports for schema, migration, and utility types
20
- - **Flexible Exports**: Modular exports for `utils`, `types`, and `database` modules
7
+ - Node.js 20.x
8
+ - TypeScript projects using CommonJS or transpiled output
9
+ - Sequelize v6
10
+ - A project-level environment file in `environment_variables/`
21
11
 
22
12
  ## Installation
23
13
 
@@ -25,191 +15,269 @@ The FiberX Backend Toolkit is a centralized library designed to streamline backe
25
15
  npm install fiberx-backend-toolkit
26
16
  ```
27
17
 
28
- ## Requirements
18
+ ## Quality Commands
29
19
 
30
- - Node.js 20.x or higher
31
- - npm or yarn package manager
20
+ ```bash
21
+ npm run typecheck
22
+ npm run lint
23
+ npm run format:check
24
+ npm run spell:check
25
+ npm run build
26
+ npm run check
27
+ ```
32
28
 
33
- ## Quick Start
29
+ Use `npm run format` to apply Prettier formatting locally. The CI workflow runs type checking, linting, formatting checks, spell checking, and the build on every push and pull request.
34
30
 
35
- ### Import Types
31
+ ## Import Paths
36
32
 
37
- ```typescript
38
- import type { SchemaInterface, MigrationInterface } from "fiberx-backend-toolkit/types";
33
+ ```ts
34
+ import { LoggerUtil, EnvManagerUtil } from "fiberx-backend-toolkit/utils";
35
+ import { SequelizeConnector, MigrationRunnerScript } from "fiberx-backend-toolkit/database";
36
+ import { AuthenticationMiddleWare } from "fiberx-backend-toolkit/middle-ware";
37
+ import type { SchemaDefinitionInterface } from "fiberx-backend-toolkit/types";
39
38
  ```
40
39
 
41
- ### Import Utilities
40
+ The root package also re-exports the public modules:
42
41
 
43
- ```typescript
44
- import { LoggerUtil, InputValidatorUtil, EnvManagerUtil } from "fiberx-backend-toolkit/utils";
42
+ ```ts
43
+ import { SequelizeConnector, LoggerUtil } from "fiberx-backend-toolkit";
44
+ ```
45
45
 
46
- // Initialize logger
47
- const logger = new LoggerUtil("my-module");
48
- logger.info("Application started");
46
+ ## Environment Configuration
49
47
 
50
- // Use environment manager
51
- const apiKey = EnvManagerUtil.get("API_KEY");
48
+ By default, the toolkit reads YAML files from:
49
+
50
+ ```text
51
+ environment_variables/
52
52
  ```
53
53
 
54
- ### Database Operations
54
+ The file is selected from `process.env.MODE`:
55
55
 
56
- ```typescript
57
- import { SequelizeConnector, MigrationRunnerScript } from "fiberx-backend-toolkit/database";
58
-
59
- // Initialize database connector
60
- const connector = new SequelizeConnector(config);
56
+ ```text
57
+ development -> development_env.yaml
58
+ staging -> staging_env.yaml
59
+ production -> production_env.yaml
60
+ ```
61
61
 
62
- // Run migrations
63
- const migrationRunner = new MigrationRunnerScript(connector);
64
- await migrationRunner.run();
62
+ Example:
63
+
64
+ ```yaml
65
+ MODE: development
66
+ DB_DIALECT: postgres
67
+ DB_HOST: localhost
68
+ DB_PORT: 5432
69
+ DB_NAME: fiberx_app
70
+ DB_USER: postgres
71
+ DB_PASSWORD: postgres
72
+ DB_LOGGING: false
65
73
  ```
66
74
 
67
- ## Core Modules
75
+ For compatibility, the previous misspelled `environment_variables/` directory is still read if the corrected directory is not present.
76
+
77
+ ## Database Connection
78
+
79
+ Use `SequelizeConnector.getInstance()` rather than constructing the connector directly.
80
+
81
+ ```ts
82
+ import { SequelizeConnector } from "fiberx-backend-toolkit/database";
68
83
 
69
- ### Utilities (`/src/utils`)
84
+ const connector = SequelizeConnector.getInstance();
70
85
 
71
- - **LoggerUtil**: Structured logging with file-based persistence
72
- - **InputValidatorUtil**: Input validation and sanitization
73
- - **InputTransformerUtil**: Data transformation utilities
74
- - **EnvManagerUtil**: Environment variable management and parsing
75
- - **SqlFormatterUtil**: SQL query formatting and beautification
86
+ const sequelize = await connector.connect({
87
+ name: "default",
88
+ dialect: "postgres",
89
+ database: "fiberx_app",
90
+ username: "postgres",
91
+ password: "postgres",
92
+ host: "localhost",
93
+ port: 5432,
94
+ logging: false,
95
+ });
96
+ ```
76
97
 
77
- ### Database (`/src/database`)
98
+ `connect()` authenticates and attempts database creation for supported SQL dialects. `connectSync()` only creates a Sequelize instance and is useful when model files need to be initialized before application bootstrap.
78
99
 
79
- #### Connectors
80
- - **BaseConnector**: Abstract base class for database connections
81
- - **SequelizeConnector**: Sequelize ORM connector implementation
100
+ ## Directory Convention
82
101
 
83
- #### Schema Utilities
84
- - **SchemaDiffUtil**: Compare database schemas and detect changes
85
- - **SchemaNormalizerUtil**: Normalize schema definitions for consistency
102
+ The generator and runner scripts expect these project-root paths:
86
103
 
87
- #### Scripts
88
- - **CreateSchemaScript**: Generate initial database schema
89
- - **MakeMigrationsScript**: Auto-generate migration files from schema changes
90
- - **MigrationRunnerScript**: Execute pending database migrations
91
- - **CreateSeederScript**: Generate seeder files for initial data
92
- - **SeederRunnerScript**: Execute database seeders
104
+ ```text
105
+ src/database/
106
+ schemas/
107
+ schema_snapshots/
108
+ models/
109
+ migrations/
110
+ seeders/
111
+ ```
93
112
 
94
- ### Types (`/src/types`)
113
+ Missing directories are created where the scripts need them.
114
+
115
+ ## Schema Definitions
116
+
117
+ Schemas are plain TypeScript files with a default export:
118
+
119
+ ```ts
120
+ import { DataTypes } from "sequelize";
121
+ import type { SchemaDefinitionInterface } from "fiberx-backend-toolkit/types";
122
+
123
+ const UserSchema: SchemaDefinitionInterface = {
124
+ connection_name: "default",
125
+ database_name: "public",
126
+ migration_priority: 1,
127
+ table_name: "users",
128
+ model_name: "User",
129
+ timestamps: true,
130
+ columns: {
131
+ id: {
132
+ type: DataTypes.BIGINT,
133
+ primaryKey: true,
134
+ autoIncrement: true,
135
+ allowNull: false,
136
+ },
137
+ email: {
138
+ type: DataTypes.STRING(255),
139
+ allowNull: false,
140
+ unique: true,
141
+ },
142
+ },
143
+ indexes: [{ name: "users_email_unique", fields: ["email"], unique: true }],
144
+ };
145
+
146
+ export default UserSchema;
147
+ ```
95
148
 
96
- - **SchemaInterface**: Database schema type definitions
97
- - **MigrationInterface**: Migration type definitions
98
- - **UtilInterface**: Utility function types
149
+ You can scaffold a schema:
99
150
 
100
- ## Module Exports
151
+ ```ts
152
+ import { CreateSchemaScript } from "fiberx-backend-toolkit/database";
101
153
 
102
- The toolkit provides structured exports for easy integration:
154
+ new CreateSchemaScript("User").run();
155
+ ```
103
156
 
104
- ```typescript
105
- // Main exports (all modules)
106
- import * as toolkit from "fiberx-backend-toolkit";
157
+ ## Migration Workflow
107
158
 
108
- // Utils only
109
- import { LoggerUtil, InputValidatorUtil } from "fiberx-backend-toolkit/utils";
159
+ Generate migrations from schema changes:
110
160
 
111
- // Database only
112
- import { SequelizeConnector, MigrationRunnerScript } from "fiberx-backend-toolkit/database";
161
+ ```ts
162
+ import { MakeMigrationsScript } from "fiberx-backend-toolkit/database";
113
163
 
114
- // Types only
115
- import type { SchemaInterface } from "fiberx-backend-toolkit/types";
164
+ new MakeMigrationsScript().run();
116
165
  ```
117
166
 
118
- ## Configuration
167
+ Run migrations:
119
168
 
120
- The toolkit uses standardized directory conventions:
169
+ ```ts
170
+ import { MigrationRunnerScript } from "fiberx-backend-toolkit/database";
121
171
 
172
+ await new MigrationRunnerScript().run("up");
122
173
  ```
123
- project_root/
124
- ├── logs/ # Log files directory
125
- ├── environment_variables/ # Environment variable files
126
- ├── src/database/
127
- │ ├── schemas/ # Schema definitions
128
- │ ├── schema_snapshots/ # Schema snapshots for comparison
129
- │ ├── models/ # Sequelize models
130
- │ ├── migrations/ # Database migrations
131
- │ └── seeders/ # Database seeders
174
+
175
+ Rollback migrations:
176
+
177
+ ```ts
178
+ await new MigrationRunnerScript().run("down");
132
179
  ```
133
180
 
134
- ## Dependencies
181
+ Run a specific migration file:
135
182
 
136
- ### Core Dependencies
137
- - **sequelize**: ^6.37.7 - SQL ORM
138
- - **sequelize-typescript**: ^2.1.6 - TypeScript decorators for Sequelize
139
- - **axios**: ^1.11.0 - HTTP client
140
- - **bcrypt**: ^6.0.0 - Password hashing
141
- - **jsonwebtoken**: ^9.0.2 - JWT handling
142
- - **dayjs**: ^1.11.18 - Date/time utilities
143
- - **js-yaml**: ^4.1.0 - YAML parsing
144
- - **uuid**: ^12.0.0 - UUID generation
183
+ ```ts
184
+ await new MigrationRunnerScript().run("up", undefined, "1_20260515120000_create_table_users.ts");
185
+ ```
145
186
 
146
- ## Build
187
+ Migration runner behavior:
188
+
189
+ - Tracks applied migrations in `sequelize_database_tables_meta`.
190
+ - Supports both `.ts` and `.js` migration files and ignores `.d.ts`.
191
+ - Uses dialect-safe quoting for metadata reads.
192
+ - Sorts by numeric migration priority, then filename.
193
+ - Runs toolkit-generated migrations and metadata updates in a Sequelize transaction.
194
+ - Skips already-applied migrations on `up` and skips unapplied migrations on `down`.
195
+
196
+ When running TypeScript migration files directly, execute your script with `ts-node` and `tsconfig-paths/register` so path aliases resolve.
147
197
 
148
198
  ```bash
149
- npm run build
199
+ node -r ts-node/register -r tsconfig-paths/register ./scripts/migrate.ts
150
200
  ```
151
201
 
152
- The build process uses `tsup` for optimized TypeScript bundling.
153
-
154
- ## API Documentation
202
+ ## Model Generation
155
203
 
156
- ### LoggerUtil
204
+ Generate Sequelize model files from schemas:
157
205
 
158
- ```typescript
159
- const logger = new LoggerUtil("module-name");
206
+ ```ts
207
+ import { SequelizeModelGeneratorScript } from "fiberx-backend-toolkit/database";
160
208
 
161
- logger.info("Information message");
162
- logger.warn("Warning message");
163
- logger.error("Error message");
164
- logger.debug("Debug message");
209
+ new SequelizeModelGeneratorScript().generateModelsFromSchemas();
165
210
  ```
166
211
 
167
- Logs are stored locally in the configured `LOG_DIR`.
212
+ The old misspelled `SeqeulizeModelGeneratorScript` export is still available for compatibility.
168
213
 
169
- ### InputValidatorUtil
214
+ ## Seeders
170
215
 
171
- Validates and sanitizes user inputs with built-in rules and custom validators.
216
+ Create and run seeders:
172
217
 
173
- ### EnvManagerUtil
218
+ ```ts
219
+ import { CreateSeederScript, SeederRunnerScript } from "fiberx-backend-toolkit/database";
174
220
 
175
- ```typescript
176
- const dbHost = EnvManagerUtil.get("DB_HOST", "localhost");
177
- const dbPort = EnvManagerUtil.getAsNumber("DB_PORT", 5432);
221
+ new CreateSeederScript("User", "initial_users").run();
222
+
223
+ await new SeederRunnerScript().run("up");
224
+ await new SeederRunnerScript().run("down", "user");
178
225
  ```
179
226
 
180
- ### SequelizeConnector
227
+ Seeder state is tracked in `sequelize_database_table_seeder_meta`.
181
228
 
182
- Provides abstraction over Sequelize for database operations with connection pooling and query management.
229
+ ## Express Middleware
183
230
 
184
- ## Project Structure
231
+ ```ts
232
+ import { AuthenticationMiddleWare } from "fiberx-backend-toolkit/middle-ware";
185
233
 
186
- ```
187
- fiberx-backend-toolkit/
188
- ├── src/
189
- │ ├── code_templates/ # Code generation templates
190
- │ ├── config/ # Configuration constants
191
- │ ├── database/ # Database module
192
- │ ├── types/ # TypeScript type definitions
193
- │ ├── utils/ # Utility functions
194
- │ └── index.ts # Main entry point
195
- ├── package.json
196
- ├── tsconfig.json
197
- ├── tsup.config.ts # Build configuration
198
- └── README.md
234
+ const auth = new AuthenticationMiddleWare({
235
+ extractRequestInfoMethod: async (req) => ({
236
+ access_token: req.headers.authorization ?? null,
237
+ refresh_token: null,
238
+ origin_url: req.headers.origin ?? "",
239
+ request_id: String(req.headers["x-request-id"] ?? ""),
240
+ }),
241
+ validateActorHasPermissionMethod: async (requestInfo) => {
242
+ return requestInfo.permission_name === "user.read";
243
+ },
244
+ });
245
+
246
+ app.get("/users", auth.setPermissionName("user.read"), handler);
199
247
  ```
200
248
 
201
- ## License
249
+ `AuthenticationMiddleWare` is the corrected export. The previous `AuthenicationMiddleWare` export remains available for existing services.
250
+
251
+ ## Utility Modules
252
+
253
+ ```ts
254
+ import {
255
+ LoggerUtil,
256
+ EnvManagerUtil,
257
+ InputValidatorUtil,
258
+ InputTransformerUtil,
259
+ SafeExecuteUtil,
260
+ UUIDGeneratorUtil,
261
+ EncryptorDecryptorUtil,
262
+ TOTPServiceUtil,
263
+ } from "fiberx-backend-toolkit/utils";
264
+ ```
202
265
 
203
- ISC
266
+ ## Build
204
267
 
205
- ## Author
268
+ ```bash
269
+ npm run build
270
+ ```
206
271
 
207
- David Matt-Ojo
272
+ The build emits CommonJS JavaScript and declarations to `dist/`.
208
273
 
209
- ## Repository
274
+ ## Notes
210
275
 
211
- [GitHub - fiberx-backend-toolkit](https://github.com/fiberx-innovations/fiberx-backend-toolkit)
276
+ - Generated migrations accept an optional third argument for transaction options.
277
+ - Existing older migrations still run, but only generated or manually transaction-aware migrations can fully participate in the runner transaction.
278
+ - Avoid `sequelize.sync({ alter: true })` in production services that use these migration scripts. Treat schema files as the source for migration generation, and treat migration files as the auditable database history.
279
+ - updated the code
212
280
 
213
- ## Support
281
+ ## License
214
282
 
215
- For issues, bugs, or feature requests, please visit the [issues page](https://github.com/fiberx-innovations/fiberx-backend-toolkit/issues).
283
+ ISC
@@ -56,8 +56,8 @@ exports.GENERATE_UTIL_METHOD_CODE = GENERATE_UTIL_METHOD_CODE;
56
56
  const GENERATE_UTIL_CLASS_CODE = (types_file_name, generated_content) => {
57
57
  return `
58
58
  import { EmailAttachmentInterface } from "fiberx-backend-toolkit";
59
- import { EmailEnqueueProcessor } from "fiberx-backend-toolkit/dist/mailer/main";
60
- import { LoggerUtil } from "fiberx-backend-toolkit/dist/utils/main";
59
+ import { EmailEnqueueProcessor } from "fiberx-backend-toolkit/mailer";
60
+ import { LoggerUtil } from "fiberx-backend-toolkit/utils";
61
61
  import * as Types from "@/${types_file_name.replace(".ts", "")}";
62
62
 
63
63
  class GeneratedEmailEnqueueUtil {
@@ -5,4 +5,4 @@ declare const SEQUELIZE_UPDATE_EXISTING_SCHEMA_MIGRATION_FILE_CODE_TEMPLATE: (ta
5
5
  declare const SEQUELIZE_SEEDER_TEMPLATE: (class_name: string, table_name: string) => string;
6
6
  declare const SEQUELIZE_MODEL_CODE_TEMPLATE: (schema_model_name: string, schema_file_name: string, schema_columns: Record<string, SchemaColumnInterface>) => string;
7
7
  declare const SEQUELIZE_MODELS_INDEX_CODE_TEMPLATE: (model_names: string[], imports: string) => string;
8
- export { SEQUELIZE_SCHEMA_CODE_TEMPLATE, SEQUELIZE_SEEDER_TEMPLATE, SEQUELIZE_CREATE_NEW_SCHEMA_MIGRATION_FILE_CODE_TEMPLATE, SEQUELIZE_UPDATE_EXISTING_SCHEMA_MIGRATION_FILE_CODE_TEMPLATE, SEQUELIZE_MODEL_CODE_TEMPLATE, SEQUELIZE_MODELS_INDEX_CODE_TEMPLATE };
8
+ export { SEQUELIZE_SCHEMA_CODE_TEMPLATE, SEQUELIZE_SEEDER_TEMPLATE, SEQUELIZE_CREATE_NEW_SCHEMA_MIGRATION_FILE_CODE_TEMPLATE, SEQUELIZE_UPDATE_EXISTING_SCHEMA_MIGRATION_FILE_CODE_TEMPLATE, SEQUELIZE_MODEL_CODE_TEMPLATE, SEQUELIZE_MODELS_INDEX_CODE_TEMPLATE, };