### Install Project Dependencies Source: https://github.com/braintree/credit-card-type/blob/main/CONTRIBUTING.md Install the project's dependencies using npm. This is a required step before development. ```bash npm install ``` -------------------------------- ### Install Node.js and Dependencies Source: https://github.com/braintree/credit-card-type/blob/main/README.md Install the required Node.js version using `nvm` and then install project dependencies with `npm install`. ```bash nvm install npm install ``` -------------------------------- ### matches() Examples Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Illustrates the behavior of the `matches` function with different pattern types and card numbers. Shows examples for exact prefix matching and range matching. ```plaintext Pattern: 4 cardNumber "4111" => true cardNumber "4" => true cardNumber "3" => false Pattern: [51, 55] cardNumber "5111" => true (51 in range) cardNumber "5" => true (5 in range 51-55 when comparing first digit) cardNumber "5611" => false (56 not in 51-55) ``` -------------------------------- ### Install credit-card-type via npm Source: https://github.com/braintree/credit-card-type/blob/main/README.md Use npm to install the credit-card-type library. This is the standard method for adding the package to your project. ```bash npm install credit-card-type ``` -------------------------------- ### Partial Matching Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md All patterns support partial matching for type-as-you-go detection, where a card number is matched if it starts with the pattern sequence. ```text Card: 401178 (Elo) Pattern: 401178 (exact) - "4" matches (starts with 4) - "40" matches (starts with 40) - "401" matches (starts with 401) - "4011" matches (starts with 4011) - "40117" matches (starts with 40117) - "401178" matches (complete) - "4011780" does NOT match (4011780 > 401178 numerically) ``` -------------------------------- ### File Structure Overview Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/DOCUMENTATION_INDEX.md This snippet shows the directory structure of the credit-card-type documentation. It serves as a navigation guide to the various documentation files. ```markdown ``` /output/ ├── README.md [Start here - Overview and quick reference] ├── DOCUMENTATION_INDEX.md [This file] ├── module-overview.md [Architecture and design] ├── imports-exports.md [All import/export patterns] ├── types.md [Type definitions] ├── configuration.md [Card configuration reference] ├── errors.md [Error cases and handling] └── api-reference/ ├── credit-card-type.md [Main detection function] ├── get-type-info.md [Card configuration retrieval] ├── add-card.md [Adding custom card types] ├── update-card.md [Modifying card configurations] ├── remove-card.md [Removing card types] ├── change-order.md [Detection priority management] ├── reset-modifications.md [Restoring default state] ├── card-types.md [Card type constants] ├── internal-functions.md [Non-public utility functions] └── usage-patterns.md [13 practical implementation patterns] ``` ``` -------------------------------- ### getTypeInfo Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Get configuration for a card type. ```APIDOC ## getTypeInfo ### Description Get configuration for a card type. ### Signature `getTypeInfo(type: string): CreditCardType | undefined` ``` -------------------------------- ### Batch Processing Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Process multiple card numbers efficiently in a batch. This pattern is useful for analyzing large datasets of card numbers. ```javascript const creditCardType = require("@braintree/credit-card-type"); const cardNumbers = [ '4111111111111111', '5100000000000000', '3711111111111111', 'invalidnumber' ]; const results = cardNumbers.map(number => ({ number: number, type: creditCardType(number)[0] ? creditCardType(number)[0].niceType : 'Unknown' })); console.log(results); // Output: [ // { number: '4111111111111111', type: 'Visa' }, // { number: '5100000000000000', type: 'Mastercard' }, // { number: '3711111111111111', type: 'American Express' }, // { number: 'invalidnumber', type: 'Unknown' } // ] ``` -------------------------------- ### Type-as-You-Go Detection Examples Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Demonstrates real-time credit card type detection as users input partial card numbers. The library returns matching types based on the input length and pattern specificity. ```typescript creditCardType("4") // [Visa, Maestro, Hiper, ...] creditCardType("41") // [Visa, ...] creditCardType("4111") // [Visa] (all matches have matchStrength set) creditCardType("4111111111111111") // [Visa] (full card) ``` -------------------------------- ### CreditCardType Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/types.md An example demonstrating the structure of a CreditCardType object, including patterns, lengths, and security code details. This is used to define specific card types like Visa and Mastercard. ```typescript const collection: CardCollection = { visa: { niceType: "Visa", type: "visa", patterns: [4], gaps: [4, 8, 12], lengths: [16, 18, 19], code: { name: "CVV", size: 3 } }, mastercard: { niceType: "Mastercard", type: "mastercard", patterns: [[51, 55], [2221, 2229]], gaps: [4, 8, 12], lengths: [16], code: { name: "CVC", size: 3 } } }; ``` -------------------------------- ### creditCardType() Return Type Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Demonstrates calling `creditCardType()` with a card number and shows the expected return type, which is an array of `CreditCardType` objects. ```typescript import creditCardType from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; const result: CreditCardType[] = creditCardType("4111"); ``` -------------------------------- ### Payment Form Input Detection Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Example for detecting credit card types in real-time as a user types into a payment form input. It handles unambiguous, multiple, and no matches. ```typescript import creditCardType, { types } from "credit-card-type"; function onCardNumberChange(input: string) { const matches = creditCardType(input); if (matches.length === 1) { // Unambiguous const cardType = matches[0].type; if (cardType === types.AMERICAN_EXPRESS) { // Show 4-digit security code input } else { // Show 3-digit security code input } } else if (matches.length > 1) { // Multiple possible types const formatted = matches .map(c => c.niceType) .join(" or "); console.log(`Could be: ${formatted}`); } } ``` -------------------------------- ### Resetting Credit Card Type Modifications Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/reset-modifications.md This example demonstrates how to add custom cards, modify their order and properties, and then reset all these modifications using `resetModifications()`. It shows the state before and after the reset to verify the changes. ```typescript import creditCardType from "credit-card-type"; // Add custom cards creditCardType.addCard({ niceType: "Custom Card", type: "custom-card", patterns: [2000], gaps: [4, 8, 12], lengths: [16], code: { name: "CVV", size: 3 }, }); // Modify test order creditCardType.changeOrder("custom-card", 0); // Update Visa creditCardType.updateCard("visa", { niceType: "Modified Visa", lengths: [11, 16], }); // Custom card is detected first const before = creditCardType("2000"); console.log(before[0].type); // "custom-card" // Reset all modifications creditCardType.resetModifications(); // Custom card is gone const after = creditCardType("2000"); console.log(after.length); // 0 (no match for 2000) // Original test order restored const visa = creditCardType.getTypeInfo("visa"); console.log(visa.niceType); // "Visa" (original) console.log(visa.lengths); // [16, 18, 19] (original) // Error: Custom card no longer exists try { creditCardType.getTypeInfo("custom-card"); } catch (e) { console.log(e); // undefined (not found) } ``` -------------------------------- ### getTypeInfo() Return Type Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Shows how to use `getTypeInfo()` to retrieve card details by type ID and emphasizes checking for a truthy return value before accessing properties like `niceType`. ```typescript import { getTypeInfo } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; const card: CreditCardType | undefined = getTypeInfo("visa"); if (card) { console.log(card.niceType); } ``` -------------------------------- ### Card Formatting Example Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Provides a function to format a credit card number string with spaces based on the card type's defined gaps. Requires the card type ID. ```typescript import { getTypeInfo } from "credit-card-type"; function formatCardNumber(number: string, typeId: string): string { const card = getTypeInfo(typeId); if (!card) return number; const offsets = [0, ...card.gaps, number.length]; const parts = []; for (let i = 0; offsets[i] < number.length; i++) { const start = offsets[i]; const end = Math.min(offsets[i + 1], number.length); parts.push(number.substring(start, end)); } return parts.join(" "); } ``` -------------------------------- ### Card Type Information Example Source: https://github.com/braintree/credit-card-type/blob/main/README.md This JSON object shows the detailed information returned for a detected Visa card, including its type, number gaps, lengths, and security code details. ```json { "niceType": "Visa", "type": "visa", "gaps": [4, 8, 12], "lengths": [16], "code": { "name": "CVV", "size": 3 } } ``` -------------------------------- ### Handle Nonexistent Card Type Error Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/update-card.md This example demonstrates the error thrown when attempting to update a card type that does not exist. Use `addCard()` for new types. ```typescript // Error: Card type must exist creditCardType.updateCard("nonexistent-card", { niceType: "Bad Update", }); // Throws: '"nonexistent-card" is not a recognized type. Use `addCard` instead.' ``` -------------------------------- ### Get Card Type Information Source: https://github.com/braintree/credit-card-type/blob/main/README.md Retrieve detailed information about a specific card type using `getTypeInfo`. This is useful for verifying updates. ```javascript var visa = creditCardType.getTypeInfo(creditCardType.types.VISA); ``` -------------------------------- ### Get All Available Card Types Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Returns a clone of all available card types in the current test order. This is used to prevent external modification of card type data. ```typescript function getAllCardTypes(): CreditCardType[] ``` -------------------------------- ### Error handling for non-existent card type Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/remove-card.md This example shows the error that occurs when attempting to remove a card type that does not exist in the detection list. ```typescript // Error: Card type does not exist creditCardType.removeCard("invalid-card"); // Throws: '"invalid-card" is not a supported card type.' ``` -------------------------------- ### Get Credit Card Type Information Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/get-type-info.md Fetches the configuration object for a given card type identifier. Use this to access details like gaps, lengths, and code information. Returns `undefined` if the type is not recognized. ```typescript import creditCardType from "credit-card-type"; // Get Visa configuration const visa = creditCardType.getTypeInfo("visa"); console.log(visa.niceType); // "Visa" console.log(visa.gaps); // [4, 8, 12] console.log(visa.lengths); // [16, 18, 19] console.log(visa.code); // { name: "CVV", size: 3 } ``` ```typescript // Using card type constants const amex = creditCardType.getTypeInfo(creditCardType.types.AMERICAN_EXPRESS); console.log(amex.code.size); // 4 ``` ```typescript // Invalid type returns undefined const unknown = creditCardType.getTypeInfo("invalid-type"); console.log(unknown); // undefined ``` -------------------------------- ### Overwrite an Existing Card Type Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/add-card.md This example demonstrates how to overwrite a built-in card type, such as 'visa', to extend its functionality, like adding support for additional card number lengths. The `type` property in the configuration must match the existing type identifier. ```typescript import creditCardType from "credit-card-type"; // Overwrite a built-in card type to extend or modify it creditCardType.addCard({ niceType: "Visa with Custom Lengths", type: "visa", // Use the built-in type identifier patterns: [4], gaps: [4, 8, 12], lengths: [13, 16, 18, 19], // Add support for older 13-digit Visas code: { name: "CVV", size: 3, }, }); // Modified Visa now supports 13-digit cards const newVisa = creditCardType.getTypeInfo("visa"); console.log(newVisa.lengths); // [13, 16, 18, 19] console.log(newVisa.niceType); // "Visa with Custom Lengths" ``` -------------------------------- ### Importing and Using Credit Card Type Functions Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/types.md Demonstrates importing necessary functions and types from the credit-card-type library. Shows how to use `creditCardType` for matching, `getTypeInfo` for specific card details, and accessing type identifiers. ```typescript import creditCardType, { getTypeInfo, types as CardType, } from "credit-card-type"; // CreditCardType returned from creditCardType() const matches: CreditCardType[] = creditCardType("4111"); // Single CreditCardType from getTypeInfo() const visa: CreditCardType = creditCardType.getTypeInfo("visa"); // Using type identifiers const cardId: CreditCardTypeCardBrandId = creditCardType.types.VISA; // Type filtering const filtered: CreditCardType[] = matches.filter( card => card.type === CardType.VISA ); // Accessing security code const codeLabel: CreditCardTypeSecurityCodeLabel = visa.code.name; const codeSize: 3 | 4 = visa.code.size; ``` -------------------------------- ### Import Patterns Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Demonstrates various ways to import the credit-card-type library, including main function only, destructured methods, namespace import, and with type imports. ```APIDOC ## Import Patterns ### Pattern 1: Main Function Only ```typescript import creditCardType from "credit-card-type"; creditCardType("4111"); // Works creditCardType.types.VISA; // Works creditCardType.getTypeInfo("visa"); // Works ``` ### Pattern 2: Destructured Methods ```typescript import creditCardType, { getTypeInfo, types } from "credit-card-type"; creditCardType("4111"); getTypeInfo("visa"); types.VISA; ``` ### Pattern 3: Namespace Import ```typescript import * as CardDetector from "credit-card-type"; CardDetector.default("4111"); CardDetector.getTypeInfo("visa"); CardDetector.types.VISA; ``` ### Pattern 4: With Type Imports ```typescript import creditCardType, { types } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; const result: CreditCardType[] = creditCardType("4111"); ``` ### Pattern 5: CommonJS with Types (TypeScript) ```typescript import creditCardType = require("credit-card-type"); import type { CreditCardType } from "credit-card-type"; const matches: CreditCardType[] = creditCardType("4111"); ``` ### Pattern 6: Named Types with Card Types ```typescript import creditCardType, { types as CardTypes } from "credit-card-type"; import type { CreditCardType, CreditCardTypeCardBrandId } from "credit-card-type"; const matches: CreditCardType[] = creditCardType("4111"); const id: CreditCardTypeCardBrandId = CardTypes.VISA; ``` ``` -------------------------------- ### Exact Pattern Matching Rule Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md An exact numeric pattern matches card numbers that start with the specified sequence. ```text Pattern: 4 Matches: "4", "41", "411", "4111", "41111111111111" Does not match: "5", "3", "421" ``` -------------------------------- ### Run Project Tests Source: https://github.com/braintree/credit-card-type/blob/main/CONTRIBUTING.md Execute the project's tests using npm. This command runs the test suite to ensure code quality. ```bash npm test ``` -------------------------------- ### ES6 Namespace Import Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Import the library as a namespace using ES6 syntax. ```javascript import * as braintreeCardType from "@braintree/credit-card-type"; ``` -------------------------------- ### Add Custom Card and Change Order Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/change-order.md Demonstrates adding a custom card type and then setting it as the highest priority using `changeOrder()`. It also shows how to move an existing card type to a middle position and how resetting modifications restores the default order. ```typescript import creditCardType from "credit-card-type"; // Give custom card highest priority creditCardType.addCard({ niceType: "Priority Card", type: "priority-card", patterns: [4], // Same pattern as Visa gaps: [4, 8, 12], lengths: [16], code: { name: "CVV", size: 3 }, }); // Move custom card to position 0 (highest priority) creditCardType.changeOrder("priority-card", 0); // Cards starting with 4 now match priority-card first const matches = creditCardType("4111"); console.log(matches[0].type); // "priority-card" // Move a card to a middle position creditCardType.changeOrder("discover", 3); // Reset and check default order creditCardType.resetModifications(); const defaultMatches = creditCardType("4111"); console.log(defaultMatches[0].type); // "visa" (restored default) // Error: Card type does not exist creditCardType.changeOrder("nonexistent", 0); // Throws: '"nonexistent" is not a supported card type.' // Lower priority (higher position) creditCardType.changeOrder("visa", 13); // Move Visa to near the end const afterLower = creditCardType("4111"); console.log(afterLower[0].type); // Different card type (depends on overlapping patterns) ``` -------------------------------- ### Get Card Type Information Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Retrieve configuration details for a specific card type using its identifier. Returns undefined if the type is not found. ```typescript getTypeInfo: (type: string) => CreditCardType | undefined ``` -------------------------------- ### Get Card Type Information Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Retrieves detailed information about a specific card type using its identifier. The `code` property contains the security code length. ```typescript creditCardType.getTypeInfo("visa").code; ``` -------------------------------- ### Get Card Type Information Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/module-overview.md Retrieve detailed information about a specific card type, such as formatting gaps. Use this to format card numbers according to the card's specifications. ```typescript const card = creditCardType.getTypeInfo("visa"); // Use card.gaps to insert spaces ``` -------------------------------- ### Import All Available Types Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Import all main types, brand identifier unions, and card collection maps from the 'credit-card-type' library. ```typescript import type { // Main types CreditCardType, BuiltInCreditCardType, // Brand identifier union CreditCardTypeCardBrandId, // Card collection map CardCollection } from "credit-card-type"; ``` -------------------------------- ### ES6 Default Import Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Import the library using ES6 default import syntax. ```javascript import creditCardType from "@braintree/credit-card-type"; ``` -------------------------------- ### Get Card Position in Test Order Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Finds the position of a card type within the test order array. It can optionally ignore errors for non-existent cards, returning -1 in such cases. ```typescript function getCardPosition( name: string, ignoreErrorForNotExisting = false ): number ``` -------------------------------- ### Import Main Function Only Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Import only the default export for basic usage. This is suitable when you only need the primary function. ```typescript import creditCardType from "credit-card-type"; creditCardType("4111"); // Works creditCardType.types.VISA; // Works creditCardType.getTypeInfo("visa"); // Works ``` -------------------------------- ### CommonJS Default Import Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Import the library using CommonJS default import syntax. ```javascript const creditCardType = require("@braintree/credit-card-type"); ``` -------------------------------- ### Discover Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Discover cards. ```typescript { niceType: "Discover", type: "discover", patterns: [6011, [644, 649], 65], gaps: [4, 8, 12], lengths: [16, 19], code: { name: "CID", size: 3 } } ``` -------------------------------- ### Determine credit card type from number Source: https://github.com/braintree/credit-card-type/blob/main/README.md Call the `creditCardType` function with a normalized card number string to get an array of matching card types. The first element in the array represents the most likely match. ```javascript var creditCardType = require("credit-card-type"); // The card number provided should be normalized prior to usage here. var visaCards = creditCardType("4111"); console.log(visaCards[0].type); // 'visa' var ambiguousCards = creditCardType("6"); console.log(ambiguousCards.length); // 6 console.log(ambiguousCards[0].niceType); // 'Discover' console.log(ambiguousCards[1].niceType); // 'UnionPay' console.log(ambiguousCards[2].niceType); // 'Maestro' ``` -------------------------------- ### Adding Custom Cards Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Demonstrates how to define and add a custom credit card type to the library using `creditCardType.addCard()`. Requires defining `niceType`, `type`, `patterns`, `gaps`, `lengths`, and `code` properties. ```typescript import creditCardType, { types as CardType } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; const customCard: CreditCardType = { niceType: "Corporate Card", type: "corp-card", patterns: [5555], gaps: [4, 8, 12], lengths: [16], code: { name: "CVV", size: 3 } }; creditCardType.addCard(customCard); ``` -------------------------------- ### matchesPattern() Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Tests for exact prefix matching of a card number against a given pattern. ```APIDOC ## matchesPattern() ### Description Tests exact prefix matching. ### Signature ```typescript function matchesPattern(cardNumber: string, pattern: string | number): boolean ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **cardNumber** (string) - Required - The card number to test. - **pattern** (string | number) - Required - The pattern to match against. ### Return Type `boolean` ### Behavior - Converts pattern to string. - Compares the first N characters of both (where N is the minimum of lengths). - Returns true if they match. ### Examples ``` matchesPattern("4111", "4"); // true matchesPattern("4", "4"); // true matchesPattern("3", "4"); // false ``` ``` -------------------------------- ### Custom Card Support - Add Card Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Add support for custom card types by providing their patterns, lengths, and other details. Use `addCard` method. ```javascript const creditCardType = require("@braintree/credit-card-type"); creditCardType.addCard({ type: 'mycustomcard', niceType: 'My Custom Card', patterns: [123456], gaps: [6, 12], lengths: [16], code: { name: 'CVV', size: 3 } }); console.log(creditCardType('1234567890123456')); // Output will include My Custom Card if it matches the pattern ``` -------------------------------- ### Elo Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Elo cards. ```typescript { niceType: "Elo", type: "elo", patterns: [ 401178, 401179, 438935, 457631, 457632, 431274, 451416, 457393, 504175, [506699, 506778], [509000, 509999], 627780, 636297, 636368, [650031, 650033], [650035, 650051], [650405, 650439], [650485, 650538], [650541, 650598], [650700, 650718], [650720, 650727], [650901, 650978], [651652, 651679], [655000, 655019], [655021, 655058] ], gaps: [4, 8, 12], lengths: [16], code: { name: "CVE", size: 3 } } ``` -------------------------------- ### ES6 Module Imports Source: https://github.com/braintree/credit-card-type/blob/main/README.md Import the credit-card-type library and its components using ES6 module syntax. ```javascript import creditCardType, { getTypeInfo, types as CardType, } from "credit-card-type"; ``` -------------------------------- ### Import with Type Annotations Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Import both the default export and types for strong typing. This is recommended for TypeScript projects to ensure type safety. ```typescript import creditCardType, { types } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; const result: CreditCardType[] = creditCardType("4111"); ``` -------------------------------- ### Add Custom Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/module-overview.md Extend the library's functionality by adding support for custom card types. Use this method to define new card configurations. ```typescript creditCardType.addCard({ /* custom config */ }); ``` -------------------------------- ### Package.json Module Resolution Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md This JSON configuration specifies the main entry point for CommonJS environments and the location of TypeScript type definitions. ```json { "main": "dist/index.js", "types": "dist/index.d.ts" } ``` -------------------------------- ### Type-as-You-Go Detection Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/module-overview.md Detect credit card types incrementally as the user types. This snippet shows how the library handles partial card numbers. ```typescript creditCardType("4") // Visa creditCardType("41") // Visa creditCardType("411") // Visa creditCardType("4111") // Visa ``` -------------------------------- ### Handle Unsupported Card Type Errors Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/errors.md Demonstrates how to catch errors when attempting to remove or reorder unsupported card types. Use built-in constants or add cards before modification. ```typescript import creditCardType from "credit-card-type"; try { creditCardType.removeCard("nonexistent-card"); } catch (error) { console.error(error.message); // '"nonexistent-card" is not a supported card type.' } try { creditCardType.changeOrder("invalid-type", 0); } catch (error) { console.error(error.message); // '"invalid-type" is not a supported card type.' } ``` -------------------------------- ### Type-as-You-Go Card Detection for UI Updates Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/usage-patterns.md Update UI elements like card type icons and security code labels in real-time as a user types a card number. This pattern involves removing non-digit characters from input and handling multiple potential matches. ```typescript import creditCardType, { types } from "credit-card-type"; function handleCardInput(event: Event) { const input = event.target as HTMLInputElement; const cardNumber = input.value.replace(/\D/g, ""); // Remove non-digits const matches = creditCardType(cardNumber); // Update card type icon updateCardIcon(matches); // Update security code label updateSecurityCodeLabel(matches); // Show formatting hint updateFormattingHint(matches); } function updateCardIcon(matches: any[]) { const icon = document.getElementById("card-icon"); if (matches.length === 0) { icon.textContent = "❓ Unknown"; icon.className = "unknown"; } else if (matches.length === 1) { const card = matches[0]; icon.textContent = card.niceType; icon.className = card.type; } else { const names = matches.map(c => c.niceType).join(" / "); icon.textContent = names; icon.className = "ambiguous"; } } function updateSecurityCodeLabel(matches: any[]) { const label = document.getElementById("cvc-label"); if (matches.length === 1) { const codeInfo = matches[0].code; label.textContent = `${codeInfo.name} (${codeInfo.size} digits)`; } else { label.textContent = "Security Code"; } } ``` -------------------------------- ### Maestro Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Maestro cards. ```typescript { niceType: "Maestro", type: "maestro", patterns: [493698, [500000, 504174], [504176, 506698], [506779, 508999], [56, 59], 63, 67, 6], gaps: [4, 8, 12], lengths: [12, 13, 14, 15, 16, 17, 18, 19], code: { name: "CVC", size: 3 } } ``` -------------------------------- ### CommonJS Module Imports Source: https://github.com/braintree/credit-card-type/blob/main/README.md Import the necessary functions and types from the credit-card-type library using CommonJS syntax. ```javascript var creditCardType = require("credit-card-type"); var getTypeInfo = require("credit-card-type").getTypeInfo; var CardType = require("credit-card-type").types; ``` -------------------------------- ### Handle Unrecognized Card Type for Update Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/errors.md Shows how to catch errors when trying to update a card type that is not recognized. Ensure the card type exists or add it using `addCard()` first. ```typescript import creditCardType from "credit-card-type"; try { creditCardType.updateCard("unknown-card-type", { niceType: "Updated Name" }); } catch (error) { console.error(error.message); // '"unknown-card-type" is not a recognized type. Use `addCard` instead.' } ``` -------------------------------- ### Type-as-You-Go Detection Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/COMPLETION_SUMMARY.txt Detect card type dynamically as the user types. Useful for real-time feedback in input fields. ```javascript const creditCardType = require("@braintree/credit-card-type"); const input = document.getElementById('card-number-input'); const cardDisplay = document.getElementById('card-type-display'); input.addEventListener('input', (event) => { const cardNumber = event.target.value; const cardTypes = creditCardType(cardNumber); if (cardTypes.length > 0) { cardDisplay.textContent = `Detected: ${cardTypes[0].niceType}`; } else { cardDisplay.textContent = ''; } }); ``` -------------------------------- ### Credit Card Type Detection Data Flow Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/module-overview.md Illustrates the step-by-step process of detecting a credit card type, from input validation to determining the best match. ```plaintext creditCardType("4111") ↓ isValidInputType() — Validates input is a string ↓ getAllCardTypes() — Returns all available types if empty string ↓ For each card type in testOrder: ↓ addMatchingCardsToResults() ↓ For each pattern in card.patterns: ↓ matches(cardNumber, pattern) ↓ matchesPattern() or matchesRange() ↓ [true/false] ↓ If matches: clone(card) Set matchStrength if pattern fully matched Add to results Break (first match per card wins) ↓ findBestMatch(results) ↓ If all results have matchStrength: Return card with highest matchStrength Else: Return null (ambiguous, multiple partials) ↓ If bestMatch found: Return [bestMatch] Else: Return results (all partial matches) ``` -------------------------------- ### Visa Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Visa cards. ```typescript { niceType: "Visa", type: "visa", patterns: [4], gaps: [4, 8, 12], lengths: [16, 18, 19], code: { name: "CVV", size: 3 } } ``` -------------------------------- ### Add Custom Card Type Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Demonstrates how to add a custom card type with specific patterns, gaps, lengths, and security code details using the `addCard` method. ```typescript const customCard = { niceType: "My Corp Card", type: "my-corp-card", patterns: [ 7777, // Exact prefix match [8000, 8099], // Range match 999 // Another exact prefix ], gaps: [4, 8, 12], // Spaces at positions 4, 8, 12 lengths: [16, 17], // Accepts 16 or 17 digit cards code: { name: "CVV", size: 3 } }; creditCardType.addCard(customCard); ``` -------------------------------- ### getAllCardTypes() Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Returns a clone of all available card types, ordered according to the test order. This prevents external modification of the card type data. ```APIDOC ## getAllCardTypes() ### Description Returns a clone of all available card types in test order. ### Return Type `CreditCardType[]` ### Behavior - Maps over the test order array - Clones each card type to prevent external modification - Returns array in the current test order ``` -------------------------------- ### Import Credit Card Type (ES6/TypeScript) Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Import the credit-card-type library and its specific functions using ES6/TypeScript module syntax. Includes type definitions. ```typescript import creditCardType, { getTypeInfo, types } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; ``` -------------------------------- ### Migrate from Old Card Library Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/usage-patterns.md Adapt data structures from an old card detection library to the new library's format. This function maps old brand names to new type IDs and provides a fallback for unknown brands. ```typescript import creditCardType, { types } from "credit-card-type"; import type { CreditCardType } from "credit-card-type"; // Old library returned different structure interface OldCardFormat { brand: string; digits: number; cvv: number; } // Adapter function function adaptFromOldLibrary(oldCard: OldCardFormat): CreditCardType { const brandMap: Record = { "Visa": types.VISA, "Mastercard": types.MASTERCARD, "American Express": types.AMERICAN_EXPRESS, // ... etc }; const typeId = brandMap[oldCard.brand]; const newCard = creditCardType.getTypeInfo(typeId); return newCard || { niceType: oldCard.brand, type: oldCard.brand.toLowerCase().replace(/ /g, "-"), patterns: [], gaps: [4, 8, 12], lengths: [oldCard.digits], code: { name: "CVV", size: oldCard.cvv } }; } ``` -------------------------------- ### Verve Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Verve cards. ```typescript { niceType: "Verve", type: "verve", patterns: [ [506099, 506127], 506129, [506133, 506150], [506158, 506163], 506166, 506168, 506170, 506173, [506176, 506180], 506184, [506187, 506188], 506191, 506195, 506197, 507865, 507866, [507868, 507877], [507880, 507888], 507900, 507941 ], gaps: [4, 8, 12], lengths: [16, 18, 19], code: { name: "CVV", size: 3 } } ``` -------------------------------- ### Type Card Number As You Go Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Detects possible card types as the user types a card number. Use the `map` function to extract display names. ```typescript creditCardType("4111").map(c => c.niceType); ``` -------------------------------- ### Format Card Number Using Type Gaps Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/get-type-info.md Demonstrates how to format a card number by applying standard spacing based on the `gaps` information retrieved from `getTypeInfo()`. This function ensures the card number is displayed with appropriate separators. ```typescript // Format card with gaps from type info function formatCard(cardNumber, typeId) { const card = creditCardType.getTypeInfo(typeId); if (!card) return cardNumber; const offsets = [0, ...card.gaps, cardNumber.length]; const parts = []; for (let i = 0; offsets[i] < cardNumber.length; i++) { const start = offsets[i]; const end = Math.min(offsets[i + 1], cardNumber.length); parts.push(cardNumber.substring(start, end)); } return parts.join(" "); } console.log(formatCard("4111111111111111", "visa")); // "4111 1111 1111 1111" ``` -------------------------------- ### Cache Card Configurations for Performance Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/usage-patterns.md Implement a cache to store card type configurations for faster retrieval. The cache is cleared when the library's internal state changes to ensure data consistency. ```typescript import creditCardType, { types } from "credit-card-type"; class CardConfigCache { private cache = new Map(); getConfig(typeId: string) { if (!this.cache.has(typeId)) { const config = creditCardType.getTypeInfo(typeId); if (config) { this.cache.set(typeId, config); } } return this.cache.get(typeId); } clearCache() { this.cache.clear(); } } // Usage const cache = new CardConfigCache(); // First call - fetches and caches const visa1 = cache.getConfig(types.VISA); // Second call - returns from cache const visa2 = cache.getConfig(types.VISA); // Same object reference (from cache) console.log(visa1 === visa2); // true // When library state changes creditCardType.updateCard(types.VISA, { niceType: "Updated Visa" }); // Cache becomes stale - clear it cache.clearCache(); // Next call gets updated config const visa3 = cache.getConfig(types.VISA); ``` -------------------------------- ### Mir Card Configuration Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/configuration.md Configuration details for Mir cards. ```typescript { niceType: "Mir", type: "mir", patterns: [[2200, 2204]], gaps: [4, 8, 12], lengths: [16, 17, 18, 19], code: { name: "CVP2", size: 3 } } ``` -------------------------------- ### Basic Card Detection with credit-card-type Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/usage-patterns.md Detect the card type from partial or full card numbers. The specificity of the detection increases with the number of digits provided. An empty array is returned if no match is found. ```typescript import creditCardType from "credit-card-type"; // Single character - may be ambiguous const oneChar = creditCardType("4"); console.log(oneChar.length); // 1 or more (Visa, Maestro, etc.) // Multiple characters - more specific const twoChars = creditCardType("41"); console.log(twoChars[0].type); // "visa" // Full card number const full = creditCardType("4111111111111111"); console.log(full.length); // 1 (unambiguous) console.log(full[0].niceType); // "Visa" // No match const noMatch = creditCardType("9999999999999999"); console.log(noMatch.length); // 0 ``` -------------------------------- ### Find Card Type by Identifier Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Looks up a card type from the registry, checking custom cards first and then falling back to built-in cards. Returns the card configuration object. ```typescript function findType(cardType: string | number): CreditCardType ``` -------------------------------- ### matchesPattern() Function Signature Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Tests exact prefix matching for a card number against a given pattern. Converts the pattern to a string and compares the initial characters. Supports partial matches where the card number is shorter than the pattern. ```typescript function matchesPattern(cardNumber: string, pattern: string | number): boolean ``` -------------------------------- ### matches() Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Tests whether a card number matches a single pattern, which can be an exact match, a range, or a partial prefix. ```APIDOC ## matches() ### Description Tests whether a card number matches a single pattern (exact or range). ### Signature ```typescript export function matches(cardNumber: string, pattern: string | number | string[] | number[]): boolean ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **cardNumber** (string) - Required - The card number to test - **pattern** (string | number | string[] | number[]) - Required - The pattern to match against. If an array, it delegates to `matchesRange()`. If a number or string, it delegates to `matchesPattern()`. ### Return Type `boolean` ### Behavior - Supports partial matches (card number shorter than pattern still matches if prefix matches). ### Examples ``` // Example usage with a string pattern matches("4111", "4"); // true matches("4", "4"); // true matches("3", "4"); // false // Example usage with an array pattern matches("5111", ["51", "55"]); // true matches("5", ["51", "55"]); // true (partial match on first digit) matches("5611", ["51", "55"]); // false ``` ``` -------------------------------- ### matchesRange() Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Tests for range matching of a card number against a specified minimum and maximum BIN range. ```APIDOC ## matchesRange() ### Description Tests range matching for BIN ranges. ### Signature ```typescript function matchesRange(cardNumber: string, min: number | string, max: number | string): boolean ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **cardNumber** (string) - Required - The card number to test. - **min** (number | string) - Required - The minimum value of the BIN range. - **max** (number | string) - Required - The maximum value of the BIN range. ### Return Type `boolean` ### Behavior - Gets the length of the `min` value to determine how many digits to check. - Extracts that many digits from the card number. - Compares the integer representation of the extracted digits against `min` and `max`. - Supports partial matching. ### Examples ``` matchesRange("5111", "51", "55"); // true matchesRange("5", "51", "55"); // true (partial match on first digit) matchesRange("5611", "51", "55"); // false ``` ``` -------------------------------- ### Add a New Custom Card Type Source: https://github.com/braintree/credit-card-type/blob/main/README.md Use `addCard` to define a new card brand not supported by default. Provide its properties like patterns, gaps, lengths, and code details. ```javascript creditCardType.addCard({ niceType: "NewCard", type: "new-card", patterns: [2345, 2376], gaps: [4, 8, 12], lengths: [16], code: { name: "CVV", size: 3, }, }); ``` -------------------------------- ### resetModifications Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Restore default state. ```APIDOC ## resetModifications ### Description Restore default state. ### Signature `resetModifications(): void` ``` -------------------------------- ### Quarantine a Flaky Describe Block Source: https://github.com/braintree/credit-card-type/blob/main/CONTRIBUTING.md Skip an entire describe block if multiple tests within it are flaky. Reference the tracking issue in the comment. ```javascript // Quarantined: intermittent failures under load (https://github.com/braintree/credit-card-type/issues/123) describe.skip("feature under investigation", function () { // ... }); ``` -------------------------------- ### changeOrder Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Adjust detection priority. ```APIDOC ## changeOrder ### Description Adjust detection priority. ### Signature `changeOrder(name: string, position: number): void` ``` -------------------------------- ### Detect Credit Card Type Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Use the main function to detect matching card types for a given card number. It accepts a partial or full card number string and returns an array of possible card types. ```typescript creditCardType(cardNumber: string): Array ``` -------------------------------- ### findType() Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/api-reference/internal-functions.md Looks up a card type from the registry, checking custom cards first and then falling back to built-in cards. Returns the card configuration object. ```APIDOC ## findType() ### Description Internal function that looks up a card type from the registry. ### Parameters #### Path Parameters - **cardType** (string | number) - Required - The card type identifier ### Return Type `CreditCardType` ### Behavior - First checks `customCards` registry for overrides - Falls back to `cardTypes` (built-in cards) if not in custom registry - Returns the card configuration object (not cloned) ``` -------------------------------- ### Import creditCardType using CommonJS Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/imports-exports.md Use require to import the main creditCardType function and named destructuring for other utilities. ```javascript const creditCardType = require("credit-card-type"); // Main function creditCardType("4111"); // Named destructuring const { getTypeInfo, types } = require("credit-card-type"); getTypeInfo("visa"); ``` -------------------------------- ### types - Card Type Name Constants Source: https://github.com/braintree/credit-card-type/blob/main/_autodocs/README.md Provides constants for all recognized credit card type names. ```APIDOC ## types ### Description An object containing constants for all supported credit card type names. ### Usage ```javascript import { types } from 'credit-card-type'; console.log(types.VISA); // "visa" console.log(types.MASTERCARD); // "mastercard" ``` ### Properties - **VISA** (string) - Constant for Visa card type. - **MASTERCARD** (string) - Constant for Mastercard card type. - **AMEX** (string) - Constant for American Express card type. - **DISCOVER** (string) - Constant for Discover card type. - ... (and other supported card types) ```