@link-foundation/ui-tokens 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md CHANGED
@@ -1,3 +1,255 @@
1
- # Temporary Holding Version
1
+ # @link-foundation/ui-tokens
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Design tokens of the associative UI framework, written in Links Notation:
4
+ token sets that extend each other, aliases between tokens and modes such as
5
+ `dark`. The package reads them, resolves them, and writes them as CSS custom
6
+ properties, a [DTCG 2025.10](https://www.designtokens.org/tr/2025.10/format/)
7
+ token file, SwiftUI constants and Jetpack Compose constants. It can also read
8
+ a DTCG file back as Links Notation, and it can hand the tokens to
9
+ [Style Dictionary](https://styledictionary.com) for other platforms.
10
+
11
+ The theme entry point also uses `@link-foundation/ui-style`. Style Dictionary
12
+ is an optional peer dependency, and it is loaded only by
13
+ `@link-foundation/ui-tokens/style-dictionary`.
14
+
15
+ ```js
16
+ import { readTokens, resolveTokens, toCss } from '@link-foundation/ui-tokens';
17
+
18
+ const { sets, diagnostics } = readTokens(`
19
+ (material3: theme
20
+ (extends base)
21
+ (token color.primary '#6750A4')
22
+ (token color.on-primary '#FFFFFF')
23
+ (token space.medium 16px)
24
+ (token shape.corner.medium 12px)
25
+ (token motion.duration.short 150ms))
26
+ `);
27
+
28
+ const resolved = resolveTokens(sets, 'material3');
29
+ console.log(toCss(resolved));
30
+ // :root {
31
+ // --color-primary: #6750a4;
32
+ // --color-on-primary: #ffffff;
33
+ // --space-medium: 16px;
34
+ // --shape-corner-medium: 12px;
35
+ // --motion-duration-short: 150ms;
36
+ // }
37
+ console.log(resolved.diagnostics.map((d) => d.code)); // ['unknown-set']: no base here
38
+ ```
39
+
40
+ The complete example is `examples/ui-tokens-basics.mjs` in the repository.
41
+
42
+ ## Grammar
43
+
44
+ A token set is a `theme` element with an id. It contains tokens, at most one
45
+ `extends` link and any number of modes:
46
+
47
+ ```lino
48
+ brand: theme
49
+ extends base
50
+ token PATH VALUE
51
+ type TYPE
52
+ description 'text'
53
+ token color.action
54
+ token color.primary
55
+ mode dark
56
+ token color.primary '#D0BCFF'
57
+ ```
58
+
59
+ | Link | Meaning |
60
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------ |
61
+ | `(token PATH VALUE ...)` | A token. `PATH` is a set of names separated by dots (`color.on-primary`), without `{`, `}` or a leading `$`. |
62
+ | `(type TYPE)` | Optional. Without it, the type is taken from how the value is written (see below). |
63
+ | `(description 'text')` | Optional. It is written as a CSS comment, `$description`, or a Swift or Kotlin doc comment. |
64
+ | `(token a (token b))` | An alias: `a` has the value of `b`. With `(type T)`, the type of `b` must be `T`. |
65
+ | `(extends base other)` | The tokens of `base`, then of `other`, then the set's own tokens; each one overrides the ones before it. |
66
+ | `(mode NAME (token ...) ...)` | Tokens that replace the set's own tokens when the mode `NAME` is active. |
67
+
68
+ Elements other than `theme` are ignored, so tokens can be kept in the same
69
+ file as a UI document.
70
+
71
+ ### Types
72
+
73
+ | Type | Written as | Inferred from |
74
+ | ------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
75
+ | `color` | `'#6750A4'`, `'#00000080'`, `(oklch 0.7 0.15 300)`, `(rgb ...)`, `(hsl ...)` | the hex string or the colour function |
76
+ | `dimension` | `16px`, `1rem`, `0`: only px and rem, as in DTCG 2025.10 section 8.2 | the unit |
77
+ | `duration` | `150ms`, `0.2s` | the unit |
78
+ | `number` | `0.38`, `1.5` | a plain number |
79
+ | `fontFamily` | `Roboto 'Noto Sans' sans-serif` | any other name or list of names |
80
+ | `fontWeight` | `400`, `bold`, `semi-bold` (the DTCG names) | a weight name; numbers need the type |
81
+ | `cubicBezier` | `(cubic-bezier 0.2 0 0 1)` | the head |
82
+ | `shadow` | `(shadow (color ...) (offset-x 0px) (offset-y 1px) (blur 3px) (spread 0px) (inset true))` | the head |
83
+ | `typography` | `(typography (font-family ...) (font-size 16px) (font-weight 400) (letter-spacing 0.5px) (line-height 1.5))` | the head |
84
+
85
+ A number such as `400` is read as a `number`, so a numeric font weight needs
86
+ `(type fontWeight)`. The field of a shadow or typography value can be an
87
+ alias: `(color (token color.scrim))`. A layered shadow lists its layers, and
88
+ each layer is a `(shadow ...)` or an alias to a shadow token:
89
+
90
+ ```lino
91
+ token elevation.high
92
+ token elevation.low
93
+ shadow
94
+ color '#0000004D'
95
+ offset-x 0px
96
+ offset-y 4px
97
+ blur 8px
98
+ spread 3px
99
+ ```
100
+
101
+ ## API
102
+
103
+ ### `readTokens(text)`
104
+
105
+ Returns `{ sets, diagnostics }`. `sets` is a `Map` of set id to
106
+ `{ id, extends, tokens, modes }`. It never throws: syntax errors and bad
107
+ tokens are diagnostics (`syntax-error`, `anonymous-set`, `invalid-token`,
108
+ `invalid-mode`, `invalid-value`, `unknown-type`, `duplicate-token`), in the
109
+ shape of ui-core diagnostics: `{ code, severity, message, at }`.
110
+
111
+ ### `resolveTokens(sets, setId, { mode })`
112
+
113
+ Returns a `Map` of path to `{ path, type, value, raw, alias?, description?, set, mode? }`
114
+ with the extra properties `setId`, `mode`, `modes` and `diagnostics`.
115
+
116
+ 1. **extends**: the parent sets are taken depth first, in the order written,
117
+ followed by the set itself. A later set overrides an earlier one.
118
+ 2. **modes**: in each set of that chain, the tokens of the selected mode
119
+ override that set's own tokens.
120
+ 3. **aliases**: `(token a.b)` is replaced by the resolved value of `a.b`. This
121
+ applies to a whole value, a composite field and a shadow layer. The token
122
+ keeps `alias: 'a.b'`, so the writers can keep the reference.
123
+
124
+ `modes` maps every other mode of the chain to the tokens that resolve
125
+ differently in it, or exist only in it. The writers use it to output every
126
+ mode in one file.
127
+
128
+ | Diagnostic | Severity | When |
129
+ | --------------- | -------- | ------------------------------------------------------------------------- |
130
+ | `unknown-set` | error | `setId` does not exist (a warning when the missing set is a parent) |
131
+ | `extends-cycle` | error | `(a: theme (extends b))` `(b: theme (extends a))` |
132
+ | `unknown-mode` | warning | no set of the chain has the mode |
133
+ | `unknown-alias` | error | an alias names a token that does not exist |
134
+ | `alias-cycle` | error | `a -> b -> a`; `at.cycle` is `['b', 'a', 'b']` when it is reported on `b` |
135
+ | `type-mismatch` | error | `(token a (token b) (type color))`, where `b` is a dimension |
136
+
137
+ A token whose alias cannot be resolved is left out of the result.
138
+
139
+ ### `toCss(resolved, options?)`
140
+
141
+ | Option | Default | Meaning |
142
+ | -------------- | --------------------------- | ------------------------------------------------------------------------ |
143
+ | `selector` | `:root` | The rule that holds the tokens. |
144
+ | `prefix` | `''` | `md` gives `--md-color-primary`. |
145
+ | `modeSelector` | `(m) => [data-mode="${m}"]` | The rule of a mode, with the tokens the mode changes. |
146
+ | `modeMedia` | `{}` | `{ dark: '(prefers-color-scheme: dark)' }` puts a mode in a media query. |
147
+
148
+ Aliases stay `var(--color-primary)`, so a change to the target at run time
149
+ reaches its aliases. A typography token is written as one property per field
150
+ (`--type-body-font-size`), because CSS has no typography value.
151
+
152
+ ### `toDtcg(resolved, { keepAliases = true })` and `fromDtcg(json, { id })`
153
+
154
+ `toDtcg` returns the object of a `.tokens.json` file. Every token has
155
+ `$type`, colours use the Color Module form (`{ colorSpace, components, alpha, hex }`),
156
+ dimensions and durations are `{ value, unit }`, and aliases stay
157
+ `"{color.primary}"` unless `keepAliases` is `false`. A token whose path is
158
+ also a group is written as the group's `$root`. DTCG 2025.10 has no modes, so
159
+ the tokens a mode changes go to
160
+ `$extensions["com.github.link-foundation.ui"].modes[mode]` (`DTCG_EXTENSION`).
161
+
162
+ `fromDtcg` reads a DTCG file (its text or its object) back as a Links
163
+ Notation token set. `fromDtcg(toDtcg(resolved))` gives the same tokens and
164
+ modes again. It also reads `{ "$ref": "#/a/b/$value" }` references, a group's
165
+ `$type`, and other colour spaces when they have a `hex` fallback. It throws a
166
+ `TypeError` naming the token for anything that has no Links Notation form.
167
+
168
+ ### `toSwift(resolved, { name = 'Tokens' })`
169
+
170
+ A `public enum Tokens` of SwiftUI constants:
171
+
172
+ | Token | Swift |
173
+ | ------------- | ----------------------------------------- |
174
+ | `color` | `Color(red:green:blue:opacity:)` (sRGB) |
175
+ | `dimension` | `CGFloat` points (1rem = 16) |
176
+ | `duration` | `TimeInterval` seconds |
177
+ | `number` | `Double` |
178
+ | `fontFamily` | `[String]` |
179
+ | `fontWeight` | `Font.Weight` (the nearest one) |
180
+ | `cubicBezier` | `(x1:y1:x2:y2:)` tuple of `Double` |
181
+ | `shadow` | `Shadow` or `[Shadow]` (generated struct) |
182
+ | `typography` | `Typography` (generated struct) |
183
+
184
+ ### `toKotlin(resolved, { packageName, name = 'Tokens' })`
185
+
186
+ An `object Tokens` of Jetpack Compose constants: `Color(0xAARRGGBB)`, `Dp`
187
+ (1rem = 16.dp), `const val ...Ms` milliseconds, `Float`, `List<String>`,
188
+ `FontWeight(n)`, `CubicBezierEasing`, and generated `Shadow` and `Typography`
189
+ data classes. An alias target is declared before its aliases, because an
190
+ object initialises its properties in order.
191
+
192
+ In both languages an alias is written as its target's constant, and each mode
193
+ is a nested namespace (`Tokens.Dark`) with the constants the mode changes.
194
+ Two tokens that would get the same constant name (`color.on-primary` and
195
+ `color.onPrimary`) cause a `TypeError`.
196
+
197
+ ### `buildWithStyleDictionary(resolved, config, options?)`
198
+
199
+ From `@link-foundation/ui-tokens/style-dictionary`. It writes the tokens as
200
+ a temporary DTCG file, makes it the `source` of the Style Dictionary
201
+ `config`, builds all platforms and returns the Style Dictionary instance. Use
202
+ it for platforms this package does not write itself (SCSS, Android XML,
203
+ Flutter and so on):
204
+
205
+ ```js
206
+ import { buildWithStyleDictionary } from '@link-foundation/ui-tokens/style-dictionary';
207
+
208
+ await buildWithStyleDictionary(resolveTokens(sets, 'brand', { mode: 'dark' }), {
209
+ platforms: {
210
+ scss: {
211
+ transformGroup: 'scss',
212
+ buildPath: 'out/',
213
+ files: [{ destination: '_dark.scss', format: 'scss/variables' }],
214
+ },
215
+ },
216
+ });
217
+ ```
218
+
219
+ Style Dictionary has no modes, so a build writes only the mode it was
220
+ resolved with. Install `style-dictionary` (version 4 or later) yourself;
221
+ otherwise the call fails with a message that says so. `options.StyleDictionary`
222
+ supplies the class, and `options.keepAliases` is passed on to `toDtcg`.
223
+
224
+ ## CLI
225
+
226
+ ```sh
227
+ link-ui-tokens build tokens.lino --set material3 \
228
+ --css out/tokens.css --dtcg out/tokens.json \
229
+ --swift out/Tokens.swift --kotlin out/Tokens.kt --package com.example.tokens
230
+ link-ui-tokens build tokens.lino --mode-media 'dark=(prefers-color-scheme: dark)'
231
+ link-ui-tokens import tokens.json --id material3 --out tokens.lino
232
+ ```
233
+
234
+ `build` resolves one set and writes each output that is asked for. Without
235
+ any output, it prints the CSS. `--set` can be left out when the file has a
236
+ single set. `--mode`, `--prefix`, `--selector`, `--name` and
237
+ `--resolve-aliases` correspond to the options above. Diagnostics go to
238
+ stderr. The exit code is 1 when there is an error diagnostic and 2 for bad
239
+ usage.
240
+
241
+ ## License
242
+
243
+ [Unlicense](LICENSE): public domain.
244
+
245
+ ## Themes
246
+
247
+ `@link-foundation/ui-tokens/themes` exports `loadThemes`, `resolveTheme`,
248
+ `compileThemeCss`, `contrastRatio`, `ensureContrast`, `resolveTemplate`,
249
+ `themeBootScript` and `exportThemeResolver`. See the
250
+ [theme contract](../../docs/spec/themes.md) and
251
+ [base theme package](../ui-themes/README.md).
252
+
253
+ Material 3 theme tokens may include `m3 md.sys.color.primary` metadata. The
254
+ loader preserves this original source name as `token.m3` for reverse exporters;
255
+ it does not participate in value typing or alias resolution.
package/bin/cli.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@link-foundation/ui-tokens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Design tokens of the associative UI framework written in Links Notation, with inheritance, aliases and modes, exported to CSS custom properties, DTCG 2025.10 JSON, Swift and Kotlin",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "default": "./src/index.js"
10
+ },
11
+ "./style-dictionary": {
12
+ "types": "./src/style-dictionary.d.ts",
13
+ "default": "./src/style-dictionary.js"
14
+ },
15
+ "./themes": {
16
+ "types": "./src/themes/index.d.ts",
17
+ "default": "./src/themes/index.js"
18
+ }
19
+ },
20
+ "types": "./src/index.d.ts",
21
+ "bin": {
22
+ "link-ui-tokens": "./bin/cli.js"
23
+ },
24
+ "files": [
25
+ "bin/",
26
+ "src/",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "keywords": [
31
+ "ui",
32
+ "links-notation",
33
+ "design-tokens",
34
+ "dtcg",
35
+ "css-custom-properties",
36
+ "swift",
37
+ "kotlin"
38
+ ],
39
+ "license": "Unlicense",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/link-foundation/ui.git",
43
+ "directory": "packages/ui-tokens"
44
+ },
45
+ "homepage": "https://github.com/link-foundation/ui/tree/main/packages/ui-tokens#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/link-foundation/ui/issues"
48
+ },
49
+ "engines": {
50
+ "node": ">=20"
51
+ },
52
+ "dependencies": {
53
+ "@link-foundation/ui-core": "^0.1.0",
54
+ "@link-foundation/ui-style": "^0.1.0"
55
+ },
56
+ "peerDependencies": {
57
+ "style-dictionary": ">=4.0.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "style-dictionary": {
61
+ "optional": true
62
+ }
63
+ },
64
+ "devDependencies": {
65
+ "ajv": "^6.15.0",
66
+ "test-anywhere": "^0.8.48"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ }
71
+ }
package/src/cli.js ADDED
@@ -0,0 +1,185 @@
1
+ /**
2
+ * The `link-ui-tokens` command line:
3
+ *
4
+ * ```sh
5
+ * link-ui-tokens build tokens.lino --set material3 \
6
+ * --css out.css --dtcg out.json --swift Tokens.swift --kotlin Tokens.kt
7
+ * link-ui-tokens import tokens.json --id material3 --out tokens.lino
8
+ * ```
9
+ *
10
+ * `main(argv, io)` does the work and returns the exit code, so that tests
11
+ * run it in-process on every runtime; `bin/cli.js` calls it.
12
+ */
13
+
14
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
15
+ import { dirname } from 'node:path';
16
+ import { parseArgs } from 'node:util';
17
+ import { toCss } from './export/css.js';
18
+ import { toDtcg } from './export/dtcg.js';
19
+ import { toKotlin } from './export/kotlin.js';
20
+ import { toSwift } from './export/swift.js';
21
+ import { fromDtcg } from './import/dtcg.js';
22
+ import { readTokens } from './model.js';
23
+ import { resolveTokens } from './resolve.js';
24
+
25
+ export const USAGE = `Usage:
26
+ link-ui-tokens build FILE.lino [--set ID] [--mode NAME]
27
+ [--css FILE] [--dtcg FILE] [--swift FILE] [--kotlin FILE]
28
+ [--prefix P] [--selector S] [--mode-media NAME=QUERY]...
29
+ [--name Tokens] [--package com.example.tokens] [--resolve-aliases]
30
+ link-ui-tokens import FILE.tokens.json [--id ID] [--out FILE.lino]
31
+
32
+ build resolve one token set and write it; CSS goes to stdout when no
33
+ output is given. --set may be left out when the file has one set.
34
+ import write a DTCG 2025.10 token file as a Links Notation token set.
35
+ `;
36
+
37
+ const OPTIONS = {
38
+ set: { type: 'string' },
39
+ mode: { type: 'string' },
40
+ css: { type: 'string' },
41
+ dtcg: { type: 'string' },
42
+ swift: { type: 'string' },
43
+ kotlin: { type: 'string' },
44
+ prefix: { type: 'string' },
45
+ selector: { type: 'string' },
46
+ 'mode-media': { type: 'string', multiple: true },
47
+ name: { type: 'string' },
48
+ package: { type: 'string' },
49
+ 'resolve-aliases': { type: 'boolean' },
50
+ id: { type: 'string' },
51
+ out: { type: 'string' },
52
+ help: { type: 'boolean', short: 'h' },
53
+ };
54
+
55
+ /** @typedef {{ stdout: (text: string) => void, stderr: (text: string) => void }} Io */
56
+
57
+ const defaultIo = {
58
+ stdout: (text) => process.stdout.write(text),
59
+ stderr: (text) => process.stderr.write(text),
60
+ };
61
+
62
+ async function write(file, text) {
63
+ await mkdir(dirname(file), { recursive: true });
64
+ await writeFile(file, text);
65
+ }
66
+
67
+ /** Print diagnostics; whether any is an error. */
68
+ function report(diagnostics, file, io) {
69
+ for (const d of diagnostics) {
70
+ io.stderr(`${file}: ${d.severity}: ${d.message} [${d.code}]\n`);
71
+ }
72
+ return diagnostics.some((d) => d.severity === 'error');
73
+ }
74
+
75
+ function modeMedia(entries = []) {
76
+ return Object.fromEntries(
77
+ entries.map((entry) => {
78
+ const i = entry.indexOf('=');
79
+ if (i <= 0) {
80
+ throw new Error(`--mode-media wants NAME=QUERY, not "${entry}"`);
81
+ }
82
+ return [entry.slice(0, i), entry.slice(i + 1)];
83
+ })
84
+ );
85
+ }
86
+
87
+ async function build(file, values, io) {
88
+ const { sets, diagnostics } = readTokens(await readFile(file, 'utf8'));
89
+ if (report(diagnostics, file, io)) {
90
+ return 1;
91
+ }
92
+ const setId =
93
+ values.set ?? (sets.size === 1 ? [...sets.keys()][0] : undefined);
94
+ if (setId === undefined) {
95
+ io.stderr(
96
+ `${file}: --set is needed; the sets are: ${[...sets.keys()].join(', ')}\n`
97
+ );
98
+ return 2;
99
+ }
100
+ const resolved = resolveTokens(sets, setId, { mode: values.mode ?? null });
101
+ if (report(resolved.diagnostics, file, io)) {
102
+ return 1;
103
+ }
104
+ const outputs = [
105
+ [
106
+ 'css',
107
+ () =>
108
+ toCss(resolved, {
109
+ prefix: values.prefix,
110
+ selector: values.selector,
111
+ modeMedia: modeMedia(values['mode-media']),
112
+ }),
113
+ ],
114
+ [
115
+ 'dtcg',
116
+ () =>
117
+ `${JSON.stringify(toDtcg(resolved, { keepAliases: !values['resolve-aliases'] }), null, 2)}\n`,
118
+ ],
119
+ ['swift', () => toSwift(resolved, { name: values.name })],
120
+ [
121
+ 'kotlin',
122
+ () =>
123
+ toKotlin(resolved, { name: values.name, packageName: values.package }),
124
+ ],
125
+ ];
126
+ const wanted = outputs.filter(([key]) => values[key] !== undefined);
127
+ if (wanted.length === 0) {
128
+ io.stdout(outputs[0][1]());
129
+ }
130
+ for (const [key, render] of wanted) {
131
+ await write(values[key], render());
132
+ }
133
+ return 0;
134
+ }
135
+
136
+ async function importDtcg(file, values, io) {
137
+ const text = fromDtcg(await readFile(file, 'utf8'), { id: values.id });
138
+ if (values.out === undefined) {
139
+ io.stdout(text);
140
+ } else {
141
+ await write(values.out, text);
142
+ }
143
+ return 0;
144
+ }
145
+
146
+ /**
147
+ * Run the command line.
148
+ * @param {string[]} argv the arguments after the program name
149
+ * @param {Io} [io]
150
+ * @returns {Promise<number>} the exit code
151
+ */
152
+ export async function main(argv, io = defaultIo) {
153
+ let parsed;
154
+ try {
155
+ parsed = parseArgs({
156
+ args: argv,
157
+ options: OPTIONS,
158
+ allowPositionals: true,
159
+ });
160
+ } catch (error) {
161
+ io.stderr(`${error.message}\n\n${USAGE}`);
162
+ return 2;
163
+ }
164
+ const { values, positionals } = parsed;
165
+ const [command, file, ...extra] = positionals;
166
+ if (values.help || command === 'help') {
167
+ io.stdout(USAGE);
168
+ return 0;
169
+ }
170
+ const commands = { build, import: importDtcg };
171
+ if (
172
+ !Object.hasOwn(commands, command ?? '') ||
173
+ file === undefined ||
174
+ extra.length > 0
175
+ ) {
176
+ io.stderr(USAGE);
177
+ return 2;
178
+ }
179
+ try {
180
+ return await commands[command](file, values, io);
181
+ } catch (error) {
182
+ io.stderr(`link-ui-tokens: ${error.message}\n`);
183
+ return 1;
184
+ }
185
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Diagnostics of the token reader and resolver, in the shape of ui-core
3
+ * diagnostics: `{ code, severity, message, at }`, where `at` names the set,
4
+ * the token and the mode.
5
+ */
6
+
7
+ const token = (at) => (at.token === undefined ? '' : ` "${at.token}"`);
8
+ const set = (at) => (at.set === undefined ? '' : ` of the set "${at.set}"`);
9
+ const mode = (at) => (at.mode === undefined ? '' : ` in the mode "${at.mode}"`);
10
+ const of = (at) => `${token(at)}${set(at)}${mode(at)}`;
11
+
12
+ const MESSAGES = {
13
+ 'anonymous-set': () => 'A token set (a theme) has no id',
14
+ 'invalid-token': (at) =>
15
+ `The token${of(at)} is not (token PATH VALUE); a path is dot-separated names without {, } or a leading $`,
16
+ 'invalid-mode': (at) => `A mode${set(at)} has no name`,
17
+ 'invalid-value': (at) =>
18
+ `The token${of(at)} has a value that is not ${at.type === undefined ? 'a token value' : `a ${at.type}`}`,
19
+ 'unknown-type': (at) =>
20
+ `The token${of(at)} has the unknown type "${at.type}"`,
21
+ 'duplicate-token': (at) =>
22
+ `The token${of(at)} is defined more than once; the last one wins`,
23
+ 'unknown-set': (at) =>
24
+ at.set === undefined
25
+ ? `The token set "${at.target}" does not exist`
26
+ : `The token set "${at.set}" extends "${at.target}", which does not exist`,
27
+ 'extends-cycle': (at) =>
28
+ `The token set "${at.set}" extends itself through ${at.cycle.join(' -> ')}`,
29
+ 'unknown-mode': (at) =>
30
+ `No set of the chain${set(at)} has the mode "${at.mode}"`,
31
+ 'unknown-alias': (at) =>
32
+ `The token${of(at)} refers to the unknown token "${at.target}"`,
33
+ 'alias-cycle': (at) =>
34
+ `The token${of(at)} refers to itself through ${at.cycle.join(' -> ')}`,
35
+ 'type-mismatch': (at) =>
36
+ `The token${of(at)} must be a ${at.expected} but "${at.target}" is a ${at.actual}`,
37
+ };
38
+
39
+ /**
40
+ * @param {string} code
41
+ * @param {'error'|'warning'|'info'} severity
42
+ * @param {Record<string, any>} at
43
+ * @returns {import('./types.js').Diagnostic}
44
+ */
45
+ export function tokenDiagnostic(code, severity, at) {
46
+ return { code, severity, message: MESSAGES[code](at), at };
47
+ }