New decoders:
- Fix a regression in
taggedUnion
(thanks for reporting, @programever) - Upgrade all dependencies
New features:
- A new
.pipe()
method onDecoder
allows you to pass the output of one decoder into another:This was previously possible already withstring .transform((s) => s.split(',')) // transform first... .pipe(array(nonEmptyString)); // ...then validate that result
.then
, but it wasn't as elegant to express. - The new
.pipe()
can also dynamically select another decoder, based on the input:string .transform((s) => s.split(',').map(Number)) // transform first... .pipe((tup) => tup.length === 2 ? point2d : tup.length === 3 ? point3d : never('Invalid coordinate'), );
- Decoder error messages will now quote identifiers using single quotes, which makes them
more human-readable in JSON responses. Compare:
"Value at key \"foo\": Must be \"bar\", \"qux\"" // ❌ Previously "Value at key 'foo': Must be 'bar', 'qux'" // ✅ Now
- Some runtime perf optimizations
New decoders:
Removed decoders:
- Remove
numericBoolean
decoder, which was deprecated since 2.3.0.
New features:
- All
enum
types are now supported (docs) - Record decoder now supports both
record(values)
andrecord(keys, values)
forms (docs) - Add
datelike
decoder (docs) - Add support for
bigint
(docs) - Add built-in support for common string validations
- Better support for symbols in
constant()
andoneOf()
New decoders:
enum_
(see docs)record()
(see docs)select()
(see docs)bigint
(see docs)datelike
(see docs)decimal
(see docs)hexadecimal
(see docs)numeric
(see docs)
Renamed decoders:
Some decoders have been renamed because their names were based on Flowisms. Names have been updated to better reflect TypeScript terminology:
dict()
→record()
maybe()
→nullish()
set()
→setFromArray()
(to make room for a betterset()
decoder in a future version)
Deprecated decoders:
The following decoders are deprecated because they were not commonly used, and a bit too specific to be in the standard library. They are also scheduled for removal in a future decoders version.
dict()
(preferrecord()
)hardcoded()
(preferalways()
)maybe()
(prefernullish()
)mixed
(preferunknown
)numericBoolean()
Other changes:
- Fix:
positiveNumber
andpositiveInteger
no longer accept-0
as valid inputs - Fix:
either
return type would sometimes get inferred incorrectly if members partially overlapped (see #941) - Reorganized internal module structure
- Simplified some of the more complicated internal types
Breaking change: Dropped Flow support*.
Breaking change: Projects that are not yet using strict: true
in their
tsconfig.json
files files are no longer supported. Previously, decoders went to great
lenghts to support both configurations, but the internal typing magic was getting too
complex to maintain without much benefit.
Breaking change: A small breaking change is introduced that removes the need for some packaging workarounds to support projects using old TypeScript/Node versions. It’s now simpler to use, and simpler to maintain:
-import { formatInline, formatShort } from 'decoders/format'; // ❌
+import { formatInline, formatShort } from 'decoders'; // ✅
-import { Result, ok, err } from 'decoders/result'; // ❌
+import { Result, ok, err } from 'decoders'; // ✅
Other, smaller changes, mostly internal:
- Rewritten source code in TypeScript (previously Flow)
- Rewritten test suite in Vitest (previously Jest)
- Modern ESM and CJS dual exports (fully tree-shakable when using ESM)
- Further reduced bundle size
- Related, greatly simplified complex internal typing magic to make it work in projects
with and without
strict
mode.
(*: I'm still open to bundling Flow types within this package, but only if that can be
supported in a maintenance-free way, for example by using a script that will generate
*.flow
files from TypeScript source files. If someone can add support for that, I'm open
to pull requests! 🙏 )
- Officially drop Node 12 and 14 support (they may still work)
- Fix unintentional inclusion of
lib.dom.d.ts
in TypeScript
- The returned value for
positiveInteger(-0)
is now0
, not-0
- The returned value for
positiveNumber(-0)
is now0
, not-0
- Fix a bug in the
url
decoder, which could incorrectly reject URLs with a/
in the query path. Thanks, @gcampax!
-
Fix bundling issue where TypeScript types would not get picked up correctly in old TypeScript versions. Thanks, @robinchow!
-
Fix TypeScript types for
Result
type to allow implicit-undefineds.
-
TypeScript-only: Fix definition of JSONObject to reflect that its values might always be
undefined
as well. -
TypeScript-only: Changed return types of
{ [key: string]: T }
toRecord<string, T>
. -
TypeScript-only: Fine-tune the type of
instanceOf()
.
This is a breaking change, which brings numerous benefits:
- A simpler API 😇
- Smaller bundle size (67% reduction 😱)
- Tree-shaking support 🍃
- Runtime speed 🏎️
- Better documentation 📚
- Better support for writing your own decoders 🛠️
Please see the migration guide for precise instructions on how to adjust your v1 code.
The main change is the brand new Decoder<T>
API! The tl;dr is:
Replace this v1 pattern... | ...with this v2 API | Notes | |
---|---|---|---|
mydecoder(input) |
→ | mydecoder.decode(input) |
migration instructions |
guard(mydecoder)(input) |
→ | mydecoder.verify(input) |
migration instructions |
map(mydecoder, ...) |
→ | mydecoder.transform(...) |
migration instructions |
compose(mydecoder, predicate(...)) |
→ | mydecoder.refine(...) |
migration instructions |
describe(mydecoder, ...) |
→ | mydecoder.describe(...) |
|
mydecoder(input).value() |
→ | mydecoder.value(input) |
|
either , either3 , ..., either9 |
→ | either |
migration instructions |
tuple1 , tuple2 , ... tuple6 |
→ | tuple |
migration instructions |
dispatch |
→ | taggedUnion |
migration instructions |
url(...) |
→ | httpsUrl / url (signature has changed) |
migration instructions |
The full documentation is available on decoders.cc.
Other features:
- Include ES modules in published NPM builds (yay tree-shaking! 🍃)
- Much smaller total bundle size (67% smaller compared to v1 😱)
Other potentially breaking changes:
- Drop support for all Node versions below 12.x
- Drop support for TypeScript versions below 4.1.0
- Drop support for Flow versions below 0.142.0
- Drop all package dependencies
- Direct reliance on
lemons
has been removed
New decoders:
Other improvements:
optional()
,nullable()
, andmaybe()
now each take an optional 2nd param to specify a default value- Better error messages for nested
either
s
Implementation changes:
- Major reorganization of internal module structure
- Various simplification of internals
-
Fix compatibility issue with TypeScript projects configured with
strictNullChecks: false
(orstrict: false
) (Thanks, @stevekrouse and @djlauk!) -
Officially support Node 16.x
- Expose
nonEmptyArray
function in TypeScript (Thanks, @mszczepanczyk!)
- Argument to
constant(...)
now has to be scalar value in both Flow and TypeScript, which matches its intended purpose.
- Avoid the need for having to manually specify "as const" in TypeScript when using
constant()
. (Thanks, @schmod!)
- Add support for Flow 0.154.0
-
Fix signature of
oneOf()
to reflect it can only be used with scalar/constant values -
In TypeScript, the inferred type for
oneOf(['foo', 'bar'])
will now beDecoder<'foo' | 'bar'>
instead ofDecoder<string>
🎉 -
Drop support for Flow versions < 0.115.0
- Tighten up signature types to indicate that incoming arrays won't get mutated
-
New decoders:
describe
: change the error message for an existing decoder
-
Add support for Flow 0.153.x
-
Drop support for Node 13.x (unstable)
TypeScript types:
- Add missing export for
tuple1
TypeScript types:
- Add missing export for
nonEmptyString
- Returned objects that are the result from
object()
,inexact()
, andexact()
decoders will no longer contain explicitundefined
values for optional keys, but instead those keys will be missing in the returned object entirely. (#574, thanks @w01fgang!)
- Add missing exports for
nonEmptyArray
andnonEmptyString
(for TypeScript)
- Include an error code with every FlowFixMe suppression (Flow 0.132.x compatibility)
-
New decoders:
-
json
: decodes any valid JSON value -
jsonObject
: decodes any valid JSON object -
jsonArray
: decodes any valid JSON array
-
-
New decoders:
-
Improved type inference for
object()
andexact()
decoders (see #515, thanks @dimfeld) -
DecoderType
is now an alias for$DecoderType
(to support both TypeScript and Flow conventional naming) -
GuardType
(and$GuardType
) is a new type function to extract the type of a guard instance
-
New decoder
lazy()
: lazily-evaluated decoder, suitable to define self-referential types. -
Fix compatibility with Flow 0.127.0
- Fix compatibility with Flow 0.126.0+
- Upgrade debrief to correct (final) version
- Fix issue where infinite recursion occurs when input object (the object being validated) contains a circular reference
- Republish due to an NPM outage
New decoders:
- To complement the tuple family of decoders, there's now also
tuple1
(thanks @sfarthin!)
- Also fix Flow type bugs when Flow option
exact_by_default=true
indebrief
dependency
New decoders:
-
nonEmptyString
: likestring
, but will fail on inputs with only whitespace (or the empty string) -
nonEmptyArray
: likearray
, but will fail on inputs with 0 elements
Fixes:
- Fix Flow type bugs when Flow option
exact_by_default=true
is enabled
May cause breakage for Flow users:
- Fix subtle bug in
object()
andexact()
Flow type definitions that could cause Flow to leakany
under rare circumstances.
- Internal change to make the code Flow 0.105.x compatible. Basically stops using array
spreads (
[...things]
) in favor ofArray.from()
.
New feature:
- Allow
map()
calls to throw an exception in the mapper function to reject the decoder. Previously, these mapper functions were not expected to ever throw.
New features:
- Support constructors that have required arguments in
instanceOf
decoders in TypeScript (see #308, thanks @Jessidhia!) - Add support for type predicates in
predicate()
in TypeScript (see #310, thanks @Jessidhia!)
Fixes:
- Add support for Flow >= 0.101.0
Potential breaking changes:
- Stricten
pojo
criteria. Now, custom classes likenew String()
ornew Error()
will not be accepted as a plain old Javascript object (= pojo) anymore.
Fixes:
- Add support for Flow 0.98+
Fixes:
- Don't reject URLs that contains commas (
,
)
Breaking changes:
-
Changed the API interface of
dispatch()
. The previous version was too complicated and was hardly used. The new version is easier to use in practice, and has better type inference support in TypeScript and Flow.Previous usage:
const shape = dispatch( field('type', string), type => { switch (type) { case 'rect': return rectangle; case 'circle': return circle; } return fail('Must be a valid shape'); } );
New usage:
const shape = dispatch('type', { rectangle, circle });
Where
rectangle
andcircle
are decoders of which exactly one will be invoked.
-
Removed the
field()
decoder. It was not generic enough to stay part of the standard decoder library. (It was typically used in combination withdispatch()
, which now isn't needed anymore, see above.) -
pojo
decoder now returnsDecoder<{[string]: mixed}>
instead of the unsafeDecoder<Object>
.
Fixes and cleanup:
- Internal reorganization of modules
- Improve TypeScript support
- Reorganization of TypeScript declarations
- More robust test suite for TypeScript
- 100% TypeScript test coverage
New decoders:
oneOf(['foo', 'bar'])
will return only values matching the given valuesinstanceOf(...)
will return only values that are instances of the given class. For example:instanceOf(TypeError)
.
- Reduce bundle size for web builds
- New build system
- Cleaner package output
Potentially breaking changes:
- Decoders now all take
mixed
(TypeScript:unknown
) arguments, instead ofany
🎉 ! This ensures that the proper type refinements in the implementation of your decoder are made. (See migration notes below.) - Invalid dates (e.g.
new Date('not a date')
) won’t be considered valid by thedate
decoder anymore.
New features:
-
guard()
now takes a config option to control how to format error messages. This is done via theguard(..., { style: 'inline' })
parameter.'inline'
: echoes back the input value and inlines errors (default);'simple'
: just returns the decoder errors. Useful for use in sensitive contexts.
-
Export
$DecoderType
utility type so it can be used outside of the decoders library.
Fixes:
- Fixes for some TypeScript type definitions.
- Add missing documentation.
Migration notes:
If your decoder code breaks after upgrading to 1.11.0, please take the following measures to upgrade:
-
If you wrote any custom decoders of this form yourself:
const mydecoder = (blob: any) => ... // ^^^ Decoder function taking `any`
You should now convert those to:
const mydecoder = (blob: mixed) => ... // ^^^^^ Decoders should take `mixed` from now on
Or, for TypeScript:
const mydecoder = (blob: unknown) => ... // ^^^^^^^ `unknown` for TypeScript
Then follow and fix type errors that pop up because you were making assumptions that are now caught by the type checker.
-
If you wrote any decoders based on
predicate()
, you may have code like this:const mydecoder: Decoder<string> = predicate( (s) => s.startsWith('x'), 'Must start with "x"' );
You'll have to change the explicit Decoder type of those to take two type arguments:
const mydecoder: Decoder<string, string> = predicate( // ^^^^^^ Provide the input type to predicate() decoders (s) => s.startsWith('x'), 'Must start with "x"' );
This now explicitly records that
predicate()
makes assumptions about its input type—previously this wasn’t get caught correctly.
- Make Flow 0.85 compatible
- Update to latest debrief (which fixes a TypeScript bug)
- Drop dependency on babel-runtime to reduce bundle size
- Fix minor declaration issue in TypeScript definitions
- Tuple decoder error messages now show decoder errors in all positions, not just the first occurrence.
New decoders:
- New tuple decoders:
tuple3
,tuple4
,tuple5
, andtuple6
unknown
decoder is an alias ofmixed
, which may be more recognizable for TypeScript users.
- TypeScript support
Breaking:
- Private helper function
undefined_or_null
was accidentally exported in the package. This is a private API.
New decoder:
dict()
is likemapping()
, but will return an object rather than a Map instance, which may be more convenient to handle in most cases.
Breaking:
optional(..., /* allowNull */ true)
has been removed (was deprecated since 1.8.3)
New decoder:
maybe()
is likeoptional(nullable(...))
, i.e. returns a "maybe type".
Deprecation warning:
optional(..., /* allowNull */ true)
is now deprecated in favor ofmaybe(...)
Improved error reporting:
- Fix bug where empty error branches could be shown in complex either expressions (fixes #83)
- Fix: revert accidentally emitting $ReadOnlyArray types in array decoders
- Drop support for Node 7
- Declare inputted arrays will not be modified (treated as read-only)
- Make decoders fully Flow Strict compatible
- Upgraded debrief dependency
- Behave better in projects that have Flow's
experimental.const_params
setting turned on
- New decoders!
exact()
is likeobject()
, but will fail if the inputted object contains superfluous keys (keys that aren't in the object definition).
- Collect and report all nested errors in an object() at once (rather than error on the first error).
Breaking:
- Remove deprecated
message
argument toobject()
- Add missing documentation
- Upgrade second-level dependencies
- Declare library to be side effect free (to help optimize webpack v4 builds)
- Upgrade dependencies
- Improve internals of the error message serializer (debrief)
- New decoders!
email
validator based on the almost perfect email regexurl
validator for validating HTTPS URLs (most common use case)anyUrl
validator for validating any URL scheme
- Fix bug where dates, or arrays (or any other Object subclass) could pass for a record with merely optional fields.
- Much improved error messages! They were redesigned to look great in terminals and to summarize only the relevant bits of the error message, striking a balance between all the details and the high level summary.
- New features:
truthy
takes any input and returns whether the value is truthynumericBoolean
takes only numbers as input, and returns their boolean interpretation (0 = false, non-0 = true)
- New feature
mixed
decoder, for unverified pass-thru of any values
- Fix Expose the following decoders publicly:
integer
positiveInteger
positiveNumber
- New feature
regex()
, for building custom string decoders - Tiny tweaks to improve error messages (more structural improvements are on the roadmap)
- Expose pojo() decoder, for plain old objects (with mixed contents)
- Expose poja() decoder, for plain old arrays (with mixed contents)
- Perf: make
tuple2()
decoder lazier
- Expose new "either" decoders at the too level
- BREAKING Removes the old public ("compat") API
- Finalize/settle on public API
- Add whole series for either, either3, either4, ..., either9
- Updated dev dependencies
- Add
date
decoder, which decodesDate
instances - Improve error output detail when throwing errors
- Export
g2d()
helper function that can help adoption to new-style APIs by converting old-style decoders (now called guards) to new-style decoders.
-
Breaking change New API: simplified names, split up decoders from guards. What used to be called "decoders" in 0.0.x ("things that either return a value or throw a runtime error") are now called "guards" in 0.1.0. The meaning of the term "decoders" is now changed to a thing that either is an "Ok" value or an "Err" value.
To convert to the new API, do this:
// Old way import { decodeNumber, decodeObject, decodeString } from 'decoders'; const decoder = decodeObject({ name: decodeString(), age: decodeNumber(), }); // ------------------------------------------------------------------- // New way import { guard, number, object, string } from 'decoders'; const guard = guard( object({ name: string, age: number, }), );