@desource/phone-mask

中文文档
2.1.0发布于 2026/11/07MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2万

⚡ Ultra-lightweight international phone number formatter & validator with auto-sync to Google libphonenumber. Framework-agnostic core library.

原始使用文档
文档目录29 节
  1. ✨ Features
  2. 📦 Installation
  3. Import Paths
  4. Distribution formats
  5. 🚀 Quick Start
  6. Display Formatting
  7. Basic Formatting
  8. Working with Country Data
  9. Multiple Mask Variants
  10. Localized Country Names
  11. Utility Functions
  12. Validate Number Against Country Rules
  13. Raw Digits for Backend Processing
  14. Custom Regex + Metadata (Regional/Carrier Prefixes)
  15. Multi-tenant: tenantId Default Country + Tenant-specific Va…
  16. 📖 API Reference
  17. Types
  18. Root Entry Exports
  19. Kit Subpath Exports
  20. 🎯 Use Cases
  21. Custom Input Formatting
  22. Phone Number Validation
  23. Building a Country Selector
  24. Getting Flag Emojis
  25. 🔄 Data Updates
  26. 📊 Bundle Size
  27. 🔗 Related Packages
  28. 📄 License
  29. 🤝 Contributing

@desource/phone-mask

Core TypeScript library for international phone number masking with Google's libphonenumber data

npm version code coverage SonarCloud Ask CodeWiki Ask Context7 Ask DeepWiki license

Framework-agnostic phone masking library that stays up-to-date with Google's libphonenumber database.

Before upgrading to 2.0.0, review Migration from 1.7.0 for breaking changes and required updates.

✨ Features

  • 🌍 240+ countries with accurate masks and dialing codes
  • 🔄 Auto-synced from Google's libphonenumber
  • 🪶 Tiny — root entry is 6.1 KB minified, 2.9 KB gzipped, 2.3 KB brotli
  • 🌳 Tree-shakeable — import only what you need
  • 🔧 TypeScript — fully typed
  • 🎯 Zero dependencies

📦 Installation

npm install @desource/phone-mask
# or
yarn add @desource/phone-mask
# or
pnpm add @desource/phone-mask

Import Paths

The root entry contains country metadata and mask data. Display formatting, lower-level formatters, input handling, detection, and utility helpers live in the kit subpath.

import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { formatPhone, createPhoneFormatter, formatDigitsWithMap } from '@desource/phone-mask/kit';

Distribution formats

Package imports use unminified ESM or CommonJS; application bundlers handle tree-shaking and minification. Both entries include TypeScript declarations for each module format.

Use caseRoot entryKit entry
ESM, including native browser modulesdist/esm/index.jsdist/esm/kit.js
CommonJSdist/phone-mask.cjsdist/kit.cjs
Browser globals, readabledist/phone-mask.umd.jsdist/kit.umd.js
Browser globals, minifieddist/phone-mask.umd.min.jsdist/kit.umd.min.js

For browser usage without a build step, load both globals to combine country data with formatting helpers:

<script src="https://cdn.jsdelivr.net/npm/@desource/phone-mask/dist/phone-mask.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@desource/phone-mask/dist/kit.umd.min.js"></script>
<script>
  const result = phoneMaskKit.formatDigitsWithMap(phoneMask.MasksBaseMap.US[0], '2025551234');
  console.log(result.display); // "+1 202-555-1234"
</script>

Pin both CDN URLs to the same package version in production. UNPKG supports the same file paths.

🚀 Quick Start

Display Formatting

import { formatPhone } from '@desource/phone-mask/kit';

formatPhone('+12345678888'); // '+1 234 567 8888'
formatPhone('2345678888', 'US', { code: false, flag: true }); // '🇺🇸 234 567 8888'

See formatPhone for options and supported input formats.

Basic Formatting

import { MasksBaseMap, MasksMap } from '@desource/phone-mask';
import { formatDigitsWithMap } from '@desource/phone-mask/kit';

// Get US mask with country code prefix
const prefixUsMask = MasksBaseMap.US;
// ["+1 ###-###-####"]

