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

@mrspartak/config

v1.0.0

Published

Config facade for TS

Downloads

543

Readme

🔧 Typescript runtime configuration resolver

@mrspartak/config is a robust TypeScript runtime configuration resolver designed to ensure that your application runs with the correct settings every time. It supports dynamic runtime validation, deep merging of configurations, and integrates seamlessly with your choice of data validation libraries.

  • ⚡️ Runtime Validation: Ensure your application never runs with the wrong configuration.
  • 🧙‍♂️ TypeScript IntelliSense: Leverage auto-completion and type-checking at development time.
  • 🍃 Zero Dependencies: Lightweight with no external dependencies
  • 🤲 Flexible Configuration Merging: Supports merging multiple configurations with a default overwrite strategy.
  • 👓 Versatile Configuration Sources: Load from JSON files, URLs, or direct objects. Inderect .env support
  • 🐻 Extensible Validation Support: Compatible with Zod, Valibot, Yup, Superstruct, and more.
  • Production Ready: Thoroughly tested and stable for use.
  • 📦 Front-end friendly: Can be used on a front-end with bundlers.

Installation

# yarn
yarn add @mrspartak/config
# npm
npm i @mrspartak/config
# pnpm
pnpm add @mrspartak/config
# bun
bun add @mrspartak/config

Using with JSON config on a back-end

This is a recomended way of doing back-end run-time configuration. It allows to have readable structures and can be used with configmaps and secrets on deploy.

// file: state/config.ts
import { fromJSONFile } from "@mrspartak/config";
import * as z from "zod"

const config = await fromJSONFile({
  path: ["../config/default.json", "../config/runtime.json"],
  schema: z.object({
    db: z.object({
      host: z.string(),
      port: zv.number(),
      username: z.string(),
      password: z.string()
    }),
    app: z.object({
      port: z.number().optional().default(3000)
    })
  }),
});

export default config
// file: index.ts
// Import your resolved configuration
import config from './state/config.js';

// Use the configuration in your application
import db from 'some-db-provider';
const dbClient = db(config.db); // Enjoy IntelliSense here!

Using with .env configuration on back-end

Libriaries that parse .env configuration files are rich with features, so no reason to write my own. But this library can still be used on top for validation and IntelliSense purposes.

// file: state/config.ts
import { fromObject } from "@mrspartak/config";
import * as z from "zod"

const schema = z
  .object({
    NODE_ENV: z.enum(["development", "production"]),
    DB_HOST: z.string(),
    DB_PORT: z.number(),
    DB_USER: z.string(),
    DB_PASSWORD: z.string(),
    APP_PORT: z.number().default(3000),
  })
  .transform((data) => ({
    environment: data.NODE_ENV,
    port: data.APP_PORT,
    db: {
      host: data.DB_HOST,
      port: data.DB_PORT,
      user: data.DB_USER,
      password: data.DB_PASSWORD,
    },
  }));

const config = await fromObject({
  data: process.env,
  schema
})

export default config
// file index.ts
import 'dotenv/config'
// ! Configuration must be loaded after dotenv so it will populate process.env
import config from './state/config.js';

// Use the configuration in your application
import db from 'some-db-provider';
const dbClient = db(config.db); // Enjoy IntelliSense here!

Using on front-end

There is a separate build, that trims Node APIs for usage on front-end. Because this library is mostly build to improve DX, I see no reason to bundle it for usage on front-ends without a bundler (vite, webpack...)
It supports both build-time and run-time configurations

Build-time front-end configuration

// file: state/config.ts
import { fromObject } from "@mrspartak/config/web"; // a separate build of the library
import * as z from "zod"

const schema = z
  .object({
    API_URL: z.string(),
  })

const config = await fromObject({
  data: import.meta.env, // example with vite 
  schema
})

export default config

Run-time front-end configuration

// file: state/config.ts
import { fromURL } from "@mrspartak/config/web"; // a separate build of the library
import * as z from "zod"

const environment = import.meta.env.DEV ? "development" : "production"
const configPath = `/config/${environment}.json`

const schema = z
  .object({
    api_url: z.string(),
  })

const config = await fromURL({
  url: configPath, // will load a json from URL
  schema
})

export default config

Front-end usage

// file main.tsx
import React from "react"
import ReactDOM from "react-dom/client"
import { ConfigProvider } from "@/context/ConfigContext"
import { Routes } from "@/routes"

async function main() {
  // Can be build-time, run-time or even both
  const config = await import("@/state/config"); 

  ReactDOM.createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
      <ConfigProvider config={config}>
        <Routes />
      </ConfigProvider>
    </React.StrictMode>
  )
}

main().catch(error => {
  console.error("Mount error", error)
  ReactDOM.createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
      <div className="flex items-center justify-center h-screen">
          1. Try to reaload the page.
          <br />
          2. If doesn't help, please talk to developers, something went wrong.
      </div>
    </React.StrictMode>
})

API documentation is generated from TS declaration is avialable here: https://mrspartak.github.io/config/

Contributing

I welcome contributions from the community! Whether it's improving the documentation, adding new features, or reporting bugs, please feel free to make a pull request or open an issue.

License

This project is licensed under the MIT License - see the LICENSE file for details.