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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@grest-ts/config

v0.0.86

Published

Configuration management for Grest Framework - resources, secrets, and settings

Readme

Part of the grest-ts framework. Documentation | All packages

@grest-ts/config

Type-safe configuration management for Grest Framework.

Features

  • Type-safe configuration keys with validation
  • Multiple key types (Settings, Secrets, Resources)
  • Pluggable storage backends (file, environment, remote)
  • Runtime configuration updates with watchers
  • Centralized configuration definitions
  • Config values are validated!

Pattern

  • Keys are defined statically, but values are resolved at runtime from async context
  • Different key types (Setting, Secret, Resource) can use different storage backends (Strategy pattern)
  • Supports watching for runtime configuration changes (Observer pattern)

Getting Started

1. Define your configuration

import {GGConfig, GGSetting, GGSecret, GGResource} from "@grest-ts/config"
import {IsString, IsPosInt, IsBoolean} from "@grest-ts/schema"

export const AppConfig = GGConfig.define('/app/', () => ({
    server: {
        port: new GGSetting('server/port', IsPosInt, 3000, 'HTTP server port'),
        debug: new GGSetting('debug', IsBoolean, false, 'Enable debug mode'),
    },
    database: {
        host: new GGResource('db/host', IsString, 'Database host'),
        password: new GGSecret('db/password', IsString, 'Database password'),
    }
}));

2. Provide local values for development

import {createLocalConfig} from "@grest-ts/config"

export const localConfig = createLocalConfig(AppConfig, {
    database: {
        host: "localhost:5432",
        password: "root"
    }
});

createLocalConfig is a compile-time helper — it type-checks the values against your config definition.

3. Wire it up in your runtime

import {GGConfigLocator, GGConfigStoreFile} from "@grest-ts/config"

new GGConfigLocator(AppConfig, localConfig)
    .add(GGSetting, new GGConfigStoreFile('./config/settings.json', import.meta.url))
    .add([GGSecret, GGResource], new GGConfigStoreAwsSecretsManager({ ... }))

When localConfig is passed to the constructor, stores are automatically swapped for GGConfigStoreLocal outside of production — so your real stores (AWS, files, etc.) are only used when NODE_ENV=production.

4. Use it

// Settings - .get()
const port = AppConfig.server.port.get();
const debug = AppConfig.server.debug.get();

// Secrets - .reveal() to make intent explicit
const dbPassword = AppConfig.database.password.reveal();

// Resources - .get()
const dbHost = AppConfig.database.host.get();

// Watch for runtime changes
const unwatch = AppConfig.server.port.watch((newPort) => {
    console.log('Port changed to:', newPort);
});
unwatch(); // stop watching

Key Types

| Type | Constructor | Read method | Use Case | |----------------|--------------------------------------|-------------|--------------------------------------| | GGSetting | (name, schema, default, description) | .get() | General configuration (ports, flags) | | GGSecret | (name, schema, description) | .reveal() | Sensitive data (API keys, passwords) | | GGResource | (name, schema, description) | .get() | Infrastructure (URLs, hosts, paths) |

Settings have a default value. Secrets and resources do not — their values must come from a store.

Validation

All keys require a @grest-ts/schema validator. Values are validated when loaded from a store. Invalid config at startup prevents the service from starting. Invalid config during a runtime reload is rejected and an error is raised — the previous valid value remains in effect.

import {IsString, IsPosInt, IsBoolean, IsLiteral} from "@grest-ts/schema"

port: new GGSetting('port', IsPosInt, 8080, 'Server port')
name: new GGSetting('name', IsString, 'default', 'App name')
env:  new GGSetting('env', IsLiteral('dev', 'staging', 'prod'), 'dev', 'Environment')

Checking a config document without starting

The definition is code, so it can describe and check a deployment's config document (the JSON a file or Secrets Manager store loads) before anything runs:

GGConfig.describe(AppConfig)            // [{name, type, required, default, description, definedAt}, ...]
GGConfig.template(AppConfig)            // {app: {db: {password: null}, ...}} — required keys as null
GGConfig.check(AppConfig, documentJson) // {missing, invalid, defaulted, unknown, ok}

