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

@weepingtown/asn1p.js

v1.2.3

Published

ASN.1 (ITU-T X.680) Parser Library based on ANTLR4

Downloads

910

Readme

asn1p.js

npm version License: MIT TypeScript Node.js

基于 ANTLR4 的 ASN.1 (ITU-T X.680) 解析器库

作者: weepingtown
邮箱: [email protected]

English Documentation


简介

asn1p.js 是一个基于 ANTLR4 构建的 ASN.1 解析器库,完整支持 ITU-T X.680 标准定义的 ASN.1 语法。提供词法分析、语法解析、AST 构建、JSON 导出和代码格式化等功能。

为什么选择 ANTLR4?

| 特性 | 手写解析器 | ANTLR4 | |------|:---------:|:------:| | 开发效率 | 低 | 高 | | 可维护性 | 差 | 好 | | 错误处理 | 手动实现 | 内置支持 | | 语法修改 | 困难 | 简单 | | 多语言支持 | 无 | 支持 10+ 语言 |


功能特性

核心功能

  • 词法解析 - 将 ASN.1 源代码分解为 Token 流
  • 语法解析 - 构建抽象语法树 (AST)
  • 类型定义解析 - 支持 SEQUENCE, SET, CHOICE, ENUMERATED 等
  • 值定义解析 - 支持整数、字符串、OID 等值定义
  • 模块定义解析 - 支持 DEFINITIONS, IMPORTS, EXPORTS
  • 约束解析 - 支持 SIZE, FROM, WITH COMPONENT, 联合约束(union) 等
  • 注释保留 - 解析并保留源码注释(leading, inline, trailing)
  • 错误恢复 - 语法错误时提供有意义的错误信息
  • 格式化输出 - 将 AST 转换回格式化的 ASN.1 代码
  • JSON 导出 - 将 AST 导出为 JSON 格式
  • 类型引用展开 - 可选展开类型引用为完整定义

支持的 ASN.1 类型

| 类型 | 支持 | 类型 | 支持 | |------|:----:|------|:----:| | INTEGER | ✅ | SEQUENCE | ✅ | | BOOLEAN | ✅ | SET | ✅ | | BIT STRING | ✅ | CHOICE | ✅ | | OCTET STRING | ✅ | ENUMERATED | ✅ | | NULL | ✅ | REAL | ✅ | | OBJECT IDENTIFIER | ✅ | TaggedType | ✅ | | CharacterString | ✅ | ConstrainedType | ✅ | | SEQUENCE OF | ✅ | SET OF | ✅ |


安装

npm install @weepingtown/asn1p.js

环境要求

  • Node.js >= 18.0.0
  • TypeScript >= 5.0(如果使用TypeScript)

快速开始

解析 ASN.1 模块

import { ASN1 } from '@weepingtown/asn1p.js';

const content = `
  TEST-MODULE DEFINITIONS AUTOMATIC TAGS ::=
  BEGIN
    Person ::= SEQUENCE {
      name    PrintableString,
      age     INTEGER OPTIONAL,
      email   IA5String OPTIONAL
    }
  END
`;

// 解析为 AST
const module = ASN1.parse(content);
console.log(module.name);        // "TEST-MODULE"
console.log(module.tagging);     // "AUTOMATIC TAGS"
console.log(module.definitions); // [...]

导出为 JSON

const json = ASN1.parseToJSON(content, {
  expandReferences: true,    // 展开类型引用
  includeComments: true,     // 包含注释
  includeMetadata: true,     // 包含元数据(行列信息)
  maxDepth: 10               // 最大展开深度
});

console.log(json);
// {
//   name: "TEST-MODULE",
//   type: "ModuleDefinition",
//   category: "constructed",
//   children: [...],
//   metadata: { line: 2, column: 2 }
// }

格式化输出

const formatted = ASN1.format(content, {
  indent: 2,                 // 缩进空格数
  alignFields: true,         // 对齐字段
  alignComments: true,       // 对齐注释
  maxLineLength: 120,        // 最大行长度
  preserveComments: true     // 保留注释
});

console.log(formatted);

验证语法

const result = ASN1.validate(content);
if (!result.valid) {
  console.error('语法错误:', result.errors);
  // [{ message: "...", line: 5, column: 10 }]
}

API 文档

ASN1.parse(content: string, options?: ParseOptions): ModuleDefinition

解析 ASN.1 内容,返回模块定义对象。

参数:

  • content - ASN.1 源代码字符串
  • options - 解析选项
    • includeComments?: boolean - 是否收集注释,默认 false

返回: ModuleDefinition 对象

interface ModuleDefinition {
  type: 'ModuleDefinition';
  name: string;
  tagging?: 'AUTOMATIC TAGS' | 'IMPLICIT TAGS' | 'EXPLICIT TAGS';
  extensibilityImplied?: boolean;
  definitions: Assignment[];
  imports: Import[];
  exports: Export[];
  oid?: string;
  line?: number;
  column?: number;
  comments?: CommentInfo;
}

ASN1.parseToJSON(content: string, options?: ParseOptions): TreeJSONNode

解析 ASN.1 内容并返回树状 JSON 结构。

参数:

  • content - ASN.1 源代码字符串
  • options - 解析选项
interface ParseOptions {
  expandReferences?: boolean;   // 展开类型引用,默认 true
  includeComments?: boolean;    // 包含注释,默认 false
  includeMetadata?: boolean;    // 包含元数据,默认 false
  maxDepth?: number;            // 最大展开深度,默认 10
}

返回: TreeJSONNode 对象

