@theunwalked/cardigantime 0.0.7 → 0.0.9
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 +136 -1
- package/dist/cardigantime.cjs +250 -29
- package/dist/cardigantime.cjs.map +1 -1
- package/dist/cardigantime.d.ts +17 -0
- package/dist/cardigantime.js +17 -0
- package/dist/cardigantime.js.map +1 -1
- package/dist/constants.js +2 -1
- package/dist/constants.js.map +1 -1
- package/dist/read.js +74 -3
- package/dist/read.js.map +1 -1
- package/dist/types.d.ts +42 -0
- package/dist/types.js.map +1 -1
- package/dist/util/hierarchical.d.ts +25 -11
- package/dist/util/hierarchical.js +157 -25
- package/dist/util/hierarchical.js.map +1 -1
- package/package.json +1 -1
package/dist/cardigantime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cardigantime.js","sources":["../src/cardigantime.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { Args, DefaultOptions, Feature, Cardigantime, Logger, Options } from 'types';\nimport { z, ZodObject } from 'zod';\nimport { configure } from './configure';\nimport { DEFAULT_FEATURES, DEFAULT_LOGGER, DEFAULT_OPTIONS } from './constants';\nimport { read } from './read';\nimport { ConfigSchema } from 'types';\nimport { validate } from './validate';\n\nexport * from './types';\nexport { ArgumentError, ConfigurationError, FileSystemError } from './validate';\n\n/**\n * Creates a new Cardigantime instance for configuration management.\n * \n * Cardigantime handles the complete configuration lifecycle including:\n * - Reading configuration from YAML files\n * - Validating configuration against Zod schemas\n * - Merging CLI arguments with file configuration and defaults\n * - Providing type-safe configuration objects\n * \n * @template T - The Zod schema shape type for your configuration\n * @param pOptions - Configuration options for the Cardigantime instance\n * @param pOptions.defaults - Default configuration settings\n * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)\n * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')\n * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)\n * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')\n * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])\n * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)\n * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)\n * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger\n * \n * @example\n * ```typescript\n * import { create } from '@theunwalked/cardigantime';\n * import { z } from 'zod';\n * \n * const MyConfigSchema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().default(5000),\n * debug: z.boolean().default(false),\n * });\n * \n * const cardigantime = create({\n * defaults: {\n * configDirectory: './config',\n * configFile: 'myapp.yaml',\n * },\n * configShape: MyConfigSchema.shape,\n * });\n * ```\n */\nexport const create = <T extends z.ZodRawShape>(pOptions: {\n defaults: Pick<DefaultOptions, 'configDirectory'> & Partial<Omit<DefaultOptions, 'configDirectory'>>,\n features?: Feature[],\n configShape: T, // Make configShape mandatory\n logger?: Logger,\n}): Cardigantime<T> => {\n\n\n const defaults: DefaultOptions = { ...DEFAULT_OPTIONS, ...pOptions.defaults } as DefaultOptions;\n const features = pOptions.features || DEFAULT_FEATURES;\n const configShape = pOptions.configShape;\n let logger = pOptions.logger || DEFAULT_LOGGER;\n\n const options: Options<T> = {\n defaults,\n features,\n configShape, // Store the shape\n logger,\n }\n\n const setLogger = (pLogger: Logger) => {\n logger = pLogger;\n options.logger = pLogger;\n }\n\n return {\n setLogger,\n configure: (command: Command) => configure(command, options),\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => validate(config, options),\n read: (args: Args) => read(args, options),\n }\n}\n\n\n\n\n\n"],"names":["create","pOptions","defaults","DEFAULT_OPTIONS","features","DEFAULT_FEATURES","configShape","logger","DEFAULT_LOGGER","options","setLogger","pLogger","configure","command","validate","config","read","args"],"mappings":";;;;;;;;;AAYA
|
|
1
|
+
{"version":3,"file":"cardigantime.js","sources":["../src/cardigantime.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { Args, DefaultOptions, Feature, Cardigantime, Logger, Options } from 'types';\nimport { z, ZodObject } from 'zod';\nimport { configure } from './configure';\nimport { DEFAULT_FEATURES, DEFAULT_LOGGER, DEFAULT_OPTIONS } from './constants';\nimport { read } from './read';\nimport { ConfigSchema } from 'types';\nimport { validate } from './validate';\n\nexport * from './types';\nexport { ArgumentError, ConfigurationError, FileSystemError } from './validate';\n\n/**\n * Creates a new Cardigantime instance for configuration management.\n * \n * Cardigantime handles the complete configuration lifecycle including:\n * - Reading configuration from YAML files\n * - Validating configuration against Zod schemas\n * - Merging CLI arguments with file configuration and defaults\n * - Providing type-safe configuration objects\n * \n * @template T - The Zod schema shape type for your configuration\n * @param pOptions - Configuration options for the Cardigantime instance\n * @param pOptions.defaults - Default configuration settings\n * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)\n * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')\n * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)\n * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')\n * @param pOptions.defaults.pathResolution - Configuration for resolving relative paths in config values relative to the config file's directory (optional)\n * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])\n * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)\n * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)\n * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger\n * \n * @example\n * ```typescript\n * import { create } from '@theunwalked/cardigantime';\n * import { z } from 'zod';\n * \n * const MyConfigSchema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().default(5000),\n * debug: z.boolean().default(false),\n * contextDirectories: z.array(z.string()).optional(),\n * });\n * \n * const cardigantime = create({\n * defaults: {\n * configDirectory: './config',\n * configFile: 'myapp.yaml',\n * // Resolve relative paths in contextDirectories relative to config file location\n * pathResolution: {\n * pathFields: ['contextDirectories'],\n * resolvePathArray: ['contextDirectories']\n * },\n * // Configure how array fields are merged in hierarchical mode\n * fieldOverlaps: {\n * 'features': 'append', // Accumulate features from all levels\n * 'excludePatterns': 'prepend' // Higher precedence patterns come first\n * }\n * },\n * configShape: MyConfigSchema.shape,\n * features: ['config', 'hierarchical'], // Enable hierarchical discovery\n * });\n * \n * // If config file is at ../config/myapp.yaml and contains:\n * // contextDirectories: ['./context', './data']\n * // These paths will be resolved relative to ../config/ directory\n * ```\n */\nexport const create = <T extends z.ZodRawShape>(pOptions: {\n defaults: Pick<DefaultOptions, 'configDirectory'> & Partial<Omit<DefaultOptions, 'configDirectory'>>,\n features?: Feature[],\n configShape: T, // Make configShape mandatory\n logger?: Logger,\n}): Cardigantime<T> => {\n\n\n const defaults: DefaultOptions = { ...DEFAULT_OPTIONS, ...pOptions.defaults } as DefaultOptions;\n const features = pOptions.features || DEFAULT_FEATURES;\n const configShape = pOptions.configShape;\n let logger = pOptions.logger || DEFAULT_LOGGER;\n\n const options: Options<T> = {\n defaults,\n features,\n configShape, // Store the shape\n logger,\n }\n\n const setLogger = (pLogger: Logger) => {\n logger = pLogger;\n options.logger = pLogger;\n }\n\n return {\n setLogger,\n configure: (command: Command) => configure(command, options),\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => validate(config, options),\n read: (args: Args) => read(args, options),\n }\n}\n\n\n\n\n\n"],"names":["create","pOptions","defaults","DEFAULT_OPTIONS","features","DEFAULT_FEATURES","configShape","logger","DEFAULT_LOGGER","options","setLogger","pLogger","configure","command","validate","config","read","args"],"mappings":";;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0DO,MAAMA,MAAAA,GAAS,CAA0BC,QAAAA,GAAAA;AAQ5C,IAAA,MAAMC,QAAAA,GAA2B;AAAE,QAAA,GAAGC,eAAe;AAAE,QAAA,GAAGF,SAASC;AAAS,KAAA;IAC5E,MAAME,QAAAA,GAAWH,QAAAA,CAASG,QAAQ,IAAIC,gBAAAA;IACtC,MAAMC,WAAAA,GAAcL,SAASK,WAAW;IACxC,IAAIC,MAAAA,GAASN,QAAAA,CAASM,MAAM,IAAIC,cAAAA;AAEhC,IAAA,MAAMC,OAAAA,GAAsB;AACxBP,QAAAA,QAAAA;AACAE,QAAAA,QAAAA;AACAE,QAAAA,WAAAA;AACAC,QAAAA;AACJ,KAAA;AAEA,IAAA,MAAMG,YAAY,CAACC,OAAAA,GAAAA;QACfJ,MAAAA,GAASI,OAAAA;AACTF,QAAAA,OAAAA,CAAQF,MAAM,GAAGI,OAAAA;AACrB,KAAA;IAEA,OAAO;AACHD,QAAAA,SAAAA;QACAE,SAAAA,EAAW,CAACC,OAAAA,GAAqBD,SAAAA,CAAUC,OAAAA,EAASJ,OAAAA,CAAAA;QACpDK,QAAAA,EAAU,CAACC,MAAAA,GAA8DD,QAAAA,CAASC,MAAAA,EAAQN,OAAAA,CAAAA;QAC1FO,IAAAA,EAAM,CAACC,IAAAA,GAAeD,IAAAA,CAAKC,IAAAA,EAAMR,OAAAA;AACrC,KAAA;AACJ;;;;"}
|
package/dist/constants.js
CHANGED
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sources":["../src/constants.ts"],"sourcesContent":["import { DefaultOptions, Feature, Logger } from \"./types\";\n\n/** Version string populated at build time with git and system information */\nexport const VERSION = '__VERSION__ (__GIT_BRANCH__/__GIT_COMMIT__ __GIT_TAGS__ __GIT_COMMIT_DATE__) __SYSTEM_INFO__';\n\n/** The program name used in CLI help and error messages */\nexport const PROGRAM_NAME = 'cardigantime';\n\n/** Default file encoding for reading configuration files */\nexport const DEFAULT_ENCODING = 'utf8';\n\n/** Default configuration file name to look for in the config directory */\nexport const DEFAULT_CONFIG_FILE = 'config.yaml';\n\n/**\n * Default configuration options applied when creating a Cardigantime instance.\n * These provide sensible defaults that work for most use cases.\n */\nexport const DEFAULT_OPTIONS: Partial<DefaultOptions> = {\n configFile: DEFAULT_CONFIG_FILE,\n isRequired: false,\n encoding: DEFAULT_ENCODING,\n}\n\n/**\n * Default features enabled when creating a Cardigantime instance.\n * Currently includes only the 'config' feature for configuration file support.\n */\nexport const DEFAULT_FEATURES: Feature[] = ['config'];\n\n/**\n * Default logger implementation using console methods.\n * Provides basic logging functionality when no custom logger is specified.\n * The verbose and silly methods are no-ops to avoid excessive output.\n */\nexport const DEFAULT_LOGGER: Logger = {\n // eslint-disable-next-line no-console\n debug: console.debug,\n // eslint-disable-next-line no-console\n info: console.info,\n // eslint-disable-next-line no-console\n warn: console.warn,\n // eslint-disable-next-line no-console\n error: console.error,\n\n verbose: () => { },\n\n silly: () => { },\n}\n"],"names":["DEFAULT_ENCODING","DEFAULT_CONFIG_FILE","DEFAULT_OPTIONS","configFile","isRequired","encoding","DEFAULT_FEATURES","DEFAULT_LOGGER","debug","console","info","warn","error","verbose","silly"],"mappings":"AAQA,6DACO,MAAMA,gBAAAA,GAAmB;AAEhC,2EACO,MAAMC,mBAAAA,GAAsB;AAEnC;;;UAIaC,eAAAA,GAA2C;IACpDC,UAAAA,EAAYF,mBAAAA;IACZG,UAAAA,EAAY,KAAA;IACZC,QAAAA,EAAUL;
|
|
1
|
+
{"version":3,"file":"constants.js","sources":["../src/constants.ts"],"sourcesContent":["import { DefaultOptions, Feature, Logger } from \"./types\";\n\n/** Version string populated at build time with git and system information */\nexport const VERSION = '__VERSION__ (__GIT_BRANCH__/__GIT_COMMIT__ __GIT_TAGS__ __GIT_COMMIT_DATE__) __SYSTEM_INFO__';\n\n/** The program name used in CLI help and error messages */\nexport const PROGRAM_NAME = 'cardigantime';\n\n/** Default file encoding for reading configuration files */\nexport const DEFAULT_ENCODING = 'utf8';\n\n/** Default configuration file name to look for in the config directory */\nexport const DEFAULT_CONFIG_FILE = 'config.yaml';\n\n/**\n * Default configuration options applied when creating a Cardigantime instance.\n * These provide sensible defaults that work for most use cases.\n */\nexport const DEFAULT_OPTIONS: Partial<DefaultOptions> = {\n configFile: DEFAULT_CONFIG_FILE,\n isRequired: false,\n encoding: DEFAULT_ENCODING,\n pathResolution: undefined, // No path resolution by default\n}\n\n/**\n * Default features enabled when creating a Cardigantime instance.\n * Currently includes only the 'config' feature for configuration file support.\n */\nexport const DEFAULT_FEATURES: Feature[] = ['config'];\n\n/**\n * Default logger implementation using console methods.\n * Provides basic logging functionality when no custom logger is specified.\n * The verbose and silly methods are no-ops to avoid excessive output.\n */\nexport const DEFAULT_LOGGER: Logger = {\n // eslint-disable-next-line no-console\n debug: console.debug,\n // eslint-disable-next-line no-console\n info: console.info,\n // eslint-disable-next-line no-console\n warn: console.warn,\n // eslint-disable-next-line no-console\n error: console.error,\n\n verbose: () => { },\n\n silly: () => { },\n}\n"],"names":["DEFAULT_ENCODING","DEFAULT_CONFIG_FILE","DEFAULT_OPTIONS","configFile","isRequired","encoding","pathResolution","undefined","DEFAULT_FEATURES","DEFAULT_LOGGER","debug","console","info","warn","error","verbose","silly"],"mappings":"AAQA,6DACO,MAAMA,gBAAAA,GAAmB;AAEhC,2EACO,MAAMC,mBAAAA,GAAsB;AAEnC;;;UAIaC,eAAAA,GAA2C;IACpDC,UAAAA,EAAYF,mBAAAA;IACZG,UAAAA,EAAY,KAAA;IACZC,QAAAA,EAAUL,gBAAAA;IACVM,cAAAA,EAAgBC;AACpB;AAEA;;;UAIaC,gBAAAA,GAA8B;AAAC,IAAA;;AAE5C;;;;UAKaC,cAAAA,GAAyB;;AAElCC,IAAAA,KAAAA,EAAOC,QAAQD,KAAK;;AAEpBE,IAAAA,IAAAA,EAAMD,QAAQC,IAAI;;AAElBC,IAAAA,IAAAA,EAAMF,QAAQE,IAAI;;AAElBC,IAAAA,KAAAA,EAAOH,QAAQG,KAAK;AAEpBC,IAAAA,OAAAA,EAAS,IAAA,EAAQ;AAEjBC,IAAAA,KAAAA,EAAO,IAAA;AACX;;;;"}
|
package/dist/read.js
CHANGED
|
@@ -12,6 +12,68 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
12
12
|
*/ function clean(obj) {
|
|
13
13
|
return Object.fromEntries(Object.entries(obj).filter(([_, v])=>v !== undefined));
|
|
14
14
|
}
|
|
15
|
+
/**
|
|
16
|
+
* Resolves relative paths in configuration values relative to the configuration file's directory.
|
|
17
|
+
*
|
|
18
|
+
* @param config - The configuration object to process
|
|
19
|
+
* @param configDir - The directory containing the configuration file
|
|
20
|
+
* @param pathFields - Array of field names (using dot notation) that contain paths to be resolved
|
|
21
|
+
* @param resolvePathArray - Array of field names whose array elements should all be resolved as paths
|
|
22
|
+
* @returns The configuration object with resolved paths
|
|
23
|
+
*/ function resolveConfigPaths(config, configDir, pathFields = [], resolvePathArray = []) {
|
|
24
|
+
if (!config || typeof config !== 'object' || pathFields.length === 0) {
|
|
25
|
+
return config;
|
|
26
|
+
}
|
|
27
|
+
const resolvedConfig = {
|
|
28
|
+
...config
|
|
29
|
+
};
|
|
30
|
+
for (const fieldPath of pathFields){
|
|
31
|
+
const value = getNestedValue(resolvedConfig, fieldPath);
|
|
32
|
+
if (value !== undefined) {
|
|
33
|
+
const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);
|
|
34
|
+
const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);
|
|
35
|
+
setNestedValue(resolvedConfig, fieldPath, resolvedValue);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return resolvedConfig;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Gets a nested value from an object using dot notation.
|
|
42
|
+
*/ function getNestedValue(obj, path) {
|
|
43
|
+
return path.split('.').reduce((current, key)=>current === null || current === void 0 ? void 0 : current[key], obj);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Sets a nested value in an object using dot notation.
|
|
47
|
+
*/ function setNestedValue(obj, path, value) {
|
|
48
|
+
const keys = path.split('.');
|
|
49
|
+
const lastKey = keys.pop();
|
|
50
|
+
const target = keys.reduce((current, key)=>{
|
|
51
|
+
if (!(key in current)) {
|
|
52
|
+
current[key] = {};
|
|
53
|
+
}
|
|
54
|
+
return current[key];
|
|
55
|
+
}, obj);
|
|
56
|
+
target[lastKey] = value;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolves a path value (string or array of strings) relative to the config directory.
|
|
60
|
+
*/ function resolvePathValue(value, configDir, resolveArrayElements) {
|
|
61
|
+
if (typeof value === 'string') {
|
|
62
|
+
return resolveSinglePath(value, configDir);
|
|
63
|
+
}
|
|
64
|
+
if (Array.isArray(value) && resolveArrayElements) {
|
|
65
|
+
return value.map((item)=>typeof item === 'string' ? resolveSinglePath(item, configDir) : item);
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Resolves a single path string relative to the config directory if it's a relative path.
|
|
71
|
+
*/ function resolveSinglePath(pathStr, configDir) {
|
|
72
|
+
if (!pathStr || path.isAbsolute(pathStr)) {
|
|
73
|
+
return pathStr;
|
|
74
|
+
}
|
|
75
|
+
return path.resolve(configDir, pathStr);
|
|
76
|
+
}
|
|
15
77
|
/**
|
|
16
78
|
* Validates and secures a user-provided path to prevent path traversal attacks.
|
|
17
79
|
*
|
|
@@ -95,7 +157,7 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
95
157
|
* // config is fully typed based on your schema
|
|
96
158
|
* ```
|
|
97
159
|
*/ const read = async (args, options)=>{
|
|
98
|
-
var _options_defaults;
|
|
160
|
+
var _options_defaults, _options_defaults_pathResolution;
|
|
99
161
|
const logger = options.logger;
|
|
100
162
|
const rawConfigDir = args.configDirectory || ((_options_defaults = options.defaults) === null || _options_defaults === void 0 ? void 0 : _options_defaults.configDirectory);
|
|
101
163
|
if (!rawConfigDir) {
|
|
@@ -108,6 +170,7 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
108
170
|
if (options.features.includes('hierarchical')) {
|
|
109
171
|
logger.verbose('Hierarchical configuration discovery enabled');
|
|
110
172
|
try {
|
|
173
|
+
var _options_defaults_pathResolution1, _options_defaults_pathResolution2;
|
|
111
174
|
// Extract the config directory name from the path for hierarchical discovery
|
|
112
175
|
const configDirName = path.basename(resolvedConfigDir);
|
|
113
176
|
const startingDir = path.dirname(resolvedConfigDir);
|
|
@@ -117,7 +180,10 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
117
180
|
configFileName: options.defaults.configFile,
|
|
118
181
|
startingDir,
|
|
119
182
|
encoding: options.defaults.encoding,
|
|
120
|
-
logger
|
|
183
|
+
logger,
|
|
184
|
+
pathFields: (_options_defaults_pathResolution1 = options.defaults.pathResolution) === null || _options_defaults_pathResolution1 === void 0 ? void 0 : _options_defaults_pathResolution1.pathFields,
|
|
185
|
+
resolvePathArray: (_options_defaults_pathResolution2 = options.defaults.pathResolution) === null || _options_defaults_pathResolution2 === void 0 ? void 0 : _options_defaults_pathResolution2.resolvePathArray,
|
|
186
|
+
fieldOverlaps: options.defaults.fieldOverlaps
|
|
121
187
|
});
|
|
122
188
|
rawFileConfig = hierarchicalResult.config;
|
|
123
189
|
if (hierarchicalResult.discoveredDirs.length > 0) {
|
|
@@ -142,8 +208,13 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
142
208
|
logger.verbose('Using single directory configuration loading');
|
|
143
209
|
rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);
|
|
144
210
|
}
|
|
211
|
+
// Apply path resolution if configured
|
|
212
|
+
let processedConfig = rawFileConfig;
|
|
213
|
+
if ((_options_defaults_pathResolution = options.defaults.pathResolution) === null || _options_defaults_pathResolution === void 0 ? void 0 : _options_defaults_pathResolution.pathFields) {
|
|
214
|
+
processedConfig = resolveConfigPaths(rawFileConfig, resolvedConfigDir, options.defaults.pathResolution.pathFields, options.defaults.pathResolution.resolvePathArray || []);
|
|
215
|
+
}
|
|
145
216
|
const config = clean({
|
|
146
|
-
...
|
|
217
|
+
...processedConfig,
|
|
147
218
|
...{
|
|
148
219
|
configDirectory: resolvedConfigDir
|
|
149
220
|
}
|
package/dist/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig } from './util/hierarchical';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n\n // Check if hierarchical configuration discovery is enabled\n if (options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger\n });\n\n rawFileConfig = hierarchicalResult.config;\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...rawFileConfig,\n ...{\n configDirectory: resolvedConfigDir,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n const configFile = validatePath(options.defaults.configFile, resolvedConfigDir);\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n const yamlContent = await storage.readFile(configFile, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","validatePath","userPath","basePath","Error","normalized","path","normalize","includes","isAbsolute","startsWith","join","validateConfigDirectory","configDir","length","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","config","discoveredDirs","forEach","dir","level","errors","error","warn","message","loadSingleDirectoryConfig","storage","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","code","test"],"mappings":";;;;;AAOA;;;;;;IAOA,SAASA,MAAMC,GAAQ,EAAA;AACnB,IAAA,OAAOC,MAAAA,CAAOC,WAAW,CACrBD,MAAAA,CAAOE,OAAO,CAACH,GAAAA,CAAAA,CAAKI,MAAM,CAAC,CAAC,CAACC,CAAAA,EAAGC,CAAAA,CAAE,GAAKA,CAAAA,KAAMC,SAAAA,CAAAA,CAAAA;AAErD;AAEA;;;;;;;;;;;;AAYC,IACD,SAASC,YAAAA,CAAaC,QAAgB,EAAEC,QAAgB,EAAA;IACpD,IAAI,CAACD,QAAAA,IAAY,CAACC,QAAAA,EAAU;AACxB,QAAA,MAAM,IAAIC,KAAAA,CAAM,yBAAA,CAAA;AACpB;IAEA,MAAMC,UAAAA,GAAaC,IAAAA,CAAKC,SAAS,CAACL,QAAAA,CAAAA;;AAGlC,IAAA,IAAIG,WAAWG,QAAQ,CAAC,SAASF,IAAAA,CAAKG,UAAU,CAACJ,UAAAA,CAAAA,EAAa;AAC1D,QAAA,MAAM,IAAID,KAAAA,CAAM,uCAAA,CAAA;AACpB;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,OAAO,CAAC,iDAAA,CAAA;AAEf,IAAA,IAAIC,gBAAwB,EAAC;IAE7B,IAAI;QACA,MAAMyB,WAAAA,GAAc,MAAMH,OAAAA,CAAQI,QAAQ,CAAChB,UAAAA,EAAYjB,OAAAA,CAAQI,QAAQ,CAACc,QAAQ,CAAA;;QAGhF,MAAMgB,UAAAA,GAAaC,IAAAA,CAAKC,IAAI,CAACJ,WAAAA,CAAAA;AAE7B,QAAA,IAAIE,UAAAA,KAAe,IAAA,IAAQ,OAAOA,UAAAA,KAAe,QAAA,EAAU;YACvD3B,aAAAA,GAAgB2B,UAAAA;AAChBjC,YAAAA,MAAAA,CAAOK,OAAO,CAAC,wCAAA,CAAA;SACnB,MAAO,IAAI4B,eAAe,IAAA,EAAM;YAC5BjC,MAAAA,CAAOyB,IAAI,CAAC,iEAAA,GAAoE,OAAOQ,UAAAA,CAAAA;AAC3F;AACJ,KAAA,CAAE,OAAOT,KAAAA,EAAY;QACjB,IAAIA,KAAAA,CAAMY,IAAI,KAAK,QAAA,IAAY,0BAA0BC,IAAI,CAACb,KAAAA,CAAME,OAAO,CAAA,EAAG;AAC1E1B,YAAAA,MAAAA,CAAOK,OAAO,CAAC,0DAAA,CAAA;SACnB,MAAO;;AAEHL,YAAAA,MAAAA,CAAOwB,KAAK,CAAC,8CAAA,IAAkDA,KAAAA,CAAME,OAAO,IAAI,eAAc,CAAA,CAAA;AAClG;AACJ;IAEA,OAAOpB,aAAAA;AACX;;;;"}
|
|
1
|
+
{"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig } from './util/hierarchical';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n const target = keys.reduce((current, key) => {\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string or array of strings) relative to the config directory.\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n\n // Check if hierarchical configuration discovery is enabled\n if (options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n const configFile = validatePath(options.defaults.configFile, resolvedConfigDir);\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n const yamlContent = await storage.readFile(configFile, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","keys","lastKey","pop","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","forEach","dir","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","storage","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","code","test"],"mappings":";;;;;AAOA;;;;;;IAOA,SAASA,MAAMC,GAAQ,EAAA;AACnB,IAAA,OAAOC,MAAAA,CAAOC,WAAW,CACrBD,MAAAA,CAAOE,OAAO,CAACH,GAAAA,CAAAA,CAAKI,MAAM,CAAC,CAAC,CAACC,CAAAA,EAAGC,CAAAA,CAAE,GAAKA,CAAAA,KAAMC,SAAAA,CAAAA,CAAAA;AAErD;AAEA;;;;;;;;IASA,SAASC,kBAAAA,CACLC,MAAW,EACXC,SAAiB,EACjBC,UAAAA,GAAuB,EAAE,EACzBC,gBAAAA,GAA6B,EAAE,EAAA;IAE/B,IAAI,CAACH,UAAU,OAAOA,MAAAA,KAAW,YAAYE,UAAAA,CAAWE,MAAM,KAAK,CAAA,EAAG;QAClE,OAAOJ,MAAAA;AACX;AAEA,IAAA,MAAMK,cAAAA,GAAiB;AAAE,QAAA,GAAGL;AAAO,KAAA;IAEnC,KA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Ae,IAAA,EAAM;YAC5BnC,MAAAA,CAAO0B,IAAI,CAAC,iEAAA,GAAoE,OAAOS,UAAAA,CAAAA;AAC3F;AACJ,KAAA,CAAE,OAAOV,KAAAA,EAAY;QACjB,IAAIA,KAAAA,CAAMa,IAAI,KAAK,QAAA,IAAY,0BAA0BC,IAAI,CAACd,KAAAA,CAAME,OAAO,CAAA,EAAG;AAC1E3B,YAAAA,MAAAA,CAAOK,OAAO,CAAC,0DAAA,CAAA;SACnB,MAAO;;AAEHL,YAAAA,MAAAA,CAAOyB,KAAK,CAAC,8CAAA,IAAkDA,KAAAA,CAAME,OAAO,IAAI,eAAc,CAAA,CAAA;AAClG;AACJ;IAEA,OAAOrB,aAAAA;AACX;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -7,6 +7,40 @@ import { ZodObject, z } from 'zod';
|
|
|
7
7
|
* - 'hierarchical': Hierarchical configuration discovery and layering
|
|
8
8
|
*/
|
|
9
9
|
export type Feature = 'config' | 'hierarchical';
|
|
10
|
+
/**
|
|
11
|
+
* Defines how array fields should be merged in hierarchical configurations.
|
|
12
|
+
*
|
|
13
|
+
* - 'override': Higher precedence arrays completely replace lower precedence arrays (default)
|
|
14
|
+
* - 'append': Higher precedence array elements are appended to lower precedence arrays
|
|
15
|
+
* - 'prepend': Higher precedence array elements are prepended to lower precedence arrays
|
|
16
|
+
*/
|
|
17
|
+
export type ArrayOverlapMode = 'override' | 'append' | 'prepend';
|
|
18
|
+
/**
|
|
19
|
+
* Configuration for how fields should be merged in hierarchical configurations.
|
|
20
|
+
* Maps field names (using dot notation) to their overlap behavior.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* const fieldOverlaps: FieldOverlapOptions = {
|
|
25
|
+
* 'features': 'append', // features arrays will be combined by appending
|
|
26
|
+
* 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending
|
|
27
|
+
* 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)
|
|
28
|
+
* };
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export interface FieldOverlapOptions {
|
|
32
|
+
[fieldPath: string]: ArrayOverlapMode;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Configuration for resolving relative paths in configuration values.
|
|
36
|
+
* Paths specified in these fields will be resolved relative to the configuration file's directory.
|
|
37
|
+
*/
|
|
38
|
+
export interface PathResolutionOptions {
|
|
39
|
+
/** Array of field names (using dot notation) that contain paths to be resolved */
|
|
40
|
+
pathFields?: string[];
|
|
41
|
+
/** Array of field names whose array elements should all be resolved as paths */
|
|
42
|
+
resolvePathArray?: string[];
|
|
43
|
+
}
|
|
10
44
|
/**
|
|
11
45
|
* Default configuration options for Cardigantime.
|
|
12
46
|
* These define the basic behavior of configuration loading.
|
|
@@ -20,6 +54,14 @@ export interface DefaultOptions {
|
|
|
20
54
|
isRequired: boolean;
|
|
21
55
|
/** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */
|
|
22
56
|
encoding: string;
|
|
57
|
+
/** Configuration for resolving relative paths in configuration values */
|
|
58
|
+
pathResolution?: PathResolutionOptions;
|
|
59
|
+
/**
|
|
60
|
+
* Configuration for how array fields should be merged in hierarchical mode.
|
|
61
|
+
* Only applies when the 'hierarchical' feature is enabled.
|
|
62
|
+
* If not specified, all arrays use 'override' behavior (default).
|
|
63
|
+
*/
|
|
64
|
+
fieldOverlaps?: FieldOverlapOptions;
|
|
23
65
|
}
|
|
24
66
|
/**
|
|
25
67
|
* Complete options object passed to Cardigantime functions.
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n"],"names":["ConfigSchema","z","object","configDirectory","string"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Defines how array fields should be merged in hierarchical configurations.\n * \n * - 'override': Higher precedence arrays completely replace lower precedence arrays (default)\n * - 'append': Higher precedence array elements are appended to lower precedence arrays\n * - 'prepend': Higher precedence array elements are prepended to lower precedence arrays\n */\nexport type ArrayOverlapMode = 'override' | 'append' | 'prepend';\n\n/**\n * Configuration for how fields should be merged in hierarchical configurations.\n * Maps field names (using dot notation) to their overlap behavior.\n * \n * @example\n * ```typescript\n * const fieldOverlaps: FieldOverlapOptions = {\n * 'features': 'append', // features arrays will be combined by appending\n * 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending\n * 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)\n * };\n * ```\n */\nexport interface FieldOverlapOptions {\n [fieldPath: string]: ArrayOverlapMode;\n}\n\n/**\n * Configuration for resolving relative paths in configuration values.\n * Paths specified in these fields will be resolved relative to the configuration file's directory.\n */\nexport interface PathResolutionOptions {\n /** Array of field names (using dot notation) that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n}\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n /** Configuration for resolving relative paths in configuration values */\n pathResolution?: PathResolutionOptions;\n /** \n * Configuration for how array fields should be merged in hierarchical mode.\n * Only applies when the 'hierarchical' feature is enabled.\n * If not specified, all arrays use 'override' behavior (default).\n */\n fieldOverlaps?: FieldOverlapOptions;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n"],"names":["ConfigSchema","z","object","configDirectory","string"],"mappings":";;AA8IA;;;AAGC,IACM,MAAMA,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;qDAEjCC,eAAAA,EAAiBF,CAAAA,CAAEG,MAAM;AAC7B,CAAA;;;;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Logger } from '../types';
|
|
1
|
+
import { Logger, FieldOverlapOptions } from '../types';
|
|
2
2
|
/**
|
|
3
3
|
* Represents a discovered configuration directory with its path and precedence level.
|
|
4
4
|
*/
|
|
@@ -24,6 +24,12 @@ export interface HierarchicalDiscoveryOptions {
|
|
|
24
24
|
encoding?: string;
|
|
25
25
|
/** Logger for debugging */
|
|
26
26
|
logger?: Logger;
|
|
27
|
+
/** Array of field names that contain paths to be resolved */
|
|
28
|
+
pathFields?: string[];
|
|
29
|
+
/** Array of field names whose array elements should all be resolved as paths */
|
|
30
|
+
resolvePathArray?: string[];
|
|
31
|
+
/** Configuration for how array fields should be merged in hierarchical mode */
|
|
32
|
+
fieldOverlaps?: FieldOverlapOptions;
|
|
27
33
|
}
|
|
28
34
|
/**
|
|
29
35
|
* Result of loading configurations from multiple directories.
|
|
@@ -68,29 +74,33 @@ export declare function discoverConfigDirectories(options: HierarchicalDiscovery
|
|
|
68
74
|
* @param configFileName Name of the configuration file
|
|
69
75
|
* @param encoding File encoding
|
|
70
76
|
* @param logger Optional logger
|
|
77
|
+
* @param pathFields Optional array of field names that contain paths to be resolved
|
|
78
|
+
* @param resolvePathArray Optional array of field names whose array elements should all be resolved as paths
|
|
71
79
|
* @returns Promise resolving to parsed configuration object or null if not found
|
|
72
80
|
*/
|
|
73
|
-
export declare function loadConfigFromDirectory(configDir: string, configFileName: string, encoding?: string, logger?: Logger): Promise<object | null>;
|
|
81
|
+
export declare function loadConfigFromDirectory(configDir: string, configFileName: string, encoding?: string, logger?: Logger, pathFields?: string[], resolvePathArray?: string[]): Promise<object | null>;
|
|
74
82
|
/**
|
|
75
|
-
* Deep merges multiple configuration objects with proper precedence.
|
|
83
|
+
* Deep merges multiple configuration objects with proper precedence and configurable array overlap behavior.
|
|
76
84
|
*
|
|
77
85
|
* Objects are merged from lowest precedence to highest precedence,
|
|
78
86
|
* meaning that properties in later objects override properties in earlier objects.
|
|
79
|
-
* Arrays
|
|
87
|
+
* Arrays can be merged using different strategies based on the fieldOverlaps configuration.
|
|
80
88
|
*
|
|
81
89
|
* @param configs Array of configuration objects, ordered from lowest to highest precedence
|
|
90
|
+
* @param fieldOverlaps Configuration for how array fields should be merged (optional)
|
|
82
91
|
* @returns Merged configuration object
|
|
83
92
|
*
|
|
84
93
|
* @example
|
|
85
94
|
* ```typescript
|
|
86
95
|
* const merged = deepMergeConfigs([
|
|
87
|
-
* { api: { timeout: 5000 },
|
|
88
|
-
* { api: { retries: 3 }, features: ['
|
|
89
|
-
* ]
|
|
90
|
-
* //
|
|
96
|
+
* { api: { timeout: 5000 }, features: ['auth'] }, // Lower precedence
|
|
97
|
+
* { api: { retries: 3 }, features: ['analytics'] }, // Higher precedence
|
|
98
|
+
* ], {
|
|
99
|
+
* 'features': 'append' // Results in features: ['auth', 'analytics']
|
|
100
|
+
* });
|
|
91
101
|
* ```
|
|
92
102
|
*/
|
|
93
|
-
export declare function deepMergeConfigs(configs: object[]): object;
|
|
103
|
+
export declare function deepMergeConfigs(configs: object[], fieldOverlaps?: FieldOverlapOptions): object;
|
|
94
104
|
/**
|
|
95
105
|
* Loads configurations from multiple directories and merges them with proper precedence.
|
|
96
106
|
*
|
|
@@ -109,10 +119,14 @@ export declare function deepMergeConfigs(configs: object[]): object;
|
|
|
109
119
|
* configDirName: '.kodrdriv',
|
|
110
120
|
* configFileName: 'config.yaml',
|
|
111
121
|
* startingDir: '/project/subdir',
|
|
112
|
-
* maxLevels: 5
|
|
122
|
+
* maxLevels: 5,
|
|
123
|
+
* fieldOverlaps: {
|
|
124
|
+
* 'features': 'append',
|
|
125
|
+
* 'excludePatterns': 'prepend'
|
|
126
|
+
* }
|
|
113
127
|
* });
|
|
114
128
|
*
|
|
115
|
-
* // result.config contains merged configuration
|
|
129
|
+
* // result.config contains merged configuration with custom array merging
|
|
116
130
|
* // result.discoveredDirs shows where configs were found
|
|
117
131
|
* // result.errors contains any non-fatal errors
|
|
118
132
|
* ```
|