sane-env 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ole Lammers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # sane-env
2
+
3
+ Mode-aware environment loading with schema validation.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add sane-env
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ #### Inject layered env files into `process.env` - requires `NODE_ENV` to be set:
14
+
15
+ ```ts
16
+ import 'sane-env/config';
17
+ ```
18
+
19
+ Loads these files:
20
+
21
+ 1. `.env`
22
+ 2. `.env.local`
23
+ 3. `.env.${NODE_ENV}`
24
+ 4. `.env.${NODE_ENV}.local`
25
+
26
+ #### Validate a loaded environment against a schema:
27
+
28
+ ```ts
29
+ import { z } from 'zod'; // Standard Schema compatible, bring your own
30
+ import { createEnvironment } from 'sane-env';
31
+
32
+ const env = createEnvironment({
33
+ source: process.env,
34
+ schema: {
35
+ NODE_ENV: z.enum(['development', 'test', 'production']),
36
+ PORT: z.coerce.number().int().positive(),
37
+ },
38
+ });
39
+ ```
40
+
41
+ #### Custom environment loading logic:
42
+
43
+ ```ts
44
+ import { loadEnvironment } from 'sane-env/load';
45
+ import { createEnvironment } from 'sane-env';
46
+
47
+ const envRecord = loadEnvironment({
48
+ // Custom loading configuration (see below)
49
+ });
50
+
51
+ const env = createEnvironment({
52
+ source: envRecord,
53
+ schema: { ... },
54
+ });
55
+ ```
56
+
57
+ ## Loading Configuration
58
+
59
+ | Property | Description | Required | Default |
60
+ | ----------------------- | ---------------------------------------------------------- | -------- | ------------------------------------------------ |
61
+ | files | The file names to load in lowest to highest priority order | ✅ | |
62
+ | root | The root directory at which to load files from | ❌ | `process.cwd()` |
63
+ | emptyStringsAsUndefined | Whether blank entries are skipped in parsing | ❌ | `true` |
64
+ | debug | Whether to announce which files are being loaded/parsed | ❌ | `false` (`true` with `/config` in `development`) |
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,56 @@
1
+ // src/load.ts
2
+ import path from "path";
3
+ import fs from "fs";
4
+ var LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
5
+ function parse(content, emptyStringsAsUndefined) {
6
+ const normalizedContent = content.replace(/\r\n?/g, `
7
+ `);
8
+ const result = {};
9
+ for (const match of normalizedContent.matchAll(LINE)) {
10
+ const key = match[1];
11
+ let value = (match[2] || "").trim();
12
+ if (key === undefined)
13
+ continue;
14
+ if (value === "" && emptyStringsAsUndefined)
15
+ continue;
16
+ const isDoubleQuoted = value[0] === '"';
17
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
18
+ if (isDoubleQuoted) {
19
+ value = value.replace(/\\n/g, `
20
+ `);
21
+ value = value.replace(/\\r/g, "\r");
22
+ }
23
+ result[key] = value;
24
+ }
25
+ return result;
26
+ }
27
+ function loadEnvironment(options) {
28
+ const { root = process.cwd(), files, emptyStringsAsUndefined = true, debug = false } = options;
29
+ let combinedResult = {};
30
+ for (const filename of files) {
31
+ const dotenvPath = path.resolve(root, filename);
32
+ if (!fs.existsSync(dotenvPath)) {
33
+ if (debug)
34
+ console.warn(`Skipping "${filename}", file missing`);
35
+ continue;
36
+ }
37
+ const content = fs.readFileSync(dotenvPath, { encoding: "utf-8" });
38
+ const result = parse(content, emptyStringsAsUndefined);
39
+ combinedResult = { ...combinedResult, ...result };
40
+ if (debug)
41
+ console.log(`Loaded "${filename}" (${Object.keys(result).length})`);
42
+ }
43
+ return combinedResult;
44
+ }
45
+
46
+ // src/config/index.ts
47
+ var mode = Reflect.get(process.env, "NODE_ENV");
48
+ if (mode === undefined)
49
+ throw new Error("`NODE_ENV` must be set when injecting environment variables");
50
+ var environment = loadEnvironment({
51
+ files: [".env", ".env.local", `.env.${mode}`, `.env.${mode}.local`],
52
+ debug: mode === "development"
53
+ });
54
+ for (const [key, value] of Object.entries(environment)) {
55
+ process.env[key] = value;
56
+ }
@@ -0,0 +1,24 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ type Environment = Record<string, string | undefined>;
3
+ type SchemaValue = StandardSchemaV1<unknown, any>;
4
+ type Schema = Record<string, SchemaValue>;
5
+ type InferSchema<T extends Schema> = {
6
+ [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>;
7
+ };
8
+ export interface EnvCreateOptions<T extends Schema> {
9
+ /**
10
+ * The raw environment values to compare against the schema.
11
+ */
12
+ source: Environment;
13
+ /**
14
+ * The schema defining which variables to pull and
15
+ * validate from the environment source.
16
+ */
17
+ schema: T;
18
+ }
19
+ /**
20
+ * Ensures an environment record matches a schema and returns the
21
+ * validated result.
22
+ */
23
+ export declare function createEnvironment<T extends Schema>(opts: EnvCreateOptions<T>): InferSchema<T>;
24
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ // src/index.ts
2
+ function throwValidationError(envKey, parsedValue, issues) {
3
+ const messages = issues.length === 0 ? "undefined" : issues.length === 1 ? issues[0]?.message : issues.map((v) => `- ${v.message}`).join(`
4
+ `);
5
+ throw new Error(`Invalid environment variable:
6
+ Key: ${envKey}
7
+ Parsed Value: ${parsedValue}
8
+ Message(s): ${messages}`);
9
+ }
10
+ function resolveSchema(standard) {
11
+ return standard["~standard"];
12
+ }
13
+ function validateEnvironmentValue(schema, environment, key) {
14
+ const standard = resolveSchema(schema[key]);
15
+ const envKey = String(key);
16
+ const envValue = environment[envKey];
17
+ const result = standard.validate(envValue);
18
+ if (result instanceof Promise) {
19
+ throw new Error(`Validation of key "${envKey}" is not synchronous`);
20
+ }
21
+ if (result.issues) {
22
+ throwValidationError(envKey, envValue, result.issues);
23
+ }
24
+ return result.value;
25
+ }
26
+ function createEnvironment(opts) {
27
+ const { schema, source } = opts;
28
+ const result = {};
29
+ for (const key in opts.schema) {
30
+ const value = validateEnvironmentValue(schema, source, key);
31
+ result[key] = value;
32
+ }
33
+ return result;
34
+ }
35
+ export {
36
+ createEnvironment
37
+ };
package/dist/load.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export interface EnvLoadOptions {
2
+ /**
3
+ * The files (relative to `root`) to load and parse.
4
+ * In Lowest -> Highest priority order.
5
+ */
6
+ files: string[];
7
+ /**
8
+ * The root path to load files from.
9
+ * Default `process.cwd()`
10
+ */
11
+ root?: string;
12
+ /**
13
+ * Whether empty (`''`) or blank (`' '`) entries are parsed as `undefined`.
14
+ * Default `true`
15
+ */
16
+ emptyStringsAsUndefined?: boolean;
17
+ /**
18
+ * Whether to display logging messages during parsing.
19
+ * Default `false`
20
+ */
21
+ debug?: boolean;
22
+ }
23
+ /**
24
+ * Reads and parses environment files into a combined
25
+ * environment record.
26
+ */
27
+ export declare function loadEnvironment(options: EnvLoadOptions): Record<string, string>;
package/dist/load.js ADDED
@@ -0,0 +1,47 @@
1
+ // src/load.ts
2
+ import path from "path";
3
+ import fs from "fs";
4
+ var LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
5
+ function parse(content, emptyStringsAsUndefined) {
6
+ const normalizedContent = content.replace(/\r\n?/g, `
7
+ `);
8
+ const result = {};
9
+ for (const match of normalizedContent.matchAll(LINE)) {
10
+ const key = match[1];
11
+ let value = (match[2] || "").trim();
12
+ if (key === undefined)
13
+ continue;
14
+ if (value === "" && emptyStringsAsUndefined)
15
+ continue;
16
+ const isDoubleQuoted = value[0] === '"';
17
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
18
+ if (isDoubleQuoted) {
19
+ value = value.replace(/\\n/g, `
20
+ `);
21
+ value = value.replace(/\\r/g, "\r");
22
+ }
23
+ result[key] = value;
24
+ }
25
+ return result;
26
+ }
27
+ function loadEnvironment(options) {
28
+ const { root = process.cwd(), files, emptyStringsAsUndefined = true, debug = false } = options;
29
+ let combinedResult = {};
30
+ for (const filename of files) {
31
+ const dotenvPath = path.resolve(root, filename);
32
+ if (!fs.existsSync(dotenvPath)) {
33
+ if (debug)
34
+ console.warn(`Skipping "${filename}", file missing`);
35
+ continue;
36
+ }
37
+ const content = fs.readFileSync(dotenvPath, { encoding: "utf-8" });
38
+ const result = parse(content, emptyStringsAsUndefined);
39
+ combinedResult = { ...combinedResult, ...result };
40
+ if (debug)
41
+ console.log(`Loaded "${filename}" (${Object.keys(result).length})`);
42
+ }
43
+ return combinedResult;
44
+ }
45
+ export {
46
+ loadEnvironment
47
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "sane-env",
3
+ "version": "0.1.1",
4
+ "description": "Mode dependent environment loader with schema validation.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./load": {
15
+ "types": "./dist/load.d.ts",
16
+ "import": "./dist/load.js",
17
+ "default": "./dist/load.js"
18
+ },
19
+ "./config": {
20
+ "types": "./dist/config/index.d.ts",
21
+ "import": "./dist/config/index.js",
22
+ "default": "./dist/config/index.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "sideEffects": [
32
+ "./dist/config/index.js"
33
+ ],
34
+ "scripts": {
35
+ "build": "rm -rf dist && bun build src/index.ts src/load.ts src/config/index.ts --outdir dist --target node --format esm && bunx tsc -p tsconfig.json --noEmit false --emitDeclarationOnly",
36
+ "prepublishOnly": "bun run build"
37
+ },
38
+ "author": {
39
+ "name": "Zyrakia",
40
+ "email": "mail@zyrakia.dev",
41
+ "url": "https://github.com/zyrakia"
42
+ },
43
+ "license": "MIT",
44
+ "devDependencies": {
45
+ "@types/bun": "latest",
46
+ "zod": "^4.3.6"
47
+ },
48
+ "dependencies": {
49
+ "@standard-schema/spec": "^1.1.0"
50
+ }
51
+ }