confstash 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 +21 -0
- package/README.md +200 -0
- package/discover.d.ts +27 -0
- package/discover.js +118 -0
- package/esm/discover.d.ts +27 -0
- package/esm/discover.js +80 -0
- package/esm/extends.d.ts +16 -0
- package/esm/extends.js +57 -0
- package/esm/index.d.ts +14 -0
- package/esm/index.js +13 -0
- package/esm/loader.d.ts +19 -0
- package/esm/loader.js +103 -0
- package/esm/loaders.d.ts +14 -0
- package/esm/loaders.js +129 -0
- package/esm/merge.d.ts +14 -0
- package/esm/merge.js +110 -0
- package/esm/types.d.ts +85 -0
- package/esm/types.js +4 -0
- package/extends.d.ts +16 -0
- package/extends.js +93 -0
- package/index.d.ts +14 -0
- package/index.js +28 -0
- package/loader.d.ts +19 -0
- package/loader.js +140 -0
- package/loaders.d.ts +14 -0
- package/loaders.js +171 -0
- package/merge.d.ts +14 -0
- package/merge.js +115 -0
- package/package.json +51 -0
- package/types.d.ts +85 -0
- package/types.js +5 -0
package/esm/loader.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { appstash, resolve as stashResolve } from 'appstash';
|
|
4
|
+
import { defaultSearchPlaces, findConfigSync } from './discover';
|
|
5
|
+
import { expandExtends } from './extends';
|
|
6
|
+
import { loadFile, loadFileSync } from './loaders';
|
|
7
|
+
import { explainLayers, mergeLayers } from './merge';
|
|
8
|
+
export function createConfigLoader(options) {
|
|
9
|
+
const searchPlaces = options.searchPlaces ?? defaultSearchPlaces(options.tool);
|
|
10
|
+
const presets = options.presets ?? {};
|
|
11
|
+
const arrayMerge = options.arrayMerge ?? 'replace';
|
|
12
|
+
const walkUp = options.walkUp ?? true;
|
|
13
|
+
function discover(params) {
|
|
14
|
+
if (params.configFile) {
|
|
15
|
+
const filepath = path.resolve(params.cwd ?? process.cwd(), params.configFile);
|
|
16
|
+
if (!fs.existsSync(filepath)) {
|
|
17
|
+
throw new Error(`Config file not found: ${filepath}`);
|
|
18
|
+
}
|
|
19
|
+
return { filepath };
|
|
20
|
+
}
|
|
21
|
+
return findConfigSync(params.cwd ?? process.cwd(), searchPlaces, walkUp);
|
|
22
|
+
}
|
|
23
|
+
function buildLayers(params, found, fileConfig) {
|
|
24
|
+
const layers = [];
|
|
25
|
+
if (options.defaults) {
|
|
26
|
+
layers.push({ source: 'defaults', origin: 'built-in defaults', config: options.defaults });
|
|
27
|
+
}
|
|
28
|
+
if (options.userStash) {
|
|
29
|
+
const user = readUserStash(options.tool);
|
|
30
|
+
if (user)
|
|
31
|
+
layers.push(user);
|
|
32
|
+
}
|
|
33
|
+
if (found && fileConfig) {
|
|
34
|
+
const baseDir = path.dirname(found.filepath);
|
|
35
|
+
const expanded = expandExtends(fileConfig, { presets, baseDir }, found.filepath);
|
|
36
|
+
layers.push(...expanded);
|
|
37
|
+
}
|
|
38
|
+
if (options.envLayer) {
|
|
39
|
+
const env = params.env ?? process.env;
|
|
40
|
+
const envConfig = options.envLayer(env);
|
|
41
|
+
if (envConfig && Object.keys(envConfig).length > 0) {
|
|
42
|
+
layers.push({ source: 'env', origin: 'environment variables', config: envConfig });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (params.overrides && Object.keys(params.overrides).length > 0) {
|
|
46
|
+
layers.push({ source: 'overrides', origin: 'runtime overrides', config: params.overrides });
|
|
47
|
+
}
|
|
48
|
+
return layers;
|
|
49
|
+
}
|
|
50
|
+
function finalize(params, found, fileConfig) {
|
|
51
|
+
const layers = buildLayers(params, found, fileConfig);
|
|
52
|
+
let config = mergeLayers(layers, arrayMerge);
|
|
53
|
+
if (options.validate) {
|
|
54
|
+
const validated = options.validate(config);
|
|
55
|
+
if (validated !== undefined)
|
|
56
|
+
config = validated;
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
config,
|
|
60
|
+
filepath: found?.filepath,
|
|
61
|
+
layers,
|
|
62
|
+
isEmpty: found == null
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
searchPlaces,
|
|
67
|
+
async load(params = {}) {
|
|
68
|
+
const found = discover(params);
|
|
69
|
+
const fileConfig = found ? (await loadFile(found)) : null;
|
|
70
|
+
return finalize(params, found, fileConfig);
|
|
71
|
+
},
|
|
72
|
+
loadSync(params = {}) {
|
|
73
|
+
const found = discover(params);
|
|
74
|
+
const fileConfig = found ? loadFileSync(found) : null;
|
|
75
|
+
return finalize(params, found, fileConfig);
|
|
76
|
+
},
|
|
77
|
+
explainSync(params = {}) {
|
|
78
|
+
const found = discover(params);
|
|
79
|
+
const fileConfig = found ? loadFileSync(found) : null;
|
|
80
|
+
const layers = buildLayers(params, found, fileConfig);
|
|
81
|
+
return explainLayers(layers, arrayMerge);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function readUserStash(tool) {
|
|
86
|
+
try {
|
|
87
|
+
const dirs = appstash(tool);
|
|
88
|
+
const filepath = stashResolve(dirs, 'config', 'config.json');
|
|
89
|
+
if (!fs.existsSync(filepath))
|
|
90
|
+
return null;
|
|
91
|
+
const config = JSON.parse(fs.readFileSync(filepath, 'utf8'));
|
|
92
|
+
if (config == null || typeof config !== 'object' || Array.isArray(config))
|
|
93
|
+
return null;
|
|
94
|
+
return { source: 'user', origin: filepath, config: config };
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Identity helper for typed config authoring in `<tool>.config.ts/js`. */
|
|
101
|
+
export function defineConfig(config) {
|
|
102
|
+
return config;
|
|
103
|
+
}
|
package/esm/loaders.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { FoundConfig } from './discover';
|
|
2
|
+
export declare class ConfigLoadError extends Error {
|
|
3
|
+
readonly filepath: string;
|
|
4
|
+
readonly cause?: unknown;
|
|
5
|
+
constructor(message: string, filepath: string, cause?: unknown);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Load a config file synchronously. Supports .json, .yaml/.yml, extensionless
|
|
9
|
+
* rc files (JSON or YAML), .js/.cjs (require), and .ts (require — needs a TS
|
|
10
|
+
* runtime like ts-node/tsx registered). `.mjs` requires the async loader.
|
|
11
|
+
*/
|
|
12
|
+
export declare function loadFileSync(found: FoundConfig): Record<string, unknown>;
|
|
13
|
+
/** Async variant of {@link loadFileSync} that additionally supports `.mjs` and ESM `.js`. */
|
|
14
|
+
export declare function loadFile(found: FoundConfig): Promise<Record<string, unknown>>;
|
package/esm/loaders.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import yaml from 'js-yaml';
|
|
4
|
+
export class ConfigLoadError extends Error {
|
|
5
|
+
filepath;
|
|
6
|
+
cause;
|
|
7
|
+
constructor(message, filepath, cause) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.filepath = filepath;
|
|
10
|
+
this.cause = cause;
|
|
11
|
+
this.name = 'ConfigLoadError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Load a config file synchronously. Supports .json, .yaml/.yml, extensionless
|
|
16
|
+
* rc files (JSON or YAML), .js/.cjs (require), and .ts (require — needs a TS
|
|
17
|
+
* runtime like ts-node/tsx registered). `.mjs` requires the async loader.
|
|
18
|
+
*/
|
|
19
|
+
export function loadFileSync(found) {
|
|
20
|
+
const { filepath, packageJsonKey } = found;
|
|
21
|
+
if (packageJsonKey) {
|
|
22
|
+
const pkg = parseJsonFile(filepath);
|
|
23
|
+
return asObject(pkg[packageJsonKey], filepath, `package.json key "${packageJsonKey}"`);
|
|
24
|
+
}
|
|
25
|
+
const ext = path.extname(filepath);
|
|
26
|
+
switch (ext) {
|
|
27
|
+
case '.json':
|
|
28
|
+
return asObject(parseJsonFile(filepath), filepath, 'JSON config');
|
|
29
|
+
case '.yaml':
|
|
30
|
+
case '.yml':
|
|
31
|
+
return asObject(parseYamlFile(filepath), filepath, 'YAML config');
|
|
32
|
+
case '.js':
|
|
33
|
+
case '.cjs':
|
|
34
|
+
case '.ts':
|
|
35
|
+
return requireModule(filepath);
|
|
36
|
+
case '.mjs':
|
|
37
|
+
throw new ConfigLoadError(`Cannot load ESM config "${filepath}" synchronously — use the async loader (load()) instead.`, filepath);
|
|
38
|
+
case '': {
|
|
39
|
+
// extensionless rc file: try JSON first, then YAML
|
|
40
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
41
|
+
try {
|
|
42
|
+
return asObject(JSON.parse(raw), filepath, 'rc config');
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return asObject(yaml.load(raw), filepath, 'rc config');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
default:
|
|
49
|
+
throw new ConfigLoadError(`Unsupported config file type: ${ext}`, filepath);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Async variant of {@link loadFileSync} that additionally supports `.mjs` and ESM `.js`. */
|
|
53
|
+
export async function loadFile(found) {
|
|
54
|
+
const { filepath } = found;
|
|
55
|
+
const ext = path.extname(filepath);
|
|
56
|
+
if (ext === '.mjs') {
|
|
57
|
+
return importModule(filepath);
|
|
58
|
+
}
|
|
59
|
+
if (ext === '.js' || ext === '.ts') {
|
|
60
|
+
try {
|
|
61
|
+
return loadFileSync(found);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
// ESM ".js" (package "type": "module") fails require() — fall back to import()
|
|
65
|
+
if (isEsmRequireError(err)) {
|
|
66
|
+
return importModule(filepath);
|
|
67
|
+
}
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return loadFileSync(found);
|
|
72
|
+
}
|
|
73
|
+
function isEsmRequireError(err) {
|
|
74
|
+
const code = err?.code
|
|
75
|
+
?? err?.cause?.code;
|
|
76
|
+
return code === 'ERR_REQUIRE_ESM';
|
|
77
|
+
}
|
|
78
|
+
function requireModule(filepath) {
|
|
79
|
+
try {
|
|
80
|
+
delete require.cache[require.resolve(filepath)];
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
82
|
+
const mod = require(filepath);
|
|
83
|
+
return asObject(mod?.default ?? mod, filepath, 'module config');
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
if (isEsmRequireError(err))
|
|
87
|
+
throw err;
|
|
88
|
+
throw new ConfigLoadError(`Failed to load config module "${filepath}": ${err.message}`, filepath, err);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async function importModule(filepath) {
|
|
92
|
+
try {
|
|
93
|
+
const { pathToFileURL } = require('url');
|
|
94
|
+
// Indirect eval keeps bundlers/transpilers (tsc CJS output, jest) from
|
|
95
|
+
// rewriting the dynamic import into a require(), which cannot load ESM.
|
|
96
|
+
const dynamicImport = new Function('u', 'return import(u)');
|
|
97
|
+
const mod = await dynamicImport(pathToFileURL(filepath).href);
|
|
98
|
+
return asObject(mod?.default ?? mod, filepath, 'module config');
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
throw new ConfigLoadError(`Failed to import config module "${filepath}": ${err.message}`, filepath, err);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function parseJsonFile(filepath) {
|
|
105
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(raw);
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
throw new ConfigLoadError(`Invalid JSON in "${filepath}": ${err.message}`, filepath, err);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function parseYamlFile(filepath) {
|
|
114
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
115
|
+
try {
|
|
116
|
+
return yaml.load(raw);
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
throw new ConfigLoadError(`Invalid YAML in "${filepath}": ${err.message}`, filepath, err);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function asObject(value, filepath, what) {
|
|
123
|
+
if (value == null)
|
|
124
|
+
return {};
|
|
125
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
126
|
+
throw new ConfigLoadError(`Expected ${what} in "${filepath}" to be an object, got ${Array.isArray(value) ? 'array' : typeof value}.`, filepath);
|
|
127
|
+
}
|
|
128
|
+
return value;
|
|
129
|
+
}
|
package/esm/merge.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ArrayMergeStrategy, ConfigLayer, ExplainedValue } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Deep-merge two values. Plain objects merge recursively; arrays follow the
|
|
4
|
+
* given strategy ('replace' by default — matching @pgpmjs/env semantics);
|
|
5
|
+
* everything else: source wins.
|
|
6
|
+
*/
|
|
7
|
+
export declare function deepMerge(target: unknown, source: unknown, arrayMerge?: ArrayMergeStrategy): unknown;
|
|
8
|
+
/** Merge layers in order (lowest precedence first). */
|
|
9
|
+
export declare function mergeLayers<T>(layers: ConfigLayer<T>[], arrayMerge?: ArrayMergeStrategy): T;
|
|
10
|
+
/**
|
|
11
|
+
* Explain the provenance of every leaf value in the merged config: for each
|
|
12
|
+
* dotted path, which layer supplied the winning value.
|
|
13
|
+
*/
|
|
14
|
+
export declare function explainLayers<T>(layers: ConfigLayer<T>[], arrayMerge?: ArrayMergeStrategy): ExplainedValue[];
|
package/esm/merge.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
function isPlainObject(value) {
|
|
2
|
+
return (value != null &&
|
|
3
|
+
typeof value === 'object' &&
|
|
4
|
+
!Array.isArray(value) &&
|
|
5
|
+
Object.getPrototypeOf(value) === Object.prototype);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Deep-merge two values. Plain objects merge recursively; arrays follow the
|
|
9
|
+
* given strategy ('replace' by default — matching @pgpmjs/env semantics);
|
|
10
|
+
* everything else: source wins.
|
|
11
|
+
*/
|
|
12
|
+
export function deepMerge(target, source, arrayMerge = 'replace') {
|
|
13
|
+
if (Array.isArray(target) && Array.isArray(source)) {
|
|
14
|
+
return arrayMerge === 'concat' ? [...target, ...source] : [...source];
|
|
15
|
+
}
|
|
16
|
+
if (isPlainObject(target) && isPlainObject(source)) {
|
|
17
|
+
const out = { ...target };
|
|
18
|
+
for (const key of Object.keys(source)) {
|
|
19
|
+
const sv = source[key];
|
|
20
|
+
if (sv === undefined)
|
|
21
|
+
continue;
|
|
22
|
+
out[key] = key in out ? deepMerge(out[key], sv, arrayMerge) : cloneValue(sv);
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
return cloneValue(source);
|
|
27
|
+
}
|
|
28
|
+
function cloneValue(value) {
|
|
29
|
+
if (Array.isArray(value))
|
|
30
|
+
return value.map(cloneValue);
|
|
31
|
+
if (isPlainObject(value)) {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const key of Object.keys(value))
|
|
34
|
+
out[key] = cloneValue(value[key]);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
/** Merge layers in order (lowest precedence first). */
|
|
40
|
+
export function mergeLayers(layers, arrayMerge = 'replace') {
|
|
41
|
+
let acc = {};
|
|
42
|
+
for (const layer of layers) {
|
|
43
|
+
acc = deepMerge(acc, layer.config, arrayMerge);
|
|
44
|
+
}
|
|
45
|
+
return acc;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Explain the provenance of every leaf value in the merged config: for each
|
|
49
|
+
* dotted path, which layer supplied the winning value.
|
|
50
|
+
*/
|
|
51
|
+
export function explainLayers(layers, arrayMerge = 'replace') {
|
|
52
|
+
const merged = mergeLayers(layers, arrayMerge);
|
|
53
|
+
const out = [];
|
|
54
|
+
const walk = (value, pathParts) => {
|
|
55
|
+
if (isPlainObject(value)) {
|
|
56
|
+
for (const key of Object.keys(value))
|
|
57
|
+
walk(value[key], [...pathParts, key]);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const dotted = pathParts.join('.');
|
|
61
|
+
const winner = findWinner(layers, pathParts, value);
|
|
62
|
+
out.push({
|
|
63
|
+
path: dotted,
|
|
64
|
+
value,
|
|
65
|
+
source: winner?.source ?? 'defaults',
|
|
66
|
+
origin: winner?.origin ?? 'unknown'
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
walk(merged, []);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
function findWinner(layers, pathParts, finalValue) {
|
|
73
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
74
|
+
const candidate = getPath(layers[i].config, pathParts);
|
|
75
|
+
if (candidate === undefined)
|
|
76
|
+
continue;
|
|
77
|
+
// Arrays with 'concat' can be composites of multiple layers; attribute to
|
|
78
|
+
// the last contributing layer regardless.
|
|
79
|
+
if (deepEqual(candidate, finalValue) || Array.isArray(finalValue)) {
|
|
80
|
+
return layers[i];
|
|
81
|
+
}
|
|
82
|
+
// The last layer that defines the path wins under deepMerge for scalars.
|
|
83
|
+
return layers[i];
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
function getPath(obj, pathParts) {
|
|
88
|
+
let cur = obj;
|
|
89
|
+
for (const part of pathParts) {
|
|
90
|
+
if (!isPlainObject(cur))
|
|
91
|
+
return undefined;
|
|
92
|
+
cur = cur[part];
|
|
93
|
+
if (cur === undefined)
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
return cur;
|
|
97
|
+
}
|
|
98
|
+
function deepEqual(a, b) {
|
|
99
|
+
if (a === b)
|
|
100
|
+
return true;
|
|
101
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
102
|
+
return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
103
|
+
}
|
|
104
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
105
|
+
const ka = Object.keys(a);
|
|
106
|
+
const kb = Object.keys(b);
|
|
107
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
package/esm/types.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core types for confstash — standardized project configuration loading.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* A place to search for configuration. Either a filename (searched during the
|
|
6
|
+
* walk-up) or a key inside `package.json`.
|
|
7
|
+
*/
|
|
8
|
+
export type SearchPlace = string | {
|
|
9
|
+
packageJson: string;
|
|
10
|
+
};
|
|
11
|
+
/** Where a resolved config value (or layer) came from. */
|
|
12
|
+
export type LayerSource = 'defaults' | 'preset' | 'user' | 'file' | 'env' | 'overrides';
|
|
13
|
+
export interface ConfigLayer<T = Record<string, unknown>> {
|
|
14
|
+
source: LayerSource;
|
|
15
|
+
/** Human-readable origin: file path, preset name, env prefix, … */
|
|
16
|
+
origin: string;
|
|
17
|
+
config: Partial<T>;
|
|
18
|
+
}
|
|
19
|
+
export interface LoadResult<T = Record<string, unknown>> {
|
|
20
|
+
/** Fully merged configuration. */
|
|
21
|
+
config: T;
|
|
22
|
+
/** Path of the project config file that was found, if any. */
|
|
23
|
+
filepath?: string;
|
|
24
|
+
/** Every layer that contributed, in merge order (lowest precedence first). */
|
|
25
|
+
layers: ConfigLayer<T>[];
|
|
26
|
+
/** Whether any project config file was found. */
|
|
27
|
+
isEmpty: boolean;
|
|
28
|
+
}
|
|
29
|
+
export type ArrayMergeStrategy = 'replace' | 'concat';
|
|
30
|
+
export interface LoadParams<T = Record<string, unknown>> {
|
|
31
|
+
/** Directory to start the walk-up search from. Default: process.cwd(). */
|
|
32
|
+
cwd?: string;
|
|
33
|
+
/** Highest-precedence overrides (e.g. parsed CLI flags). */
|
|
34
|
+
overrides?: Partial<T>;
|
|
35
|
+
/** Load an exact config file, skipping discovery. */
|
|
36
|
+
configFile?: string;
|
|
37
|
+
/** Environment to read the env layer from. Default: process.env. */
|
|
38
|
+
env?: NodeJS.ProcessEnv;
|
|
39
|
+
}
|
|
40
|
+
export interface ConfigLoaderOptions<T = Record<string, unknown>> {
|
|
41
|
+
/** Tool name, e.g. 'safegres'. Drives default search places and stash dir. */
|
|
42
|
+
tool: string;
|
|
43
|
+
/**
|
|
44
|
+
* Ordered list of places to look for project config. When omitted, defaults
|
|
45
|
+
* derived from the tool name are used (see `defaultSearchPlaces`).
|
|
46
|
+
*/
|
|
47
|
+
searchPlaces?: SearchPlace[];
|
|
48
|
+
/** Built-in defaults — the lowest-precedence layer. */
|
|
49
|
+
defaults?: Partial<T>;
|
|
50
|
+
/**
|
|
51
|
+
* Named presets resolvable via `extends` (e.g. `'safegres:recommended'`).
|
|
52
|
+
* A preset is just a partial config, and may itself use `extends`.
|
|
53
|
+
*/
|
|
54
|
+
presets?: Record<string, Partial<T>>;
|
|
55
|
+
/**
|
|
56
|
+
* Map environment variables into a config layer. Return a partial config.
|
|
57
|
+
* Runs between the project-file layer and CLI overrides.
|
|
58
|
+
*/
|
|
59
|
+
envLayer?: (env: NodeJS.ProcessEnv) => Partial<T>;
|
|
60
|
+
/**
|
|
61
|
+
* Include a user-level layer read from `~/.<tool>/config/config.json`
|
|
62
|
+
* (via appstash). Default: false.
|
|
63
|
+
*/
|
|
64
|
+
userStash?: boolean;
|
|
65
|
+
/** Array merge behavior. Default: 'replace' (later layers win entirely). */
|
|
66
|
+
arrayMerge?: ArrayMergeStrategy;
|
|
67
|
+
/**
|
|
68
|
+
* Validate/normalize the final merged config. Throw to reject. The return
|
|
69
|
+
* value (if not undefined) replaces the config.
|
|
70
|
+
*/
|
|
71
|
+
validate?: (config: T) => T | void;
|
|
72
|
+
/**
|
|
73
|
+
* When true, `load()`/`loadSync()` stop at the first search place found in
|
|
74
|
+
* each directory but keep walking up if none matched (cosmiconfig behavior).
|
|
75
|
+
* Default: true. When false, only `cwd` itself is searched.
|
|
76
|
+
*/
|
|
77
|
+
walkUp?: boolean;
|
|
78
|
+
}
|
|
79
|
+
/** A single key's provenance, produced by `explain()`. */
|
|
80
|
+
export interface ExplainedValue {
|
|
81
|
+
path: string;
|
|
82
|
+
value: unknown;
|
|
83
|
+
source: LayerSource;
|
|
84
|
+
origin: string;
|
|
85
|
+
}
|
package/esm/types.js
ADDED
package/extends.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ConfigLayer } from './types';
|
|
2
|
+
export interface ExtendsContext<T> {
|
|
3
|
+
presets: Record<string, Partial<T>>;
|
|
4
|
+
/** Directory used to resolve relative / npm `extends` entries. */
|
|
5
|
+
baseDir: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Expand a config object's `extends` chain into an ordered list of layers
|
|
9
|
+
* (lowest precedence first, the config itself last with `extends` stripped).
|
|
10
|
+
*
|
|
11
|
+
* Entries resolve as:
|
|
12
|
+
* - a name present in `presets` (e.g. `safegres:recommended`)
|
|
13
|
+
* - a relative path (`./preset.js`, `../shared/preset.json`)
|
|
14
|
+
* - an npm package name (resolved from `baseDir`)
|
|
15
|
+
*/
|
|
16
|
+
export declare function expandExtends<T>(config: Partial<T>, ctx: ExtendsContext<T>, origin: string, seen?: Set<string>): ConfigLayer<T>[];
|
package/extends.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.expandExtends = expandExtends;
|
|
37
|
+
const path = __importStar(require("path"));
|
|
38
|
+
const loaders_1 = require("./loaders");
|
|
39
|
+
/**
|
|
40
|
+
* Expand a config object's `extends` chain into an ordered list of layers
|
|
41
|
+
* (lowest precedence first, the config itself last with `extends` stripped).
|
|
42
|
+
*
|
|
43
|
+
* Entries resolve as:
|
|
44
|
+
* - a name present in `presets` (e.g. `safegres:recommended`)
|
|
45
|
+
* - a relative path (`./preset.js`, `../shared/preset.json`)
|
|
46
|
+
* - an npm package name (resolved from `baseDir`)
|
|
47
|
+
*/
|
|
48
|
+
function expandExtends(config, ctx, origin, seen = new Set()) {
|
|
49
|
+
const { extends: extendsField, ...rest } = config;
|
|
50
|
+
const layers = [];
|
|
51
|
+
const entries = extendsField == null ? [] : Array.isArray(extendsField) ? extendsField : [extendsField];
|
|
52
|
+
for (const entry of entries) {
|
|
53
|
+
if (seen.has(entry)) {
|
|
54
|
+
throw new Error(`Circular "extends" detected: "${entry}" (chain: ${[...seen].join(' -> ')})`);
|
|
55
|
+
}
|
|
56
|
+
const resolved = resolveEntry(entry, ctx);
|
|
57
|
+
const nextSeen = new Set(seen).add(entry);
|
|
58
|
+
layers.push(...expandExtends(resolved.config, { ...ctx, baseDir: resolved.baseDir }, resolved.origin, nextSeen));
|
|
59
|
+
}
|
|
60
|
+
layers.push({
|
|
61
|
+
source: origin.startsWith('preset:') ? 'preset' : 'file',
|
|
62
|
+
origin,
|
|
63
|
+
config: rest
|
|
64
|
+
});
|
|
65
|
+
return layers;
|
|
66
|
+
}
|
|
67
|
+
function resolveEntry(entry, ctx) {
|
|
68
|
+
// 1. Named preset
|
|
69
|
+
if (entry in ctx.presets) {
|
|
70
|
+
return { config: ctx.presets[entry], origin: `preset:${entry}`, baseDir: ctx.baseDir };
|
|
71
|
+
}
|
|
72
|
+
// 2. Relative or absolute path
|
|
73
|
+
if (entry.startsWith('.') || path.isAbsolute(entry)) {
|
|
74
|
+
const filepath = path.resolve(ctx.baseDir, entry);
|
|
75
|
+
return {
|
|
76
|
+
config: (0, loaders_1.loadFileSync)({ filepath }),
|
|
77
|
+
origin: filepath,
|
|
78
|
+
baseDir: path.dirname(filepath)
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// 3. npm package
|
|
82
|
+
try {
|
|
83
|
+
const resolved = require.resolve(entry, { paths: [ctx.baseDir] });
|
|
84
|
+
return {
|
|
85
|
+
config: (0, loaders_1.loadFileSync)({ filepath: resolved }),
|
|
86
|
+
origin: resolved,
|
|
87
|
+
baseDir: path.dirname(resolved)
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
throw new Error(`Cannot resolve "extends": "${entry}" — not a known preset (${Object.keys(ctx.presets).join(', ') || 'none registered'}), file path, or installed package. ${err.message}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* confstash — standardized project configuration loading for CLI tools.
|
|
3
|
+
*
|
|
4
|
+
* Discovers `<tool>.config.{ts,js,mjs,cjs}`, `.<tool>rc{,.json,.yaml,.yml,.js}`,
|
|
5
|
+
* `<tool>.json`, and `package.json` keys via walk-up search; merges layered
|
|
6
|
+
* config (defaults -> presets/extends -> user stash -> project file -> env ->
|
|
7
|
+
* overrides) with per-key provenance.
|
|
8
|
+
*/
|
|
9
|
+
export { defaultSearchPlaces, findConfigSync, findUpDir, type FoundConfig } from './discover';
|
|
10
|
+
export { expandExtends, type ExtendsContext } from './extends';
|
|
11
|
+
export { createConfigLoader, defineConfig, type ConfigLoader } from './loader';
|
|
12
|
+
export { ConfigLoadError, loadFile, loadFileSync } from './loaders';
|
|
13
|
+
export { deepMerge, explainLayers, mergeLayers } from './merge';
|
|
14
|
+
export type { ArrayMergeStrategy, ConfigLayer, ConfigLoaderOptions, ExplainedValue, LayerSource, LoadParams, LoadResult, SearchPlace } from './types';
|
package/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* confstash — standardized project configuration loading for CLI tools.
|
|
4
|
+
*
|
|
5
|
+
* Discovers `<tool>.config.{ts,js,mjs,cjs}`, `.<tool>rc{,.json,.yaml,.yml,.js}`,
|
|
6
|
+
* `<tool>.json`, and `package.json` keys via walk-up search; merges layered
|
|
7
|
+
* config (defaults -> presets/extends -> user stash -> project file -> env ->
|
|
8
|
+
* overrides) with per-key provenance.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.mergeLayers = exports.explainLayers = exports.deepMerge = exports.loadFileSync = exports.loadFile = exports.ConfigLoadError = exports.defineConfig = exports.createConfigLoader = exports.expandExtends = exports.findUpDir = exports.findConfigSync = exports.defaultSearchPlaces = void 0;
|
|
12
|
+
var discover_1 = require("./discover");
|
|
13
|
+
Object.defineProperty(exports, "defaultSearchPlaces", { enumerable: true, get: function () { return discover_1.defaultSearchPlaces; } });
|
|
14
|
+
Object.defineProperty(exports, "findConfigSync", { enumerable: true, get: function () { return discover_1.findConfigSync; } });
|
|
15
|
+
Object.defineProperty(exports, "findUpDir", { enumerable: true, get: function () { return discover_1.findUpDir; } });
|
|
16
|
+
var extends_1 = require("./extends");
|
|
17
|
+
Object.defineProperty(exports, "expandExtends", { enumerable: true, get: function () { return extends_1.expandExtends; } });
|
|
18
|
+
var loader_1 = require("./loader");
|
|
19
|
+
Object.defineProperty(exports, "createConfigLoader", { enumerable: true, get: function () { return loader_1.createConfigLoader; } });
|
|
20
|
+
Object.defineProperty(exports, "defineConfig", { enumerable: true, get: function () { return loader_1.defineConfig; } });
|
|
21
|
+
var loaders_1 = require("./loaders");
|
|
22
|
+
Object.defineProperty(exports, "ConfigLoadError", { enumerable: true, get: function () { return loaders_1.ConfigLoadError; } });
|
|
23
|
+
Object.defineProperty(exports, "loadFile", { enumerable: true, get: function () { return loaders_1.loadFile; } });
|
|
24
|
+
Object.defineProperty(exports, "loadFileSync", { enumerable: true, get: function () { return loaders_1.loadFileSync; } });
|
|
25
|
+
var merge_1 = require("./merge");
|
|
26
|
+
Object.defineProperty(exports, "deepMerge", { enumerable: true, get: function () { return merge_1.deepMerge; } });
|
|
27
|
+
Object.defineProperty(exports, "explainLayers", { enumerable: true, get: function () { return merge_1.explainLayers; } });
|
|
28
|
+
Object.defineProperty(exports, "mergeLayers", { enumerable: true, get: function () { return merge_1.mergeLayers; } });
|
package/loader.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { defaultSearchPlaces } from './discover';
|
|
2
|
+
import type { ConfigLoaderOptions, ExplainedValue, LoadParams, LoadResult } from './types';
|
|
3
|
+
export interface ConfigLoader<T = Record<string, unknown>> {
|
|
4
|
+
/** Discover, load, and merge all config layers (async — supports ESM configs). */
|
|
5
|
+
load(params?: LoadParams<T>): Promise<LoadResult<T>>;
|
|
6
|
+
/** Synchronous variant (no `.mjs` / ESM support). */
|
|
7
|
+
loadSync(params?: LoadParams<T>): LoadResult<T>;
|
|
8
|
+
/** Per-key provenance of the resolved config (for `print-config` UX). */
|
|
9
|
+
explainSync(params?: LoadParams<T>): ExplainedValue[];
|
|
10
|
+
/** The search places this loader uses. */
|
|
11
|
+
searchPlaces: ReturnType<typeof defaultSearchPlaces>;
|
|
12
|
+
}
|
|
13
|
+
export declare function createConfigLoader<T = Record<string, unknown>>(options: ConfigLoaderOptions<T>): ConfigLoader<T>;
|
|
14
|
+
/** Identity helper for typed config authoring in `<tool>.config.ts/js`. */
|
|
15
|
+
export declare function defineConfig<T>(config: T & {
|
|
16
|
+
extends?: string | string[];
|
|
17
|
+
}): T & {
|
|
18
|
+
extends?: string | string[];
|
|
19
|
+
};
|