@zigordev/config 0.0.0 → 1.8.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/README.md CHANGED
@@ -1,3 +1,111 @@
1
1
  # @zigordev/config
2
2
 
3
- This is the first, empty version of this package. The pipeline of [zigordev/toolkit](https://github.com/zigordev/toolkit) publishes every later one.
3
+ One function that reads an app's settings from the environment, once, through a Zod schema. When a setting is missing or wrong, the app stops as it starts, and says which ones.
4
+
5
+ ## What it is
6
+
7
+ An app describes its settings in one place, as a schema. A schema is a description of data that a program can check: here, the name of each environment variable, its type and its rules. Zod is the library the schema is written with.
8
+
9
+ | Export | What it is |
10
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------- |
11
+ | `loadConfig(schema, options?)` | Reads the variables the schema names, and returns them checked, typed and frozen |
12
+ | `ConfigError` | The error it throws. Its `message` has one line per problem, and its `issues` hold the same as a list |
13
+ | `ConfigIssue` | The type of one problem: the `variable` and the `message` |
14
+ | `Env`, `LoadConfigOptions` | The types of what `loadConfig` accepts |
15
+
16
+ ## Why we have it
17
+
18
+ Every app on the platform promises to read all its settings from environment variables and to check them once, at start. [The platform](../../docs/handbook/the-platform.md) lists that promise with the eleven others. This package keeps it for a TypeScript app.
19
+
20
+ Without it, three things go wrong:
21
+
22
+ - Each app writes its own loader, and each one differs a little.
23
+ - A missing setting shows late. The app starts, and it fails at the first request that needs the setting, which can be days after the deploy. Checked at start, the new version never becomes healthy, so it never receives traffic.
24
+ - Code reads `process.env` wherever it likes, and nobody can say which settings an app needs.
25
+
26
+ ## How it works here
27
+
28
+ `loadConfig` does five things, in this order:
29
+
30
+ 1. It reads from the environment only the variables that the schema names. It ignores every other variable.
31
+ 2. It treats an empty variable as one that is not set. A compose file that takes a value from a variable nobody set passes it on empty, and empty text would otherwise pass as the number 0.
32
+ 3. It checks the values against the schema. The schema also turns text into numbers and booleans and fills in the defaults.
33
+ 4. When anything is wrong, it throws one `ConfigError` that lists every problem at once, so one failed start shows them all.
34
+ 5. Otherwise it returns the settings, typed from the schema and frozen, so no code changes them later.
35
+
36
+ A problem is named by its variable. A variable with no value reads `is missing`, and a wrong value gets the reason that Zod gives:
37
+
38
+ ```text
39
+ ConfigError: Invalid configuration:
40
+ - PORT: Invalid input: expected number, received NaN
41
+ - DATABASE_URL: is missing
42
+ - LOG_LEVEL: Invalid option: expected one of "debug"|"info"|"warn"|"error"
43
+ ```
44
+
45
+ Neither the message nor `issues` ever holds a value, because Zod's own messages name the rule and not the input. A secret therefore cannot reach a log through this error. A message that a schema's author writes is the author's to keep free of values.
46
+
47
+ The package does not stop the process itself, and it does not log. The app calls `loadConfig` while it starts and does not catch the error. Node.js then prints the error to its error output and exits with code 1, before the app listens on its port.
48
+
49
+ Nothing differs between the laptop and production except the values. In both, an app gets its settings as environment variables only, so this package reads no file.
50
+
51
+ Zod is a peer dependency: the app installs it, and the app and this package share one copy.
52
+
53
+ ## How to use it
54
+
55
+ Add the package and Zod to the app:
56
+
57
+ ```bash
58
+ pnpm add @zigordev/config zod
59
+ ```
60
+
61
+ The worked example is the `src/config.ts` of an API. It is the only file of the app that reads the environment:
62
+
63
+ ```ts
64
+ import { loadConfig } from '@zigordev/config';
65
+ import * as z from 'zod';
66
+
67
+ export const config = loadConfig(
68
+ z.object({
69
+ PORT: z.coerce.number().int().min(1).max(65535).default(3000),
70
+ LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
71
+ DATABASE_URL: z.url(),
72
+ SIGNUP_OPEN: z.stringbool().default(true),
73
+ })
74
+ );
75
+ ```
76
+
77
+ Every other file imports `config`. Here `config.PORT` is a `number` and `config.SIGNUP_OPEN` is a `boolean`, and a misspelt name does not compile.
78
+
79
+ The environment holds only text, so the schema says how to read each value:
80
+
81
+ | The setting is | Write | Why |
82
+ | ----------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
83
+ | A number | `z.coerce.number()`, with its limits | It turns the text into a number, and text that is no number fails |
84
+ | True or false | `z.stringbool()` | It reads `true`, `false`, `1`, `0`, `yes` and `no`. `z.coerce.boolean()` reads every text as true, `false` too |
85
+ | One of a few words | `z.enum([...])` | Any other word fails, and the message lists the words |
86
+ | Not required | `.optional()`, or `.default(...)` | Without one of them the variable is required |
87
+ | Tied to another setting | `.refine(...)` on the object, with a `path` | The problem is then named by the variable the `path` gives |
88
+
89
+ A test passes the values in and leaves `process.env` alone:
90
+
91
+ ```ts
92
+ const config = loadConfig(schema, {
93
+ env: { PORT: '8080', DATABASE_URL: 'postgres://db:5432/app' },
94
+ });
95
+ ```
96
+
97
+ ## How to check that it works
98
+
99
+ | Try this | What must happen |
100
+ | -------------------------------------------------------- | -------------------------------------------------------------------------------------- |
101
+ | Start the app with a required variable not set | It exits with code 1 before it listens, and its error output has `- NAME: is missing` |
102
+ | Start it with a wrong value, such as `PORT=eighty` | It exits with code 1. The line names `PORT` and the reason, and the value is not shown |
103
+ | Start it with two wrong values | Both are listed in the one error |
104
+ | Start it with an empty value for a variable with default | It starts, and the setting has its default |
105
+ | Read `config.PORT` in the editor | Its type is `number` |
106
+
107
+ When the error says a variable is missing and you did set it, the value is empty or the variable never reached the app. A container gets only the variables that its compose file names.
108
+
109
+ When a wrong value gets through, the schema is too loose for it. Give a number its limits, and read true and false with `z.stringbool()`.
110
+
111
+ When a problem reads `(config)` in place of a variable, a rule on the whole schema failed and has no `path`. Add one, so the line names the variable to fix.
@@ -0,0 +1,10 @@
1
+ export interface ConfigIssue {
2
+ readonly variable: string;
3
+ readonly message: string;
4
+ }
5
+ export declare class ConfigError extends Error {
6
+ readonly name = "ConfigError";
7
+ readonly issues: readonly ConfigIssue[];
8
+ constructor(issues: readonly ConfigIssue[]);
9
+ }
10
+ //# sourceMappingURL=config-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-error.d.ts","sourceRoot":"","sources":["../src/config-error.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED,qBAAa,WAAY,SAAQ,KAAK;IACpC,SAAkB,IAAI,iBAAiB;IACvC,QAAQ,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,CAAC;IAExC,YAAY,MAAM,EAAE,SAAS,WAAW,EAAE,EAIzC;CACF"}
@@ -0,0 +1,10 @@
1
+ export class ConfigError extends Error {
2
+ name = 'ConfigError';
3
+ issues;
4
+ constructor(issues) {
5
+ const lines = issues.map((issue) => `- ${issue.variable}: ${issue.message}`);
6
+ super(['Invalid configuration:', ...lines].join('\n'));
7
+ this.issues = issues;
8
+ }
9
+ }
10
+ //# sourceMappingURL=config-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-error.js","sourceRoot":"","sources":["../src/config-error.ts"],"names":[],"mappings":"AAKA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,MAAM,CAAyB;IAExC,YAAY,MAA8B;QACxC,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7E,KAAK,CAAC,CAAC,wBAAwB,EAAE,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF"}
@@ -0,0 +1,5 @@
1
+ export type { ConfigIssue } from './config-error.ts';
2
+ export { ConfigError } from './config-error.ts';
3
+ export type { Env, LoadConfigOptions } from './load-config.ts';
4
+ export { loadConfig } from './load-config.ts';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,YAAY,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ConfigError } from './config-error.js';
2
+ export { loadConfig } from './load-config.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type * as z from 'zod';
2
+ export type Env = Readonly<Record<string, string | undefined>>;
3
+ export interface LoadConfigOptions {
4
+ readonly env?: Env;
5
+ }
6
+ export declare function loadConfig<Schema extends z.ZodObject>(schema: Schema, options?: LoadConfigOptions): Readonly<z.output<Schema>>;
7
+ //# sourceMappingURL=load-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-config.d.ts","sourceRoot":"","sources":["../src/load-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,CAAC,MAAM,KAAK,CAAC;AAG9B,MAAM,MAAM,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AAE/D,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC;CACpB;AAyBD,wBAAgB,UAAU,CAAC,MAAM,SAAS,CAAC,CAAC,SAAS,EACnD,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,iBAAsB,GAC9B,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAO5B"}
@@ -0,0 +1,28 @@
1
+ import { ConfigError } from './config-error.js';
2
+ function readVariables(names, env) {
3
+ const input = {};
4
+ for (const name of names) {
5
+ const value = env[name];
6
+ if (value !== undefined && value !== '') {
7
+ input[name] = value;
8
+ }
9
+ }
10
+ return input;
11
+ }
12
+ function describe(issue, input) {
13
+ if (issue.path.length === 0) {
14
+ return { variable: '(config)', message: issue.message };
15
+ }
16
+ const variable = issue.path.map(String).join('.');
17
+ const missing = issue.path.length === 1 && input[variable] === undefined && issue.code !== 'custom';
18
+ return { variable, message: missing ? 'is missing' : issue.message };
19
+ }
20
+ export function loadConfig(schema, options = {}) {
21
+ const input = readVariables(Object.keys(schema.shape), options.env ?? process.env);
22
+ const result = schema.safeParse(input);
23
+ if (!result.success) {
24
+ throw new ConfigError(result.error.issues.map((issue) => describe(issue, input)));
25
+ }
26
+ return Object.freeze(result.data);
27
+ }
28
+ //# sourceMappingURL=load-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-config.js","sourceRoot":"","sources":["../src/load-config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAoB,MAAM,mBAAmB,CAAC;AAUlE,SAAS,aAAa,CAAC,KAAwB,EAAE,GAAQ;IACvD,MAAM,KAAK,GAA2B,EAAE,CAAC;IACzC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;QACxB,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;YACxC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;QACtB,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,QAAQ,CAAC,KAAuB,EAAE,KAAY;IACrD,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAC1D,CAAC;IACD,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,MAAM,OAAO,GACX,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;IACtF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;AACvE,CAAC;AAED,MAAM,UAAU,UAAU,CACxB,MAAc,EACd,OAAO,GAAsB,EAAE;IAE/B,MAAM,KAAK,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC;IACnF,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACpC,CAAC"}
package/package.json CHANGED
@@ -1,10 +1,41 @@
1
1
  {
2
2
  "name": "@zigordev/config",
3
- "version": "0.0.0",
4
- "description": "The first, empty version of this package. The pipeline of zigordev/toolkit publishes every later one.",
3
+ "version": "1.8.0",
4
+ "description": "Configuration for zigordev apps: the environment, read once through a Zod schema, and a start that fails when a value is missing or wrong",
5
5
  "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "peerDependencies": {
20
+ "zod": "^4.6.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "26.6.6",
24
+ "@zigordev/dev": "1.8.0",
25
+ "typescript": "7.0.2",
26
+ "vitest": "5.1.1",
27
+ "zod": "4.6.7"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
6
32
  "repository": {
7
33
  "type": "git",
8
- "url": "git+https://github.com/zigordev/toolkit.git"
34
+ "url": "git+https://github.com/zigordev/toolkit.git",
35
+ "directory": "packages/config"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "typecheck": "tsc -p tsconfig.json"
9
40
  }
10
- }
41
+ }