@link-foundation/ui-tokens 0.0.0-stage → 0.0.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.
@@ -0,0 +1,195 @@
1
+ /**
2
+ * `toCss(resolved, options)`: CSS custom properties. Aliases stay
3
+ * `var(--color-primary)` so that a runtime change of the target cascades;
4
+ * a typography token becomes one property per field
5
+ * (`--type-body-font-size`), because CSS has no typography value.
6
+ */
7
+
8
+ import { values as coreValues } from '@link-foundation/ui-core';
9
+ import { rgba } from './native.js';
10
+ import { cssVariable } from '../names.js';
11
+ import { COMPOSITE_FIELDS, FONT_WEIGHTS } from '../values.js';
12
+
13
+ const { colorCss } = coreValues;
14
+
15
+ /**
16
+ * @typedef {import('../types.js').ResolvedTokens} ResolvedTokens
17
+ * @typedef {import('../types.js').ResolvedToken} ResolvedToken
18
+ * @typedef {import('../types.js').TokenValue} TokenValue
19
+ */
20
+
21
+ /** Generic families are keywords; other names are quoted strings. */
22
+ const GENERIC_FAMILIES = new Set([
23
+ 'serif',
24
+ 'sans-serif',
25
+ 'monospace',
26
+ 'cursive',
27
+ 'fantasy',
28
+ 'system-ui',
29
+ 'ui-serif',
30
+ 'ui-sans-serif',
31
+ 'ui-monospace',
32
+ 'ui-rounded',
33
+ 'math',
34
+ 'emoji',
35
+ 'fangsong',
36
+ ]);
37
+
38
+ const fontName = (name) =>
39
+ GENERIC_FAMILIES.has(name) ? name : `"${name.replace(/["\\]/gu, '\\$&')}"`;
40
+
41
+ /** A colour as CSS; hex is lower-case (`#6750a4`). */
42
+ const color = (value) => {
43
+ const css = colorCss(value);
44
+ return css.startsWith('#') ? css.toLowerCase() : css;
45
+ };
46
+
47
+ /**
48
+ * One value as CSS text.
49
+ * @param {TokenValue} value as written, aliases kept
50
+ * @param {(path: string) => string} ref CSS of an alias
51
+ */
52
+ function valueCss(value, ref) {
53
+ switch (value.type) {
54
+ case 'token-ref':
55
+ return ref(value.path);
56
+ case 'color':
57
+ return color(value);
58
+ case 'dimension':
59
+ case 'duration':
60
+ return `${value.value}${value.unit}`;
61
+ case 'number':
62
+ return String(value.value);
63
+ case 'fontFamily':
64
+ return [value.value]
65
+ .flat()
66
+ .flatMap((name) => name.split(',').map((part) => part.trim()))
67
+ .map(fontName)
68
+ .join(', ');
69
+ case 'fontWeight':
70
+ return String(FONT_WEIGHTS[value.value] ?? value.value);
71
+ case 'cubicBezier':
72
+ return `cubic-bezier(${value.value.join(', ')})`;
73
+ case 'shadow':
74
+ return [value.value]
75
+ .flat()
76
+ .map((layer) => shadowCss(layer, ref))
77
+ .join(', ');
78
+ default:
79
+ throw new TypeError(`No CSS value for the type ${value.type}`);
80
+ }
81
+ }
82
+
83
+ function shadowCss(layer, ref) {
84
+ if (layer.type === 'token-ref') {
85
+ return ref(layer.path);
86
+ }
87
+ const { color: c, offsetX, offsetY, blur, spread, inset } = layer;
88
+ const parts = [offsetX, offsetY, blur, spread, c].map((v) =>
89
+ valueCss(v, ref)
90
+ );
91
+ return `${inset ? 'inset ' : ''}${parts.join(' ')}`;
92
+ }
93
+
94
+ const kebab = (key) => key.replace(/[A-Z]/gu, (c) => `-${c.toLowerCase()}`);
95
+
96
+ /**
97
+ * The declarations of one token: `[name, value, description?]`.
98
+ * @param {ResolvedToken} token
99
+ */
100
+ function declarations(token, prefix, channels) {
101
+ const ref = (path) => `var(${cssVariable(path, prefix)})`;
102
+ const name = cssVariable(token.path, prefix);
103
+ if (token.type !== 'typography') {
104
+ const output = [[name, valueCss(token.raw, ref)]];
105
+ if (channels && token.type === 'color') {
106
+ const c = rgba(token.value);
107
+ output.push([
108
+ `${name}-rgb`,
109
+ token.raw.type === 'token-ref'
110
+ ? `var(${cssVariable(token.raw.path, prefix)}-rgb)`
111
+ : [c.r, c.g, c.b].map((n) => Number((n * 255).toFixed(6))).join(' '),
112
+ ]);
113
+ }
114
+ return output;
115
+ }
116
+ return COMPOSITE_FIELDS.typography.map(([field, key]) => [
117
+ `${name}-${field}`,
118
+ token.raw.type === 'token-ref'
119
+ ? `var(${cssVariable(token.raw.path, prefix)}-${kebab(key)})`
120
+ : valueCss(token.raw.value[key], ref),
121
+ ]);
122
+ }
123
+
124
+ const comment = (text) => `/* ${text.replace(/\*\//gu, '* /')} */`;
125
+
126
+ function block(selector, tokens, prefix, pad, channels) {
127
+ const lines = [`${pad}${selector} {`];
128
+ for (const token of tokens.values()) {
129
+ if (token.description !== undefined) {
130
+ lines.push(`${pad} ${comment(token.description)}`);
131
+ }
132
+ for (const [name, value] of declarations(token, prefix, channels)) {
133
+ lines.push(`${pad} ${name}: ${value};`);
134
+ }
135
+ }
136
+ lines.push(`${pad}}`);
137
+ return lines.join('\n');
138
+ }
139
+
140
+ /**
141
+ * The tokens as CSS custom properties: one rule for the resolved tokens and
142
+ * one per mode with the tokens the mode changes.
143
+ * @param {ResolvedTokens} resolved
144
+ * @param {{
145
+ * selector?: string,
146
+ * prefix?: string,
147
+ * modeSelector?: (mode: string) => string,
148
+ * modeMedia?: Record<string, string>,
149
+ * }} [options]
150
+ * `selector` (default `:root`) holds the tokens; `prefix` starts every
151
+ * name (`md` gives `--md-color-primary`); a mode's rule uses
152
+ * `modeSelector(mode)` (default `[data-mode="dark"]`) unless
153
+ * `modeMedia[mode]` gives a media query, then it is
154
+ * `@media QUERY { SELECTOR { ... } }`
155
+ * @returns {string}
156
+ */
157
+ export function toCss(
158
+ resolved,
159
+ {
160
+ selector = ':root',
161
+ prefix = '',
162
+ modeSelector = (mode) => `[data-mode="${mode}"]`,
163
+ modeMedia = {},
164
+ channels = false,
165
+ pack = false,
166
+ paletteSelector = (id) => `[data-palette=${JSON.stringify(id)}]`,
167
+ } = {}
168
+ ) {
169
+ if (pack) {
170
+ return [...resolved]
171
+ .map(([id, tokens]) => {
172
+ const scope = paletteSelector(id);
173
+ return toCss(tokens, {
174
+ selector: scope,
175
+ prefix,
176
+ channels,
177
+ modeMedia,
178
+ modeSelector: (mode) => `${scope}:is(${modeSelector(mode)})`,
179
+ });
180
+ })
181
+ .join('\n');
182
+ }
183
+ const rules = [block(selector, resolved, prefix, '', channels)];
184
+ for (const [mode, tokens] of resolved.modes ?? []) {
185
+ if (tokens.size === 0) {
186
+ continue;
187
+ }
188
+ rules.push(
189
+ Object.hasOwn(modeMedia, mode)
190
+ ? `@media ${modeMedia[mode]} {\n${block(selector, tokens, prefix, ' ', channels)}\n}`
191
+ : block(modeSelector(mode), tokens, prefix, '', channels)
192
+ );
193
+ }
194
+ return `${rules.join('\n\n')}\n`;
195
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * `toDtcg(resolved, { keepAliases })`: the tokens as a Design Tokens Format
3
+ * Module 2025.10 file (https://www.designtokens.org/tr/2025.10/format/),
4
+ * the nested JSON object of a `.tokens.json` file.
5
+ *
6
+ * - Every token has `$type` (section 5.2.2: tools "MUST NOT attempt to
7
+ * guess the type"), `$value` and, when written, `$description`.
8
+ * - Aliases stay aliases, `"{color.primary}"` (section 7.1.1), unless
9
+ * `keepAliases` is `false`; aliases inside composites stay too.
10
+ * - A token whose path is also a group (`a` and `a.b`) is the group's
11
+ * `$root` token (section 6.2), referenced as `"{a.$root}"`.
12
+ * - The tokens a mode changes go to the root
13
+ * `$extensions["com.github.link-foundation.ui"].modes[mode]`, a token
14
+ * group of the same shape: DTCG 2025.10 has no modes, and extensions are
15
+ * the place for "vendor-specific data" (section 5.2.3).
16
+ */
17
+
18
+ import { values as coreValues } from '@link-foundation/ui-core';
19
+ import { COMPOSITE_FIELDS } from '../values.js';
20
+
21
+ const { toHex } = coreValues;
22
+
23
+ /**
24
+ * @typedef {import('../types.js').ResolvedTokens} ResolvedTokens
25
+ * @typedef {import('../types.js').ResolvedToken} ResolvedToken
26
+ * @typedef {import('../types.js').TokenValue} TokenValue
27
+ */
28
+
29
+ /** The `$extensions` key of this package (reverse domain name notation). */
30
+ export const DTCG_EXTENSION = 'com.github.link-foundation.ui';
31
+
32
+ /** `x` with at most 4 decimals when that is still the same hex byte. */
33
+ const component = (x) => {
34
+ const short = Math.round(x * 10000) / 10000;
35
+ return Math.round(short * 255) === Math.round(x * 255) &&
36
+ Math.abs(x * 255 - Math.round(x * 255)) < 1e-9
37
+ ? short
38
+ : x;
39
+ };
40
+
41
+ /**
42
+ * A colour as a DTCG Color Module 2025.10 object. Section 4.1 "Format":
43
+ *
44
+ * > "colorSpace: A string that specifies the color space or color model
45
+ * > ... components: An array representing the color components. The number
46
+ * > of components depends on the color space. ... alpha (optional): A
47
+ * > number that represents the alpha value of the color. This value is
48
+ * > between 0 and 1, where 0 is fully transparent and 1 is fully opaque. If
49
+ * > omitted, the alpha value of the color MUST be assumed to be 1 (fully
50
+ * > opaque). hex (optional): A string that represents a fallback value of
51
+ * > the color. The fallback color MUST be formatted in 6 digit CSS hex
52
+ * > color notation format to avoid conflicts with the provided alpha
53
+ * > value."
54
+ *
55
+ * (https://www.designtokens.org/tr/2025.10/color/#format). sRGB components
56
+ * are 0..1; an sRGB channel that is an exact hex byte is written with 4
57
+ * decimals (`0x67 / 255` is `0.4039`), which reads back as the same byte.
58
+ * @param {TokenValue} color
59
+ */
60
+ function colorObject(color) {
61
+ const hex = toHex({ ...color, a: 1 }).toLowerCase();
62
+ if (color.space === 'oklch') {
63
+ return {
64
+ colorSpace: 'oklch',
65
+ components: [color.l, color.c, color.h],
66
+ alpha: color.a,
67
+ hex,
68
+ };
69
+ }
70
+ return {
71
+ colorSpace: 'srgb',
72
+ components: [color.r, color.g, color.b].map(component),
73
+ alpha: component(color.a),
74
+ hex,
75
+ };
76
+ }
77
+
78
+ /** `"{a.b}"`, or `"{a.b.$root}"` when `a.b` is also a group. */
79
+ const reference = (path, groups) =>
80
+ `{${groups.has(path) ? `${path}.$root` : path}}`;
81
+
82
+ /**
83
+ * A token value as a DTCG `$value`.
84
+ * @param {TokenValue} value
85
+ * @param {Set<string>} groups
86
+ */
87
+ function dtcgValue(value, groups) {
88
+ switch (value.type) {
89
+ case 'token-ref':
90
+ return reference(value.path, groups);
91
+ case 'color':
92
+ return colorObject(value);
93
+ case 'dimension':
94
+ case 'duration':
95
+ return { value: value.value, unit: value.unit };
96
+ case 'fontFamily':
97
+ return Array.isArray(value.value) ? [...value.value] : value.value;
98
+ case 'number':
99
+ case 'fontWeight':
100
+ return value.value;
101
+ case 'cubicBezier':
102
+ return [...value.value];
103
+ case 'shadow':
104
+ return Array.isArray(value.value)
105
+ ? value.value.map((layer) => shadowLayer(layer, groups))
106
+ : shadowLayer(value.value, groups);
107
+ case 'typography':
108
+ return fields('typography', value.value, groups);
109
+ default:
110
+ throw new TypeError(`No DTCG value for the type ${value.type}`);
111
+ }
112
+ }
113
+
114
+ function fields(kind, object, groups) {
115
+ return Object.fromEntries(
116
+ COMPOSITE_FIELDS[kind].map(([, key]) => [
117
+ key,
118
+ dtcgValue(object[key], groups),
119
+ ])
120
+ );
121
+ }
122
+
123
+ function shadowLayer(layer, groups) {
124
+ if (layer.type === 'token-ref') {
125
+ return reference(layer.path, groups);
126
+ }
127
+ const out = fields('shadow', layer, groups);
128
+ if (layer.inset !== undefined) {
129
+ out.inset = layer.inset;
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /** Every path that has tokens under it: `a` for `a.b`. */
135
+ function groupPaths(maps) {
136
+ const groups = new Set();
137
+ for (const map of maps) {
138
+ for (const path of map.keys()) {
139
+ const parts = path.split('.');
140
+ for (let i = 1; i < parts.length; i += 1) {
141
+ groups.add(parts.slice(0, i).join('.'));
142
+ }
143
+ }
144
+ }
145
+ return groups;
146
+ }
147
+
148
+ /**
149
+ * Set an own property: a token path is input, and `parent[name] = value`
150
+ * with the name `__proto__` would replace the prototype (or, through
151
+ * `constructor`, reach `Object`); `JSON.parse` reads such a name back as an
152
+ * own property too.
153
+ */
154
+ const own = (object, name, value) =>
155
+ Object.defineProperty(object, name, {
156
+ value,
157
+ enumerable: true,
158
+ writable: true,
159
+ configurable: true,
160
+ });
161
+
162
+ /**
163
+ * The nested group of some tokens.
164
+ * @param {Map<string, ResolvedToken>} tokens
165
+ */
166
+ function group(tokens, groups, keepAliases) {
167
+ const root = {};
168
+ for (const token of tokens.values()) {
169
+ const node = {
170
+ $type: token.type,
171
+ $value: dtcgValue(keepAliases ? token.raw : token.value, groups),
172
+ };
173
+ if (token.description !== undefined) {
174
+ node.$description = token.description;
175
+ }
176
+ const parts = token.path.split('.');
177
+ if (groups.has(token.path)) {
178
+ parts.push('$root');
179
+ }
180
+ let parent = root;
181
+ for (const part of parts.slice(0, -1)) {
182
+ if (!Object.hasOwn(parent, part)) {
183
+ own(parent, part, {});
184
+ }
185
+ parent = parent[part];
186
+ }
187
+ own(parent, parts.at(-1), node);
188
+ }
189
+ return root;
190
+ }
191
+
192
+ /**
193
+ * The tokens as a DTCG 2025.10 token file.
194
+ * @param {ResolvedTokens} resolved
195
+ * @param {{ keepAliases?: boolean }} [options] `keepAliases` (default
196
+ * `true`) writes aliases as references; `false` writes resolved values
197
+ * @returns {Record<string, any>} the JSON object; `JSON.stringify` it
198
+ */
199
+ export function toDtcg(resolved, { keepAliases = true } = {}) {
200
+ const modes = [...(resolved.modes ?? [])].filter(([, t]) => t.size > 0);
201
+ const groups = groupPaths([resolved, ...modes.map(([, t]) => t)]);
202
+ const out = group(resolved, groups, keepAliases);
203
+ if (modes.length > 0) {
204
+ out.$extensions = {
205
+ [DTCG_EXTENSION]: {
206
+ modes: Object.fromEntries(
207
+ modes.map(([mode, tokens]) => [
208
+ mode,
209
+ group(tokens, groups, keepAliases),
210
+ ])
211
+ ),
212
+ },
213
+ };
214
+ }
215
+ return out;
216
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * `toKotlin(resolved, { packageName, name })`: the tokens as Jetpack
3
+ * Compose constants.
4
+ *
5
+ * ```kotlin
6
+ * package com.example.tokens
7
+ *
8
+ * import androidx.compose.ui.graphics.Color
9
+ * import androidx.compose.ui.unit.dp
10
+ *
11
+ * object Tokens {
12
+ * val ColorPrimary = Color(0xFF6750A4)
13
+ * val SpaceMedium = 16.dp
14
+ * const val MotionDurationShortMs = 150
15
+ * }
16
+ * ```
17
+ *
18
+ * colour -> `Color(0xAARRGGBB)`, dimension -> `Dp` (1rem = 16.dp),
19
+ * duration -> `const val ...Ms` milliseconds, number -> `const val` Float,
20
+ * fontFamily -> `List<String>`, fontWeight -> `FontWeight(n)`,
21
+ * cubicBezier -> `CubicBezierEasing`, shadow -> `Shadow` or
22
+ * `List<Shadow>`, typography -> `Typography` (both data classes are
23
+ * generated when used). An alias is its target's constant; a mode is a
24
+ * nested object (`Tokens.Dark`) with the constants the mode changes.
25
+ */
26
+
27
+ import { values as coreValues } from '@link-foundation/ui-core';
28
+ import { upperCamel } from '../names.js';
29
+ import {
30
+ aliasReference,
31
+ checkNames,
32
+ descriptionLines,
33
+ layers,
34
+ millis,
35
+ num,
36
+ points,
37
+ rgba,
38
+ sections,
39
+ usedTypes,
40
+ weight,
41
+ } from './native.js';
42
+
43
+ const { toHex } = coreValues;
44
+
45
+ /** @typedef {import('../types.js').ResolvedTokens} ResolvedTokens */
46
+
47
+ const constant = (token) =>
48
+ `${upperCamel(token.path)}${token.type === 'duration' ? 'Ms' : ''}`;
49
+
50
+ const float = (x) => `${num(x)}f`;
51
+ const dp = (d) => `${num(points(d))}.dp`;
52
+
53
+ /** `Color(0xAARRGGBB)`. */
54
+ function color(c) {
55
+ const hex = toHex({ type: 'color', space: 'srgb', ...rgba(c) });
56
+ const alpha = hex.length === 9 ? hex.slice(7) : 'FF';
57
+ return `Color(0x${alpha}${hex.slice(1, 7)})`;
58
+ }
59
+
60
+ const fontFamily = (f) =>
61
+ `listOf(${[f.value]
62
+ .flat()
63
+ .map((s) => JSON.stringify(s))
64
+ .join(', ')})`;
65
+
66
+ const shadowLayer = (l) =>
67
+ `Shadow(${color(l.color)}, ${dp(l.offsetX)}, ${dp(l.offsetY)}, ${dp(l.blur)}, ${dp(l.spread)}, ${l.inset === true})`;
68
+
69
+ /** `[const, expression]` of a resolved value. */
70
+ function kotlinValue(value) {
71
+ switch (value.type) {
72
+ case 'color':
73
+ return [false, color(value)];
74
+ case 'dimension':
75
+ return [false, dp(value)];
76
+ case 'duration':
77
+ return [true, num(millis(value))];
78
+ case 'number':
79
+ return [true, float(value.value)];
80
+ case 'fontFamily':
81
+ return [false, fontFamily(value)];
82
+ case 'fontWeight':
83
+ return [false, `FontWeight(${weight(value)})`];
84
+ case 'cubicBezier':
85
+ return [false, `CubicBezierEasing(${value.value.map(float).join(', ')})`];
86
+ case 'shadow': {
87
+ const all = layers(value).map(shadowLayer);
88
+ return [
89
+ false,
90
+ Array.isArray(value.value) ? `listOf(${all.join(', ')})` : all[0],
91
+ ];
92
+ }
93
+ default: {
94
+ const t = value.value;
95
+ return [
96
+ false,
97
+ `Typography(${fontFamily(t.fontFamily)}, ${num(points(t.fontSize))}.sp, FontWeight(${weight(t.fontWeight)}), ${num(points(t.letterSpacing))}.sp, ${float(t.lineHeight.value)})`,
98
+ ];
99
+ }
100
+ }
101
+ }
102
+
103
+ /** A KDoc comment: one line when the text is one line. */
104
+ function kdoc(text, pad) {
105
+ const body = descriptionLines(text.replaceAll('*/', '* /'));
106
+ return body.length === 1
107
+ ? [`${pad}/** ${body[0]} */`]
108
+ : [`${pad}/**`, ...body.map((l) => `${pad} * ${l}`), `${pad} */`];
109
+ }
110
+
111
+ /** The imports the used types need, sorted. */
112
+ function imports(types) {
113
+ const out = new Set();
114
+ const need = {
115
+ color: ['androidx.compose.ui.graphics.Color'],
116
+ dimension: ['androidx.compose.ui.unit.dp'],
117
+ shadow: ['androidx.compose.ui.unit.Dp'],
118
+ fontWeight: ['androidx.compose.ui.text.font.FontWeight'],
119
+ cubicBezier: ['androidx.compose.animation.core.CubicBezierEasing'],
120
+ typography: [
121
+ 'androidx.compose.ui.unit.TextUnit',
122
+ 'androidx.compose.ui.unit.sp',
123
+ ],
124
+ };
125
+ for (const type of types) {
126
+ for (const name of need[type] ?? []) {
127
+ out.add(name);
128
+ }
129
+ }
130
+ return [...out].sort().map((name) => `import ${name}`);
131
+ }
132
+
133
+ const DATA_CLASSES = {
134
+ shadow: [
135
+ ' data class Shadow(',
136
+ ' val color: Color,',
137
+ ' val offsetX: Dp,',
138
+ ' val offsetY: Dp,',
139
+ ' val blur: Dp,',
140
+ ' val spread: Dp,',
141
+ ' val inset: Boolean = false,',
142
+ ' )',
143
+ ],
144
+ typography: [
145
+ ' data class Typography(',
146
+ ' val fontFamily: List<String>,',
147
+ ' val fontSize: TextUnit,',
148
+ ' val fontWeight: FontWeight,',
149
+ ' val letterSpacing: TextUnit,',
150
+ ' val lineHeight: Float,',
151
+ ' )',
152
+ ],
153
+ };
154
+
155
+ /**
156
+ * The tokens as a Kotlin source file.
157
+ * @param {ResolvedTokens} resolved
158
+ * @param {{ packageName?: string, name?: string }} [options] the package
159
+ * (none when omitted) and the object name (default `Tokens`)
160
+ * @returns {string}
161
+ */
162
+ export function toKotlin(resolved, { packageName, name = 'Tokens' } = {}) {
163
+ const all = sections(resolved, name);
164
+ checkNames(all, constant);
165
+ const types = usedTypes(all);
166
+ const lines = [];
167
+ if (packageName !== undefined) {
168
+ lines.push(`package ${packageName}`, '');
169
+ }
170
+ const head = imports(types);
171
+ if (head.length > 0) {
172
+ lines.push(...head, '');
173
+ }
174
+ lines.push(`object ${name} {`);
175
+ for (const kind of ['shadow', 'typography']) {
176
+ if (types.has(kind)) {
177
+ lines.push(...DATA_CLASSES[kind], '');
178
+ }
179
+ }
180
+ for (const section of all) {
181
+ const pad = section.mode === null ? ' ' : ' ';
182
+ if (section.mode !== null) {
183
+ lines.push(
184
+ '',
185
+ ` /** The tokens the mode "${section.mode}" changes. */`
186
+ );
187
+ lines.push(` object ${section.scope[1]} {`);
188
+ }
189
+ for (const token of section.tokens.values()) {
190
+ if (token.description !== undefined) {
191
+ lines.push(...kdoc(token.description, pad));
192
+ }
193
+ const [isConst, expression] = kotlinValue(token.value);
194
+ const value =
195
+ token.alias === undefined
196
+ ? expression
197
+ : aliasReference(token, section, constant, resolved);
198
+ lines.push(
199
+ `${pad}${isConst ? 'const ' : ''}val ${constant(token)} = ${value}`
200
+ );
201
+ }
202
+ if (section.mode !== null) {
203
+ lines.push(' }');
204
+ }
205
+ }
206
+ lines.push('}');
207
+ return `${lines.join('\n')}\n`;
208
+ }