Skip to content

Instantly share code, notes, and snippets.

@khalidx
Last active October 2, 2023 09:08
Show Gist options
  • Save khalidx/3e3d14ad2dc2b2c606cf2f4d084b76b1 to your computer and use it in GitHub Desktop.
Save khalidx/3e3d14ad2dc2b2c606cf2f4d084b76b1 to your computer and use it in GitHub Desktop.
Validate fields from a package.json file.

You could use this code to, for example, validate fields from a package.json file for use in a Node.js CLI application.

It gives you a packageInfo object that has some useful fields that you could use (in a help or usage message, for example):

  • packageInfo.version, so that you can display the CLI version
  • packageInfo.bin, so that you can display the name of the CLI command
  • packageInfo.repository, so that you can display a URL to the repo for the CLI

Make sure your tsconfig.json includes "resolveJsonModule": true.

import { version, bin, repository } from '../../package.json'

import { z } from 'zod'

export const packageInfo = z
.object({
  version: z.string().min(1).max(10000),
  bin: z.record(z.string().min(1).max(10000)).transform((arg, ctx) => {
    const name = Object.keys(arg).at(0)
    if (name) return name
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: 'A bin object (with at least one key) must be defined in the package.json file'
    })
    return z.NEVER
  }),
  repository: z.object({
    url: z.string().url({ message: 'A repository.url must be defined in the package.json file' })
  }).transform(arg => arg.url)
}, {
  invalid_type_error: 'A version, repository.url, and a bin object (with at least one key) must be defined in the package.json file'
})
.parse({ version, bin, repository })

Save the file as ./src/utilities/packageInfo.ts and use it like:

import { packageInfo } from '../utilities/packageInfo'

console.log('version', packageInfo.version)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment