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

@zen_tools/x-sdk

v2.0.9

Published

TypeScript SDK for Twitter/X API with OAuth 1.0a support

Readme

X SDK for TypeScript

A TypeScript SDK for the Twitter/X API v2 with OAuth 1.0a authentication support.

Features

  • ✅ OAuth 1.0a authentication with automatic request signing
  • ✅ Post tweets (POST /2/tweets)
  • ✅ Full TypeScript type safety
  • ✅ Comprehensive error handling with retry information
  • ✅ Promise-based async/await API
  • ✅ Built on axios for reliable HTTP handling

Installation

npm install @zen_tools/x-sdk
# or
yarn add @zen_tools/x-sdk

Quick Start

import { XClient, createTweetRequest } from '@zen_tools/x-sdk';

// Create client with credentials
const client = new XClient({
  credentials: {
    appKey: 'your_app_key',
    appSecret: 'your_app_secret',
    accessToken: 'your_access_token',
    accessSecret: 'your_access_secret',
  },
});

// Post a tweet
const tweet = createTweetRequest('Hello from TypeScript! 🚀');
const response = await client.tweets().post(tweet);
console.log('Tweet posted! ID:', response.data.id);

Examples

Basic Tweet Posting

import { XClient, createTweetRequest } from '@zen_tools/x-sdk';

async function postTweet() {
  const client = new XClient({
    credentials: {
      appKey: process.env.X_APP_KEY!,
      appSecret: process.env.X_APP_SECRET!,
      accessToken: process.env.X_ACCESS_TOKEN!,
      accessSecret: process.env.X_ACCESS_SECRET!,
    },
  });

  const tweet = createTweetRequest('Hello, X!');
  const response = await client.tweets().post(tweet);

  console.log('Tweet ID:', response.data.id);
  console.log('Tweet text:', response.data.text);
}

Error Handling

import { XClient, createTweetRequest, XError, XErrorCode } from '@zen_tools/x-sdk';

async function postWithErrorHandling() {
  const client = new XClient({
    credentials: {
      appKey: process.env.X_APP_KEY!,
      appSecret: process.env.X_APP_SECRET!,
      accessToken: process.env.X_ACCESS_TOKEN!,
      accessSecret: process.env.X_ACCESS_SECRET!,
    },
  });

  try {
    const tweet = createTweetRequest('Hello!');
    const response = await client.tweets().post(tweet);
    console.log('Success:', response.data.id);
  } catch (error) {
    if (error instanceof XError) {
      switch (error.code) {
        case XErrorCode.RATE_LIMIT_EXCEEDED:
          console.error('Rate limited:', error.message);
          const retryAfter = error.getRetryDelay();
          if (retryAfter) {
            console.error(`Retry after ${retryAfter} seconds`);
          }
          break;

        case XErrorCode.AUTHENTICATION_FAILED:
          console.error('Authentication failed:', error.message);
          break;

        case XErrorCode.INVALID_REQUEST:
          console.error('Invalid request:', error.message);
          break;

        default:
          console.error('Error:', error.message);
      }
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

Custom Configuration

import { XClient } from '@zen_tools/x-sdk';

const client = new XClient({
  credentials: {
    appKey: 'your_app_key',
    appSecret: 'your_app_secret',
    accessToken: 'your_access_token',
    accessSecret: 'your_access_secret',
  },
  timeout: 60000, // 60 seconds
  baseUrl: 'https://api.twitter.com', // Custom base URL (if needed)
});

API Documentation

XClient

Main client for interacting with the X API.

const client = new XClient({
  credentials: {
    appKey: string;
    appSecret: string;
    accessToken: string;
    accessSecret: string;
  },
  timeout?: number;  // Default: 30000ms
  baseUrl?: string;  // Default: 'https://api.twitter.com'
});

createTweetRequest(text: string): TweetRequest

Create and validate a tweet request.

const tweet = createTweetRequest('Hello, world!');

Validates that:

  • Text is not empty
  • Text does not exceed 280 characters

TweetResponse

Response from posting a tweet.

interface TweetResponse {
  data: {
    id: string;
    text: string;
    edit_history_tweet_ids?: string[];
  };
}

Error Handling

All operations throw XError on failure:

class XError extends Error {
  code: XErrorCode;
  details: XErrorDetails;
  cause?: Error;

  isRetryable(): boolean;
  getRetryDelay(): number | null;
}

Error Codes:

  • AUTHENTICATION_FAILED - Invalid credentials (401, 403)
  • RATE_LIMIT_EXCEEDED - Rate limit hit (429)
  • INVALID_REQUEST - Bad request (400, 422)
  • NETWORK_ERROR - Network failure
  • API_ERROR - Other API errors
  • UNKNOWN_ERROR - Unexpected errors

Check if an error is retryable:

if (error instanceof XError && error.isRetryable()) {
  const delay = error.getRetryDelay();
  // Wait and retry
}

Running Examples

Set your credentials as environment variables:

export X_APP_KEY="your_app_key"
export X_APP_SECRET="your_app_secret"
export X_ACCESS_TOKEN="your_access_token"
export X_ACCESS_SECRET="your_access_secret"

Run the example:

npm install
npx ts-node examples/post-tweet.ts "Your tweet text here"

Testing

Run the test suite:

npm test

Run tests with coverage:

npm run test:coverage

Building

Build the project:

npm run build

This will compile TypeScript to JavaScript in the dist/ directory.

License

MIT

References