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 versionpackageInfo.bin
, so that you can display the name of the CLI commandpackageInfo.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)