c12 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 - UnJS
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,118 @@
1
+ # c12
2
+
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![Github Actions][github-actions-src]][github-actions-href]
6
+ [![Codecov][codecov-src]][codecov-href]
7
+
8
+ > Smart Config Loader
9
+
10
+ ## Features
11
+
12
+ - JSON, CJS, Typescript and ESM config loader with [unjs/jiti](https://github.com/unjs/jiti)
13
+ - RC config support with [unjs/rc9](https://github.com/unjs/rc9)
14
+ - Multiple sources merged with [unjs/defu](https://github.com/unjs/defu)
15
+ - `.env` support with [dotenv](https://www.npmjs.com/package/dotenv)
16
+
17
+ ## Usage
18
+
19
+ Install package:
20
+
21
+ ```sh
22
+ # npm
23
+ npm install c12
24
+
25
+ # yarn
26
+ yarn install c12
27
+
28
+ # pnpm
29
+ pnpm install c12
30
+ ```
31
+
32
+ Import:
33
+
34
+ ```js
35
+ // ESM
36
+ import { loadConfig } from 'c12'
37
+
38
+ // CommonJS
39
+ const { loadConfig } = require('c12')
40
+ ```
41
+
42
+ Load configuration:
43
+
44
+ ```js
45
+ const { config } = await loadConfig({})
46
+ ```
47
+
48
+ ## Loading priority
49
+
50
+ c12 merged config sources with [unjs/defu](https://github.com/unjs/defu) by below order:
51
+
52
+ 1. config overrides passed by options
53
+ 2. config file in CWD
54
+ 3. RC file in CWD
55
+ 4. global RC file in user's home directory
56
+ 5. default config passed by options
57
+
58
+ ## Options
59
+
60
+ ### `cwd`
61
+
62
+ Resolve configuration from this working directory. Default is `process.cwd()`
63
+
64
+ ### `name`
65
+
66
+ Configuration base name. Default is `config`.
67
+
68
+ ### `configName`
69
+
70
+ Configuration file name without extension . Default is generated from `name` (name=foo => `foo.config`).
71
+
72
+ Set to `false` to avoid loading config file.
73
+
74
+ ### `rcFile`
75
+
76
+ RC Config file name. Default is generated from `name` (name=foo => `.foorc`).
77
+
78
+ Set to `false` to disable loading RC config.
79
+
80
+ ### `globalRC`
81
+
82
+ Load RC config from the user's home directory. Only enabled when `rcFile` is provided. Set to `false` to disable this functionality.
83
+
84
+ ### `dotenv`
85
+
86
+ Loads `.env` file if enabled. It is disabled by default.
87
+
88
+ ### `defaults`
89
+
90
+ Specify default configuration. It has the **lowest** priority.
91
+
92
+ ### `overides`
93
+
94
+ Specify override configuration. It has the **highest** priority.
95
+
96
+ ## 💻 Development
97
+
98
+ - Clone this repository
99
+ - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10)
100
+ - Install dependencies using `yarn install`
101
+ - Run interactive tests using `yarn dev`
102
+
103
+ ## License
104
+
105
+ Made with 💛 Published under [MIT License](./LICENSE).
106
+
107
+ <!-- Badges -->
108
+ [npm-version-src]: https://img.shields.io/npm/v/c12?style=flat-square
109
+ [npm-version-href]: https://npmjs.com/package/c12
110
+
111
+ [npm-downloads-src]: https://img.shields.io/npm/dm/c12?style=flat-square
112
+ [npm-downloads-href]: https://npmjs.com/package/c12
113
+
114
+ [github-actions-src]: https://img.shields.io/github/workflow/status/unjs/c12/ci/main?style=flat-square
115
+ [github-actions-href]: https://github.com/unjs/c12/actions?query=workflow%3Aci
116
+
117
+ [codecov-src]: https://img.shields.io/codecov/c/gh/unjs/c12/main?style=flat-square
118
+ [codecov-href]: https://codecov.io/gh/unjs/c12
package/dist/index.cjs ADDED
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const fs = require('fs');
6
+ const pathe = require('pathe');
7
+ const dotenv = require('dotenv');
8
+ const createJiti = require('jiti');
9
+ const rc9 = require('rc9');
10
+ const defu = require('defu');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
13
+
14
+ function _interopNamespace(e) {
15
+ if (e && e.__esModule) return e;
16
+ const n = Object.create(null);
17
+ if (e) {
18
+ for (const k in e) {
19
+ n[k] = e[k];
20
+ }
21
+ }
22
+ n["default"] = e;
23
+ return n;
24
+ }
25
+
26
+ const dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
27
+ const createJiti__default = /*#__PURE__*/_interopDefaultLegacy(createJiti);
28
+ const rc9__namespace = /*#__PURE__*/_interopNamespace(rc9);
29
+ const defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
30
+
31
+ async function setupDotenv(options) {
32
+ const targetEnv = options.env ?? process.env;
33
+ const env = await loadDotenv({
34
+ cwd: options.cwd,
35
+ fileName: options.fileName ?? ".env",
36
+ env: targetEnv,
37
+ interpolate: options.interpolate ?? true
38
+ });
39
+ for (const key in env) {
40
+ if (!key.startsWith("_") && targetEnv[key] === void 0) {
41
+ targetEnv[key] = env[key];
42
+ }
43
+ }
44
+ return env;
45
+ }
46
+ async function loadDotenv(opts) {
47
+ const env = /* @__PURE__ */ Object.create(null);
48
+ const dotenvFile = pathe.resolve(opts.cwd, opts.fileName);
49
+ if (fs.existsSync(dotenvFile)) {
50
+ const parsed = dotenv__namespace.parse(await fs.promises.readFile(dotenvFile, "utf-8"));
51
+ Object.assign(env, parsed);
52
+ }
53
+ if (!opts.env._applied) {
54
+ Object.assign(env, opts.env);
55
+ env._applied = true;
56
+ }
57
+ if (opts.interpolate) {
58
+ interpolate(env);
59
+ }
60
+ return env;
61
+ }
62
+ function interpolate(target, source = {}, parse = (v) => v) {
63
+ function getValue(key) {
64
+ return source[key] !== void 0 ? source[key] : target[key];
65
+ }
66
+ function interpolate2(value, parents = []) {
67
+ if (typeof value !== "string") {
68
+ return value;
69
+ }
70
+ const matches = value.match(/(.?\${?(?:[a-zA-Z0-9_:]+)?}?)/g) || [];
71
+ return parse(matches.reduce((newValue, match) => {
72
+ const parts = /(.?)\${?([a-zA-Z0-9_:]+)?}?/g.exec(match);
73
+ const prefix = parts[1];
74
+ let value2, replacePart;
75
+ if (prefix === "\\") {
76
+ replacePart = parts[0];
77
+ value2 = replacePart.replace("\\$", "$");
78
+ } else {
79
+ const key = parts[2];
80
+ replacePart = parts[0].substring(prefix.length);
81
+ if (parents.includes(key)) {
82
+ console.warn(`Please avoid recursive environment variables ( loop: ${parents.join(" > ")} > ${key} )`);
83
+ return "";
84
+ }
85
+ value2 = getValue(key);
86
+ value2 = interpolate2(value2, [...parents, key]);
87
+ }
88
+ return value2 !== void 0 ? newValue.replace(replacePart, value2) : newValue;
89
+ }, value));
90
+ }
91
+ for (const key in target) {
92
+ target[key] = interpolate2(getValue(key));
93
+ }
94
+ }
95
+
96
+ async function loadConfig(opts) {
97
+ opts.cwd = pathe.resolve(process.cwd(), opts.cwd || ".");
98
+ opts.name = opts.name || "config";
99
+ opts.configFile = opts.configFile ?? (opts.name !== "config" ? `${opts.name}.config` : "config");
100
+ opts.rcFile = opts.rcFile ?? `.${opts.name}rc`;
101
+ const ctx = {
102
+ config: {}
103
+ };
104
+ if (opts.dotenv) {
105
+ ctx.env = await setupDotenv({
106
+ cwd: opts.cwd,
107
+ ...opts.dotenv === true ? {} : opts.dotenv
108
+ });
109
+ }
110
+ const { config, configPath } = await loadConfigFile(opts);
111
+ ctx.configPath = configPath;
112
+ const configRC = {};
113
+ if (opts.rcFile) {
114
+ if (opts.globalRc) {
115
+ Object.assign(configRC, rc9__namespace.readUser({ name: opts.rcFile, dir: opts.cwd }));
116
+ }
117
+ Object.assign(configRC, rc9__namespace.read({ name: opts.rcFile, dir: opts.cwd }));
118
+ }
119
+ ctx.config = defu__default(opts.overrides, config, configRC, opts.defaults);
120
+ return ctx;
121
+ }
122
+ const jiti = createJiti__default(null, { cache: false, interopDefault: true });
123
+ async function loadConfigFile(opts) {
124
+ const res = {
125
+ configPath: null,
126
+ config: null
127
+ };
128
+ if (!opts.configFile) {
129
+ return res;
130
+ }
131
+ try {
132
+ res.configPath = jiti.resolve(pathe.resolve(opts.cwd, opts.configFile), { paths: [opts.cwd] });
133
+ res.config = jiti(res.configPath);
134
+ if (typeof res.config === "function") {
135
+ res.config = await res.config();
136
+ }
137
+ } catch (err) {
138
+ if (err.code !== "MODULE_NOT_FOUND") {
139
+ throw err;
140
+ }
141
+ }
142
+ return res;
143
+ }
144
+
145
+ exports.loadConfig = loadConfig;
146
+ exports.loadDotenv = loadDotenv;
147
+ exports.setupDotenv = setupDotenv;
@@ -0,0 +1,55 @@
1
+ interface DotenvOptions {
2
+ /**
3
+ * The project root directory (either absolute or relative to the current working directory).
4
+ */
5
+ cwd: string;
6
+ /**
7
+ * What file to look in for environment variables (either absolute or relative
8
+ * to the current working directory). For example, `.env`.
9
+ */
10
+ fileName?: string;
11
+ /**
12
+ * Whether to interpolate variables within .env.
13
+ *
14
+ * @example
15
+ * ```env
16
+ * BASE_DIR="/test"
17
+ * # resolves to "/test/further"
18
+ * ANOTHER_DIR="${BASE_DIR}/further"
19
+ * ```
20
+ */
21
+ interpolate?: boolean;
22
+ /**
23
+ * An object describing environment variables (key, value pairs).
24
+ */
25
+ env?: NodeJS.ProcessEnv;
26
+ }
27
+ declare type Env = typeof process.env;
28
+ /**
29
+ * Load and interpolate environment variables into `process.env`.
30
+ * If you need more control (or access to the values), consider using `loadDotenv` instead
31
+ *
32
+ */
33
+ declare function setupDotenv(options: DotenvOptions): Promise<Env>;
34
+ /** Load environment variables into an object. */
35
+ declare function loadDotenv(opts: DotenvOptions): Promise<Env>;
36
+
37
+ declare type ConfigT = Record<string, any>;
38
+ interface LoadConfigOptions<T extends ConfigT = ConfigT> {
39
+ name?: string;
40
+ cwd?: string;
41
+ configFile?: false | string;
42
+ rcFile?: false | string;
43
+ globalRc?: boolean;
44
+ dotenv?: boolean | DotenvOptions;
45
+ defaults?: T;
46
+ overrides?: T;
47
+ }
48
+ interface ResolvedConfig<T extends ConfigT = ConfigT> {
49
+ config: T;
50
+ configPath?: string;
51
+ env?: Record<string, any>;
52
+ }
53
+ declare function loadConfig<T extends ConfigT = ConfigT>(opts: LoadConfigOptions<T>): Promise<ResolvedConfig<T>>;
54
+
55
+ export { ConfigT, DotenvOptions, Env, LoadConfigOptions, ResolvedConfig, loadConfig, loadDotenv, setupDotenv };
package/dist/index.mjs ADDED
@@ -0,0 +1,122 @@
1
+ import { existsSync, promises } from 'fs';
2
+ import { resolve } from 'pathe';
3
+ import * as dotenv from 'dotenv';
4
+ import createJiti from 'jiti';
5
+ import * as rc9 from 'rc9';
6
+ import defu from 'defu';
7
+
8
+ async function setupDotenv(options) {
9
+ const targetEnv = options.env ?? process.env;
10
+ const env = await loadDotenv({
11
+ cwd: options.cwd,
12
+ fileName: options.fileName ?? ".env",
13
+ env: targetEnv,
14
+ interpolate: options.interpolate ?? true
15
+ });
16
+ for (const key in env) {
17
+ if (!key.startsWith("_") && targetEnv[key] === void 0) {
18
+ targetEnv[key] = env[key];
19
+ }
20
+ }
21
+ return env;
22
+ }
23
+ async function loadDotenv(opts) {
24
+ const env = /* @__PURE__ */ Object.create(null);
25
+ const dotenvFile = resolve(opts.cwd, opts.fileName);
26
+ if (existsSync(dotenvFile)) {
27
+ const parsed = dotenv.parse(await promises.readFile(dotenvFile, "utf-8"));
28
+ Object.assign(env, parsed);
29
+ }
30
+ if (!opts.env._applied) {
31
+ Object.assign(env, opts.env);
32
+ env._applied = true;
33
+ }
34
+ if (opts.interpolate) {
35
+ interpolate(env);
36
+ }
37
+ return env;
38
+ }
39
+ function interpolate(target, source = {}, parse = (v) => v) {
40
+ function getValue(key) {
41
+ return source[key] !== void 0 ? source[key] : target[key];
42
+ }
43
+ function interpolate2(value, parents = []) {
44
+ if (typeof value !== "string") {
45
+ return value;
46
+ }
47
+ const matches = value.match(/(.?\${?(?:[a-zA-Z0-9_:]+)?}?)/g) || [];
48
+ return parse(matches.reduce((newValue, match) => {
49
+ const parts = /(.?)\${?([a-zA-Z0-9_:]+)?}?/g.exec(match);
50
+ const prefix = parts[1];
51
+ let value2, replacePart;
52
+ if (prefix === "\\") {
53
+ replacePart = parts[0];
54
+ value2 = replacePart.replace("\\$", "$");
55
+ } else {
56
+ const key = parts[2];
57
+ replacePart = parts[0].substring(prefix.length);
58
+ if (parents.includes(key)) {
59
+ console.warn(`Please avoid recursive environment variables ( loop: ${parents.join(" > ")} > ${key} )`);
60
+ return "";
61
+ }
62
+ value2 = getValue(key);
63
+ value2 = interpolate2(value2, [...parents, key]);
64
+ }
65
+ return value2 !== void 0 ? newValue.replace(replacePart, value2) : newValue;
66
+ }, value));
67
+ }
68
+ for (const key in target) {
69
+ target[key] = interpolate2(getValue(key));
70
+ }
71
+ }
72
+
73
+ async function loadConfig(opts) {
74
+ opts.cwd = resolve(process.cwd(), opts.cwd || ".");
75
+ opts.name = opts.name || "config";
76
+ opts.configFile = opts.configFile ?? (opts.name !== "config" ? `${opts.name}.config` : "config");
77
+ opts.rcFile = opts.rcFile ?? `.${opts.name}rc`;
78
+ const ctx = {
79
+ config: {}
80
+ };
81
+ if (opts.dotenv) {
82
+ ctx.env = await setupDotenv({
83
+ cwd: opts.cwd,
84
+ ...opts.dotenv === true ? {} : opts.dotenv
85
+ });
86
+ }
87
+ const { config, configPath } = await loadConfigFile(opts);
88
+ ctx.configPath = configPath;
89
+ const configRC = {};
90
+ if (opts.rcFile) {
91
+ if (opts.globalRc) {
92
+ Object.assign(configRC, rc9.readUser({ name: opts.rcFile, dir: opts.cwd }));
93
+ }
94
+ Object.assign(configRC, rc9.read({ name: opts.rcFile, dir: opts.cwd }));
95
+ }
96
+ ctx.config = defu(opts.overrides, config, configRC, opts.defaults);
97
+ return ctx;
98
+ }
99
+ const jiti = createJiti(null, { cache: false, interopDefault: true });
100
+ async function loadConfigFile(opts) {
101
+ const res = {
102
+ configPath: null,
103
+ config: null
104
+ };
105
+ if (!opts.configFile) {
106
+ return res;
107
+ }
108
+ try {
109
+ res.configPath = jiti.resolve(resolve(opts.cwd, opts.configFile), { paths: [opts.cwd] });
110
+ res.config = jiti(res.configPath);
111
+ if (typeof res.config === "function") {
112
+ res.config = await res.config();
113
+ }
114
+ } catch (err) {
115
+ if (err.code !== "MODULE_NOT_FOUND") {
116
+ throw err;
117
+ }
118
+ }
119
+ return res;
120
+ }
121
+
122
+ export { loadConfig, loadDotenv, setupDotenv };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "c12",
3
+ "version": "0.1.0",
4
+ "description": "Smart Config Loader",
5
+ "repository": "unjs/c12",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "scripts": {
22
+ "build": "unbuild",
23
+ "dev": "vitest dev",
24
+ "lint": "eslint --ext .ts,.js,.mjs,.cjs .",
25
+ "prepack": "unbuild",
26
+ "release": "yarn test && standard-version && git push --follow-tags && npm publish",
27
+ "test": "vitest run --coverage"
28
+ },
29
+ "dependencies": {
30
+ "defu": "^5.0.1",
31
+ "dotenv": "^14.3.2",
32
+ "jiti": "^1.12.14",
33
+ "mlly": "^0.4.1",
34
+ "pathe": "^0.2.0",
35
+ "rc9": "^1.2.0"
36
+ },
37
+ "devDependencies": {
38
+ "@nuxtjs/eslint-config-typescript": "latest",
39
+ "c8": "latest",
40
+ "eslint": "latest",
41
+ "standard-version": "latest",
42
+ "typescript": "latest",
43
+ "unbuild": "latest",
44
+ "vitest": "latest"
45
+ }
46
+ }