// Format digits
const result = formatDigitsWithMap(prefixUsMask[0], '2025551234');
console.log(result.display); // "+1 202-555-1234"
console.log(result.map); // [-1, -1, -1, 0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, 9]

// Get US mask without country code prefix
const usMask = MasksMap.US.mask;
// ["###-###-####"]

// Format digits without country code
const resultNoCode = formatDigitsWithMap(usMask[0], '2025551234');
console.log(resultNoCode.display); // "202-555-1234"
console.log(resultNoCode.map); // [0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, 9]

Working with Country Data

import { MasksFullMapEn, type MaskFull } from '@desource/phone-mask';

// Access country data
const us = MasksFullMapEn.US;

console.log(us.name); // "United States"
console.log(us.code); // "+1"
console.log(us.mask); // ["###-###-####"]
console.log(us.flag); // "🇺🇸"

Multiple Mask Variants

Some countries have multiple mask formats:

import { MasksFullMapEn } from '@desource/phone-mask';

const gb = MasksFullMapEn.GB;
console.log(gb.mask);
// [
//   "#### ######",
//   "### ### ####",
//   "## #### ####"
// ]

Localized Country Names

import { MasksFullMap } from '@desource/phone-mask';

// Get localized names
const germanMap = MasksFullMap('de');
console.log(germanMap.US.name); // "Vereinigte Staaten"

const frenchMap = MasksFullMap('fr');
console.log(frenchMap.US.name); // "États-Unis"

Utility Functions

import { countPlaceholders, removeCountryCodePrefix, pickMaskVariant, extractDigits } from '@desource/phone-mask/kit';

// Count placeholder digits
const count = countPlaceholders('+1 ###-###-####');
// 10

// Remove country code prefix
const stripped = removeCountryCodePrefix('+1 ###-###-####');
// "###-###-####"

// Pick best mask variant for digit count
const variants = ['+44 #### ######', '+44 ### ### ####'];
const best = pickMaskVariant(variants, 10);
// "+44 #### ######"

// Extract only digits from string
const digits = extractDigits('+1 (202) 555-1234');
// "12025551234"

Validate Number Against Country Rules

Use createPhoneFormatter() to validate length against a specific country's mask variants.

The recipes below accept local numbers or international numbers with the selected country's calling code. They truncate excess digits to match the framework inputs. Use country.code to remove a known calling code from phone values; removeCountryCodePrefix() is intended for mask templates.

import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';

function validateForCountry(input: string, id: CountryKey) {
  const country = MasksFullMapEn[id];
  const value = input.trim();
  if (!country || (value.startsWith('+') && !value.startsWith(country.code))) {
    return {
      digits: '',
      display: '',
      isComplete: false
    };
  }

  const formatter = createPhoneFormatter(country);
  const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
  const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());

  return {
    digits,
    display: formatter.formatDisplay(digits),
    isComplete: formatter.isComplete(digits)
  };
}

validateForCountry('+1 (202) 555-1234', 'US');
// { digits: "2025551234", display: "202-555-1234", isComplete: true }
validateForCountry('+12025551234', 'US');
// { digits: "2025551234", display: "202-555-1234", isComplete: true }

Raw Digits for Backend Processing

Use raw digits for storage and transport. Keep formatting on the client only.

import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';

function buildPhonePayload(input: string, id: CountryKey) {
  const country = MasksFullMapEn[id];
  const value = input.trim();
  if (!country || (value.startsWith('+') && !value.startsWith(country.code))) return null;

  const formatter = createPhoneFormatter(country);
  const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
  const localDigits = extractDigits(inputWithoutCode, formatter.getMaxDigits());

  return {
    country: id,
    phoneDigits: localDigits, // canonical backend field
    phoneE164: `${country.code}${localDigits}` // optional: with dialing prefix
  };
}

Custom Regex + Metadata (Regional/Carrier Prefixes)

Combine Phone Mask metadata with region-specific regex rules:

import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';

const tenantCarrierRules: Partial<Record<CountryKey, RegExp>> = {
  BR: /^(11|21|31)\d{8,9}$/,
  IN: /^(98|99)\d{8}$/
};

