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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
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,200 @@
|
|
|
1
|
+
# confstash
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" height="250">
|
|
5
|
+
<br />
|
|
6
|
+
<strong>standardized project configuration loading</strong>
|
|
7
|
+
<br />
|
|
8
|
+
<br />
|
|
9
|
+
Config files, rc files, presets, and layered merge with provenance
|
|
10
|
+
<br />
|
|
11
|
+
<br />
|
|
12
|
+
<a href="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml">
|
|
13
|
+
<img height="20" src="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml/badge.svg" />
|
|
14
|
+
</a>
|
|
15
|
+
<a href="https://github.com/constructive-io/dev-utils/blob/main/LICENSE">
|
|
16
|
+
<img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
|
|
17
|
+
</a>
|
|
18
|
+
</p>
|
|
19
|
+
|
|
20
|
+
Standardized project configuration loading for CLI tools — the project-level complement to [`appstash`](../appstash) (user-level directories).
|
|
21
|
+
|
|
22
|
+
Give it a tool name and it discovers `mytool.config.{ts,js,mjs,cjs}`, `.mytoolrc{,.json,.yaml,.yml,.js}`, `mytool.json`, and `package.json` keys via walk-up search, resolves `extends`/preset chains, and merges layered configuration with per-key provenance:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
defaults -> presets (extends) -> user stash -> project file -> env vars -> runtime overrides
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm install confstash
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Features
|
|
35
|
+
|
|
36
|
+
- **Walk-up discovery**: finds config in the current directory or any parent
|
|
37
|
+
- **Every format**: `.config.ts/js/mjs/cjs` modules, rc files (JSON/YAML), JSON, `package.json` keys
|
|
38
|
+
- **Presets & extends**: named presets, relative paths, or npm packages — recursively, with cycle detection
|
|
39
|
+
- **Layered merge**: deterministic precedence with `replace` or `concat` array strategies
|
|
40
|
+
- **Provenance**: `explainSync()` tells you which layer supplied every value (`--print-config` UX)
|
|
41
|
+
- **Sync and async**: fully synchronous path for CLIs (ESM configs require `load()`)
|
|
42
|
+
- **User layer**: optional `~/.<tool>/config/config.json` layer via appstash
|
|
43
|
+
- **Typed**: `defineConfig<T>()` + generic loader for full type safety
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
### Basic Usage
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
import { createConfigLoader } from 'confstash';
|
|
51
|
+
|
|
52
|
+
interface MyConfig {
|
|
53
|
+
level: string;
|
|
54
|
+
rules: Record<string, string>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const loader = createConfigLoader<MyConfig>({
|
|
58
|
+
tool: 'mytool',
|
|
59
|
+
defaults: { level: 'medium', rules: {} }
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const { config, filepath, layers, isEmpty } = loader.loadSync();
|
|
63
|
+
// or: await loader.load() — also supports .mjs / ESM configs
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Presets and extends
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
const loader = createConfigLoader<MyConfig>({
|
|
70
|
+
tool: 'mytool',
|
|
71
|
+
presets: {
|
|
72
|
+
'mytool:recommended': { level: 'medium', rules: { A1: 'error' } },
|
|
73
|
+
'mytool:strict': { extends: 'mytool:recommended', level: 'high' }
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```jsonc
|
|
79
|
+
// .mytoolrc.json
|
|
80
|
+
{
|
|
81
|
+
"extends": "mytool:strict", // or "./team-preset.js", or "some-npm-pkg"
|
|
82
|
+
"rules": { "A1": "off" }
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Typed config authoring
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// mytool.config.ts
|
|
90
|
+
import { defineConfig } from 'confstash';
|
|
91
|
+
|
|
92
|
+
export default defineConfig({
|
|
93
|
+
extends: 'mytool:recommended',
|
|
94
|
+
level: 'high'
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Environment and CLI layers
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
const loader = createConfigLoader<MyConfig>({
|
|
102
|
+
tool: 'mytool',
|
|
103
|
+
envLayer: (env) => (env.MYTOOL_LEVEL ? { level: env.MYTOOL_LEVEL } : {}),
|
|
104
|
+
userStash: true // include ~/.mytool/config/config.json (via appstash)
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const { config } = loader.loadSync({
|
|
108
|
+
overrides: parsedCliFlags // highest precedence
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Provenance / print-config
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
for (const entry of loader.explainSync()) {
|
|
116
|
+
console.log(`${entry.path} = ${JSON.stringify(entry.value)} (${entry.source}: ${entry.origin})`);
|
|
117
|
+
}
|
|
118
|
+
// level = "high" (file: /repo/mytool.config.ts)
|
|
119
|
+
// rules.A1 = "error" (preset: mytool:recommended)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Custom search places
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
// pgpm-compatible discovery
|
|
126
|
+
const loader = createConfigLoader({
|
|
127
|
+
tool: 'pgpm',
|
|
128
|
+
searchPlaces: ['pgpm.config.js', 'pgpm.json'],
|
|
129
|
+
arrayMerge: 'replace'
|
|
130
|
+
});
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## API
|
|
134
|
+
|
|
135
|
+
### `createConfigLoader<T>(options)`
|
|
136
|
+
|
|
137
|
+
**Options:**
|
|
138
|
+
- `tool` (string): tool name; drives default search places and the user stash directory
|
|
139
|
+
- `searchPlaces` (SearchPlace[]): filenames or `{ packageJson: key }` entries, in precedence order
|
|
140
|
+
- `defaults` (Partial<T>): lowest-precedence layer
|
|
141
|
+
- `presets` (Record<string, Partial<T>>): named presets resolvable via `extends`
|
|
142
|
+
- `envLayer` ((env) => Partial<T>): map environment variables into a layer
|
|
143
|
+
- `userStash` (boolean): include `~/.<tool>/config/config.json` (default `false`)
|
|
144
|
+
- `arrayMerge` (`'replace' | 'concat'`): array strategy (default `'replace'`)
|
|
145
|
+
- `validate` ((config: T) => T | void): validate/normalize the merged result
|
|
146
|
+
- `walkUp` (boolean): search parent directories (default `true`)
|
|
147
|
+
|
|
148
|
+
**Returns:** `ConfigLoader<T>` with `load(params)`, `loadSync(params)`, `explainSync(params)`, `searchPlaces`.
|
|
149
|
+
|
|
150
|
+
**Load params:** `cwd`, `overrides`, `configFile` (skip discovery), `env`.
|
|
151
|
+
|
|
152
|
+
### Utilities
|
|
153
|
+
|
|
154
|
+
- `defineConfig<T>(config)` — identity helper for typed config files
|
|
155
|
+
- `defaultSearchPlaces(tool)` — the derived search place list
|
|
156
|
+
- `findConfigSync(startDir, searchPlaces, walkUp?)` / `findUpDir(startDir, filename)` — discovery primitives
|
|
157
|
+
- `loadFileSync(found)` / `loadFile(found)` — format-aware file loading
|
|
158
|
+
- `deepMerge(target, source, arrayMerge?)` / `mergeLayers(layers)` / `explainLayers(layers)` — merge primitives
|
|
159
|
+
- `ConfigLoadError` — thrown for unreadable/invalid config files
|
|
160
|
+
|
|
161
|
+
## Related
|
|
162
|
+
|
|
163
|
+
- [`appstash`](../appstash) — user-level directories (`~/.<tool>/{config,cache,data,logs}`) and the optional `userStash` layer
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## Development
|
|
168
|
+
|
|
169
|
+
### Setup
|
|
170
|
+
|
|
171
|
+
1. Clone the repository:
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
git clone https://github.com/constructive-io/dev-utils.git
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
2. Install dependencies:
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
cd dev-utils
|
|
181
|
+
pnpm install
|
|
182
|
+
pnpm build
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
3. Test the package of interest:
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
cd packages/<packagename>
|
|
189
|
+
pnpm test:watch
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Credits
|
|
193
|
+
|
|
194
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
195
|
+
|
|
196
|
+
## Disclaimer
|
|
197
|
+
|
|
198
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
199
|
+
|
|
200
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/discover.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SearchPlace } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Default search places for a tool, in precedence order:
|
|
4
|
+
*
|
|
5
|
+
* <tool>.config.ts / .js / .mjs / .cjs
|
|
6
|
+
* .<tool>rc / .<tool>rc.json / .<tool>rc.yaml / .<tool>rc.yml / .<tool>rc.js
|
|
7
|
+
* <tool>.json
|
|
8
|
+
* package.json ("<tool>" key)
|
|
9
|
+
*/
|
|
10
|
+
export declare function defaultSearchPlaces(tool: string): SearchPlace[];
|
|
11
|
+
export interface FoundConfig {
|
|
12
|
+
/** Absolute path of the file containing the config. */
|
|
13
|
+
filepath: string;
|
|
14
|
+
/** Set when the config lives under a key in package.json. */
|
|
15
|
+
packageJsonKey?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Walk up from `startDir` looking for the first directory containing any of
|
|
19
|
+
* the search places. Within a directory, places are checked in order.
|
|
20
|
+
*/
|
|
21
|
+
export declare function findConfigSync(startDir: string, searchPlaces: SearchPlace[], walkUp?: boolean): FoundConfig | null;
|
|
22
|
+
/**
|
|
23
|
+
* Walk up from `startDir` to find the directory containing `filename`.
|
|
24
|
+
* Returns the directory path or null. (Non-throwing analog of
|
|
25
|
+
* `@pgpmjs/env`'s `walkUp`.)
|
|
26
|
+
*/
|
|
27
|
+
export declare function findUpDir(startDir: string, filename: string): string | null;
|
package/discover.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
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.defaultSearchPlaces = defaultSearchPlaces;
|
|
37
|
+
exports.findConfigSync = findConfigSync;
|
|
38
|
+
exports.findUpDir = findUpDir;
|
|
39
|
+
const fs = __importStar(require("fs"));
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
/**
|
|
42
|
+
* Default search places for a tool, in precedence order:
|
|
43
|
+
*
|
|
44
|
+
* <tool>.config.ts / .js / .mjs / .cjs
|
|
45
|
+
* .<tool>rc / .<tool>rc.json / .<tool>rc.yaml / .<tool>rc.yml / .<tool>rc.js
|
|
46
|
+
* <tool>.json
|
|
47
|
+
* package.json ("<tool>" key)
|
|
48
|
+
*/
|
|
49
|
+
function defaultSearchPlaces(tool) {
|
|
50
|
+
return [
|
|
51
|
+
`${tool}.config.ts`,
|
|
52
|
+
`${tool}.config.js`,
|
|
53
|
+
`${tool}.config.mjs`,
|
|
54
|
+
`${tool}.config.cjs`,
|
|
55
|
+
`.${tool}rc`,
|
|
56
|
+
`.${tool}rc.json`,
|
|
57
|
+
`.${tool}rc.yaml`,
|
|
58
|
+
`.${tool}rc.yml`,
|
|
59
|
+
`.${tool}rc.js`,
|
|
60
|
+
`${tool}.json`,
|
|
61
|
+
{ packageJson: tool }
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Walk up from `startDir` looking for the first directory containing any of
|
|
66
|
+
* the search places. Within a directory, places are checked in order.
|
|
67
|
+
*/
|
|
68
|
+
function findConfigSync(startDir, searchPlaces, walkUp = true) {
|
|
69
|
+
let currentDir = path.resolve(startDir);
|
|
70
|
+
for (;;) {
|
|
71
|
+
for (const place of searchPlaces) {
|
|
72
|
+
if (typeof place === 'string') {
|
|
73
|
+
const candidate = path.join(currentDir, place);
|
|
74
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
|
75
|
+
return { filepath: candidate };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
const pkgPath = path.join(currentDir, 'package.json');
|
|
80
|
+
if (fs.existsSync(pkgPath) && packageJsonHasKey(pkgPath, place.packageJson)) {
|
|
81
|
+
return { filepath: pkgPath, packageJsonKey: place.packageJson };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (!walkUp)
|
|
86
|
+
return null;
|
|
87
|
+
const parent = path.dirname(currentDir);
|
|
88
|
+
if (parent === currentDir)
|
|
89
|
+
return null;
|
|
90
|
+
currentDir = parent;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function packageJsonHasKey(pkgPath, key) {
|
|
94
|
+
try {
|
|
95
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
96
|
+
return pkg != null && typeof pkg === 'object' && pkg[key] != null;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Walk up from `startDir` to find the directory containing `filename`.
|
|
104
|
+
* Returns the directory path or null. (Non-throwing analog of
|
|
105
|
+
* `@pgpmjs/env`'s `walkUp`.)
|
|
106
|
+
*/
|
|
107
|
+
function findUpDir(startDir, filename) {
|
|
108
|
+
let currentDir = path.resolve(startDir);
|
|
109
|
+
for (;;) {
|
|
110
|
+
if (fs.existsSync(path.join(currentDir, filename))) {
|
|
111
|
+
return currentDir;
|
|
112
|
+
}
|
|
113
|
+
const parent = path.dirname(currentDir);
|
|
114
|
+
if (parent === currentDir)
|
|
115
|
+
return null;
|
|
116
|
+
currentDir = parent;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SearchPlace } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Default search places for a tool, in precedence order:
|
|
4
|
+
*
|
|
5
|
+
* <tool>.config.ts / .js / .mjs / .cjs
|
|
6
|
+
* .<tool>rc / .<tool>rc.json / .<tool>rc.yaml / .<tool>rc.yml / .<tool>rc.js
|
|
7
|
+
* <tool>.json
|
|
8
|
+
* package.json ("<tool>" key)
|
|
9
|
+
*/
|
|
10
|
+
export declare function defaultSearchPlaces(tool: string): SearchPlace[];
|
|
11
|
+
export interface FoundConfig {
|
|
12
|
+
/** Absolute path of the file containing the config. */
|
|
13
|
+
filepath: string;
|
|
14
|
+
/** Set when the config lives under a key in package.json. */
|
|
15
|
+
packageJsonKey?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Walk up from `startDir` looking for the first directory containing any of
|
|
19
|
+
* the search places. Within a directory, places are checked in order.
|
|
20
|
+
*/
|
|
21
|
+
export declare function findConfigSync(startDir: string, searchPlaces: SearchPlace[], walkUp?: boolean): FoundConfig | null;
|
|
22
|
+
/**
|
|
23
|
+
* Walk up from `startDir` to find the directory containing `filename`.
|
|
24
|
+
* Returns the directory path or null. (Non-throwing analog of
|
|
25
|
+
* `@pgpmjs/env`'s `walkUp`.)
|
|
26
|
+
*/
|
|
27
|
+
export declare function findUpDir(startDir: string, filename: string): string | null;
|
package/esm/discover.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
/**
|
|
4
|
+
* Default search places for a tool, in precedence order:
|
|
5
|
+
*
|
|
6
|
+
* <tool>.config.ts / .js / .mjs / .cjs
|
|
7
|
+
* .<tool>rc / .<tool>rc.json / .<tool>rc.yaml / .<tool>rc.yml / .<tool>rc.js
|
|
8
|
+
* <tool>.json
|
|
9
|
+
* package.json ("<tool>" key)
|
|
10
|
+
*/
|
|
11
|
+
export function defaultSearchPlaces(tool) {
|
|
12
|
+
return [
|
|
13
|
+
`${tool}.config.ts`,
|
|
14
|
+
`${tool}.config.js`,
|
|
15
|
+
`${tool}.config.mjs`,
|
|
16
|
+
`${tool}.config.cjs`,
|
|
17
|
+
`.${tool}rc`,
|
|
18
|
+
`.${tool}rc.json`,
|
|
19
|
+
`.${tool}rc.yaml`,
|
|
20
|
+
`.${tool}rc.yml`,
|
|
21
|
+
`.${tool}rc.js`,
|
|
22
|
+
`${tool}.json`,
|
|
23
|
+
{ packageJson: tool }
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Walk up from `startDir` looking for the first directory containing any of
|
|
28
|
+
* the search places. Within a directory, places are checked in order.
|
|
29
|
+
*/
|
|
30
|
+
export function findConfigSync(startDir, searchPlaces, walkUp = true) {
|
|
31
|
+
let currentDir = path.resolve(startDir);
|
|
32
|
+
for (;;) {
|
|
33
|
+
for (const place of searchPlaces) {
|
|
34
|
+
if (typeof place === 'string') {
|
|
35
|
+
const candidate = path.join(currentDir, place);
|
|
36
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
|
37
|
+
return { filepath: candidate };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const pkgPath = path.join(currentDir, 'package.json');
|
|
42
|
+
if (fs.existsSync(pkgPath) && packageJsonHasKey(pkgPath, place.packageJson)) {
|
|
43
|
+
return { filepath: pkgPath, packageJsonKey: place.packageJson };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!walkUp)
|
|
48
|
+
return null;
|
|
49
|
+
const parent = path.dirname(currentDir);
|
|
50
|
+
if (parent === currentDir)
|
|
51
|
+
return null;
|
|
52
|
+
currentDir = parent;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function packageJsonHasKey(pkgPath, key) {
|
|
56
|
+
try {
|
|
57
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
58
|
+
return pkg != null && typeof pkg === 'object' && pkg[key] != null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Walk up from `startDir` to find the directory containing `filename`.
|
|
66
|
+
* Returns the directory path or null. (Non-throwing analog of
|
|
67
|
+
* `@pgpmjs/env`'s `walkUp`.)
|
|
68
|
+
*/
|
|
69
|
+
export function findUpDir(startDir, filename) {
|
|
70
|
+
let currentDir = path.resolve(startDir);
|
|
71
|
+
for (;;) {
|
|
72
|
+
if (fs.existsSync(path.join(currentDir, filename))) {
|
|
73
|
+
return currentDir;
|
|
74
|
+
}
|
|
75
|
+
const parent = path.dirname(currentDir);
|
|
76
|
+
if (parent === currentDir)
|
|
77
|
+
return null;
|
|
78
|
+
currentDir = parent;
|
|
79
|
+
}
|
|
80
|
+
}
|
package/esm/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/esm/extends.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as path from 'path';
|
|
2
|
+
import { loadFileSync } from './loaders';
|
|
3
|
+
/**
|
|
4
|
+
* Expand a config object's `extends` chain into an ordered list of layers
|
|
5
|
+
* (lowest precedence first, the config itself last with `extends` stripped).
|
|
6
|
+
*
|
|
7
|
+
* Entries resolve as:
|
|
8
|
+
* - a name present in `presets` (e.g. `safegres:recommended`)
|
|
9
|
+
* - a relative path (`./preset.js`, `../shared/preset.json`)
|
|
10
|
+
* - an npm package name (resolved from `baseDir`)
|
|
11
|
+
*/
|
|
12
|
+
export function expandExtends(config, ctx, origin, seen = new Set()) {
|
|
13
|
+
const { extends: extendsField, ...rest } = config;
|
|
14
|
+
const layers = [];
|
|
15
|
+
const entries = extendsField == null ? [] : Array.isArray(extendsField) ? extendsField : [extendsField];
|
|
16
|
+
for (const entry of entries) {
|
|
17
|
+
if (seen.has(entry)) {
|
|
18
|
+
throw new Error(`Circular "extends" detected: "${entry}" (chain: ${[...seen].join(' -> ')})`);
|
|
19
|
+
}
|
|
20
|
+
const resolved = resolveEntry(entry, ctx);
|
|
21
|
+
const nextSeen = new Set(seen).add(entry);
|
|
22
|
+
layers.push(...expandExtends(resolved.config, { ...ctx, baseDir: resolved.baseDir }, resolved.origin, nextSeen));
|
|
23
|
+
}
|
|
24
|
+
layers.push({
|
|
25
|
+
source: origin.startsWith('preset:') ? 'preset' : 'file',
|
|
26
|
+
origin,
|
|
27
|
+
config: rest
|
|
28
|
+
});
|
|
29
|
+
return layers;
|
|
30
|
+
}
|
|
31
|
+
function resolveEntry(entry, ctx) {
|
|
32
|
+
// 1. Named preset
|
|
33
|
+
if (entry in ctx.presets) {
|
|
34
|
+
return { config: ctx.presets[entry], origin: `preset:${entry}`, baseDir: ctx.baseDir };
|
|
35
|
+
}
|
|
36
|
+
// 2. Relative or absolute path
|
|
37
|
+
if (entry.startsWith('.') || path.isAbsolute(entry)) {
|
|
38
|
+
const filepath = path.resolve(ctx.baseDir, entry);
|
|
39
|
+
return {
|
|
40
|
+
config: loadFileSync({ filepath }),
|
|
41
|
+
origin: filepath,
|
|
42
|
+
baseDir: path.dirname(filepath)
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// 3. npm package
|
|
46
|
+
try {
|
|
47
|
+
const resolved = require.resolve(entry, { paths: [ctx.baseDir] });
|
|
48
|
+
return {
|
|
49
|
+
config: loadFileSync({ filepath: resolved }),
|
|
50
|
+
origin: resolved,
|
|
51
|
+
baseDir: path.dirname(resolved)
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
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}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
package/esm/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/esm/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
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 } from './discover';
|
|
10
|
+
export { expandExtends } from './extends';
|
|
11
|
+
export { createConfigLoader, defineConfig } from './loader';
|
|
12
|
+
export { ConfigLoadError, loadFile, loadFileSync } from './loaders';
|
|
13
|
+
export { deepMerge, explainLayers, mergeLayers } from './merge';
|
package/esm/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
|
+
};
|