@theunwalked/cardigantime 0.0.1 → 0.0.3

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.
Files changed (52) hide show
  1. package/README.md +699 -0
  2. package/dist/cardigantime.cjs +907 -15
  3. package/dist/cardigantime.cjs.map +1 -1
  4. package/dist/cardigantime.d.ts +42 -0
  5. package/dist/cardigantime.js +49 -345
  6. package/dist/cardigantime.js.map +1 -1
  7. package/dist/configure.d.ts +50 -1
  8. package/dist/configure.js +102 -3
  9. package/dist/configure.js.map +1 -1
  10. package/dist/constants.d.ts +17 -0
  11. package/dist/constants.js +17 -9
  12. package/dist/constants.js.map +1 -1
  13. package/dist/error/ArgumentError.d.ts +26 -0
  14. package/dist/error/ArgumentError.js +48 -0
  15. package/dist/error/ArgumentError.js.map +1 -0
  16. package/dist/error/ConfigurationError.d.ts +21 -0
  17. package/dist/error/ConfigurationError.js +46 -0
  18. package/dist/error/ConfigurationError.js.map +1 -0
  19. package/dist/error/FileSystemError.d.ts +30 -0
  20. package/dist/error/FileSystemError.js +58 -0
  21. package/dist/error/FileSystemError.js.map +1 -0
  22. package/dist/error/index.d.ts +3 -0
  23. package/dist/read.d.ts +30 -0
  24. package/dist/read.js +105 -12
  25. package/dist/read.js.map +1 -1
  26. package/dist/types.d.ts +63 -0
  27. package/dist/types.js +5 -3
  28. package/dist/types.js.map +1 -1
  29. package/dist/util/storage.js +33 -4
  30. package/dist/util/storage.js.map +1 -1
  31. package/dist/validate.d.ts +96 -1
  32. package/dist/validate.js +164 -20
  33. package/dist/validate.js.map +1 -1
  34. package/package.json +30 -23
  35. package/.gitcarve/config.yaml +0 -10
  36. package/.gitcarve/context/content.md +0 -1
  37. package/dist/configure.cjs +0 -12
  38. package/dist/configure.cjs.map +0 -1
  39. package/dist/constants.cjs +0 -35
  40. package/dist/constants.cjs.map +0 -1
  41. package/dist/read.cjs +0 -69
  42. package/dist/read.cjs.map +0 -1
  43. package/dist/types.cjs +0 -13
  44. package/dist/types.cjs.map +0 -1
  45. package/dist/util/storage.cjs +0 -149
  46. package/dist/util/storage.cjs.map +0 -1
  47. package/dist/validate.cjs +0 -130
  48. package/dist/validate.cjs.map +0 -1
  49. package/eslint.config.mjs +0 -82
  50. package/nodemon.json +0 -14
  51. package/vite.config.ts +0 -98
  52. package/vitest.config.ts +0 -17