function validateWithCarrierRule(input: string, id: CountryKey): boolean {
  const country = MasksFullMapEn[id];
  const value = input.trim();
  if (!country || (value.startsWith('+') && !value.startsWith(country.code))) return false;

  const formatter = createPhoneFormatter(country);
  const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
  const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
  const carrierRule = tenantCarrierRules[id];

  if (!formatter.isComplete(digits)) return false;
  return carrierRule ? carrierRule.test(digits) : true;
}

Multi-tenant: tenantId Default Country + Tenant-specific Validation Rules

import { MasksFullMapEn, type CountryKey } from '@desource/phone-mask';
import { createPhoneFormatter, extractDigits } from '@desource/phone-mask/kit';

type TenantPolicy = {
  defaultCountry: CountryKey;
  prefixRule?: RegExp;
};

const TENANT_POLICIES: Record<string, TenantPolicy> = {
  acme: { defaultCountry: 'US', prefixRule: /^(202|303)\d{7}$/ },
  globex: { defaultCountry: 'GB', prefixRule: /^7\d{9}$/ }
};

function createTenantPhoneService(tenantId: string) {
  const policy = TENANT_POLICIES[tenantId] ?? { defaultCountry: 'US' as const };
  const id = policy.defaultCountry;
  const country = MasksFullMapEn[id];
  const formatter = createPhoneFormatter(country);

  return {
    defaultCountry: id,
    format(input: string) {
      const value = input.trim();
      if (value.startsWith('+') && !value.startsWith(country.code)) return input;
      const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
      const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
      return formatter.formatDisplay(digits);
    },
    validate(input: string) {
      const value = input.trim();
      if (value.startsWith('+') && !value.startsWith(country.code)) return false;
      const inputWithoutCode = value.startsWith(country.code) ? value.slice(country.code.length) : value;
      const digits = extractDigits(inputWithoutCode, formatter.getMaxDigits());
      const complete = formatter.isComplete(digits);
      const prefixOk = policy.prefixRule ? policy.prefixRule.test(digits) : true;
      return complete && prefixOk;
    }
  };
}

📖 API Reference

Types

// Country ISO 3166-1 alpha-2 code
type CountryKey = 'US' | 'GB' | 'DE' | ... // 240+ countries

// Mask interfaces
interface MaskBase {
  id: CountryKey;
  mask: Array<string>;
}
interface Mask extends MaskBase {
  code: string;
}
interface MaskWithFlag extends Mask {
  flag: string;
}
interface MaskFull extends MaskWithFlag {
  name: string;
}
type MaskBaseMap = Record<CountryKey, Array<string>>;
type MaskMap = Record<CountryKey, Omit<Mask, 'id'>>;
type MaskWithFlagMap = Record<CountryKey, Omit<MaskWithFlag, 'id'>>;
type MaskFullMap = Record<CountryKey, Omit<MaskFull, 'id'>>;

Root Entry Exports

Import mask data and country types from @desource/phone-mask.

MasksBaseMap & MasksBase

Basic country masks including country code prefix (lightweight version):

const MasksBaseMap: MaskBaseMap;
const MasksBase: MaskBase[];

Use these to get raw masks with country code prefix. Note: some helper functions may expect masks without country code.

MasksMap & Masks

Masks with country code as separate property:

const MasksMap: MaskMap;
const Masks: Mask[];

MasksWithFlagMap & MasksWithFlag

Masks with country code and flag:

const MasksWithFlagMap: MaskWithFlagMap;
const MasksWithFlag: MaskWithFlag[];

MasksFullMapEn & MasksFullEn

Full country data with country names in English:

const MasksFullMapEn: MaskFullMap;
const MasksFullEn: MaskFull[];

MasksFullMap(locale: string) & MasksFull(locale: string)

Get full country data with localized country names:

function MasksFullMap(locale: string): MaskFullMap;
function MasksFull(locale: string): MaskFull[];

Supported locales: en, de, fr, es, it, pt, ru, zh, ja, ko, and more.

getFlagEmoji(countryCode: CountryKey)

Get flag emoji for country code:

function getFlagEmoji(countryCode: CountryKey): string;

Kit Subpath Exports

Import formatter, input handling, detection, and utility helpers from @desource/phone-mask/kit.

// Count # placeholders in mask
function countPlaceholders(mask: string): number;

