@digdir/designsystemet 1.13.2 → 1.13.3

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.
Files changed (74) hide show
  1. package/dist/bin/config.js +50 -658
  2. package/dist/bin/designsystemet.js +131 -4623
  3. package/dist/bin/options.js +22 -14
  4. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BorderValues.js +9 -0
  5. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowTypes.js +8 -0
  6. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowValues.js +13 -0
  7. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorModifierTypes.js +10 -0
  8. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorSpaceTypes.js +10 -0
  9. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/Properties.js +53 -0
  10. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/StrokeStyleValues.js +14 -0
  11. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenSetStatus.js +9 -0
  12. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenTypes.js +32 -0
  13. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TypographyValues.js +15 -0
  14. package/dist/node_modules/.pnpm/@tokens-studio_types@0.5.2/node_modules/@tokens-studio/types/dist/types/index.js +11 -0
  15. package/dist/package.js +5 -0
  16. package/dist/src/colors/colorMetadata.js +255 -261
  17. package/dist/src/colors/index.js +5 -522
  18. package/dist/src/colors/theme.js +104 -343
  19. package/dist/src/colors/types.js +22 -25
  20. package/dist/src/colors/utils.js +241 -154
  21. package/dist/src/config.js +103 -444
  22. package/dist/src/index.js +10 -3588
  23. package/dist/src/migrations/beta-to-v1.js +339 -537
  24. package/dist/src/migrations/codemods/css/plugins.js +31 -42
  25. package/dist/src/migrations/codemods/css/run.js +20 -151
  26. package/dist/src/migrations/color-rename-next49.js +44 -220
  27. package/dist/src/migrations/index.js +7 -577
  28. package/dist/src/tokens/build.js +39 -1816
  29. package/dist/src/tokens/create/files.js +43 -602
  30. package/dist/src/tokens/create/generators/$designsystemet.js +8 -97
  31. package/dist/src/tokens/create/generators/$metadata.js +17 -20
  32. package/dist/src/tokens/create/generators/$themes.js +137 -311
  33. package/dist/src/tokens/create/generators/primitives/color-scheme.js +68 -443
  34. package/dist/src/tokens/create/generators/primitives/globals.js +141 -147
  35. package/dist/src/tokens/create/generators/primitives/size.js +146 -156
  36. package/dist/src/tokens/create/generators/primitives/typography.js +213 -217
  37. package/dist/src/tokens/create/generators/semantic/color-modes.js +24 -59
  38. package/dist/src/tokens/create/generators/semantic/color.js +42 -326
  39. package/dist/src/tokens/create/generators/semantic/style.js +379 -382
  40. package/dist/src/tokens/create/generators/themes/theme.js +108 -392
  41. package/dist/src/tokens/create.js +47 -1591
  42. package/dist/src/tokens/format.js +38 -3324
  43. package/dist/src/tokens/generate-config.js +155 -298
  44. package/dist/src/tokens/index.js +3 -3344
  45. package/dist/src/tokens/process/configs/color.js +50 -1085
  46. package/dist/src/tokens/process/configs/semantic.js +45 -1083
  47. package/dist/src/tokens/process/configs/shared.js +18 -109
  48. package/dist/src/tokens/process/configs/size-mode.js +27 -1082
  49. package/dist/src/tokens/process/configs/size.js +32 -1083
  50. package/dist/src/tokens/process/configs/type-scale.js +49 -1083
  51. package/dist/src/tokens/process/configs/typography.js +63 -1084
  52. package/dist/src/tokens/process/configs.js +88 -1224
  53. package/dist/src/tokens/process/formats/css/color.js +58 -1079
  54. package/dist/src/tokens/process/formats/css/semantic.js +27 -1081
  55. package/dist/src/tokens/process/formats/css/size-mode.js +43 -1077
  56. package/dist/src/tokens/process/formats/css/size.js +86 -1079
  57. package/dist/src/tokens/process/formats/css/type-scale.js +53 -1083
  58. package/dist/src/tokens/process/formats/css/typography.js +27 -1081
  59. package/dist/src/tokens/process/formats/css.js +18 -1081
  60. package/dist/src/tokens/process/output/declarations.js +18 -1201
  61. package/dist/src/tokens/process/output/tailwind.js +26 -40
  62. package/dist/src/tokens/process/output/theme.js +73 -206
  63. package/dist/src/tokens/process/platform.js +165 -1355
  64. package/dist/src/tokens/process/transformers.js +49 -89
  65. package/dist/src/tokens/process/utils/getMultidimensionalThemes.js +100 -1183
  66. package/dist/src/tokens/process/utils/kebab-case.js +7 -5
  67. package/dist/src/tokens/types.js +6 -7
  68. package/dist/src/tokens/utils.js +102 -93
  69. package/dist/src/types.js +1 -5
  70. package/dist/src/utils/filesystem.js +112 -124
  71. package/package.json +10 -13
  72. package/configs/test-tokens.config.json +0 -82
  73. package/dist/src/scripts/createJsonSchema.js +0 -409
  74. package/dist/src/scripts/update-preview-tokens.js +0 -3353
@@ -1,4498 +1,19 @@
1
1
  #!/usr/bin/env node
2
-
3
- // bin/designsystemet.ts
4
- import path4 from "path";
5
- import { Argument, createCommand, program } from "@commander-js/extra-typings";
6
- import pc11 from "picocolors";
7
- import * as R28 from "ramda";
8
-
9
- // src/colors/colorMetadata.ts
10
- import * as R from "ramda";
11
- var baseColors = {
12
- info: "#0A71C0",
13
- success: "#068718",
14
- warning: "#EA9B1B",
15
- danger: "#C01B1B"
16
- };
17
- var dsLinkColor = "#663299";
18
- var colorMetadata = {
19
- "background-default": {
20
- number: 1,
21
- name: "background-default",
22
- group: "background",
23
- displayName: "Background Default",
24
- description: {
25
- long: "Background Default er den mest n\xF8ytrale bakgrunnsfargen.",
26
- short: "Standard bakgrunnsfarge."
27
- },
28
- luminance: {
29
- light: 1,
30
- dark: 9e-3,
31
- contrast: 1e-3
32
- }
33
- },
34
- "background-tinted": {
35
- number: 2,
36
- name: "background-tinted",
37
- group: "background",
38
- displayName: "Background Tinted",
39
- description: {
40
- long: "Background Tinted er en bakgrunnsfarge som har et hint av farge i seg.",
41
- short: "Bakgrunn med et hint av farge i seg."
42
- },
43
- luminance: {
44
- light: 0.9,
45
- dark: 0.014,
46
- contrast: 65e-4
47
- }
48
- },
49
- "surface-default": {
50
- number: 3,
51
- name: "surface-default",
52
- group: "surface",
53
- displayName: "Surface Default",
54
- description: {
55
- long: "Surface Default brukes p\xE5 flater som ligger opp\xE5 bakgrunnsfargene. Dette er den mest n\xF8ytrale surface fargen.",
56
- short: "Standardfarge for overflater / komponenter."
57
- },
58
- luminance: {
59
- light: 1,
60
- dark: 0.021,
61
- contrast: 0.015
62
- }
63
- },
64
- "surface-tinted": {
65
- number: 4,
66
- name: "surface-tinted",
67
- group: "surface",
68
- displayName: "Surface Tinted",
69
- description: {
70
- long: "Surface Tinted brukes p\xE5 flater som ligger opp\xE5 bakgrunnsfargene. Denne har et hint av farge i seg.",
71
- short: "Overflater / komponenter med et hint av farge i seg."
72
- },
73
- luminance: {
74
- light: 0.81,
75
- dark: 0.027,
76
- contrast: 0.015
77
- }
78
- },
79
- "surface-hover": {
80
- number: 5,
81
- name: "surface-hover",
82
- group: "surface",
83
- displayName: "Surface Hover",
84
- description: {
85
- long: "Surface Hover brukes p\xE5 interaktive flater som ligger opp\xE5 bakgrunnsfargene i en hover state.",
86
- short: "Hover-farge til overflater / komponenter."
87
- },
88
- luminance: {
89
- light: 0.7,
90
- dark: 0.036,
91
- contrast: 0.028
92
- }
93
- },
94
- "surface-active": {
95
- number: 6,
96
- name: "surface-active",
97
- group: "surface",
98
- displayName: "Surface Active",
99
- description: {
100
- long: "Surface Active brukes p\xE5 interaktive flater som ligger opp\xE5 bakgrunnsfargene i en active state.",
101
- short: "Active-farge til overflater / komponenter."
102
- },
103
- luminance: {
104
- light: 0.59,
105
- dark: 0.056,
106
- contrast: 0.045
107
- }
108
- },
109
- "border-subtle": {
110
- number: 7,
111
- name: "border-subtle",
112
- group: "border",
113
- displayName: "Border Subtle",
114
- description: {
115
- long: "Border Subtle er den lyseste border-fargen og brukes for \xE5 skille elementer fra hverandre.",
116
- short: "Border-farge med lav kontrast til dekorativ bruk (skillelinjer)."
117
- },
118
- luminance: {
119
- light: 0.5,
120
- dark: 0.08,
121
- contrast: 0.26
122
- }
123
- },
124
- "border-default": {
125
- number: 8,
126
- name: "border-default",
127
- group: "border",
128
- displayName: "Border Default",
129
- description: {
130
- long: "Border Default er en border-farge som brukes n\xE5r man \xF8nsker god kontrast mot bakgrunnsfargene.",
131
- short: "Standard border-farge til skjemakomponenter og meningsb\xE6rende elementer."
132
- },
133
- luminance: {
134
- light: 0.19,
135
- dark: 0.22,
136
- contrast: 0.4
137
- }
138
- },
139
- "border-strong": {
140
- number: 9,
141
- name: "border-strong",
142
- group: "border",
143
- displayName: "Border Strong",
144
- description: {
145
- long: "Border Strong er den m\xF8rkeste border-fargen og brukes n\xE5r man \xF8nsker en veldig tydelig og sterk border.",
146
- short: "Border-farge med h\xF8y kontrast for ekstra synlighet."
147
- },
148
- luminance: {
149
- light: 0.11,
150
- dark: 0.39,
151
- contrast: 0.6
152
- }
153
- },
154
- "text-subtle": {
155
- number: 10,
156
- name: "text-subtle",
157
- group: "text",
158
- displayName: "Text Subtle",
159
- description: {
160
- long: "Text Subtle er den lyseste tekstfargen og brukes p\xE5 tekst som skal v\xE6re litt mindre synlig eller for \xE5 skape variasjon i typografien.",
161
- short: "Tekst- og ikonfarge med lavere kontrast."
162
- },
163
- luminance: {
164
- light: 0.11,
165
- dark: 0.39,
166
- contrast: 0.57
167
- }
168
- },
169
- "text-default": {
170
- number: 11,
171
- name: "text-default",
172
- group: "text",
173
- displayName: "Text Default",
174
- description: {
175
- long: "Text Default er den m\xF8rkeste tekstfargen og brukes p\xE5 tekst som skal v\xE6re mest synlig. Denne fargen b\xF8r brukes p\xE5 mesteparten av teksten p\xE5 en side.",
176
- short: "Tekst- og ikonfarge med h\xF8y kontrast og god synlighet."
177
- },
178
- luminance: {
179
- light: 0.0245,
180
- dark: 0.84,
181
- contrast: 0.86
182
- }
183
- },
184
- "base-default": {
185
- number: 12,
186
- name: "base-default",
187
- group: "base",
188
- displayName: "Base Default",
189
- description: {
190
- long: "Base Default fargen f\xE5r den samme hex koden som fargen som er valgt i verkt\xF8yet. Brukes ofte som farge p\xE5 viktige elementer og p\xE5 flater som skal fange brukerens oppmerksomhet.",
191
- short: "Standardfarge for solide bakgrunner."
192
- },
193
- luminance: {
194
- light: 1,
195
- dark: 1,
196
- contrast: 1
197
- }
198
- },
199
- "base-hover": {
200
- number: 13,
201
- name: "base-hover",
202
- group: "base",
203
- displayName: "Base Hover",
204
- description: {
205
- long: "Base Hover brukes som hover farge p\xE5 elementer som bruker Base Default fargen.",
206
- short: "Hover-farge for solide bakgrunner."
207
- },
208
- luminance: {
209
- light: 1,
210
- dark: 1,
211
- contrast: 1
212
- }
213
- },
214
- "base-active": {
215
- number: 14,
216
- name: "base-active",
217
- group: "base",
218
- displayName: "Base Active",
219
- description: {
220
- long: "Base Active brukes som active farge p\xE5 elementer som bruker Base Default fargen.",
221
- short: "Active-farge for solide bakgrunner."
222
- },
223
- luminance: {
224
- light: 1,
225
- dark: 1,
226
- contrast: 1
227
- }
228
- },
229
- "base-contrast-subtle": {
230
- number: 15,
231
- name: "base-contrast-subtle",
232
- group: "base",
233
- displayName: "Contrast Subtle",
234
- description: {
235
- long: "Contrast Subtle brukes som en viktig meningsb\xE6rende farge opp\xE5 Base Default fargen.",
236
- short: "Farge med god kontrast mot Base-default."
237
- },
238
- luminance: {
239
- light: 1,
240
- dark: 1,
241
- contrast: 1
242
- }
243
- },
244
- "base-contrast-default": {
245
- number: 16,
246
- name: "base-contrast-default",
247
- group: "base",
248
- displayName: "Contrast Default",
249
- description: {
250
- long: "Contrast Default brukes som en viktig meningsb\xE6rende farge opp\xE5 alle Base fargane.",
251
- short: "Farge med god kontrast mot Base-default og Base-hover."
252
- },
253
- luminance: {
254
- light: 1,
255
- dark: 1,
256
- contrast: 1
257
- }
258
- }
259
- };
260
- var colorMetadataByNumber = R.indexBy((metadata) => metadata.number, Object.values(colorMetadata));
261
- var colorNames = Object.keys(colorMetadata);
262
- var baseColorNames = Object.keys(baseColors);
263
-
264
- // src/colors/theme.ts
265
- import chroma2 from "chroma-js";
266
- import * as R2 from "ramda";
267
-
268
- // src/colors/utils.ts
269
- import chroma from "chroma-js";
270
- import Colorjs from "colorjs.io";
271
- import { Hsluv } from "hsluv";
272
- var getLuminanceFromLightness = (lightness) => {
273
- const conv = new Hsluv();
274
- conv.hsluv_l = lightness;
275
- conv.hsluvToHex();
276
- return chroma(conv.hex).luminance();
277
- };
278
- var getLightnessFromHex = (hex) => {
279
- const conv = new Hsluv();
280
- conv.hex = hex;
281
- conv.hexToHsluv();
282
- return conv.hsluv_l;
283
- };
284
- var convertToHex = (color) => {
285
- if (!color) {
286
- return "#000000";
287
- }
288
- if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
289
- return color;
290
- }
291
- return chroma(color).hex();
292
- };
293
-
294
- // src/colors/theme.ts
295
- var RESERVED_COLORS = ["neutral", "success", "warning", "danger", "info"];
296
- var generateColorScale = (color, colorScheme2) => {
297
- let interpolationColor = color;
298
- if (colorScheme2 === "dark") {
299
- const [L, C, H] = chroma2(color).oklch();
300
- const chromaModifier = 0.7;
301
- interpolationColor = chroma2(L, C * chromaModifier, H, "oklch").hex();
302
- }
303
- const colors2 = R2.mapObjIndexed((colorData) => {
304
- const luminance = colorData.luminance[colorScheme2];
305
- return {
306
- ...colorData,
307
- hex: chroma2(interpolationColor).luminance(luminance).hex()
308
- };
309
- }, colorMetadata);
310
- const baseColors2 = generateBaseColors(color, colorScheme2);
311
- colors2["base-default"] = { ...colors2["base-default"], hex: baseColors2.default };
312
- colors2["base-hover"] = { ...colors2["base-hover"], hex: baseColors2.hover };
313
- colors2["base-active"] = { ...colors2["base-active"], hex: baseColors2.active };
314
- colors2["base-contrast-subtle"] = {
315
- ...colors2["base-contrast-subtle"],
316
- hex: generateColorContrast(baseColors2.default, "subtle")
317
- };
318
- colors2["base-contrast-default"] = {
319
- ...colors2["base-contrast-default"],
320
- hex: generateColorContrast(baseColors2.default, "default")
321
- };
322
- return Object.values(colors2);
323
- };
324
- var generateBaseColors = (color, colorScheme2) => {
325
- let colorLightness = getLightnessFromHex(color);
326
- if (colorScheme2 !== "light") {
327
- colorLightness = colorLightness <= 30 ? 70 : 100 - colorLightness;
328
- }
329
- const modifier = colorLightness <= 30 || colorLightness >= 49 && colorLightness <= 65 ? -8 : 8;
330
- const calculateLightness = (base, mod) => base - mod;
331
- return {
332
- default: colorScheme2 === "light" ? color : chroma2(color).luminance(getLuminanceFromLightness(colorLightness)).hex(),
333
- hover: chroma2(color).luminance(getLuminanceFromLightness(calculateLightness(colorLightness, modifier))).hex(),
334
- active: chroma2(color).luminance(getLuminanceFromLightness(calculateLightness(colorLightness, modifier * 2))).hex()
335
- };
336
- };
337
- var generateColorContrast = (color, type) => {
338
- if (type === "default") {
339
- return chroma2.contrast(color, "#ffffff") >= chroma2.contrast(color, "#000000") ? "#ffffff" : "#000000";
340
- }
341
- if (type === "subtle") {
342
- const contrastWhite = chroma2.contrast(color, "#ffffff");
343
- const contrastBlack = chroma2.contrast(color, "#000000");
344
- const lightness = getLightnessFromHex(color);
345
- const modifier = lightness <= 40 || lightness >= 60 ? 60 : 50;
346
- const targetLightness = contrastWhite >= contrastBlack ? lightness + modifier : lightness - modifier;
347
- return chroma2(color).luminance(getLuminanceFromLightness(targetLightness)).hex();
348
- }
349
- return color;
350
- };
351
-
352
- // src/colors/types.ts
353
- import * as R3 from "ramda";
354
- var semanticColorMap = {
355
- "background-default": 1,
356
- "background-tinted": 2,
357
- "surface-default": 3,
358
- "surface-tinted": 4,
359
- "surface-hover": 5,
360
- "surface-active": 6,
361
- "border-subtle": 7,
362
- "border-default": 8,
363
- "border-strong": 9,
364
- "text-subtle": 10,
365
- "text-default": 11,
366
- "base-default": 12,
367
- "base-hover": 13,
368
- "base-active": 14,
369
- "base-contrast-subtle": 15,
370
- "base-contrast-default": 16
371
- };
372
- var semanticColorNames = R3.keys(semanticColorMap);
373
- var semanticColorNumbers = R3.values(semanticColorMap);
374
-
375
- // src/migrations/codemods/css/plugins.ts
376
- import hash from "object-hash";
2
+ import { convertToHex } from "../src/colors/utils.js";
3
+ import "../src/colors/index.js";
4
+ import { cliOptions, createTokens } from "../src/tokens/create.js";
5
+ import { dsfs } from "../src/utils/filesystem.js";
6
+ import { parseCreateConfig, readConfigFile } from "./config.js";
7
+ import migrations_default from "../src/migrations/index.js";
8
+ import { buildTokens } from "../src/tokens/build.js";
9
+ import { createTokenFiles } from "../src/tokens/create/files.js";
10
+ import { generateConfigFromTokens } from "../src/tokens/generate-config.js";
377
11
  import pc from "picocolors";
