envapt 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +197 -0
- package/NOTICE +2 -0
- package/README.md +445 -0
- package/dist/index.d.mts +330 -0
- package/dist/index.d.ts +330 -0
- package/dist/index.js +625 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +621 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +97 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2025 Dhruv Jain (materwelonDhruv)
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
191
|
+
|
|
192
|
+
### Third-Party Components
|
|
193
|
+
|
|
194
|
+
This project includes code originally developed and licensed under the MIT License:
|
|
195
|
+
|
|
196
|
+
- Portions derived from envuments (c) 2020 Mason Rogers
|
|
197
|
+
See `envuments.license` for full license text.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
# Envapt - The apt way to handle env
|
|
2
|
+
|
|
3
|
+
A powerful TypeScript-first environment configuration library that provides type detection, template variable resolution, and decorator-based class property configuration by extending dotenv.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔧 **Automatic Type Detection** - Types inferred from fallback values
|
|
8
|
+
- 🔗 **Template Variables** - `${VAR}` syntax with circular reference protection
|
|
9
|
+
- 🎯 **Class Properties** - Decorator-based configuration for class members
|
|
10
|
+
- 🏷️ **Built-in & Custom Converters** - Ready-to-use converters for common patterns + custom transformations
|
|
11
|
+
- 🌍 **Environment Detection** - Built-in development/staging/production handling
|
|
12
|
+
- 📂 **Multiple .env Files** - Load from multiple sources
|
|
13
|
+
- 💪 **Edge Case Handling** - Robust parsing for all scenarios
|
|
14
|
+
- 🛡️ **Type Safety** - Full TypeScript support with proper type inference
|
|
15
|
+
|
|
16
|
+
## Table of Contents
|
|
17
|
+
|
|
18
|
+
- [Requirements](#requirements)
|
|
19
|
+
- [Quick Start](#quick-start)
|
|
20
|
+
- [Installation](#installation)
|
|
21
|
+
- [Basic Usage](#basic-usage)
|
|
22
|
+
- [API Reference](#api-reference)
|
|
23
|
+
- [Decorator API](#decorator-api)
|
|
24
|
+
- [Built-in Converters](#built-in-converters)
|
|
25
|
+
- [Custom Array Converters](#custom-array-converters)
|
|
26
|
+
- [Custom Converters](#custom-converters)
|
|
27
|
+
- [Handling Missing Values](#handling-missing-values)
|
|
28
|
+
- [Functional API](#functional-api)
|
|
29
|
+
- [Environment Detection](#environment-detection)
|
|
30
|
+
- [Template Variables](#template-variables)
|
|
31
|
+
- [Advanced Examples](#advanced-examples)
|
|
32
|
+
|
|
33
|
+
## Requirements
|
|
34
|
+
|
|
35
|
+
- **Node.js**: v18 or later (recommended for ESM and nodenext support)
|
|
36
|
+
- **TypeScript**: v5.8 or later
|
|
37
|
+
- **Dependencies**:
|
|
38
|
+
- `dotenv` (runtime dependency | bundled)
|
|
39
|
+
- `reflect-metadata` (peer dependency, required for decorators)
|
|
40
|
+
- **TypeScript Compiler Options**:
|
|
41
|
+
- `experimentalDecorators: true`
|
|
42
|
+
- `emitDecoratorMetadata: true`
|
|
43
|
+
- `module: nodenext`
|
|
44
|
+
- `moduleResolution: nodenext`
|
|
45
|
+
- `target: esnext`
|
|
46
|
+
- `lib: ESNext`
|
|
47
|
+
- **ESM Support**: Project uses ESM (`nodenext`), so your environment and tooling should support ES modules.
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
### Installation
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
# npm
|
|
55
|
+
npm install envapt reflect-metadata
|
|
56
|
+
|
|
57
|
+
# pnpm
|
|
58
|
+
pnpm add envapt reflect-metadata
|
|
59
|
+
|
|
60
|
+
# yarn
|
|
61
|
+
yarn add envapt reflect-metadata
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Basic Usage
|
|
65
|
+
|
|
66
|
+
Create a `.env` file:
|
|
67
|
+
|
|
68
|
+
```env
|
|
69
|
+
APP_PORT=8443
|
|
70
|
+
APP_URL=http://localhost:${APP_PORT}
|
|
71
|
+
DATABASE_URL=postgres://localhost:5432/mydb
|
|
72
|
+
IS_PRODUCTION=false
|
|
73
|
+
MAX_CONNECTIONS=100
|
|
74
|
+
ALLOWED_ORIGINS=https://app.com,https://admin.com
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Use with decorators (recommended):
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { Envapt, Envapter } from 'envapt';
|
|
81
|
+
|
|
82
|
+
// Global app configuration (static properties)
|
|
83
|
+
class AppConfig extends Envapter {
|
|
84
|
+
@Envapt('APP_PORT', 3000)
|
|
85
|
+
static readonly port: number;
|
|
86
|
+
|
|
87
|
+
@Envapt('APP_URL', 'http://localhost:3000', 'url')
|
|
88
|
+
static readonly url: URL;
|
|
89
|
+
|
|
90
|
+
@Envapt('ALLOWED_ORIGINS', {
|
|
91
|
+
fallback: ['http://localhost:3000'],
|
|
92
|
+
converter: 'array'
|
|
93
|
+
})
|
|
94
|
+
static readonly allowedOrigins: string[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Service configuration (instance properties)
|
|
98
|
+
class DatabaseService {
|
|
99
|
+
@Envapt('DATABASE_URL', 'sqlite://memory')
|
|
100
|
+
declare readonly databaseUrl: string;
|
|
101
|
+
|
|
102
|
+
@Envapt('MAX_CONNECTIONS', { converter: 'number', fallback: 10 })
|
|
103
|
+
declare readonly maxConnections: number;
|
|
104
|
+
|
|
105
|
+
@Envapt('REQUEST_TIMEOUT', { converter: 'time', fallback: 5000 })
|
|
106
|
+
declare readonly timeout: number; // Converts "5s" to 5000ms
|
|
107
|
+
|
|
108
|
+
async connect() {
|
|
109
|
+
console.log(`Connecting to ${this.databaseUrl}`);
|
|
110
|
+
// Connection logic here
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Usage
|
|
115
|
+
console.log(AppConfig.port); // 8443 (number)
|
|
116
|
+
console.log(AppConfig.url.href); // "http://localhost:8443" (templated!)
|
|
117
|
+
|
|
118
|
+
const dbService = new DatabaseService();
|
|
119
|
+
await dbService.connect();
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Or use functionally:\
|
|
123
|
+
<sub>Limited to primitives, String, Number, Boolean, Symbol, and BigInt. Does not support converters.</sub>
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { Envapter } from 'envapt';
|
|
127
|
+
|
|
128
|
+
const port = Envapter.getNumber('APP_PORT', 3000);
|
|
129
|
+
const url = Envapter.get('APP_URL', 'http://localhost:3000');
|
|
130
|
+
const isProduction = Envapter.getBoolean('IS_PRODUCTION', false);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## API Reference
|
|
134
|
+
|
|
135
|
+
### Decorator API
|
|
136
|
+
|
|
137
|
+
The `@Envapt` decorator can be used on both **static** and **instance** class properties:
|
|
138
|
+
|
|
139
|
+
- **Static properties**: Use for global configuration that's shared across your entire application (e.g., app port, global features, environment settings)
|
|
140
|
+
- **Instance properties**: Use for service-specific configuration that may vary per service or when you want the configuration tied to a specific class instance (e.g., database connections, service endpoints, per-service settings)
|
|
141
|
+
|
|
142
|
+
**Important**: Instance properties must be declared with `declare` keyword or `!` assertion since they're populated by the decorator rather than set in a constructor.
|
|
143
|
+
|
|
144
|
+
#### Modern Syntax (Recommended)
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
@Envapt('ENV_VAR', { fallback?: T, converter?: EnvConverter<T> })
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
#### Classic Syntax
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
@Envapt('ENV_VAR', fallback?, converter?)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
#### Automatic Type Detection
|
|
157
|
+
|
|
158
|
+
Types are automatically inferred from fallback values. Use static properties for app-wide config and instance properties for service-specific config:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
class Config extends Envapter {
|
|
162
|
+
// Static properties for global settings
|
|
163
|
+
@Envapt('APP_NAME', 'MyApp') // string
|
|
164
|
+
static readonly appName: string;
|
|
165
|
+
|
|
166
|
+
@Envapt('APP_PORT', 3000) // number
|
|
167
|
+
static readonly port: number;
|
|
168
|
+
|
|
169
|
+
@Envapt('DEBUG_MODE', false) // boolean
|
|
170
|
+
static readonly debugMode: boolean;
|
|
171
|
+
|
|
172
|
+
// Instance properties for service-specific settings
|
|
173
|
+
@Envapt('SMTP_HOST', 'localhost') // string
|
|
174
|
+
declare readonly smtpHost: string;
|
|
175
|
+
|
|
176
|
+
@Envapt('SMTP_PORT', 587) // number
|
|
177
|
+
declare readonly smtpPort: number;
|
|
178
|
+
|
|
179
|
+
@Envapt('SMTP_SECURE', true) // boolean
|
|
180
|
+
declare readonly smtpSecure: boolean;
|
|
181
|
+
|
|
182
|
+
sendEmail(to: string, subject: string) {
|
|
183
|
+
console.log(`Sending via ${this.smtpHost}:${this.smtpPort}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
#### Built-in Converters
|
|
189
|
+
|
|
190
|
+
Envapt provides many built-in converters for common patterns:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
class Config extends Envapter {
|
|
194
|
+
// Basic types
|
|
195
|
+
@Envapt('APP_NAME', { converter: 'string', fallback: 'MyApp' })
|
|
196
|
+
static readonly appName: string;
|
|
197
|
+
|
|
198
|
+
@Envapt('PORT', { converter: 'number', fallback: 3000 })
|
|
199
|
+
static readonly port: number;
|
|
200
|
+
|
|
201
|
+
@Envapt('PRODUCTION_MODE', { converter: 'boolean', fallback: false })
|
|
202
|
+
static readonly productionMode: boolean;
|
|
203
|
+
|
|
204
|
+
// Advanced types
|
|
205
|
+
@Envapt('CORS_ORIGINS', { converter: 'array', fallback: [] })
|
|
206
|
+
static readonly corsOrigins: string[];
|
|
207
|
+
|
|
208
|
+
@Envapt('CONFIG_JSON', { converter: 'json', fallback: {} })
|
|
209
|
+
static readonly config: object;
|
|
210
|
+
|
|
211
|
+
@Envapt('API_URL', { converter: 'url', fallback: new URL('http://localhost') })
|
|
212
|
+
static readonly apiUrl: URL;
|
|
213
|
+
|
|
214
|
+
@Envapt('TIMEOUT', { converter: 'time', fallback: 5000 })
|
|
215
|
+
static readonly timeout: number; // Converts "30s" to 30000ms
|
|
216
|
+
|
|
217
|
+
// Instance properties work the same way
|
|
218
|
+
@Envapt('CACHE_TTL', { converter: 'time', fallback: 3600000 })
|
|
219
|
+
declare readonly cacheTtl: number; // "1h" becomes 3600000ms
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
**Available Built-in Converters:**
|
|
224
|
+
|
|
225
|
+
- `'string'` - String values
|
|
226
|
+
- `'number'` - Numeric values (integers and floats)
|
|
227
|
+
- `'integer'` - Integer values only
|
|
228
|
+
- `'float'` - Float values only
|
|
229
|
+
- `'boolean'` - Boolean values (true/false, yes/no, on/off, 1/0)
|
|
230
|
+
- `'bigint'` - BigInt values for large integers
|
|
231
|
+
- `'symbol'` - Symbol values (creates symbols from string descriptions)
|
|
232
|
+
- `'time'` - Time values (converts "5s", "30m", "2h" to milliseconds)
|
|
233
|
+
- `'json'` - JSON objects/arrays (safe parsing with fallback)
|
|
234
|
+
- `'array'` - Comma-separated string arrays
|
|
235
|
+
- `'url'` - URL objects
|
|
236
|
+
- `'regexp'` - Regular expressions (supports `/pattern/flags` syntax)
|
|
237
|
+
- `'date'` - Date objects (supports ISO strings and timestamps)
|
|
238
|
+
- `'time'` - Values denoting time. Such as 100, 30ms, 5s, 10m, 1.5h. (parsed to ms)
|
|
239
|
+
|
|
240
|
+
#### Custom Array Converters
|
|
241
|
+
|
|
242
|
+
For more control over array parsing:
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
class Config extends Envapter {
|
|
246
|
+
// Basic array (comma-separated strings)
|
|
247
|
+
@Envapt('TAGS', { converter: 'array', fallback: [] })
|
|
248
|
+
static readonly tags: string[];
|
|
249
|
+
|
|
250
|
+
// Custom delimiter
|
|
251
|
+
@Envapt('ALLOWED_METHODS', { converter: { delimiter: '|' }, fallback: ['GET'] })
|
|
252
|
+
declare readonly allowedMethods: string[];
|
|
253
|
+
|
|
254
|
+
// Custom delimiter with type conversion
|
|
255
|
+
@Envapt('RATE_LIMITS', { converter: { delimiter: ',', type: 'number' }, fallback: [100] })
|
|
256
|
+
declare readonly rateLimits: number[];
|
|
257
|
+
|
|
258
|
+
@Envapt('FEATURE_FLAGS', { converter: { delimiter: ';', type: 'boolean' }, fallback: [false] })
|
|
259
|
+
declare readonly featureFlags: boolean[];
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
**ArrayConverter Interface:**
|
|
264
|
+
|
|
265
|
+
- `delimiter: string` - The string used to split array elements
|
|
266
|
+
- `type?: BuiltInConverter` - Optional type to convert each element to (excludes 'array', 'json', and 'regexp')
|
|
267
|
+
|
|
268
|
+
#### Custom Converters
|
|
269
|
+
|
|
270
|
+
Transform environment values to any type:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
class Config extends Envapter {
|
|
274
|
+
@Envapt('TAGS', {
|
|
275
|
+
fallback: new Set(['default']),
|
|
276
|
+
converter: (raw, fallback) => {
|
|
277
|
+
if (!raw) return fallback;
|
|
278
|
+
return new Set(raw.split(',').map((s) => s.trim()));
|
|
279
|
+
}
|
|
280
|
+
})
|
|
281
|
+
static readonly tags: Set<string>;
|
|
282
|
+
|
|
283
|
+
@Envapt('NOTIFICATION_CHANNELS', {
|
|
284
|
+
fallback: new Map([['email', 'enabled']]),
|
|
285
|
+
converter: (raw, fallback) => {
|
|
286
|
+
if (!raw) return fallback;
|
|
287
|
+
const map = new Map();
|
|
288
|
+
raw.split(',').forEach((pair) => {
|
|
289
|
+
const [key, value] = pair.split(':');
|
|
290
|
+
map.set(key?.trim(), value?.trim() || 'enabled');
|
|
291
|
+
});
|
|
292
|
+
return map;
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
declare readonly channels: Map<string, string>;
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
#### Handling Missing Values
|
|
300
|
+
|
|
301
|
+
Control what happens when environment variables don't exist:
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
class Config extends Envapter {
|
|
305
|
+
// Returns undefined if not found
|
|
306
|
+
@Envapt('OPTIONAL_FEATURE', { fallback: undefined })
|
|
307
|
+
static readonly optionalFeature: string | undefined;
|
|
308
|
+
|
|
309
|
+
// Returns null if not found (no fallback provided)
|
|
310
|
+
@Envapt('MISSING_CONFIG', { converter: 'string' })
|
|
311
|
+
static readonly missingConfig: string | null;
|
|
312
|
+
|
|
313
|
+
// Uses fallback if not found
|
|
314
|
+
@Envapt('DEFAULT_THEME', { fallback: 'light' })
|
|
315
|
+
static readonly defaultTheme: string;
|
|
316
|
+
|
|
317
|
+
// Instance properties work the same way
|
|
318
|
+
@Envapt('LOG_FILE_PATH', { fallback: undefined })
|
|
319
|
+
declare readonly logFilePath: string | undefined;
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### Functional API
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
import { Envapter } from 'envapt';
|
|
327
|
+
|
|
328
|
+
// Type-specific getters
|
|
329
|
+
const str = Envapter.get('STRING_VAR', 'default');
|
|
330
|
+
const num = Envapter.getNumber('NUMBER_VAR', 42);
|
|
331
|
+
const bool = Envapter.getBoolean('BOOLEAN_VAR', false);
|
|
332
|
+
|
|
333
|
+
// Instance methods (same API)
|
|
334
|
+
const envapter = new Envapter();
|
|
335
|
+
const value = envapter.get('VAR', 'default');
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## Environment Detection
|
|
339
|
+
|
|
340
|
+
Envapt automatically detects your environment from these variables (in order):
|
|
341
|
+
|
|
342
|
+
1. `ENVIRONMENT`
|
|
343
|
+
2. `ENV`
|
|
344
|
+
3. `NODE_ENV`
|
|
345
|
+
|
|
346
|
+
Supported values: `development`, `staging`, `production` (case-sensitive)
|
|
347
|
+
|
|
348
|
+
### Environment Management
|
|
349
|
+
|
|
350
|
+
```ts
|
|
351
|
+
import { Envapter, EnvaptEnvironment } from 'envapt';
|
|
352
|
+
|
|
353
|
+
// Check current environment
|
|
354
|
+
console.log(Envapter.environment); // Environment.Development
|
|
355
|
+
console.log(Envapter.isProduction); // false
|
|
356
|
+
console.log(Envapter.isDevelopment); // true
|
|
357
|
+
console.log(Envapter.isStaging); // false
|
|
358
|
+
|
|
359
|
+
// Set environment
|
|
360
|
+
Envapter.environment = EnvaptEnvironment.Production;
|
|
361
|
+
Envapter.environment = 'staging'; // string also works
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
### Multiple .env Files
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
import { resolve } from 'node:path';
|
|
368
|
+
import { Envapter } from 'envapt';
|
|
369
|
+
|
|
370
|
+
// Load from multiple files
|
|
371
|
+
Envapter.envPaths = [resolve(__dirname, '.env.local'), resolve(__dirname, '.env.production')];
|
|
372
|
+
|
|
373
|
+
// Or single file
|
|
374
|
+
Envapter.envPaths = resolve(__dirname, '.env.production');
|
|
375
|
+
|
|
376
|
+
// Or just don't set a path for it to default to .env at the root of your project
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
## Template Variables
|
|
380
|
+
|
|
381
|
+
Envapt supports variable interpolation with `${VARIABLE}` syntax:
|
|
382
|
+
|
|
383
|
+
```env
|
|
384
|
+
DATABASE_HOST=localhost
|
|
385
|
+
DATABASE_PORT=5432
|
|
386
|
+
DATABASE_URL=postgres://${DATABASE_HOST}:${DATABASE_PORT}/mydb
|
|
387
|
+
|
|
388
|
+
API_VERSION=v1
|
|
389
|
+
API_BASE=https://api.example.com
|
|
390
|
+
API_ENDPOINT=${API_BASE}/${API_VERSION}/users
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### Circular Reference Protection
|
|
394
|
+
|
|
395
|
+
```env
|
|
396
|
+
CIRCULAR_A=${CIRCULAR_B}
|
|
397
|
+
CIRCULAR_B=${CIRCULAR_A}
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Circular references are detected and preserved as-is rather than causing infinite loops.
|
|
401
|
+
|
|
402
|
+
## Advanced Examples
|
|
403
|
+
|
|
404
|
+
### Complex Configuration
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
import { Envapt, Envapter } from 'envapt';
|
|
408
|
+
|
|
409
|
+
class AppConfig extends Envapter {
|
|
410
|
+
// Global settings (static)
|
|
411
|
+
@Envapt('PORT', 3000)
|
|
412
|
+
static readonly port: number;
|
|
413
|
+
|
|
414
|
+
@Envapt('REQUEST_TIMEOUT', { converter: 'time', fallback: 10000 })
|
|
415
|
+
static readonly requestTimeout: number; // "5s" -> 5000ms (if env is set to "5s")
|
|
416
|
+
|
|
417
|
+
@Envapt('FEATURE_FLAGS', {
|
|
418
|
+
fallback: new Set(['basic']),
|
|
419
|
+
converter: (raw, fallback) => {
|
|
420
|
+
if (!raw) return fallback;
|
|
421
|
+
return new Set(raw.split(',').map((s) => s.trim()));
|
|
422
|
+
}
|
|
423
|
+
})
|
|
424
|
+
static readonly featureFlags: Set<string>;
|
|
425
|
+
|
|
426
|
+
// Service settings (instance)
|
|
427
|
+
@Envapt('DB_URL', 'sqlite://memory')
|
|
428
|
+
declare readonly databaseUrl: string;
|
|
429
|
+
|
|
430
|
+
@Envapt('CACHE_TTL', { converter: 'time', fallback: 3600000 })
|
|
431
|
+
declare readonly cacheTtl: number; // "1h" -> 3600000ms
|
|
432
|
+
|
|
433
|
+
@Envapt('REDIS_URLS', {
|
|
434
|
+
fallback: [new URL('redis://localhost:6379')],
|
|
435
|
+
converter: (raw, fallback) => (raw ? raw.split(',').map((s) => new URL(s)) : fallback)
|
|
436
|
+
})
|
|
437
|
+
declare readonly redisUrls: URL[];
|
|
438
|
+
|
|
439
|
+
async initialize() {
|
|
440
|
+
console.log(`App running on port ${AppConfig.port}`);
|
|
441
|
+
console.log(`Database: ${this.databaseUrl}`);
|
|
442
|
+
console.log(`Cache TTL: ${this.cacheTtl}ms`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
```
|