@abdokouta/react-config 1.0.1 → 1.0.2

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 (39) hide show
  1. package/dist/{index.d.mts → index.d.cts} +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs.map +1 -1
  5. package/package.json +46 -17
  6. package/.examples/01-basic-usage.ts +0 -291
  7. package/.examples/02-env-helper.ts +0 -282
  8. package/.examples/README.md +0 -297
  9. package/.prettierrc.js +0 -1
  10. package/__tests__/config.module.test.ts +0 -244
  11. package/__tests__/drivers/env.driver.test.ts +0 -259
  12. package/__tests__/services/config.service.test.ts +0 -335
  13. package/__tests__/setup.d.ts +0 -11
  14. package/__tests__/vitest.setup.ts +0 -30
  15. package/eslint.config.js +0 -13
  16. package/src/config.module.ts +0 -152
  17. package/src/constants/index.ts +0 -5
  18. package/src/constants/tokens.constant.ts +0 -38
  19. package/src/drivers/env.driver.ts +0 -208
  20. package/src/drivers/file.driver.ts +0 -82
  21. package/src/drivers/index.ts +0 -6
  22. package/src/index.ts +0 -93
  23. package/src/interfaces/config-driver.interface.ts +0 -30
  24. package/src/interfaces/config-module-options.interface.ts +0 -84
  25. package/src/interfaces/config-service.interface.ts +0 -71
  26. package/src/interfaces/index.ts +0 -8
  27. package/src/interfaces/vite-config-plugin-options.interface.ts +0 -56
  28. package/src/plugins/index.ts +0 -5
  29. package/src/plugins/vite.plugin.ts +0 -118
  30. package/src/services/config.service.ts +0 -172
  31. package/src/services/index.ts +0 -5
  32. package/src/utils/define-config.util.ts +0 -35
  33. package/src/utils/get-nested-value.util.ts +0 -53
  34. package/src/utils/index.ts +0 -9
  35. package/src/utils/load-config-file.util.ts +0 -32
  36. package/src/utils/scan-config-files.util.ts +0 -36
  37. package/tsconfig.json +0 -28
  38. package/tsup.config.ts +0 -105
  39. package/vitest.config.ts +0 -66
