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 🙏

© 2024 – Pkg Stats / Ryan Hefner

design-tokens-format-module

v0.10.1

Published

A Typescript implementation of the Design Tokens Format Module specification

Downloads

295

Readme

Design Tokens Format Module

— A TypeScript implementation of the Design Tokens Format Module specification along with some utility functions

Abstract

This packages aims to provide the most agnostic JavaScript/TypeScript definitions from the Design Tokens Format Module specification, for library developers and tooling creators.

Join the conversation on the W3C Design Tokens Community Group repository.

⚠️ Please note, the DTCG specification is NOT stable yet, breaking changes might occur in the future.

Installation

Using npm

npm install design-tokens-format-module

Using yarn

yarn add design-tokens-format-module

Using pnpm

pnpm add design-tokens-format-module

Usage

This module provides all the type definitions and the most basic helpers required to work with a JSON design token tree.

Token tree

Constrain a JSON object that represents a design token tree.

import { JSONTokenTree } from 'design-tokens-format-module';

const tokenTree = {
  color: {
    primary: {
      $type: 'color',
      $value: '#000000',
    },
  },
  spacing: {
    small: {
      $type: 'dimension',
      $value: '8px',
    },
  },
} satisfies JSONTokenTree;

Design Token

Each design token type is available as a TypeScript namespace.

import {
  Color // Dimension, FontFamily... 
} from 'design-tokens-format-module';

declare function parseColorToken(token: unknown): Color.Token;
declare function parseColorValue(tokens: unknown): Color.Value;
declare function matchIsColorTokenTypeName(
  name: string,
): name is Color.TypeName;

Design token type names

All token type names are available as a constant.

import { tokenTypeNames } from 'design-tokens-format-module';

for(const tokenTypeName of tokenTypeNames) {
  // color, dimension...
}

All token types

All token type signatures are available within a type union.

import { DesignToken } from 'design-tokens-format-module';

declare function parseDesignToken(token: unknown): DesignToken;

Matchers

JSON values can be evaluated against the token signature

import { matchIsToken, matchIsTokenTypeName, matchIsAliasValue } from 'design-tokens-format-module';

function validateToken(token: unknown) {
  if (matchIsToken(token)) {
    const isValidType = matchIsTokenTypeName(token.$type ?? '');
    if(matchIsAliasValue(token.$value)) {
      // ...
    }
  }
  // ...
}

Alias utils

Alias values can be validated and parsed.

import { captureAliasPath } from 'design-tokens-format-module';

const result = captureAliasPath('{path.to.token}');

if(result.status === 'ok') {
  result.value // string[]
} else {
  switch (result.error.tag) {
    case 'TYPE_ERROR': {
      result.error.message // Expected a string value. Got [x].
      break;
    }
    case 'FORMAT_ERROR': {
      result.error.message // Expected an alias value. Got [x].
      break;
    }
  }
}

Enum-like constants

Some token types have a fixed set of values. These are available as constants.

import { fontWeightValues, strokeStyleStringValues, strokeStyleLineCapValues } from 'design-tokens-format-module';

Previous versions

The packages goal has shifted from being a generic parser — which requires way more feedback — to a reliable source of truth for the DTCG implementations in the JavaScript land.

The features and APIs available before version 0.9.0 has been relocated to a new location where they get revamped and improved.

Contributing

If you find any typos, errors, or additional improvements, feel free to contribute to the project.

Development

Install dependencies.

npm install

Run test in watch mode.

npm run test

Please add tests to cover the new functionality or bug fix you are working upon.

Before opening a PR

We expect the tests and the build to pass for a PR to be reviewed and merged.

npm run test --run
npm run build

API

AliasValue (type)

type AliasValue = `{${string}}`;

Json (namespace)

namespace Json {
  export type Value = JSONValue;
  export type Object = JSONObject;
  export type Array = JSONArray;
  export type Primitive = string | number | boolean | null;
}

JSONTokenTree (type)

type JSONTokenTree = {
  [key: string]: DesignToken | JSONTokenTree | GroupProperties;
} & GroupProperties;

Color,Dimension, ... (namespace)

namespace TokenTypeName {
  export type TypeName = TypeName;
  export type Value = Value;
  export type Token = Token;
}

DesignToken (type)

type DesignToken =
  | ColorToken
  | DimensionToken
  // | ...

TokenTypeName (type)

type TokenTypeName = 
  | 'color'
  | 'dimension'
  // | ... 

captureAliasPath (function)

const CAPTURE_ALIAS_PATH_ERRORS = {
  TYPE_ERROR: 'Expected a string value.',
  // ...
} as const;

type ValidationError = {
  [k in keyof Writable<typeof CAPTURE_ALIAS_PATH_ERRORS>]?: {
    message: string;
  };
};

type Result<T, E> =
  | {
  status: 'ok';
  value: T;
  error?: undefined;
}
  | {
  status: 'error';
  error: E;
  value?: undefined;
};

declare function captureAliasPath(
  value: unknown,
): Result<Array<string>, ValidationError>;
declare function captureAliasPath<AsString extends boolean | undefined>(
  value: unknown,
  asString: AsString,
): Result<AsString extends true ? string : Array<string>, ValidationError>;

Usage

const result = captureAliasPath('{path.to.token}');

if(result.status === 'ok') {
  result.value // string[]
} else {
  switch (result.error.tag) {
    case 'TYPE_ERROR': {
      result.error.message // Expected a string value. Got [x].
      break;
    }
    case 'FORMAT_ERROR': {
      result.error.message // Expected an alias value. Got [x].
      break;
    }
  }
}

matchIsAliasValue (function)

declare function matchIsAliasValue(candidate: unknown): candidate is AliasValue;

matchIsGroup (function)

declare function matchIsGroup(candidate: unknown): candidate is JSONTokenTree;

matchIsToken (function)

declare function matchIsToken(candidate: unknown): candidate is DesignToken;

matchIsTokenTypeName (function)

declare function matchIsTokenTypeName(candidate: unknown): candidate is TokenTypeName;

ALIAS_PATH_SEPARATOR (constant)

const ALIAS_PATH_SEPARATOR = '.';

tokenTypeNames (constant)

const tokenTypeNames = [
  'color',
  'dimension',
  // ...
] as const;

fontWeightValues (constant)

const fontWeightValues = [
  100,
  'thin',
  'hairline',
  // ...
] as const;

strokeStyleStringValues (constant)

const strokeStyleStringValues = [
  'solid',
  'dashed',
  // ...
] as const;

strokeStyleLineCapValues (constant)

const strokeStyleLineCapValues = [
  'round',
  'butt',
  // ...
] as const;