@unifast/core

unifast 런타임 패키지 간에 공유되는 TypeScript 타입 정의, HAST 유틸리티, 에러 클래스

개요

@unifast/core는 컴파일 옵션, 결과, HAST(HTML Abstract Syntax Tree) 노드, 플러그인 인터페이스, 에러 클래스에 대한 공유 TypeScript 타입 정의를 제공합니다. @unifast/node 같은 런타임 패키지의 의존성이므로 일반적으로 직접 설치할 필요가 없습니다.

컴파일러와 빌트인 플러그인을 사용하려면 @unifast/node를 사용하세요.

설치

타입 정의

CompileOptions

compile() 함수의 설정.

속성타입기본값설명
inputKind"md" | "mdx""md"입력 형식
outputKind"html" | "hast" | "mdast" | "mdxJs""html"출력 형식
gfmobject-GitHub Flavored Markdown 설정
gfm.tablesboolean-GFM 표 활성화
gfm.taskListboolean-작업 목록 체크박스 활성화
gfm.strikethroughboolean-~~취소선~~ 활성화
gfm.footnotesboolean-각주 활성화
gfm.autolinkboolean-URL 자동 링크 활성화
frontmatterobject-frontmatter 파싱 설정
frontmatter.yamlboolean-YAML frontmatter 파싱
frontmatter.tomlboolean-TOML frontmatter 파싱
frontmatter.jsonboolean-JSON frontmatter 파싱
rawHtml"disallow" | "allowDangerous" | "parseAndSanitize"-원본 HTML 처리 방식
sanitizeobject-HTML 새니타이즈 설정
sanitize.enabledboolean-새니타이즈 활성화
sanitize.schemaSanitizeSchema-커스텀 새니타이즈 규칙
highlightobject-구문 강조 설정
highlight.enabledboolean-구문 강조 활성화
highlight.engine"none" | "syntect" | "treeSitter"-강조 엔진
slugobject-제목 슬러그 생성 설정
slug.mode"github" | "unicode"-슬러그 생성 알고리즘
tocobject-목차 설정
toc.enabledboolean-TOC 추출 활성화
toc.maxDepthnumber-포함할 최대 제목 레벨
diagnosticsobject-진단 출력 설정
diagnostics.format"compact" | "verbose"-진단 형식
cacheobject-캐시 설정
cache.enabledboolean-결과 캐시 활성화
cache.dirstring-캐시 디렉터리 경로
pluginsUnifastPlugin[][]적용할 플러그인 배열

CompileResult

compile() 함수의 반환값.

속성타입설명
outputstring | object컴파일된 결과 (HTML 문자열, HAST JSON, MDAST JSON — outputKind에 따라 달라짐)
frontmatterRecord<string, unknown>파싱된 frontmatter 메타데이터
diagnosticsDiagnostic[]경고와 오류 배열
stats{ parseMs, transformMs, emitMs }단계별 소요 시간(ms)
tocTocEntry[]추출된 목차 항목

Diagnostic

속성타입설명
level"error" | "warn"심각도
messagestring사람이 읽을 수 있는 메시지
startnumber | undefined소스의 시작 바이트 오프셋
endnumber | undefined소스의 끝 바이트 오프셋
linenumber | undefined줄 번호 (1부터 시작)
columnnumber | undefined열 번호 (1부터 시작)

TocEntry

목차를 위해 추출된 단일 제목.

속성타입설명
depthnumber제목 레벨 (1-6)
textstring제목의 평문 내용
slugstring앵커 링크용으로 생성된 슬러그

SanitizeSchema

커스텀 새니타이즈 규칙.

속성타입설명
allowedTagsstring[]허용할 HTML 태그
allowedAttributesRecord<string, string[]>태그별 허용 속성
allowedProtocolsRecord<string, string[]>속성별 허용 URL 프로토콜

UnifastPlugin

unifast를 확장하기 위한 플러그인 인터페이스.

속성타입설명
namestring고유한 플러그인 이름
options?Partial<CompileOptions>컴파일 옵션에 병합할 옵션
hastTransform?(hast: HastRoot) => HastRoot컴파일 후 HAST 트리를 변환

HAST 노드 타입

타입type 필드속성설명
HastRoot"root"children: HastNode[]트리의 루트 노드
HastElement"element"tagName, properties, childrenHTML 요소
HastText"text"value: string텍스트 노드
HastRaw"raw"value: string원본 HTML 패스스루
HastComment"comment"value: stringHTML 주석
HastDoctype"doctype"-<!DOCTYPE html> 노드

HastNode는 유니언 타입입니다: HastRoot | HastElement | HastText | HastRaw | HastComment | HastDoctype

에러 클래스

클래스확장속성설명
UnifastErrorErrorcode?: string, span?: { start, end }모든 unifast 에러의 기반 클래스
ParseErrorUnifastErrorcode: "PARSE_ERROR"Markdown/MDX 입력을 파싱할 수 없을 때 발생
CompileErrorUnifastErrorcode: "COMPILE_ERROR"파싱 이후 컴파일이 실패할 때 발생
import { UnifastError, ParseError, CompileError } from "@unifast/core";

try {
  // ... 컴파일 수행
} catch (err) {
  if (err instanceof ParseError) {
    console.error(`Parse error at ${err.span?.start}: ${err.message}`);
  } else if (err instanceof CompileError) {
    console.error(`Compile error: ${err.message}`);
  }
}

Exports 요약

Export종류설명
CompileOptionstype컴파일 설정
CompileResulttype컴파일 결과
TocEntrytype목차 항목
SanitizeSchematype새니타이즈 규칙
UnifastPlugintype플러그인 인터페이스
HastNodetype모든 HAST 노드 타입의 유니언
HastRoottypeHAST 루트 노드
HastElementtypeHAST 요소 노드
HastTexttypeHAST 텍스트 노드
HastRawtypeHAST 원본 HTML 노드
HastCommenttypeHAST 주석 노드
HastDoctypetypeHAST doctype 노드
hastToHtmlfunctionHAST-to-HTML 시리얼라이저
escapeHtmlfunctionHTML 특수 문자 이스케이프 (&, <, >, ")
extractLangfunctionHAST <code> 요소에서 언어 식별자 추출
extractTextfunctionHAST 노드에서 평문 텍스트 추출
findCodeChildfunction<pre> 요소 안의 <code> 자식 요소 찾기
visitHastfunctionHAST 트리를 순회하기 위한 비지터 유틸리티
UnifastErrorclass기반 에러 클래스
ParseErrorclass파싱 에러 클래스
CompileErrorclass컴파일 에러 클래스