npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

zod-invertible

v1.2.0

Published

declare zod schemas that can be inverted to format from output to input

Downloads

1,202

Readme

zod-invertible

declare zod schemas that can be inverted to format from output to input

CircleCI Coverage Status semantic-release Commitizen friendly npm version

Limitations and notes

zod-invertible doesn't support the following schemas, and invert will throw an error if it encounters them:

  • z.preprocess(...)
  • ZodType.transform(...) (outside of the transform created by invertible)

However, you may work around this by marking the schema with ignoreEffect:

import { schema, ignoreEffect } from 'zod-intervible'

const innerSchema = ...
const schema = ignoreEffect(z.preprocess((value) => ..., innerSchema))
const inverse = invert(schema) // equivalent to invert(innerSchema)

The inverse of ZodType.default(...) will not have a default, which should be okay, since the input to the inverse should always be defined.

The inverse of ZodType.catch(...) will not catch. If you want to use a fallback value if errors are thrown during parsing or formatting, add your own logic in the parse and format functions you pass to invertible.

If the output types of z.union([...]) options overlap, then invert(z.union([...])).parse(output) may format with a different union option than the one that parsed the input.

If you have recursive schemas (using z.lazy()), the inverse z.lazy() schemas will re-invert the resolved schema each time they are used. I may fix this in the future with a WeakMap inverse cache.

Example

npm i zod-invertible
# OR
pnpm i zod-invertible
import z from 'zod'
import { invertible, invert, ZodInvertible } from 'zod-intertible'

const StringToNumber = invertible(
  z.string(),
  (s, ctx) => {
    const result = parseFloat(s)
    if (isNaN(result)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'invalid float',
      })
    }
    return result
  },
  z.number(),
  (n) => String(n)
)

StringToNumber instanceof ZodInvertible // true

StringToNumber.parse('3.5') // 3.5

const NumberToString = invert(StringToNumber)

NumberToString.parse(3.5) // '3.5'

const obj = z.object({ foo: StringToNumber })
obj.parse({ foo: '3.5' }) // { foo: 3.5 }
// invert works deeply:
invert(obj).parse({ foo: 3.5 }) // { foo: '3.5' }

invertible(inputSchema, parse, outputSchema, format)

Creates an invertible schema that transforms from an input type to a different output type. Returns a ZodInvertible, which is a subclass of ZodPipeline.

inputSchema

The ZodType for validating the input value

parse

The function for transforming the input value into the output value. It is called with two arguments:

  • value: the output of inputSchema
  • ctx: the zod RefinementCtx

parse may be async.

outputSchema

The ZodType for validating the output

format

The function for converting from the output value back into the input value. It is called with two arguments:

  • value: the input of outputSchema
  • ctx: the zod RefinementCtx

format may be async.

invert(schema)

Deeply inverts a zod schema, inverting any ZodInvertible schemas inside it, and otherwise preserving the structure of objects, arrays, etc.

If the zod schema parses input type I into output type O, the inverted schema will parse input type O into output type I.