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

@saleandwin/common

v1.0.5

Published

Common utilities for framework-ts projects

Downloads

9

Readme

@saleandwin/common

Common utilities for framework-ts projects, providing database transaction management, API response formatting, pagination, and batch validation functionality.

Installation

pnpm add @saleandwin/common

Features

  • TransactionBuilder: A powerful utility for building and executing batch database operations with Cloudflare D1
  • API Response Utilities: Standardized API response formatting for Next.js applications
  • Pagination Tools: Complete pagination parameter validation and response formatting
  • Batch Validator: Advanced validation framework for complex database operations
  • Cloudflare API Client: Complete Cloudflare API client with support for Zones, DNS, Pages, and Workers
  • Type-safe database operations
  • Built for Cloudflare Workers and Next.js environment

Usage

TransactionBuilder

The TransactionBuilder class helps you build and execute batch database operations atomically.

import { createTransaction, TransactionBuilder } from '@saleandwin/common';

// Using the factory function
const transaction = await createTransaction();

// Or create directly
const db = await getYourDatabase();
const transaction = new TransactionBuilder(db);

// Add statements to the transaction
transaction
  .add(db.prepare('INSERT INTO users (name) VALUES (?)').bind('John'))
  .add(db.prepare('INSERT INTO users (name) VALUES (?)').bind('Jane'))
  .addAll([
    db.prepare('UPDATE users SET active = ? WHERE id = ?').bind(true, 1),
    db.prepare('UPDATE users SET active = ? WHERE id = ?').bind(true, 2)
  ]);

// Execute all statements atomically
const results = await transaction.execute();

// Clear statements for reuse
transaction.clear();

API Response Utilities

Standardized API response formatting for Next.js applications.

import {
  createSuccessResponse,
  createErrorResponse,
  createAuthErrorResponse,
  validatePaginationParamsFromURL
} from '@saleandwin/common';

// Success response
return createSuccessResponse({ users: [] }, '获取成功');

// Error response
return createErrorResponse('用户不存在', 404);

// Auth error
return createAuthErrorResponse('请先登录');

Pagination Tools

Complete pagination parameter validation and response formatting.

import {
  validatePaginationParamsFromURL,
  calculatePaginationResult,
  createStandardResponse,
  PAGINATION_CONSTRAINTS
} from '@saleandwin/common';

// Validate pagination from URL
const { isValid, params, error } = validatePaginationParamsFromURL(searchParams);
if (!isValid) {
  return createErrorResponse(error);
}

// Calculate pagination result
const pagination = calculatePaginationResult(params.page, params.limit, totalCount);

// Create standardized response
return createStandardResponse('users', userData, pagination);

Batch Validator

Advanced validation framework for complex database operations.

import {
  BatchValidator,
  createBatchValidator,
  notExists,
  exists,
  validateUserStatus
} from '@saleandwin/common';

const validator = createBatchValidator();

const validationResult = await validator.validate([
  {
    name: 'checkUserExists',
    statement: db.prepare('SELECT * FROM users WHERE email = ?').bind(email),
    validator: notExists('用户已存在')
  },
  {
    name: 'checkInviteCode',
    statement: db.prepare('SELECT * FROM invite_codes WHERE code = ?').bind(code),
    validator: validateInviteCode()
  }
]);

if (!validationResult.valid) {
  return createErrorResponse(validationResult.error);
}

Cloudflare API Client

Complete Cloudflare API client with support for Zones, DNS, Pages, and Workers management.

import { CloudflareApiClient } from '@saleandwin/common';

// Initialize client
const client = new CloudflareApiClient({
  apiToken: 'your-api-token',
  accountId: 'your-account-id'
});

// Zone management
const zones = await client.getZones();
const newZone = await client.createZone({
  name: 'example.com',
  jump_start: true
});

// DNS management
const dnsRecords = await client.getDnsRecords(zoneId);
const newRecord = await client.createDnsRecord(zoneId, {
  type: 'A',
  name: 'www',
  content: '192.168.1.1',
  proxied: true
});

// Pages management
const projects = await client.getPagesProjects();
const newProject = await client.createPagesProject({
  name: 'my-site',
  production_branch: 'main'
});

// Worker management
const workers = await client.getWorkerScripts();
await client.createWorkerScript('my-worker', {
  script: 'export default { fetch() { return new Response("Hello!"); } }'
});

// Utility methods
const isConnected = await client.checkConnection();
const accountId = await client.getAccountId();

API Reference

TransactionBuilder

Static Methods
  • createInstance(): Promise<TransactionBuilder> - Creates a new instance with automatic database connection
Instance Methods
  • add(statement: D1PreparedStatement): this - Add a single statement to the transaction
  • addAll(statements: D1PreparedStatement[]): this - Add multiple statements to the transaction
  • execute(): Promise<D1Result[]> - Execute all statements atomically
  • clear(): this - Clear all statements from the transaction
  • count(): number - Get the number of statements in the transaction
Factory Function
  • createTransaction(): Promise<TransactionBuilder> - Convenience function to create a new TransactionBuilder instance

Requirements

  • Node.js >= 18.0.0
  • Cloudflare Workers environment
  • @opennextjs/cloudflare peer dependency

Development

# Install dependencies
pnpm install

# Build the package
pnpm run build

# Run tests
pnpm test

# Watch mode for development
pnpm run dev

License

MIT