378
- import * as R4 from "ramda";
379
- var printDelete = (text) => console.log(`${pc.red("Deleted:")} ${text}`.replace(/"|'/g, ""));
380
- var deleteMsg = (decl, from) => `${pc.yellow(from)} @ ${pc.gray(`${JSON.stringify(decl.source?.input.file)}:${decl.source?.start?.line}:${decl.source?.start?.column}`)}`;
381
- var cssClassRename = (dictionary) => ({
382
- postcssPlugin: `Renames CSS classes ${hash(dictionary)}`,
383
- Rule(rule) {
384
- const selector = rule.selector;
385
- if (!selector) return;
386
- for (const [from, to] of Object.entries(dictionary)) {
387
- if (!selector.includes(from)) return;
388
- const newSelector = selector.replace(new RegExp(from, "g"), to);
389
- rule.selector = newSelector;
390
- }
391
- }
392
- });
393
- var cssVarRename = (dictionary) => ({
394
- postcssPlugin: `Replaces CSS variables ${hash(dictionary)}`,
395
- Declaration(decl) {
396
- const { value, prop: prop3 } = decl;
397
- const deleted = /* @__PURE__ */ new Set();
398
- for (const [from, to] of Object.entries(dictionary)) {
399
- if (R4.isNotEmpty(to)) {
400
- if (to === "[delete]") {
401
- deleted.add(deleteMsg(decl, from));
402
- }
403
- if (R4.includes(from, value)) {
404
- decl.value = value.replace(from, to);
405
- continue;
406
- }
407
- if (R4.includes(from, prop3) && decl.variable) {
408
- decl.prop = prop3.replace(from, to);
409
- }
410
- }
411
- }
412
- if (deleted.size > 0) {
413
- Array.from(deleted).forEach(printDelete);
414
- }
415
- }
416
- });
417
-
418
- // src/migrations/codemods/css/run.ts
419
- import glob from "fast-glob";
420
- import postcss from "postcss";
421
-
422
- // src/utils/filesystem.ts
423
- import fs from "fs/promises";
424
- import path from "path";
425
- import pc2 from "picocolors";
426
- var FileSystem = class {
427
- isInitialized = false;
428
- dry = false;
429
- verbose = false;
430
- /** Default working directory is where the process was started */
431
- workingDir = process.cwd();
432
- outDir = this.workingDir;
433
- /** Initialize the file system */
434
- init({ dry, outdir, verbose }) {
435
- if (this.isInitialized) {
436
- console.warn(pc2.yellow("FileSystem is already initialized. Ignoring subsequent init call."));
437
- return;
438
- }
439
- if (dry) {
440
- console.log(pc2.blue("Initializing FileSystem in dry-run mode. No files will be written."));
441
- }
442
- this.dry = dry ?? false;
443
- this.verbose = verbose ?? false;
444
- this.outDir = outdir ? path.isAbsolute(outdir) ? outdir : path.join(this.workingDir, outdir) : this.workingDir;
445
- if (this.verbose) {
446
- console.log(
447
- `FileSystem initialized with workingDir: ${pc2.green(this.workingDir)}, outDir: ${pc2.green(this.outDir)}`
448
- );
449
- }
450
- this.isInitialized = true;
451
- }
452
- /**
453
- * Creates a directory if it does not already exist.
454
- *
455
- * @param dir - The path of the directory to create.
456
- *
457
- * @returns A promise that resolves when the operation is complete.
458
- * If the directory already exists or `dry` is `true`, the promise resolves immediately.
459
- */
460
- mkdir = async (dir) => {
461
- if (this.dry) {
462
- console.log(`${pc2.blue("mkdir")} ${dir}`);
463
- return Promise.resolve();
464
- }
465
- const exists = await fs.access(dir, fs.constants.F_OK).then(() => true).catch(() => false);
466
- if (exists) {
467
- return Promise.resolve();
468
- }
469
- return fs.mkdir(dir, { recursive: true });
470
- };
471
- writeFile = async (path5, data) => {
472
- if (this.dry) {
473
- console.log(`${pc2.blue("writeFile")} ${path5}`);
474
- return Promise.resolve();
475
- }
476
- return fs.writeFile(path5, data, { encoding: "utf-8" }).catch((error) => {
477
- console.error(pc2.red(`Error writing file: ${path5}`));
478
- console.error(pc2.red(error));
479
- throw error;
480
- });
481
- };
482
- cp = async (src, dest, filter) => {
483
- if (this.dry) {
484
- console.log(`${pc2.blue("cp")} ${src} ${dest}`);
485
- return Promise.resolve();
486
- }
487
- return fs.cp(src, dest, { recursive: true, filter });
488
- };
489
- copyFile = async (src, dest) => {
490
- if (this.dry) {
491
- console.log(`${pc2.blue("copyFile")} ${src} to ${dest}`);
492
- return Promise.resolve();
493
- }
494
- return fs.copyFile(src, dest);
495
- };
496
- cleanDir = async (dir) => {
497
- if (this.dry) {
498
- console.log(`${pc2.blue("cleanDir")} ${dir}`);
499
- return Promise.resolve();
500
- }
501
- console.log(`
502
- \u{1F525} Cleaning dir ${pc2.red(`${dir.trim()}`)} `);
503
- return fs.rm(dir, { recursive: true, force: true });
504
- };
505
- readFile = async (path5, allowFileNotFound) => {
506
- if (this.dry) {
507
- console.log(`${pc2.blue("readFile")} ${path5}`);
508
- }
509
- try {
510
- return await fs.readFile(path5, "utf-8");
511
- } catch (error) {
512
- if (allowFileNotFound && error.code === "ENOENT") {
513
- return "";
514
- }
515
- throw error;
516
- }
517
- };
518
- readdir = async (path5) => {
519
- if (this.dry) {
520
- console.log(`${pc2.blue("readdir")} ${path5}`);
521
- }
522
- try {
523
- return await fs.readdir(path5);
524
- } catch (error) {
525
- if (error.code === "ENOENT") {
526
- return [];
527
- }
528
- throw error;
529
- }
530
- };
531
- writeFiles = async (files, outDir, log) => {
532
- for (const { destination: filename, output } of files) {
533
- if (filename) {
534
- const filePath = path.join(outDir, filename);
535
- const fileDir = path.dirname(filePath);
536
- if (log) {
537
- console.log(filename);
538
- }
539
- await this.mkdir(fileDir);
540
- await this.writeFile(filePath, output);
541
- }
542
- }
543
- };
544
- };
545
- var dsfs = new FileSystem();
546
-
547
- // src/migrations/codemods/css/run.ts
548
- var runCssCodemod = async ({ plugins = [], globPattern = "./**/*.css" }) => {
549
- const processor = postcss(plugins);
550
- const transform = async () => {
551
- console.log(`Running migration in ${globPattern}`);
552
- const files = await glob([globPattern], {
553
- ignore: ["**/node_modules/**", "**/dist/**"],
554
- // TODO: Not working as expected
555
- absolute: true
556
- });
557
- const filePromises = files.map(async (file) => {
558
- if (file.includes("node_modules") || file.includes("dist")) {
559
- return;
560
- }
561
- const contents = await dsfs.readFile(file);
562
- const result = await processor.process(contents.toString(), { from: file });
563
- await dsfs.writeFile(file, result.css);
564
- });
565
- await Promise.all(filePromises);
566
- };
567
- return transform();
568
- };
569
-
570
- // src/migrations/beta-to-v1.ts
571
- var beta_to_v1_default = (glob2) => runCssCodemod({
572
- globPattern: glob2,
573
- plugins: [
574
- cssClassRename({
575
- ".fds-": ".ds-"
576
- }),
577
- // New component token prefixes
578
- cssVarRename({
579
- "--fds-accordion": "--dsc-accordion",
580
- "--fds-alert": "--dsc-alert",
581
- "--fds-btn": "--dsc-btn",
582
- "--fds-checkbox": "--dsc-checkbox",
583
- "--fdsc-chip": "--dsc-chip",
584
- "--fdsc-gap": "--dsc-chip-group-gap",
585
- "--fdsc-removable": "--dsc-removable",
586
- "--fdsc-bottom": "--dsc-bottom",
587
- "--fds-pagination": "--dsc-pagination",
588
- "--fds-popover": "--dsc-popover",
589
- "--fds-radio": "--dsc-radio",
590
- "--f-search": "--dsc-search",
591
- "--fds-skeleton": "--dsc-skeleton",
592
- "--fds-switch--transition": "--dsc-switch-transition",
593
- "--fds-switch": "--dsc-switch",
594
- "--table-padding": "--dsc-table-padding",
595
- "--border-radius": "--dsc-table-border-radius",
596
- "--fds-tabs": "--dsc-tabs",
597
- "--fds-tag": "--dsc-tag",
598
- "--fds-focus-border-width": "--ds-border-width-focus"
599
- }),
600
- // New tokens
601
- cssVarRename({
602
- "--fds-semantic-surface-first-light": "--ds-color-brand1-surface-default",
603
- "--fds-semantic-surface-first-light-hover": "--ds-color-brand1-surface-hover",
604
- "--fds-semantic-surface-first-light-active": "--ds-color-brand1-surface-active",
605
- "--fds-semantic-surface-first-dark": "[delete]",
606
- "--fds-semantic-surface-second-light": "--ds-color-brand2-surface-default",
607
- "--fds-semantic-surface-second-light-hover": "--ds-color-brand2-surface-hover",
608
- "--fds-semantic-surface-second-light-active": "--ds-color-brand2-surface-active",
609
- "--fds-semantic-surface-second-dark": "[delete]",
610
- "--fds-semantic-surface-third-light": "--ds-color-brand3-surface-default",
611
- "--fds-semantic-surface-third-light-hover": "--ds-color-brand3-surface-hover",
612
- "--fds-semantic-surface-third-light-active": "--ds-color-brand3-surface-active",
613
- "--fds-semantic-surface-third-dark": "[delete]",
614
- "--fds-semantic-surface-action-first-subtle": "--ds-color-accent-surface-default",
615
- "--fds-semantic-surface-action-first-subtle-hover": "--ds-color-accent-surface-hover",
616
- "--fds-semantic-surface-action-first-default": "--ds-color-accent-base-default",
617
- "--fds-semantic-surface-action-first-hover": "--ds-color-accent-base-hover",
618
- "--fds-semantic-surface-action-first-active": "--ds-color-accent-base-active",
619
- "--fds-semantic-surface-action-first-no_fill": "--ds-color-accent-background-default",
620
- "--fds-semantic-surface-action-first-no_fill-hover": "--ds-color-accent-surface-default",
621
- "--fds-semantic-surface-action-first-no_fill-active": "--ds-color-accent-surface-hover",
622
- "--fds-semantic-surface-action-second-subtle": "--ds-color-neutral-surface-default",
623
- "--fds-semantic-surface-action-second-subtle-hover": "--ds-color-neutral-surface-hover",
624
- "--fds-semantic-surface-action-second-default": "--ds-color-neutral-base-default",
625
- "--fds-semantic-surface-action-second-hover": "--ds-color-neutral-base-hover",
626
- "--fds-semantic-surface-action-second-active": "--ds-color-neutral-base-active",
627
- "--fds-semantic-surface-action-second-no_fill": "--ds-color-neutral-background-default",
628
- "--fds-semantic-surface-action-second-no_fill-hover": "--ds-color-neutral-surface-default",
629
- "--fds-semantic-surface-action-second-no_fill-active": "--ds-color-neutral-surface-hover",
630
- "--fds-semantic-surface-action-subtle": "--ds-color-accent-surface-default",
631
- "--fds-semantic-surface-action-subtle-hover": "--ds-color-accent-surface-hover",
632
- "--fds-semantic-surface-action-default": "--ds-color-accent-base-default",
633
- "--fds-semantic-surface-action-hover": "--ds-color-accent-base-hover",
634
- "--fds-semantic-surface-action-active": "--ds-color-accent-base-active",
635
- "--fds-semantic-surface-action-no_fill": "--ds-color-accent-background-default",
636
- "--fds-semantic-surface-action-no_fill-hover": "--ds-color-accent-surface-default",
637
- "--fds-semantic-surface-action-no_fill-active": "--ds-color-accent-surface-hover",
638
- "--fds-semantic-surface-action-checked": "--ds-color-accent-base-default",
639
- "--fds-semantic-surface-neutral-default": "--ds-color-neutral-background-default",
640
- "--fds-semantic-surface-neutral-selected": "[delete]",
641
- "--fds-semantic-surface-neutral-subtle": "--ds-color-neutral-background-subtle",
642
- "--fds-semantic-surface-neutral-subtle-hover": "--ds-color-neutral-surface-default",
643
- "--fds-semantic-surface-neutral-dark": "[delete]",
644
- "--fds-semantic-surface-neutral-dark-hover": "[delete]",
645
- "--fds-semantic-surface-neutral-inverted": "[delete]",
646
- "--fds-semantic-surface-success-subtle": "--ds-color-success-surface-default",
647
- "--fds-semantic-surface-success-subtle-hover": "--ds-color-success-surface-hover",
648
- "--fds-semantic-surface-success-default": "--ds-color-success-base-default",
649
- "--fds-semantic-surface-success-hover": "--ds-color-success-base-hover",
650
- "--fds-semantic-surface-success-active": "--ds-color-success-base-active",
651
- "--fds-semantic-surface-success-no_fill": "--ds-color-success-background-default",
652
- "--fds-semantic-surface-success-no_fill-hover": "--ds-color-success-surface-default",
653
- "--fds-semantic-surface-success-no_fill-active": "--ds-color-success-surface-hover",
654
- "--fds-semantic-surface-warning-subtle": "--ds-color-warning-surface-default",
655
- "--fds-semantic-surface-warning-subtle-hover": "--ds-color-warning-surface-default",
656
- "--fds-semantic-surface-warning-default": "--ds-color-warning-surface-default",
657
- "--fds-semantic-surface-warning-default-hover": "--ds-color-warning-surface-hover",
658
- "--fds-semantic-surface-danger-subtle": "--ds-color-danger-surface-default",
659
- "--fds-semantic-surface-danger-subtle-hover": "--ds-color-danger-surface-hover",
660
- "--fds-semantic-surface-danger-default": "--ds-color-danger-base-default",
661
- "--fds-semantic-surface-danger-hover": "--ds-color-danger-base-hover",
662
- "--fds-semantic-surface-danger-active": "--ds-color-danger-base-active",
663
- "--fds-semantic-surface-danger-no_fill": "--ds-color-danger-background-default",
664
- "--fds-semantic-surface-danger-no_fill-hover": "--ds-color-danger-surface-default",
665
- "--fds-semantic-surface-danger-no_fill-active": "--ds-color-danger-surface-hover",
666
- "--fds-semantic-surface-info-subtle": "--ds-color-info-surface-default",
667
- "--fds-semantic-surface-info-subtle-hover": "[delete]",
668
- "--fds-semantic-surface-on_inverted-default": "[delete]",
669
- "--fds-semantic-surface-on_inverted-hover": "[delete]",
670
- "--fds-semantic-surface-on_inverted-active": "[delete]",
671
- "--fds-semantic-surface-on_inverted-no_fill": "[delete]",
672
- "--fds-semantic-surface-on_inverted-no_fill-hover": "[delete]",
673
- "--fds-semantic-surface-on_inverted-no_fill-active": "[delete]",
674
- "--fds-semantic-surface-focus-default": "[delete]",
675
- "--fds-semantic-border-first-default": "--ds-color-brand1-base-default",
676
- "--fds-semantic-border-first-hover": "--ds-color-brand1-base-hover",
677
- "--fds-semantic-border-first-active": "--ds-color-brand1-base-active",
678
- "--fds-semantic-border-second-default": "--ds-color-brand2-base-default",
679
- "--fds-semantic-border-second-hover": "--ds-color-brand2-base-hover",
680
- "--fds-semantic-border-second-active": "--ds-color-brand2-base-active",
681
- "--fds-semantic-border-third-default": "--ds-color-brand3-base-default",
682
- "--fds-semantic-border-third-hover": "--ds-color-brand3-base-hover",
683
- "--fds-semantic-border-third-active": "--ds-color-brand3-base-active",
684
- "--fds-semantic-border-action-first-subtle": "--ds-color-accent-border-subtle",
685
- "--fds-semantic-border-action-first-subtle-hover": "--ds-color-accent-border-default",
686
- "--fds-semantic-border-action-first-default": "--ds-color-accent-base-default",
687
- "--fds-semantic-border-action-first-hover": "--ds-color-accent-base-hover",
688
- "--fds-semantic-border-action-first-active": "--ds-color-accent-base-active",
689
- "--fds-semantic-border-action-second-subtle": "--ds-color-neutral-border-subtle",
690
- "--fds-semantic-border-action-second-subtle-hover": "--ds-color-neutral-border-default",
691
- "--fds-semantic-border-action-second-default": "--ds-color-neutral-base-default",
692
- "--fds-semantic-border-action-second-hover": "--ds-color-neutral-base-hover",
693
- "--fds-semantic-border-action-second-active": "--ds-color-neutral-base-active",
694
- "--fds-semantic-border-action-subtle": "--ds-color-accent-border-subtle",
695
- "--fds-semantic-border-action-subtle-hover": "--ds-color-accent-border-default",
696
- "--fds-semantic-border-action-default": "--ds-color-accent-base-default",
697
- "--fds-semantic-border-action-hover": "--ds-color-accent-base-hover",
698
- "--fds-semantic-border-action-active": "--ds-color-accent-base-active",
699
- "--fds-semantic-border-action-dark": "[delete]",
700
- "--fds-semantic-border-action-dark-hover": "[delete]",
701
- "--fds-semantic-border-info-default": "--ds-color-info-border-strong",
702
- "--fds-semantic-border-neutral-default": "--ds-color-neutral-border-strong",
703
- "--fds-semantic-border-neutral-subtle": "--ds-color-neutral-border-subtle",
704
- "--fds-semantic-border-neutral-strong": "--ds-color-neutral-base-default",
705
- "--fds-semantic-border-success-default": "--ds-color-success-border-default",
706
- "--fds-semantic-border-success-hover": "[delete]",
707
- "--fds-semantic-border-success-active": "[delete]",
708
- "--fds-semantic-border-warning-default": "--ds-color-warning-border-default",
709
- "--fds-semantic-border-warning-hover": "[delete]",
710
- "--fds-semantic-border-warning-active": "[delete]",
711
- "--fds-semantic-border-danger-default": "--ds-color-danger-border-default",
712
- "--fds-semantic-border-danger-hover": "--ds-color-danger-border-strong",
713
- "--fds-semantic-border-danger-active": "--ds-color-danger-border-strong",
714
- "--fds-semantic-border-focus-outline": "--ds-color-neutral-text-default",
715
- "--fds-semantic-border-focus-boxshadow": "--ds-color-neutral-background-default",
716
- "--fds-semantic-border-on_inverted-default": "[delete]",
717
- "--fds-semantic-border-input-default": "--ds-color-neutral-border-default",
718
- "--fds-semantic-border-input-hover": "--ds-color-accent-border-strong",
719
- "--fds-semantic-border-divider-default": "--ds-color-neutral-border-subtle",
720
- "--fds-semantic-border-divider-subtle": "--ds-color-neutral-border-subtle",
721
- "--fds-semantic-border-divider-strong": "--ds-color-neutral-border-default",
722
- "--fds-semantic-text-action-first-default": "--ds-color-accent-base-default",
723
- "--fds-semantic-text-action-first-hover": "--ds-color-accent-base-hover",
724
- "--fds-semantic-text-action-first-active": "--ds-color-accent-base-active",
725
- "--fds-semantic-text-action-first-on_action": "--ds-color-accent-contrast-default",
726
- "--fds-semantic-text-action-second-default": "--ds-color-neutral-base-default",
727
- "--fds-semantic-text-action-second-hover": "--ds-color-neutral-base-hover",
728
- "--fds-semantic-text-action-second-active": "--ds-color-neutral-base-active",
729
- "--fds-semantic-text-action-second-on_action": "--ds-color-neutral-contrast-default",
730
- "--fds-semantic-text-action-default": "--ds-color-accent-base-default",
731
- "--fds-semantic-text-action-hover": "--ds-color-accent-base-hover",
732
- "--fds-semantic-text-action-active": "--ds-color-accent-base-active",
733
- "--fds-semantic-text-action-on_action": "--ds-color-accent-contrast-default",
734
- "--fds-semantic-text-success-default": "--ds-color-success-base-default",
735
- "--fds-semantic-text-success-hover": "--ds-color-success-base-default",
736
- "--fds-semantic-text-success-active": "--ds-color-success-base-default",
737
- "--fds-semantic-text-success-on_success": "--ds-color-success-contrast-default",
738
- "--fds-semantic-text-success-on_success_subtle": "--ds-color-success-text-default",
739
- "--fds-semantic-text-neutral-default": "--ds-color-neutral-text-default",
740
- "--fds-semantic-text-neutral-subtle": "--ds-color-neutral-text-subtle",
741
- "--fds-semantic-text-neutral-on_inverted": "--ds-color-neutral-contrast-default",
742
- "--fds-semantic-text-warning-default": "[delete]",
743
- "--fds-semantic-text-warning-icon_warning": "--ds-color-warning-base-default",
744
- "--fds-semantic-text-warning-on_warning": "--ds-color-neutral-text-default",
745
- "--fds-semantic-text-danger-default": "--ds-color-danger-text-default",
746
- "--fds-semantic-text-danger-hover": "--ds-color-danger-text-default",
747
- "--fds-semantic-text-danger-active": "--ds-color-danger-text-default",
748
- "--fds-semantic-text-danger-on_danger": "--ds-color-danger-contrast-default",
749
- "--fds-semantic-text-danger-on_danger_subtle": "--ds-color-danger-text-default",
750
- "--fds-semantic-text-visited-default": "--ds-global-purple-13",
751
- "--fds-semantic-background-default": "--ds-color-neutral-background-default",
752
- "--fds-semantic-background-subtle": "--ds-color-neutral-background-subtle",
753
- "--fds-typography-heading-3xlarge": "[delete]",
754
- "--fds-typography-heading-2xlarge": "--ds-typography-heading-2xl",
755
- "--fds-typography-heading-xlarge": "--ds-typography-heading-xl",
756
- "--fds-typography-heading-large": "--ds-typography-heading-lg",
757
- "--fds-typography-heading-medium": "--ds-typography-heading-md",
758
- "--fds-typography-heading-small": "--ds-typography-heading-sm",
759
- "--fds-typography-heading-xsmall": "--ds-typography-heading-xs",
760
- "--fds-typography-heading-xxsmall": "--ds-typography-heading-2xs",
761
- "--fds-typography-ingress-large": "--ds-typography-ingress-lg",
762
- "--fds-typography-ingress-medium": "--ds-typography-ingress-md",
763
- "--fds-typography-ingress-small": "--ds-typography-ingress-sm",
764
- "--fds-typography-ingress-xsmall": "--ds-typography-ingress-xs",
765
- "--fds-typography-paragraph-large": "--ds-typography-paragraph-lg",
766
- "--fds-typography-paragraph-medium": "--ds-typography-paragraph-md",
767
- "--fds-typography-paragraph-small": "--ds-typography-paragraph-sm",
768
- "--fds-typography-paragraph-xsmall": "--ds-typography-paragraph-xs",
769
- "--fds-typography-paragraph-short-large": "--ds-typography-paragraph-short-lg",
770
- "--fds-typography-paragraph-short-medium": "--ds-typography-paragraph-short-md",
771
- "--fds-typography-paragraph-short-small": "--ds-typography-paragraph-short-sm",
772
- "--fds-typography-paragraph-short-xsmall": "--ds-typography-paragraph-short-xs",
773
- "--fds-typography-paragraph-long-large": "--ds-typography-paragraph-long-lg",
774
- "--fds-typography-paragraph-long-medium": "--ds-typography-paragraph-long-md",
775
- "--fds-typography-paragraph-long-small": "--ds-typography-paragraph-long-sm",
776
- "--fds-typography-paragraph-long-xsmall": "--ds-typography-paragraph-long-xs",
777
- "--fds-typography-label-large": "--ds-typography-label-lg",
778
- "--fds-typography-label-medium": "--ds-typography-label-md",
779
- "--fds-typography-label-small": "--ds-typography-label-sm",
780
- "--fds-typography-label-xsmall": "--ds-typography-label-xs",
781
- "--fds-typography-error_message-large": "--ds-typography-error_message-lg",
782
- "--fds-typography-error_message-medium": "--ds-typography-error_message-md",
783
- "--fds-typography-error_message-small": "--ds-typography-error_message-sm",
784
- "--fds-typography-error_message-xsmall": "--ds-typography-error_message-xs",
785
- "--fds-typography-interactive-large": "--ds-typography-paragraph-short-lg",
786
- "--fds-typography-interactive-medium": "--ds-typography-paragraph-short-md",
787
- "--fds-typography-interactive-small": "--ds-typography-paragraph-short-sm",
788
- "--fds-border_radius-interactive": "--ds-border-radius-md",
789
- "--fds-border_radius-small": "--ds-border-radius-sm",
790
- "--fds-border_radius-medium": "--ds-border-radius-md",
791
- "--fds-border_radius-large": "--ds-border-radius-lg",
792
- "--fds-border_radius-xlarge": "--ds-border-radius-lg",
793
- "--fds-border_radius-xxlarge": "--ds-border-radius-lg",
794
- "--fds-border_radius-xxxlarge": "--ds-border-radius-lg",
795
- "--fds-border_radius-xxxxlarge": "--ds-border-radius-lg",
796
- "--fds-border_radius-full": "--ds-border-radius-full",
797
- "--fds-base_spacing": "[delete]",
798
- "--fds-base_sizing": "[delete]",
799
- "--fds-border_width-default": "--ds-border-width-default",
800
- "--fds-border_width-active": "--ds-border-width-highlight",
801
- "--fds-border_width-tab_focus": "--ds-border-width-highlight",
802
- "--fds-shadow-xsmall": "--ds-shadow-xs",
803
- "--fds-shadow-small": "--ds-shadow-sm",
804
- "--fds-shadow-medium": "--ds-shadow-md",
805
- "--fds-shadow-large": "--ds-shadow-lg",
806
- "--fds-shadow-xlarge": "--ds-shadow-xl",
807
- "--fds-spacing-0": "--ds-size-0",
808
- "--fds-spacing-1": "--ds-size-1",
809
- "--fds-spacing-2": "--ds-size-2",
810
- "--fds-spacing-3": "--ds-size-3",
811
- "--fds-spacing-4": "--ds-size-4",
812
- "--fds-spacing-5": "--ds-size-5",
813
- "--fds-spacing-6": "--ds-size-6",
814
- "--fds-spacing-7": "--ds-size-7",
815
- "--fds-spacing-8": "--ds-size-8",
816
- "--fds-spacing-9": "--ds-size-9",
817
- "--fds-spacing-10": "--ds-size-10",
818
- "--fds-spacing-11": "--ds-size-11",
819
- "--fds-spacing-12": "--ds-size-12",
820
- "--fds-spacing-13": "--ds-size-13",
821
- "--fds-spacing-14": "--ds-size-14",
822
- "--fds-spacing-15": "--ds-size-15",
823
- "--fds-spacing-18": "--ds-size-18",
824
- "--fds-spacing-22": "--ds-size-22",
825
- "--fds-spacing-26": "--ds-size-26",
826
- "--fds-spacing-30": "--ds-size-30",
827
- "--fds-sizing-0": "--ds-size-0",
828
- "--fds-sizing-1": "--ds-size-1",
829
- "--fds-sizing-2": "--ds-size-2",
830
- "--fds-sizing-3": "--ds-size-3",
831
- "--fds-sizing-4": "--ds-size-4",
832
- "--fds-sizing-5": "--ds-size-5",
833
- "--fds-sizing-6": "--ds-size-6",
834
- "--fds-sizing-7": "--ds-size-7",
835
- "--fds-sizing-8": "--ds-size-8",
836
- "--fds-sizing-9": "--ds-size-9",
837
- "--fds-sizing-10": "--ds-size-10",
838
- "--fds-sizing-11": "--ds-size-11",
839
- "--fds-sizing-12": "--ds-size-12",
840
- "--fds-sizing-13": "--ds-size-13",
841
- "--fds-sizing-14": "--ds-size-14",
842
- "--fds-sizing-15": "--ds-size-15",
843
- "--fds-sizing-18": "--ds-size-18",
844
- "--fds-sizing-22": "--ds-size-22",
845
- "--fds-sizing-26": "--ds-size-26",
846
- "--fds-sizing-30": "--ds-size-30",
847
- "--fds-opacity-disabled": "--ds-opacity-disabled",
848
- "--fds-colors-blue-100": "--ds-global-blue-1",
849
- "--fds-colors-blue-200": "--ds-global-blue-2",
850
- "--fds-colors-blue-700": "--ds-global-blue-7",
851
- "--fds-colors-blue-800": "--ds-global-blue-8",
852
- "--fds-colors-blue-900": "--ds-global-blue-9",
853
- "--fds-colors-grey-100": "--ds-color-neutral-1",
854
- "--fds-colors-grey-200": "--ds-color-neutral-2",
855
- "--fds-colors-grey-400": "--ds-color-neutral-4",
856
- "--fds-colors-grey-600": "--ds-color-neutral-6",
857
- "--fds-colors-grey-700": "--ds-color-neutral-7",
858
- "--fds-colors-grey-800": "--ds-color-neutral-8",
859
- "--fds-colors-green-200": "--ds-global-green-2",
860
- "--fds-colors-green-300": "--ds-global-green-3",
861
- "--fds-colors-green-700": "--ds-global-green-7",
862
- "--fds-colors-green-800": "--ds-global-green-8",
863
- "--fds-colors-green-900": "--ds-global-green-9",
864
- "--fds-colors-yellow-100": "--ds-global-yellow-1",
865
- "--fds-colors-yellow-200": "--ds-global-yellow-2",
866
- "--fds-colors-yellow-300": "--ds-global-yellow-3",
867
- "--fds-colors-yellow-500": "--ds-global-yellow-5",
868
- "--fds-colors-blue-400": "--ds-global-blue-4",
869
- "--fds-colors-grey-300": "--ds-global-grey-3",
870
- "--fds-colors-orange-600": "--ds-global-orange-6",
871
- "--fds-colors-orange-700": "--ds-global-orange-7",
872
- "--fds-colors-orange-800": "--ds-global-orange-8",
873
- "--fds-colors-red-800": "--ds-global-red-8",
874
- "--fds-colors-purple-700": "--ds-global-purple-7",
875
- "--fds-colors-red-100": "--ds-global-red-1",
876
- "--fds-colors-red-200": "--ds-global-red-2",
877
- "--fds-colors-red-500": "--ds-global-red-5",
878
- "--fds-colors-red-600": "--ds-global-red-6",
879
- "--fds-colors-red-700": "--ds-global-red-7",
880
- "--fds-brand-alt1-100": "--ds-color-brand1-1",
881
- "--fds-brand-alt1-200": "--ds-color-brand1-2",
882
- "--fds-brand-alt1-300": "--ds-color-brand1-3",
883
- "--fds-brand-alt1-400": "--ds-color-brand1-4",
884
- "--fds-brand-alt1-500": "--ds-color-brand1-5",
885
- "--fds-brand-alt1-600": "--ds-color-brand1-6",
886
- "--fds-brand-alt1-700": "--ds-color-brand1-7",
887
- "--fds-brand-alt1-800": "--ds-color-brand1-8",
888
- "--fds-brand-alt1-900": "--ds-color-brand1-9",
889
- "--fds-brand-alt2-100": "--ds-color-brand2-1",
890
- "--fds-brand-alt2-200": "--ds-color-brand2-2",
891
- "--fds-brand-alt2-300": "--ds-color-brand2-3",
892
- "--fds-brand-alt2-400": "--ds-color-brand2-4",
893
- "--fds-brand-alt2-500": "--ds-color-brand2-5",
894
- "--fds-brand-alt2-600": "--ds-color-brand2-6",
895
- "--fds-brand-alt2-700": "--ds-color-brand2-7",
896
- "--fds-brand-alt2-800": "--ds-color-brand2-8",
897
- "--fds-brand-alt2-900": "--ds-color-brand2-9",
898
- "--fds-brand-alt3-100": "--ds-color-brand3-1",
899
- "--fds-brand-alt3-200": "--ds-color-brand3-2",
900
- "--fds-brand-alt3-300": "--ds-color-brand3-3",
901
- "--fds-brand-alt3-400": "--ds-color-brand3-4",
902
- "--fds-brand-alt3-500": "--ds-color-brand3-5",
903
- "--fds-brand-alt3-600": "--ds-color-brand3-6",
904
- "--fds-brand-alt3-700": "--ds-color-brand3-7",
905
- "--fds-brand-alt3-800": "--ds-color-brand3-8",
906
- "--fds-brand-alt3-900": "--ds-color-brand3-9"
907
- })
908
- ]
909
- });
910
-
911
- // src/migrations/color-rename-next49.ts
912
- import * as R5 from "ramda";
913
- var replace = (oldTemplate, newTemplate, colors2, placeholder = "[color]") => R5.reduce(
914
- (acc, color) => {
915
- acc[oldTemplate.replace(placeholder, color)] = newTemplate.replace(placeholder, color);
916
- return acc;
917
- },
918
- {},
919
- colors2
920
- );
921
- var colors = ["neutral", "accent", "brand1", "brand2", "brand3", "danger", "warning", "success", "info"];
922
- var color_rename_next49_default = (glob2) => {
923
- const renames = {
924
- // Background
925
- "--ds-color-background-subtle": "--ds-color-background-tinted",
926
- ...replace("--ds-color-[color]-background-subtle", "--ds-color-[color]-background-tinted", colors),
927
- // Surface
928
- "--ds-color-surface-default": "--ds-color-surface-tinted",
929
- ...replace("--ds-color-[color]-surface-default", "--ds-color-[color]-surface-tinted", colors),
930
- // Contrast
931
- "--ds-color-contrast-default": "--ds-color-base-contrast-default",
932
- "--ds-color-contrast-subtle": "--ds-color-base-contrast-subtle",
933
- ...replace("--ds-color-[color]-contrast-default", "--ds-color-[color]-base-contrast-default", colors),
934
- ...replace("--ds-color-[color]-contrast-subtle", "--ds-color-[color]-base-contrast-subtle", colors)
935
- };
936
- console.log(`Renaming ${Object.keys(renames).length} variables`, renames);
937
- return runCssCodemod({
938
- globPattern: glob2,
939
- plugins: [
940
- // https://github.com/digdir/designsystemet/issues/3046
941
- cssVarRename(renames)
942
- ]
943
- });
944
- };
945
-
946
- // src/migrations/index.ts
947
- var migrations_default = {
948
- "css-beta-to-v1": beta_to_v1_default,
949
- "css-renames-next48-to-next49": color_rename_next49_default
950
- };
951
-
952
- // src/tokens/build.ts
953
- import pc7 from "picocolors";
954
- import * as R22 from "ramda";
955
-
956
- // src/tokens/process/output/declarations.ts
957
- import pc5 from "picocolors";
958
-
959
- // package.json
960
- var package_default = {
961
- name: "@digdir/designsystemet",
962
- version: "1.13.2",
963
- description: "CLI for Designsystemet",
964
- author: "Designsystemet team",
965
- engines: {
966
- node: ">=20.20.2"
967
- },
968
- repository: {
969
- type: "git",
970
- url: "git+https://github.com/digdir/designsystemet.git"
971
- },
972
- homepage: "https://github.com/digdir/designsystemet/tree/main/packages/cli",
973
- license: "MIT",
974
- type: "module",
975
- main: "./dist/src/index.js",
976
- files: [
977
- "./dist/**",
978
- "./configs/**"
979
- ],
980
- bin: "dist/bin/designsystemet.js",
981
- exports: {
982
- ".": {
983
- import: "./dist/src/index.js"
984
- },
985
- "./color": {
986
- import: "./dist/src/colors/index.js"
987
- },
988
- "./tokens": {
989
- import: "./dist/src/tokens/index.js"
990
- },
991
- "./types": {
992
- import: "./dist/src/types.js"
993
- }
994
- },
995
- publishConfig: {
996
- access: "public"
997
- },
998
- scripts: {
999
- designsystemet: "tsx ./bin/designsystemet.ts",
1000
- "designsystemet:inspect": "tsx --inspect-brk ./bin/designsystemet.ts",
1001
- build: "tsup && pnpm build:types && pnpm build:json-schema",
1002
- "build:types": "tsc --emitDeclarationOnly --declaration",
1003
- "build:json-schema": "tsx ./src/scripts/createJsonSchema.ts",
1004
- types: "tsc --noEmit",
1005
- "test:tokens-create-options": 'pnpm run designsystemet tokens create -m dominant:"#007682" -n "#003333" -b 99 -o ./temp/options/design-tokens --theme options --clean',
1006
- "test:tokens-create-config": "pnpm run designsystemet tokens create --config ./configs/test-tokens.config.json",
1007
- "test:tokens-build": "pnpm run designsystemet tokens build -t ./temp/options/design-tokens -o ./temp/options/build --clean",
1008
- "test:tokens-build-tailwind": "pnpm run designsystemet tokens build -t ./temp/options/design-tokens -o ./temp/options/build --clean --experimental-tailwind",
1009
- "test:tokens-build-config": "pnpm run designsystemet tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean",
1010
- "test:tokens-build-config:inspect": "pnpm run designsystemet:inspect tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean",
1011
- "test:tokens-build-config-tailwind": "pnpm run designsystemet tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean --experimental-tailwind",
1012
- "test:tokens-create-and-build-options": "pnpm test:tokens-create-options && pnpm test:tokens-build",
1013
- "test:tokens-create-and-build-config": "pnpm test:tokens-create-config && pnpm test:tokens-build-config",
1014
- "test:generate-config-from-tokens": "pnpm run designsystemet generate-config-from-tokens -d ../../design-tokens --dry",
1015
- test: "node -v && pnpm test:tokens-create-and-build-options && pnpm test:generate-config-from-tokens && pnpm test:tokens-create-and-build-config",
1016
- "update:preview-tokens": "tsx ./src/scripts/update-preview-tokens.ts",
1017
- verify: "pnpm test && pnpm update:template && pnpm --filter @internal/digdir update:theme-digdir"
1018
- },
1019
- dependencies: {
1020
- "@commander-js/extra-typings": "^14.0.0",
1021
- "@digdir/designsystemet-types": "workspace:",
1022
- "@tokens-studio/sd-transforms": "2.0.3",
1023
- "chroma-js": "^3.2.0",
1024
- "colorjs.io": "^0.6.1",
1025
- commander: "^14.0.3",
1026
- "fast-glob": "^3.3.3",
1027
- hsluv: "^1.0.1",
1028
- "object-hash": "^3.0.0",
1029
- picocolors: "^1.1.1",
1030
- postcss: "^8.5.8",
1031
- ramda: "^0.32.0",
1032
- "style-dictionary": "^5.4.0",
1033
- zod: "^4.3.6",
1034
- "zod-validation-error": "^5.0.0"
1035
- },
1036
- devDependencies: {
1037
- "@tokens-studio/types": "0.5.2",
1038
- "@types/chroma-js": "3.1.2",
1039
- "@types/node": "24.12.2",
1040
- "@types/object-hash": "3.0.6",
1041
- "@types/ramda": "0.31.1",
1042
- tsup: "8.5.1",
1043
- tsx: "4.21.0",
1044
- typescript: "5.9.3"
1045
- }
1046
- };
1047
-
1048
- // src/tokens/process/platform.ts
1049
- import pc4 from "picocolors";
1050
- import * as R20 from "ramda";
1051
- import StyleDictionary2 from "style-dictionary";
1052
-
1053
- // src/tokens/types.ts
1054
- var colorCategories = {
1055
- main: "main",
1056
- support: "support"
1057
- };
1058
-
1059
- // src/tokens/process/configs.ts
1060
- import { register } from "@tokens-studio/sd-transforms";
1061
- import * as R19 from "ramda";
1062
- import StyleDictionary from "style-dictionary";
1063
-
1064
- // src/tokens/utils.ts
1065
- import * as R6 from "ramda";
1066
- var mapToLowerCase = R6.map(R6.toLower);
1067
- var hasAnyTruth = R6.any(R6.equals(true));
1068
- var getType = (token) => (token.$type ?? token.type) || "";
1069
- var getValue = (token) => token.$value ?? token.value;
1070
- var typeEquals = R6.curry(
1071
- (types, token) => {
1072
- if (R6.isNil(token)) {
1073
- return false;
1074
- }
1075
- return R6.includes(R6.toLower(getType(token)), R6.map(R6.toLower, Array.isArray(types) ? types : [types]));
1076
- }
1077
- );
1078
- var pathStartsWithOneOf = R6.curry(
1079
- (paths, token) => {
1080
- if (R6.isNil(token)) {
1081
- return false;
1082
- }
1083
- const tokenPath = mapToLowerCase(token.path);
1084
- const matchPathsStartingWith = R6.map((pathOrString) => {
1085
- const path5 = typeof pathOrString === "string" ? [pathOrString] : pathOrString;
1086
- return R6.startsWith(mapToLowerCase(path5), tokenPath);
1087
- }, paths);
1088
- return hasAnyTruth(matchPathsStartingWith);
1089
- }
1090
- );
1091
- function isSemanticToken(token) {
1092
- return token.filePath.includes("semantic/");
1093
- }
1094
- function isSemanticColorToken(token, color) {
1095
- return token.filePath.includes("semantic/") && R6.startsWith(["color", color], token.path);
1096
- }
1097
- function isGlobalColorToken(token) {
1098
- return typeEquals("color", token) && pathStartsWithOneOf(["global"], token);
1099
- }
1100
- function isColorCategoryToken(token, category) {
1101
- if (!category) {
1102
- return Object.keys(colorCategories).some(
1103
- (colorCategory2) => isColorCategoryToken(token, colorCategory2)
1104
- );
1105
- }
1106
- return R6.startsWith(["color", category], token.path);
1107
- }
1108
- var isDigit = (s) => /^\d+$/.test(s);
1109
- function traverseObj(obj, fn) {
1110
- for (const key in obj) {
1111
- const prop3 = obj[key];
1112
- if (prop3 != null) {
1113
- fn.apply(null, [obj, key, prop3]);
1114
- if (typeof prop3 === "object") {
1115
- traverseObj(prop3, fn);
1116
- }
1117
- }
1118
- }
1119
- return obj;
1120
- }
1121
- function inlineTokens(shouldInline, tokens) {
1122
- const [inlineableTokens, otherTokens] = R6.partition(shouldInline, tokens);
1123
- return otherTokens.map((token) => {
1124
- let transformed = getValue(token.original);
1125
- for (const ref of inlineableTokens) {
1126
- const refName = ref.path.join(".");
1127
- if (typeof transformed === "string") {
1128
- transformed = transformed.replaceAll(`{${refName}}`, getValue(ref.original));
1129
- }
1130
- }
1131
- const tokenWithInlinedRefs = R6.set(R6.lensPath(["original", "$value"]), transformed, token);
1132
- return tokenWithInlinedRefs;
1133
- });
1134
- }
1135
- var sizeMap = {
1136
- xsmall: "xs",
1137
- small: "sm",
1138
- medium: "md",
1139
- large: "lg",
1140
- xlarge: "xl"
1141
- };
1142
- function shortSizeName(size2) {
1143
- return sizeMap[size2] ?? size2;
1144
- }
1145
- var sizeComparator = (size2) => {
1146
- const sortIndex = Object.entries(sizeMap).findIndex(([key, val]) => key === size2 || val === size2);
1147
- return sortIndex ?? 0;
1148
- };
1149
- function orderBySize(sizes) {
1150
- return R6.sortBy(sizeComparator, sizes);
1151
- }
1152
-
1153
- // src/tokens/process/configs/color.ts
1154
- import * as R14 from "ramda";
1155
-
1156
- // src/tokens/process/formats/css/color.ts
1157
- import * as R7 from "ramda";
1158
- import { createPropertyFormatter } from "style-dictionary/utils";
1159
- var prefersColorScheme = (colorScheme2, content) => `
1160
- @media (prefers-color-scheme: ${colorScheme2}) {
1161
- [data-color-scheme="auto"] ${content}
1162
- }
1163
- `;
1164
- var colorScheme = {
1165
- name: "ds/css-colorscheme",
1166
- format: async ({ dictionary, options, platform }) => {
1167
- const { allTokens } = dictionary;
1168
- const { outputReferences, usesDtcg } = options;
1169
- const { selector, colorScheme: colorScheme2, layer } = platform;
1170
- const colorScheme_ = colorScheme2;
1171
- const format = createPropertyFormatter({
1172
- outputReferences,
1173
- dictionary,
1174
- format: "css",
1175
- usesDtcg
1176
- });
1177
- const colorSchemeProperty = colorScheme_ === "dark" || colorScheme_ === "light" ? `
1178
- color-scheme: ${colorScheme_};
1179
- ` : "";
1180
- const filteredAllTokens = allTokens.filter(
1181
- R7.allPass([
1182
- R7.anyPass([
1183
- // Include semantic tokens in the output
1184
- isSemanticToken,
1185
- // Include global color tokens
1186
- isGlobalColorToken
1187
- ]),
1188
- // Don't include color category tokens -- they are exported separately
1189
- (t) => !isColorCategoryToken(t)
1190
- ])
1191
- );
1192
- const formattedMap = filteredAllTokens.map((token) => ({
1193
- token,
1194
- formatted: format(token)
1195
- }));
1196
- const formattedTokens = formattedMap.map(R7.view(R7.lensProp("formatted"))).join("\n");
1197
- const content = `{
1198
- ${formattedTokens}
1199
- ${colorSchemeProperty}}
1200
- `;
1201
- const autoSelectorContent = ["light", "dark"].includes(colorScheme_) ? prefersColorScheme(colorScheme_, content) : "";
1202
- const body = R7.isNotNil(layer) ? `@layer ${layer} {
1203
- ${selector} ${content} ${autoSelectorContent}
1204
- }
1205
- ` : `${selector} ${content} ${autoSelectorContent}
1206
- `;
1207
- return body;
1208
- }
1209
- };
1210
- var colorCategory = {
1211
- name: "ds/css-colorcategory",
1212
- format: async ({ dictionary, file, options, platform }) => {
1213
- const { outputReferences, usesDtcg } = options;
1214
- const { selector, layer } = platform;
1215
- const destination = file.destination;
1216
- const format = R7.compose(
1217
- createPropertyFormatter({
1218
- outputReferences,
1219
- dictionary,
1220
- format: "css",
1221
- usesDtcg
1222
- }),
1223
- (token) => ({
1224
- ...token,
1225
- name: token.name.replace(/color-\w+-/, "color-"),
1226
- original: {
1227
- ...token.original,
1228
- $value: new RegExp(`color-(${colorCategories.main}|${colorCategories.support})-`).test(token.name) ? token.original.$value : `{${token.path.join(".")}}`
1229
- }
1230
- })
1231
- );
1232
- const formattedMap = dictionary.allTokens.map((token) => ({
1233
- token,
1234
- formatted: format(token)
1235
- }));
1236
- buildOptions.buildTokenFormats[destination] = formattedMap;
1237
- const formattedTokens = formattedMap.map(R7.view(R7.lensProp("formatted"))).join("\n");
1238
- const content = `{
1239
- ${formattedTokens}
1240
- }
1241
- `;
1242
- const body = R7.isNotNil(layer) ? `@layer ${layer} {
1243
- ${selector} ${content}
1244
- }
1245
- ` : `${selector} ${content}
1246
- `;
1247
- return body;
1248
- }
1249
- };
1250
-
1251
- // src/tokens/process/formats/css/semantic.ts
1252
- import * as R9 from "ramda";
1253
- import { createPropertyFormatter as createPropertyFormatter3 } from "style-dictionary/utils";
1254
-
1255
- // src/tokens/process/formats/css/size.ts
1256
- import * as R8 from "ramda";
1257
- import { createPropertyFormatter as createPropertyFormatter2 } from "style-dictionary/utils";
1258
- var isNumericBorderRadiusToken = (t) => t.path[0] === "border-radius" && isDigit(t.path[1]);
1259
- var isNumericSizeToken = (t) => pathStartsWithOneOf(["size"], t) && isDigit(t.path[1]);
1260
- var isSizeToken = (t) => pathStartsWithOneOf(["size"], t);
1261
- var isInlineTokens = R8.anyPass([isNumericBorderRadiusToken, isNumericSizeToken, isSizeToken]);
1262
- var overrideSizingFormula = (format, token) => {
1263
- const [name, value] = format(token).replace(/;$/, "").split(": ");
1264
- let calc;
1265
- let round;
1266
- if (token.path[1] === "unit") {
1267
- calc = `calc(1rem * ${value})`;
1268
- } else if (value.startsWith("floor")) {
1269
- calc = value.replace(/^floor\((.*)\)$/, "calc($1)");
1270
- round = `round(down, ${calc}, 1px)`;
1271
- } else {
1272
- calc = value.includes("*") ? `calc(${value})` : value;
1273
- }
1274
- return {
1275
- name,
1276
- round: round ?? calc,
1277
- calc
1278
- };
1279
- };
1280
- var formatSizingTokens = (format, tokens) => R8.reduce(
1281
- (acc, token) => {
1282
- const { round, calc, name } = overrideSizingFormula(format, token);
1283
- return {
1284
- tokens: [...acc.tokens, token],
1285
- round: [...acc.round, `${name}: ${round};`],
1286
- calc: [...acc.calc, `${name}: ${calc};`]
1287
- };
1288
- },
1289
- { tokens: [], round: [], calc: [] },
1290
- tokens
1291
- );
1292
- var sizingTemplate = ({ round, calc }) => {
1293
- const usesRounding = round.filter((val, i) => val !== calc[i]);
1294
- return `
1295
- ${calc.join("\n")}
1296
-
1297
- @supports (width: round(down, .1em, 1px)) {
1298
- ${usesRounding.join("\n ")}
1299
- }`;
1300
- };
1301
- var size = {
1302
- name: "ds/css-size",
1303
- format: async ({ dictionary, file, options, platform }) => {
1304
- const { outputReferences, usesDtcg } = options;
1305
- const { selector, layer } = platform;
1306
- const destination = file.destination;
1307
- const format = createPropertyFormatter2({
1308
- outputReferences,
1309
- dictionary,
1310
- format: "css",
1311
- usesDtcg
1312
- });
1313
- const tokens = inlineTokens(isInlineTokens, dictionary.allTokens);
1314
- const filteredTokens = R8.reject((token) => R8.equals(["_size", "mode-font-size"], token.path), tokens);
1315
- const [sizingTokens, restTokens] = R8.partition(
1316
- (t) => pathStartsWithOneOf(["_size"], t) && (isDigit(t.path[1]) || t.path[1] === "unit"),
1317
- filteredTokens
1318
- );
1319
- const formattedSizingTokens = formatSizingTokens(format, sizingTokens);
1320
- const formattedMap = restTokens.map((token) => ({
1321
- token,
1322
- formatted: format(token)
1323
- }));
1324
- const formattedSizingMap = formattedSizingTokens.round.map((t, i) => ({
1325
- token: formattedSizingTokens.tokens[i],
1326
- formatted: t
1327
- }));
1328
- buildOptions.buildTokenFormats[destination] = [...formattedMap, ...formattedSizingMap];
1329
- const formattedTokens = [formattedMap.map(R8.prop("formatted")).join("\n"), sizingTemplate(formattedSizingTokens)];
1330
- const content = `${selector} {
1331
- ${formattedTokens.join("\n")}
1332
- }
1333
- `;
1334
- const body = R8.isNotNil(layer) ? `@layer ${layer} {
1335
- ${content}
1336
- }
1337
- ` : `${content}
1338
- `;
1339
- return body;
1340
- }
1341
- };
1342
-
1343
- // src/tokens/process/formats/css/semantic.ts
1344
- var semantic = {
1345
- name: "ds/css-semantic",
1346
- format: async ({ dictionary, file, options, platform }) => {
1347
- const { outputReferences, usesDtcg } = options;
1348
- const { selector, layer } = platform;
1349
- const destination = file.destination;
1350
- const format = createPropertyFormatter3({
1351
- outputReferences,
1352
- dictionary,
1353
- format: "css",
1354
- usesDtcg
1355
- });
1356
- const tokens = inlineTokens(isInlineTokens, dictionary.allTokens);
1357
- const formattedMap = tokens.map((token) => ({
1358
- token,
1359
- formatted: format(token)
1360
- }));
1361
- buildOptions.buildTokenFormats[destination] = formattedMap;
1362
- const formattedTokens = formattedMap.map(R9.prop("formatted")).join("\n");
1363
- const content = `${selector} {
1364
- ${formattedTokens}
1365
- }
1366
- `;
1367
- const body = R9.isNotNil(layer) ? `@layer ${layer} {
1368
- ${content}
1369
- }
1370
- ` : `${content}
1371
- `;
1372
- return body;
1373
- }
1374
- };
1375
-
1376
- // src/tokens/process/formats/css/size-mode.ts
1377
- import * as R11 from "ramda";
1378
- import { createPropertyFormatter as createPropertyFormatter4 } from "style-dictionary/utils";
1379
-
1380
- // src/tokens/process/transformers.ts
1381
- import { checkAndEvaluateMath } from "@tokens-studio/sd-transforms";
1382
- import * as R10 from "ramda";
1383
- var isPx = R10.test(/\b\d+px\b/g);
1384
- var sizeRem = {
1385
- name: "ds/size/toRem",
1386
- type: "value",
1387
- transitive: true,
1388
- filter: (token) => {
1389
- const hasWantedType = typeEquals(["dimension", "fontsize"], token);
1390
- const hasWantedPath = pathStartsWithOneOf([
1391
- "border-radius",
1392
- "font-size"
1393
- /*, ['_size', 'mode-font-size']*/
1394
- ], token);
1395
- return hasWantedType && hasWantedPath;
1396
- },
1397
- transform: (token, config) => {
1398
- const value = getValue(token);
1399
- if (isPx(value)) {
1400
- const baseFont = config.basePxFontSize || 16;
1401
- const size2 = parseInt(value, 10);
1402
- if (size2 === 0) {
1403
- return "0";
1404
- }
1405
- return `${size2 / baseFont}rem`;
1406
- }
1407
- return value;
1408
- }
1409
- };
1410
- var typographyName = {
1411
- name: "name/typography",
1412
- type: "name",
1413
- transitive: true,
1414
- // expanded tokens have different type so we match on path instead
1415
- filter: (token) => pathStartsWithOneOf(["typography"], token),
1416
- transform: (token) => {
1417
- return token.name.replace("-typography", "");
1418
- }
1419
- };
1420
- var resolveMath = {
1421
- name: "ds/resolveMath",
1422
- type: "value",
1423
- transitive: true,
1424
- filter: (token) => {
1425
- const isValidValue = ["string", "object"].includes(typeof getValue(token));
1426
- const isTokenOfInterest = !pathStartsWithOneOf(["border-radius"], token);
1427
- return isValidValue && isTokenOfInterest;
1428
- },
1429
- transform: (token, platformCfg) => checkAndEvaluateMath(token, platformCfg.mathFractionDigits)
1430
- };
1431
- var unitless = {
1432
- name: "ds/unitless",
1433
- type: "value",
1434
- transitive: true,
1435
- filter: (token) => pathStartsWithOneOf(["size", "_size"], token),
1436
- transform: (token) => parseInt(getValue(token), 10)
1437
- };
1438
-
1439
- // src/tokens/process/configs/shared.ts
1440
- var prefix = "ds";
1441
- var basePxFontSize = 16;
1442
- var dsTransformers = [
1443
- "name/kebab",
1444
- resolveMath.name,
1445
- "ts/size/px",
1446
- sizeRem.name,
1447
- unitless.name,
1448
- "ts/typography/fontWeight",
1449
- typographyName.name,
1450
- "ts/color/modifiers",
1451
- "ts/color/css/hexrgba",
1452
- "ts/size/lineheight",
1453
- "shadow/css/shorthand"
1454
- ];
1455
-
1456
- // src/tokens/process/formats/css/size-mode.ts
1457
- var formatBaseSizeToken = (size2) => (token) => ({
1458
- ...token,
1459
- originalName: token.name,
1460
- name: `${token.name}--${shortSizeName(size2)}`,
1461
- $value: token.$value / basePxFontSize
1462
- });
1463
- var sizeMode = {
1464
- name: "ds/css-size-mode",
1465
- format: async ({ dictionary, file, options, platform }) => {
1466
- const { outputReferences, usesDtcg } = options;
1467
- const { selector, layer, size: size2 } = platform;
1468
- const destination = file.destination;
1469
- const format = createPropertyFormatter4({
1470
- outputReferences,
1471
- dictionary,
1472
- format: "css",
1473
- usesDtcg
1474
- });
1475
- const sizeSpecificTokens = dictionary.allTokens.map(formatBaseSizeToken(size2));
1476
- const sizeSpecificVariables = sizeSpecificTokens.map(format).join("\n");
1477
- const formattedMap = sizeSpecificTokens.map((token) => ({
1478
- token,
1479
- formatted: format({
1480
- ...token,
1481
- // Remove the `--<size>` suffix for the token listing, since that is the only token we actually use
1482
- name: token.originalName
1483
- })
1484
- }));
1485
- buildOptions.buildTokenFormats[destination] = formattedMap;
1486
- const content = `${selector} /* ${size2} */ {
1487
- ${sizeSpecificVariables}
1488
- }`;
1489
- const body = wrapInLayer(content, layer);
1490
- const sizes = orderBySize(buildOptions?.sizeModes ?? []).map(shortSizeName);
1491
- const defaultSize = shortSizeName(buildOptions?.defaultSize ?? "");
1492
- const sizingToggles = `:root, [data-size] {
1493
- --ds-size: var(--ds-size--${defaultSize});
1494
- ${sizes.map((size3) => ` --ds-size--${size3}: var(--ds-size,);`).join("\n")}
1495
- --ds-size-mode-font-size:
1496
- ${sizes.map((size3) => ` var(--ds-size--${size3}, var(--ds-size-mode-font-size--${size3}))`).join("\n")};
1497
- }`;
1498
- const sizingHelpers = sizes.map((size3) => `[data-size='${size3}'] { --ds-size: var(--ds-size--${size3}); }`).join("\n");
1499
- const sharedContent = `${sizingToggles}
1500
-
1501
- ${sizingHelpers}`;
1502
- const sharedBody = shortSizeName(size2) === R11.last(sizes) ? `
1503
- ${wrapInLayer(sharedContent, layer)}` : "";
1504
- return body + sharedBody;
1505
- }
1506
- };
1507
- function wrapInLayer(content, layer) {
1508
- return R11.isNotNil(layer) ? `@layer ${layer} {
1509
- ${content}
1510
- }
1511
- ` : `${content}
1512
- `;
1513
- }
1514
-
1515
- // src/tokens/process/formats/css/typography.ts
1516
- import * as R12 from "ramda";
1517
- import { createPropertyFormatter as createPropertyFormatter5 } from "style-dictionary/utils";
1518
- var typographyFontFamilyPredicate = R12.allPass([
1519
- R12.pathSatisfies(R12.includes("typography"), ["path"]),
1520
- R12.pathSatisfies(R12.includes("fontFamily"), ["path"])
1521
- ]);
1522
- var typography = {
1523
- name: "ds/css-typography",
1524
- format: async ({ dictionary, file, options, platform }) => {
1525
- const { outputReferences, usesDtcg } = options;
1526
- const { selector, layer } = platform;
1527
- const destination = file.destination;
1528
- const format = createPropertyFormatter5({
1529
- outputReferences,
1530
- dictionary,
1531
- format: "css",
1532
- usesDtcg
1533
- });
1534
- const filteredTokens = R12.reject(typographyFontFamilyPredicate, dictionary.allTokens);
1535
- const formattedMap = filteredTokens.map((token) => ({
1536
- token,
1537
- formatted: format(token)
1538
- }));
1539
- buildOptions.buildTokenFormats[destination] = formattedMap;
1540
- const formattedTokens = formattedMap.map(R12.view(R12.lensProp("formatted"))).join("\n");
1541
- const content = selector ? `${selector} {
1542
- ${formattedTokens}
1543
- }` : formattedTokens;
1544
- const body = R12.isNotNil(layer) ? `@layer ${layer} {
1545
- ${content}
1546
- }` : content;
1547
- return body;
1548
- }
1549
- };
1550
-
1551
- // src/tokens/process/formats/css/type-scale.ts
1552
- import * as R13 from "ramda";
1553
- import { createPropertyFormatter as createPropertyFormatter6 } from "style-dictionary/utils";
1554
- var isTypographyFontFamilyToken = R13.allPass([
1555
- R13.pathSatisfies(R13.includes("typography"), ["path"]),
1556
- R13.pathSatisfies(R13.includes("fontFamily"), ["path"])
1557
- ]);
1558
- var formatTypographySizeToken = (format, token) => {
1559
- const [name, value] = format(token).replace(/;$/, "").split(": ");
1560
- let calc;
1561
- let round;
1562
- if (R13.startsWith(["font-size"], token.path)) {
1563
- calc = `calc(${value} * var(--_ds-font-size-factor))`;
1564
- round = `round(${calc}, 1px)`;
1565
- } else {
1566
- calc = value;
1567
- }
1568
- return { name, calc, round: round ?? calc };
1569
- };
1570
- var formatTypographySizeTokens = (format, tokens) => R13.reduce(
1571
- (acc, token) => {
1572
- const { name, calc, round } = formatTypographySizeToken(format, token);
1573
- acc.tokens.push(token);
1574
- acc.calc.push(`${name}: ${calc};`);
1575
- acc.round.push(`${name}: ${round};`);
1576
- return acc;
1577
- },
1578
- { tokens: [], calc: [], round: [] },
1579
- tokens
1580
- );
1581
- var typeScale = {
1582
- name: "ds/css-type-scale",
1583
- format: async ({ dictionary, file, options, platform }) => {
1584
- const { outputReferences, usesDtcg } = options;
1585
- const { selector, layer } = platform;
1586
- const destination = file.destination;
1587
- const format = createPropertyFormatter6({
1588
- outputReferences,
1589
- dictionary,
1590
- format: "css",
1591
- usesDtcg
1592
- });
1593
- const filteredTokens = R13.reject(R13.anyPass([isTypographyFontFamilyToken]), dictionary.allTokens);
1594
- const formattedTokens = formatTypographySizeTokens(format, filteredTokens);
1595
- const formattedMap = formattedTokens.round.map((t, i) => ({
1596
- token: formattedTokens.tokens[i],
1597
- formatted: t
1598
- }));
1599
- buildOptions.buildTokenFormats[destination] = formattedMap;
1600
- const sizeFactor = ` --_ds-font-size-factor: calc(var(--ds-size-mode-font-size) / (var(--ds-size-base) / ${basePxFontSize}));`;
1601
- const content = `${selector} {
1602
- ${sizeFactor}${sizingTemplate(formattedTokens)}
1603
- }`;
1604
- const body = R13.isNotNil(layer) ? `@layer ${layer} {
1605
- ${content}
1606
- }` : content;
1607
- return body;
1608
- }
1609
- };
1610
-
1611
- // src/tokens/process/formats/css.ts
1612
- var formats = {
1613
- colorScheme,
1614
- colorCategory,
1615
- semantic,
1616
- sizeMode,
1617
- size,
1618
- typography,
1619
- typeScale
1620
- };
1621
-
1622
- // src/tokens/process/configs/color.ts
1623
- var colorSchemeVariables = ({ "color-scheme": colorScheme2 = "light", theme }) => {
1624
- const selector = `${colorScheme2 === "light" ? ":root, " : ""}[data-color-scheme="${colorScheme2}"]`;
1625
- const layer = `ds.theme.color-scheme.${colorScheme2}`;
1626
- return {
1627
- preprocessors: ["tokens-studio"],
1628
- platforms: {
1629
- css: {
1630
- // custom
1631
- colorScheme: colorScheme2,
1632
- theme,
1633
- selector,
1634
- layer,
1635
- //
1636
- prefix,
1637
- buildPath: `${theme}/`,
1638
- transforms: dsTransformers,
1639
- files: [
1640
- {
1641
- destination: `color-scheme/${colorScheme2}.css`,
1642
- format: formats.colorScheme.name,
1643
- filter: (token) => typeEquals("color", token) && !R14.startsWith(["global"], token.path)
1644
- }
1645
- ],
1646
- options: {
1647
- outputReferences: false
1648
- }
1649
- }
1650
- }
1651
- };
1652
- };
1653
- var colorCategoryVariables = (opts) => ({ "color-scheme": colorScheme2, theme, ...permutation }) => {
1654
- const category = opts.category;
1655
- const color = category === "builtin" ? opts.color : permutation[`${category}-color`];
1656
- if (!color) {
1657
- throw new Error(
1658
- category === "builtin" ? `Missing color for built-in color ${opts.color}` : `Missing color for category ${category}`
1659
- );
1660
- }
1661
- const layer = `ds.theme.color`;
1662
- const isRootColor = color === buildOptions?.defaultColor;
1663
- const selector = isRootColor ? `:root, [data-color-scheme], [data-color="${color}"]` : `[data-color="${color}"], [data-color-scheme][data-color="${color}"]`;
1664
- const config = {
1665
- preprocessors: ["tokens-studio"],
1666
- platforms: {
1667
- css: {
1668
- // custom
1669
- colorScheme: colorScheme2,
1670
- theme,
1671
- selector,
1672
- layer,
1673
- //
1674
- prefix,
1675
- buildPath: `${theme}/`,
1676
- transforms: dsTransformers,
1677
- files: [
1678
- {
1679
- destination: `color/${color}.css`,
1680
- format: formats.colorCategory.name,
1681
- filter: (token) => category === "builtin" ? isSemanticColorToken(token, color) : isColorCategoryToken(token, category)
1682
- }
1683
- ],
1684
- options: {
1685
- outputReferences: true
1686
- }
1687
- }
1688
- }
1689
- };
1690
- return config;
1691
- };
1692
-
1693
- // src/tokens/process/configs/semantic.ts
1694
- import * as R15 from "ramda";
1695
- import { outputReferencesFilter } from "style-dictionary/utils";
1696
- var semanticVariables = ({ theme }) => {
1697
- const selector = `:root`;
1698
- const layer = `ds.theme.semantic`;
1699
- return {
1700
- preprocessors: ["tokens-studio"],
1701
- platforms: {
1702
- css: {
1703
- // custom
1704
- theme,
1705
- basePxFontSize,
1706
- selector,
1707
- layer,
1708
- //
1709
- prefix,
1710
- buildPath: `${theme}/`,
1711
- transforms: dsTransformers,
1712
- files: [
1713
- {
1714
- destination: `semantic.css`,
1715
- format: formats.semantic.name,
1716
- filter: (token) => {
1717
- const isUwantedToken = R15.anyPass([R15.includes("primitives/global")])(token.filePath);
1718
- const isPrivateToken = R15.includes("_", token.path);
1719
- const unwantedPaths = pathStartsWithOneOf(
1720
- ["size", "_size", "font-size", "line-height", "letter-spacing"],
1721
- token
1722
- );
1723
- const unwantedTypes = typeEquals(["color", "fontWeight", "fontFamily", "typography"], token);
1724
- const unwantedTokens = !(unwantedPaths || unwantedTypes || isPrivateToken || isUwantedToken);
1725
- return unwantedTokens;
1726
- }
1727
- }
1728
- ],
1729
- options: {
1730
- outputReferences: (token, options) => {
1731
- const include = pathStartsWithOneOf(["border-radius"], token);
1732
- return include && outputReferencesFilter(token, options);
1733
- }
1734
- }
1735
- }
1736
- }
1737
- };
1738
- };
1739
-
1740
- // src/tokens/process/configs/size.ts
1741
- import * as R16 from "ramda";
1742
- import { outputReferencesFilter as outputReferencesFilter2 } from "style-dictionary/utils";
1743
- var sizeVariables = ({ theme }) => {
1744
- const selector = `:root, [data-size]`;
1745
- const layer = `ds.theme.size`;
1746
- return {
1747
- preprocessors: ["tokens-studio"],
1748
- platforms: {
1749
- css: {
1750
- // custom
1751
- theme,
1752
- basePxFontSize,
1753
- selector,
1754
- layer,
1755
- //
1756
- prefix,
1757
- buildPath: `${theme}/`,
1758
- transforms: dsTransformers,
1759
- files: [
1760
- {
1761
- destination: `size.css`,
1762
- format: formats.size.name,
1763
- filter: (token) => {
1764
- const isUwantedToken = R16.anyPass([R16.includes("primitives/global")])(token.filePath);
1765
- const isPrivateToken = R16.includes("_", token.path);
1766
- return pathStartsWithOneOf(["size", "_size"], token) && !(isUwantedToken || isPrivateToken);
1767
- }
1768
- }
1769
- ],
1770
- options: {
1771
- outputReferences: (token, options) => {
1772
- const isWantedSize = pathStartsWithOneOf(["size", "_size"], token) && (isDigit(token.path[1]) || token.path[1] === "unit");
1773
- return isWantedSize && outputReferencesFilter2(token, options);
1774
- }
1775
- }
1776
- }
1777
- }
1778
- };
1779
- };
1780
-
1781
- // src/tokens/process/configs/size-mode.ts
1782
- import * as R17 from "ramda";
1783
- var sizeModeVariables = ({ theme, size: size2 }) => {
1784
- const selector = `:root`;
1785
- const layer = `ds.theme.size-mode`;
1786
- return {
1787
- preprocessors: ["tokens-studio"],
1788
- platforms: {
1789
- css: {
1790
- // custom
1791
- size: size2,
1792
- theme,
1793
- basePxFontSize,
1794
- selector,
1795
- layer,
1796
- //
1797
- prefix,
1798
- buildPath: `${theme}/`,
1799
- transforms: dsTransformers,
1800
- files: [
1801
- {
1802
- destination: `size-mode/${size2}.css`,
1803
- format: formats.sizeMode.name,
1804
- filter: (token) => {
1805
- return R17.equals(["_size", "mode-font-size"], token.path);
1806
- }
1807
- }
1808
- ]
1809
- }
1810
- }
1811
- };
1812
- };
1813
-
1814
- // src/tokens/process/configs/type-scale.ts
1815
- var typeScaleVariables = ({ theme }) => {
1816
- const selector = ":root, [data-size]";
1817
- const layer = `ds.theme.type-scale`;
1818
- return {
1819
- usesDtcg: true,
1820
- preprocessors: ["tokens-studio"],
1821
- expand: {
1822
- include: ["typography"]
1823
- },
1824
- platforms: {
1825
- css: {
1826
- prefix,
1827
- selector,
1828
- layer,
1829
- buildPath: `${theme}/`,
1830
- basePxFontSize,
1831
- transforms: [
1832
- "name/kebab",
1833
- "ts/size/px",
1834
- sizeRem.name,
1835
- "ts/size/lineheight",
1836
- "ts/typography/fontWeight",
1837
- typographyName.name
1838
- ],
1839
- files: [
1840
- {
1841
- destination: `type-scale.css`,
1842
- format: formats.typeScale.name,
1843
- filter: (token) => {
1844
- const included = typeEquals(["typography", "dimension", "fontsize"], token);
1845
- if (/primitives\/modes\/typography\/(primary|secondary)/.test(token.filePath)) return false;
1846
- return included && !pathStartsWithOneOf(["spacing", "sizing", "size", "border-width", "border-radius"], token) && (pathStartsWithOneOf(["font-size"], token) || token.path.includes("fontSize"));
1847
- }
1848
- }
1849
- ],
1850
- options: {
1851
- outputReferences: (token) => pathStartsWithOneOf(["typography"], token) && token.path.includes("fontSize")
1852
- }
1853
- }
1854
- }
1855
- };
1856
- };
1857
-
1858
- // src/tokens/process/configs/typography.ts
1859
- import { expandTypesMap } from "@tokens-studio/sd-transforms";
1860
- var typographyVariables = ({ theme, typography: typography2 }) => {
1861
- const selector = `${typography2 === "primary" ? ":root, " : ""}[data-typography="${typography2}"]`;
1862
- const layer = `ds.theme.typography.${typography2}`;
1863
- return {
1864
- usesDtcg: true,
1865
- preprocessors: ["tokens-studio"],
1866
- expand: {
1867
- include: ["typography"],
1868
- typesMap: { ...expandTypesMap, typography: { ...expandTypesMap.typography, letterSpacing: "dimension" } }
1869
- },
1870
- platforms: {
1871
- css: {
1872
- prefix,
1873
- typography: typography2,
1874
- selector,
1875
- layer,
1876
- buildPath: `${theme}/`,
1877
- basePxFontSize,
1878
- transforms: [
1879
- "name/kebab",
1880
- "ts/size/px",
1881
- sizeRem.name,
1882
- "ts/size/lineheight",
1883
- "ts/typography/fontWeight",
1884
- "ts/size/css/letterspacing",
1885
- typographyName.name
1886
- ],
1887
- files: [
1888
- {
1889
- destination: `typography/${typography2}.css`,
1890
- format: formats.typography.name,
1891
- filter: (token) => {
1892
- const included = typeEquals(["fontweight", "fontFamily", "lineHeight", "dimension"], token);
1893
- if (/primitives\/modes\/typography\/(primary|secondary)/.test(token.filePath)) return false;
1894
- return included && !pathStartsWithOneOf(["spacing", "sizing", "size", "_size", "border-width", "border-radius"], token) && !(pathStartsWithOneOf(["typography"], token) && token.path.includes("fontSize"));
1895
- }
1896
- }
1897
- ]
1898
- }
1899
- }
1900
- };
1901
- };
1902
-
1903
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowTypes.js
1904
- var BoxShadowTypes;
1905
- (function(BoxShadowTypes2) {
1906
- BoxShadowTypes2["DROP_SHADOW"] = "dropShadow";
1907
- BoxShadowTypes2["INNER_SHADOW"] = "innerShadow";
1908
- })(BoxShadowTypes || (BoxShadowTypes = {}));
1909
-
1910
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorModifierTypes.js
1911
- var ColorModifierTypes;
1912
- (function(ColorModifierTypes2) {
1913
- ColorModifierTypes2["LIGHTEN"] = "lighten";
1914
- ColorModifierTypes2["DARKEN"] = "darken";
1915
- ColorModifierTypes2["MIX"] = "mix";
1916
- ColorModifierTypes2["ALPHA"] = "alpha";
1917
- })(ColorModifierTypes || (ColorModifierTypes = {}));
1918
-
1919
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorSpaceTypes.js
1920
- var ColorSpaceTypes;
1921
- (function(ColorSpaceTypes2) {
1922
- ColorSpaceTypes2["LCH"] = "lch";
1923
- ColorSpaceTypes2["SRGB"] = "srgb";
1924
- ColorSpaceTypes2["P3"] = "p3";
1925
- ColorSpaceTypes2["HSL"] = "hsl";
1926
- })(ColorSpaceTypes || (ColorSpaceTypes = {}));
1927
-
1928
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/Properties.js
1929
- var Properties;
1930
- (function(Properties2) {
1931
- Properties2["sizing"] = "sizing";
1932
- Properties2["height"] = "height";
1933
- Properties2["width"] = "width";
1934
- Properties2["spacing"] = "spacing";
1935
- Properties2["verticalPadding"] = "verticalPadding";
1936
- Properties2["horizontalPadding"] = "horizontalPadding";
1937
- Properties2["paddingTop"] = "paddingTop";
1938
- Properties2["paddingRight"] = "paddingRight";
1939
- Properties2["paddingBottom"] = "paddingBottom";
1940
- Properties2["paddingLeft"] = "paddingLeft";
1941
- Properties2["itemSpacing"] = "itemSpacing";
1942
- Properties2["fill"] = "fill";
1943
- Properties2["backgroundBlur"] = "backgroundBlur";
1944
- Properties2["border"] = "border";
1945
- Properties2["borderTop"] = "borderTop";
1946
- Properties2["borderRight"] = "borderRight";
1947
- Properties2["borderBottom"] = "borderBottom";
1948
- Properties2["borderLeft"] = "borderLeft";
1949
- Properties2["borderColor"] = "borderColor";
1950
- Properties2["borderRadius"] = "borderRadius";
1951
- Properties2["borderRadiusTopLeft"] = "borderRadiusTopLeft";
1952
- Properties2["borderRadiusTopRight"] = "borderRadiusTopRight";
1953
- Properties2["borderRadiusBottomRight"] = "borderRadiusBottomRight";
1954
- Properties2["borderRadiusBottomLeft"] = "borderRadiusBottomLeft";
1955
- Properties2["borderWidth"] = "borderWidth";
1956
- Properties2["borderWidthTop"] = "borderWidthTop";
1957
- Properties2["borderWidthRight"] = "borderWidthRight";
1958
- Properties2["borderWidthBottom"] = "borderWidthBottom";
1959
- Properties2["borderWidthLeft"] = "borderWidthLeft";
1960
- Properties2["boxShadow"] = "boxShadow";
1961
- Properties2["opacity"] = "opacity";
1962
- Properties2["fontFamilies"] = "fontFamilies";
1963
- Properties2["fontWeights"] = "fontWeights";
1964
- Properties2["fontSizes"] = "fontSizes";
1965
- Properties2["lineHeights"] = "lineHeights";
1966
- Properties2["typography"] = "typography";
1967
- Properties2["composition"] = "composition";
1968
- Properties2["letterSpacing"] = "letterSpacing";
1969
- Properties2["paragraphSpacing"] = "paragraphSpacing";
1970
- Properties2["textCase"] = "textCase";
1971
- Properties2["dimension"] = "dimension";
1972
- Properties2["textDecoration"] = "textDecoration";
1973
- Properties2["asset"] = "asset";
1974
- Properties2["tokenValue"] = "tokenValue";
1975
- Properties2["value"] = "value";
1976
- Properties2["tokenName"] = "tokenName";
1977
- Properties2["description"] = "description";
1978
- })(Properties || (Properties = {}));
1979
-
1980
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenSetStatus.js
1981
- var TokenSetStatus;
1982
- (function(TokenSetStatus2) {
1983
- TokenSetStatus2["DISABLED"] = "disabled";
1984
- TokenSetStatus2["SOURCE"] = "source";
1985
- TokenSetStatus2["ENABLED"] = "enabled";
1986
- })(TokenSetStatus || (TokenSetStatus = {}));
1987
-
1988
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenTypes.js
1989
- var TokenTypes;
1990
- (function(TokenTypes2) {
1991
- TokenTypes2["OTHER"] = "other";
1992
- TokenTypes2["COLOR"] = "color";
1993
- TokenTypes2["BORDER_RADIUS"] = "borderRadius";
1994
- TokenTypes2["SIZING"] = "sizing";
1995
- TokenTypes2["SPACING"] = "spacing";
1996
- TokenTypes2["TEXT"] = "text";
1997
- TokenTypes2["TYPOGRAPHY"] = "typography";
1998
- TokenTypes2["OPACITY"] = "opacity";
1999
- TokenTypes2["BORDER_WIDTH"] = "borderWidth";
2000
- TokenTypes2["STROKE_STYLE"] = "strokeStyle";
2001
- TokenTypes2["BOX_SHADOW"] = "boxShadow";
2002
- TokenTypes2["FONT_FAMILIES"] = "fontFamilies";
2003
- TokenTypes2["FONT_WEIGHTS"] = "fontWeights";
2004
- TokenTypes2["LINE_HEIGHTS"] = "lineHeights";
2005
- TokenTypes2["FONT_SIZES"] = "fontSizes";
2006
- TokenTypes2["LETTER_SPACING"] = "letterSpacing";
2007
- TokenTypes2["PARAGRAPH_SPACING"] = "paragraphSpacing";
2008
- TokenTypes2["PARAGRAPH_INDENT"] = "paragraphIndent";
2009
- TokenTypes2["TEXT_DECORATION"] = "textDecoration";
2010
- TokenTypes2["TEXT_CASE"] = "textCase";
2011
- TokenTypes2["COMPOSITION"] = "composition";
2012
- TokenTypes2["DIMENSION"] = "dimension";
2013
- TokenTypes2["BORDER"] = "border";
2014
- TokenTypes2["ASSET"] = "asset";
2015
- TokenTypes2["BOOLEAN"] = "boolean";
2016
- TokenTypes2["NUMBER"] = "number";
2017
- })(TokenTypes || (TokenTypes = {}));
2018
-
2019
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BorderValues.js
2020
- var BorderValues;
2021
- (function(BorderValues2) {
2022
- BorderValues2["BORDER_COLOR"] = "color";
2023
- BorderValues2["BORDER_WIDTH"] = "width";
2024
- BorderValues2["BORDER_STYLE"] = "style";
2025
- })(BorderValues || (BorderValues = {}));
2026
-
2027
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/StrokeStyleValues.js
2028
- var StrokeStyleValues;
2029
- (function(StrokeStyleValues2) {
2030
- StrokeStyleValues2["SOLID"] = "solid";
2031
- StrokeStyleValues2["DASHED"] = "dashed";
2032
- StrokeStyleValues2["DOTTED"] = "dotted";
2033
- StrokeStyleValues2["DOUBLE"] = "double";
2034
- StrokeStyleValues2["GROOVE"] = "groove";
2035
- StrokeStyleValues2["RIDGE"] = "ridge";
2036
- StrokeStyleValues2["OUTSET"] = "outset";
2037
- StrokeStyleValues2["INSET"] = "inset";
2038
- })(StrokeStyleValues || (StrokeStyleValues = {}));
2039
-
2040
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowValues.js
2041
- var BoxShadowValues;
2042
- (function(BoxShadowValues2) {
2043
- BoxShadowValues2["TYPE"] = "type";
2044
- BoxShadowValues2["COLOR"] = "color";
2045
- BoxShadowValues2["X"] = "x";
2046
- BoxShadowValues2["Y"] = "y";
2047
- BoxShadowValues2["BLUR"] = "blur";
2048
- BoxShadowValues2["SPREAD"] = "spread";
2049
- BoxShadowValues2["BLEND_MODE"] = "blendMode";
2050
- })(BoxShadowValues || (BoxShadowValues = {}));
2051
-
2052
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TypographyValues.js
2053
- var TypographyValues;
2054
- (function(TypographyValues2) {
2055
- TypographyValues2["FONT_FAMILY"] = "fontFamily";
2056
- TypographyValues2["FONT_WEIGHT"] = "fontWeight";
2057
- TypographyValues2["LINE_HEIGHT"] = "lineHeight";
2058
- TypographyValues2["FONT_SIZE"] = "fontSize";
2059
- TypographyValues2["LETTER_SPACING"] = "letterSpacing";
2060
- TypographyValues2["PARAGRAPH_SPACING"] = "paragraphSpacing";
2061
- TypographyValues2["PARAGRAPH_INDENT"] = "paragraphIndent";
2062
- TypographyValues2["TEXT_DECORATION"] = "textDecoration";
2063
- TypographyValues2["TEXT_CASE"] = "textCase";
2064
- })(TypographyValues || (TypographyValues = {}));
2065
-
2066
- // src/tokens/process/utils/getMultidimensionalThemes.ts
2067
- import pc3 from "picocolors";
2068
- import * as R18 from "ramda";
2069
-
2070
- // src/tokens/process/utils/kebab-case.ts
2071
- function kebabCase(str) {
2072
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
2073
- }
2074
-
2075
- // src/tokens/process/utils/getMultidimensionalThemes.ts
2076
- var getMultidimensionalThemes = (processed$themes, dimensions) => {
2077
- const verboseLogging = buildOptions?.verbose;
2078
- const grouped$themes = groupThemes(processed$themes);
2079
- const permutations = permutateThemes(grouped$themes);
2080
- const ALL_DEPENDENT_ON = ["theme"];
2081
- const keys4 = R18.keys(grouped$themes);
2082
- const nonDependentKeys = keys4.filter((x) => ![...ALL_DEPENDENT_ON, ...dimensions].includes(x));
2083
- if (verboseLogging) {
2084
- console.log(pc3.cyan(`\u{1F50E} Finding theme permutations for ${dimensions}`));
2085
- console.log(pc3.cyan(` (ignoring permutations for ${nonDependentKeys})`));
2086
- }
2087
- return permutations.filter((val) => {
2088
- const filters = nonDependentKeys.map((x) => val.permutation[x] === grouped$themes[x][0].name);
2089
- return filters.every((x) => x);
2090
- });
2091
- };
2092
- var processed = /* @__PURE__ */ Symbol("Type brand for ProcessedThemeObject");
2093
- function isProcessed(theme) {
2094
- return Boolean(theme[processed]);
2095
- }
2096
- function processThemeObject(theme) {
2097
- if (isProcessed(theme)) {
2098
- return theme;
2099
- }
2100
- const result = { ...theme, [processed]: true };
2101
- if (result.group) {
2102
- result.group = kebabCase(result.group);
2103
- }
2104
- result.name = kebabCase(result.name);
2105
- return result;
2106
- }
2107
- function groupThemes(themes) {
2108
- const groups = {};
2109
- for (const theme of themes) {
2110
- if (theme.group) {
2111
- const groupKey = theme.group;
2112
- groups[groupKey] = [...groups[groupKey] ?? [], theme];
2113
- } else {
2114
- throw new Error(
2115
- `Theme ${theme.name} does not have a group property, which is required for multi-dimensional theming.`
2116
- );
2117
- }
2118
- }
2119
- return groups;
2120
- }
2121
- var hasUnknownProps = R18.pipe(R18.values, R18.none(R18.equals("unknown")), R18.not);
2122
- function permutateThemes(groups) {
2123
- const separator = "_";
2124
- const permutations = cartesian(Object.values(groups));
2125
- const permutatedThemes = permutations.map((perm) => {
2126
- const permutatedTheme = perm.reduce(
2127
- (acc, theme) => {
2128
- const { group, name, selectedTokenSets } = theme;
2129
- let updatedPermutation = acc.permutation;
2130
- if (group) {
2131
- const groupProp = R18.lensProp(group);
2132
- updatedPermutation = R18.set(groupProp, name, updatedPermutation);
2133
- }
2134
- const updatedName = `${String(acc.name)}${acc ? separator : ""}${name}`;
2135
- const sets = [...acc.selectedTokenSets, ...filterTokenSets(selectedTokenSets)];
2136
- return {
2137
- permutation: updatedPermutation,
2138
- name: updatedName,
2139
- selectedTokenSets: sets
2140
- };
2141
- },
2142
- {
2143
- name: "",
2144
- selectedTokenSets: [],
2145
- permutation: {
2146
- "color-scheme": "unknown",
2147
- "main-color": "unknown",
2148
- "support-color": "unknown",
2149
- theme: "unknown",
2150
- semantic: "unknown",
2151
- size: "unknown",
2152
- typography: "unknown"
2153
- }
2154
- }
2155
- );
2156
- if (hasUnknownProps(permutatedTheme)) {
2157
- throw Error(`Theme ${permutatedTheme.name} has unknown props: ${JSON.stringify(permutatedTheme)}`);
2158
- }
2159
- const uniqueTokenSets = new Set(permutatedTheme.selectedTokenSets);
2160
- return { ...permutatedTheme, selectedTokenSets: Array.from(uniqueTokenSets) };
2161
- });
2162
- return permutatedThemes;
2163
- }
2164
- function filterTokenSets(tokensets) {
2165
- return Object.entries(tokensets).filter(([, val]) => val !== TokenSetStatus.DISABLED).sort((a, b) => {
2166
- if (a[1] === TokenSetStatus.SOURCE && b[1] === TokenSetStatus.ENABLED) {
2167
- return -1;
2168
- }
2169
- if (a[1] === TokenSetStatus.ENABLED && b[1] === TokenSetStatus.SOURCE) {
2170
- return 1;
2171
- }
2172
- return 0;
2173
- }).map((entry) => entry[0]);
2174
- }
2175
- function cartesian(a) {
2176
- return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e].flat())));
2177
- }
2178
- var getCustomColors = (processed$themes, colorGroups) => processed$themes.filter((x) => {
2179
- if (!x.group) {
2180
- return false;
2181
- }
2182
- return colorGroups.includes(x.group);
2183
- }).map((x) => x.name);
2184
-
2185
- // src/tokens/process/configs.ts
2186
- void register(StyleDictionary, { withSDBuiltins: false });
2187
- StyleDictionary.registerTransform(sizeRem);
2188
- StyleDictionary.registerTransform(typographyName);
2189
- StyleDictionary.registerTransform(resolveMath);
2190
- StyleDictionary.registerTransform(unitless);
2191
- for (const format of Object.values(formats)) {
2192
- StyleDictionary.registerFormat(format);
2193
- }
2194
- var configs = {
2195
- colorSchemeVariables,
2196
- mainColorVariables: colorCategoryVariables({ category: "main" }),
2197
- supportColorVariables: colorCategoryVariables({ category: "support" }),
2198
- neutralColorVariables: colorCategoryVariables({ category: "builtin", color: "neutral" }),
2199
- successColorVariables: colorCategoryVariables({ category: "builtin", color: "success" }),
2200
- dangerColorVariables: colorCategoryVariables({ category: "builtin", color: "danger" }),
2201
- warningColorVariables: colorCategoryVariables({ category: "builtin", color: "warning" }),
2202
- infoColorVariables: colorCategoryVariables({ category: "builtin", color: "info" }),
2203
- sizeModeVariables,
2204
- sizeVariables,
2205
- typographyVariables,
2206
- typeScaleVariables,
2207
- semanticVariables
2208
- };
2209
- var getConfigsForThemeDimensions = (getConfig, processed$themes, dimensions, options) => {
2210
- const { tokensDir, tokenSets } = options;
2211
- const permutations = getMultidimensionalThemes(processed$themes, dimensions);
2212
- return permutations.flatMap(({ selectedTokenSets, permutation }) => {
2213
- const tokenSource = { source: void 0, tokens: {} };
2214
- if (tokenSets) {
2215
- for (const tokenSet of selectedTokenSets) {
2216
- const tokens = tokenSets.get(tokenSet);
2217
- if (tokens) {
2218
- const tokensWithFilePath = traverseObj(tokens, (obj) => {
2219
- if (Object.hasOwn(obj, `$value`) && !obj.filePath) {
2220
- obj.filePath = tokenSet;
2221
- }
2222
- });
2223
- tokenSource.tokens = R19.mergeDeepRight(tokenSource.tokens, tokensWithFilePath);
2224
- }
2225
- }
2226
- } else {
2227
- tokenSource.source = selectedTokenSets.map((x) => `${tokensDir}/${x}.json`);
2228
- }
2229
- const configOrConfigs = getConfig(permutation);
2230
- const configs_ = Array.isArray(configOrConfigs) ? configOrConfigs : [{ config: configOrConfigs }];
2231
- const configs2 = configs_.map(({ config, permutationOverrides }) => {
2232
- return {
2233
- permutation: { ...permutation, ...permutationOverrides },
2234
- config: {
2235
- ...config,
2236
- /** Use official W3C design token format
2237
- @see https://v4.styledictionary.com/info/dtcg/
2238
- @see https://design-tokens.github.io/community-group/format/ */
2239
- usesDtcg: true,
2240
- log: {
2241
- ...config?.log,
2242
- verbosity: buildOptions?.verbose ? "verbose" : "silent"
2243
- },
2244
- ...tokenSource
2245
- }
2246
- };
2247
- });
2248
- return configs2;
2249
- }).sort();
2250
- };
2251
-
2252
- // src/tokens/process/platform.ts
2253
- var initResult = {
2254
- formatted: [],
2255
- tokens: [],
2256
- permutation: {
2257
- "color-scheme": "",
2258
- "main-color": "",
2259
- "support-color": "",
2260
- semantic: "",
2261
- size: "",
2262
- theme: "",
2263
- typography: ""
2264
- }
2265
- };
2266
- var buildOptions = {
2267
- verbose: false,
2268
- processed$themes: [],
2269
- buildTokenFormats: {}
2270
- };
2271
- var sd = new StyleDictionary2();
2272
- var buildConfigs = {
2273
- typography: { getConfig: configs.typographyVariables, dimensions: ["typography"] },
2274
- sizeMode: { getConfig: configs.sizeModeVariables, dimensions: ["size"] },
2275
- size: { getConfig: configs.sizeVariables, dimensions: ["semantic"] },
2276
- typeScale: { getConfig: configs.typeScaleVariables, dimensions: ["semantic"] },
2277
- "color-scheme": { getConfig: configs.colorSchemeVariables, dimensions: ["color-scheme"] },
2278
- "main-color": { getConfig: configs.mainColorVariables, dimensions: ["main-color"] },
2279
- "support-color": { getConfig: configs.supportColorVariables, dimensions: ["support-color"] },
2280
- "neutral-color": {
2281
- getConfig: configs.neutralColorVariables,
2282
- dimensions: ["semantic"],
2283
- log: ({ permutation: { theme } }) => `${theme} - neutral`
2284
- },
2285
- "success-color": {
2286
- getConfig: configs.successColorVariables,
2287
- dimensions: ["semantic"],
2288
- log: ({ permutation: { theme } }) => `${theme} - success`
2289
- },
2290
- "danger-color": {
2291
- getConfig: configs.dangerColorVariables,
2292
- dimensions: ["semantic"],
2293
- log: ({ permutation: { theme } }) => `${theme} - danger`
2294
- },
2295
- "warning-color": {
2296
- getConfig: configs.warningColorVariables,
2297
- dimensions: ["semantic"],
2298
- log: ({ permutation: { theme } }) => `${theme} - warning`
2299
- },
2300
- "info-color": {
2301
- getConfig: configs.infoColorVariables,
2302
- dimensions: ["semantic"],
2303
- log: ({ permutation: { theme } }) => `${theme} - info`
2304
- },
2305
- semantic: { getConfig: configs.semanticVariables, dimensions: ["semantic"] }
2306
- };
2307
- async function processPlatform(options) {
2308
- const { type, processed$themes } = options;
2309
- const platform = "css";
2310
- const tokenSets = type === "format" ? options.tokenSets : void 0;
2311
- const tokensDir = type === "build" ? options.tokensDir : void 0;
2312
- const UNSAFE_DEFAULT_COLOR = process.env.UNSAFE_DEFAULT_COLOR ?? "";
2313
- if (UNSAFE_DEFAULT_COLOR) {
2314
- console.warn(
2315
- pc4.yellow(
2316
- `
2317
- \u26A0\uFE0F UNSAFE_DEFAULT_COLOR is set to ${pc4.blue(UNSAFE_DEFAULT_COLOR)}. This will override the default color.`
2318
- )
2319
- );
2320
- }
2321
- const UNSAFE_COLOR_GROUPS = Array.from(process.env.UNSAFE_COLOR_GROUPS?.split(",") ?? []);
2322
- if (UNSAFE_COLOR_GROUPS.length > 0) {
2323
- console.warn(
2324
- pc4.yellow(
2325
- `
2326
- \u26A0\uFE0F UNSAFE_COLOR_GROUPS is set to ${pc4.blue(`[${UNSAFE_COLOR_GROUPS.join(", ")}]`)}. This will override the default color groups.`
2327
- )
2328
- );
2329
- }
2330
- const colorGroups = UNSAFE_COLOR_GROUPS.length > 0 ? UNSAFE_COLOR_GROUPS : [colorCategories.main, colorCategories.support].map((c) => `${c}-color`);
2331
- buildOptions = options;
2332
- buildOptions.defaultColor = UNSAFE_DEFAULT_COLOR;
2333
- buildOptions.colorGroups = colorGroups;
2334
- if (!buildOptions.defaultColor) {
2335
- const customColors = getCustomColors(processed$themes, colorGroups);
2336
- const firstMainColor = R20.head(customColors);
2337
- buildOptions.defaultColor = firstMainColor;
2338
- }
2339
- if (buildOptions.defaultColor) {
2340
- console.log(`
2341
- \u{1F3A8} Using ${pc4.blue(buildOptions.defaultColor)} as default color`);
2342
- }
2343
- const sizeModes2 = processed$themes.filter((x) => x.group === "size").map((x) => x.name);
2344
- buildOptions.sizeModes = sizeModes2;
2345
- if (!buildOptions.defaultSize) {
2346
- const defaultSize = R20.head(sizeModes2);
2347
- buildOptions.defaultSize = defaultSize;
2348
- }
2349
- if (buildOptions.defaultSize) {
2350
- console.log(`
2351
- \u{1F4CF} Using ${pc4.blue(buildOptions.defaultSize)} as default size`);
2352
- }
2353
- const buildAndSdConfigs = R20.map((buildConfig) => {
2354
- const sdConfigs = getConfigsForThemeDimensions(buildConfig.getConfig, processed$themes, buildConfig.dimensions, {
2355
- tokensDir,
2356
- tokenSets
2357
- });
2358
- const unknownConfigs = buildConfig.dimensions.map(
2359
- (dimension) => sdConfigs.filter((x) => x.permutation[dimension] === "unknown")
2360
- );
2361
- for (const unknowns of unknownConfigs) {
2362
- if (unknowns.length === sdConfigs.length) {
2363
- buildConfig.enabled = () => false;
2364
- }
2365
- }
2366
- return {
2367
- buildConfig,
2368
- sdConfigs
2369
- };
2370
- }, buildConfigs);
2371
- const processedBuilds = {
2372
- "color-scheme": [initResult],
2373
- "main-color": [initResult],
2374
- "support-color": [initResult],
2375
- "neutral-color": [initResult],
2376
- "success-color": [initResult],
2377
- "danger-color": [initResult],
2378
- "warning-color": [initResult],
2379
- "info-color": [initResult],
2380
- semantic: [initResult],
2381
- typography: [initResult],
2382
- sizeMode: [initResult],
2383
- size: [initResult],
2384
- typeScale: [initResult]
2385
- };
2386
- try {
2387
- for (const [buildName, { buildConfig, sdConfigs }] of R20.toPairs(buildAndSdConfigs)) {
2388
- if (!(buildConfig.enabled?.() ?? true)) {
2389
- continue;
2390
- }
2391
- if (sdConfigs.length > 0) {
2392
- console.log(`
2393
- \u{1F371} Building ${pc4.green(buildConfig.name ?? buildName)}`);
2394
- const results = await Promise.all(
2395
- sdConfigs.map(async (sdConfig) => {
2396
- const { config, permutation } = sdConfig;
2397
- const modes = ["theme", ...buildConfig.dimensions];
2398
- const modeMessage = modes.map((x) => permutation[x]).join(" - ");
2399
- const logMessage = R20.isNil(buildConfig.log) ? modeMessage : buildConfig?.log(sdConfig);
2400
- console.log(logMessage);
2401
- const sdOptions = { cache: true };
2402
- const sdExtended = await sd.extend(config);
2403
- const formatted = await sdExtended.formatPlatform(platform, sdOptions);
2404
- const tokens = (await sdExtended.getPlatformTokens(platform, sdOptions)).allTokens;
2405
- const result = {
2406
- permutation,
2407
- formatted,
2408
- tokens
2409
- };
2410
- return Promise.resolve(result);
2411
- })
2412
- );
2413
- processedBuilds[buildName] = results;
2414
- }
2415
- }
2416
- } catch (err) {
2417
- if (err instanceof Error) {
2418
- err.message = err.message.replace('log.verbosity "verbose" or use ', "");
2419
- }
2420
- throw err;
2421
- }
2422
- return processedBuilds;
2423
- }
2424
-
2425
- // src/tokens/process/output/declarations.ts
2426
- var defaultFileHeader = `build: v${package_default.version}`;
2427
- var createTypeDeclarationFiles = (processed$themes) => {
2428
- const colorGroups = buildOptions?.colorGroups || [];
2429
- const customColors = getCustomColors(processed$themes, colorGroups);
2430
- const typeDeclaration = createColorTypeDeclaration([...customColors, "neutral"]);
2431
- return [
2432
- {
2433
- output: `/* This file is deprecated and will be removed in a future release. Use types.d.ts instead */
2434
- ${typeDeclaration}`,
2435
- destination: "colors.d.ts"
2436
- },
2437
- {
2438
- output: typeDeclaration,
2439
- destination: "types.d.ts"
2440
- }
2441
- ];
2442
- };
2443
- function createColorTypeDeclaration(colors2) {
2444
- console.log(`
2445
- \u{1F371} Building ${pc5.green("type declarations")}`);
2446
- const typeDeclaration = `
2447
- /* ${defaultFileHeader} */
2448
- import type {} from '@digdir/designsystemet-types';
2449
-
2450
- // Augment types based on theme
2451
- declare module '@digdir/designsystemet-types' {
2452
- export interface ColorDefinitions {
2453
- ${colors2.map((color) => ` ${color.includes("-") ? `'${color}'` : color}: never;`).join("\n")}
2454
- }
2455
- export interface SeverityColorDefinitions {
2456
- info: never;
2457
- success: never;
2458
- warning: never;
2459
- danger: never;
2460
- }
2461
- }
2462
- `.trimStart();
2463
- return typeDeclaration;
2464
- }
2465
-
2466
- // src/tokens/process/output/tailwind.ts
2467
- var createTailwindCSSFiles = (cssFiles) => {
2468
- console.log("\n\u{1F371} Creating Tailwind Config");
2469
- return cssFiles.map((file) => {
2470
- if (file.destination) {
2471
- const tailwindConfig = generateTailwind(file.output);
2472
- const tailwindFile = {
2473
- destination: file.destination.replace(".css", ".tailwind.css"),
2474
- output: tailwindConfig
2475
- };
2476
- return tailwindFile;
2477
- }
2478
- return void 0;
2479
- }).filter((item) => item !== void 0);
2480
- };
2481
- var generateTailwind = (css) => {
2482
- const tailwind = ["--font-sans: var(--ds-font-family)"];
2483
- const tokens = Array.from(new Set(css.match(/--ds-[^:)]+/g)), (m) => m).sort(
2484
- (a, b) => a.localeCompare(b, void 0, { numeric: true, sensitivity: "base" })
2485
- );
2486
- for (const token of tokens) {
2487
- if (token.startsWith("--ds-color-") && !token.startsWith("--ds-color-focus")) {
2488
- tailwind.push(`--color-${token.replace("--ds-color-", "")}: var(${token})`);
2489
- } else if (token.startsWith("--ds-font-weight-")) {
2490
- tailwind.push(`--font-weight-${token.replace("--ds-font-weight-", "")}: var(${token})`);
2491
- } else if (token.match(/--ds-border-radius-(sm|md|lg|xl)/)) {
2492
- tailwind.push(`--radius-${token.replace("--ds-border-radius-", "")}: var(${token})`);
2493
- } else if (token.match(/--ds-body-(sm|mg|lg)-body-font-size/)) {
2494
- tailwind.push(`--text-${token.replace("--ds-body-", "").replace("-font-size", "")}: var(${token})`);
2495
- } else if (token.match(/^--ds-size-\d+$/)) {
2496
- tailwind.push(`--spacing-${token.replace("--ds-size-", "")}: var(${token})`);
2497
- }
2498
- }
2499
- const dynamicColors = `[data-color] {
2500
- --color-background-default: var(--ds-color-background-default);
2501
- --color-background-tinted: var(--ds-color-background-tinted);
2502
- --color-surface-default: var(--ds-color-surface-default);
2503
- --color-surface-tinted: var(--ds-color-surface-tinted);
2504
- --color-surface-hover: var(--ds-color-surface-hover);
2505
- --color-surface-active: var(--ds-color-surface-active);
2506
- --color-border-subtle: var(--ds-color-border-subtle);
2507
- --color-border-default: var(--ds-color-border-default);
2508
- --color-border-strong: var(--ds-color-border-strong);
2509
- --color-text-subtle: var(--ds-color-text-subtle);
2510
- --color-text-default: var(--ds-color-text-default);
2511
- --color-base-default: var(--ds-color-base-default);
2512
- --color-base-hover: var(--ds-color-base-hover);
2513
- --color-base-active: var(--ds-color-base-active);
2514
- --color-base-contrast-subtle: var(--ds-color-base-contrast-subtle);
2515
- --color-base-contrast-default: var(--ds-color-base-contrast-default);
2516
- }`;
2517
- return `@theme {${tailwind.map((str) => `
2518
- ${str};`).join("")}
2519
- }
2520
- ${dynamicColors}`;
2521
- };
2522
-
2523
- // src/tokens/process/output/theme.ts
2524
- import pc6 from "picocolors";
2525
- import * as R21 from "ramda";
2526
- var defaultFileHeader2 = `build: v${package_default.version}`;
2527
- var getFileNameWithoutExtension = (path5) => {
2528
- const pathSegments = path5.split("/");
2529
- return pathSegments[pathSegments.length - 1].split(".").slice(0, -1).join(".");
2530
- };
2531
- var createThemeCSSFiles = ({
2532
- processedBuilds,
2533
- fileHeader = defaultFileHeader2
2534
- }) => {
2535
- const groupedByTheme = {};
2536
- for (const [_, buildResults] of Object.entries(processedBuilds)) {
2537
- for (const buildResult of buildResults) {
2538
- const themeName = buildResult.permutation.theme;
2539
- const newOutputs = buildResult.formatted;
2540
- if (R21.isNotEmpty(newOutputs)) {
2541
- const currentOutputs = groupedByTheme[themeName] ?? [];
2542
- groupedByTheme[themeName] = R21.concat(currentOutputs, newOutputs);
2543
- }
2544
- }
2545
- }
2546
- const sortOrder = [
2547
- "size-mode/",
2548
- "type-scale",
2549
- "color-scheme/light",
2550
- "typography/secondary",
2551
- "size",
2552
- "semantic",
2553
- "color-scheme/dark",
2554
- "color-scheme/contrast",
2555
- "typography/primary",
2556
- "color/"
2557
- ];
2558
- const sortByDefinedOrder = R21.sortBy((file) => {
2559
- const filePath = file.destination || "";
2560
- const sortIndex = sortOrder.findIndex((sortElement) => {
2561
- if (sortElement.endsWith("/")) {
2562
- return filePath.includes(sortElement);
2563
- }
2564
- return filePath.includes(`${sortElement}.css`);
2565
- });
2566
- if (sortIndex === -1) {
2567
- console.error(
2568
- pc6.yellow(`WARNING: CSS section does not have a defined sort order: ${filePath.replace(".css", "")}`)
2569
- );
2570
- console.log(
2571
- pc6.dim(
2572
- `
2573
- The section will currently be added to the end of the entry file, but the exact
2574
- order may change due to nondeterminism.`.trim()
2575
- )
2576
- );
2577
- return Infinity;
2578
- }
2579
- return sortIndex;
2580
- });
2581
- const header = `@charset "UTF-8";
2582
- /*
2583
- ${fileHeader}
2584
- */
2585
-
2586
- `;
2587
- const sortAlphabetically = R21.sort(R21.ascend((x) => x.destination || ""));
2588
- const sortBySize = R21.sortBy(
2589
- R21.pipe((s) => getFileNameWithoutExtension(s.destination ?? ""), sizeComparator)
2590
- );
2591
- const pickOutputs = R21.map(R21.view(R21.lensProp("output")));
2592
- const themeCSSFile = R21.pipe(
2593
- sortAlphabetically,
2594
- sortBySize,
2595
- sortByDefinedOrder,
2596
- pickOutputs,
2597
- R21.join("\n"),
2598
- (content) => header + content
2599
- );
2600
- const themeCSSFiles = Object.entries(groupedByTheme).map(([theme, files]) => ({
2601
- destination: `${theme}.css`,
2602
- output: themeCSSFile(files)
2603
- }));
2604
- return themeCSSFiles;
2605
- };
2606
-
2607
- // src/tokens/build.ts
2608
- var buildTokens = async (options) => {
2609
- const tokensDir = options.tokensDir;
2610
- const $themes = JSON.parse(await dsfs.readFile(`${tokensDir}/$themes.json`));
2611
- const processed$themes = $themes.map(processThemeObject);
2612
- let $designsystemet;
2613
- try {
2614
- const $designsystemetContent = await dsfs.readFile(`${tokensDir}/$designsystemet.jsonc`);
2615
- $designsystemet = JSON.parse($designsystemetContent);
2616
- } catch (_error) {
2617
- }
2618
- console.log(`
2619
- \u{1F3D7}\uFE0F Start building tokens in ${pc7.green(tokensDir)}`);
2620
- const processedBuilds = await processPlatform({
2621
- ...options,
2622
- tokensDir,
2623
- type: "build",
2624
- processed$themes,
2625
- buildTokenFormats: {}
2626
- });
2627
- const fileHeader = R22.join("")([
2628
- defaultFileHeader2,
2629
- $designsystemet ? `
2630
- design-tokens: v${$designsystemet.version}` : ""
2631
- ]);
2632
- let files = [];
2633
- const declarationFiles = createTypeDeclarationFiles(processed$themes);
2634
- const cssFiles = createThemeCSSFiles({ processedBuilds, fileHeader });
2635
- files = [...declarationFiles, ...cssFiles];
2636
- if (options.tailwind) {
2637
- const tailwindFiles = createTailwindCSSFiles(cssFiles);
2638
- files = files.concat(tailwindFiles.filter(Boolean));
2639
- }
2640
- return files;
2641
- };
2642
-
2643
- // src/tokens/create/generators/$designsystemet.ts
2644
- function generate$Designsystemet() {
2645
- return {
2646
- name: package_default.name,
2647
- version: package_default.version
2648
- };
2649
- }
2650
-
2651
- // src/tokens/create/generators/$metadata.ts
2652
- function generate$Metadata(schemes, themes, colors2, sizeModes2) {
2653
- return {
2654
- tokenSetOrder: [
2655
- "primitives/globals",
2656
- ...sizeModes2.map((size2) => `primitives/modes/size/${size2}`),
2657
- "primitives/modes/size/global",
2658
- ...sizeModes2.map((size2) => `primitives/modes/typography/size/${size2}`),
2659
- ...themes.map((theme) => `primitives/modes/typography/primary/${theme}`),
2660
- ...themes.map((theme) => `primitives/modes/typography/secondary/${theme}`),
2661
- ...schemes.flatMap((scheme) => [...themes.map((theme) => `primitives/modes/color-scheme/${scheme}/${theme}`)]),
2662
- ...themes.map((theme) => `themes/${theme}`),
2663
- "semantic/color",
2664
- ...Object.entries(colors2.main).map(([color]) => `semantic/modes/main-color/${color}`),
2665
- ...Object.entries(colors2.support).map(([color]) => `semantic/modes/support-color/${color}`),
2666
- "semantic/style"
2667
- ]
2668
- };
2669
- }
2670
-
2671
- // src/tokens/create/generators/$themes.ts
2672
- var capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1);
2673
- async function createHash(text, algo = "SHA-1") {
2674
- const crypto = globalThis.crypto;
2675
- return Array.from(
2676
- new Uint8Array(await crypto.subtle.digest(algo, new TextEncoder().encode(text))),
2677
- (byte) => byte.toString(16).padStart(2, "0")
2678
- ).join("");
2679
- }
2680
- async function generate$Themes(colorSchemes, themes, colors2, sizeModes2) {
2681
- return [
2682
- ...generateSizeGroup(sizeModes2),
2683
- ...await generateThemesGroup(themes),
2684
- ...generateTypographyGroup(themes),
2685
- ...generateColorSchemesGroup(colorSchemes, themes),
2686
- generateSemanticGroup(),
2687
- ...await generateColorGroup("main", colors2),
2688
- ...await generateColorGroup("support", colors2)
2689
- ];
2690
- }
2691
- function generateSizeGroup(_sizes) {
2692
- return [
2693
- {
2694
- id: "8b2c8cc86611a34b135cb22948666779361fd729",
2695
- name: "medium",
2696
- $figmaStyleReferences: {},
2697
- selectedTokenSets: {
2698
- "primitives/modes/size/medium": TokenSetStatus.SOURCE,
2699
- "primitives/modes/size/global": TokenSetStatus.ENABLED,
2700
- "primitives/modes/typography/size/medium": TokenSetStatus.ENABLED
2701
- },
2702
- $figmaCollectionId: "VariableCollectionId:36248:20757",
2703
- $figmaModeId: "41630:1",
2704
- group: "Size"
2705
- },
2706
- {
2707
- id: "d49b9eebeb48a4f165a74b7261733d0a73370f0e",
2708
- name: "large",
2709
- $figmaStyleReferences: {},
2710
- selectedTokenSets: {
2711
- "primitives/modes/size/large": TokenSetStatus.SOURCE,
2712
- "primitives/modes/size/global": TokenSetStatus.ENABLED,
2713
- "primitives/modes/typography/size/large": TokenSetStatus.ENABLED
2714
- },
2715
- $figmaCollectionId: "VariableCollectionId:36248:20757",
2716
- $figmaModeId: "41630:2",
2717
- group: "Size"
2718
- },
2719
- {
2720
- id: "fb11567729c298ca37c9da4e3a27716a23480824",
2721
- name: "small",
2722
- $figmaStyleReferences: {},
2723
- selectedTokenSets: {
2724
- "primitives/modes/size/small": TokenSetStatus.SOURCE,
2725
- "primitives/modes/size/global": TokenSetStatus.ENABLED,
2726
- "primitives/modes/typography/size/small": TokenSetStatus.ENABLED
2727
- },
2728
- $figmaCollectionId: "VariableCollectionId:36248:20757",
2729
- $figmaModeId: "41630:3",
2730
- group: "Size"
2731
- }
2732
- ];
2733
- }
2734
- var colorSchemeDefaults = {
2735
- light: {
2736
- name: "Light",
2737
- selectedTokenSets: {},
2738
- id: "0daa3ca0b427b9349da7e7dc00101b5668972926",
2739
- $figmaCollectionId: "VariableCollectionId:34811:5472",
2740
- $figmaModeId: "34811:0"
2741
- },
2742
- dark: {
2743
- name: "Dark",
2744
- selectedTokenSets: {},
2745
- id: "9ebd8aed52afbffc17e2666e8b4653a53498b257",
2746
- $figmaCollectionId: "VariableCollectionId:34811:5472",
2747
- $figmaModeId: "34811:1"
2748
- },
2749
- contrast: {
2750
- name: "Contrast",
2751
- selectedTokenSets: {},
2752
- id: "9ebd8aed52afbffc17e2666e8b4653a53498b123",
2753
- $figmaCollectionId: "VariableCollectionId:34811:5472",
2754
- $figmaModeId: "34811:2"
2755
- }
2756
- };
2757
- function generateColorSchemesGroup(colorSchemes, themes) {
2758
- return colorSchemes.map(
2759
- (scheme) => ({
2760
- ...colorSchemeDefaults[scheme],
2761
- selectedTokenSets: Object.fromEntries([
2762
- ...themes.map((theme) => [`primitives/modes/color-scheme/${scheme}/${theme}`, TokenSetStatus.ENABLED])
2763
- ]),
2764
- group: "Color scheme"
2765
- })
2766
- );
2767
- }
2768
- async function generateThemesGroup(themes) {
2769
- return Promise.all(
2770
- themes.map(
2771
- async (theme, index) => ({
2772
- id: await createHash(theme),
2773
- $figmaCollectionId: "VariableCollectionId:36528:61712",
2774
- $figmaModeId: `40960:${index + 6}`,
2775
- // Start on 6 in Token Studio and Community file for some reason
2776
- name: theme,
2777
- selectedTokenSets: {
2778
- [`themes/${theme}`]: TokenSetStatus.ENABLED
2779
- },
2780
- group: "Theme"
2781
- })
2782
- )
2783
- );
2784
- }
2785
- function generateSemanticGroup() {
2786
- return {
2787
- id: "541629445ef90ad5363f9e88f52a1ccb617e6f84",
2788
- name: "Semantic",
2789
- selectedTokenSets: {
2790
- "semantic/style": TokenSetStatus.ENABLED,
2791
- "semantic/color": TokenSetStatus.ENABLED,
2792
- "primitives/globals": TokenSetStatus.SOURCE
2793
- },
2794
- $figmaCollectionId: "VariableCollectionId:34811:5976",
2795
- $figmaModeId: "34811:5",
2796
- group: "Semantic"
2797
- };
2798
- }
2799
- async function generateColorGroup(group, colors2) {
2800
- return Promise.all(
2801
- Object.entries(colors2[group]).map(
2802
- async ([color]) => ({
2803
- id: await createHash(`${group}-${color}`),
2804
- name: color,
2805
- selectedTokenSets: {
2806
- [`semantic/modes/${group}-color/${color}`]: TokenSetStatus.ENABLED
2807
- },
2808
- group: `${capitalize(group)} color`
2809
- })
2810
- )
2811
- );
2812
- }
2813
- function generateTypographyGroup(themes) {
2814
- return [
2815
- {
2816
- id: "368d753fcac4455f289500eaa42e70dc0a03522f",
2817
- $figmaCollectionId: "VariableCollectionId:36248:20769",
2818
- $figmaModeId: "36248:2",
2819
- name: "Primary",
2820
- selectedTokenSets: Object.fromEntries(
2821
- themes.map((theme) => [`primitives/modes/typography/primary/${theme}`, TokenSetStatus.ENABLED])
2822
- ),
2823
- group: "Typography"
2824
- },
2825
- {
2826
- id: "264b8bd1d40b364e1ea3acf09e49795ddd4c513c",
2827
- $figmaCollectionId: "VariableCollectionId:36248:20769",
2828
- $figmaModeId: "36248:3",
2829
- name: "Secondary",
2830
- selectedTokenSets: Object.fromEntries(
2831
- themes.map((theme) => [`primitives/modes/typography/secondary/${theme}`, TokenSetStatus.ENABLED])
2832
- ),
2833
- group: "Typography"
2834
- }
2835
- ];
2836
- }
2837
-
2838
- // src/tokens/create/files.ts
2839
- var stringify = (data) => JSON.stringify(data, null, 2);
2840
- var createTokenFiles = async (options) => {
2841
- const {
2842
- outDir,
2843
- tokenSets,
2844
- theme: { colors: colors2 },
2845
- themeNames
2846
- } = options;
2847
- const $themesPath = "$themes.json";
2848
- const $metadataPath = "$metadata.json";
2849
- const $designsystemetPath = "$designsystemet.jsonc";
2850
- const sizeModes2 = ["small", "medium", "large"];
2851
- await dsfs.mkdir(outDir);
2852
- const $themes = await generate$Themes(["dark", "light"], themeNames, colors2, sizeModes2);
2853
- const $metadata = generate$Metadata(["dark", "light"], themeNames, colors2, sizeModes2);
2854
- const $designsystemet = generate$Designsystemet();
2855
- const files = [];
2856
- files.push({ destination: $themesPath, output: stringify($themes) });
2857
- files.push({ destination: $metadataPath, output: stringify($metadata) });
2858
- files.push({ destination: $designsystemetPath, output: stringify($designsystemet) });
2859
- for (const [set4, tokens] of tokenSets) {
2860
- const filePath = `${set4}.json`;
2861
- files.push({ destination: filePath, output: stringify(tokens) });
2862
- }
2863
- return files;
2864
- };
2865
-
2866
- // src/tokens/create/generators/primitives/color-scheme.ts
2867
- import * as R23 from "ramda";
2868
- var generateColor = (colorArray, overrides) => {
2869
- const obj = {};
2870
- const $type = "color";
2871
- for (const index in colorArray) {
2872
- const position = Number(index) + 1;
2873
- const overrideValue = overrides?.[position];
2874
- obj[position] = {
2875
- $type,
2876
- $value: overrideValue || colorArray[index].hex
2877
- };
2878
- }
2879
- return obj;
2880
- };
2881
- var generateColorScheme = (themeName, colorScheme2, colors2, overrides) => {
2882
- const createColorOverrides = (colorName) => {
2883
- if (!overrides?.colors || !(colorName in overrides.colors)) {
2884
- return void 0;
2885
- }
2886
- const colorOverrides = overrides.colors[colorName];
2887
- const positionOverrides = {};
2888
- Object.entries(colorOverrides).forEach(([semanticTokenName, modeOverrides]) => {
2889
- const position = colorMetadata[semanticTokenName].number;
2890
- if (position) {
2891
- let overrideValue;
2892
- if (colorScheme2 === "light" && modeOverrides.light) {
2893
- overrideValue = modeOverrides.light;
2894
- } else if (colorScheme2 === "dark" && modeOverrides.dark) {
2895
- overrideValue = modeOverrides.dark;
2896
- }
2897
- if (overrideValue) {
2898
- positionOverrides[position] = overrideValue;
2899
- }
2900
- }
2901
- });
2902
- return Object.keys(positionOverrides).length > 0 ? positionOverrides : void 0;
2903
- };
2904
- const main = R23.mapObjIndexed(
2905
- (color, colorName) => generateColor(generateColorScale(color, colorScheme2), createColorOverrides(colorName)),
2906
- colors2.main
2907
- );
2908
- const support = R23.mapObjIndexed(
2909
- (color, colorName) => generateColor(generateColorScale(color, colorScheme2), createColorOverrides(colorName)),
2910
- colors2.support
2911
- );
2912
- const neutralColorScale = generateColorScale(colors2.neutral, colorScheme2);
2913
- const neutral = generateColor(neutralColorScale, createColorOverrides("neutral"));
2914
- const baseColorsWithOverrides = {
2915
- ...baseColors,
2916
- ...overrides?.severity
2917
- };
2918
- const globalColors = R23.mapObjIndexed(
2919
- (color, colorName) => generateColor(generateColorScale(color, colorScheme2), createColorOverrides(colorName)),
2920
- baseColorsWithOverrides
2921
- );
2922
- const linkColor = generateColor(generateColorScale(dsLinkColor, colorScheme2));
2923
- const defaultLinkVisited = linkColor[12];
2924
- const linkOverride = overrides?.linkVisited?.[colorScheme2] ? { $type: "color", $value: overrides.linkVisited[colorScheme2] } : void 0;
2925
- const defaultFocusInner = neutralColorScale[0].hex;
2926
- const defaultFocusOuter = neutralColorScale[10].hex;
2927
- const focusInnerOverride = overrides?.focus?.inner?.[colorScheme2];
2928
- const focusOuterOverride = overrides?.focus?.outer?.[colorScheme2];
2929
- return {
2930
- [themeName]: {
2931
- ...main,
2932
- ...support,
2933
- neutral,
2934
- ...globalColors,
2935
- link: {
2936
- visited: linkOverride || defaultLinkVisited
2937
- },
2938
- focus: {
2939
- inner: {
2940
- $type: "color",
2941
- $value: focusInnerOverride || defaultFocusInner
2942
- },
2943
- outer: {
2944
- $type: "color",
2945
- $value: focusOuterOverride || defaultFocusOuter
2946
- }
2947
- }
2948
- }
2949
- };
2950
- };
2951
-
2952
- // src/tokens/create/generators/primitives/globals.ts
2953
- var globals = {
2954
- "border-width": {
2955
- "1": {
2956
- $type: "borderWidth",
2957
- $value: "1px"
2958
- },
2959
- "3": {
2960
- $type: "borderWidth",
2961
- $value: "3px"
2962
- }
2963
- },
2964
- shadow: {
2965
- "100": {
2966
- $type: "boxShadow",
2967
- $value: [
2968
- {
2969
- color: "rgba(0,0,0,0.16)",
2970
- x: "0",
2971
- y: "0",
2972
- blur: "1",
2973
- spread: "0"
2974
- },
2975
- {
2976
- x: "0",
2977
- y: "1",
2978
- blur: "2",
2979
- spread: "0",
2980
- color: "rgba(0,0,0,0.12)"
2981
- }
2982
- ]
2983
- },
2984
- "200": {
2985
- $type: "boxShadow",
2986
- $value: [
2987
- {
2988
- color: "rgba(0,0,0,0.15)",
2989
- x: "0",
2990
- y: "0",
2991
- blur: "1",
2992
- spread: "0"
2993
- },
2994
- {
2995
- color: "rgba(0,0,0,0.12)",
2996
- x: "0",
2997
- y: "1",
2998
- blur: "2",
2999
- spread: "0"
3000
- },
3001
- {
3002
- x: "0",
3003
- y: "2",
3004
- blur: "4",
3005
- spread: "0",
3006
- color: "rgba(0,0,0,0.1)"
3007
- }
3008
- ]
3009
- },
3010
- "300": {
3011
- $type: "boxShadow",
3012
- $value: [
3013
- {
3014
- color: "rgba(0,0,0,0.14)",
3015
- x: "0",
3016
- y: "0",
3017
- blur: "1",
3018
- spread: "0"
3019
- },
3020
- {
3021
- color: "rgba(0,0,0,0.12)",
3022
- x: "0",
3023
- y: "2",
3024
- blur: "4",
3025
- spread: "0"
3026
- },
3027
- {
3028
- x: "0",
3029
- y: "4",
3030
- blur: "8",
3031
- spread: "0",
3032
- color: "rgba(0,0,0,0.12)"
3033
- }
3034
- ]
3035
- },
3036
- "400": {
3037
- $type: "boxShadow",
3038
- $value: [
3039
- {
3040
- color: "rgba(0,0,0,0.13)",
3041
- x: "0",
3042
- y: "0",
3043
- blur: "1",
3044
- spread: "0"
3045
- },
3046
- {
3047
- color: "rgba(0,0,0,0.13)",
3048
- x: "0",
3049
- y: "3",
3050
- blur: "5",
3051
- spread: "0"
3052
- },
3053
- {
3054
- x: "0",
3055
- y: "6",
3056
- blur: "12",
3057
- spread: "0",
3058
- color: "rgba(0,0,0,0.14)"
3059
- }
3060
- ]
3061
- },
3062
- "500": {
3063
- $type: "boxShadow",
3064
- $value: [
3065
- {
3066
- color: "rgba(0,0,0,0.12)",
3067
- x: "0",
3068
- y: "0",
3069
- blur: "1",
3070
- spread: "0"
3071
- },
3072
- {
3073
- color: "rgba(0,0,0,0.16)",
3074
- x: "0",
3075
- y: "4",
3076
- blur: "8",
3077
- spread: "0"
3078
- },
3079
- {
3080
- x: "0",
3081
- y: "12",
3082
- blur: "24",
3083
- spread: "0",
3084
- color: "rgba(0,0,0,0.16)"
3085
- }
3086
- ]
3087
- }
3088
- },
3089
- opacity: {
3090
- "30": {
3091
- $type: "opacity",
3092
- $value: "30%"
3093
- }
3094
- }
3095
- };
3096
- var generateGlobals = () => globals;
3097
-
3098
- // src/tokens/create/generators/primitives/size.ts
3099
- var global = {
3100
- _size: {
3101
- "0": {
3102
- $type: "dimension",
3103
- $value: "floor({_size.unit} * 0)"
3104
- },
3105
- "1": {
3106
- $type: "dimension",
3107
- $value: "floor({_size.unit} * 1)"
3108
- },
3109
- "2": {
3110
- $type: "dimension",
3111
- $value: "floor({_size.unit} * 2)"
3112
- },
3113
- "3": {
3114
- $type: "dimension",
3115
- $value: "floor({_size.unit} * 3)"
3116
- },
3117
- "4": {
3118
- $type: "dimension",
3119
- $value: "floor({_size.unit} * 4)"
3120
- },
3121
- "5": {
3122
- $type: "dimension",
3123
- $value: "floor({_size.unit} * 5)"
3124
- },
3125
- "6": {
3126
- $type: "dimension",
3127
- $value: "floor({_size.unit} * 6)"
3128
- },
3129
- "7": {
3130
- $type: "dimension",
3131
- $value: "floor({_size.unit} * 7)"
3132
- },
3133
- "8": {
3134
- $type: "dimension",
3135
- $value: "floor({_size.unit} * 8)"
3136
- },
3137
- "9": {
3138
- $type: "dimension",
3139
- $value: "floor({_size.unit} * 9)"
3140
- },
3141
- "10": {
3142
- $type: "dimension",
3143
- $value: "floor({_size.unit} * 10)"
3144
- },
3145
- "11": {
3146
- $type: "dimension",
3147
- $value: "floor({_size.unit} * 11)"
3148
- },
3149
- "12": {
3150
- $type: "dimension",
3151
- $value: "floor({_size.unit} * 12)"
3152
- },
3153
- "13": {
3154
- $type: "dimension",
3155
- $value: "floor({_size.unit} * 13)"
3156
- },
3157
- "14": {
3158
- $type: "dimension",
3159
- $value: "floor({_size.unit} * 14)"
3160
- },
3161
- "15": {
3162
- $type: "dimension",
3163
- $value: "floor({_size.unit} * 15)"
3164
- },
3165
- "18": {
3166
- $type: "dimension",
3167
- $value: "floor({_size.unit} * 18)"
3168
- },
3169
- "22": {
3170
- $type: "dimension",
3171
- $value: "floor({_size.unit} * 22)"
3172
- },
3173
- "26": {
3174
- $type: "dimension",
3175
- $value: "floor({_size.unit} * 26)"
3176
- },
3177
- "30": {
3178
- $type: "dimension",
3179
- $value: "floor({_size.unit} * 30)"
3180
- },
3181
- "mode-font-size": {
3182
- $type: "number",
3183
- $value: "{size._mode-font-size}"
3184
- },
3185
- base: {
3186
- $type: "number",
3187
- $value: "{size._base}"
3188
- },
3189
- step: {
3190
- $type: "number",
3191
- $value: "{size._step}"
3192
- },
3193
- unit: {
3194
- $type: "number",
3195
- $value: "{_size.step} / {_size.base} * {_size.mode-font-size}"
3196
- }
3197
- }
3198
- };
3199
- var sizeModes = {
3200
- large: {
3201
- size: {
3202
- "_mode-font-size": {
3203
- $type: "dimension",
3204
- $value: "21"
3205
- },
3206
- _base: {
3207
- $type: "dimension",
3208
- $value: "18"
3209
- },
3210
- _step: {
3211
- $type: "dimension",
3212
- $value: "4"
3213
- }
3214
- }
3215
- },
3216
- medium: {
3217
- size: {
3218
- "_mode-font-size": {
3219
- $type: "dimension",
3220
- $value: "18"
3221
- },
3222
- _base: {
3223
- $type: "dimension",
3224
- $value: "18"
3225
- },
3226
- _step: {
3227
- $type: "dimension",
3228
- $value: "4"
3229
- }
3230
- }
3231
- },
3232
- small: {
3233
- size: {
3234
- "_mode-font-size": {
3235
- $type: "dimension",
3236
- $value: "16"
3237
- },
3238
- _base: {
3239
- $type: "dimension",
3240
- $value: "18"
3241
- },
3242
- _step: {
3243
- $type: "dimension",
3244
- $value: "4"
3245
- }
3246
- }
3247
- }
3248
- };
3249
- var generateSize = (size2) => sizeModes[size2];
3250
- var generateSizeGlobal = () => global;
3251
-
3252
- // src/tokens/create/generators/primitives/typography.ts
3253
- var generateTypography = (themeName, { fontFamily }) => ({
3254
- [themeName]: {
3255
- "font-family": {
3256
- $type: "fontFamilies",
3257
- $value: fontFamily
3258
- },
3259
- "font-weight": {
3260
- medium: {
3261
- $type: "fontWeights",
3262
- $value: "Medium"
3263
- },
3264
- semibold: {
3265
- $type: "fontWeights",
3266
- $value: "Semi bold"
3267
- },
3268
- regular: {
3269
- $type: "fontWeights",
3270
- $value: "Regular"
3271
- }
3272
- }
3273
- }
3274
- });
3275
- var generateFontSizes = (size2) => fontSizes[size2];
3276
- var lineHeights = {
3277
- sm: {
3278
- $type: "lineHeights",
3279
- $value: "130%"
3280
- },
3281
- md: {
3282
- $type: "lineHeights",
3283
- $value: "150%"
3284
- },
3285
- lg: {
3286
- $type: "lineHeights",
3287
- $value: "170%"
3288
- }
3289
- };
3290
- var letterSpacings = {
3291
- "1": {
3292
- $type: "letterSpacing",
3293
- $value: "-1%"
3294
- },
3295
- "2": {
3296
- $type: "letterSpacing",
3297
- $value: "-0.5%"
3298
- },
3299
- "3": {
3300
- $type: "letterSpacing",
3301
- $value: "-0.25%"
3302
- },
3303
- "4": {
3304
- $type: "letterSpacing",
3305
- $value: "-0.15%"
3306
- },
3307
- "5": {
3308
- $type: "letterSpacing",
3309
- $value: "0%"
3310
- },
3311
- "6": {
3312
- $type: "letterSpacing",
3313
- $value: "0.15%"
3314
- },
3315
- "7": {
3316
- $type: "letterSpacing",
3317
- $value: "0.25%"
3318
- },
3319
- "8": {
3320
- $type: "letterSpacing",
3321
- $value: "0.5%"
3322
- },
3323
- "9": {
3324
- $type: "letterSpacing",
3325
- $value: "1.5%"
3326
- }
3327
- };
3328
- var fontSizes = {
3329
- large: {
3330
- "line-height": lineHeights,
3331
- "font-size": {
3332
- "1": {
3333
- $type: "fontSizes",
3334
- $value: "13"
3335
- },
3336
- "2": {
3337
- $type: "fontSizes",
3338
- $value: "16"
3339
- },
3340
- "3": {
3341
- $type: "fontSizes",
3342
- $value: "18"
3343
- },
3344
- "4": {
3345
- $type: "fontSizes",
3346
- $value: "21"
3347
- },
3348
- "5": {
3349
- $type: "fontSizes",
3350
- $value: "24"
3351
- },
3352
- "6": {
3353
- $type: "fontSizes",
3354
- $value: "30"
3355
- },
3356
- "7": {
3357
- $type: "fontSizes",
3358
- $value: "36"
3359
- },
3360
- "8": {
3361
- $type: "fontSizes",
3362
- $value: "48"
3363
- },
3364
- "9": {
3365
- $type: "fontSizes",
3366
- $value: "60"
3367
- },
3368
- "10": {
3369
- $type: "fontSizes",
3370
- $value: "72"
3371
- }
3372
- },
3373
- "letter-spacing": letterSpacings
3374
- },
3375
- medium: {
3376
- "line-height": lineHeights,
3377
- "font-size": {
3378
- "1": {
3379
- $type: "fontSizes",
3380
- $value: "12"
3381
- },
3382
- "2": {
3383
- $type: "fontSizes",
3384
- $value: "14"
3385
- },
3386
- "3": {
3387
- $type: "fontSizes",
3388
- $value: "16"
3389
- },
3390
- "4": {
3391
- $type: "fontSizes",
3392
- $value: "18"
3393
- },
3394
- "5": {
3395
- $type: "fontSizes",
3396
- $value: "21"
3397
- },
3398
- "6": {
3399
- $type: "fontSizes",
3400
- $value: "24"
3401
- },
3402
- "7": {
3403
- $type: "fontSizes",
3404
- $value: "30"
3405
- },
3406
- "8": {
3407
- $type: "fontSizes",
3408
- $value: "36"
3409
- },
3410
- "9": {
3411
- $type: "fontSizes",
3412
- $value: "48"
3413
- },
3414
- "10": {
3415
- $type: "fontSizes",
3416
- $value: "60"
3417
- }
3418
- },
3419
- "letter-spacing": letterSpacings
3420
- },
3421
- small: {
3422
- "line-height": lineHeights,
3423
- "font-size": {
3424
- "1": {
3425
- $type: "fontSizes",
3426
- $value: "11"
3427
- },
3428
- "2": {
3429
- $type: "fontSizes",
3430
- $value: "13"
3431
- },
3432
- "3": {
3433
- $type: "fontSizes",
3434
- $value: "14"
3435
- },
3436
- "4": {
3437
- $type: "fontSizes",
3438
- $value: "16"
3439
- },
3440
- "5": {
3441
- $type: "fontSizes",
3442
- $value: "18"
3443
- },
3444
- "6": {
3445
- $type: "fontSizes",
3446
- $value: "21"
3447
- },
3448
- "7": {
3449
- $type: "fontSizes",
3450
- $value: "24"
3451
- },
3452
- "8": {
3453
- $type: "fontSizes",
3454
- $value: "30"
3455
- },
3456
- "9": {
3457
- $type: "fontSizes",
3458
- $value: "36"
3459
- },
3460
- "10": {
3461
- $type: "fontSizes",
3462
- $value: "48"
3463
- }
3464
- },
3465
- "letter-spacing": letterSpacings
3466
- }
3467
- };
3468
-
3469
- // src/tokens/create/generators/semantic/color.ts
3470
- import * as R24 from "ramda";
3471
- var generateSemanticColors = (colors2, _themeName) => {
3472
- const mainColorNames = Object.keys(colors2.main);
3473
- const supportColorNames = Object.keys(colors2.support);
3474
- const customColors = [...mainColorNames, "neutral", ...supportColorNames];
3475
- const allColors = [...customColors, ...baseColorNames];
3476
- const semanticColorTokens = allColors.map((colorName) => [colorName, generateColorScaleTokens(colorName)]);
3477
- return {
3478
- ...baseColorTemplate,
3479
- color: {
3480
- ...Object.fromEntries(semanticColorTokens),
3481
- ...baseColorTemplate.color
3482
- }
3483
- };
3484
- };
3485
- var baseColorTemplate = {
3486
- color: {
3487
- focus: {
3488
- inner: {
3489
- $type: "color",
3490
- $value: "{color.focus.inner-color}"
3491
- },
3492
- outer: {
3493
- $type: "color",
3494
- $value: "{color.focus.outer-color}"
3495
- }
3496
- }
3497
- },
3498
- link: {
3499
- color: {
3500
- visited: {
3501
- $type: "color",
3502
- $value: "{color.link.visited}"
3503
- }
3504
- }
3505
- }
3506
- };
3507
- var generateColorScaleTokens = (colorName) => {
3508
- const colorScale = {};
3509
- for (const [colorSemantic, colorNumber] of R24.toPairs(semanticColorMap)) {
3510
- colorScale[colorSemantic] = {
3511
- $type: "color",
3512
- $value: `{color.${colorName}.${colorNumber}}`
3513
- };
3514
- }
3515
- return colorScale;
3516
- };
3517
-
3518
- // src/tokens/create/generators/semantic/color-modes.ts
3519
- var generateColorModes = (colors2, _themeName) => {
3520
- const mainColorNames = Object.keys(colors2.main);
3521
- const supportColorNames = Object.keys(colors2.support);
3522
- const modes = {
3523
- "main-color": {},
3524
- "support-color": {}
3525
- };
3526
- const categories = [
3527
- ["main-color", mainColorNames],
3528
- ["support-color", supportColorNames]
3529
- ];
3530
- for (const [colorCategory2, colorNames2] of categories) {
3531
- for (const colorName of colorNames2) {
3532
- const category = colorCategory2.replace("-color", "");
3533
- const customColorTokens = {
3534
- color: {
3535
- [category]: generateColorScaleTokens2(colorName)
3536
- }
3537
- };
3538
- modes[colorCategory2][colorName] = customColorTokens;
3539
- }
3540
- }
3541
- return modes;
3542
- };
3543
- var generateColorScaleTokens2 = (colorName) => {
3544
- const colorScale = {};
3545
- for (const colorSemantic of semanticColorNames) {
3546
- colorScale[colorSemantic] = {
3547
- $type: "color",
3548
- $value: `{color.${colorName}.${colorSemantic}}`
3549
- };
3550
- }
3551
- return colorScale;
3552
- };
3553
-
3554
- // src/tokens/create/generators/semantic/style.ts
3555
- function generateSemanticStyle() {
3556
- return {
3557
- typography: {
3558
- heading: {
3559
- "2xl": {
3560
- $type: "typography",
3561
- $value: {
3562
- fontFamily: "{font-family}",
3563
- fontWeight: "{font-weight.medium}",
3564
- lineHeight: "{line-height.sm}",
3565
- fontSize: "{font-size.10}",
3566
- letterSpacing: "{letter-spacing.1}"
3567
- }
3568
- },
3569
- xl: {
3570
- $type: "typography",
3571
- $value: {
3572
- fontFamily: "{font-family}",
3573
- fontWeight: "{font-weight.medium}",
3574
- lineHeight: "{line-height.sm}",
3575
- fontSize: "{font-size.9}",
3576
- letterSpacing: "{letter-spacing.1}"
3577
- }
3578
- },
3579
- lg: {
3580
- $type: "typography",
3581
- $value: {
3582
- fontFamily: "{font-family}",
3583
- fontWeight: "{font-weight.medium}",
3584
- lineHeight: "{line-height.sm}",
3585
- fontSize: "{font-size.8}",
3586
- letterSpacing: "{letter-spacing.2}"
3587
- }
3588
- },
3589
- md: {
3590
- $type: "typography",
3591
- $value: {
3592
- fontFamily: "{font-family}",
3593
- fontWeight: "{font-weight.medium}",
3594
- lineHeight: "{line-height.sm}",
3595
- fontSize: "{font-size.7}",
3596
- letterSpacing: "{letter-spacing.3}"
3597
- }
3598
- },
3599
- sm: {
3600
- $type: "typography",
3601
- $value: {
3602
- fontFamily: "{font-family}",
3603
- fontWeight: "{font-weight.medium}",
3604
- lineHeight: "{line-height.sm}",
3605
- fontSize: "{font-size.6}",
3606
- letterSpacing: "{letter-spacing.5}"
3607
- }
3608
- },
3609
- xs: {
3610
- $type: "typography",
3611
- $value: {
3612
- fontFamily: "{font-family}",
3613
- fontWeight: "{font-weight.medium}",
3614
- lineHeight: "{line-height.sm}",
3615
- fontSize: "{font-size.5}",
3616
- letterSpacing: "{letter-spacing.6}"
3617
- }
3618
- },
3619
- "2xs": {
3620
- $type: "typography",
3621
- $value: {
3622
- fontFamily: "{font-family}",
3623
- fontWeight: "{font-weight.medium}",
3624
- lineHeight: "{line-height.sm}",
3625
- fontSize: "{font-size.4}",
3626
- letterSpacing: "{letter-spacing.6}"
3627
- }
3628
- }
3629
- },
3630
- body: {
3631
- xl: {
3632
- $type: "typography",
3633
- $value: {
3634
- fontFamily: "{font-family}",
3635
- fontWeight: "{font-weight.regular}",
3636
- lineHeight: "{line-height.md}",
3637
- fontSize: "{font-size.6}",
3638
- letterSpacing: "{letter-spacing.8}"
3639
- }
3640
- },
3641
- lg: {
3642
- $type: "typography",
3643
- $value: {
3644
- fontFamily: "{font-family}",
3645
- fontWeight: "{font-weight.regular}",
3646
- lineHeight: "{line-height.md}",
3647
- fontSize: "{font-size.5}",
3648
- letterSpacing: "{letter-spacing.8}"
3649
- }
3650
- },
3651
- md: {
3652
- $type: "typography",
3653
- $value: {
3654
- fontFamily: "{font-family}",
3655
- fontWeight: "{font-weight.regular}",
3656
- lineHeight: "{line-height.md}",
3657
- fontSize: "{font-size.4}",
3658
- letterSpacing: "{letter-spacing.8}"
3659
- }
3660
- },
3661
- sm: {
3662
- $type: "typography",
3663
- $value: {
3664
- fontFamily: "{font-family}",
3665
- fontWeight: "{font-weight.regular}",
3666
- lineHeight: "{line-height.md}",
3667
- fontSize: "{font-size.3}",
3668
- letterSpacing: "{letter-spacing.7}"
3669
- }
3670
- },
3671
- xs: {
3672
- $type: "typography",
3673
- $value: {
3674
- fontFamily: "{font-family}",
3675
- fontWeight: "{font-weight.regular}",
3676
- lineHeight: "{line-height.md}",
3677
- fontSize: "{font-size.2}",
3678
- letterSpacing: "{letter-spacing.6}"
3679
- }
3680
- },
3681
- short: {
3682
- xl: {
3683
- $type: "typography",
3684
- $value: {
3685
- fontFamily: "{font-family}",
3686
- fontWeight: "{font-weight.regular}",
3687
- lineHeight: "{line-height.sm}",
3688
- fontSize: "{font-size.6}",
3689
- letterSpacing: "{letter-spacing.8}"
3690
- }
3691
- },
3692
- lg: {
3693
- $type: "typography",
3694
- $value: {
3695
- fontFamily: "{font-family}",
3696
- fontWeight: "{font-weight.regular}",
3697
- lineHeight: "{line-height.sm}",
3698
- fontSize: "{font-size.5}",
3699
- letterSpacing: "{letter-spacing.8}"
3700
- }
3701
- },
3702
- md: {
3703
- $type: "typography",
3704
- $value: {
3705
- fontFamily: "{font-family}",
3706
- fontWeight: "{font-weight.regular}",
3707
- lineHeight: "{line-height.sm}",
3708
- fontSize: "{font-size.4}",
3709
- letterSpacing: "{letter-spacing.8}"
3710
- }
3711
- },
3712
- sm: {
3713
- $type: "typography",
3714
- $value: {
3715
- fontFamily: "{font-family}",
3716
- fontWeight: "{font-weight.regular}",
3717
- lineHeight: "{line-height.sm}",
3718
- fontSize: "{font-size.3}",
3719
- letterSpacing: "{letter-spacing.7}"
3720
- }
3721
- },
3722
- xs: {
3723
- $type: "typography",
3724
- $value: {
3725
- fontFamily: "{font-family}",
3726
- fontWeight: "{font-weight.regular}",
3727
- lineHeight: "{line-height.sm}",
3728
- fontSize: "{font-size.2}",
3729
- letterSpacing: "{letter-spacing.6}"
3730
- }
3731
- }
3732
- },
3733
- long: {
3734
- xl: {
3735
- $type: "typography",
3736
- $value: {
3737
- fontFamily: "{font-family}",
3738
- fontWeight: "{font-weight.regular}",
3739
- lineHeight: "{line-height.lg}",
3740
- fontSize: "{font-size.6}",
3741
- letterSpacing: "{letter-spacing.8}"
3742
- }
3743
- },
3744
- lg: {
3745
- $type: "typography",
3746
- $value: {
3747
- fontFamily: "{font-family}",
3748
- fontWeight: "{font-weight.regular}",
3749
- lineHeight: "{line-height.lg}",
3750
- fontSize: "{font-size.5}",
3751
- letterSpacing: "{letter-spacing.8}"
3752
- }
3753
- },
3754
- md: {
3755
- $type: "typography",
3756
- $value: {
3757
- fontFamily: "{font-family}",
3758
- fontWeight: "{font-weight.regular}",
3759
- lineHeight: "{line-height.lg}",
3760
- fontSize: "{font-size.4}",
3761
- letterSpacing: "{letter-spacing.8}"
3762
- }
3763
- },
3764
- sm: {
3765
- $type: "typography",
3766
- $value: {
3767
- fontFamily: "{font-family}",
3768
- fontWeight: "{font-weight.regular}",
3769
- lineHeight: "{line-height.lg}",
3770
- fontSize: "{font-size.3}",
3771
- letterSpacing: "{letter-spacing.7}"
3772
- }
3773
- },
3774
- xs: {
3775
- $type: "typography",
3776
- $value: {
3777
- fontFamily: "{font-family}",
3778
- fontWeight: "{font-weight.regular}",
3779
- lineHeight: "{line-height.lg}",
3780
- fontSize: "{font-size.2}",
3781
- letterSpacing: "{letter-spacing.6}"
3782
- }
3783
- }
3784
- }
3785
- }
3786
- },
3787
- opacity: {
3788
- disabled: {
3789
- $type: "opacity",
3790
- $value: "{opacity.30}"
3791
- }
3792
- },
3793
- "border-width": {
3794
- default: {
3795
- $type: "borderWidth",
3796
- $value: "{border-width.1}"
3797
- },
3798
- focus: {
3799
- $type: "borderWidth",
3800
- $value: "{border-width.3}"
3801
- }
3802
- },
3803
- shadow: {
3804
- xs: {
3805
- $type: "boxShadow",
3806
- $value: "{shadow.100}"
3807
- },
3808
- sm: {
3809
- $type: "boxShadow",
3810
- $value: "{shadow.200}"
3811
- },
3812
- md: {
3813
- $type: "boxShadow",
3814
- $value: "{shadow.300}"
3815
- },
3816
- lg: {
3817
- $type: "boxShadow",
3818
- $value: "{shadow.400}"
3819
- },
3820
- xl: {
3821
- $type: "boxShadow",
3822
- $value: "{shadow.500}"
3823
- }
3824
- },
3825
- "border-radius": {
3826
- sm: {
3827
- $type: "dimension",
3828
- $value: "{border-radius.1}"
3829
- },
3830
- md: {
3831
- $type: "dimension",
3832
- $value: "{border-radius.2}"
3833
- },
3834
- lg: {
3835
- $type: "dimension",
3836
- $value: "{border-radius.3}"
3837
- },
3838
- xl: {
3839
- $type: "dimension",
3840
- $value: "{border-radius.4}"
3841
- },
3842
- default: {
3843
- $type: "dimension",
3844
- $value: "{border-radius.5}"
3845
- },
3846
- full: {
3847
- $type: "dimension",
3848
- $value: "{border-radius.6}"
3849
- }
3850
- },
3851
- size: {
3852
- "0": {
3853
- $type: "dimension",
3854
- $value: "{_size.0}"
3855
- },
3856
- "1": {
3857
- $type: "dimension",
3858
- $value: "{_size.1}"
3859
- },
3860
- "2": {
3861
- $type: "dimension",
3862
- $value: "{_size.2}"
3863
- },
3864
- "3": {
3865
- $type: "dimension",
3866
- $value: "{_size.3}"
3867
- },
3868
- "4": {
3869
- $type: "dimension",
3870
- $value: "{_size.4}"
3871
- },
3872
- "5": {
3873
- $type: "dimension",
3874
- $value: "{_size.5}"
3875
- },
3876
- "6": {
3877
- $type: "dimension",
3878
- $value: "{_size.6}"
3879
- },
3880
- "7": {
3881
- $type: "dimension",
3882
- $value: "{_size.7}"
3883
- },
3884
- "8": {
3885
- $type: "dimension",
3886
- $value: "{_size.8}"
3887
- },
3888
- "9": {
3889
- $type: "dimension",
3890
- $value: "{_size.9}"
3891
- },
3892
- "10": {
3893
- $type: "dimension",
3894
- $value: "{_size.10}"
3895
- },
3896
- "11": {
3897
- $type: "dimension",
3898
- $value: "{_size.11}"
3899
- },
3900
- "12": {
3901
- $type: "dimension",
3902
- $value: "{_size.12}"
3903
- },
3904
- "13": {
3905
- $type: "dimension",
3906
- $value: "{_size.13}"
3907
- },
3908
- "14": {
3909
- $type: "dimension",
3910
- $value: "{_size.14}"
3911
- },
3912
- "15": {
3913
- $type: "dimension",
3914
- $value: "{_size.15}"
3915
- },
3916
- "18": {
3917
- $type: "dimension",
3918
- $value: "{_size.18}"
3919
- },
3920
- "22": {
3921
- $type: "dimension",
3922
- $value: "{_size.22}"
3923
- },
3924
- "26": {
3925
- $type: "dimension",
3926
- $value: "{_size.26}"
3927
- },
3928
- "30": {
3929
- $type: "dimension",
3930
- $value: "{_size.30}"
3931
- }
3932
- }
3933
- };
3934
- }
3935
-
3936
- // src/tokens/create/generators/themes/theme.ts
3937
- import * as R25 from "ramda";
3938
- var generateTheme = (colors2, themeName, borderRadius) => {
3939
- const mainColorNames = Object.keys(colors2.main);
3940
- const supportColorNames = Object.keys(colors2.support);
3941
- const customColors = [...mainColorNames, "neutral", ...supportColorNames, ...baseColorNames];
3942
- const themeColorTokens = Object.fromEntries(
3943
- customColors.map((colorName) => [colorName, generateColorScaleTokens3(colorName, themeName)])
3944
- );
3945
- const { color: themeBaseFileColor, ...remainingThemeFile } = generateBase(themeName);
3946
- const themeFile = {
3947
- color: {
3948
- ...themeColorTokens,
3949
- ...themeBaseFileColor,
3950
- link: {
3951
- visited: {
3952
- $type: "color",
3953
- $value: `{${themeName}.link.visited}`
3954
- }
3955
- },
3956
- focus: {
3957
- "inner-color": {
3958
- $type: "color",
3959
- $value: `{${themeName}.focus.inner}`
3960
- },
3961
- "outer-color": {
3962
- $type: "color",
3963
- $value: `{${themeName}.focus.outer}`
3964
- }
3965
- }
3966
- },
3967
- ...remainingThemeFile
3968
- };
3969
- const baseBorderRadius = R25.lensPath(["border-radius", "base", "$value"]);
3970
- const updatedThemeFile = R25.set(baseBorderRadius, String(borderRadius), themeFile);
3971
- const token = JSON.parse(
3972
- JSON.stringify(
3973
- updatedThemeFile,
3974
- (key, value) => {
3975
- if (key === "$value") {
3976
- return value.replace("<theme>", themeName);
3977
- }
3978
- return value;
3979
- },
3980
- 2
3981
- )
3982
- );
3983
- return token;
3984
- };
3985
- var generateBase = (themeName) => ({
3986
- color: {},
3987
- "font-family": {
3988
- $type: "fontFamilies",
3989
- $value: `{${themeName}.font-family}`
3990
- },
3991
- "font-weight": {
3992
- medium: {
3993
- $type: "fontWeights",
3994
- $value: `{${themeName}.font-weight.medium}`
3995
- },
3996
- semibold: {
3997
- $type: "fontWeights",
3998
- $value: `{${themeName}.font-weight.semibold}`
3999
- },
4000
- regular: {
4001
- $type: "fontWeights",
4002
- $value: `{${themeName}.font-weight.regular}`
4003
- }
4004
- },
4005
- "border-radius": {
4006
- "1": {
4007
- $type: "dimension",
4008
- $value: "min({border-radius.base}*0.5,{border-radius.scale})"
4009
- },
4010
- "2": {
4011
- $type: "dimension",
4012
- $value: "min({border-radius.base},{border-radius.scale}*2)"
4013
- },
4014
- "3": {
4015
- $type: "dimension",
4016
- $value: "min({border-radius.base}*2,{border-radius.scale}*5)"
4017
- },
4018
- "4": {
4019
- $type: "dimension",
4020
- $value: "min({border-radius.base}*3,{border-radius.scale}*7)"
4021
- },
4022
- "5": {
4023
- $type: "dimension",
4024
- $value: "{border-radius.base}"
4025
- },
4026
- "6": {
4027
- $type: "dimension",
4028
- $value: "9999"
4029
- },
4030
- base: {
4031
- $type: "dimension",
4032
- $value: "4"
4033
- },
4034
- scale: {
4035
- $type: "dimension",
4036
- $value: "4"
4037
- }
4038
- }
4039
- });
4040
- var generateColorScaleTokens3 = (colorName, themeName) => {
4041
- const colorScale = {};
4042
- for (const [_, colorNumber] of R25.toPairs(semanticColorMap)) {
4043
- colorScale[colorNumber] = {
4044
- $type: "color",
4045
- $value: `{${themeName}.${colorName}.${colorNumber}}`
4046
- };
4047
- }
4048
- return colorScale;
4049
- };
4050
-
4051
- // src/tokens/create.ts
4052
- var cliOptions = {
4053
- outDir: "out-dir",
4054
- clean: "clean",
4055
- tailwind: "tailwind",
4056
- theme: {
4057
- colors: {
4058
- main: "main-colors",
4059
- support: "support-colors",
4060
- neutral: "neutral-color"
4061
- },
4062
- typography: {
4063
- fontFamily: "font-family"
4064
- },
4065
- borderRadius: "border-radius"
4066
- }
4067
- };
4068
- var createTokens = async (theme) => {
4069
- const { colors: colors2, typography: typography2, name, borderRadius, overrides } = theme;
4070
- const colorSchemes = ["light", "dark"];
4071
- const sizeModes2 = ["small", "medium", "large"];
4072
- const tokenSets = new Map([
4073
- ["primitives/globals", generateGlobals()],
4074
- ...sizeModes2.map((size2) => [`primitives/modes/size/${size2}`, generateSize(size2)]),
4075
- ["primitives/modes/size/global", generateSizeGlobal()],
4076
- ...sizeModes2.map((size2) => [
4077
- `primitives/modes/typography/size/${size2}`,
4078
- generateFontSizes(size2)
4079
- ]),
4080
- [`primitives/modes/typography/primary/${name}`, generateTypography(name, typography2)],
4081
- [`primitives/modes/typography/secondary/${name}`, generateTypography(name, typography2)],
4082
- ...colorSchemes.flatMap((scheme) => [
4083
- [`primitives/modes/color-scheme/${scheme}/${name}`, generateColorScheme(name, scheme, colors2, overrides)]
4084
- ]),
4085
- [`themes/${name}`, generateTheme(colors2, name, borderRadius)],
4086
- ["semantic/color", generateSemanticColors(colors2, name)],
4087
- // maps out semantic modes, ieg 'semantic/modes/main-color/accent', and 'semantic/modes/support-color/brand1'
4088
- ...Object.entries(generateColorModes(colors2, name)).flatMap(
4089
- ([mode, colors3]) => Object.entries(colors3).map(([key, colorSet]) => [`semantic/modes/${mode}/${key}`, colorSet])
4090
- ),
4091
- [`semantic/style`, generateSemanticStyle()]
4092
- ]);
4093
- return { tokenSets };
4094
- };
4095
-
4096
- // src/tokens/generate-config.ts
4097
- import path2 from "path";
4098
- import pc8 from "picocolors";
4099
- async function readJsonFile(filePath) {
4100
- try {
4101
- const content = await dsfs.readFile(filePath);
4102
- return JSON.parse(content);
4103
- } catch (err) {
4104
- throw new Error(`Failed to read token file at ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
4105
- }
4106
- }
4107
- function extractBaseColor(colorScale) {
4108
- if ("12" in colorScale && typeof colorScale["12"] === "object" && "$value" in colorScale["12"]) {
4109
- const token = colorScale["12"];
4110
- if (token.$type === "color") {
4111
- return token.$value;
4112
- }
4113
- }
4114
- return null;
4115
- }
4116
- async function discoverThemes(tokensDir) {
4117
- const lightModePath = path2.join(tokensDir, "themes");
4118
- try {
4119
- const files = await dsfs.readdir(lightModePath);
4120
- const themes = files.filter((file) => file.endsWith(".json")).map((file) => file.replace(".json", ""));
4121
- return themes;
4122
- } catch {
4123
- throw new Error(`Could not find themes. Make sure ${pc8.blue(lightModePath)} exists and contains theme JSON files.`);
4124
- }
4125
- }
4126
- async function readThemeTokens(tokensDir, themeName) {
4127
- const themePath = path2.join(tokensDir, "primitives", "modes", "color-scheme", "light", `${themeName}.json`);
4128
- return readJsonFile(themePath);
4129
- }
4130
- async function readThemeConfig(tokensDir, themeName) {
4131
- const themeConfigPath = path2.join(tokensDir, "themes", `${themeName}.json`);
4132
- try {
4133
- return await readJsonFile(themeConfigPath);
4134
- } catch {
4135
- return null;
4136
- }
4137
- }
4138
- function extractBorderRadius(themeConfig) {
4139
- if (!themeConfig || !("border-radius" in themeConfig)) {
4140
- return void 0;
4141
- }
4142
- const borderRadius = themeConfig["border-radius"];
4143
- if ("base" in borderRadius && typeof borderRadius.base === "object" && "$value" in borderRadius.base) {
4144
- const token = borderRadius.base;
4145
- return Number(token.$value);
4146
- }
4147
- return void 0;
4148
- }
4149
- function extractFontFamily(themeConfig) {
4150
- if (!themeConfig || !("font-family" in themeConfig)) {
4151
- return void 0;
4152
- }
4153
- const fontFamily = themeConfig["font-family"];
4154
- if (typeof fontFamily === "object" && "$value" in fontFamily) {
4155
- const token = fontFamily;
4156
- const value = token.$value;
4157
- if (value.startsWith("{") && value.endsWith("}")) {
4158
- return void 0;
4159
- }
4160
- return value;
4161
- }
4162
- return void 0;
4163
- }
4164
- async function readTypographyConfig(tokensDir, themeName) {
4165
- const typographyConfigPath = path2.join(
4166
- tokensDir,
4167
- "primitives",
4168
- "modes",
4169
- "typography",
4170
- "primary",
4171
- `${themeName}.json`
4172
- );
4173
- try {
4174
- return await readJsonFile(typographyConfigPath);
4175
- } catch {
4176
- return null;
4177
- }
4178
- }
4179
- function extractFontFamilyFromPrimitives(typographyConfig, themeName) {
4180
- if (!typographyConfig) {
4181
- return void 0;
4182
- }
4183
- const themeTypography = typographyConfig[themeName];
4184
- if (!themeTypography || !("font-family" in themeTypography)) {
4185
- return void 0;
4186
- }
4187
- const fontFamily = themeTypography["font-family"];
4188
- if (typeof fontFamily === "object" && "$value" in fontFamily) {
4189
- const token = fontFamily;
4190
- return token.$value;
4191
- }
4192
- return void 0;
4193
- }
4194
- function categorizeColors(themeTokens, themeName) {
4195
- const main = {};
4196
- const support = {};
4197
- let neutral = null;
4198
- const builtInColors = ["neutral", "info", "success", "warning", "danger"];
4199
- const specialKeys = ["link"];
4200
- const themeColors = themeTokens[themeName];
4201
- if (!themeColors) {
4202
- return { main, support, neutral };
4203
- }
4204
- for (const [colorName, colorValue] of Object.entries(themeColors)) {
4205
- if (specialKeys.includes(colorName)) {
4206
- continue;
4207
- }
4208
- if (typeof colorValue === "object" && !("$value" in colorValue)) {
4209
- const baseColor = extractBaseColor(colorValue);
4210
- if (baseColor) {
4211
- if (colorName === "neutral") {
4212
- neutral = baseColor;
4213
- } else if (builtInColors.includes(colorName)) {
4214
- } else if (colorName === "accent") {
4215
- main[colorName] = baseColor;
4216
- } else {
4217
- support[colorName] = baseColor;
4218
- }
4219
- }
4220
- }
4221
- }
4222
- return { main, support, neutral };
4223
- }
4224
- async function generateConfigFromTokens(options) {
4225
- const { tokensDir } = options;
4226
- console.log(`
4227
- Reading tokens from ${pc8.blue(tokensDir)}`);
4228
- const themes = await discoverThemes(tokensDir);
4229
- if (themes.length === 0) {
4230
- throw new Error(`
4231
- No themes found in ${pc8.blue(tokensDir)}`);
4232
- }
4233
- console.log(`
4234
- Found ${pc8.green(String(themes.length))} theme(s): ${themes.map((t) => pc8.cyan(t)).join(", ")}`);
4235
- const config = {
4236
- outDir: tokensDir,
4237
- themes: {}
4238
- };
4239
- for (const themeName of themes) {
4240
- console.log(`
4241
- Processing theme ${pc8.cyan(themeName)}...`);
4242
- const themeTokens = await readThemeTokens(tokensDir, themeName);
4243
- const themeConfig = await readThemeConfig(tokensDir, themeName);
4244
- const typographyConfig = await readTypographyConfig(tokensDir, themeName);
4245
- const { main, support, neutral } = categorizeColors(themeTokens, themeName);
4246
- if (Object.keys(main).length === 0) {
4247
- console.warn(pc8.yellow(`
4248
- Warning: No main colors found for theme ${themeName}`));
4249
- }
4250
- if (!neutral) {
4251
- console.warn(pc8.yellow(`
4252
- Warning: No neutral color found for theme ${themeName}`));
4253
- continue;
4254
- }
4255
- const borderRadius = extractBorderRadius(themeConfig);
4256
- const fontFamily = extractFontFamily(themeConfig) ?? extractFontFamilyFromPrimitives(typographyConfig, themeName);
4257
- config.themes[themeName] = {
4258
- colors: {
4259
- main,
4260
- support,
4261
- neutral
4262
- },
4263
- borderRadius,
4264
- typography: fontFamily ? { fontFamily } : void 0
4265
- };
4266
- console.log(
4267
- `
4268
- \u2705 Main colors: ${Object.keys(main).map((c) => pc8.cyan(c)).join(", ") || pc8.dim("none")}`
4269
- );
4270
- console.log(
4271
- `
4272
- \u2705 Support colors: ${Object.keys(support).map((c) => pc8.cyan(c)).join(", ") || pc8.dim("none")}`
4273
- );
4274
- console.log(`
4275
- \u2705 Neutral: ${pc8.cyan(neutral)}`);
4276
- if (borderRadius !== void 0) {
4277
- console.log(`
4278
- \u2705 Border radius: ${pc8.cyan(String(borderRadius))}`);
4279
- }
4280
- if (fontFamily) {
4281
- console.log(`
4282
- \u2705 Font family: ${pc8.cyan(fontFamily)}`);
4283
- }
4284
- }
4285
- return config;
4286
- }
4287
-
4288
- // bin/config.ts
4289
- import pc10 from "picocolors";
4290
- import * as R27 from "ramda";
4291
-
4292
- // src/config.ts
4293
- import pc9 from "picocolors";
4294
- import * as R26 from "ramda";
4295
- import { z } from "zod";
4296
- import { fromError } from "zod-validation-error";
4297
- function mapPathToOptionName(path5) {
4298
- const normalisedPath = path5[0] === "themes" ? ["theme", ...R26.drop(2, path5)] : path5;
4299
- const option = R26.path(normalisedPath, cliOptions);
4300
- if (typeof option !== "string") {
4301
- return;
4302
- }
4303
- return option;
4304
- }
4305
- function makeFriendlyError(err) {
4306
- try {
4307
- return fromError(err, {
4308
- messageBuilder: (issues) => issues.map((issue) => {
4309
- const issuePath = issue.path.join(".");
4310
- const optionName = mapPathToOptionName(issue.path);
4311
- const errorCode = `(error code: ${issue.code})`;
4312
- const optionMessage = optionName ? ` or CLI option --${optionName}` : "";
4313
- return ` - Error in JSON value ${pc9.red(issuePath)}${optionMessage}:
4314
- ${issue.message} ${pc9.dim(errorCode)}`;
4315
- }).join("\n")
4316
- });
4317
- } catch (_err2) {
4318
- console.error(pc9.red(err instanceof Error ? err.message : "Unknown error occurred while parsing config file"));
4319
- console.error(err instanceof Error ? err.stack : "No stack trace available");
4320
- }
4321
- }
4322
- function validateConfig(schema, unvalidatedConfig, configFilePath) {
4323
- try {
4324
- return schema.parse(unvalidatedConfig);
4325
- } catch (err) {
4326
- console.error(pc9.redBright(`Invalid config file at ${pc9.red(configFilePath)}`));
4327
- const validationError = makeFriendlyError(err);
4328
- console.error(validationError?.toString());
4329
- process.exit(1);
4330
- }
4331
- }
4332
- function parseConfig(configFile, configFilePath) {
4333
- if (!configFile) {
4334
- return {};
4335
- }
4336
- try {
4337
- return JSON.parse(configFile);
4338
- } catch (err) {
4339
- console.error(pc9.redBright(`Failed parsing config file at ${pc9.red(configFilePath)}`));
4340
- const validationError = makeFriendlyError(err);
4341
- console.error(validationError?.toString());
4342
- process.exit(1);
4343
- }
4344
- }
4345
- var hexPatterns = [
4346
- // Hex colors: #000, #0000, #000000, #00000000
4347
- `#[0-9a-fA-F]{3}`,
4348
- `#[0-9a-fA-F]{4}`,
4349
- `#[0-9a-fA-F]{6}`,
4350
- `#[0-9a-fA-F]{8}`
4351
- ];
4352
- var reservedColorsPattern = `^(?!(?:${RESERVED_COLORS.join("|")})$)`;
4353
- var colorRegex = new RegExp(`^${hexPatterns.join("|")}$`);
4354
- var colorSchema = z.string().regex(colorRegex).transform(convertToHex).describe(
4355
- `A hex color, which is used for creating a color scale. Invalid color names: ${RESERVED_COLORS.join(", ")}`
4356
- );
4357
- var colorCategorySchema = z.record(
4358
- z.string().regex(new RegExp(reservedColorsPattern, "i"), {
4359
- error: `Color names cannot include reserved names: ${RESERVED_COLORS.join(", ")}`
4360
- }),
4361
- colorSchema,
4362
- {
4363
- error: "Color definitions must be hex color values"
4364
- }
4365
- ).refine((colors2) => !Object.keys(colors2).some((key) => RESERVED_COLORS.includes(key.toLowerCase())), {
4366
- error: `Color names cannot include reserved names: ${RESERVED_COLORS.join(", ")}`
4367
- }).describe("An object with one or more color definitions. The property name is used as the color name.");
4368
- var colorModeOverrideSchema = z.object({
4369
- light: colorSchema.optional().describe("A hex color that overrides light mode"),
4370
- dark: colorSchema.optional().describe("A hex color that overrides dark mode")
4371
- }).describe('Override values for semantic color tokens like "background-subtle", "border-default", etc.');
4372
- var colorWeightOverrideSchema = z.partialRecord(z.enum([...colorNames]), colorModeOverrideSchema).describe('The name of the color to add overrides for, e.g. "accent"');
4373
- var semanticColorOverrideSchema = z.record(z.string(), colorWeightOverrideSchema).describe("An object with color names as keys");
4374
- var severityColorOverrideSchema = z.partialRecord(z.enum(baseColorNames), colorSchema.describe("A hex color, which is used for creating a color scale")).optional().describe("An object with severity color names as keys");
4375
- var linkVisitedOverrideSchema = z.object({
4376
- light: colorSchema.optional().describe("A hex color that overrides light mode"),
4377
- dark: colorSchema.optional().describe("A hex color that overrides dark mode")
4378
- }).describe('Overrides for the "link-visited" color');
4379
- var focusOverrideSchema = z.object({
4380
- inner: z.object({
4381
- light: colorSchema.optional().describe("A hex color that overrides light mode"),
4382
- dark: colorSchema.optional().describe("A hex color that overrides dark mode")
4383
- }).optional().describe('Overrides for the "focus-inner" color'),
4384
- outer: z.object({
4385
- light: colorSchema.optional().describe("A hex color that overrides light mode"),
4386
- dark: colorSchema.optional().describe("A hex color that overrides dark mode")
4387
- }).optional().describe('Overrides for the "focus-outer" color')
4388
- }).describe("Overrides for the focus colors");
4389
- var overridesSchema = z.object({
4390
- colors: semanticColorOverrideSchema.optional(),
4391
- severity: severityColorOverrideSchema.optional(),
4392
- linkVisited: linkVisitedOverrideSchema.optional(),
4393
- focus: focusOverrideSchema.optional()
4394
- }).describe("Overrides for generated design tokens. Currently only supports colors defined in your theme").optional();
4395
- var themeSchema = z.object({
4396
- colors: z.object({
4397
- main: colorCategorySchema,
4398
- support: colorCategorySchema.optional().default({}),
4399
- neutral: colorSchema.describe("A hex color, which is used for creating a color scale.")
4400
- }).meta({ description: "Defines the colors for this theme" }),
4401
- typography: z.object({
4402
- fontFamily: z.string().meta({ description: "Sets the font-family for this theme" })
4403
- }).describe("Defines the typography for a given theme").optional(),
4404
- borderRadius: z.number().meta({ description: "Defines the border-radius for this theme" }).optional(),
4405
- overrides: overridesSchema
4406
- }).meta({ description: "An object defining a theme. The property name holding the object becomes the theme name." });
4407
- var commonConfig = z.object({
4408
- clean: z.boolean().meta({ description: "Delete the output directory before building or creating tokens" }).optional()
4409
- });
4410
- var _configFileCreateSchema = z.object({
4411
- outDir: z.string().meta({ description: "Path to the output directory for the created design tokens" }),
4412
- themes: z.record(z.string(), themeSchema).meta({
4413
- description: "An object with one or more themes. Each property defines a theme, and the property name is used as the theme name."
4414
- })
4415
- }).required();
4416
- var configFileCreateSchema = _configFileCreateSchema.extend(commonConfig.shape);
4417
-
4418
- // bin/options.ts
4419
- var getOptionIfMatchingSource = (...sources) => (command, option) => {
4420
- const source = command.getOptionValueSource(option);
4421
- if (sources.includes(source)) {
4422
- return command.getOptionValue(option);
4423
- }
4424
- };
4425
- var getSuppliedCliOption = getOptionIfMatchingSource("cli");
4426
- var getDefaultCliOption = getOptionIfMatchingSource("default");
4427
- var getCliOption = getOptionIfMatchingSource("cli", "default");
4428
-
4429
- // bin/config.ts
4430
- async function readConfigFile(configFilePath, allowFileNotFound = true) {
4431
- let configFile;
4432
- try {
4433
- configFile = await dsfs.readFile(configFilePath, allowFileNotFound);
4434
- } catch (err) {
4435
- if (allowFileNotFound) {
4436
- return "";
4437
- }
4438
- console.error(pc10.redBright(`Could not read config file at ${pc10.blue(configFilePath)}`));
4439
- throw err;
4440
- }
4441
- if (configFile) {
4442
- console.log(`Found config file: ${pc10.green(configFilePath)}`);
4443
- }
4444
- return configFile;
4445
- }
4446
- async function parseCreateConfig(configFile, options) {
4447
- const { cmd, theme = "theme", configFilePath } = options;
4448
- const configParsed = parseConfig(configFile, configFilePath);
4449
- const themeColors = Object.values(configParsed?.themes ?? {}).map(
4450
- (x) => /* @__PURE__ */ new Set([...R27.keys(x.colors.main), ...R27.keys(x.colors.support)])
4451
- );
4452
- if (!R27.all(R27.equals(R27.__, themeColors[0]), themeColors)) {
4453
- console.error(pc10.redBright(`In config, all themes must have the same custom color names, but we found:`));
4454
- const themeNames = R27.keys(configParsed.themes ?? {});
4455
- themeColors.forEach((colors2, index) => {
4456
- const colorNames2 = Array.from(colors2);
4457
- console.log(` - ${themeNames[index]}: ${colorNames2.join(", ")}`);
4458
- });
4459
- console.log();
4460
- process.exit(1);
4461
- }
4462
- const noUndefined = R27.reject(R27.isNil);
4463
- const getThemeOptions = (optionGetter) => noUndefined({
4464
- colors: noUndefined({
4465
- main: optionGetter(cmd, "mainColors"),
4466
- support: optionGetter(cmd, "supportColors"),
4467
- neutral: optionGetter(cmd, "neutralColor")
4468
- }),
4469
- typography: noUndefined({
4470
- fontFamily: optionGetter(cmd, "fontFamily")
4471
- }),
4472
- borderRadius: optionGetter(cmd, "borderRadius"),
4473
- defaultColor: optionGetter(cmd, "defaultColor")
4474
- });
4475
- const unvalidatedConfig = noUndefined({
4476
- outDir: configParsed?.outDir ?? getCliOption(cmd, "outDir"),
4477
- clean: configParsed?.clean ?? getCliOption(cmd, "clean"),
4478
- themes: configParsed?.themes ? R27.map((jsonThemeValues) => {
4479
- const defaultThemeValues = getThemeOptions(getDefaultCliOption);
4480
- const cliThemeValues = getThemeOptions(getSuppliedCliOption);
4481
- const mergedConfigs = R27.mergeDeepRight(defaultThemeValues, R27.mergeDeepRight(jsonThemeValues, cliThemeValues));
4482
- return mergedConfigs;
4483
- }, configParsed.themes) : (
4484
- // If there are no themes specified in the JSON config, we use both explicit
4485
- // and default theme options from the CLI.
4486
- {
4487
- [theme]: getThemeOptions(getCliOption)
4488
- }
4489
- )
4490
- });
4491
- return validateConfig(configFileCreateSchema, unvalidatedConfig, configFilePath);
4492
- }
4493
-
4494
- // bin/designsystemet.ts
4495
- var figletAscii = `
12
+ import * as R from "ramda";
13
+ import path from "node:path";
14
+ import { Argument, createCommand, program } from "@commander-js/extra-typings";
15
+ //#region bin/designsystemet.ts
16
+ const figletAscii = `
4496
17
  _____ _ _ _
4497
18
  | __ \\ (_) | | | |
4498
19
  | | | | ___ ___ _ __ _ _ __ ___ _ _ ___| |_ ___ _ __ ___ ___| |_
@@ -4503,146 +24,133 @@ var figletAscii = `
4503
24
  |___/ |___/
4504
25
  `;
4505
26
  program.name("designsystemet").description("CLI for working with Designsystemet").showHelpAfterError();
4506
- var DEFAULT_TOKENS_CREATE_DIR = "./design-tokens";
4507
- var DEFAULT_TOKENS_BUILD_DIR = "./design-tokens-build";
4508
- var DEFAULT_FONT = "Inter";
4509
- var DEFAULT_THEME_NAME = "theme";
4510
- var DEFAULT_CONFIG_FILEPATH = "designsystemet.config.json";
27
+ const DEFAULT_TOKENS_CREATE_DIR = "./design-tokens";
28
+ const DEFAULT_TOKENS_BUILD_DIR = "./design-tokens-build";
29
+ const DEFAULT_FONT = "Inter";
30
+ const DEFAULT_THEME_NAME = "theme";
31
+ const DEFAULT_CONFIG_FILEPATH = "designsystemet.config.json";
4511
32
  function makeTokenCommands() {
4512
- const tokenCmd = createCommand("tokens");
4513
- tokenCmd.command("build").description("Build Designsystemet tokens").option("-t, --tokens <string>", `Path to ${pc11.blue("design-tokens")}`, DEFAULT_TOKENS_CREATE_DIR).option(
4514
- "-o, --out-dir <string>",
4515
- `Output directory for built ${pc11.blue("design-tokens")}`,
4516
- DEFAULT_TOKENS_BUILD_DIR
4517
- ).option(`--${cliOptions.clean} [boolean]`, "Clean output directory before building tokens", parseBoolean, false).option("--dry [boolean]", `Dry run for built ${pc11.blue("design-tokens")}`, parseBoolean, false).option("--verbose", "Enable verbose output", false).option("--config <string>", `Path to config file (default: "${DEFAULT_CONFIG_FILEPATH}")`).option("--experimental-tailwind", "Generate Tailwind CSS classes for tokens", false).action(async (opts) => {
4518
- console.log(figletAscii);
4519
- const { verbose, clean, dry, experimentalTailwind, tokens } = opts;
4520
- dsfs.init({ dry, outdir: opts.outDir, verbose });
4521
- const outDir = dsfs.outDir;
4522
- if (clean) {
4523
- await dsfs.cleanDir(outDir);
4524
- }
4525
- const files = await buildTokens({
4526
- tokensDir: tokens,
4527
- verbose,
4528
- tailwind: experimentalTailwind
4529
- });
4530
- console.log(`
4531
- \u{1F4BE} Writing build to ${pc11.green(outDir)}`);
4532
- await dsfs.writeFiles(files, outDir, true);
4533
- console.log(`
4534
- \u2705 Finished building tokens in ${pc11.green(outDir)}`);
4535
- return Promise.resolve();
4536
- });
4537
- tokenCmd.command("create").description("Create Designsystemet tokens").option(`-m, --${cliOptions.theme.colors.main} <name:hex...>`, `Main colors`, parseColorValues).option(`-s, --${cliOptions.theme.colors.support} <name:hex...>`, `Support colors`, parseColorValues).option(`-n, --${cliOptions.theme.colors.neutral} <hex>`, `Neutral hex color`, convertToHex).option(
4538
- `-o, --${cliOptions.outDir} <string>`,
4539
- `Output directory for created ${pc11.blue("design-tokens")}`,
4540
- DEFAULT_TOKENS_CREATE_DIR
4541
- ).option(`--${cliOptions.clean} [boolean]`, "Clean output directory before creating tokens", parseBoolean, false).option("--dry [boolean]", `Dry run for created ${pc11.blue("design-tokens")}`, parseBoolean, false).option(`-f, --${cliOptions.theme.typography.fontFamily} <string>`, `Font family (experimental)`, DEFAULT_FONT).option(
4542
- `-b, --${cliOptions.theme.borderRadius} <number>`,
4543
- `Unitless base border-radius in px`,
4544
- (radiusAsString) => Number(radiusAsString),
4545
- 4
4546
- ).option("--theme <string>", "Theme name (ignored when using JSON config file)", DEFAULT_THEME_NAME).option("--config <string>", `Path to config file (default: "${DEFAULT_CONFIG_FILEPATH}")`).action(async (opts, cmd) => {
4547
- console.log(figletAscii);
4548
- if (opts.dry) {
4549
- console.log(`Performing dry run, no files will be written`);
4550
- }
4551
- const themeName = opts.theme;
4552
- const { configFile, configFilePath } = await getConfigFile(opts.config);
4553
- const config = await parseCreateConfig(configFile, {
4554
- theme: themeName,
4555
- cmd,
4556
- configFilePath
4557
- });
4558
- const themeNames = Object.keys(config.themes);
4559
- if (themeNames.length > 0) {
4560
- console.log(`Using themes from config file: ${pc11.blue(themeNames.join(", "))}`);
4561
- }
4562
- dsfs.init({ dry: opts.dry, outdir: config.outDir });
4563
- const outDir = dsfs.outDir;
4564
- if (config.clean) {
4565
- await dsfs.cleanDir(outDir);
4566
- }
4567
- let files = [];
4568
- if (config.themes) {
4569
- for (const [name, themeWithoutName] of Object.entries(config.themes)) {
4570
- const theme = { name, ...themeWithoutName };
4571
- const { tokenSets } = await createTokens(theme);
4572
- files = files.concat(await createTokenFiles({ outDir, theme, tokenSets, themeNames }));
4573
- }
4574
- }
4575
- await dsfs.writeFiles(files, outDir);
4576
- console.log(`
4577
- \u2705 Finished creating tokens in ${pc11.green(outDir)} for themes: ${pc11.blue(themeNames.join(", "))}`);
4578
- return Promise.resolve();
4579
- });
4580
- return tokenCmd;
33
+ const tokenCmd = createCommand("tokens");
34
+ tokenCmd.command("build").description("Build Designsystemet tokens").option("-t, --tokens <string>", `Path to ${pc.blue("design-tokens")}`, DEFAULT_TOKENS_CREATE_DIR).option("-o, --out-dir <string>", `Output directory for built ${pc.blue("design-tokens")}`, DEFAULT_TOKENS_BUILD_DIR).option(`--${cliOptions.clean} [boolean]`, "Clean output directory before building tokens", parseBoolean, false).option("--dry [boolean]", `Dry run for built ${pc.blue("design-tokens")}`, parseBoolean, false).option("--verbose", "Enable verbose output", false).option("--config <string>", `Path to config file (default: "${DEFAULT_CONFIG_FILEPATH}")`).option("--experimental-tailwind", "Generate Tailwind CSS classes for tokens", false).action(async (opts) => {
35
+ console.log(figletAscii);
36
+ const { verbose, clean, dry, experimentalTailwind, tokens } = opts;
37
+ dsfs.init({
38
+ dry,
39
+ outdir: opts.outDir,
40
+ verbose
41
+ });
42
+ const outDir = dsfs.outDir;
43
+ if (clean) await dsfs.cleanDir(outDir);
44
+ const files = await buildTokens({
45
+ tokensDir: tokens,
46
+ verbose,
47
+ tailwind: experimentalTailwind
48
+ });
49
+ console.log(`\n💾 Writing build to ${pc.green(outDir)}`);
50
+ await dsfs.writeFiles(files, outDir, true);
51
+ console.log(`\n✅ Finished building tokens in ${pc.green(outDir)}`);
52
+ return Promise.resolve();
53
+ });
54
+ tokenCmd.command("create").description("Create Designsystemet tokens").option(`-m, --${cliOptions.theme.colors.main} <name:hex...>`, `Main colors`, parseColorValues).option(`-s, --${cliOptions.theme.colors.support} <name:hex...>`, `Support colors`, parseColorValues).option(`-n, --${cliOptions.theme.colors.neutral} <hex>`, `Neutral hex color`, convertToHex).option(`-o, --${cliOptions.outDir} <string>`, `Output directory for created ${pc.blue("design-tokens")}`, DEFAULT_TOKENS_CREATE_DIR).option(`--${cliOptions.clean} [boolean]`, "Clean output directory before creating tokens", parseBoolean, false).option("--dry [boolean]", `Dry run for created ${pc.blue("design-tokens")}`, parseBoolean, false).option(`-f, --${cliOptions.theme.typography.fontFamily} <string>`, `Font family (experimental)`, DEFAULT_FONT).option(`-b, --${cliOptions.theme.borderRadius} <number>`, `Unitless base border-radius in px`, (radiusAsString) => Number(radiusAsString), 4).option("--theme <string>", "Theme name (ignored when using JSON config file)", DEFAULT_THEME_NAME).option("--config <string>", `Path to config file (default: "${DEFAULT_CONFIG_FILEPATH}")`).action(async (opts, cmd) => {
55
+ console.log(figletAscii);
56
+ if (opts.dry) console.log(`Performing dry run, no files will be written`);
57
+ const themeName = opts.theme;
58
+ const { configFile, configFilePath } = await getConfigFile(opts.config);
59
+ const config = await parseCreateConfig(configFile, {
60
+ theme: themeName,
61
+ cmd,
62
+ configFilePath
63
+ });
64
+ const themeNames = Object.keys(config.themes);
65
+ if (themeNames.length > 0) console.log(`Using themes from config file: ${pc.blue(themeNames.join(", "))}`);
66
+ dsfs.init({
67
+ dry: opts.dry,
68
+ outdir: config.outDir
69
+ });
70
+ const outDir = dsfs.outDir;
71
+ if (config.clean) await dsfs.cleanDir(outDir);
72
+ let files = [];
73
+ if (config.themes) for (const [name, themeWithoutName] of Object.entries(config.themes)) {
74
+ const theme = {
75
+ name,
76
+ ...themeWithoutName
77
+ };
78
+ const { tokenSets } = await createTokens(theme);
79
+ files = files.concat(await createTokenFiles({
80
+ outDir,
81
+ theme,
82
+ tokenSets,
83
+ themeNames
84
+ }));
85
+ }
86
+ await dsfs.writeFiles(files, outDir);
87
+ console.log(`\n✅ Finished creating tokens in ${pc.green(outDir)} for themes: ${pc.blue(themeNames.join(", "))}`);
88
+ return Promise.resolve();
89
+ });
90
+ return tokenCmd;
4581
91
  }
4582
92
  program.addCommand(makeTokenCommands());
4583
93
  program.command("generate-config-from-tokens").description("Generate a config file from existing design tokens. Will not include overrides.").option("-d, --dir <string>", "Path to design tokens directory", DEFAULT_TOKENS_CREATE_DIR).option("-o, --out <string>", "Output path for config file", DEFAULT_CONFIG_FILEPATH).option("--dry [boolean]", "Dry run - show config without writing file", parseBoolean, false).action(async (opts) => {
4584
- console.log(figletAscii);
4585
- const { dry } = opts;
4586
- const tokensDir = path4.resolve(opts.dir);
4587
- const configFilePath = path4.resolve(opts.out);
4588
- dsfs.init({ dry, outdir: path4.dirname(configFilePath) });
4589
- try {
4590
- const config = await generateConfigFromTokens({
4591
- tokensDir,
4592
- outFile: configFilePath
4593
- });
4594
- if (dry) {
4595
- console.log();
4596
- console.log("Generated config (dry run):");
4597
- console.log(JSON.stringify(config, null, 2));
4598
- }
4599
- if (configFilePath) {
4600
- const configJson = JSON.stringify(config, null, 2);
4601
- await dsfs.writeFile(configFilePath, configJson);
4602
- console.log();
4603
- console.log(`
4604
- \u2705 Config file written to ${pc11.blue(configFilePath)}`);
4605
- }
4606
- } catch (error) {
4607
- console.error(pc11.redBright("Error generating config:"));
4608
- console.error(error instanceof Error ? error.message : String(error));
4609
- process.exit(1);
4610
- }
94
+ console.log(figletAscii);
95
+ const { dry } = opts;
96
+ const tokensDir = path.resolve(opts.dir);
97
+ const configFilePath = path.resolve(opts.out);
98
+ dsfs.init({
99
+ dry,
100
+ outdir: path.dirname(configFilePath)
101
+ });
102
+ try {
103
+ const config = await generateConfigFromTokens({
104
+ tokensDir,
105
+ outFile: configFilePath
106
+ });
107
+ if (dry) {
108
+ console.log();
109
+ console.log("Generated config (dry run):");
110
+ console.log(JSON.stringify(config, null, 2));
111
+ }
112
+ if (configFilePath) {
113
+ const configJson = JSON.stringify(config, null, 2);
114
+ await dsfs.writeFile(configFilePath, configJson);
115
+ console.log();
116
+ console.log(`\n✅ Config file written to ${pc.blue(configFilePath)}`);
117
+ }
118
+ } catch (error) {
119
+ console.error(pc.redBright("Error generating config:"));
120
+ console.error(error instanceof Error ? error.message : String(error));
121
+ process.exit(1);
122
+ }
4611
123
  });
4612
124
  program.command("migrate").description("run a Designsystemet migration").addArgument(new Argument("[migration]", "Available migrations").choices(Object.keys(migrations_default))).option("-l --list", "List available migrations").option("-g --glob <glob>", "Glob for files upon which to apply the migration", "./**/*.(tsx|css)").action((migrationKey, opts) => {
4613
- console.log(figletAscii);
4614
- const { glob: glob2, list } = opts;
4615
- if (list) {
4616
- for (const key of Object.keys(migrations_default)) {
4617
- console.log(key);
4618
- }
4619
- } else if (migrationKey) {
4620
- const migration = migrations_default[migrationKey];
4621
- if (!migration) {
4622
- console.error("Migration not found!");
4623
- throw "Aborting";
4624
- }
4625
- console.log(`Applying migration ${pc11.blue(migrationKey)} with glob: ${pc11.green(glob2)}`);
4626
- migration?.(glob2).then(() => console.log(`Migration ${pc11.blue(migrationKey)} finished`)).catch((error) => console.log(error));
4627
- } else {
4628
- console.log("Migrate: please specify a migration name or --list");
4629
- }
125
+ console.log(figletAscii);
126
+ const { glob, list } = opts;
127
+ if (list) for (const key of Object.keys(migrations_default)) console.log(key);
128
+ else if (migrationKey) {
129
+ const migration = migrations_default[migrationKey];
130
+ if (!migration) {
131
+ console.error("Migration not found!");
132
+ throw "Aborting";
133
+ }
134
+ console.log(`Applying migration ${pc.blue(migrationKey)} with glob: ${pc.green(glob)}`);
135
+ migration?.(glob).then(() => console.log(`Migration ${pc.blue(migrationKey)} finished`)).catch((error) => console.log(error));
136
+ } else console.log("Migrate: please specify a migration name or --list");
4630
137
  });
4631
138
  await program.parseAsync(process.argv);
4632
139
  function parseColorValues(value, previous = {}) {
4633
- const [name, hex] = value.split(":");
4634
- previous[name] = convertToHex(hex);
4635
- return previous;
140
+ const [name, hex] = value.split(":");
141
+ previous[name] = convertToHex(hex);
142
+ return previous;
4636
143
  }
4637
144
  function parseBoolean(value) {
4638
- return value === "true" || value === true;
145
+ return value === "true" || value === true;
4639
146
  }
4640
147
  async function getConfigFile(userConfigFilePath) {
4641
- const allowFileNotFound = R28.isNil(userConfigFilePath) || userConfigFilePath === DEFAULT_CONFIG_FILEPATH;
4642
- const configFilePath = userConfigFilePath ?? DEFAULT_CONFIG_FILEPATH;
4643
- const configFile = await readConfigFile(configFilePath, allowFileNotFound);
4644
- return { configFile, configFilePath };
4645
- }
4646
- export {
4647
- figletAscii
4648
- };
148
+ const allowFileNotFound = R.isNil(userConfigFilePath) || userConfigFilePath === DEFAULT_CONFIG_FILEPATH;
149
+ const configFilePath = userConfigFilePath ?? DEFAULT_CONFIG_FILEPATH;
150
+ return {
151
+ configFile: await readConfigFile(configFilePath, allowFileNotFound),
152
+ configFilePath
153
+ };
154
+ }
155
+ //#endregion
156
+ export { figletAscii };