4 A ridiculously light-weight function argument validator
7 var validate = require("aproba")
9 function myfunc(a, b, c) {
10 // `a` must be a string, `b` a number, `c` a function
11 validate('SNF', arguments) // [a,b,c] is also valid
14 myfunc('test', 23, function () {}) // ok
15 myfunc(123, 23, function () {}) // type error
16 myfunc('test', 23) // missing arg error
17 myfunc('test', 23, function () {}, true) // too many args error
26 A | Array.isArray OR an arguments object
29 F | typeof == function
30 O | typeof == object and not type A and not type E
32 E | instanceof Error OR null **(special: see below)**
35 Validation failures throw one of three exception types, distinguished by a
36 `code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`.
38 If you pass in an invalid type then it will throw with a code of
41 If an **error** argument is found and is not null then the remaining
42 arguments are optional. That is, if you say `ESO` then that's like using a
43 non-magical `E` in: `E|ESO|ZSO`.
45 ### But I have optional arguments?!
47 You can provide more than one signature by separating them with pipes `|`.
48 If any signature matches the arguments then they'll be considered valid.
50 So for example, say you wanted to write a signature for
51 `fs.createWriteStream`. The docs for it describe it thusly:
54 fs.createWriteStream(path[, options])
57 This would be a signature of `SO|S`. That is, a string and and object, or
60 Now, if you read the full `fs` docs, you'll see that actually path can ALSO
61 be a buffer. And options can be a string, that is:
63 path <String> | <Buffer>
64 options <String> | <Object>
67 To reproduce this you have to fully enumerate all of the possible
68 combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The
69 awkwardness is a feature: It reminds you of the complexity you're adding to
70 your API when you do this sort of thing.
75 I wanted a very simple argument validator. It needed to do two things:
77 1. Be more concise and easier to use than assertions
79 2. Not encourage an infinite bikeshed of DSLs
81 This is why types are specified by a single character and there's no such
82 thing as an optional argument.
84 This is not intended to validate user data. This is specifically about
85 asserting the interface of your functions.
87 If you need greater validation, I encourage you to write them by hand or