[![npm-badge][npm-badge]][npm]
![types-badge][types-badge]

# app-config

> set values in global app configuration, e.g. for CLI

Features:

- store settings in global config file by appName
- writes and reads JSON files
- schema and schema-less mode
- schema validation with [valibot][]
- set defaults
- use different filename (other than default global one)

## Usage

```sh
npm install --save @commenthol/app-config
```

in your code (schemaless):

```js
import { AppConfig } from '@commenthol/app-config'

const conf = new AppConfig({ appName: 'example' })
// read the config, if file exists
await conf.read()

// set a value
conf.set('foo', 'bar')
// write the config to file, there is no automatic write
await conf.write()

// get value for key
console.log(conf.get('foo'))
//> 'bar

// set a nested value
conf.set('nested.key', 123)
console.log(conf.config)
//> { foo: 'bar', nested: { key: 123 } }
```

with defaults and schema validation:

```js
import * as v from 'valibot'
import { AppConfig, StringSchema } from '@commenthol/app-config'

// allow 'green' as well as '#00ff00'
const colorSchema = v.pipe(v.tuple([v.string(), v.hexColor()]))

const schema = {
  // shortcut see `./src/validate.js`
  foo: StringSchema,
  // custom schema
  direction: v.pipe(v.string(), v.pickList(['left', 'right'])),
  // nested keys (separated by '.')
  'color.ok': colorSchema,
  'color.fail': colorSchema
}

const defaults = {
  direction: 'left',
  // nested keys require separate object!
  color: {
    ok: 'green',
    fail: '#ff0000'
  }
}

const conf = new AppConfig({ appName: 'example', schema, defaults })
await conf.read()

conf.set('foo', 'bar')
conf.set('color.ok') // deletes key
conf.set('color.fail', 'magenta')

console.log(conf.config)
//> {
//>   foo: 'bar',
//>   color: {
//>     fail: 'magenta'
//>   }
//> }
```

Check `./example/cli.js` for an example.

## Contributing

Contributions are welcome! If you have any issues or suggestions, please open an
issue on GitLab.

## License

This project is licensed under the [MIT-0 License][LICENSE].

[LICENSE]: ./LICENSE
[npm-badge]: https://badgen.net/npm/v/@commenthol/app-config?color=green
[npm]: https://www.npmjs.com/package/@commenthol/app-config
[types-badge]: https://badgen.net/npm/types/@commenthol/app-config
[valibot]: https://valibot.dev/
