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

@contract-kit/application

v1.0.0

Published

Use case builder for contract-kit - framework-agnostic

Readme

@contract-kit/application

Use case builder for Contract Kit - framework-agnostic commands and queries

This package provides a clean way to define use cases (commands and queries) that are framework-agnostic and work with any Standard Schema library.

Installation

npm install @contract-kit/application

# Use with your preferred Standard Schema library
npm install zod

TypeScript requirements

This package requires TypeScript 5.0 or higher for proper type inference.

Concepts

Commands vs queries

  • Commands - Write operations with side effects (create, update, delete)
  • Queries - Read-only operations (get, list, search)

This separation helps with:

  • Clear intent in your code
  • Easier testing (queries are pure functions)
  • CQRS-style architecture if needed

Use cases

A use case encapsulates a single business operation with:

  • A unique name for identification
  • Input schema for runtime validation
  • Output schema for runtime validation
  • Optional domain events it may emit

Use cases validate their input before your .run(...) function is called and validate the returned output before resolving. That makes them safe to call from HTTP handlers, jobs, scripts, tests, and event handlers.

Usage

Route handler or use case?

Use a route handler alone when the endpoint is just transport glue: health checks, webhooks that only normalize a payload, or a one-off adapter response. Use a use case when the workflow has business rules, touches ports, should be tested directly, or may later run from HTTP, jobs, scripts, events, or tests.

Authorization

Use hooks or adapter middleware for HTTP boundary authentication. Put business authorization in use cases or app-owned policy functions so ownership, role, tenant, plan, and resource-state rules run no matter which entrypoint calls the workflow.

import { requireUser } from "@/lib/auth";
import { authorizePost } from "@/policies/posts";
import { appError } from "@/server/errors";

export const updatePost = useCase
  .command("posts.update")
  .input(UpdatePostInput)
  .output(PostOutput)
  .run(async ({ ctx, input }) => {
    const user = requireUser(ctx);
    const post = await ctx.ports.posts.findById(input.id);

    if (!post) {
      throw appError("PostNotFound", { details: { id: input.id } });
    }

    authorizePost(user, "update", post);

    return ctx.ports.posts.update(input.id, input);
  });

Policy functions should stay plain TypeScript. One-off checks can live inline; repeated rules can move to modules like policies/posts.ts.

Creating a use case builder

// use-cases/builder.ts
import { createUseCase } from "@contract-kit/application";
import type { AppCtx } from "./ctx";

export const useCase = createUseCase<AppCtx>();

Validation is enabled by default. You can opt out at the builder level when you only want schema metadata or you are deliberately avoiding duplicate validation:

export const useCase = createUseCase<AppCtx>({
  validate: false,
});

// Or configure phases independently:
export const useCase = createUseCase<AppCtx>({
  validate: { input: true, output: false },
});

Defining commands

// use-cases/todos/create.ts
import { z } from "zod";
import { useCase } from "../builder";

const CreateTodoInput = z.object({
  title: z.string().min(1),
  description: z.string().optional(),
});

const CreateTodoOutput = z.object({
  id: z.string(),
  title: z.string(),
  completed: z.boolean(),
});

export const createTodo = useCase
  .command("todos.create")
  .input(CreateTodoInput)
  .output(CreateTodoOutput)
  .run(async ({ ctx, input }) => {
    const todo = await ctx.ports.db.todos.create({
      id: crypto.randomUUID(),
      title: input.title,
      description: input.description,
      completed: false,
    });

    return {
      id: todo.id,
      title: todo.title,
      completed: todo.completed,
    };
  });

The input value received by .run(...) is the parsed schema output, so schema coercions, defaults, and transforms are applied before your business logic runs.

The finalized use case exposes its schemas as public properties. Reuse them in contracts when the HTTP shape matches the application shape:

export const createTodoContract = todos
  .post("/api/todos")
  .body(createTodo.inputSchema)
  .responses({
    201: createTodo.outputSchema,
  });

Defining queries

// use-cases/todos/get.ts
import { z } from "zod";
import { useCase } from "../builder";

const GetTodoInput = z.object({
  id: z.string(),
});

const GetTodoOutput = z.object({
  id: z.string(),
  title: z.string(),
  description: z.string().nullable(),
  completed: z.boolean(),
}).nullable();

export const getTodo = useCase
  .query("todos.get")
  .input(GetTodoInput)
  .output(GetTodoOutput)
  .run(async ({ ctx, input }) => {
    const todo = await ctx.ports.db.todos.findById(input.id);
    
    if (!todo) {
      return null;
    }

    return {
      id: todo.id,
      title: todo.title,
      description: todo.description,
      completed: todo.completed,
    };
  });

Emitting domain events

Use cases can declare which domain events they may emit. .emits(...) records metadata; publish the event from inside .run(...) using your event bus port:

