{"name":"ow","version":"3.0.0","keywords":["type","types","check","checking","guard","guards","assert","assertion","predicate","predicates","is","validate","validation","utility","util","typeof","instanceof","object"],"author":{"url":"https://sindresorhus.com","name":"Sindre Sorhus","email":"sindresorhus@gmail.com"},"license":"MIT","_id":"ow@3.0.0","maintainers":[{"name":"sindresorhus","email":"sindresorhus@gmail.com"}],"homepage":"https://github.com/sindresorhus/ow#readme","bugs":{"url":"https://github.com/sindresorhus/ow/issues"},"c8":{"reporter":["text","lcov"]},"xo":{"rules":{"no-useless-return":"off","@typescript-eslint/ban-types":"off","@typescript-eslint/no-explicit-any":"off","@typescript-eslint/no-unsafe-return":"off","@typescript-eslint/no-empty-function":"off","@typescript-eslint/no-unsafe-argument":"off","@typescript-eslint/explicit-function-return-type":"error","@typescript-eslint/restrict-template-expressions":"off"},"ignores":["example.js","dev-only.js","source/utils/infer-label.browser.ts"]},"ava":{"files":["test/**","!test/fixtures/**"],"extensions":{"ts":"module"},"workerThreads":false},"dist":{"shasum":"0767166d585f0705501e528cbfddb226f640d85e","tarball":"http://registry-npm.ywwl.com/ow/download/ow-3.0.0.tgz","fileCount":72,"integrity":"sha512-Hud8xDH/tbY0iAdiGry4ZtaTloALVVdykLhuKgztOjYI+YRdB3NB8eqsCSn91r7oj1pZ+MZFLYB88sDhW0Od4Q==","signatures":[{"sig":"MEUCICCCO8jSzaS9BG3niOyFMrV+BFGl7qqoIvbqi+SZ0EP8AiEAy+Xcfv8ABCLd/U0rsx1xwopWpWw9Obcmr2uQGxKMeSA=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":130060,"size":25878,"noattachment":false,"key":"/ow/-/ow-3.0.0.tgz"},"type":"module","browser":{"./dist/utils/infer-label.js":"./dist/utils/infer-label.browser.js"},"engines":{"node":">=20"},"exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./dev-only":{"types":"./dist/index.d.ts","default":"./dev-only.js"}},"funding":"https://github.com/sponsors/sindresorhus","gitHead":"4b0a9efdb843f79ea5fd5c2167c855482acb46a2","scripts":{"docs":"typedoc source/index.ts","test":"xo && NODE_OPTIONS='--import=tsx/esm' c8 ava","build":"del-cli dist && tsc","example":"npm run build && node example.js","prepare":"npm run build","postpublish":"npm run docs && gh-pages --dist docs --no-history --message \"Deploy documentation\""},"_npmUser":{"name":"sindresorhus","email":"sindresorhus@gmail.com"},"repository":{"url":"git+https://github.com/sindresorhus/ow.git","type":"git"},"_npmVersion":"10.9.2","description":"Function argument validation for humans","directories":{},"sideEffects":false,"_nodeVersion":"20.19.1","dependencies":{"dot-prop":"^8.0.2","callsites":"^4.1.0","environment":"^1.0.0","fast-equals":"^5.0.1","is-identifier":"^1.0.0","@sindresorhus/is":"^6.3.0"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^9.1.0","xo":"^0.58.0","ava":"^6.1.2","tsx":"^4.9.1","del-cli":"^5.1.0","typedoc":"^0.25.13","gh-pages":"^6.1.1","typescript":"^5.4.5","@types/node":"^20.12.8","expect-type":"^0.19.0","@sindresorhus/tsconfig":"^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ow_3.0.0_1757456908227_0.8085933577518878","host":"s3://npm-registry-packages-npm-production"},"readme":"<p align=\"center\">\n\t<img src=\"media/logo.png\" width=\"300\">\n\t<br>\n\t<br>\n</p>\n\n[![Coverage Status](https://codecov.io/gh/sindresorhus/ow/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/ow)\n\n> Function argument validation for humans\n\n## Why use Ow?\n\nTypeScript only validates types at compile time. Once compiled, your program can still receive unexpected data at runtime from:\n\n- Function arguments receiving untrusted input\n- CLI arguments and flags\n- Environment variables and configuration files\n\nFor complex schema validation (API responses, database queries, JSON parsing), use [`zod`](https://github.com/colinhacks/zod) instead.\n\nOw provides runtime validation that:\n\n- **Catches errors early** - Fail fast with descriptive error messages instead of cryptic runtime errors\n- **Documents expectations** - Make your code self-documenting by explicitly stating what you expect\n- **Simplifies debugging** - Spend less time tracking down type-related bugs in production\n- **Works anywhere** - Use the same validation on the server, in the browser, or in CLI tools\n- **Provides type guards** - Narrow TypeScript types for safer code after validation\n\n## Highlights\n\n- Expressive chainable API\n- Lots of built-in validations\n- Supports custom validations\n- Automatic label inference in Node.js\n- Written in TypeScript\n\n## Install\n\n```sh\nnpm install ow\n```\n\n## Usage\n\n```ts\nimport ow from 'ow';\n\nconst unicorn = input => {\n\tow(input, ow.string.minLength(5));\n\n\t// …\n};\n\nunicorn(3);\n//=> ArgumentError: Expected `input` to be of type `string` but received type `number`\n\nunicorn('yo');\n//=> ArgumentError: Expected string `input` to have a minimum length of `5`, got `yo`\n```\n\n## Practical Examples\n\n### Function Arguments\n\n```ts\nimport ow from 'ow';\n\nconst resize = (width: unknown, height: unknown) => {\n\tow(width, 'width', ow.number.positive.integer);\n\tow(height, 'height', ow.number.positive.integer);\n\t\n\t// Process the image...\n};\n\nresize(640, 480); // ✓\nresize(-100, 200); // ✗ ArgumentError: Expected `width` to be a positive number\nresize(640, \"480\"); // ✗ ArgumentError: Expected `height` to be of type `number`\n```\n\n### Configuration Validation\n\n```ts\nimport ow from 'ow';\n\nconst config = {\n\tport: process.env.PORT,\n\tapiKey: process.env.API_KEY,\n\tnodeEnv: process.env.NODE_ENV\n};\n\n// Validate configuration at startup\now(config.port, ow.string.numeric);\now(config.apiKey, ow.string.minLength(32));\now(config.nodeEnv, ow.string.oneOf(['development', 'production', 'test']));\n\n// Your app won't start with invalid configuration\nconst port = parseInt(config.port, 10);\n```\n\n### Constructor Validation\n\n```ts\nimport ow from 'ow';\n\nclass User {\n\tconstructor(name: string, email: string, age?: number) {\n\t\tow(name, ow.string.nonEmpty);\n\t\tow(email, ow.string.email);\n\t\tow(age, ow.optional.number.integer.positive.lessThanOrEqual(120));\n\t\t\n\t\tthis.name = name;\n\t\tthis.email = email;\n\t\tthis.age = age;\n\t}\n}\n\nnew User('Jane', 'jane@example.com', 25); // ✓\nnew User('', 'jane@example.com'); // ✗ ArgumentError: Expected string to not be empty\n```\n\n### Utility Functions\n\n```ts\nimport ow from 'ow';\n\nconst delay = (milliseconds: unknown) => {\n\tow(milliseconds, ow.number.positive.integer);\n\treturn new Promise(resolve => setTimeout(resolve, milliseconds));\n};\n\nconst getRandomInteger = (min: number, max: number) => {\n\tow(min, ow.number.integer);\n\tow(max, ow.number.integer.greaterThanOrEqual(min));\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};\n```\n\n### CLI Arguments\n\n```ts\nimport ow from 'ow';\n\nconst cli = (arguments_: string[]) => {\n\tconst [command, ...options] = arguments_;\n\t\n\tow(command, ow.string.oneOf(['build', 'test', 'deploy']));\n\t\n\tif (command === 'deploy') {\n\t\tconst [environment] = options;\n\t\tow(environment, ow.string.oneOf(['staging', 'production']));\n\t}\n\t\n\t// Proceed with validated command\n};\n```\n\n> [!NOTE]\n> If you intend on using `ow` for development purposes only, use `import ow from 'ow/dev-only'` instead of the usual `import ow from 'ow'`, and run the bundler with `NODE_ENV` set to `production` (e.g. `$ NODE_ENV=\"production\" parcel build index.js`). This will make `ow` automatically export a shim when running in production, which should result in a significantly lower bundle size.\n\n## API\n\n[Complete API documentation](https://sindresorhus.com/ow/)\n\nOw includes TypeScript type guards, so using it will narrow the type of previously-unknown values.\n\n```ts\nfunction (input: unknown) {\n\tinput.slice(0, 3) // Error, Property 'slice' does not exist on type 'unknown'\n\n\tow(input, ow.string)\n\n\tinput.slice(0, 3) // OK\n}\n```\n\n### ow(value, predicate)\n\nTest if `value` matches the provided `predicate`. Throws an `ArgumentError` if the test fails.\n\n### ow(value, label, predicate)\n\nTest if `value` matches the provided `predicate`. Throws an `ArgumentError` with the specified `label` if the test fails.\n\nThe `label` is automatically inferred in Node.js but you can override it by passing in a value for `label`. The automatic label inference doesn't work in the browser.\n\n### ow.isValid(value, predicate)\n\nReturns `true` if the value matches the predicate, otherwise returns `false`.\n\n### ow.validate(value, predicate)\n\nValidate a value against a predicate without throwing. Returns a result object with type narrowing.\n\n```ts\nimport ow, {type ValidateResult} from 'ow';\n\nconst result = ow.validate(value, ow.string);\n\nif (!result.success) {\n\tconsole.error(result.error.message);\n\treturn;\n}\n\n// result.value is now typed as string\nconsole.log(result.value.length);\n```\n\nThe return type is a discriminated union:\n\n```ts\ntype ValidateResult<T> =\n\t| {success: true; value: T}\n\t| {success: false; error: ArgumentError};\n```\n\nThis allows TypeScript to narrow the type based on the `success` property. When `success` is `true`, you can access `value`. When `success` is `false`, you can access `error`.\n\n### ow.validate(value, label, predicate)\n\nValidate a value against a predicate with a custom label without throwing.\n\n```ts\nconst result = ow.validate(username, 'username', ow.string.minLength(3));\n\nif (!result.success) {\n\tconsole.error(result.error.message);\n\t//=> Expected string `username` to have a minimum length of `3`, got `ab`\n}\n```\n\n### ow.isPredicate(value)\n\nTest if the provided value is an Ow predicate.\n\nUseful for building higher-order functions that need to distinguish between predicates and other values.\n\n### ow.create(predicate)\n\nCreate a reusable validator.\n\n```ts\nconst checkPassword = ow.create(ow.string.minLength(6));\n\nconst password = 'foo';\n\ncheckPassword(password);\n//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`\n```\n\n### ow.create(label, predicate)\n\nCreate a reusable validator with a specific `label`.\n\n```ts\nconst checkPassword = ow.create('password', ow.string.minLength(6));\n\ncheckPassword('foo');\n//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`\n```\n\n### ow.any(...predicate[])\n\nReturns a predicate that verifies if the value matches at least one of the given predicates.\n\n```ts\now('foo', ow.any(ow.string.maxLength(3), ow.number));\n```\n\n### ow.optional.{type}\n\nMakes the predicate optional. An optional predicate means that it doesn't fail if the value is `undefined`.\n\n```ts\now(1, ow.optional.number);\n\now(undefined, ow.optional.number);\n```\n\n### ow.nullable.{type}\n\nMakes the predicate nullable. A nullable predicate means that it doesn't fail if the value is `null`.\n\n```ts\now(1, ow.nullable.number);\n\now(null, ow.nullable.number);\n```\n\nThis is useful for validating inputs from external sources (like GraphQL APIs) that use `null` to represent absent values. We encourage using `undefined` over `null` in your own APIs, but recognize you can't control what external APIs return. [See our recommendation against using `null`](https://github.com/sindresorhus/meta/issues/7).\n\n### ow.absent.{type}\n\nMarks properties in object shapes as absent, meaning the key can be completely missing from the object. This is different from `optional` which allows both missing keys AND `undefined` values.\n\n```ts\ntype Hotdog = {\n\tlength: number;\n\ttopping: string;\n};\n\nfunction patchHotdog(hotdog: Hotdog, patchBody: unknown): Hotdog {\n\tow(\n\t\tpatchBody,\n\t\tow.object.exactShape({\n\t\t\tlength: ow.absent.number,\n\t\t\ttopping: ow.absent.string,\n\t\t}),\n\t);\n\n\treturn {\n\t\t...hotdog,\n\t\t...patchBody, // Type-safe object spreading\n\t};\n}\n\nconst dog = {length: 10, topping: 'mustard'};\n\npatchHotdog(dog, {length: 12}); // ✓ Partial update\npatchHotdog(dog, {}); // ✓ Empty update\npatchHotdog(dog, {length: 12, topping: 'ketchup'}); // ✓ Full update\npatchHotdog(dog, {length: 'twelve'}); // ✗ Wrong type\n```\n\nThis is particularly useful for:\n- Patch/update operations where missing keys mean \"don't change\"\n- Partial form submissions\n- Configuration merging where only specified keys should be overridden\n\n**Key differences from `optional`:**\n\nAt runtime, both modifiers allow missing keys. The difference is in how they handle undefined values and type inference:\n\n```ts\n// optional: allows missing keys AND undefined values\n// Type inference: { name: string | undefined }\now({}, ow.object.exactShape({\n\tname: ow.optional.string // ✓ Valid - missing key\n}));\now({name: undefined}, ow.object.exactShape({\n\tname: ow.optional.string // ✓ Valid - undefined value\n}));\n\n// absent: allows missing keys but NOT undefined values\n// Type inference: { name?: string }\now({}, ow.object.exactShape({\n\tname: ow.absent.string // ✓ Valid - missing key\n}));\now({name: undefined}, ow.object.exactShape({\n\tname: ow.absent.string // ✗ Invalid - undefined not allowed\n}));\n```\n\nThe key distinction: use `.absent` when missing keys mean \"don't change\" (patch operations), and `.optional` when undefined is a valid value.\n\n### ow.{type}\n\nAll the below types return a predicate. Every predicate has some extra operators that you can use to test the value even more fine-grained.\n\n[Predicate docs.](https://sindresorhus.com/ow/types/Predicates.html)\n\n#### Primitives\n\n- `undefined`\n- `null`\n- `string`\n- `number`\n- `boolean`\n- `symbol`\n\n#### Built-in types\n\n- `array`\n- `function`\n- `object`\n- `regExp`\n- `date`\n- `error`\n- `promise`\n- `map`\n- `set`\n- `weakMap`\n- `weakSet`\n\n#### Typed arrays\n\n- `int8Array`\n- `uint8Array`\n- `uint8ClampedArray`\n- `int16Array`\n- `uint16Array`\n- `int32Array`\n- `uint32Array`\n- `float32Array`\n- `float64Array`\n\n#### Structured data\n\n- `arrayBuffer`\n- `dataView`\n- `sharedArrayBuffer`\n\n#### Miscellaneous\n\n- `nan`\n- `nullOrUndefined`\n- `iterable`\n- `typedArray`\n\n### Predicates\n\nThe following predicates are available on every type.\n\n#### not\n\nInverts the following predicate.\n\n```ts\now(1, ow.number.not.infinite);\n\now('', ow.string.not.empty);\n//=> ArgumentError: Expected string to not be empty, got ``\n```\n\n#### is(fn)\n\nUse a custom validation function. Return `true` if the value matches the validation, return `false` if it doesn't.\n\n```ts\now(1, ow.number.is(x => x < 10));\n\now(1, ow.number.is(x => x > 10));\n//=> ArgumentError: Expected `1` to pass custom validation function\n```\n\nInstead of returning `false`, you can also return a custom error message which results in a failure.\n\n```ts\nconst greaterThan = (max: number, x: number) => {\n\treturn x > max || `Expected \\`${x}\\` to be greater than \\`${max}\\``;\n};\n\now(5, ow.number.is(x => greaterThan(10, x)));\n//=> ArgumentError: Expected `5` to be greater than `10`\n```\n\n#### validate(fn)\n\nUse a custom validation object. The difference with `is` is that the function should return a validation object, which allows more flexibility.\n\n```ts\now(1, ow.number.validate(value => ({\n\tvalidator: value > 10,\n\tmessage: `Expected value to be greater than 10, got ${value}`\n})));\n//=> ArgumentError: (number) Expected value to be greater than 10, got 1\n```\n\nYou can also pass in a function as `message` value which accepts the label as argument.\n\n```ts\now(1, 'input', ow.number.validate(value => ({\n\tvalidator: value > 10,\n\tmessage: label => `Expected ${label} to be greater than 10, got ${value}`\n})));\n//=> ArgumentError: Expected number `input` to be greater than 10, got 1\n```\n\n#### custom(fn)\n\nUse a custom validation function that throws an error when the validation fails. This is useful for reusing existing validators or composing complex validations.\n\n```ts\nimport ow from 'ow';\n\ninterface User {\n\tname: string;\n\tage: number;\n}\n\nconst validateUser = (user: User) => {\n\tow(user.name, 'User.name', ow.string.nonEmpty);\n\tow(user.age, 'User.age', ow.number.integer.positive);\n};\n\now([{name: 'Alice', age: 30}], ow.array.ofType(ow.object.custom(validateUser)));\n```\n\nThis is particularly useful when you have existing validation functions and want to compose them:\n\n```ts\nimport ow from 'ow';\n\ninterface Animal {\n\ttype: string;\n\tweight: number;\n}\n\nconst validateAnimal = (animal: Animal) => {\n\tow(animal.type, 'Animal.type', ow.string.oneOf(['dog', 'cat', 'elephant']));\n\tow(animal.weight, 'Animal.weight', ow.number.finite.positive);\n};\n\nconst animals: Animal[] = [\n\t{type: 'dog', weight: 5},\n\t{type: 'cat', weight: Number.POSITIVE_INFINITY}\n];\n\now(animals, ow.array.ofType(ow.object.custom(validateAnimal)));\n//=> ArgumentError: (array) (object) Expected number `Animal.weight` to be finite, got Infinity\n```\n\n#### message(string | fn)\n\nProvide a custom message:\n\n```ts\now('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));\n//=> ArgumentError: Expected unicorn, got rainbow\n```\n\nYou can also pass in a function which receives the value as the first parameter and the label as the second parameter and is expected to return the message.\n\n```ts\now('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \\`${value}\\``));\n//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`\n```\n\nIt's also possible to add a separate message per validation:\n\n```ts\now(\n\t'1234',\n\tow.string\n\t\t.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \\`${value}\\``)\n\t\t.url.message('This is no url')\n);\n//=> ArgumentError: Expected string, to be have a minimum length of 5, got `1234`\n\now(\n\t'12345',\n\tow.string\n\t\t.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \\`${value}\\``)\n\t\t.url.message('This is no url')\n);\n//=> ArgumentError: This is no url\n```\n\nThis can be useful for creating your own reusable validators which can be extracted to a separate npm package.\n\n### TypeScript\n\nOw includes a type utility that lets you to extract a TypeScript type from the given predicate.\n\n```ts\nimport ow, {Infer} from 'ow';\n\nconst userPredicate = ow.object.exactShape({\n\tname: ow.string\n});\n\ntype User = Infer<typeof userPredicate>;\n```\n\n#### Literal Type Narrowing\n\n`string.equals()` and `string.oneOf()` narrow to literal types:\n\n```ts\n// ow.string.equals('hello') narrows to 'hello'\n// ow.string.oneOf(['red', 'blue']) narrows to 'red' | 'blue'\n\nfunction validateColor(input: unknown): 'red' | 'blue' {\n\tow(input, ow.string.oneOf(['red', 'blue']));\n\treturn input; // TypeScript knows this is 'red' | 'blue'\n}\n```\n\n### Performance\n\nOw is designed for runtime validation of function arguments. While it performs well for most use cases, there are a few things to keep in mind for performance-critical apps:\n\n#### Label Inference\n\nBy default, Ow automatically infers the label of the validated value from the source code when no explicit label is provided. This requires reading the source file from disk and parsing it, which can be slow in performance-critical scenarios.\n\nTo improve performance, always provide an explicit label as the second argument:\n\n```ts\n// Slower - label is inferred\now(username, ow.string);\n\n// Faster - explicit label provided\now(username, 'username', ow.string);\n```\n\n## Related\n\n- [@sindresorhus/is](https://github.com/sindresorhus/is) - Type check values\n- [ngx-ow](https://github.com/SamVerschueren/ngx-ow) - Angular form validation on steroids\n","publish_time":1757456908407,"_cnpm_publish_time":1757456908407,"dist-tags":{"latest":"3.1.1","version-0-28":"0.28.2"}}