// Remove country code prefix from mask
function removeCountryCodePrefix(mask: string): string;

// Pick best mask variant for digit length
function pickMaskVariant(masks: string[], digitLength: number): string;

// Extract digits from any string
function extractDigits(value: string, maxLength?: number): string;

// Detect a complete international number from current masks
function detectCountryFromPhone(value: string): CountryKey | undefined;

// Format digits according to template
function formatDigitsWithMap(value: string, digits: string): { display: string; map: number[] };

detectCountryFromPhone requires a leading +. It first matches formatting exactly, then falls back to calling code and digit count excluding that code. Shared matches use the calling code's generated default country; for example, unformatted +1 numbers default to US. Unsupported syntax, unknown calling codes, and unmatched lengths return undefined. Detection uses masks, not allocation prefixes or number validation.

import { detectCountryFromPhone } from '@desource/phone-mask/kit';

detectCountryFromPhone('+7 123 456 7788'); // 'KZ': unique mask
detectCountryFromPhone('+71234567788'); // 'RU': shared length, default country
detectCountryFromPhone('1234567788'); // undefined: no international prefix

processPaste returns an optional country when detection succeeds. Apply that country before the returned newDigits, which excludes the calling code. A detected international paste replaces the whole input and places the caret at the end, without truncating to the previous country's mask. Other pastes retain normal selection and insertion behavior.

formatPhone(value, country?, options?)

Format a phone number for display using the country's mask groups, separated by spaces. This pure function works in the browser and during SSR. React, Vue, and Svelte re-export this function for use in templates and JSX. Angular’s PhonePipe delegates to it. Each framework package also exposes it through its /core subpath.

import { formatPhone, type PhoneFormatOptions } from '@desource/phone-mask/kit';

formatPhone('+12345678888'); // '+1 234 567 8888'
formatPhone('2345678888', 'US'); // '+1 234 567 8888'
formatPhone('+1 (234) 567-8888', 'US', { code: false }); // '234 567 8888'
formatPhone('+12345678888', 'US', { flag: true }); // '🇺🇸 +1 234 567 8888'
formatPhone('234 567 8888', 'US', { code: false, flag: true }); // '🇺🇸 234 567 8888'
interface PhoneFormatOptions {
  readonly code?: boolean; // Include the calling code; defaults to true.
  readonly flag?: boolean; // Prepend the flag emoji; defaults to false.
}

function formatPhone(
  value: string | null | undefined,
  country?: CountryKey | null,
  options?: PhoneFormatOptions
): string;

Only an explicit + calling code is removed; bare digits are treated as a number without a calling code. Pass an ISO country code for those values. With no country, detection requires a complete international number and uses mask shape, calling code, and length. Shared matches use a default country, such as US for +1; detection does not inspect area-code allocations. Pass undefined or null as the country to combine detection with options.

A supplied country takes priority when its calling code matches, so formatPhone('+12345678888', 'CA', { flag: true }) retains the Canadian flag. If codes conflict, successful detection takes priority: formatPhone('+442079460958', 'US') returns '+44 2079 460958'. Unsuccessful detection preserves the original value.

Significant leading zeros are preserved. Empty, whitespace-only, null, and undefined values return ''. Unsupported countries, invalid characters, extensions, and values exceeding the selected mask's length remain unchanged. The function does not infer trunk prefixes or validate whether a number is assigned. Render its result as text, as with any user-provided value.

🎯 Use Cases

Custom Input Formatting

import { MasksFullMapEn } from '@desource/phone-mask';
import { formatDigitsWithMap, extractDigits } from '@desource/phone-mask/kit';

function formatPhoneInput(value: string, countryCode: string = 'US') {
  const country = MasksFullMapEn[countryCode];
  const mask = country?.mask[0];
  if (!mask) return value;

  const digits = extractDigits(value);

  return `${country.code} ${formatDigitsWithMap(mask, digits).display}`;
}

// Usage
const formatted = formatPhoneInput('2025551234', 'US');
// "+1 202-555-1234"

Phone Number Validation

import { MasksFullMapEn } from '@desource/phone-mask';
import { countPlaceholders } from '@desource/phone-mask/kit';

