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

safe-yaml-env

v1.0.1

Published

Parse YAML files safely with schema validation, supporting environment variables and default values.

Downloads

161

Readme

safe-yaml-env

Parse YAML files safely with schema validation, supporting environment variables and default values.

This library uses jsr:@std/yaml for the YAML parsing and Zod for the schema validation.

Note: This library is written using Deno and is also published on JSR.

Usage

Load YAML Synchronously

config.yaml

---
name: Loris Ipsum
age: 25

main.ts

import { load } from "safe-yaml-env/zod";
import { z } from "zod";

const schema = z.object({
  name: z.string(),
  age: z.number(),
}).strict();

const data = load("./config.yaml", schema);
console.log(data); // { name: 'Loris Ipsum', age: 25 }

Load YAML Asynchronously

config.yaml

---
name: Loris Ipsum
age: 25

main.ts

import { loadAsync } from "safe-yaml-env/zod";
import { z } from "zod";

const schema = z.object({
  name: z.string(),
  age: z.number(),
}).strict();

const data = await loadAsync("./config.yaml", schema);
console.log(data); // { name: 'Loris Ipsum', age: 25 }

Environment Variables in YAML

YAML files can include references to environment variables, like ${ENV_VAR}, which will be replaced with their corresponding values from the environment (or throw an error if it's not set).

config.yaml

---
name: ${ENV_NAME} # ENV_NAME must be defined
age: 25

main.ts

const data = load("./config.yaml", schema);
console.log(data); // { name: 'Loris Ipsum', age: 25 }

Default environment variable values in the YAML file

You can provide a default value for an environment variable by using ${ENV_VAR:-default}. If the environment variable is not set, the default value will be used, and won't throw an error.

config.yaml

---
name: ${ENV_NAME:-John Doe}
age: 25

Default values in the Zod schema

You can also provide a default value for an environment variable by using the default method of the Zod schema. If the environment variable is not set, the default value will be used, and won't throw an error.

Note: default values in the YAML file have precedence over default values in the Zod schema.

main.ts

const schema = z.object({
  name: z.string().default("John Doe"),
  age: z.number(),
}).strict();

Type coercion

Environment variables are always of type string. If you want to parse them as another type, you can use Zod's coerce as follows :

main.ts

const schema = z.object({
  name: z.string(),
  age: z.coerce.number(), // This will try to convert the type to number
}).strict();

Now, if the age property is referenced from an environment variable inside the YAML file, the type will be converted from string to number (if possible), instead of throwing an error.

Error Handling

The following errors can be thrown:

  • FileNotFoundError: Thrown if the YAML file is not found.
  • SyntaxError: Thrown if the YAML file is invalid.
  • MissingEnvVarError: Thrown if an environment variable is referenced but not set.
  • ZodError: Thrown if the data doesn't conform to the Zod schema.

main.ts

import { load } from "safe-yaml-env/zod";
import { FileNotFoundError, MissingEnvVarError } from "safe-yaml-env";
import { ZodError } from "zod";

try {
  load("./config.yaml", schema);
} catch (error) {
  if (error instanceof FileNotFoundError) {
    console.error("File not found");
  } else if (error instanceof SyntaxError) {
    console.error("Invalid YAML");
  } else if (error instanceof MissingEnvVarError) {
    console.error("Missing environment variable:", error.envVarKey);
  } else if (error instanceof ZodError) {
    console.error("Invalid data:", error.errors);
  }
}