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

kysforge

v0.1.5

Published

Migration CLI, schema helpers, and codegen for Kysely + PostgreSQL projects.

Readme

kysforge

Migration CLI, schema helpers, and codegen for Kysely + PostgreSQL projects.

Features

  • Migration CLI - up, down, status, to <target>, create-migration
  • Column helpers - UUID PKs, timestamps, foreign keys via .$call() chaining
  • Index helpers - single, composite, trigram (GIN) indexes
  • Trigger helpers - updated_at auto-update trigger
  • Enum helpers - create PostgreSQL enum types
  • Codegen - introspect your database and generate fully-typed Kysely interfaces

Installation

npm install kysforge
# peer deps (skip if already installed)
npm install kysely pg

Quick start

1. Environment variables

POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=my_db
POSTGRES_USER=dev
POSTGRES_PASSWORD=password

Use a .env file - the CLI loads it automatically via dotenv.

2. Add scripts to package.json

{
  "scripts": {
    "migrate": "kysforge migrate",
    "migration:create": "kysforge create-migration",
    "codegen": "kysforge codegen"
  }
}

3. Create your first migration

npm run migration:create add-users-table
# -> migrations/20260316120000-add-users-table.ts

Migration files are written to ./migrations/ by default. Override with MIGRATIONS_DIR env var or --migrations-dir CLI flag.

4. Run migrations

npm run migrate up          # apply all pending
npm run migrate down        # roll back one
npm run migrate down 3      # roll back three
npm run migrate status      # show applied / pending
npm run migrate to none     # roll back everything
npm run migrate to 20260316120000-add-users-table  # migrate to specific name

TypeScript migrations: The CLI runs compiled JavaScript. If your migration files are .ts you need to compile them first.


Codegen

Introspect your live database and generate TypeScript types for Kysely.

1. Create kysforge.config.js in your project root

// kysforge.config.js
/** @type {import('kysforge').KyselyPgConfig} */
export default {
  output: {
    database: "./src/database.generated.ts",
    // Optional: write enums to a separate file
    enums: "./src/enums.generated.ts",
    // Optional: module specifier used to import enums inside the database file
    // If omitted, a relative path is derived automatically.
    enumsImportPath: "@my-app/shared",
  },
  overrides: {
    columns: {
      // Override inferred TypeScript type for specific columns
      "books.type": '"book"',
      "movies.type": '"movie"',
    },
  },
};

2. Run codegen

npm run codegen
# or with a custom config path:
kysforge codegen --config ./config/kysforge.config.js
# or via env var:
KYSELY_PG_CONFIG=./config/kysforge.config.js kysforge codegen

Generated output (example)

// database.generated.ts
import type {
  ColumnType,
  Generated,
  Insertable,
  Selectable,
  Updateable,
} from "kysely";

export interface UsersTable {
  id: Generated<string>;
  email: string;
  created_at: ColumnType<Date, string | Date | undefined, never>;
  updated_at: ColumnType<Date, string | Date | undefined, string | Date>;
}

export type User = Selectable<UsersTable>;
export type NewUser = Insertable<UsersTable>;
export type UserUpdate = Updateable<UsersTable>;

export interface Database {
  users: UsersTable;
}

Library API

Import utilities directly for use inside migration files.

import {
  createKyselyInstance,
  postgresConfigFromEnv,
  withUuidPrimaryKey,
  withTimestampColumns,
  setupTimestampIndexesAndTrigger,
  createSingleIndex,
  createMultiIndex,
  createTrigramIndex,
  setupUpdatedAtTrigger,
  createEnum,
} from "kysforge";

createKyselyInstance<T>(config)

Creates a typed Kysely instance backed by a pg connection pool.

const db = createKyselyInstance<Database>({
  host: "localhost",
  port: 5432,
  database: "my_db",
  user: "dev",
  password: "password",
});

postgresConfigFromEnv()

Reads POSTGRES_HOST/PORT/DB/USER/PASSWORD from process.env.


Column helpers

All helpers are used with Kysely's .$call() pattern inside createTable.

withUuidPrimaryKey(columnName?)

Adds a UUID primary key with uuid_generate_v4() as its default.

Prerequisite: CREATE EXTENSION IF NOT EXISTS "uuid-ossp" (add in your init migration).

await db.schema
  .createTable("users")
  .$call(withUuidPrimaryKey()) // default column name: 'id'
  .$call(withUuidPrimaryKey("uid")) // custom name
  .execute();

withTimestampColumns()

Adds created_at and updated_at (timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP).

await db.schema
  .createTable("posts")
  .$call(withUuidPrimaryKey())
  .$call(withTimestampColumns())
  .execute();

// Wire up indexes + auto-update trigger (see prerequisites below)
await setupTimestampIndexesAndTrigger(db, "posts");

Prerequisite: The update_updated_at_column() PL/pgSQL function must exist in the database. Add it in your first/init migration:

CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ language 'plpgsql';

Index helpers

createSingleIndex(db, table, column, options?)

await createSingleIndex(db, "users", "email", { unique: true });
await createSingleIndex(db, "posts", "deleted_at", { notNull: true }); // partial index

createMultiIndex(db, table, columns[], options?)

await createMultiIndex(db, "orders", ["user_id", "status"]);
await createMultiIndex(db, "posts", ["author_id", "published_at"], {
  unique: true,
});

createTrigramIndex(db, table, column, options?)

Creates a GIN trigram index for fast ILIKE / similarity queries. Installs pg_trgm automatically.

await createTrigramIndex(db, "products", "name");
await createTrigramIndex(db, "articles", "body", { notNull: true });

Enum helpers

await createEnum(db, 'status_type', ['active', 'inactive', 'pending']);

// Use in a table:
.addColumn('status', sql`status_type`, (col) => col.notNull())

// Drop in down migration (after dropping the table):
await db.schema.dropType('status_type').execute();

Complete migration example

import type { Kysely } from "kysely";
import { sql } from "kysely";
import {
  withUuidPrimaryKey,
  withTimestampColumns,
  setupTimestampIndexesAndTrigger,
  createSingleIndex,
  createMultiIndex,
  createEnum,
} from "kysforge";

export async function up(db: Kysely<any>): Promise<void> {
  await createEnum(db, "post_status", ["draft", "published", "archived"]);

  await db.schema
    .createTable("posts")
    .$call(withUuidPrimaryKey())
    .$call(withTimestampColumns())
    .addColumn("user_id", "uuid", (col) => col.notNull().references("users").onDelete("cascade"))
    .addColumn("title", "varchar(255)", (col) => col.notNull())
    .addColumn("body", "text")
    .addColumn("status", sql`post_status`, (col) => col.notNull())
    .addColumn("published_at", "timestamptz")
    .execute();

  await setupTimestampIndexesAndTrigger(db, "posts");
  await createSingleIndex(db, "posts", "user_id");
  await createSingleIndex(db, "posts", "status");
  await createMultiIndex(db, "posts", ["user_id", "status"]);
}

export async function down(db: Kysely<any>): Promise<void> {
  await db.schema.dropTable("posts").execute();
  await db.schema.dropType("post_status").execute();
}

Resources