function isValidPhoneLength(digits: string, country: string): boolean {
  const masks = MasksFullMapEn[country]?.mask;
  if (!masks) return false;
  const validLengths = masks.map((m) => countPlaceholders(m));

  return validLengths.includes(digits.length);
}

// Usage
isValidPhoneLength('2025551234', 'US'); // true (10 digits)
isValidPhoneLength('202555', 'US'); // false (too short)

Building a Country Selector

import { MasksFullEn, type CountryKey, type MaskFull } from '@desource/phone-mask';

type CountryOption = Omit<MaskFull, 'mask'>;

function getCountryOptions(): CountryOption[] {
  return MasksFullEn.map((data) => ({
    id: data.id,
    name: data.name,
    code: data.code,
    flag: data.flag
  }));
}

// Usage
const countries = getCountryOptions();
// [
//   { id: 'US', name: 'United States', code: '+1', flag: '🇺🇸' },
//   { id: 'GB', name: 'United Kingdom', code: '+44', flag: '🇬🇧' },
//   ...
// ]

Getting Flag Emojis

import { getFlagEmoji } from '@desource/phone-mask';

// Get flag emoji for country code
const flag = getFlagEmoji('US'); // "🇺🇸"

🔄 Data Updates

The library syncs with Google's libphonenumber via automated workflow. To update manually:

pnpm gen

This fetches the latest data and regenerates data.json. This updates generated metadata files used by the package (src/data.json, src/data.min.js, and src/data-types.ts).

📊 Bundle Size

Measured by bundling the packed package in a real consumer build with tree-shaking enabled:

Consumer importSize (minified)GzippedBrotli
import * as PhoneMask from '@desource/phone-mask'6.09 KB2.86 KB2.30 KB
import { MasksFullMapEn } from '@desource/phone-mask'5.75 KB2.67 KB2.13 KB
import * as Kit from '@desource/phone-mask/kit'13.28 KB5.83 KB4.90 KB
import { createPhoneFormatter } from '@desource/phone-mask/kit'1.03 KB0.59 KB0.53 KB
import { formatDigitsWithMap } from '@desource/phone-mask/kit'0.25 KB0.21 KB0.18 KB
import { extractDigits } from '@desource/phone-mask/kit'0.08 KB0.10 KB0.08 KB
import { getCountry } from '@desource/phone-mask/kit'5.84 KB2.72 KB2.18 KB

The root entry contains country metadata and mask data. Use @desource/phone-mask/kit when you need display formatting, lower-level formatters, input handling, detection, or utility helpers. Data-dependent helpers such as getCountry include mask data; pure formatter and input helpers tree-shake to small standalone bundles.

📄 License

MIT © 2026 DeSource Labs

🤝 Contributing

See Contributing Guide for development, testing, and publication checks.


Made with ❤️ by DeSource Labs

版本与发布记录

@desource/phone-mask 共发布 24 个版本,首次发布于 2025/11/04;过去 12 个月发布了 22 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.1.0latest2026/11/074 天前
2.0.02026/10/3111 天前
1.7.02026/10/101 个月前
1.6.42026/09/261 个月前
1.6.32026/09/082 个月前
1.6.22026/08/242 个月前

其他发布通道:internal-beta → 1.2.1-beta.2。

关于 @desource/phone-mask 的常见问题

@desource/phone-mask 是什么?

⚡ Ultra-lightweight international phone number formatter & validator with auto-sync to Google libphonenumber. Framework-agnostic core library.

如何安装 @desource/phone-mask?

在项目目录运行 npm install @desource/phone-mask,或使用 pnpm add / yarn add / bun add。

@desource/phone-mask 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@desource/phone-mask 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@desource/phone-mask 可以商用吗?

@desource/phone-mask 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@desource/phone-mask 的下载量有多少?

根据 npm 官方下载统计,@desource/phone-mask 在 2026/10/12 – 2026/11/10 这 30 天内被下载 20,428 次,日均约 681 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@desource/phone-mask 还在维护吗?

最新版本 2.1.0 发布于 2026/11/07(4 天前);至今共发布 24 个版本,其中过去 12 个月发布了 22 个;首次发布于 2025/11/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。