{"name":"vnopts","version":"1.0.1","description":"validate and normalize options","main":"lib/index.js","types":"lib/index.d.ts","repository":{"type":"git","url":"git+https://github.com/ikatyang/vnopts.git"},"homepage":"https://github.com/ikatyang/vnopts#readme","author":{"name":"Ika","email":"ikatyang@gmail.com","url":"https://github.com/ikatyang"},"license":"MIT","scripts":{"prepublish":"yarn run build","lint":"tslint -p ./tsconfig.json --type-check","test":"jest","prebuild":"rm -rf ./lib","build":"tsc -p ./tsconfig.build.json","release":"standard-version"},"dependencies":{"chalk":"^2.4.1","leven":"^2.1.0","tslib":"^1.9.3"},"devDependencies":{"@types/jest":"23.3.1","@types/leven":"2.1.1","@types/node":"6.0.116","has-ansi":"3.0.0","jest":"23.5.0","prettier":"1.14.2","prettier-config-ikatyang":"1.1.1","standard-version":"4.4.0","strip-ansi":"4.0.0","ts-jest":"23.1.4","tslint":"5.11.0","tslint-config-prettier":"1.15.0","tslint-plugin-prettier":"1.3.0","typescript":"3.0.1"},"engines":{"node":">= 6"},"gitHead":"f3a2a16fe554c65c26fb4b7a2016e56f8ddeb90a","bugs":{"url":"https://github.com/ikatyang/vnopts/issues"},"_id":"vnopts@1.0.1","_npmVersion":"6.1.0","_nodeVersion":"8.11.1","_npmUser":{"name":"ikatyang","email":"ikatyang@gmail.com"},"dist":{"integrity":"sha512-lbO99OqHWHeSt5vetKMTBRhyMMST/s6hP5Tk/otuP+uYggzhgy8OsJd/83ihID4vqdnC0OnV7pWVfwZHHDBZHg==","shasum":"bff2a7b741d778458befc6d8e5143da385d6c301","tarball":"http://registry-npm.ywwl.com/vnopts/download/vnopts-1.0.1.tgz","fileCount":52,"unpackedSize":51056,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbhkM8CRA9TVsSAnZWagAABbEQAJWzZxGhs2mF6IRFxfIA\nuy2ObptmFTlvGSte8iqPqSNG0sAHxbjlLZZ7xTgpH/nOczwl5z51ipVtFcnv\n43rmmeB1gGIK3IegoSIraqA1ZvB/mg31Oarr/VvY4dDfTOF6clEZGR9lA1jV\nh9pvqV5ywwGYMiPveoViludFwvfmTezFaoQ4yqNoL5qu1MVXWfRA4lWui66Z\nbS0gPoD73SR+gAwPZm6C5GUZzLZ9KxDm0UyWAhh5hzW0TGpVm/1+6zWR6wfe\nNy8cyedGgtRJ4LJyheTqLbqW+QUyDkGSTMpX4V9Cyw8lksyzbsT05H1E+lTQ\n9zIInurMNCULH9GIpuOLXT7LJCrvWFm0IxfUkEJWtF6WzZEl+zbZAaKbPTGC\nMt1R47Hoi7vZu8zSdIxUqVv1CezxG5JB34z+UlNGTKT7/onzipyIdQncB/ZI\nqZyIBESvgAX7AEeJ9nq0uzMX2c5eHb0MxgERTra4ALR5RodumZejHZl+hZot\nJxWyjee5AaVsVkJaDr1j2s/Tf8Wk7F+9ypieEhXRjt2m6SqN6qzyDklJeCo+\na7I/Spdi+4tGgv2vJCnG1fKkauHsgNyFArKUB1Tsf3ZOB1JkurnkN3o2ISjp\nbFW0tPIe7soqi0Can9aPBd9YQB0LWx/rzWswAIPcq9feM89aDny8hYce94TM\nDmej\r\n=Hy51\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICkB/rCl9CWOT/zfFY7upB185GHORNnaW0I6atRBjgCDAiBYg+OxJW7b8ZlH1YiPUDE6Bc5VhnJoRsdBsjbbg3yFVQ=="}],"size":12559,"noattachment":false,"key":"/vnopts/-/vnopts-1.0.1.tgz"},"maintainers":[{"name":"ikatyang","email":"ikatyang@gmail.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/vnopts_1.0.1_1535525692022_0.26066187986050626"},"_hasShrinkwrap":false,"readme":"# vnopts\n\n[![npm](https://img.shields.io/npm/v/vnopts.svg)](https://www.npmjs.com/package/vnopts)\n[![build](https://img.shields.io/github/actions/workflow/status/ikatyang/vnopts/test.yml)](https://github.com/ikatyang/vnopts/actions?query=branch%3Amaster)\n\nvalidate and normalize options\n\n[Changelog](https://github.com/ikatyang/vnopts/blob/master/CHANGELOG.md)\n\n## Install\n\n```sh\nnpm install vnopts\n```\n\n## Usage\n\n```js\nimport * as vnopts from 'vnopts'\n\nconst schemas = [\n  vnopts.ChoiceSchema.create({\n    name: 'parser',\n    choices: ['babylon', 'flow', 'typescript'],\n  }),\n  vnopts.BooleanSchema.create({\n    name: 'useFlowParser',\n    deprecated: true,\n    redirect: value =>\n      !value ? undefined : { to: { key: 'parser', value: 'flow' } },\n  }),\n]\n\nvnopts.normalize({ useFlowParser: true }, schemas)\n//=> { parser: \"flow\" }\n// warning: `useFlowParser` is deprecated, we now treat it as `{ parser: \"flow\" }`.\n\nvnopts.normalize({ parser: 'none' }, schemas)\n//=> error: Invalid `parser` value. Expected `\"babylon\", \"flow\" or \"typescript\"`, but received `\"none\"`.\n\nvnopts.normalize({ parserr: 'typescript' }, schemas)\n//=> {}\n// warning: Ignored unknown option `{ parserr: \"typescript\" }`. Did you mean `parser`?\n```\n\n## API\n\n### Normalizer\n\n```ts\n/** a shortcut for `new Normalizer(...).normalize(...)` */\nfunction normalize(\n  options: object,\n  schemas: Schema[],\n  opts?: NormalizerOptions,\n): object\n```\n\n```ts\nclass Normalizer {\n  constructor(schemas: Schema[], opts?: NormalizerOptions)\n  /** normalize the options based on schemas */\n  normalize(options: object): object\n  /** clear the deprecation warning history so as to show the same warning again */\n  cleanHistory(): void\n}\n```\n\n```ts\ninterface NormalizerOptions {\n  logger?: Logger | false\n  loggerPrintWidth?: number\n  descriptor?: Descriptor\n  unknown?: UnknownHandler\n  invalid?: InvalidHandler\n  deprecated?: DeprecatedHandler\n  missing?: IdentifyMissing\n  required?: IdentifyRequired\n  preprocess?: (options: Options, utils: Utils) => Options\n  postprocess?: (\n    options: Options,\n    utils: Utils,\n  ) => typeof VALUE_UNCHANGED | { delete?: string[]; override?: Options }\n}\n```\n\n#### Logger\n\nDefaults to `console`.\n\n```ts\ninterface Logger {\n  warn(message: string): void\n}\n```\n\n#### Descriptor\n\nDefaults to [`apiDescriptor`](https://github.com/ikatyang/vnopts/blob/master/src/descriptors/api.ts).\n\n```ts\ninterface Descriptor {\n  key: (key: string) => string\n  value: (value: any) => string\n  pair: (pair: { key: string; value: any }) => string\n}\n```\n\n#### UnknownHandler\n\nDefaults to [`levenUnknownHandler`](https://github.com/ikatyang/vnopts/blob/master/src/handlers/unknown/leven.ts).\n\n```ts\ntype UnknownHandler = (key: string, value: any, utils: Utils) => void | object\n```\n\nThe returned object will be merged into the output object (and validate its value if the key is known).\n\n#### InvalidHandler\n\nDefaults to [`commonInvalidHandler`](https://github.com/ikatyang/vnopts/blob/master/src/handlers/invalid/common.ts).\n\n```ts\ntype InvalidHandler = (\n  key: string,\n  value: OptionValue,\n  utils: Utils,\n) => string | Error\n```\n\nReturns an error message or the error itself.\n\n#### DeprecatedHandler\n\nDefaults to [`commonDeprecatedHandler`](https://github.com/ikatyang/vnopts/blob/master/src/handlers/deprecated/common.ts).\n\n```ts\ntype DeprecatedHandler = (\n  keyOrPair: string | { key: string; value: any },\n  redirectToKeyOrPair: undefined | string | { key: string; value: any },\n  utils: Utils,\n) => string\n```\n\nReturns a deprecation warning.\n\n#### IdentifyMissing\n\nDefaults to `() => false`.\n\n```ts\ntype IdentifyMissing = (key: string, options: Options) => boolean\n```\n\nReturns a boolean to indicate if `key` is _missing_ in `options`.\n(`!(key in options)` is always considered missing.)\n\n#### IdentifyRequired\n\nDefaults to `() => false`.\n\n```ts\ntype IdentifyRequired = (key: string) => boolean\n```\n\nReturns a boolean to indicate if `key` is required in the output.\n\n### Schemas\n\n#### AnySchema\n\n```ts\ninterface AnySchemaParameters extends SchemaHandlers {\n  name: string\n}\n```\n\n```js\nconst schemas = [vnopts.AnySchema.create({ name: 'any' })]\n\nvnopts.normalize({ any: 'hello world' }, schemas)\n//=> { any: \"hello world\" }\n\nvnopts.normalize({ unknown: 'hello world' }, schemas)\n//=> {}\n// warning: Ignored unknown option `{ unknown: \"hello world\" }`.\n```\n\n#### BooleanSchema\n\n```ts\ninterface BooleanSchemaParameters extends SchemaHandlers {\n  name: string\n}\n```\n\n```js\nconst schemas = [vnopts.BooleanSchema.create({ name: 'bool' })]\n\nvnopts.normalize({ bool: true }, schemas)\n//=> { bool: true }\n\nvnopts.normalize({ bool: 'hello world' }, schemas)\n// error: Invalid `bool` value. Expected `true or false`, but received `\"hello world\"`.\n```\n\n#### NumberSchema\n\n```ts\ninterface NumberSchemaParameters extends SchemaHandlers {\n  name: string\n}\n```\n\n```js\nconst schemas = [vnopts.NumberSchema.create({ name: 'num' })]\n\nvnopts.normalize({ num: 1 }, schemas)\n//=> { num: 1 }\n\nvnopts.normalize({ num: null }, schemas)\n// error: Invalid `num` value. Expected `a number`, but received `null`.\n```\n\n#### IntegerSchema\n\n```ts\ninterface IntegerSchemaParameters extends SchemaHandlers {\n  name: string\n}\n```\n\n```js\nconst schemas = [vnopts.IntegerSchema.create({ name: 'int' })]\n\nvnopts.normalize({ int: 1 }, schemas)\n//=> { int: 1 }\n\nvnopts.normalize({ int: 1.5 }, schemas)\n// error: Invalid `int` value. Expected `an integer`, but received `1.5`.\n```\n\n#### StringSchema\n\n```ts\ninterface StringSchemaParameters extends SchemaHandlers {\n  name: string\n}\n```\n\n```js\nconst schemas = [vnopts.StringSchema.create({ name: 'str' })]\n\nvnopts.normalize({ str: 'hi' }, schemas)\n//=> { str: \"hi\" }\n\nvnopts.normalize({ str: true }, schemas)\n// error: Invalid `str` value. Expected `a string`, but received `true`.\n```\n\n#### ChoiceSchema\n\n```ts\ninterface ChoiceSchemaParameters extends SchemaHandlers {\n  name: string\n  choices: Array<\n    | undefined\n    | null\n    | boolean\n    | number\n    | string\n    | {\n        value: undefined | null | boolean | number | string\n        deprecated?: boolean\n        hidden?: boolean // do not show this value in `expected`\n        redirect?: /* key */ string | { key: string; value: any }\n        forward?: /* key */ string | { key: string; value: any }\n      }\n  >\n}\n```\n\n```js\nconst schemas = [\n  vnopts.ChoiceSchema.create({ name: 'choice', choices: [2, false, 'hey'] }),\n]\n\nvnopts.normalize({ choice: 2 }, schemas)\n//=> { choice: 2 }\n\nvnopts.normalize({ choice: true }, schemas)\n// error: Invalid `choice` value. Expected `false, 2 or \"hey\"`, but received `true`.\n```\n\n#### AliasSchema\n\n`AliasSchema` validates values using the validator from the source schema and redirects all the value to the source key.\n\n```ts\ninterface AliasSchemaParameters extends SchemaHandlers {\n  name: string\n  /** the name of the source schema */\n  sourceName: string\n}\n```\n\n```js\nconst schemas = [\n  vnopts.BooleanSchema.create({ name: 'source' }),\n  vnopts.AliasSchema.create({ name: 'alias', sourceName: 'source' }),\n]\n\nvnopts.normalize({ alias: true }, schemas)\n//=> { source: true }\n\nvnopts.normalize({ alias: 'invalid' }, schemas)\n//=> error: Invalid `alias` value. Expected `true or false`, but received `\"invalid\"`.\n```\n\n#### ArraySchema\n\n`AliasSchema` validates values using the validator from the source schema and redirects all the value to the source key.\n\n```ts\ninterface ArraySchemaParameters extends SchemaHandlers {\n  /** defaults to valueSchema's name */\n  name?: string\n  valueSchema: Schema\n}\n```\n\n```js\nconst schemas = [\n  vnopts.ArraySchema.create({\n    valueSchema: vnopts.ChoiceSchema.create({\n      name: 'choices',\n      choices: [1, true, 'foo'],\n    }),\n  }),\n]\n\nvnopts.normalize({ choices: [1, 'foo'] }, schemas)\n//=> { choices: [1, \"foo\"] }\n\nvnopts.normalize({ choices: 1 }, schemas)\n//=> error: Invalid `choices` value. Expected `an array of true, 1 or \"foo\"`, but received `1`.\n```\n\n### Handlers\n\nEvery schema has its own handlers but you can still override/extend them.\n\n```ts\ninterface SchemaHandlers {\n  default?: SchemaDefaultHandler\n  expected?: SchemaExpectedHandler\n  validate?: SchemaValidateHandler\n  deprecated?: SchemaDeprecateHandler\n  forward?: SchemaForwardHandler\n  redirect?: SchemaRedirectHandler\n  overlap?: SchemaOverlapHandler\n  preprocess?: SchemaPreprocessHandler\n  postprocess?: SchemaPostprocessHandler\n}\n```\n\n#### default\n\n```ts\ntype SchemaDefaultHandler =\n  | DefaultResult\n  | ((schema: Schema, utils: Utils) => DefaultResult)\n\ntype DefaultResult = undefined | { value?: any }\n```\n\n`undefined` represents no default value,\ndefault values are wrapped in an object's `value` field\nto avoid the ambiguity between missing and `undefined`.\n\n#### expected\n\n```ts\ntype SchemaExpectedHandler =\n  | ExpectedResult\n  | ((schema: Schema, utils: Utils) => ExpectedResult)\n\ntype ExpectedResult =\n  | string\n  | { text: string }\n  | {\n      text?: string\n      list: {\n        title: string\n        values: ExpectedResult[]\n      }\n    }\n```\n\nReturns the description for the expected value in the form of text and/or list.\nFor example the following `ExpectedResult`:\n\n```json\n{\n  \"list\": {\n    \"title\": \"one of the following values\",\n    \"values\": [\"foo\", \"bar\", \"baz\"]\n  }\n}\n```\n\nwill produce the following message in `commonInvalidHandler`:\n\n```\nInvalid `<key>` value. Expected `one of the following values`, but received `<value>`.\n- `\"foo\"`\n- `\"bar\"`\n- `\"baz\"`\n```\n\nIf both `text` and `list` are returned,\n`text` will be chosen if its width is the minimum one or its width is less than `loggerPrintWidth`,\notherwise `list`.\n\n#### validate\n\n```ts\ntype SchemaValidateHandler =\n  | ValidateResult\n  | ((value: unknown, schema: Schema, utils: Utils) => ValidateResult)\n\ntype ValidateResult = boolean | { value: unknown }\n```\n\nReturns a boolean represents if the entire value is valid,\nor put the invalid value in an object's `value` field if only part of the value is invalid,\nthis is useful for collection schema like `ArraySchema`.\n\n#### deprecated\n\n```ts\ntype SchemaDeprecatedHandler =\n  | DeprecatedResult\n  | ((value: unknown, schema: Schema, utils: Utils) => DeprecatedResult)\n\ntype DeprecatedResult = boolean | { value: any } | Array<{ value: any }>\n```\n\nReturns `true` if the entire key is deprecated, `false` if it's not deprecated,\nor (an array of) an object with `value` field if only part of the value is deprecated,\none object corresponds to one deprecation warning.\n\n#### forward\n\n```ts\ntype SchemaForwardHandler =\n  | ForwardResult\n  | ((value: any, schema: Schema, utils: Utils) => ForwardResult)\n\ntype TransferTo = /* key */ string | { key: string; value: any }\ntype TransferResult = TransferTo | { from?: /* value */ any; to: TransferTo }\ntype ForwardResult = undefined | TransferResult | Array<TransferResult>\n```\n\nReturns a key or a key-value pair if the entire value needs to be forwarded there,\nor (an array of) an object with `from`/`to` field if only part of the value needs to be forwarded.\n\n#### redirect\n\n```ts\ntype SchemaRedirectHandler =\n  | RedirectResult\n  | ((value: any, schema: Schema, utils: Utils) => RedirectResult)\n\ntype RedirectResult =\n  | ForwardResult\n  | {\n      remain?: any\n      redirect: ForwardResult\n    }\n```\n\nSimilar to `forward` but returns an object with `remain`/`redirect` field if not the entire value needs to be redirected.\n\n#### overlap\n\n```ts\ntype SchemaOverlapHandler = (\n  currentValue: any,\n  newValue: any,\n  schema: Schema,\n  utils: Utils,\n) => any\n```\n\nDescribes what should the normalizer do if there're multiple values assigned to the same key.\n\n#### preprocess\n\n```ts\ntype SchemaPreprocessHandler = (\n  value: unknown,\n  schema: Schema,\n  utils: Utils,\n) => unknown\n```\n\nThe preprocess before passing into the validator.\n\n#### postprocess\n\n```ts\ntype SchemaPostprocessHandler = (\n  value: unknown,\n  schema: Schema,\n  utils: Utils,\n) => unknown\n```\n\nThe postprocess after normalization.\n\n## Development\n\n```sh\n# lint\npnpm run lint\n\n# build\npnpm run build\n\n# test\npnpm run test\n```\n\n## License\n\nMIT © [Ika](https://github.com/ikatyang)\n","publish_time":1535525692158,"_cnpm_publish_time":1535525692158,"dist-tags":{"latest":"2.0.5"}}