@@ -1,291 +0,0 @@
1
- /**
2
- * Basic Config Usage Example
3
- *
4
- * This example demonstrates the fundamental configuration operations:
5
- * - Environment variable access
6
- * - Type-safe getters
7
- * - Default values
8
- * - Nested configuration
9
- *
10
- * @example
11
- * Run this example:
12
- * ```bash
13
- * ts-node examples/01-basic-usage.ts
14
- * ```
15
- */
16
-
17
- import { ConfigModule, ConfigService } from '@abdokouta/config';
18
- import { Inversiland } from '@abdokouta/react-di';
19
-
20
- /**
21
- * Initialize the config module
22
- */
23
- async function setupConfig() {
24
- // Set some example environment variables
25
- process.env.APP_NAME = 'My Application';
26
- process.env.APP_PORT = '3000';
27
- process.env.APP_DEBUG = 'true';
28
- process.env.APP_URL = 'http://localhost:3000';
29
- process.env.ALLOWED_HOSTS = 'localhost,127.0.0.1,example.com';
30
- process.env.DATABASE_CONFIG = JSON.stringify({
31
- host: 'localhost',
32
- port: 5432,
33
- database: 'myapp',
34
- });
35
-
36
- // Create the application module with config
37
- const app = await Inversiland.run({
38
- module: class AppModule {},
39
- imports: [
40
- ConfigModule.forRoot({
41
- driver: 'env',
42
- ignoreEnvFile: true, // Use process.env directly for this example
43
- isGlobal: true,
44
- }),
45
- ],
46
- });
47
-
48
- return app.get(ConfigService);
49
- }
50
-
51
- /**
52
- * Example 1: Basic string values
53
- */
54
- function stringValues(config: ConfigService) {
55
- console.log('\n=== Example 1: String Values ===\n');
56
-
57
- // Get string value
58
- const appName = config.getString('APP_NAME');
59
- console.log(`✓ APP_NAME: "${appName}"`);
60
-
61
- // Get string with default
62
- const appEnv = config.getString('APP_ENV', 'development');
63
- console.log(`✓ APP_ENV: "${appEnv}" (using default)`);
64
-
65
- // Get URL
66
- const appUrl = config.getString('APP_URL');
67
- console.log(`✓ APP_URL: "${appUrl}"`);
68
- }
69
-
70
- /**
71
- * Example 2: Number values
72
- */
73
- function numberValues(config: ConfigService) {
74
- console.log('\n=== Example 2: Number Values ===\n');
75
-
76
- // Get number value
77
- const port = config.getNumber('APP_PORT');
78
- console.log(`✓ APP_PORT: ${port} (type: ${typeof port})`);
79
-
80
- // Get number with default
81
- const timeout = config.getNumber('APP_TIMEOUT', 5000);
82
- console.log(`✓ APP_TIMEOUT: ${timeout} (using default)`);
83
-
84
- // Get number that doesn't exist
85
- const maxConnections = config.getNumber('MAX_CONNECTIONS', 100);
86
- console.log(`✓ MAX_CONNECTIONS: ${maxConnections} (using default)`);
87
- }
88
-
89
- /**
90
- * Example 3: Boolean values
91
- */
92
- function booleanValues(config: ConfigService) {
93
- console.log('\n=== Example 3: Boolean Values ===\n');
94
-
95
- // Get boolean value (true)
96
- const debug = config.getBool('APP_DEBUG');
97
- console.log(`✓ APP_DEBUG: ${debug} (type: ${typeof debug})`);
98
-
99
- // Get boolean with default
100
- const enableCache = config.getBool('ENABLE_CACHE', true);
101
- console.log(`✓ ENABLE_CACHE: ${enableCache} (using default)`);
102
-
103
- // Test various boolean formats
104
- process.env.TEST_TRUE_1 = 'true';
105
- process.env.TEST_TRUE_2 = '1';
106
- process.env.TEST_TRUE_3 = 'yes';
107
- process.env.TEST_TRUE_4 = 'on';
108
- process.env.TEST_FALSE = 'false';
109
-
110
- console.log(`✓ "true" → ${config.getBool('TEST_TRUE_1')}`);
111
- console.log(`✓ "1" → ${config.getBool('TEST_TRUE_2')}`);
112
- console.log(`✓ "yes" → ${config.getBool('TEST_TRUE_3')}`);
113
- console.log(`✓ "on" → ${config.getBool('TEST_TRUE_4')}`);
114
- console.log(`✓ "false" → ${config.getBool('TEST_FALSE')}`);
115
- }
116
-
117
- /**
118
- * Example 4: Array values
119
- */
120
- function arrayValues(config: ConfigService) {
121
- console.log('\n=== Example 4: Array Values ===\n');
122
-
123
- // Get array from comma-separated string
124
- const allowedHosts = config.getArray('ALLOWED_HOSTS');
125
- console.log(`✓ ALLOWED_HOSTS:`, allowedHosts);
126
-
127
- // Get array with default
128
- const corsOrigins = config.getArray('CORS_ORIGINS', ['http://localhost:3000']);
129
- console.log(`✓ CORS_ORIGINS:`, corsOrigins, '(using default)');
130
-
131
- // Empty array
132
- const emptyArray = config.getArray('EMPTY_ARRAY', []);
133
- console.log(`✓ EMPTY_ARRAY:`, emptyArray, '(using default)');
134
- }
135
-
136
- /**
137
- * Example 5: JSON values
138
- */
139
- function jsonValues(config: ConfigService) {
140
- console.log('\n=== Example 5: JSON Values ===\n');
141
-
142
- // Get JSON object
143
- const dbConfig = config.getJson('DATABASE_CONFIG');
144
- console.log(`✓ DATABASE_CONFIG:`, dbConfig);
145
-
146
- // Get JSON with default
147
- const apiConfig = config.getJson('API_CONFIG', {
148
- url: 'http://localhost:3000',
149
- timeout: 5000,
150
- });
151
- console.log(`✓ API_CONFIG:`, apiConfig, '(using default)');
152
- }
153
-
154
- /**
155
- * Example 6: Check if keys exist
156
- */
157
- function checkExistence(config: ConfigService) {
158
- console.log('\n=== Example 6: Check Existence ===\n');
159
-
160
- // Check existing key
161
- const hasAppName = config.has('APP_NAME');
162
- console.log(`✓ has('APP_NAME'): ${hasAppName}`);
163
-
164
- // Check non-existent key
165
- const hasApiKey = config.has('API_KEY');
166
- console.log(`✓ has('API_KEY'): ${hasApiKey}`);
167
- }
168
-
169
- /**
170
- * Example 7: Required values (OrThrow)
171
- */
172
- function requiredValues(config: ConfigService) {
173
- console.log('\n=== Example 7: Required Values ===\n');
174
-
175
- try {
176
- // Get required value that exists
177
- const appName = config.getStringOrThrow('APP_NAME');
178
- console.log(`✓ getStringOrThrow('APP_NAME'): "${appName}"`);
179
-
180
- // Try to get required value that doesn't exist
181
- const apiKey = config.getStringOrThrow('API_KEY');
182
- console.log(`✓ getStringOrThrow('API_KEY'): "${apiKey}"`);
183
- } catch (error) {
184
- console.log(`✗ Error: ${(error as Error).message}`);
185
- console.log(` 💡 Use OrThrow methods for required configuration`);
186
- }
187
- }
188
-
189
- /**
190
- * Example 8: Get all configuration
191
- */
192
- function getAllConfig(config: ConfigService) {
193
- console.log('\n=== Example 8: Get All Configuration ===\n');
194
-
195
- const allConfig = config.all();
196
- const keys = Object.keys(allConfig).filter(
197
- (k) => k.startsWith('APP_') || k.startsWith('ALLOWED_')
198
- );
199
-
200
- console.log('✓ All APP_* and ALLOWED_* configuration:');
201
- keys.forEach((key) => {
202
- console.log(` - ${key}: ${allConfig[key]}`);
203
- });
204
- }
205
-
206
- /**
207
- * Example 9: Practical use case - Database configuration
208
- */
209
- function databaseConfig(config: ConfigService) {
210
- console.log('\n=== Example 9: Database Configuration ===\n');
211
-
212
- // Set database environment variables
213
- process.env.DB_HOST = 'localhost';
214
- process.env.DB_PORT = '5432';
215
- process.env.DB_NAME = 'myapp';
216
- process.env.DB_USER = 'admin';
217
- process.env.DB_PASSWORD = 'secret123';
218
- process.env.DB_SSL = 'true';
219
- process.env.DB_POOL_MIN = '2';
220
- process.env.DB_POOL_MAX = '10';
221
-
222
- // Build database configuration object
223
- const dbConfig = {
224
- host: config.getString('DB_HOST', 'localhost'),
225
- port: config.getNumber('DB_PORT', 5432),
226
- database: config.getString('DB_NAME', 'myapp'),
227
- username: config.getString('DB_USER'),
228
- password: config.getString('DB_PASSWORD'),
229
- ssl: config.getBool('DB_SSL', false),
230
- pool: {
231
- min: config.getNumber('DB_POOL_MIN', 2),
232
- max: config.getNumber('DB_POOL_MAX', 10),
233
- },
234
- };
235
-
236
- console.log('✓ Database configuration:');
237
- console.log(JSON.stringify(dbConfig, null, 2));
238
- }
239
-
240
- /**
241
- * Example 10: Practical use case - Feature flags
242
- */
243
- function featureFlags(config: ConfigService) {
244
- console.log('\n=== Example 10: Feature Flags ===\n');
245
-
246
- // Set feature flags
247
- process.env.FEATURE_CACHE = 'true';
248
- process.env.FEATURE_LOGGING = 'true';
249
- process.env.FEATURE_METRICS = 'false';
250
- process.env.FEATURE_ANALYTICS = '1';
251
-
252
- // Read feature flags
253
- const features = {
254
- cache: config.getBool('FEATURE_CACHE', false),
255
- logging: config.getBool('FEATURE_LOGGING', false),
256
- metrics: config.getBool('FEATURE_METRICS', false),
257
- analytics: config.getBool('FEATURE_ANALYTICS', false),
258
- };
259
-
260
- console.log('✓ Feature flags:');
261
- Object.entries(features).forEach(([name, enabled]) => {
262
- console.log(` - ${name}: ${enabled ? '✅ enabled' : '❌ disabled'}`);
263
- });
264
- }
265
-
266
- /**
267
- * Run all examples
268
- */
269
- async function main() {
270
- console.log('╔════════════════════════════════════════╗');
271
- console.log('║ Config Basic Usage Examples ║');
272
- console.log('╚════════════════════════════════════════╝');
273
-
274
- const config = await setupConfig();
275
-
276
- stringValues(config);
277
- numberValues(config);
278
- booleanValues(config);
279
- arrayValues(config);
280
- jsonValues(config);
281
- checkExistence(config);
282
- requiredValues(config);
283
- getAllConfig(config);
284
- databaseConfig(config);
285
- featureFlags(config);
286
-
287
- console.log('\n✅ All examples completed successfully!\n');
288
- }
289
-
290
- // Run the examples
291
- main().catch(console.error);
@@ -1,282 +0,0 @@
1
- /**
2
- * Env Helper Example
3
- *
4
- * This example demonstrates the standalone Env utility for quick
5
- * environment variable access without dependency injection.
6
- *
7
- * @example
8
- * Run this example:
9
- * ```bash
10
- * ts-node examples/02-env-helper.ts
11
- * ```
12
- */
13
-
14
- import { Env } from '@abdokouta/config';
15
-
16
- /**
17
- * Setup example environment variables
18
- */
19
- function setupEnv() {
20
- process.env.APP_NAME = 'My Application';
21
- process.env.APP_PORT = '3000';
22
- process.env.APP_DEBUG = 'true';
23
- process.env.NODE_ENV = 'development';
24
- process.env.API_TIMEOUT = '5000';
25
- process.env.ENABLE_CACHE = '1';
26
- process.env.ALLOWED_ORIGINS = 'http://localhost:3000,http://localhost:4000';
27
- process.env.FEATURE_FLAGS = JSON.stringify({
28
- newUI: true,
29
- betaFeatures: false,
30
- });
31
- }
32
-
33
- /**
34
- * Example 1: Basic Env usage
35
- */
36
- function basicUsage() {
37
- console.log('\n=== Example 1: Basic Env Usage ===\n');
38
-
39
- // Get string values
40
- const appName = Env.get('APP_NAME');
41
- console.log(`✓ APP_NAME: "${appName}"`);
42
-
43
- // Get with default
44
- const appEnv = Env.get('APP_ENV', 'production');
45
- console.log(`✓ APP_ENV: "${appEnv}" (using default)`);
46
-
47
- // Get non-existent key
48
- const apiKey = Env.get('API_KEY');
49
- console.log(`✓ API_KEY: ${apiKey} (undefined)`);
50
- }
51
-
52
- /**
53
- * Example 2: Type-safe getters
54
- */
55
- function typeSafeGetters() {
56
- console.log('\n=== Example 2: Type-Safe Getters ===\n');
57
-
58
- // Get string
59
- const appName = Env.getString('APP_NAME', 'Default App');
60
- console.log(`✓ getString('APP_NAME'): "${appName}"`);
61
-
62
- // Get number
63
- const port = Env.getNumber('APP_PORT', 3000);
64
- console.log(`✓ getNumber('APP_PORT'): ${port} (type: ${typeof port})`);
65
-
66
- // Get boolean
67
- const debug = Env.getBool('APP_DEBUG', false);
68
- console.log(`✓ getBool('APP_DEBUG'): ${debug} (type: ${typeof debug})`);
69
-
70
- // Get array
71
- const origins = Env.getArray('ALLOWED_ORIGINS', []);
72
- console.log(`✓ getArray('ALLOWED_ORIGINS'):`, origins);
73
-
74
- // Get JSON
75
- const features = Env.getJson('FEATURE_FLAGS', {});
76
- console.log(`✓ getJson('FEATURE_FLAGS'):`, features);
77
- }
78
-
79
- /**
80
- * Example 3: Required values
81
- */
82
- function requiredValues() {
83
- console.log('\n=== Example 3: Required Values ===\n');
84
-
85
- try {
86
- // Get required value that exists
87
- const appName = Env.getOrThrow('APP_NAME');
88
- console.log(`✓ getOrThrow('APP_NAME'): "${appName}"`);
89
-
90
- // Try to get required value that doesn't exist
91
- const apiKey = Env.getOrThrow('API_KEY');
92
- console.log(`✓ getOrThrow('API_KEY'): "${apiKey}"`);
93
- } catch (error) {
94
- console.log(`✗ Error: ${(error as Error).message}`);
95
- }
96
- }
97
-
98
- /**
99
- * Example 4: Check existence
100
- */
101
- function checkExistence() {
102
- console.log('\n=== Example 4: Check Existence ===\n');
103
-
104
- const hasAppName = Env.has('APP_NAME');
105
- console.log(`✓ has('APP_NAME'): ${hasAppName}`);
106
-
107
- const hasApiKey = Env.has('API_KEY');
108
- console.log(`✓ has('API_KEY'): ${hasApiKey}`);
109
- }
110
-
111
- /**
112
- * Example 5: Get all environment variables
113
- */
114
- function getAllEnv() {
115
- console.log('\n=== Example 5: Get All Environment Variables ===\n');
116
-
117
- const allEnv = Env.all();
118
- const appVars = Object.keys(allEnv).filter((k) => k.startsWith('APP_'));
119
-
120
- console.log('✓ All APP_* environment variables:');
121
- appVars.forEach((key) => {
122
- console.log(` - ${key}: ${allEnv[key]}`);
123
- });
124
- }
125
-
126
- /**
127
- * Example 6: Practical use case - Configuration class
128
- */
129
- class AppConfig {
130
- static get name(): string {
131
- return Env.getString('APP_NAME', 'My App');
132
- }
133
-
134
- static get port(): number {
135
- return Env.getNumber('APP_PORT', 3000);
136
- }
137
-
138
- static get debug(): boolean {
139
- return Env.getBool('APP_DEBUG', false);
140
- }
141
-
142
- static get environment(): string {
143
- return Env.getString('NODE_ENV', 'development');
144
- }
145
-
146
- static get isProduction(): boolean {
147
- return this.environment === 'production';
148
- }
149
-
150
- static get isDevelopment(): boolean {
151
- return this.environment === 'development';
152
- }
153
-
154
- static get apiTimeout(): number {
155
- return Env.getNumber('API_TIMEOUT', 5000);
156
- }
157
-
158
- static get allowedOrigins(): string[] {
159
- return Env.getArray('ALLOWED_ORIGINS', ['http://localhost:3000']);
160
- }
161
-
162
- static toJSON() {
163
- return {
164
- name: this.name,
165
- port: this.port,
166
- debug: this.debug,
167
- environment: this.environment,
168
- isProduction: this.isProduction,
169
- isDevelopment: this.isDevelopment,
170
- apiTimeout: this.apiTimeout,
171
- allowedOrigins: this.allowedOrigins,
172
- };
173
- }
174
- }
175
-
176
- function configurationClass() {
177
- console.log('\n=== Example 6: Configuration Class ===\n');
178
-
179
- console.log('✓ Application configuration:');
180
- console.log(JSON.stringify(AppConfig.toJSON(), null, 2));
181
- }
182
-
183
- /**
184
- * Example 7: Practical use case - Database configuration
185
- */
186
- function databaseConfig() {
187
- console.log('\n=== Example 7: Database Configuration ===\n');
188
-
189
- // Set database environment variables
190
- process.env.DB_HOST = 'localhost';
191
- process.env.DB_PORT = '5432';
192
- process.env.DB_NAME = 'myapp';
193
- process.env.DB_USER = 'admin';
194
- process.env.DB_PASSWORD = 'secret123';
195
- process.env.DB_SSL = 'true';
196
-
197
- // Build database configuration using Env helper
198
- const dbConfig = {
199
- host: Env.getString('DB_HOST', 'localhost'),
200
- port: Env.getNumber('DB_PORT', 5432),
201
- database: Env.getString('DB_NAME', 'myapp'),
202
- username: Env.getStringOrThrow('DB_USER'),
203
- password: Env.getStringOrThrow('DB_PASSWORD'),
204
- ssl: Env.getBool('DB_SSL', false),
205
- };
206
-
207
- console.log('✓ Database configuration:');
208
- console.log(JSON.stringify(dbConfig, null, 2));
209
- }
210
-
211
- /**
212
- * Example 8: Practical use case - Feature flags
213
- */
214
- function featureFlags() {
215
- console.log('\n=== Example 8: Feature Flags ===\n');
216
-
217
- // Set feature flags
218
- process.env.FEATURE_CACHE = 'true';
219
- process.env.FEATURE_LOGGING = '1';
220
- process.env.FEATURE_METRICS = 'false';
221
-
222
- // Read feature flags using Env helper
223
- const features = {
224
- cache: Env.getBool('FEATURE_CACHE', false),
225
- logging: Env.getBool('FEATURE_LOGGING', false),
226
- metrics: Env.getBool('FEATURE_METRICS', false),
227
- };
228
-
229
- console.log('✓ Feature flags:');
230
- Object.entries(features).forEach(([name, enabled]) => {
231
- console.log(` - ${name}: ${enabled ? '✅ enabled' : '❌ disabled'}`);
232
- });
233
- }
234
-
235
- /**
236
- * Example 9: Comparison with ConfigService
237
- */
238
- function comparisonWithConfigService() {
239
- console.log('\n=== Example 9: Env vs ConfigService ===\n');
240
-
241
- console.log('Env Helper:');
242
- console.log(' ✅ No dependency injection needed');
243
- console.log(' ✅ Static methods, easy to use anywhere');
244
- console.log(' ✅ Perfect for simple scripts and utilities');
245
- console.log(' ✅ Direct access to process.env');
246
- console.log(' ❌ No driver support (env only)');
247
- console.log(' ❌ No caching or advanced features');
248
-
249
- console.log('\nConfigService:');
250
- console.log(' ✅ Multiple driver support (env, file, etc.)');
251
- console.log(' ✅ Dependency injection integration');
252
- console.log(' ✅ Advanced features (caching, validation)');
253
- console.log(' ✅ Better for large applications');
254
- console.log(' ❌ Requires module setup');
255
- console.log(' ❌ Needs dependency injection');
256
- }
257
-
258
- /**
259
- * Run all examples
260
- */
261
- function main() {
262
- console.log('╔════════════════════════════════════════╗');
263
- console.log('║ Env Helper Examples ║');
264
- console.log('╚════════════════════════════════════════╝');
265
-
266
- setupEnv();
267
-
268
- basicUsage();
269
- typeSafeGetters();
270
- requiredValues();
271
- checkExistence();
272
- getAllEnv();
273
- configurationClass();
274
- databaseConfig();
275
- featureFlags();
276
- comparisonWithConfigService();
277
-
278
- console.log('\n✅ All examples completed successfully!\n');
279
- }
280
-
281
- // Run the examples
282
- main();