zod icon indicating copy to clipboard operation
zod copied to clipboard

feat: `z.envbool()` - coerce string inputs to boolean

Open Jay-Karia opened this issue 8 months ago • 4 comments

z.envbool()

Closes #3906

Usage

Using default truthy and falsy values

const envbool = z.envbool();
envbool.parse("1") // true
envbool.parse("on") // true
envbool.parse("ON") // true

envbool.parse("0") // false
envbool.parse("off") // false
envbool.parse("OFF") // false

envbool.parse("foo") // throws Error

Custom values

const envbool = z.envbool({
  true: ["always"],
  false: ["never"],
  case: "sensitive"
})

envbool.parse("always") // true
envbool.parse("on") // true

envbool.parse("never") // false
envbool.parse("off") // false

envbool.parse("Always") // throws Error
envbool.parse("Off") // throws Error

Additional functions

const envbool = z.envbool();

envbool._truthyValues; // Default truthy values
envbool._falsyValues; // Default falsy values
envbool._caseSensitivity; // Default case sensitivity

Default Values

truthyValues = ["true",  "1",  "on",  "yes",  "y",  "enabled"];
falsyValues = ["false",  "0",  "off", "no",  "n",  "disabled"];
caseSensitivity = "insensitive"

Summary by CodeRabbit

  • New Features

    • Added an environment boolean validation option that allows the parsing of boolean-like string values with both default and customizable configurations, including control over case sensitivity.
  • Tests

    • Introduced comprehensive tests to ensure the new environment boolean validation behaves correctly under various configurations and accurately distinguishes valid from invalid boolean representations.

Jay-Karia avatar Mar 27 '25 10:03 Jay-Karia

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
zod ❌ Failed (Inspect) Mar 27, 2025 10:52am

vercel[bot] avatar Mar 27 '25 10:03 vercel[bot]

Walkthrough

This pull request introduces a new "envbool" string validation type for environment boolean values, enhancing the validation capabilities of the library. It adds test cases to ensure the functionality works correctly under both case-sensitive and insensitive scenarios. Additionally, a new ZodEnvBool class is implemented, along with associated types, constants, utility functions, and updates to the enum and export definitions. These changes are reflected in both the deno and src directories.

Changes

File(s) Change Summary
deno/lib/ZodError.ts, src/ZodError.ts Updated StringValidation type to include the "envbool" option for validating environment boolean values.
deno/lib/__tests__/string.test.ts, src/__tests__/string.test.ts Added test cases for z.envbool(), verifying correct parsing for case-insensitive, case-sensitive, and custom configurations of boolean-like string representations.
deno/lib/types.ts, src/types.ts Introduced the ZodEnvBool class (extending ZodType), new interface ZodEnvBoolDef, type CaseSensitivity, constants for truthy/falsy values, utility functions (safeMergeTruthy, safeMergeFalsy), updated the ZodFirstPartyTypeKind enum, and export adjustments for supporting environment boolean parsing.

Sequence Diagram(s)

sequenceDiagram
    participant Tester as Test Suite
    participant Validator as z.envbool() Function
    participant EnvBool as ZodEnvBool
    participant Util as Utility Functions

    Tester->>Validator: Invoke envbool() with input
    Validator->>EnvBool: Delegate to _parse(input)
    EnvBool->>Util: Merge custom truthy/falsy values (if provided)
    EnvBool->>EnvBool: Validate input based on case sensitivity settings
    EnvBool->>Tester: Return true, false, or error

Poem

I'm a little rabbit with a coding delight,
Hopping through strings by day and by night.
I added "envbool" to keep booleans clear,
With tests and types, the solution is here!
Code hops along—a joyful, wild sight! 🐇

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Mar 27 '25 10:03 coderabbitai[bot]

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 39242d067c5d3480256cd877c5ac2414f017d05b
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67e52df2f19f88000818af0b
Deploy Preview https://deploy-preview-4054--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

netlify[bot] avatar Mar 27 '25 10:03 netlify[bot]

@colinhacks, Do I need to fix the Vercel CI, before pushing ?

Jay-Karia avatar Apr 01 '25 07:04 Jay-Karia

This feature has been implemented in the Zod 4 beta and I'm not planning to backport it to Zod 3 for compatibility reasons I'm afraid. But thanks for the PR, it was really well done.

colinhacks avatar Apr 17 '25 23:04 colinhacks