// use-cases/todos/complete.ts
import { z } from "zod";
import { useCase } from "../builder";
import { TodoCompletedEvent } from "@/domain/events";
import { publishEvent } from "@contract-kit/events";

const CompleteTodoInput = z.object({
  id: z.string(),
});

const CompleteTodoOutput = z.object({
  success: z.boolean(),
});

export const completeTodo = useCase
  .command("todos.complete")
  .input(CompleteTodoInput)
  .output(CompleteTodoOutput)
  .emits([TodoCompletedEvent])
  .run(async ({ ctx, input }) => {
    const todo = await ctx.ports.db.todos.update(input.id, {
      completed: true,
      completedAt: new Date(),
    });

    if (!todo) {
      return { success: false };
    }

    // Publish the domain event through the validated helper
    await publishEvent(ctx.ports.eventBus, TodoCompletedEvent, {
      todoId: todo.id,
      completedAt: todo.completedAt.toISOString(),
    });

    return { success: true };
  });

Application context

Your application context provides access to ports (dependencies):

// app-context.ts
import type { PortsContext } from "@contract-kit/ports";
import type { AppPorts } from "@/ports";

export interface AppCtx extends PortsContext<AppPorts> {
  user: { id: string; role: string } | null;
  now: () => Date;
  requestId: string;
}

Using with Next.js adapter

Use cases integrate directly with @contract-kit/next:

// server/index.ts
import { defineRoutes } from "@contract-kit/next";
import { getTodoContract } from "@/contracts/todos";
import { getTodo } from "@/use-cases/todos/get";

export const routes = defineRoutes([
  {
    contract: getTodoContract,
    handle: async ({ ctx, path }) => {
      const todo = await getTodo.run({
        ctx,
        input: { id: path.id },
      });

      return { status: 200, body: todo };
    },
  },
]);

API reference

createUseCase<Ctx>()

Creates a use case builder with a specific context type.

const useCase = createUseCase<AppCtx>();

useCase.command(name)

Starts building a command use case.

useCase
  .command("todos.create")
  .input(InputSchema)
  .output(OutputSchema)
  .emits([DomainEvent]) // Optional
  .run(async ({ ctx, input }) => { ... });

useCase.query(name)

Starts building a query use case.

useCase
  .query("todos.get")
  .input(InputSchema)
  .output(OutputSchema)
  .run(async ({ ctx, input }) => { ... });

createUseCaseTester<Ctx>(ctx)

Creates a small test harness around a fixed context or a context factory:

import { createUseCaseTester } from "@contract-kit/application";

const tester = createUseCaseTester<AppCtx>(() => ({
  ports: { db: createInMemoryDb() },
  user: { id: "user-1", role: "user" },
  requestId: "test-request",
}));

const result = await tester.run(createTodo, { title: "Test" });

Use a context factory when tests mutate in-memory ports or request-scoped state. Call tester.ctx() when multiple use cases in the same test need to share one context instance.

Type helpers

UseCaseInput<TUseCase>, UseCaseOutput<TUseCase>, and UseCaseContext<TUseCase> extract the input, output, and context types from a finalized use case.

Use case definition

The resulting use case definition includes:

type UseCaseDef = {
  name: string;           // Unique identifier
  kind: "command" | "query";
  inputSchema: StandardSchema;
  outputSchema: StandardSchema;
  emits: DomainEvent[];   // Domain events (metadata only)
  run: (args: { ctx: Ctx; input: Input }) => Promise<Output>;
};

Validation errors

If input or output validation fails, .run(...) throws UseCaseValidationError:

import { UseCaseValidationError } from "@contract-kit/application";

try {
  await createTodo.run({ ctx, input });
} catch (error) {
  if (error instanceof UseCaseValidationError) {
    console.log(error.useCaseName); // "todos.create"
    console.log(error.phase);       // "input" | "output"
    console.log(error.issues);      // Standard Schema issues
  }
}

Testing use cases

Use cases are easy to test because their dependencies come from the explicit context you pass to the tester:

import { createUseCaseTester } from "@contract-kit/application";
import { createTodo } from "@/use-cases/todos/create";

describe("createTodo", () => {
  it("creates a todo", async () => {
    const mockDb = {
      todos: {
        create: vi.fn().mockResolvedValue({
          id: "1",
          title: "Test",
          completed: false,
        }),
      },
    };

    const tester = createUseCaseTester(() => ({
      ports: { db: mockDb },
      user: { id: "user-1", role: "user" },
    }));

    const result = await tester.run(createTodo, { title: "Test" });

    expect(result).toEqual({
      id: "1",
      title: "Test",
      completed: false,
    });
    expect(mockDb.todos.create).toHaveBeenCalled();
  });
});

Related packages

License

MIT