@@ -1 +1 @@
1
- {"version":3,"file":"cardigantime.cjs","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';\n\n// Make create function generic\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":";;;;;;;;;;AAWA;AACO,MAAMA,SAAS,CAA0BC,QAAAA,GAAAA;AAQ5C,IAAA,MAAMC,QAA2B,GAAA;AAAE,QAAA,GAAGC,yBAAe;AAAE,QAAA,GAAGF,SAASC;AAAS,KAAA;IAC5E,MAAME,QAAAA,GAAWH,QAASG,CAAAA,QAAQ,IAAIC,0BAAAA;IACtC,MAAMC,WAAAA,GAAcL,SAASK,WAAW;IACxC,IAAIC,MAAAA,GAASN,QAASM,CAAAA,MAAM,IAAIC,wBAAAA;AAEhC,IAAA,MAAMC,OAAsB,GAAA;AACxBP,QAAAA,QAAAA;AACAE,QAAAA,QAAAA;AACAE,QAAAA,WAAAA;AACAC,QAAAA;AACJ,KAAA;AAEA,IAAA,MAAMG,YAAY,CAACC,OAAAA,GAAAA;QACfJ,MAASI,GAAAA,OAAAA;AACTF,QAAAA,OAAAA,CAAQF,MAAM,GAAGI,OAAAA;AACrB,KAAA;IAEA,OAAO;AACHD,QAAAA,SAAAA;QACAE,SAAW,EAAA,CAACC,OAAqBD,GAAAA,mBAAAA,CAAUC,OAASJ,EAAAA,OAAAA,CAAAA;QACpDK,QAAU,EAAA,CAACC,MAA8DD,GAAAA,iBAAAA,CAASC,MAAQN,EAAAA,OAAAA,CAAAA;QAC1FO,IAAM,EAAA,CAACC,IAAeD,GAAAA,SAAAA,CAAKC,IAAMR,EAAAA,OAAAA;AACrC,KAAA;AACJ;;;;;"}
1
+ {"version":3,"file":"cardigantime.cjs","sources":["../src/error/ArgumentError.ts","../src/configure.ts","../src/constants.ts","../src/error/FileSystemError.ts","../src/util/storage.ts","../src/read.ts","../src/error/ConfigurationError.ts","../src/types.ts","../src/validate.ts","../src/cardigantime.ts"],"sourcesContent":["/**\n * Error thrown when CLI arguments or function parameters are invalid.\n * \n * This error provides specific context about which argument failed validation\n * and why, making it easier for users to fix their command-line usage or\n * for developers to debug parameter issues.\n * \n * @example\n * ```typescript\n * throw new ArgumentError('config-directory', 'Path cannot be empty');\n * // Error message: \"Path cannot be empty\"\n * // error.argument: \"config-directory\"\n * ```\n */\nexport class ArgumentError extends Error {\n /** The name of the argument that caused the error */\n private argumentName: string;\n\n /**\n * Creates a new ArgumentError instance.\n * \n * @param argumentName - The name of the invalid argument\n * @param message - Description of why the argument is invalid\n */\n constructor(argumentName: string, message: string) {\n super(`${message}`);\n this.name = 'ArgumentError';\n this.argumentName = argumentName;\n }\n\n /**\n * Gets the name of the argument that caused this error.\n * \n * @returns The argument name\n */\n get argument(): string {\n return this.argumentName;\n }\n}","import { Command } from \"commander\";\nimport { z } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { Options } from \"./types\";\nexport { ArgumentError };\n\n/**\n * Validates a configuration directory path to ensure it's safe and valid.\n * \n * Performs security and safety checks including:\n * - Non-empty string validation\n * - Null byte injection prevention\n * - Path length validation\n * - Type checking\n * \n * @param configDirectory - The configuration directory path to validate\n * @param _testThrowNonArgumentError - Internal testing parameter to simulate non-ArgumentError exceptions\n * @returns The trimmed and validated configuration directory path\n * @throws {ArgumentError} When the directory path is invalid\n * \n * @example\n * ```typescript\n * const validDir = validateConfigDirectory('./config'); // Returns './config'\n * const invalidDir = validateConfigDirectory(''); // Throws ArgumentError\n * ```\n */\nexport function validateConfigDirectory(configDirectory: string, _testThrowNonArgumentError?: boolean): string {\n if (_testThrowNonArgumentError) {\n throw new Error('Test non-ArgumentError for coverage');\n }\n\n if (!configDirectory) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty');\n }\n\n if (typeof configDirectory !== 'string') {\n throw new ArgumentError('configDirectory', 'Configuration directory must be a string');\n }\n\n const trimmed = configDirectory.trim();\n if (trimmed.length === 0) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty or whitespace only');\n }\n\n // Check for obviously invalid paths\n if (trimmed.includes('\\0')) {\n throw new ArgumentError('configDirectory', 'Configuration directory contains invalid null character');\n }\n\n // Validate path length (reasonable limit)\n if (trimmed.length > 1000) {\n throw new ArgumentError('configDirectory', 'Configuration directory path is too long (max 1000 characters)');\n }\n\n return trimmed;\n}\n\n/**\n * Configures a Commander.js command with Cardigantime's CLI options.\n * \n * This function adds command-line options that allow users to override\n * configuration settings at runtime, such as:\n * - --config-directory: Override the default configuration directory\n * \n * The function validates both the command object and the options to ensure\n * they meet the requirements for proper integration.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param command - The Commander.js Command instance to configure\n * @param options - Cardigantime options containing defaults and schema\n * @param _testThrowNonArgumentError - Internal testing parameter\n * @returns Promise resolving to the configured Command instance\n * @throws {ArgumentError} When command or options are invalid\n * \n * @example\n * ```typescript\n * import { Command } from 'commander';\n * import { configure } from './configure';\n * \n * const program = new Command();\n * const configuredProgram = await configure(program, options);\n * \n * // Now the program accepts: --config-directory <path>\n * ```\n */\nexport const configure = async <T extends z.ZodRawShape>(\n command: Command,\n options: Options<T>,\n _testThrowNonArgumentError?: boolean\n): Promise<Command> => {\n // Validate the command object\n if (!command) {\n throw new ArgumentError('command', 'Command instance is required');\n }\n\n if (typeof command.option !== 'function') {\n throw new ArgumentError('command', 'Command must be a valid Commander.js Command instance');\n }\n\n // Validate options\n if (!options) {\n throw new ArgumentError('options', 'Options object is required');\n }\n\n if (!options.defaults) {\n throw new ArgumentError('options.defaults', 'Options must include defaults configuration');\n }\n\n if (!options.defaults.configDirectory) {\n throw new ArgumentError('options.defaults.configDirectory', 'Default config directory is required');\n }\n\n // Validate the default config directory\n const validatedDefaultDir = validateConfigDirectory(options.defaults.configDirectory, _testThrowNonArgumentError);\n\n let retCommand = command;\n\n // Add the config directory option with validation\n retCommand = retCommand.option(\n '-c, --config-directory <configDirectory>',\n 'Configuration directory path',\n (value: string) => {\n try {\n return validateConfigDirectory(value, _testThrowNonArgumentError);\n } catch (error) {\n if (error instanceof ArgumentError) {\n // Re-throw with more specific context for CLI usage\n throw new ArgumentError('config-directory', `Invalid --config-directory: ${error.message}`);\n }\n throw error;\n }\n },\n validatedDefaultDir\n );\n\n return retCommand;\n}\n\n\n\n\n","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","/**\n * Error thrown when file system operations fail\n */\nexport class FileSystemError extends Error {\n public readonly errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed';\n public readonly path: string;\n public readonly operation: string;\n public readonly originalError?: Error;\n\n constructor(\n errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed',\n message: string,\n path: string,\n operation: string,\n originalError?: Error\n ) {\n super(message);\n this.name = 'FileSystemError';\n this.errorType = errorType;\n this.path = path;\n this.operation = operation;\n this.originalError = originalError;\n }\n\n /**\n * Creates an error for when a required directory doesn't exist\n */\n static directoryNotFound(path: string, isRequired: boolean = false): FileSystemError {\n const message = isRequired\n ? 'Configuration directory does not exist and is required'\n : 'Configuration directory not found';\n return new FileSystemError('not_found', message, path, 'directory_access');\n }\n\n /**\n * Creates an error for when a directory exists but isn't readable\n */\n static directoryNotReadable(path: string): FileSystemError {\n const message = 'Configuration directory exists but is not readable';\n return new FileSystemError('not_readable', message, path, 'directory_read');\n }\n\n /**\n * Creates an error for directory creation failures\n */\n static directoryCreationFailed(path: string, originalError: Error): FileSystemError {\n const message = 'Failed to create directory: ' + (originalError.message || 'Unknown error');\n return new FileSystemError('creation_failed', message, path, 'directory_create', originalError);\n }\n\n /**\n * Creates an error for file operation failures (glob, etc.)\n */\n static operationFailed(operation: string, path: string, originalError: Error): FileSystemError {\n const message = `Failed to ${operation}: ${originalError.message || 'Unknown error'}`;\n return new FileSystemError('operation_failed', message, path, operation, originalError);\n }\n\n /**\n * Creates an error for when a file is not found\n */\n static fileNotFound(path: string): FileSystemError {\n const message = 'Configuration file not found';\n return new FileSystemError('not_found', message, path, 'file_read');\n }\n} ","// eslint-disable-next-line no-restricted-imports\nimport * as fs from 'fs';\nimport { glob } from 'glob';\nimport path from 'path';\nimport crypto from 'crypto';\nimport { FileSystemError } from '../error/FileSystemError';\n/**\n * This module exists to isolate filesystem operations from the rest of the codebase.\n * This makes testing easier by avoiding direct fs mocking in jest configuration.\n * \n * Additionally, abstracting storage operations allows for future flexibility - \n * this export utility may need to work with storage systems other than the local filesystem\n * (e.g. S3, Google Cloud Storage, etc).\n */\n\nexport interface Utility {\n exists: (path: string) => Promise<boolean>;\n isDirectory: (path: string) => Promise<boolean>;\n isFile: (path: string) => Promise<boolean>;\n isReadable: (path: string) => Promise<boolean>;\n isWritable: (path: string) => Promise<boolean>;\n isFileReadable: (path: string) => Promise<boolean>;\n isDirectoryWritable: (path: string) => Promise<boolean>;\n isDirectoryReadable: (path: string) => Promise<boolean>;\n createDirectory: (path: string) => Promise<void>;\n readFile: (path: string, encoding: string) => Promise<string>;\n readStream: (path: string) => Promise<fs.ReadStream>;\n writeFile: (path: string, data: string | Buffer, encoding: string) => Promise<void>;\n forEachFileIn: (directory: string, callback: (path: string) => Promise<void>, options?: { pattern: string }) => Promise<void>;\n hashFile: (path: string, length: number) => Promise<string>;\n listFiles: (directory: string) => Promise<string[]>;\n}\n\nexport const create = (params: { log?: (message: string, ...args: any[]) => void }): Utility => {\n\n // eslint-disable-next-line no-console\n const log = params.log || console.log;\n\n const exists = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.stat(path);\n return true;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error: any) {\n return false;\n }\n }\n\n const isDirectory = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isDirectory()) {\n log(`${path} is not a directory`);\n return false;\n }\n return true;\n }\n\n const isFile = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isFile()) {\n log(`${path} is not a file`);\n return false;\n }\n return true;\n }\n\n const isReadable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.R_OK);\n } catch (error: any) {\n log(`${path} is not readable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isWritable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.W_OK);\n } catch (error: any) {\n log(`${path} is not writable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isFileReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isFile(path) && await isReadable(path);\n }\n\n const isDirectoryWritable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isWritable(path);\n }\n\n const isDirectoryReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isReadable(path);\n }\n\n const createDirectory = async (path: string): Promise<void> => {\n try {\n await fs.promises.mkdir(path, { recursive: true });\n } catch (mkdirError: any) {\n throw FileSystemError.directoryCreationFailed(path, mkdirError);\n }\n }\n\n const readFile = async (path: string, encoding: string): Promise<string> => {\n // Validate encoding parameter\n const validEncodings = ['utf8', 'utf-8', 'ascii', 'latin1', 'base64', 'hex', 'utf16le', 'ucs2', 'ucs-2'];\n if (!validEncodings.includes(encoding.toLowerCase())) {\n throw new Error('Invalid encoding specified');\n }\n\n // Check file size before reading to prevent DoS\n try {\n const stats = await fs.promises.stat(path);\n const maxFileSize = 10 * 1024 * 1024; // 10MB limit\n if (stats.size > maxFileSize) {\n throw new Error('File too large to process');\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n throw FileSystemError.fileNotFound(path);\n }\n throw error;\n }\n\n return await fs.promises.readFile(path, { encoding: encoding as BufferEncoding });\n }\n\n const writeFile = async (path: string, data: string | Buffer, encoding: string): Promise<void> => {\n await fs.promises.writeFile(path, data, { encoding: encoding as BufferEncoding });\n }\n\n const forEachFileIn = async (directory: string, callback: (file: string) => Promise<void>, options: { pattern: string | string[] } = { pattern: '*.*' }): Promise<void> => {\n try {\n const files = await glob(options.pattern, { cwd: directory, nodir: true });\n for (const file of files) {\n await callback(path.join(directory, file));\n }\n } catch (err: any) {\n throw FileSystemError.operationFailed(`glob pattern ${options.pattern}`, directory, err);\n }\n }\n\n const readStream = async (path: string): Promise<fs.ReadStream> => {\n return fs.createReadStream(path);\n }\n\n const hashFile = async (path: string, length: number): Promise<string> => {\n const file = await readFile(path, 'utf8');\n return crypto.createHash('sha256').update(file).digest('hex').slice(0, length);\n }\n\n const listFiles = async (directory: string): Promise<string[]> => {\n return await fs.promises.readdir(directory);\n }\n\n return {\n exists,\n isDirectory,\n isFile,\n isReadable,\n isWritable,\n isFileReadable,\n isDirectoryWritable,\n isDirectoryReadable,\n createDirectory,\n readFile,\n readStream,\n writeFile,\n forEachFileIn,\n hashFile,\n listFiles,\n };\n}","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';\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 const storage = Storage.create({ log: logger.debug });\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.debug('Resolved config directory');\n\n const configFile = validatePath(options.defaults.configFile, resolvedConfigDir);\n logger.debug('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.debug('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.debug('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 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 * Error thrown when configuration validation fails\n */\nexport class ConfigurationError extends Error {\n public readonly errorType: 'validation' | 'schema' | 'extra_keys';\n public readonly details?: any;\n public readonly configPath?: string;\n\n constructor(\n errorType: 'validation' | 'schema' | 'extra_keys',\n message: string,\n details?: any,\n configPath?: string\n ) {\n super(message);\n this.name = 'ConfigurationError';\n this.errorType = errorType;\n this.details = details;\n this.configPath = configPath;\n }\n\n /**\n * Creates a validation error for when config doesn't match the schema\n */\n static validation(message: string, zodError?: any, configPath?: string): ConfigurationError {\n return new ConfigurationError('validation', message, zodError, configPath);\n }\n\n /**\n * Creates an error for when extra/unknown keys are found\n */\n static extraKeys(extraKeys: string[], allowedKeys: string[], configPath?: string): ConfigurationError {\n const message = `Unknown configuration keys found: ${extraKeys.join(', ')}. Allowed keys are: ${allowedKeys.join(', ')}`;\n return new ConfigurationError('extra_keys', message, { extraKeys, allowedKeys }, configPath);\n }\n\n /**\n * Creates a schema error for when the configuration schema itself is invalid\n */\n static schema(message: string, details?: any): ConfigurationError {\n return new ConfigurationError('schema', message, details);\n }\n} ","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 */\nexport type Feature = 'config';\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","import { z, ZodObject } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { ConfigurationError } from \"./error/ConfigurationError\";\nimport { FileSystemError } from \"./error/FileSystemError\";\nimport { ConfigSchema, Logger, Options } from \"./types\";\nimport * as Storage from \"./util/storage\";\nexport { ArgumentError, ConfigurationError, FileSystemError };\n\n/**\n * Recursively extracts all keys from a Zod schema in dot notation.\n * \n * This function traverses a Zod schema structure and builds a flat list\n * of all possible keys, using dot notation for nested objects. It handles\n * optional/nullable types by unwrapping them and supports arrays by\n * introspecting their element type.\n * \n * Special handling for:\n * - ZodOptional/ZodNullable: Unwraps to get the underlying type\n * - ZodAny/ZodRecord: Accepts any keys, returns the prefix or empty array\n * - ZodArray: Introspects the element type\n * - ZodObject: Recursively processes all shape properties\n * \n * @param schema - The Zod schema to introspect\n * @param prefix - Internal parameter for building nested key paths\n * @returns Array of strings representing all possible keys in dot notation\n * \n * @example\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string(),\n * settings: z.object({ theme: z.string() })\n * }),\n * debug: z.boolean()\n * });\n * \n * const keys = listZodKeys(schema);\n * // Returns: ['user.name', 'user.settings.theme', 'debug']\n * ```\n */\nexport const listZodKeys = (schema: z.ZodTypeAny, prefix = ''): string[] => {\n // Check if schema has unwrap method (which both ZodOptional and ZodNullable have)\n if (schema._def && (schema._def.typeName === 'ZodOptional' || schema._def.typeName === 'ZodNullable')) {\n // Use type assertion to handle the unwrap method\n const unwrappable = schema as z.ZodOptional<any> | z.ZodNullable<any>;\n return listZodKeys(unwrappable.unwrap(), prefix);\n }\n\n // Handle ZodAny and ZodRecord - these accept any keys, so don't introspect\n if (schema._def && (schema._def.typeName === 'ZodAny' || schema._def.typeName === 'ZodRecord')) {\n return prefix ? [prefix] : [];\n }\n\n if (schema._def && schema._def.typeName === 'ZodArray') {\n // Use type assertion to handle the element property\n const arraySchema = schema as z.ZodArray<any>;\n return listZodKeys(arraySchema.element, prefix);\n }\n if (schema._def && schema._def.typeName === 'ZodObject') {\n // Use type assertion to handle the shape property\n const objectSchema = schema as z.ZodObject<any>;\n return Object.entries(objectSchema.shape).flatMap(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n const nested = listZodKeys(subschema as z.ZodTypeAny, fullKey);\n return nested.length ? nested : fullKey;\n });\n }\n return [];\n}\n\n/**\n * Type guard to check if a value is a plain object (not array, null, or other types).\n * \n * @param value - The value to check\n * @returns True if the value is a plain object\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n // Check if it's an object, not null, and not an array.\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n};\n\n/**\n * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.\n * Mimics the behavior of listZodKeys but operates on plain objects.\n * For arrays, it inspects the first element that is a plain object to determine nested keys.\n * If an array contains no plain objects, or is empty, the key for the array itself is listed.\n *\n * @param obj The object to introspect.\n * @param prefix Internal use for recursion: the prefix for the current nesting level.\n * @returns An array of strings representing all keys in dot notation.\n */\nexport const listObjectKeys = (obj: Record<string, unknown>, prefix = ''): string[] => {\n const keys = new Set<string>(); // Use Set to automatically handle duplicates from array recursion\n\n for (const key in obj) {\n // Ensure it's an own property, not from the prototype chain\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (Array.isArray(value)) {\n // Find the first element that is a plain object to determine structure\n const firstObjectElement = value.find(isPlainObject);\n if (firstObjectElement) {\n // Recurse into the structure of the first object element found\n const nestedKeys = listObjectKeys(firstObjectElement, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // Array is empty or contains no plain objects, list the array key itself\n keys.add(fullKey);\n }\n } else if (isPlainObject(value)) {\n // Recurse into nested plain objects\n const nestedKeys = listObjectKeys(value, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // It's a primitive, null, or other non-plain object/array type\n keys.add(fullKey);\n }\n }\n }\n return Array.from(keys); // Convert Set back to Array\n};\n\n/**\n * Validates that the configuration object contains only keys allowed by the schema.\n * \n * This function prevents configuration errors by detecting typos or extra keys\n * that aren't defined in the Zod schema. It intelligently handles:\n * - ZodRecord types that accept arbitrary keys\n * - Nested objects and their key structures\n * - Arrays and their element key structures\n * \n * The function throws a ConfigurationError if extra keys are found, providing\n * helpful information about what keys are allowed vs. what was found.\n * \n * @param mergedSources - The merged configuration object to validate\n * @param fullSchema - The complete Zod schema including base and user schemas\n * @param logger - Logger for error reporting\n * @throws {ConfigurationError} When extra keys are found that aren't in the schema\n * \n * @example\n * ```typescript\n * const schema = z.object({ name: z.string(), age: z.number() });\n * const config = { name: 'John', age: 30, typo: 'invalid' };\n * \n * checkForExtraKeys(config, schema, console);\n * // Throws: ConfigurationError with details about 'typo' being an extra key\n * ```\n */\nexport const checkForExtraKeys = (mergedSources: object, fullSchema: ZodObject<any>, logger: Logger | typeof console): void => {\n const allowedKeys = new Set(listZodKeys(fullSchema));\n const actualKeys = listObjectKeys(mergedSources as Record<string, unknown>);\n\n // Filter out keys that are under a record type (ZodRecord accepts any keys)\n const recordPrefixes = new Set<string>();\n\n // Find all prefixes that are ZodRecord types\n const findRecordPrefixes = (schema: z.ZodTypeAny, prefix = ''): void => {\n if (schema._def && (schema._def.typeName === 'ZodOptional' || schema._def.typeName === 'ZodNullable')) {\n const unwrappable = schema as z.ZodOptional<any> | z.ZodNullable<any>;\n findRecordPrefixes(unwrappable.unwrap(), prefix);\n return;\n }\n\n if (schema._def && (schema._def.typeName === 'ZodAny' || schema._def.typeName === 'ZodRecord')) {\n if (prefix) recordPrefixes.add(prefix);\n return;\n }\n\n if (schema._def && schema._def.typeName === 'ZodObject') {\n const objectSchema = schema as z.ZodObject<any>;\n Object.entries(objectSchema.shape).forEach(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n findRecordPrefixes(subschema as z.ZodTypeAny, fullKey);\n });\n }\n };\n\n findRecordPrefixes(fullSchema);\n\n // Filter out keys that are under record prefixes\n const extraKeys = actualKeys.filter(key => {\n if (allowedKeys.has(key)) return false;\n\n // Check if this key is under a record prefix\n for (const recordPrefix of recordPrefixes) {\n if (key.startsWith(recordPrefix + '.')) {\n return false; // This key is allowed under a record\n }\n }\n\n return true; // This is an extra key\n });\n\n if (extraKeys.length > 0) {\n const allowedKeysArray = Array.from(allowedKeys);\n const error = ConfigurationError.extraKeys(extraKeys, allowedKeysArray);\n logger.error(error.message);\n throw error;\n }\n}\n\n/**\n * Validates that a configuration directory exists and is accessible.\n * \n * This function performs file system checks to ensure the configuration\n * directory can be used. It handles the isRequired flag to determine\n * whether a missing directory should cause an error or be silently ignored.\n * \n * @param configDirectory - Path to the configuration directory\n * @param isRequired - Whether the directory must exist\n * @param logger - Optional logger for debug information\n * @throws {FileSystemError} When the directory is required but missing or unreadable\n */\nconst validateConfigDirectory = async (configDirectory: string, isRequired: boolean, logger?: Logger): Promise<void> => {\n const storage = Storage.create({ log: logger?.debug || (() => { }) });\n const exists = await storage.exists(configDirectory);\n if (!exists) {\n if (isRequired) {\n throw FileSystemError.directoryNotFound(configDirectory, true);\n }\n } else if (exists) {\n const isReadable = await storage.isDirectoryReadable(configDirectory);\n if (!isReadable) {\n throw FileSystemError.directoryNotReadable(configDirectory);\n }\n }\n}\n\n/**\n * Validates a configuration object against the combined Zod schema.\n * \n * This is the main validation function that:\n * 1. Validates the configuration directory (if config feature enabled)\n * 2. Combines the base ConfigSchema with user-provided schema shape\n * 3. Checks for extra keys not defined in the schema\n * 4. Validates all values against their schema definitions\n * 5. Provides detailed error reporting for validation failures\n * \n * The validation is comprehensive and catches common configuration errors\n * including typos, missing required fields, wrong types, and invalid values.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param config - The merged configuration object to validate\n * @param options - Cardigantime options containing schema, defaults, and logger\n * @throws {ConfigurationError} When configuration validation fails\n * @throws {FileSystemError} When configuration directory validation fails\n * \n * @example\n * ```typescript\n * const schema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().positive(),\n * });\n * \n * await validate(config, {\n * configShape: schema.shape,\n * defaults: { configDirectory: './config', isRequired: true },\n * logger: console,\n * features: ['config']\n * });\n * // Throws detailed errors if validation fails\n * ```\n */\nexport const validate = async <T extends z.ZodRawShape>(config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>, options: Options<T>): Promise<void> => {\n const logger = options.logger;\n\n if (options.features.includes('config') && config.configDirectory) {\n await validateConfigDirectory(config.configDirectory, options.defaults.isRequired, logger);\n }\n\n // Combine the base schema with the user-provided shape\n const fullSchema = z.object({\n ...ConfigSchema.shape,\n ...options.configShape,\n });\n\n // Validate the merged sources against the full schema\n const validationResult = fullSchema.safeParse(config);\n\n // Check for extraneous keys\n checkForExtraKeys(config, fullSchema, logger);\n\n if (!validationResult.success) {\n const formattedError = JSON.stringify(validationResult.error.format(), null, 2);\n logger.error('Configuration validation failed: %s', formattedError);\n throw ConfigurationError.validation('Configuration validation failed. Check logs for details.', validationResult.error);\n }\n\n return;\n}\n\n","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":["_define_property","ArgumentError","Error","argument","argumentName","message","name","validateConfigDirectory","configDirectory","_testThrowNonArgumentError","trimmed","trim","length","includes","configure","command","options","option","defaults","validatedDefaultDir","retCommand","value","error","DEFAULT_ENCODING","DEFAULT_CONFIG_FILE","DEFAULT_OPTIONS","configFile","isRequired","encoding","DEFAULT_FEATURES","DEFAULT_LOGGER","debug","console","info","warn","verbose","silly","FileSystemError","directoryNotFound","path","directoryNotReadable","directoryCreationFailed","originalError","operationFailed","operation","fileNotFound","errorType","create","params","log","exists","fs","promises","stat","isDirectory","stats","isFile","isReadable","access","constants","R_OK","stack","isWritable","W_OK","isFileReadable","isDirectoryWritable","isDirectoryReadable","createDirectory","mkdir","recursive","mkdirError","readFile","validEncodings","toLowerCase","maxFileSize","size","code","writeFile","data","forEachFileIn","directory","callback","pattern","files","glob","cwd","nodir","file","join","err","readStream","createReadStream","hashFile","crypto","createHash","update","digest","slice","listFiles","readdir","clean","obj","Object","fromEntries","entries","filter","_","v","undefined","validatePath","userPath","basePath","normalized","normalize","isAbsolute","startsWith","configDir","read","args","logger","storage","Storage","rawConfigDir","resolvedConfigDir","rawFileConfig","yamlContent","parsedYaml","yaml","load","test","config","ConfigurationError","validation","zodError","configPath","extraKeys","allowedKeys","schema","details","ConfigSchema","z","object","string","listZodKeys","prefix","_def","typeName","unwrappable","unwrap","arraySchema","element","objectSchema","shape","flatMap","key","subschema","fullKey","nested","isPlainObject","Array","isArray","listObjectKeys","keys","Set","prototype","hasOwnProperty","call","firstObjectElement","find","nestedKeys","forEach","k","add","from","checkForExtraKeys","mergedSources","fullSchema","actualKeys","recordPrefixes","findRecordPrefixes","has","recordPrefix","allowedKeysArray","validate","features","configShape","validationResult","safeParse","success","formattedError","JSON","stringify","format","pOptions","setLogger","pLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;AAaC,IAAA,SAAAA,kBAAA,CAAA,GAAA,EAAA,GAAA,EAAA,KAAA,EAAA;;;;;;;;;;;;;AACM,MAAMC,aAAAA,SAAsBC,KAAAA,CAAAA;AAgB/B;;;;AAIC,QACD,IAAIC,QAAAA,GAAmB;QACnB,OAAO,IAAI,CAACC,YAAY;AAC5B;AAnBA;;;;;AAKC,QACD,WAAA,CAAYA,YAAoB,EAAEC,OAAe,CAAE;QAC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E,OAAAA;AACrB,KAAA;IAEA,OAAO;AACHD,QAAAA,SAAAA;QACApL,SAAAA,EAAW,CAACC,OAAAA,GAAqBD,SAAAA,CAAUC,OAAAA,EAASC,OAAAA,CAAAA;QACpDuK,QAAAA,EAAU,CAACrD,MAAAA,GAA8DqD,QAAAA,CAASrD,MAAAA,EAAQlH,OAAAA,CAAAA;QAC1FqG,IAAAA,EAAM,CAACC,IAAAA,GAAeD,IAAAA,CAAKC,IAAAA,EAAMtG,OAAAA;AACrC,KAAA;AACJ;;;;;;;;"}
@@ -1,6 +1,48 @@
1
1
  import { DefaultOptions, Feature, Cardigantime, Logger } from './types';
2
2
  import { z } from 'zod';
3
3
  export * from './types';
4
+ export { ArgumentError, ConfigurationError, FileSystemError } from './validate';
5
+ /**
6
+ * Creates a new Cardigantime instance for configuration management.
7
+ *
8
+ * Cardigantime handles the complete configuration lifecycle including:
9
+ * - Reading configuration from YAML files
10
+ * - Validating configuration against Zod schemas
11
+ * - Merging CLI arguments with file configuration and defaults
12
+ * - Providing type-safe configuration objects
13
+ *
14
+ * @template T - The Zod schema shape type for your configuration
15
+ * @param pOptions - Configuration options for the Cardigantime instance
16
+ * @param pOptions.defaults - Default configuration settings
17
+ * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)
18
+ * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')
19
+ * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)
20
+ * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')
21
+ * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])
22
+ * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)
23
+ * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)
24
+ * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * import { create } from '@theunwalked/cardigantime';
29
+ * import { z } from 'zod';
30
+ *
31
+ * const MyConfigSchema = z.object({
32
+ * apiKey: z.string().min(1),
33
+ * timeout: z.number().default(5000),
34
+ * debug: z.boolean().default(false),
35
+ * });
36
+ *
37
+ * const cardigantime = create({
38
+ * defaults: {
39
+ * configDirectory: './config',
40
+ * configFile: 'myapp.yaml',
41
+ * },
42
+ * configShape: MyConfigSchema.shape,
43
+ * });
44
+ * ```
45
+ */
4
46
  export declare const create: <T extends z.ZodRawShape>(pOptions: {
5
47
  defaults: Pick<DefaultOptions, "configDirectory"> & Partial<Omit<DefaultOptions, "configDirectory">>;
6
48
  features?: Feature[];
@@ -1,348 +1,53 @@
1
- 'use strict';
1
+ import { configure } from './configure.js';
2
+ import { DEFAULT_FEATURES, DEFAULT_LOGGER, DEFAULT_OPTIONS } from './constants.js';
3
+ import { read } from './read.js';
4
+ import { validate } from './validate.js';
5
+ export { ConfigSchema } from './types.js';
6
+ export { ArgumentError } from './error/ArgumentError.js';
7
+ export { ConfigurationError } from './error/ConfigurationError.js';
8
+ export { FileSystemError } from './error/FileSystemError.js';
2
9
 
3
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
-
5
- const yaml = require('js-yaml');
6
- const path = require('path');
7
- const fs = require('fs');
8
- const glob = require('glob');
9
- const crypto = require('crypto');
10
- const zod = require('zod');
11
-
12
- function _interopNamespaceDefault(e) {
13
- const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
14
- if (e) {
15
- for (const k in e) {
16
- if (k !== 'default') {
17
- const d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: () => e[k]
21
- });
22
- }
23
- }
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- const yaml__namespace = /*#__PURE__*/_interopNamespaceDefault(yaml);
30
- const fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
31
-
32
- const configure = async (command, options)=>{
33
- let retCommand = command;
34
- retCommand = retCommand.option('-c, --config-directory <configDirectory>', 'Config Directory', options.defaults.configDirectory);
35
- return retCommand;
36
- };
37
-
38
- const DEFAULT_ENCODING = 'utf8';
39
- const DEFAULT_CONFIG_FILE = 'config.yaml';
40
- const DEFAULT_OPTIONS = {
41
- configFile: DEFAULT_CONFIG_FILE,
42
- isRequired: false,
43
- encoding: DEFAULT_ENCODING
44
- };
45
- const DEFAULT_FEATURES = [
46
- 'config'
47
- ];
48
- const DEFAULT_LOGGER = {
49
- // eslint-disable-next-line no-console
50
- debug: console.debug,
51
- // eslint-disable-next-line no-console
52
- info: console.info,
53
- // eslint-disable-next-line no-console
54
- warn: console.warn,
55
- // eslint-disable-next-line no-console
56
- error: console.error,
57
- // eslint-disable-next-line no-console
58
- verbose: console.log,
59
- // eslint-disable-next-line no-console
60
- silly: console.log
61
- };
62
-
63
- // eslint-disable-next-line no-restricted-imports
64
- const create$1 = (params)=>{
65
- // eslint-disable-next-line no-console
66
- const log = params.log || console.log;
67
- const exists = async (path)=>{
68
- try {
69
- await fs__namespace.promises.stat(path);
70
- return true;
71
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
72
- } catch (error) {
73
- return false;
74
- }
75
- };
76
- const isDirectory = async (path)=>{
77
- const stats = await fs__namespace.promises.stat(path);
78
- if (!stats.isDirectory()) {
79
- log(`${path} is not a directory`);
80
- return false;
81
- }
82
- return true;
83
- };
84
- const isFile = async (path)=>{
85
- const stats = await fs__namespace.promises.stat(path);
86
- if (!stats.isFile()) {
87
- log(`${path} is not a file`);
88
- return false;
89
- }
90
- return true;
91
- };
92
- const isReadable = async (path)=>{
93
- try {
94
- await fs__namespace.promises.access(path, fs__namespace.constants.R_OK);
95
- } catch (error) {
96
- log(`${path} is not readable: %s %s`, error.message, error.stack);
97
- return false;
98
- }
99
- return true;
100
- };
101
- const isWritable = async (path)=>{
102
- try {
103
- await fs__namespace.promises.access(path, fs__namespace.constants.W_OK);
104
- } catch (error) {
105
- log(`${path} is not writable: %s %s`, error.message, error.stack);
106
- return false;
107
- }
108
- return true;
109
- };
110
- const isFileReadable = async (path)=>{
111
- return await exists(path) && await isFile(path) && await isReadable(path);
112
- };
113
- const isDirectoryWritable = async (path)=>{
114
- return await exists(path) && await isDirectory(path) && await isWritable(path);
115
- };
116
- const isDirectoryReadable = async (path)=>{
117
- return await exists(path) && await isDirectory(path) && await isReadable(path);
118
- };
119
- const createDirectory = async (path)=>{
120
- try {
121
- await fs__namespace.promises.mkdir(path, {
122
- recursive: true
123
- });
124
- } catch (mkdirError) {
125
- throw new Error(`Failed to create output directory ${path}: ${mkdirError.message} ${mkdirError.stack}`);
126
- }
127
- };
128
- const readFile = async (path, encoding)=>{
129
- return await fs__namespace.promises.readFile(path, {
130
- encoding: encoding
131
- });
132
- };
133
- const writeFile = async (path, data, encoding)=>{
134
- await fs__namespace.promises.writeFile(path, data, {
135
- encoding: encoding
136
- });
137
- };
138
- const forEachFileIn = async (directory, callback, options = {
139
- pattern: '*.*'
140
- })=>{
141
- try {
142
- const files = await glob.glob(options.pattern, {
143
- cwd: directory,
144
- nodir: true
145
- });
146
- for (const file of files){
147
- await callback(path.join(directory, file));
148
- }
149
- } catch (err) {
150
- throw new Error(`Failed to glob pattern ${options.pattern} in ${directory}: ${err.message}`);
151
- }
152
- };
153
- const readStream = async (path)=>{
154
- return fs__namespace.createReadStream(path);
155
- };
156
- const hashFile = async (path, length)=>{
157
- const file = await readFile(path, 'utf8');
158
- return crypto.createHash('sha256').update(file).digest('hex').slice(0, length);
159
- };
160
- const listFiles = async (directory)=>{
161
- return await fs__namespace.promises.readdir(directory);
162
- };
163
- return {
164
- exists,
165
- isDirectory,
166
- isFile,
167
- isReadable,
168
- isWritable,
169
- isFileReadable,
170
- isDirectoryWritable,
171
- isDirectoryReadable,
172
- createDirectory,
173
- readFile,
174
- readStream,
175
- writeFile,
176
- forEachFileIn,
177
- hashFile,
178
- listFiles
179
- };
180
- };
181
-
182
- function clean(obj) {
183
- return Object.fromEntries(Object.entries(obj).filter(([_, v])=>v !== undefined));
184
- }
185
- const read = async (args, options)=>{
186
- var _options_defaults;
187
- const logger = options.logger;
188
- const storage = create$1({
189
- log: logger.debug
190
- });
191
- const resolvedConfigDir = args.configDirectory || ((_options_defaults = options.defaults) === null || _options_defaults === void 0 ? void 0 : _options_defaults.configDirectory);
192
- logger.debug(`Resolved config directory: ${resolvedConfigDir}`);
193
- const configFile = path.join(resolvedConfigDir, options.defaults.configFile);
194
- logger.debug(`Attempting to load config file for cardigantime: ${configFile}`);
195
- let rawFileConfig = {};
196
- try {
197
- const yamlContent = await storage.readFile(configFile, options.defaults.encoding);
198
- const parsedYaml = yaml__namespace.load(yamlContent);
199
- if (parsedYaml !== null && typeof parsedYaml === 'object') {
200
- rawFileConfig = parsedYaml;
201
- logger.debug('Loaded Raw File Config for getValuesFromFile: \n\n%s\n\n', JSON.stringify(rawFileConfig, null, 2));
202
- } else if (parsedYaml !== null) {
203
- logger.warn(`Ignoring invalid configuration format in ${configFile} for cardigantime. Expected an object, got ${typeof parsedYaml}.`);
204
- }
205
- } catch (error) {
206
- if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {
207
- logger.debug(`Configuration file not found at ${configFile} for cardigantime. Returning empty object.`);
208
- } else {
209
- // Log error but don't throw, just return empty object as per the goal of just *getting* values
210
- logger.error(`Failed to load or parse configuration from ${configFile} for getValuesFromFile: ${error.message}`);
211
- }
212
- }
213
- const config = clean({
214
- ...rawFileConfig,
215
- ...{
216
- configDirectory: resolvedConfigDir
217
- }
218
- });
219
- return config;
220
- };
221
-
222
- // Base schema for core options
223
- const ConfigSchema = zod.z.object({
224
- configDirectory: zod.z.string()
225
- });
226
-
227
- const listZodKeys = (schema, prefix = '')=>{
228
- // Check if schema has unwrap method (which both ZodOptional and ZodNullable have)
229
- if (schema._def && (schema._def.typeName === 'ZodOptional' || schema._def.typeName === 'ZodNullable')) {
230
- // Use type assertion to handle the unwrap method
231
- const unwrappable = schema;
232
- return listZodKeys(unwrappable.unwrap(), prefix);
233
- }
234
- if (schema._def && schema._def.typeName === 'ZodArray') {
235
- // Use type assertion to handle the element property
236
- const arraySchema = schema;
237
- return listZodKeys(arraySchema.element, prefix);
238
- }
239
- if (schema._def && schema._def.typeName === 'ZodObject') {
240
- // Use type assertion to handle the shape property
241
- const objectSchema = schema;
242
- return Object.entries(objectSchema.shape).flatMap(([key, subschema])=>{
243
- const fullKey = prefix ? `${prefix}.${key}` : key;
244
- const nested = listZodKeys(subschema, fullKey);
245
- return nested.length ? nested : fullKey;
246
- });
247
- }
248
- return [];
249
- };
250
- const isPlainObject = (value)=>{
251
- // Check if it's an object, not null, and not an array.
252
- return value !== null && typeof value === 'object' && !Array.isArray(value);
253
- };
254
10
  /**
255
- * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.
256
- * Mimics the behavior of listZodKeys but operates on plain objects.
257
- * For arrays, it inspects the first element that is a plain object to determine nested keys.
258
- * If an array contains no plain objects, or is empty, the key for the array itself is listed.
259
- *
260
- * @param obj The object to introspect.
261
- * @param prefix Internal use for recursion: the prefix for the current nesting level.
262
- * @returns An array of strings representing all keys in dot notation.
263
- */ const listObjectKeys = (obj, prefix = '')=>{
264
- const keys = new Set(); // Use Set to automatically handle duplicates from array recursion
265
- for(const key in obj){
266
- // Ensure it's an own property, not from the prototype chain
267
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
268
- const value = obj[key];
269
- const fullKey = prefix ? `${prefix}.${key}` : key;
270
- if (Array.isArray(value)) {
271
- // Find the first element that is a plain object to determine structure
272
- const firstObjectElement = value.find(isPlainObject);
273
- if (firstObjectElement) {
274
- // Recurse into the structure of the first object element found
275
- const nestedKeys = listObjectKeys(firstObjectElement, fullKey);
276
- nestedKeys.forEach((k)=>keys.add(k));
277
- } else {
278
- // Array is empty or contains no plain objects, list the array key itself
279
- keys.add(fullKey);
280
- }
281
- } else if (isPlainObject(value)) {
282
- // Recurse into nested plain objects
283
- const nestedKeys = listObjectKeys(value, fullKey);
284
- nestedKeys.forEach((k)=>keys.add(k));
285
- } else {
286
- // It's a primitive, null, or other non-plain object/array type
287
- keys.add(fullKey);
288
- }
289
- }
290
- }
291
- return Array.from(keys); // Convert Set back to Array
292
- };
293
- const checkForExtraKeys = (mergedSources, fullSchema, logger)=>{
294
- const allowedKeys = new Set(listZodKeys(fullSchema));
295
- const actualKeys = listObjectKeys(mergedSources);
296
- const extraKeys = actualKeys.filter((key)=>!allowedKeys.has(key));
297
- if (extraKeys.length > 0) {
298
- const allowedKeysString = Array.from(allowedKeys).join(', ');
299
- const extraKeysString = extraKeys.join(', ');
300
- const errorMessage = `Unknown configuration keys found: ${extraKeysString}. Allowed keys are: ${allowedKeysString}`;
301
- logger.error(errorMessage);
302
- throw new Error(`Configuration validation failed: Unknown keys found (${extraKeysString}). Check logs for details.`);
303
- }
304
- };
305
- const validateConfigDirectory = async (configDirectory, isRequired)=>{
306
- // eslint-disable-next-line no-console
307
- const storage = create$1({
308
- log: console.log
309
- });
310
- const exists = await storage.exists(configDirectory);
311
- if (!exists) {
312
- if (isRequired) {
313
- throw new Error(`Config directory does not exist and is required: ${configDirectory}`);
314
- }
315
- } else if (exists) {
316
- const isReadable = await storage.isDirectoryReadable(configDirectory);
317
- if (!isReadable) {
318
- throw new Error(`Config directory exists but is not readable: ${configDirectory}`);
319
- }
320
- }
321
- };
322
- const validate = async (config, options)=>{
323
- const logger = options.logger;
324
- if (options.features.includes('config') && config.configDirectory) {
325
- await validateConfigDirectory(config.configDirectory, options.defaults.isRequired);
326
- }
327
- // Combine the base schema with the user-provided shape
328
- const fullSchema = zod.z.object({
329
- ...ConfigSchema.shape,
330
- ...options.configShape
331
- });
332
- logger.debug('Full Schema: \n\n%s\n\n', JSON.stringify(listZodKeys(fullSchema), null, 2));
333
- // Validate the merged sources against the full schema
334
- const validationResult = fullSchema.safeParse(config);
335
- // Check for extraneous keys
336
- checkForExtraKeys(config, fullSchema, logger);
337
- if (!validationResult.success) {
338
- logger.error('Configuration validation failed: %s', JSON.stringify(validationResult.error.format(), null, 2));
339
- throw new Error(`Configuration validation failed. Check logs for details.`);
340
- }
341
- return;
342
- };
343
-
344
- // Make create function generic
345
- const create = (pOptions)=>{
11
+ * Creates a new Cardigantime instance for configuration management.
12
+ *
13
+ * Cardigantime handles the complete configuration lifecycle including:
14
+ * - Reading configuration from YAML files
15
+ * - Validating configuration against Zod schemas
16
+ * - Merging CLI arguments with file configuration and defaults
17
+ * - Providing type-safe configuration objects
18
+ *
19
+ * @template T - The Zod schema shape type for your configuration
20
+ * @param pOptions - Configuration options for the Cardigantime instance
21
+ * @param pOptions.defaults - Default configuration settings
22
+ * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)
23
+ * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')
24
+ * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)
25
+ * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')
26
+ * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])
27
+ * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)
28
+ * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)
29
+ * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * import { create } from '@theunwalked/cardigantime';
34
+ * import { z } from 'zod';
35
+ *
36
+ * const MyConfigSchema = z.object({
37
+ * apiKey: z.string().min(1),
38
+ * timeout: z.number().default(5000),
39
+ * debug: z.boolean().default(false),
40
+ * });
41
+ *
42
+ * const cardigantime = create({
43
+ * defaults: {
44
+ * configDirectory: './config',
45
+ * configFile: 'myapp.yaml',
46
+ * },
47
+ * configShape: MyConfigSchema.shape,
48
+ * });
49
+ * ```
50
+ */ const create = (pOptions)=>{
346
51
  const defaults = {
347
52
  ...DEFAULT_OPTIONS,
348
53
  ...pOptions.defaults
@@ -368,6 +73,5 @@ const create = (pOptions)=>{
368
73
  };
369
74
  };
370
75
 
371
- exports.ConfigSchema = ConfigSchema;
372
- exports.create = create;
76
+ export { create };
373
77
  //# sourceMappingURL=cardigantime.js.map