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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tratta/blocks

v0.6.0

Published

A JavaScript library for integrating Tratta Blocks into your web application, providing secure, iframe-based payment form components with advanced validation and real-time feedback.

Readme

Tratta Blocks

A JavaScript library for integrating Tratta Blocks into your web application, providing secure, iframe-based payment form components with advanced validation and real-time feedback.

Installation

npm install @tratta/blocks

Then import the library in your JavaScript:

import Tratta from '@tratta/blocks';

Quick Start

// Initialize Tratta with your public key
const tratta = Tratta('your_public_key_here');

// Create blocks instance
const blocks = tratta.blocks();

// Create a card block with pre-filled values
const cardBlock = blocks.create('card', {
  hidePostalCode: false,
  hideCardHolder: false,
  value: {
    cardholderName: 'John Doe',
    postalCode: '12345'
  }
});

// Mount the card block to a container
cardBlock.mount('#card-block-container');

// Listen for form completion
cardBlock.on('change', (event) => {
  if (event.complete) {
    // Form is complete and valid - enable submit button
    submitButton.disabled = false;
  }
});

// Handle form submission
submitButton.addEventListener('click', async () => {
  try {
    // Create token using the card block
    const result = await tratta.createToken(cardBlock);
    
    if (result.error) {
      console.error('Error:', result.error);
      if (result.errors) {
        // Handle validation errors
        console.error('Validation errors:', result.errors);
      }
    } else {
      console.log('Token created:', result.id);
      console.log('Token type:', result.type);
      console.log('Card details:', result.card);
    }
  } catch (error) {
    console.error('Error:', error);
  }
});

API Reference

Tratta(publicKey, options)

Creates a new Tratta instance.

Parameters:

  • publicKey (string, required): Your Tratta public key
  • options (object, optional): Configuration options
    • environment (string): Environment to use ('sandbox', 'production')

Returns: Tratta instance

tratta.blocks(options)

Creates a blocks instance for creating payment blocks.

Parameters:

  • options (object, optional): Global options for all blocks

Returns: Blocks instance

tratta.createToken(block)

Creates a token using the provided block.

Parameters:

  • block (Block instance, required): The block instance to create a token from

Returns: Promise that resolves with token data containing id, type, card, and created_at properties, or error object with error property

Example:

const result = await tratta.createToken(cardBlock);

if (result.error) {
  console.error('Error:', result.error);
  if (result.errors) {
    // Handle validation errors
    console.error('Validation errors:', result.errors);
  }
} else {
  console.log('Token ID:', result.id);
  console.log('Token type:', result.type);
  console.log('Card details:', result.card);
  console.log('Created at:', result.created_at);
}

Response Structure:

{
  id: "pm_1234567890abcdef",
  type: "card",
  card: {
    card_holder: "John Doe",           // Cardholder name (optional)
    card_number: "1234",               // Last 4 digits of card number
    expiration_month: "12",            // Expiration month
    expiration_year: "25",             // Expiration year (2 digits)
    card_type: "visa",                 // Card type (visa, mastercard, etc.)
    card_zip: "12345"                  // Postal code (if provided)
  },
  created_at: "2024-01-15 10:30:00"
}

blocks.create(type, options)

Creates a specific block.

Parameters:

  • type (string, required): Block type ('card')
  • options (object, optional): Block-specific options

Returns: Block instance

Block Methods

mount(container)

Mounts the block to a DOM container.

Parameters:

  • container (string|Element): CSS selector or DOM element

Returns: Block instance

unmount()

Unmounts the block from the DOM. The block can be re-mounted later.

Returns: Block instance

update(options)

Updates the block configuration.

Parameters:

  • options (object): New configuration options

Returns: Block instance

focus()

Focuses the block.

Returns: Block instance

blur()

Removes focus from the block.

Returns: Block instance

clear()

Clears the block values.

Returns: Block instance

destroy()

Destroys the block and removes it from the DOM. Cannot be re-mounted.

Returns: Block instance

Event Handling

on(event, handler)

Attaches an event handler to the block.

Events:

  • ready: Block is ready for interaction
  • change: Block values have changed
  • focus: Block has received focus
  • blur: Block has lost focus
  • escape: Escape key was pressed within the block

Returns: Block instance

off(event)

Removes an event handler from the block.

Returns: Block instance

onMessage(type, handler)

Attaches a custom message handler for iframe communication.

Parameters:

  • type (string): Message type to listen for
  • handler (function): Handler function

Returns: Block instance

Block Types

Card Block

The card block provides a secure way to collect card information through an iframe with advanced validation and real-time feedback.

Pre-filling Fields

You can pre-fill non-sensitive fields to improve user experience. Only the cardholder name and postal code can be pre-filled - sensitive card information (card number, CVC, and expiration date) cannot be pre-filled for security reasons.

const cardBlock = blocks.create('card', {
  hidePostalCode: false,
  hideCardholder: false,
  value: {
    cardholderName: 'John Doe',    // Pre-fill cardholder name
    postalCode: '12345'            // Pre-fill postal code
  }
});