interface TreeJSONNode {
  name: string;
  type: string;
  category: 'primitive' | 'constructed' | 'reference' | 'tagged';
  isOptional?: boolean;
  hasExtensionMarker?: boolean;
  hasDefaultValue?: boolean;
  path: string;
  baseType?: string;
  children?: TreeJSONNode[];
  resolvedType?: TreeJSONNode;
  constraints?: {
    valueRange?: { min: number | string; max: number | string };
    sizeConstraint?: { min?: number | string; max?: number | string };
    patternConstraint?: string;
    permittedAlphabet?: string[];
    constraintType?: 'union' | 'intersection';
    ranges?: Array<{ min: number | string; max: number | string }>;
  };
  comments?: {
    leading?: string[];
    inline?: string;
    trailing?: string[];
  };
  enumValues?: string[];
  defaultValue?: unknown;
  metadata?: {
    line?: number;
    column?: number;
  };
}

ASN1.format(content: string, options?: FormatOptions): string

格式化 ASN.1 内容。

参数:

  • content - ASN.1 源代码字符串
  • options - 格式化选项
interface FormatOptions {
  indent?: number;                 // 缩进空格数,默认 2
  level?: number;                  // 当前缩进层级,默认 0
  alignFields?: boolean;           // 对齐字段名,默认 true
  alignComments?: boolean;         // 对齐注释,默认 true
  alignTypeToColumn?: number;      // 类型对齐到的列位置
  alignOptionalToColumn?: number;  // OPTIONAL对齐到的列位置
  maxLineLength?: number;          // 最大行长度,默认 120
  preserveComments?: boolean;      // 保留注释,默认 true
}

ASN1.validate(content: string): ValidationResult

验证 ASN.1 语法正确性。

返回: ValidationResult 对象

interface ValidationResult {
  valid: boolean;
  errors: Array<{
    message: string;
    line: number;
    column: number;
    context?: string;
  }>;
}

技术架构

基于 ANTLR4

ASN.1 源代码
     │
     ▼
┌─────────────┐
│   Lexer     │  词法分析
│ (ASN1Lexer) │
└─────────────┘
     │
     ▼ Token 流
┌─────────────┐
│   Parser    │  语法分析
│(ASN1Parser) │
└─────────────┘
     │
     ▼ CST
┌─────────────┐
│   Visitor   │  AST 构建
│(ASTBuilder) │
└─────────────┘
     │
     ▼ AST
┌─────────────┐
│  Formatter  │  格式化输出
│  /Exporter  │  JSON导出
└─────────────┘

项目结构

asn1p.js/
├── grammar/
│   ├── ASN1Lexer.g4          # 词法规则
│   └── ASN1Parser.g4         # 语法规则
├── src/
│   ├── generated/            # ANTLR4 生成的代码
│   ├── ast/                  # AST 节点定义和构建器
│   │   ├── nodes.ts          # AST节点类型定义
│   │   └── ASTBuilder.ts     # AST构建器
│   ├── index.ts              # 主入口,提供parse/format/validate API
│   └── parser.ts             # 解析器封装(已合并到index.ts)
├── test/
│   └── *.test.ts             # 测试文件
├── dist/                     # 编译输出
├── package.json
├── tsconfig.json
├── rollup.config.js          # Rollup打包配置
├── typedoc.json              # TypeDoc文档配置
├── .eslintrc.json            # ESLint配置
├── .prettierrc               # Prettier配置
├── CHANGELOG.md              # 更新日志
├── README.md
└── LICENSE

开发指南

环境要求

  • Node.js >= 18.0.0
  • npm >= 9.0.0

本地开发

# 克隆仓库
git clone https://gitee.com/weepingtown/asn1p.js.git
cd asn1p.js

# 安装依赖
npm install

# 生成解析器代码(从grammar文件生成)
npm run generate

# 编译 TypeScript
npm run build

# 运行测试
npm test

# 运行测试并生成覆盖率报告
npm run test:coverage

# 代码检查
npm run lint

# 代码检查并自动修复
npm run lint:fix

# 代码格式化
npm run format

# 生成 API 文档
npm run docs

# 安全审计
npm run audit

NPM 脚本

| 命令 | 说明 | |------|------| | npm run generate | 从 grammar 文件生成 ANTLR4 解析器代码 | | npm run build | 编译 TypeScript 并打包 | | npm run clean | 清理 dist 目录 | | npm test | 运行测试 | | npm run test:coverage | 运行测试并生成覆盖率报告 | | npm run lint | 运行 ESLint 代码检查 | | npm run lint:fix | 自动修复 ESLint 问题 | | npm run format | 使用 Prettier 格式化代码 | | npm run format:check | 检查代码格式 | | npm run docs | 生成 TypeDoc API 文档 | | npm run typecheck | 运行 TypeScript 类型检查(包含测试文件) | | npm run verify | 运行完整验证(build + typecheck + lint + test) | | npm run audit | 检查依赖安全漏洞 | | npm run audit:fix | 修复依赖安全漏洞 |


性能

基于 10000 行 ASN.1 文件的性能测试:

| 操作 | 耗时 | 内存 | |------|------|------| | 词法分析 | ~50ms | ~5MB | | 语法分析 | ~100ms | ~10MB | | AST 构建 | ~50ms | ~8MB | | JSON 导出 | ~30ms | ~3MB | | 总计 | ~230ms | ~26MB |


更新日志

详见 CHANGELOG.md

许可证

MIT License © 2026 weepingtown


贡献

欢迎提交 Issue 和 Pull Request!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'feat: add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

提交规范

  • feat: 新功能
  • fix: 修复bug
  • docs: 文档更新
  • test: 测试相关
  • chore: 构建/工具
  • refactor: 代码重构

联系方式