@nclsndr/w3c-design-tokens-parser
v0.2.0
Published
a TypeScript implementation of the parser for the W3C Design Tokens Format Module specification
Downloads
165
Maintainers
Readme
W3C Design Tokens Parser
This package provides a TypeScript implementation of the parser for the W3C Design Tokens Format Module specification. It returns a structured object containing the parsed design tokens, groups and the potential errors found during the parsing and validation processes.
Installation
Using npm
$ npm install @nclsndr/w3c-design-tokens-parser
Using yarn
$ yarn add @nclsndr/w3c-design-tokens-parser
Using pnpm
$ pnpm add @nclsndr/w3c-design-tokens-parser
Usage
Parse a JSON token tree
The main API of the package is the parseJSONTokenTree
function. It takes a JSON object representing the design tokens tree and returns an Either (from Effect) type wrapping either, an object literal containing the parsed tokens, groups and their validation errors; either, a parse error encountered with the input.
import { Either } from 'effect'
import { parseJSONTokenTree } from '@nclsndr/w3c-design-tokens-parser';
const designTokens = {
color: {
$type: 'color',
primary: {
$value: '#ff0000',
},
}
}
const parsedJSONTokenTree = parseJSONTokenTree(designTokens);
const matched = Either.match(result, {
onRight: (r) => {
const errors = [...r.tokenErrors, ...r.groupErrors];
if (errors.length) {
throw new Error(errors.map((e) => e.message).join('\n'));
}
return {
tokens: r.analyzedTokens,
groups: r.analyzedGroups,
}
},
onLeft: (err) => {
throw new Error(err.map(e => e.message).join('\n'));
},
})
API
parseJSONTokenTree
type ParsedJSONTokenTree = Either.Either<{
tokenTree: JSONTypes.Object;
analyzedTokens: Array<AnalyzedToken>;
analyzedGroups: Array<AnalyzedGroup>;
tokenErrors: Array<ValidationError>;
groupErrors: Array<ValidationError>;
}, ValidationError[]>;
declare function parseJSONTokenTree(input: unknown): ParsedJSONTokenTree;