Important Notes:

  • Pre-filled values are only applied when the corresponding fields are visible (not hidden)
  • Values are set when the block is initialized
  • Users can still modify pre-filled values
  • Pre-filling does not affect validation - all validation rules still apply
const cardBlock = blocks.create('card');

Features:

  • Secure iframe implementation - Card data never touches your server
  • Real-time validation - Instant feedback on card number, expiration, CVV, postal code, and cardholder name
  • Card network detection - Automatically detects and validates supported card networks
  • BIN validation - Validation of card issuer and type
  • Optional cardholder name - Cardholder name field is optional for enhanced flexibility
  • Dynamic height adjustment - Automatically resizes based on content
  • Accessibility support - Screen reader friendly with proper ARIA attributes
  • Mobile responsive - Optimized for touch devices

CardBlock Options

const cardBlock = blocks.create('card', {
  hidePostalCode: true,     // Hide the postal code field. Default is true.
  hideCardholder: true,     // Hide the cardholder name field. Default is true.
  value: {                  // Pre-fill values for non-sensitive fields
    cardholderName: 'John Doe',
    postalCode: '12345'
  }
});

Options:

  • hidePostalCode (boolean): Hide the postal code field. Default is true.
  • hideCardholder (boolean): Hide the cardholder name field. Default is true.
  • value (object): Pre-filled values for non-sensitive fields. Note that sensitive card information (card number, CVC, and expiration date) cannot be pre-filled.
    • cardholderName (string): Pre-fill the cardholder name field
    • postalCode (string): Pre-fill the postal code field

CardBlock Events

The card block emits detailed change events with comprehensive form state:

cardBlock.on('change', (event) => {
  console.log('Form state:', {
    empty: event.empty,           // true if no fields have values
    complete: event.complete,     // true if all required fields are valid
    error: event.error,           // validation errors object or null
    blockType: event.blockType    // 'card'
  });
});

Environments

The library supports multiple environments:

  • sandbox: https://sandbox.tratta.com - For testing and development
  • production: https://app.tratta.com - For live applications
// Initialize with sandbox environment
const tratta = Tratta('pk_test_key', { environment: 'sandbox' });

// Initialize with production environment
const tratta = Tratta('pk_live_key', { environment: 'production' });

Demo

See the demo/index.html file for complete working examples.

Error Handling

The library provides comprehensive error handling with detailed validation feedback.

Error Types

All validation errors follow a consistent format:

const result = await tratta.createToken(cardBlock);

if (result.error) {
  console.error('Error:', result.error);
  if (result.errors) {
    // Handle field-specific validation errors
    Object.entries(result.errors).forEach(([field, messages]) => {
      console.error(`${field}:`, messages);
    });
  }
} else {
  console.log('Token ID:', result.id);
  console.log('Token type:', result.type);
}

Validation Messages

The library provides user-friendly validation messages for all card fields:

  • Card Number: Required, invalid format, unsupported network, card type restrictions
  • Expiration Date: Required, invalid format, invalid month/year
  • Security Code: Required, invalid format, length validation based on card type
  • Cardholder Name: Optional, invalid format (when provided)
  • Postal Code: Required (when visible), invalid format

Error Format

All error objects follow a consistent format:

{
  error: 'Validation failed',
  errors: {
    card_number: ['Your card number is invalid.'],
    card_expiration: ['Your card\'s expiration date is required.'],
    card_security_code: ['Your card\'s security code is invalid.'],
    card_holder: ['Your cardholder name is invalid.'],
    postal_code: ['Your postal code is required.']
  }
}

Security Features

Iframe Security

  • Sandboxed execution - Restricted iframe permissions for enhanced security
  • Cross-origin isolation - Card data never accessible to parent page
  • Secure communication - PostMessage API with origin validation
  • No sensitive data exposure - Card details never logged or stored in parent context

Validation Layers

  • Client-side validation - Real-time feedback for immediate user experience
  • Server-side validation - Comprehensive validation including BIN checks
  • Card network validation - Automatic detection and validation of supported networks
  • Type restrictions - Configurable card type and network restrictions

Styling

The card block provides a pre-styled, secure iframe that automatically adapts to your container:

#card-block {
  background-color: white;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  padding: 1rem;
  width: 100%;
  max-width: 800px;
}

Key styling features:

  • Automatic height adjustment - Dynamically resizes based on content
  • Responsive design - Adapts to container width
  • Consistent branding - Can be styled to match your brand colors
  • Smooth transitions - Height changes are animated for better UX

Browser Support

  • Chrome 105+ (2022)
  • Firefox 121+ (2023)
  • Safari 15.4+ (2022)
  • Edge 105+ (2022)

Note: The library uses modern JavaScript features (ES6+) and CSS features. For older browsers, some styling features may not work as expected, but core functionality remains available.

License

MIT License - see the LICENSE file for details.