check resolves paths exactly like the stores, so ok: true means a store loading this document would start. A required key left null counts as missing — check(template()) lists what is still to fill in. unknown lists paths no key reads (stale or misspelled keys). Pass {types: [GGSecret, GGResource]} to scope any of them to the key types one store serves.

Prefer GGResource over a GGSetting default for anything deployment-specific (URLs, domains, bucket names): a resource has no default, so a deployment that forgets it fails at startup instead of silently using another environment's value.

Storage Backends

GGConfigLocator maps key types to stores. Each key type must have a store registered before start.

new GGConfigLocator(AppConfig)
    .add(GGSetting, new GGConfigStoreFile("./config/settings.json", import.meta.url))
    .add(GGResource, new GGConfigStoreFile("./config/resources.json", import.meta.url))

Multiple key types can share a store:

new GGConfigLocator(AppConfig)
    .add([GGSetting, GGResource], new GGConfigStoreFile("./config/config.json", import.meta.url))

GGConfigStoreFile

Reads values from a JSON file. Watches the file's directory and automatically reloads (100ms debounce), so both in-place writes and atomic writes (write a temp file, then rename it over the target) are picked up.

  • Initial load fails loudly: a missing, empty, unparsable or invalid file makes start() throw.
  • Reloads are all-or-nothing: every key is validated before any value changes. If anything fails (unreadable file, empty file, bad JSON, schema failure), the store keeps its last good values and reports the error to GGConfigLocator.onReloadError (default: console.error; override it to route to your logger or alerting). A deleted file is reported the same way; writing it back triggers a reload.
  • Watchers (key.watch()) fire once per reload, only for keys whose validated value changed (deep equality). A watcher that throws goes to onNotifyError; if that throws (the default), the error is passed to onReloadError instead of escaping as an unhandled rejection.

The key path /app/server/port maps to app.server.port in JSON:

{
    "app": {
        "server": {
            "port": 8080
        },
        "debug": true
    }
}

GGConfigStoreLocal

Type-safe development store. Refuses to start when NODE_ENV=production.

import {createLocalConfig, GGConfigStoreLocal} from "@grest-ts/config"

const localConfig = createLocalConfig(AppConfig, {
    database: {
        host: "localhost:5432",
        password: "root"
    }
});

new GGConfigLocator(AppConfig)
    .add([GGResource, GGSecret], new GGConfigStoreLocal(AppConfig, localConfig))
    .add(GGSetting, new GGConfigStoreFile('./config/settings.json', import.meta.url))

GGConfigStoreEnv

Reads environment variables, for processes whose deployment hands them config as env (systemd EnvironmentFile, containers). Key /app/db/host reads {prefix}DB_HOST: the config root is dropped and / becomes _. An unset or empty variable falls back to the key's default. A value the schema rejects as a plain string is JSON-parsed, so numbers, booleans and objects work. Values are read once at start.

new GGConfigLocator(AppConfig)
    .add([GGSetting, GGResource], new GGConfigStoreEnv({prefix: "MYAPP_"}))

GGConfigStoreAwsSecretsManager

See @grest-ts/config-aws.

Testing

Config is automatically restored between tests — no manual cleanup needed. When a test modifies config via t.config.update(), the testkit records which keys were changed and reverts them after the test completes.

describe("my tests", () => {
    const t = GGTest.startWorker(MyRuntime);

    test('modify config for this test', async () => {
        await t.config.update(AppConfig.server.port, 9999);
        // ... test with modified config
    });

    test('next test sees original config', async () => {
        const port = await t.config.get(AppConfig.server.port);
        expect(port).toBe(3000); // automatically restored
    });
});

Config set in beforeAll or by framework hooks (e.g. GGTest.with().clone()) is preserved — only changes made during individual tests are reverted. This also works with nested describe blocks: each scope's beforeAll overrides are reverted in its afterAll, so sibling describes don't see each other's config.

Further Reading

  • Extending - How to add custom key types and stores