@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,1818 +1,41 @@
1
- // src/tokens/build.ts
2
- import pc6 from "picocolors";
3
- import * as R17 from "ramda";
4
-
5
- // src/utils/filesystem.ts
6
- import fs from "fs/promises";
7
- import path from "path";
1
+ import { dsfs } from "../utils/filesystem.js";
2
+ import { processThemeObject } from "./process/utils/getMultidimensionalThemes.js";
3
+ import { processPlatform } from "./process/platform.js";
4
+ import { createTypeDeclarationFiles } from "./process/output/declarations.js";
5
+ import { createTailwindCSSFiles } from "./process/output/tailwind.js";
6
+ import { createThemeCSSFiles, defaultFileHeader } from "./process/output/theme.js";
8
7
  import pc from "picocolors";
9
- var FileSystem = class {
10
- isInitialized = false;
11
- dry = false;
12
- verbose = false;
13
- /** Default working directory is where the process was started */
14
- workingDir = process.cwd();
15
- outDir = this.workingDir;
16
- /** Initialize the file system */
17
- init({ dry, outdir, verbose }) {
18
- if (this.isInitialized) {
19
- console.warn(pc.yellow("FileSystem is already initialized. Ignoring subsequent init call."));
20
- return;
21
- }
22
- if (dry) {
23
- console.log(pc.blue("Initializing FileSystem in dry-run mode. No files will be written."));
24
- }
25
- this.dry = dry ?? false;
26
- this.verbose = verbose ?? false;
27
- this.outDir = outdir ? path.isAbsolute(outdir) ? outdir : path.join(this.workingDir, outdir) : this.workingDir;
28
- if (this.verbose) {
29
- console.log(
30
- `FileSystem initialized with workingDir: ${pc.green(this.workingDir)}, outDir: ${pc.green(this.outDir)}`
31
- );
32
- }
33
- this.isInitialized = true;
34
- }
35
- /**
36
- * Creates a directory if it does not already exist.
37
- *
38
- * @param dir - The path of the directory to create.
39
- *
40
- * @returns A promise that resolves when the operation is complete.
41
- * If the directory already exists or `dry` is `true`, the promise resolves immediately.
42
- */
43
- mkdir = async (dir) => {
44
- if (this.dry) {
45
- console.log(`${pc.blue("mkdir")} ${dir}`);
46
- return Promise.resolve();
47
- }
48
- const exists = await fs.access(dir, fs.constants.F_OK).then(() => true).catch(() => false);
49
- if (exists) {
50
- return Promise.resolve();
51
- }
52
- return fs.mkdir(dir, { recursive: true });
53
- };
54
- writeFile = async (path2, data) => {
55
- if (this.dry) {
56
- console.log(`${pc.blue("writeFile")} ${path2}`);
57
- return Promise.resolve();
58
- }
59
- return fs.writeFile(path2, data, { encoding: "utf-8" }).catch((error) => {
60
- console.error(pc.red(`Error writing file: ${path2}`));
61
- console.error(pc.red(error));
62
- throw error;
63
- });
64
- };
65
- cp = async (src, dest, filter) => {
66
- if (this.dry) {
67
- console.log(`${pc.blue("cp")} ${src} ${dest}`);
68
- return Promise.resolve();
69
- }
70
- return fs.cp(src, dest, { recursive: true, filter });
71
- };
72
- copyFile = async (src, dest) => {
73
- if (this.dry) {
74
- console.log(`${pc.blue("copyFile")} ${src} to ${dest}`);
75
- return Promise.resolve();
76
- }
77
- return fs.copyFile(src, dest);
78
- };
79
- cleanDir = async (dir) => {
80
- if (this.dry) {
81
- console.log(`${pc.blue("cleanDir")} ${dir}`);
82
- return Promise.resolve();
83
- }
84
- console.log(`
85
- \u{1F525} Cleaning dir ${pc.red(`${dir.trim()}`)} `);
86
- return fs.rm(dir, { recursive: true, force: true });
87
- };
88
- readFile = async (path2, allowFileNotFound) => {
89
- if (this.dry) {
90
- console.log(`${pc.blue("readFile")} ${path2}`);
91
- }
92
- try {
93
- return await fs.readFile(path2, "utf-8");
94
- } catch (error) {
95
- if (allowFileNotFound && error.code === "ENOENT") {
96
- return "";
97
- }
98
- throw error;
99
- }
100
- };
101
- readdir = async (path2) => {
102
- if (this.dry) {
103
- console.log(`${pc.blue("readdir")} ${path2}`);
104
- }
105
- try {
106
- return await fs.readdir(path2);
107
- } catch (error) {
108
- if (error.code === "ENOENT") {
109
- return [];
110
- }
111
- throw error;
112
- }
113
- };
114
- writeFiles = async (files, outDir, log) => {
115
- for (const { destination: filename, output } of files) {
116
- if (filename) {
117
- const filePath = path.join(outDir, filename);
118
- const fileDir = path.dirname(filePath);
119
- if (log) {
120
- console.log(filename);
121
- }
122
- await this.mkdir(fileDir);
123
- await this.writeFile(filePath, output);
124
- }
125
- }
126
- };
127
- };
128
- var dsfs = new FileSystem();
129
-
130
- // src/tokens/process/output/declarations.ts
131
- import pc4 from "picocolors";
132
-
133
- // package.json
134
- var package_default = {
135
- name: "@digdir/designsystemet",
136
- version: "1.13.2",
137
- description: "CLI for Designsystemet",
138
- author: "Designsystemet team",
139
- engines: {
140
- node: ">=20.20.2"
141
- },
142
- repository: {
143
- type: "git",
144
- url: "git+https://github.com/digdir/designsystemet.git"
145
- },
146
- homepage: "https://github.com/digdir/designsystemet/tree/main/packages/cli",
147
- license: "MIT",
148
- type: "module",
149
- main: "./dist/src/index.js",
150
- files: [
151
- "./dist/**",
152
- "./configs/**"
153
- ],
154
- bin: "dist/bin/designsystemet.js",
155
- exports: {
156
- ".": {
157
- import: "./dist/src/index.js"
158
- },
159
- "./color": {
160
- import: "./dist/src/colors/index.js"
161
- },
162
- "./tokens": {
163
- import: "./dist/src/tokens/index.js"
164
- },
165
- "./types": {
166
- import: "./dist/src/types.js"
167
- }
168
- },
169
- publishConfig: {
170
- access: "public"
171
- },
172
- scripts: {
173
- designsystemet: "tsx ./bin/designsystemet.ts",
174
- "designsystemet:inspect": "tsx --inspect-brk ./bin/designsystemet.ts",
175
- build: "tsup && pnpm build:types && pnpm build:json-schema",
176
- "build:types": "tsc --emitDeclarationOnly --declaration",
177
- "build:json-schema": "tsx ./src/scripts/createJsonSchema.ts",
178
- types: "tsc --noEmit",
179
- "test:tokens-create-options": 'pnpm run designsystemet tokens create -m dominant:"#007682" -n "#003333" -b 99 -o ./temp/options/design-tokens --theme options --clean',
180
- "test:tokens-create-config": "pnpm run designsystemet tokens create --config ./configs/test-tokens.config.json",
181
- "test:tokens-build": "pnpm run designsystemet tokens build -t ./temp/options/design-tokens -o ./temp/options/build --clean",
182
- "test:tokens-build-tailwind": "pnpm run designsystemet tokens build -t ./temp/options/design-tokens -o ./temp/options/build --clean --experimental-tailwind",
183
- "test:tokens-build-config": "pnpm run designsystemet tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean",
184
- "test:tokens-build-config:inspect": "pnpm run designsystemet:inspect tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean",
185
- "test:tokens-build-config-tailwind": "pnpm run designsystemet tokens build -t ./temp/config/design-tokens -o ./temp/config/build --clean --experimental-tailwind",
186
- "test:tokens-create-and-build-options": "pnpm test:tokens-create-options && pnpm test:tokens-build",
187
- "test:tokens-create-and-build-config": "pnpm test:tokens-create-config && pnpm test:tokens-build-config",
188
- "test:generate-config-from-tokens": "pnpm run designsystemet generate-config-from-tokens -d ../../design-tokens --dry",
189
- test: "node -v && pnpm test:tokens-create-and-build-options && pnpm test:generate-config-from-tokens && pnpm test:tokens-create-and-build-config",
190
- "update:preview-tokens": "tsx ./src/scripts/update-preview-tokens.ts",
191
- verify: "pnpm test && pnpm update:template && pnpm --filter @internal/digdir update:theme-digdir"
192
- },
193
- dependencies: {
194
- "@commander-js/extra-typings": "^14.0.0",
195
- "@digdir/designsystemet-types": "workspace:",
196
- "@tokens-studio/sd-transforms": "2.0.3",
197
- "chroma-js": "^3.2.0",
198
- "colorjs.io": "^0.6.1",
199
- commander: "^14.0.3",
200
- "fast-glob": "^3.3.3",
201
- hsluv: "^1.0.1",
202
- "object-hash": "^3.0.0",
203
- picocolors: "^1.1.1",
204
- postcss: "^8.5.8",
205
- ramda: "^0.32.0",
206
- "style-dictionary": "^5.4.0",
207
- zod: "^4.3.6",
208
- "zod-validation-error": "^5.0.0"
209
- },
210
- devDependencies: {
211
- "@tokens-studio/types": "0.5.2",
212
- "@types/chroma-js": "3.1.2",
213
- "@types/node": "24.12.2",
214
- "@types/object-hash": "3.0.6",
215
- "@types/ramda": "0.31.1",
216
- tsup: "8.5.1",
217
- tsx: "4.21.0",
218
- typescript: "5.9.3"
219
- }
220
- };
221
-
222
- // src/tokens/process/platform.ts
223
- import pc3 from "picocolors";
224
- import * as R15 from "ramda";
225
- import StyleDictionary2 from "style-dictionary";
226
-
227
- // src/tokens/types.ts
228
- var colorCategories = {
229
- main: "main",
230
- support: "support"
231
- };
232
-
233
- // src/tokens/process/configs.ts
234
- import { register } from "@tokens-studio/sd-transforms";
235
- import * as R14 from "ramda";
236
- import StyleDictionary from "style-dictionary";
237
-
238
- // src/tokens/utils.ts
239
8
  import * as R from "ramda";
240
- var mapToLowerCase = R.map(R.toLower);
241
- var hasAnyTruth = R.any(R.equals(true));
242
- var getType = (token) => (token.$type ?? token.type) || "";
243
- var getValue = (token) => token.$value ?? token.value;
244
- var typeEquals = R.curry(
245
- (types, token) => {
246
- if (R.isNil(token)) {
247
- return false;
248
- }
249
- return R.includes(R.toLower(getType(token)), R.map(R.toLower, Array.isArray(types) ? types : [types]));
250
- }
251
- );
252
- var pathStartsWithOneOf = R.curry(
253
- (paths, token) => {
254
- if (R.isNil(token)) {
255
- return false;
256
- }
257
- const tokenPath = mapToLowerCase(token.path);
258
- const matchPathsStartingWith = R.map((pathOrString) => {
259
- const path2 = typeof pathOrString === "string" ? [pathOrString] : pathOrString;
260
- return R.startsWith(mapToLowerCase(path2), tokenPath);
261
- }, paths);
262
- return hasAnyTruth(matchPathsStartingWith);
263
- }
264
- );
265
- function isSemanticToken(token) {
266
- return token.filePath.includes("semantic/");
267
- }
268
- function isSemanticColorToken(token, color) {
269
- return token.filePath.includes("semantic/") && R.startsWith(["color", color], token.path);
270
- }
271
- function isGlobalColorToken(token) {
272
- return typeEquals("color", token) && pathStartsWithOneOf(["global"], token);
273
- }
274
- function isColorCategoryToken(token, category) {
275
- if (!category) {
276
- return Object.keys(colorCategories).some(
277
- (colorCategory2) => isColorCategoryToken(token, colorCategory2)
278
- );
279
- }
280
- return R.startsWith(["color", category], token.path);
281
- }
282
- var isDigit = (s) => /^\d+$/.test(s);
283
- function traverseObj(obj, fn) {
284
- for (const key in obj) {
285
- const prop3 = obj[key];
286
- if (prop3 != null) {
287
- fn.apply(null, [obj, key, prop3]);
288
- if (typeof prop3 === "object") {
289
- traverseObj(prop3, fn);
290
- }
291
- }
292
- }
293
- return obj;
294
- }
295
- function inlineTokens(shouldInline, tokens) {
296
- const [inlineableTokens, otherTokens] = R.partition(shouldInline, tokens);
297
- return otherTokens.map((token) => {
298
- let transformed = getValue(token.original);
299
- for (const ref of inlineableTokens) {
300
- const refName = ref.path.join(".");
301
- if (typeof transformed === "string") {
302
- transformed = transformed.replaceAll(`{${refName}}`, getValue(ref.original));
303
- }
304
- }
305
- const tokenWithInlinedRefs = R.set(R.lensPath(["original", "$value"]), transformed, token);
306
- return tokenWithInlinedRefs;
307
- });
308
- }
309
- var sizeMap = {
310
- xsmall: "xs",
311
- small: "sm",
312
- medium: "md",
313
- large: "lg",
314
- xlarge: "xl"
315
- };
316
- function shortSizeName(size2) {
317
- return sizeMap[size2] ?? size2;
318
- }
319
- var sizeComparator = (size2) => {
320
- const sortIndex = Object.entries(sizeMap).findIndex(([key, val]) => key === size2 || val === size2);
321
- return sortIndex ?? 0;
322
- };
323
- function orderBySize(sizes) {
324
- return R.sortBy(sizeComparator, sizes);
325
- }
326
-
327
- // src/tokens/process/configs/color.ts
328
- import * as R9 from "ramda";
329
-
330
- // src/tokens/process/formats/css/color.ts
331
- import * as R2 from "ramda";
332
- import { createPropertyFormatter } from "style-dictionary/utils";
333
- var prefersColorScheme = (colorScheme2, content) => `
334
- @media (prefers-color-scheme: ${colorScheme2}) {
335
- [data-color-scheme="auto"] ${content}
336
- }
337
- `;
338
- var colorScheme = {
339
- name: "ds/css-colorscheme",
340
- format: async ({ dictionary, options, platform }) => {
341
- const { allTokens } = dictionary;
342
- const { outputReferences, usesDtcg } = options;
343
- const { selector, colorScheme: colorScheme2, layer } = platform;
344
- const colorScheme_ = colorScheme2;
345
- const format = createPropertyFormatter({
346
- outputReferences,
347
- dictionary,
348
- format: "css",
349
- usesDtcg
350
- });
351
- const colorSchemeProperty = colorScheme_ === "dark" || colorScheme_ === "light" ? `
352
- color-scheme: ${colorScheme_};
353
- ` : "";
354
- const filteredAllTokens = allTokens.filter(
355
- R2.allPass([
356
- R2.anyPass([
357
- // Include semantic tokens in the output
358
- isSemanticToken,
359
- // Include global color tokens
360
- isGlobalColorToken
361
- ]),
362
- // Don't include color category tokens -- they are exported separately
363
- (t) => !isColorCategoryToken(t)
364
- ])
365
- );
366
- const formattedMap = filteredAllTokens.map((token) => ({
367
- token,
368
- formatted: format(token)
369
- }));
370
- const formattedTokens = formattedMap.map(R2.view(R2.lensProp("formatted"))).join("\n");
371
- const content = `{
372
- ${formattedTokens}
373
- ${colorSchemeProperty}}
374
- `;
375
- const autoSelectorContent = ["light", "dark"].includes(colorScheme_) ? prefersColorScheme(colorScheme_, content) : "";
376
- const body = R2.isNotNil(layer) ? `@layer ${layer} {
377
- ${selector} ${content} ${autoSelectorContent}
378
- }
379
- ` : `${selector} ${content} ${autoSelectorContent}
380
- `;
381
- return body;
382
- }
383
- };
384
- var colorCategory = {
385
- name: "ds/css-colorcategory",
386
- format: async ({ dictionary, file, options, platform }) => {
387
- const { outputReferences, usesDtcg } = options;
388
- const { selector, layer } = platform;
389
- const destination = file.destination;
390
- const format = R2.compose(
391
- createPropertyFormatter({
392
- outputReferences,
393
- dictionary,
394
- format: "css",
395
- usesDtcg
396
- }),
397
- (token) => ({
398
- ...token,
399
- name: token.name.replace(/color-\w+-/, "color-"),
400
- original: {
401
- ...token.original,
402
- $value: new RegExp(`color-(${colorCategories.main}|${colorCategories.support})-`).test(token.name) ? token.original.$value : `{${token.path.join(".")}}`
403
- }
404
- })
405
- );
406
- const formattedMap = dictionary.allTokens.map((token) => ({
407
- token,
408
- formatted: format(token)
409
- }));
410
- buildOptions.buildTokenFormats[destination] = formattedMap;
411
- const formattedTokens = formattedMap.map(R2.view(R2.lensProp("formatted"))).join("\n");
412
- const content = `{
413
- ${formattedTokens}
414
- }
415
- `;
416
- const body = R2.isNotNil(layer) ? `@layer ${layer} {
417
- ${selector} ${content}
418
- }
419
- ` : `${selector} ${content}
420
- `;
421
- return body;
422
- }
423
- };
424
-
425
- // src/tokens/process/formats/css/semantic.ts
426
- import * as R4 from "ramda";
427
- import { createPropertyFormatter as createPropertyFormatter3 } from "style-dictionary/utils";
428
-
429
- // src/tokens/process/formats/css/size.ts
430
- import * as R3 from "ramda";
431
- import { createPropertyFormatter as createPropertyFormatter2 } from "style-dictionary/utils";
432
- var isNumericBorderRadiusToken = (t) => t.path[0] === "border-radius" && isDigit(t.path[1]);
433
- var isNumericSizeToken = (t) => pathStartsWithOneOf(["size"], t) && isDigit(t.path[1]);
434
- var isSizeToken = (t) => pathStartsWithOneOf(["size"], t);
435
- var isInlineTokens = R3.anyPass([isNumericBorderRadiusToken, isNumericSizeToken, isSizeToken]);
436
- var overrideSizingFormula = (format, token) => {
437
- const [name, value] = format(token).replace(/;$/, "").split(": ");
438
- let calc;
439
- let round;
440
- if (token.path[1] === "unit") {
441
- calc = `calc(1rem * ${value})`;
442
- } else if (value.startsWith("floor")) {
443
- calc = value.replace(/^floor\((.*)\)$/, "calc($1)");
444
- round = `round(down, ${calc}, 1px)`;
445
- } else {
446
- calc = value.includes("*") ? `calc(${value})` : value;
447
- }
448
- return {
449
- name,
450
- round: round ?? calc,
451
- calc
452
- };
453
- };
454
- var formatSizingTokens = (format, tokens) => R3.reduce(
455
- (acc, token) => {
456
- const { round, calc, name } = overrideSizingFormula(format, token);
457
- return {
458
- tokens: [...acc.tokens, token],
459
- round: [...acc.round, `${name}: ${round};`],
460
- calc: [...acc.calc, `${name}: ${calc};`]
461
- };
462
- },
463
- { tokens: [], round: [], calc: [] },
464
- tokens
465
- );
466
- var sizingTemplate = ({ round, calc }) => {
467
- const usesRounding = round.filter((val, i) => val !== calc[i]);
468
- return `
469
- ${calc.join("\n")}
470
-
471
- @supports (width: round(down, .1em, 1px)) {
472
- ${usesRounding.join("\n ")}
473
- }`;
474
- };
475
- var size = {
476
- name: "ds/css-size",
477
- format: async ({ dictionary, file, options, platform }) => {
478
- const { outputReferences, usesDtcg } = options;
479
- const { selector, layer } = platform;
480
- const destination = file.destination;
481
- const format = createPropertyFormatter2({
482
- outputReferences,
483
- dictionary,
484
- format: "css",
485
- usesDtcg
486
- });
487
- const tokens = inlineTokens(isInlineTokens, dictionary.allTokens);
488
- const filteredTokens = R3.reject((token) => R3.equals(["_size", "mode-font-size"], token.path), tokens);
489
- const [sizingTokens, restTokens] = R3.partition(
490
- (t) => pathStartsWithOneOf(["_size"], t) && (isDigit(t.path[1]) || t.path[1] === "unit"),
491
- filteredTokens
492
- );
493
- const formattedSizingTokens = formatSizingTokens(format, sizingTokens);
494
- const formattedMap = restTokens.map((token) => ({
495
- token,
496
- formatted: format(token)
497
- }));
498
- const formattedSizingMap = formattedSizingTokens.round.map((t, i) => ({
499
- token: formattedSizingTokens.tokens[i],
500
- formatted: t
501
- }));
502
- buildOptions.buildTokenFormats[destination] = [...formattedMap, ...formattedSizingMap];
503
- const formattedTokens = [formattedMap.map(R3.prop("formatted")).join("\n"), sizingTemplate(formattedSizingTokens)];
504
- const content = `${selector} {
505
- ${formattedTokens.join("\n")}
506
- }
507
- `;
508
- const body = R3.isNotNil(layer) ? `@layer ${layer} {
509
- ${content}
510
- }
511
- ` : `${content}
512
- `;
513
- return body;
514
- }
515
- };
516
-
517
- // src/tokens/process/formats/css/semantic.ts
518
- var semantic = {
519
- name: "ds/css-semantic",
520
- format: async ({ dictionary, file, options, platform }) => {
521
- const { outputReferences, usesDtcg } = options;
522
- const { selector, layer } = platform;
523
- const destination = file.destination;
524
- const format = createPropertyFormatter3({
525
- outputReferences,
526
- dictionary,
527
- format: "css",
528
- usesDtcg
529
- });
530
- const tokens = inlineTokens(isInlineTokens, dictionary.allTokens);
531
- const formattedMap = tokens.map((token) => ({
532
- token,
533
- formatted: format(token)
534
- }));
535
- buildOptions.buildTokenFormats[destination] = formattedMap;
536
- const formattedTokens = formattedMap.map(R4.prop("formatted")).join("\n");
537
- const content = `${selector} {
538
- ${formattedTokens}
539
- }
540
- `;
541
- const body = R4.isNotNil(layer) ? `@layer ${layer} {
542
- ${content}
543
- }
544
- ` : `${content}
545
- `;
546
- return body;
547
- }
548
- };
549
-
550
- // src/tokens/process/formats/css/size-mode.ts
551
- import * as R6 from "ramda";
552
- import { createPropertyFormatter as createPropertyFormatter4 } from "style-dictionary/utils";
553
-
554
- // src/tokens/process/transformers.ts
555
- import { checkAndEvaluateMath } from "@tokens-studio/sd-transforms";
556
- import * as R5 from "ramda";
557
- var isPx = R5.test(/\b\d+px\b/g);
558
- var sizeRem = {
559
- name: "ds/size/toRem",
560
- type: "value",
561
- transitive: true,
562
- filter: (token) => {
563
- const hasWantedType = typeEquals(["dimension", "fontsize"], token);
564
- const hasWantedPath = pathStartsWithOneOf([
565
- "border-radius",
566
- "font-size"
567
- /*, ['_size', 'mode-font-size']*/
568
- ], token);
569
- return hasWantedType && hasWantedPath;
570
- },
571
- transform: (token, config) => {
572
- const value = getValue(token);
573
- if (isPx(value)) {
574
- const baseFont = config.basePxFontSize || 16;
575
- const size2 = parseInt(value, 10);
576
- if (size2 === 0) {
577
- return "0";
578
- }
579
- return `${size2 / baseFont}rem`;
580
- }
581
- return value;
582
- }
583
- };
584
- var typographyName = {
585
- name: "name/typography",
586
- type: "name",
587
- transitive: true,
588
- // expanded tokens have different type so we match on path instead
589
- filter: (token) => pathStartsWithOneOf(["typography"], token),
590
- transform: (token) => {
591
- return token.name.replace("-typography", "");
592
- }
593
- };
594
- var resolveMath = {
595
- name: "ds/resolveMath",
596
- type: "value",
597
- transitive: true,
598
- filter: (token) => {
599
- const isValidValue = ["string", "object"].includes(typeof getValue(token));
600
- const isTokenOfInterest = !pathStartsWithOneOf(["border-radius"], token);
601
- return isValidValue && isTokenOfInterest;
602
- },
603
- transform: (token, platformCfg) => checkAndEvaluateMath(token, platformCfg.mathFractionDigits)
604
- };
605
- var unitless = {
606
- name: "ds/unitless",
607
- type: "value",
608
- transitive: true,
609
- filter: (token) => pathStartsWithOneOf(["size", "_size"], token),
610
- transform: (token) => parseInt(getValue(token), 10)
611
- };
612
-
613
- // src/tokens/process/configs/shared.ts
614
- var prefix = "ds";
615
- var basePxFontSize = 16;
616
- var dsTransformers = [
617
- "name/kebab",
618
- resolveMath.name,
619
- "ts/size/px",
620
- sizeRem.name,
621
- unitless.name,
622
- "ts/typography/fontWeight",
623
- typographyName.name,
624
- "ts/color/modifiers",
625
- "ts/color/css/hexrgba",
626
- "ts/size/lineheight",
627
- "shadow/css/shorthand"
628
- ];
629
-
630
- // src/tokens/process/formats/css/size-mode.ts
631
- var formatBaseSizeToken = (size2) => (token) => ({
632
- ...token,
633
- originalName: token.name,
634
- name: `${token.name}--${shortSizeName(size2)}`,
635
- $value: token.$value / basePxFontSize
636
- });
637
- var sizeMode = {
638
- name: "ds/css-size-mode",
639
- format: async ({ dictionary, file, options, platform }) => {
640
- const { outputReferences, usesDtcg } = options;
641
- const { selector, layer, size: size2 } = platform;
642
- const destination = file.destination;
643
- const format = createPropertyFormatter4({
644
- outputReferences,
645
- dictionary,
646
- format: "css",
647
- usesDtcg
648
- });
649
- const sizeSpecificTokens = dictionary.allTokens.map(formatBaseSizeToken(size2));
650
- const sizeSpecificVariables = sizeSpecificTokens.map(format).join("\n");
651
- const formattedMap = sizeSpecificTokens.map((token) => ({
652
- token,
653
- formatted: format({
654
- ...token,
655
- // Remove the `--<size>` suffix for the token listing, since that is the only token we actually use
656
- name: token.originalName
657
- })
658
- }));
659
- buildOptions.buildTokenFormats[destination] = formattedMap;
660
- const content = `${selector} /* ${size2} */ {
661
- ${sizeSpecificVariables}
662
- }`;
663
- const body = wrapInLayer(content, layer);
664
- const sizes = orderBySize(buildOptions?.sizeModes ?? []).map(shortSizeName);
665
- const defaultSize = shortSizeName(buildOptions?.defaultSize ?? "");
666
- const sizingToggles = `:root, [data-size] {
667
- --ds-size: var(--ds-size--${defaultSize});
668
- ${sizes.map((size3) => ` --ds-size--${size3}: var(--ds-size,);`).join("\n")}
669
- --ds-size-mode-font-size:
670
- ${sizes.map((size3) => ` var(--ds-size--${size3}, var(--ds-size-mode-font-size--${size3}))`).join("\n")};
671
- }`;
672
- const sizingHelpers = sizes.map((size3) => `[data-size='${size3}'] { --ds-size: var(--ds-size--${size3}); }`).join("\n");
673
- const sharedContent = `${sizingToggles}
674
-
675
- ${sizingHelpers}`;
676
- const sharedBody = shortSizeName(size2) === R6.last(sizes) ? `
677
- ${wrapInLayer(sharedContent, layer)}` : "";
678
- return body + sharedBody;
679
- }
680
- };
681
- function wrapInLayer(content, layer) {
682
- return R6.isNotNil(layer) ? `@layer ${layer} {
683
- ${content}
684
- }
685
- ` : `${content}
686
- `;
687
- }
688
-
689
- // src/tokens/process/formats/css/typography.ts
690
- import * as R7 from "ramda";
691
- import { createPropertyFormatter as createPropertyFormatter5 } from "style-dictionary/utils";
692
- var typographyFontFamilyPredicate = R7.allPass([
693
- R7.pathSatisfies(R7.includes("typography"), ["path"]),
694
- R7.pathSatisfies(R7.includes("fontFamily"), ["path"])
695
- ]);
696
- var typography = {
697
- name: "ds/css-typography",
698
- format: async ({ dictionary, file, options, platform }) => {
699
- const { outputReferences, usesDtcg } = options;
700
- const { selector, layer } = platform;
701
- const destination = file.destination;
702
- const format = createPropertyFormatter5({
703
- outputReferences,
704
- dictionary,
705
- format: "css",
706
- usesDtcg
707
- });
708
- const filteredTokens = R7.reject(typographyFontFamilyPredicate, dictionary.allTokens);
709
- const formattedMap = filteredTokens.map((token) => ({
710
- token,
711
- formatted: format(token)
712
- }));
713
- buildOptions.buildTokenFormats[destination] = formattedMap;
714
- const formattedTokens = formattedMap.map(R7.view(R7.lensProp("formatted"))).join("\n");
715
- const content = selector ? `${selector} {
716
- ${formattedTokens}
717
- }` : formattedTokens;
718
- const body = R7.isNotNil(layer) ? `@layer ${layer} {
719
- ${content}
720
- }` : content;
721
- return body;
722
- }
723
- };
724
-
725
- // src/tokens/process/formats/css/type-scale.ts
726
- import * as R8 from "ramda";
727
- import { createPropertyFormatter as createPropertyFormatter6 } from "style-dictionary/utils";
728
- var isTypographyFontFamilyToken = R8.allPass([
729
- R8.pathSatisfies(R8.includes("typography"), ["path"]),
730
- R8.pathSatisfies(R8.includes("fontFamily"), ["path"])
731
- ]);
732
- var formatTypographySizeToken = (format, token) => {
733
- const [name, value] = format(token).replace(/;$/, "").split(": ");
734
- let calc;
735
- let round;
736
- if (R8.startsWith(["font-size"], token.path)) {
737
- calc = `calc(${value} * var(--_ds-font-size-factor))`;
738
- round = `round(${calc}, 1px)`;
739
- } else {
740
- calc = value;
741
- }
742
- return { name, calc, round: round ?? calc };
743
- };
744
- var formatTypographySizeTokens = (format, tokens) => R8.reduce(
745
- (acc, token) => {
746
- const { name, calc, round } = formatTypographySizeToken(format, token);
747
- acc.tokens.push(token);
748
- acc.calc.push(`${name}: ${calc};`);
749
- acc.round.push(`${name}: ${round};`);
750
- return acc;
751
- },
752
- { tokens: [], calc: [], round: [] },
753
- tokens
754
- );
755
- var typeScale = {
756
- name: "ds/css-type-scale",
757
- format: async ({ dictionary, file, options, platform }) => {
758
- const { outputReferences, usesDtcg } = options;
759
- const { selector, layer } = platform;
760
- const destination = file.destination;
761
- const format = createPropertyFormatter6({
762
- outputReferences,
763
- dictionary,
764
- format: "css",
765
- usesDtcg
766
- });
767
- const filteredTokens = R8.reject(R8.anyPass([isTypographyFontFamilyToken]), dictionary.allTokens);
768
- const formattedTokens = formatTypographySizeTokens(format, filteredTokens);
769
- const formattedMap = formattedTokens.round.map((t, i) => ({
770
- token: formattedTokens.tokens[i],
771
- formatted: t
772
- }));
773
- buildOptions.buildTokenFormats[destination] = formattedMap;
774
- const sizeFactor = ` --_ds-font-size-factor: calc(var(--ds-size-mode-font-size) / (var(--ds-size-base) / ${basePxFontSize}));`;
775
- const content = `${selector} {
776
- ${sizeFactor}${sizingTemplate(formattedTokens)}
777
- }`;
778
- const body = R8.isNotNil(layer) ? `@layer ${layer} {
779
- ${content}
780
- }` : content;
781
- return body;
782
- }
783
- };
784
-
785
- // src/tokens/process/formats/css.ts
786
- var formats = {
787
- colorScheme,
788
- colorCategory,
789
- semantic,
790
- sizeMode,
791
- size,
792
- typography,
793
- typeScale
794
- };
795
-
796
- // src/tokens/process/configs/color.ts
797
- var colorSchemeVariables = ({ "color-scheme": colorScheme2 = "light", theme }) => {
798
- const selector = `${colorScheme2 === "light" ? ":root, " : ""}[data-color-scheme="${colorScheme2}"]`;
799
- const layer = `ds.theme.color-scheme.${colorScheme2}`;
800
- return {
801
- preprocessors: ["tokens-studio"],
802
- platforms: {
803
- css: {
804
- // custom
805
- colorScheme: colorScheme2,
806
- theme,
807
- selector,
808
- layer,
809
- //
810
- prefix,
811
- buildPath: `${theme}/`,
812
- transforms: dsTransformers,
813
- files: [
814
- {
815
- destination: `color-scheme/${colorScheme2}.css`,
816
- format: formats.colorScheme.name,
817
- filter: (token) => typeEquals("color", token) && !R9.startsWith(["global"], token.path)
818
- }
819
- ],
820
- options: {
821
- outputReferences: false
822
- }
823
- }
824
- }
825
- };
826
- };
827
- var colorCategoryVariables = (opts) => ({ "color-scheme": colorScheme2, theme, ...permutation }) => {
828
- const category = opts.category;
829
- const color = category === "builtin" ? opts.color : permutation[`${category}-color`];
830
- if (!color) {
831
- throw new Error(
832
- category === "builtin" ? `Missing color for built-in color ${opts.color}` : `Missing color for category ${category}`
833
- );
834
- }
835
- const layer = `ds.theme.color`;
836
- const isRootColor = color === buildOptions?.defaultColor;
837
- const selector = isRootColor ? `:root, [data-color-scheme], [data-color="${color}"]` : `[data-color="${color}"], [data-color-scheme][data-color="${color}"]`;
838
- const config = {
839
- preprocessors: ["tokens-studio"],
840
- platforms: {
841
- css: {
842
- // custom
843
- colorScheme: colorScheme2,
844
- theme,
845
- selector,
846
- layer,
847
- //
848
- prefix,
849
- buildPath: `${theme}/`,
850
- transforms: dsTransformers,
851
- files: [
852
- {
853
- destination: `color/${color}.css`,
854
- format: formats.colorCategory.name,
855
- filter: (token) => category === "builtin" ? isSemanticColorToken(token, color) : isColorCategoryToken(token, category)
856
- }
857
- ],
858
- options: {
859
- outputReferences: true
860
- }
861
- }
862
- }
863
- };
864
- return config;
865
- };
866
-
867
- // src/tokens/process/configs/semantic.ts
868
- import * as R10 from "ramda";
869
- import { outputReferencesFilter } from "style-dictionary/utils";
870
- var semanticVariables = ({ theme }) => {
871
- const selector = `:root`;
872
- const layer = `ds.theme.semantic`;
873
- return {
874
- preprocessors: ["tokens-studio"],
875
- platforms: {
876
- css: {
877
- // custom
878
- theme,
879
- basePxFontSize,
880
- selector,
881
- layer,
882
- //
883
- prefix,
884
- buildPath: `${theme}/`,
885
- transforms: dsTransformers,
886
- files: [
887
- {
888
- destination: `semantic.css`,
889
- format: formats.semantic.name,
890
- filter: (token) => {
891
- const isUwantedToken = R10.anyPass([R10.includes("primitives/global")])(token.filePath);
892
- const isPrivateToken = R10.includes("_", token.path);
893
- const unwantedPaths = pathStartsWithOneOf(
894
- ["size", "_size", "font-size", "line-height", "letter-spacing"],
895
- token
896
- );
897
- const unwantedTypes = typeEquals(["color", "fontWeight", "fontFamily", "typography"], token);
898
- const unwantedTokens = !(unwantedPaths || unwantedTypes || isPrivateToken || isUwantedToken);
899
- return unwantedTokens;
900
- }
901
- }
902
- ],
903
- options: {
904
- outputReferences: (token, options) => {
905
- const include = pathStartsWithOneOf(["border-radius"], token);
906
- return include && outputReferencesFilter(token, options);
907
- }
908
- }
909
- }
910
- }
911
- };
912
- };
913
-
914
- // src/tokens/process/configs/size.ts
915
- import * as R11 from "ramda";
916
- import { outputReferencesFilter as outputReferencesFilter2 } from "style-dictionary/utils";
917
- var sizeVariables = ({ theme }) => {
918
- const selector = `:root, [data-size]`;
919
- const layer = `ds.theme.size`;
920
- return {
921
- preprocessors: ["tokens-studio"],
922
- platforms: {
923
- css: {
924
- // custom
925
- theme,
926
- basePxFontSize,
927
- selector,
928
- layer,
929
- //
930
- prefix,
931
- buildPath: `${theme}/`,
932
- transforms: dsTransformers,
933
- files: [
934
- {
935
- destination: `size.css`,
936
- format: formats.size.name,
937
- filter: (token) => {
938
- const isUwantedToken = R11.anyPass([R11.includes("primitives/global")])(token.filePath);
939
- const isPrivateToken = R11.includes("_", token.path);
940
- return pathStartsWithOneOf(["size", "_size"], token) && !(isUwantedToken || isPrivateToken);
941
- }
942
- }
943
- ],
944
- options: {
945
- outputReferences: (token, options) => {
946
- const isWantedSize = pathStartsWithOneOf(["size", "_size"], token) && (isDigit(token.path[1]) || token.path[1] === "unit");
947
- return isWantedSize && outputReferencesFilter2(token, options);
948
- }
949
- }
950
- }
951
- }
952
- };
953
- };
954
-
955
- // src/tokens/process/configs/size-mode.ts
956
- import * as R12 from "ramda";
957
- var sizeModeVariables = ({ theme, size: size2 }) => {
958
- const selector = `:root`;
959
- const layer = `ds.theme.size-mode`;
960
- return {
961
- preprocessors: ["tokens-studio"],
962
- platforms: {
963
- css: {
964
- // custom
965
- size: size2,
966
- theme,
967
- basePxFontSize,
968
- selector,
969
- layer,
970
- //
971
- prefix,
972
- buildPath: `${theme}/`,
973
- transforms: dsTransformers,
974
- files: [
975
- {
976
- destination: `size-mode/${size2}.css`,
977
- format: formats.sizeMode.name,
978
- filter: (token) => {
979
- return R12.equals(["_size", "mode-font-size"], token.path);
980
- }
981
- }
982
- ]
983
- }
984
- }
985
- };
986
- };
987
-
988
- // src/tokens/process/configs/type-scale.ts
989
- var typeScaleVariables = ({ theme }) => {
990
- const selector = ":root, [data-size]";
991
- const layer = `ds.theme.type-scale`;
992
- return {
993
- usesDtcg: true,
994
- preprocessors: ["tokens-studio"],
995
- expand: {
996
- include: ["typography"]
997
- },
998
- platforms: {
999
- css: {
1000
- prefix,
1001
- selector,
1002
- layer,
1003
- buildPath: `${theme}/`,
1004
- basePxFontSize,
1005
- transforms: [
1006
- "name/kebab",
1007
- "ts/size/px",
1008
- sizeRem.name,
1009
- "ts/size/lineheight",
1010
- "ts/typography/fontWeight",
1011
- typographyName.name
1012
- ],
1013
- files: [
1014
- {
1015
- destination: `type-scale.css`,
1016
- format: formats.typeScale.name,
1017
- filter: (token) => {
1018
- const included = typeEquals(["typography", "dimension", "fontsize"], token);
1019
- if (/primitives\/modes\/typography\/(primary|secondary)/.test(token.filePath)) return false;
1020
- return included && !pathStartsWithOneOf(["spacing", "sizing", "size", "border-width", "border-radius"], token) && (pathStartsWithOneOf(["font-size"], token) || token.path.includes("fontSize"));
1021
- }
1022
- }
1023
- ],
1024
- options: {
1025
- outputReferences: (token) => pathStartsWithOneOf(["typography"], token) && token.path.includes("fontSize")
1026
- }
1027
- }
1028
- }
1029
- };
1030
- };
1031
-
1032
- // src/tokens/process/configs/typography.ts
1033
- import { expandTypesMap } from "@tokens-studio/sd-transforms";
1034
- var typographyVariables = ({ theme, typography: typography2 }) => {
1035
- const selector = `${typography2 === "primary" ? ":root, " : ""}[data-typography="${typography2}"]`;
1036
- const layer = `ds.theme.typography.${typography2}`;
1037
- return {
1038
- usesDtcg: true,
1039
- preprocessors: ["tokens-studio"],
1040
- expand: {
1041
- include: ["typography"],
1042
- typesMap: { ...expandTypesMap, typography: { ...expandTypesMap.typography, letterSpacing: "dimension" } }
1043
- },
1044
- platforms: {
1045
- css: {
1046
- prefix,
1047
- typography: typography2,
1048
- selector,
1049
- layer,
1050
- buildPath: `${theme}/`,
1051
- basePxFontSize,
1052
- transforms: [
1053
- "name/kebab",
1054
- "ts/size/px",
1055
- sizeRem.name,
1056
- "ts/size/lineheight",
1057
- "ts/typography/fontWeight",
1058
- "ts/size/css/letterspacing",
1059
- typographyName.name
1060
- ],
1061
- files: [
1062
- {
1063
- destination: `typography/${typography2}.css`,
1064
- format: formats.typography.name,
1065
- filter: (token) => {
1066
- const included = typeEquals(["fontweight", "fontFamily", "lineHeight", "dimension"], token);
1067
- if (/primitives\/modes\/typography\/(primary|secondary)/.test(token.filePath)) return false;
1068
- return included && !pathStartsWithOneOf(["spacing", "sizing", "size", "_size", "border-width", "border-radius"], token) && !(pathStartsWithOneOf(["typography"], token) && token.path.includes("fontSize"));
1069
- }
1070
- }
1071
- ]
1072
- }
1073
- }
1074
- };
1075
- };
1076
-
1077
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowTypes.js
1078
- var BoxShadowTypes;
1079
- (function(BoxShadowTypes2) {
1080
- BoxShadowTypes2["DROP_SHADOW"] = "dropShadow";
1081
- BoxShadowTypes2["INNER_SHADOW"] = "innerShadow";
1082
- })(BoxShadowTypes || (BoxShadowTypes = {}));
1083
-
1084
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorModifierTypes.js
1085
- var ColorModifierTypes;
1086
- (function(ColorModifierTypes2) {
1087
- ColorModifierTypes2["LIGHTEN"] = "lighten";
1088
- ColorModifierTypes2["DARKEN"] = "darken";
1089
- ColorModifierTypes2["MIX"] = "mix";
1090
- ColorModifierTypes2["ALPHA"] = "alpha";
1091
- })(ColorModifierTypes || (ColorModifierTypes = {}));
1092
-
1093
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/ColorSpaceTypes.js
1094
- var ColorSpaceTypes;
1095
- (function(ColorSpaceTypes2) {
1096
- ColorSpaceTypes2["LCH"] = "lch";
1097
- ColorSpaceTypes2["SRGB"] = "srgb";
1098
- ColorSpaceTypes2["P3"] = "p3";
1099
- ColorSpaceTypes2["HSL"] = "hsl";
1100
- })(ColorSpaceTypes || (ColorSpaceTypes = {}));
1101
-
1102
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/Properties.js
1103
- var Properties;
1104
- (function(Properties2) {
1105
- Properties2["sizing"] = "sizing";
1106
- Properties2["height"] = "height";
1107
- Properties2["width"] = "width";
1108
- Properties2["spacing"] = "spacing";
1109
- Properties2["verticalPadding"] = "verticalPadding";
1110
- Properties2["horizontalPadding"] = "horizontalPadding";
1111
- Properties2["paddingTop"] = "paddingTop";
1112
- Properties2["paddingRight"] = "paddingRight";
1113
- Properties2["paddingBottom"] = "paddingBottom";
1114
- Properties2["paddingLeft"] = "paddingLeft";
1115
- Properties2["itemSpacing"] = "itemSpacing";
1116
- Properties2["fill"] = "fill";
1117
- Properties2["backgroundBlur"] = "backgroundBlur";
1118
- Properties2["border"] = "border";
1119
- Properties2["borderTop"] = "borderTop";
1120
- Properties2["borderRight"] = "borderRight";
1121
- Properties2["borderBottom"] = "borderBottom";
1122
- Properties2["borderLeft"] = "borderLeft";
1123
- Properties2["borderColor"] = "borderColor";
1124
- Properties2["borderRadius"] = "borderRadius";
1125
- Properties2["borderRadiusTopLeft"] = "borderRadiusTopLeft";
1126
- Properties2["borderRadiusTopRight"] = "borderRadiusTopRight";
1127
- Properties2["borderRadiusBottomRight"] = "borderRadiusBottomRight";
1128
- Properties2["borderRadiusBottomLeft"] = "borderRadiusBottomLeft";
1129
- Properties2["borderWidth"] = "borderWidth";
1130
- Properties2["borderWidthTop"] = "borderWidthTop";
1131
- Properties2["borderWidthRight"] = "borderWidthRight";
1132
- Properties2["borderWidthBottom"] = "borderWidthBottom";
1133
- Properties2["borderWidthLeft"] = "borderWidthLeft";
1134
- Properties2["boxShadow"] = "boxShadow";
1135
- Properties2["opacity"] = "opacity";
1136
- Properties2["fontFamilies"] = "fontFamilies";
1137
- Properties2["fontWeights"] = "fontWeights";
1138
- Properties2["fontSizes"] = "fontSizes";
1139
- Properties2["lineHeights"] = "lineHeights";
1140
- Properties2["typography"] = "typography";
1141
- Properties2["composition"] = "composition";
1142
- Properties2["letterSpacing"] = "letterSpacing";
1143
- Properties2["paragraphSpacing"] = "paragraphSpacing";
1144
- Properties2["textCase"] = "textCase";
1145
- Properties2["dimension"] = "dimension";
1146
- Properties2["textDecoration"] = "textDecoration";
1147
- Properties2["asset"] = "asset";
1148
- Properties2["tokenValue"] = "tokenValue";
1149
- Properties2["value"] = "value";
1150
- Properties2["tokenName"] = "tokenName";
1151
- Properties2["description"] = "description";
1152
- })(Properties || (Properties = {}));
1153
-
1154
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenSetStatus.js
1155
- var TokenSetStatus;
1156
- (function(TokenSetStatus2) {
1157
- TokenSetStatus2["DISABLED"] = "disabled";
1158
- TokenSetStatus2["SOURCE"] = "source";
1159
- TokenSetStatus2["ENABLED"] = "enabled";
1160
- })(TokenSetStatus || (TokenSetStatus = {}));
1161
-
1162
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TokenTypes.js
1163
- var TokenTypes;
1164
- (function(TokenTypes2) {
1165
- TokenTypes2["OTHER"] = "other";
1166
- TokenTypes2["COLOR"] = "color";
1167
- TokenTypes2["BORDER_RADIUS"] = "borderRadius";
1168
- TokenTypes2["SIZING"] = "sizing";
1169
- TokenTypes2["SPACING"] = "spacing";
1170
- TokenTypes2["TEXT"] = "text";
1171
- TokenTypes2["TYPOGRAPHY"] = "typography";
1172
- TokenTypes2["OPACITY"] = "opacity";
1173
- TokenTypes2["BORDER_WIDTH"] = "borderWidth";
1174
- TokenTypes2["STROKE_STYLE"] = "strokeStyle";
1175
- TokenTypes2["BOX_SHADOW"] = "boxShadow";
1176
- TokenTypes2["FONT_FAMILIES"] = "fontFamilies";
1177
- TokenTypes2["FONT_WEIGHTS"] = "fontWeights";
1178
- TokenTypes2["LINE_HEIGHTS"] = "lineHeights";
1179
- TokenTypes2["FONT_SIZES"] = "fontSizes";
1180
- TokenTypes2["LETTER_SPACING"] = "letterSpacing";
1181
- TokenTypes2["PARAGRAPH_SPACING"] = "paragraphSpacing";
1182
- TokenTypes2["PARAGRAPH_INDENT"] = "paragraphIndent";
1183
- TokenTypes2["TEXT_DECORATION"] = "textDecoration";
1184
- TokenTypes2["TEXT_CASE"] = "textCase";
1185
- TokenTypes2["COMPOSITION"] = "composition";
1186
- TokenTypes2["DIMENSION"] = "dimension";
1187
- TokenTypes2["BORDER"] = "border";
1188
- TokenTypes2["ASSET"] = "asset";
1189
- TokenTypes2["BOOLEAN"] = "boolean";
1190
- TokenTypes2["NUMBER"] = "number";
1191
- })(TokenTypes || (TokenTypes = {}));
1192
-
1193
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BorderValues.js
1194
- var BorderValues;
1195
- (function(BorderValues2) {
1196
- BorderValues2["BORDER_COLOR"] = "color";
1197
- BorderValues2["BORDER_WIDTH"] = "width";
1198
- BorderValues2["BORDER_STYLE"] = "style";
1199
- })(BorderValues || (BorderValues = {}));
1200
-
1201
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/StrokeStyleValues.js
1202
- var StrokeStyleValues;
1203
- (function(StrokeStyleValues2) {
1204
- StrokeStyleValues2["SOLID"] = "solid";
1205
- StrokeStyleValues2["DASHED"] = "dashed";
1206
- StrokeStyleValues2["DOTTED"] = "dotted";
1207
- StrokeStyleValues2["DOUBLE"] = "double";
1208
- StrokeStyleValues2["GROOVE"] = "groove";
1209
- StrokeStyleValues2["RIDGE"] = "ridge";
1210
- StrokeStyleValues2["OUTSET"] = "outset";
1211
- StrokeStyleValues2["INSET"] = "inset";
1212
- })(StrokeStyleValues || (StrokeStyleValues = {}));
1213
-
1214
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/BoxShadowValues.js
1215
- var BoxShadowValues;
1216
- (function(BoxShadowValues2) {
1217
- BoxShadowValues2["TYPE"] = "type";
1218
- BoxShadowValues2["COLOR"] = "color";
1219
- BoxShadowValues2["X"] = "x";
1220
- BoxShadowValues2["Y"] = "y";
1221
- BoxShadowValues2["BLUR"] = "blur";
1222
- BoxShadowValues2["SPREAD"] = "spread";
1223
- BoxShadowValues2["BLEND_MODE"] = "blendMode";
1224
- })(BoxShadowValues || (BoxShadowValues = {}));
1225
-
1226
- // ../../node_modules/.pnpm/@tokens-studio+types@0.5.2/node_modules/@tokens-studio/types/dist/constants/TypographyValues.js
1227
- var TypographyValues;
1228
- (function(TypographyValues2) {
1229
- TypographyValues2["FONT_FAMILY"] = "fontFamily";
1230
- TypographyValues2["FONT_WEIGHT"] = "fontWeight";
1231
- TypographyValues2["LINE_HEIGHT"] = "lineHeight";
1232
- TypographyValues2["FONT_SIZE"] = "fontSize";
1233
- TypographyValues2["LETTER_SPACING"] = "letterSpacing";
1234
- TypographyValues2["PARAGRAPH_SPACING"] = "paragraphSpacing";
1235
- TypographyValues2["PARAGRAPH_INDENT"] = "paragraphIndent";
1236
- TypographyValues2["TEXT_DECORATION"] = "textDecoration";
1237
- TypographyValues2["TEXT_CASE"] = "textCase";
1238
- })(TypographyValues || (TypographyValues = {}));
1239
-
1240
- // src/tokens/process/utils/getMultidimensionalThemes.ts
1241
- import pc2 from "picocolors";
1242
- import * as R13 from "ramda";
1243
-
1244
- // src/tokens/process/utils/kebab-case.ts
1245
- function kebabCase(str) {
1246
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
1247
- }
1248
-
1249
- // src/tokens/process/utils/getMultidimensionalThemes.ts
1250
- var getMultidimensionalThemes = (processed$themes, dimensions) => {
1251
- const verboseLogging = buildOptions?.verbose;
1252
- const grouped$themes = groupThemes(processed$themes);
1253
- const permutations = permutateThemes(grouped$themes);
1254
- const ALL_DEPENDENT_ON = ["theme"];
1255
- const keys2 = R13.keys(grouped$themes);
1256
- const nonDependentKeys = keys2.filter((x) => ![...ALL_DEPENDENT_ON, ...dimensions].includes(x));
1257
- if (verboseLogging) {
1258
- console.log(pc2.cyan(`\u{1F50E} Finding theme permutations for ${dimensions}`));
1259
- console.log(pc2.cyan(` (ignoring permutations for ${nonDependentKeys})`));
1260
- }
1261
- return permutations.filter((val) => {
1262
- const filters = nonDependentKeys.map((x) => val.permutation[x] === grouped$themes[x][0].name);
1263
- return filters.every((x) => x);
1264
- });
1265
- };
1266
- var processed = /* @__PURE__ */ Symbol("Type brand for ProcessedThemeObject");
1267
- function isProcessed(theme) {
1268
- return Boolean(theme[processed]);
1269
- }
1270
- function processThemeObject(theme) {
1271
- if (isProcessed(theme)) {
1272
- return theme;
1273
- }
1274
- const result = { ...theme, [processed]: true };
1275
- if (result.group) {
1276
- result.group = kebabCase(result.group);
1277
- }
1278
- result.name = kebabCase(result.name);
1279
- return result;
1280
- }
1281
- function groupThemes(themes) {
1282
- const groups = {};
1283
- for (const theme of themes) {
1284
- if (theme.group) {
1285
- const groupKey = theme.group;
1286
- groups[groupKey] = [...groups[groupKey] ?? [], theme];
1287
- } else {
1288
- throw new Error(
1289
- `Theme ${theme.name} does not have a group property, which is required for multi-dimensional theming.`
1290
- );
1291
- }
1292
- }
1293
- return groups;
1294
- }
1295
- var hasUnknownProps = R13.pipe(R13.values, R13.none(R13.equals("unknown")), R13.not);
1296
- function permutateThemes(groups) {
1297
- const separator = "_";
1298
- const permutations = cartesian(Object.values(groups));
1299
- const permutatedThemes = permutations.map((perm) => {
1300
- const permutatedTheme = perm.reduce(
1301
- (acc, theme) => {
1302
- const { group, name, selectedTokenSets } = theme;
1303
- let updatedPermutation = acc.permutation;
1304
- if (group) {
1305
- const groupProp = R13.lensProp(group);
1306
- updatedPermutation = R13.set(groupProp, name, updatedPermutation);
1307
- }
1308
- const updatedName = `${String(acc.name)}${acc ? separator : ""}${name}`;
1309
- const sets = [...acc.selectedTokenSets, ...filterTokenSets(selectedTokenSets)];
1310
- return {
1311
- permutation: updatedPermutation,
1312
- name: updatedName,
1313
- selectedTokenSets: sets
1314
- };
1315
- },
1316
- {
1317
- name: "",
1318
- selectedTokenSets: [],
1319
- permutation: {
1320
- "color-scheme": "unknown",
1321
- "main-color": "unknown",
1322
- "support-color": "unknown",
1323
- theme: "unknown",
1324
- semantic: "unknown",
1325
- size: "unknown",
1326
- typography: "unknown"
1327
- }
1328
- }
1329
- );
1330
- if (hasUnknownProps(permutatedTheme)) {
1331
- throw Error(`Theme ${permutatedTheme.name} has unknown props: ${JSON.stringify(permutatedTheme)}`);
1332
- }
1333
- const uniqueTokenSets = new Set(permutatedTheme.selectedTokenSets);
1334
- return { ...permutatedTheme, selectedTokenSets: Array.from(uniqueTokenSets) };
1335
- });
1336
- return permutatedThemes;
1337
- }
1338
- function filterTokenSets(tokensets) {
1339
- return Object.entries(tokensets).filter(([, val]) => val !== TokenSetStatus.DISABLED).sort((a, b) => {
1340
- if (a[1] === TokenSetStatus.SOURCE && b[1] === TokenSetStatus.ENABLED) {
1341
- return -1;
1342
- }
1343
- if (a[1] === TokenSetStatus.ENABLED && b[1] === TokenSetStatus.SOURCE) {
1344
- return 1;
1345
- }
1346
- return 0;
1347
- }).map((entry) => entry[0]);
1348
- }
1349
- function cartesian(a) {
1350
- return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e].flat())));
1351
- }
1352
- var getCustomColors = (processed$themes, colorGroups) => processed$themes.filter((x) => {
1353
- if (!x.group) {
1354
- return false;
1355
- }
1356
- return colorGroups.includes(x.group);
1357
- }).map((x) => x.name);
1358
-
1359
- // src/tokens/process/configs.ts
1360
- void register(StyleDictionary, { withSDBuiltins: false });
1361
- StyleDictionary.registerTransform(sizeRem);
1362
- StyleDictionary.registerTransform(typographyName);
1363
- StyleDictionary.registerTransform(resolveMath);
1364
- StyleDictionary.registerTransform(unitless);
1365
- for (const format of Object.values(formats)) {
1366
- StyleDictionary.registerFormat(format);
1367
- }
1368
- var configs = {
1369
- colorSchemeVariables,
1370
- mainColorVariables: colorCategoryVariables({ category: "main" }),
1371
- supportColorVariables: colorCategoryVariables({ category: "support" }),
1372
- neutralColorVariables: colorCategoryVariables({ category: "builtin", color: "neutral" }),
1373
- successColorVariables: colorCategoryVariables({ category: "builtin", color: "success" }),
1374
- dangerColorVariables: colorCategoryVariables({ category: "builtin", color: "danger" }),
1375
- warningColorVariables: colorCategoryVariables({ category: "builtin", color: "warning" }),
1376
- infoColorVariables: colorCategoryVariables({ category: "builtin", color: "info" }),
1377
- sizeModeVariables,
1378
- sizeVariables,
1379
- typographyVariables,
1380
- typeScaleVariables,
1381
- semanticVariables
1382
- };
1383
- var getConfigsForThemeDimensions = (getConfig, processed$themes, dimensions, options) => {
1384
- const { tokensDir, tokenSets } = options;
1385
- const permutations = getMultidimensionalThemes(processed$themes, dimensions);
1386
- return permutations.flatMap(({ selectedTokenSets, permutation }) => {
1387
- const tokenSource = { source: void 0, tokens: {} };
1388
- if (tokenSets) {
1389
- for (const tokenSet of selectedTokenSets) {
1390
- const tokens = tokenSets.get(tokenSet);
1391
- if (tokens) {
1392
- const tokensWithFilePath = traverseObj(tokens, (obj) => {
1393
- if (Object.hasOwn(obj, `$value`) && !obj.filePath) {
1394
- obj.filePath = tokenSet;
1395
- }
1396
- });
1397
- tokenSource.tokens = R14.mergeDeepRight(tokenSource.tokens, tokensWithFilePath);
1398
- }
1399
- }
1400
- } else {
1401
- tokenSource.source = selectedTokenSets.map((x) => `${tokensDir}/${x}.json`);
1402
- }
1403
- const configOrConfigs = getConfig(permutation);
1404
- const configs_ = Array.isArray(configOrConfigs) ? configOrConfigs : [{ config: configOrConfigs }];
1405
- const configs2 = configs_.map(({ config, permutationOverrides }) => {
1406
- return {
1407
- permutation: { ...permutation, ...permutationOverrides },
1408
- config: {
1409
- ...config,
1410
- /** Use official W3C design token format
1411
- @see https://v4.styledictionary.com/info/dtcg/
1412
- @see https://design-tokens.github.io/community-group/format/ */
1413
- usesDtcg: true,
1414
- log: {
1415
- ...config?.log,
1416
- verbosity: buildOptions?.verbose ? "verbose" : "silent"
1417
- },
1418
- ...tokenSource
1419
- }
1420
- };
1421
- });
1422
- return configs2;
1423
- }).sort();
1424
- };
1425
-
1426
- // src/tokens/process/platform.ts
1427
- var initResult = {
1428
- formatted: [],
1429
- tokens: [],
1430
- permutation: {
1431
- "color-scheme": "",
1432
- "main-color": "",
1433
- "support-color": "",
1434
- semantic: "",
1435
- size: "",
1436
- theme: "",
1437
- typography: ""
1438
- }
1439
- };
1440
- var buildOptions = {
1441
- verbose: false,
1442
- processed$themes: [],
1443
- buildTokenFormats: {}
1444
- };
1445
- var sd = new StyleDictionary2();
1446
- var buildConfigs = {
1447
- typography: { getConfig: configs.typographyVariables, dimensions: ["typography"] },
1448
- sizeMode: { getConfig: configs.sizeModeVariables, dimensions: ["size"] },
1449
- size: { getConfig: configs.sizeVariables, dimensions: ["semantic"] },
1450
- typeScale: { getConfig: configs.typeScaleVariables, dimensions: ["semantic"] },
1451
- "color-scheme": { getConfig: configs.colorSchemeVariables, dimensions: ["color-scheme"] },
1452
- "main-color": { getConfig: configs.mainColorVariables, dimensions: ["main-color"] },
1453
- "support-color": { getConfig: configs.supportColorVariables, dimensions: ["support-color"] },
1454
- "neutral-color": {
1455
- getConfig: configs.neutralColorVariables,
1456
- dimensions: ["semantic"],
1457
- log: ({ permutation: { theme } }) => `${theme} - neutral`
1458
- },
1459
- "success-color": {
1460
- getConfig: configs.successColorVariables,
1461
- dimensions: ["semantic"],
1462
- log: ({ permutation: { theme } }) => `${theme} - success`
1463
- },
1464
- "danger-color": {
1465
- getConfig: configs.dangerColorVariables,
1466
- dimensions: ["semantic"],
1467
- log: ({ permutation: { theme } }) => `${theme} - danger`
1468
- },
1469
- "warning-color": {
1470
- getConfig: configs.warningColorVariables,
1471
- dimensions: ["semantic"],
1472
- log: ({ permutation: { theme } }) => `${theme} - warning`
1473
- },
1474
- "info-color": {
1475
- getConfig: configs.infoColorVariables,
1476
- dimensions: ["semantic"],
1477
- log: ({ permutation: { theme } }) => `${theme} - info`
1478
- },
1479
- semantic: { getConfig: configs.semanticVariables, dimensions: ["semantic"] }
1480
- };
1481
- async function processPlatform(options) {
1482
- const { type, processed$themes } = options;
1483
- const platform = "css";
1484
- const tokenSets = type === "format" ? options.tokenSets : void 0;
1485
- const tokensDir = type === "build" ? options.tokensDir : void 0;
1486
- const UNSAFE_DEFAULT_COLOR = process.env.UNSAFE_DEFAULT_COLOR ?? "";
1487
- if (UNSAFE_DEFAULT_COLOR) {
1488
- console.warn(
1489
- pc3.yellow(
1490
- `
1491
- \u26A0\uFE0F UNSAFE_DEFAULT_COLOR is set to ${pc3.blue(UNSAFE_DEFAULT_COLOR)}. This will override the default color.`
1492
- )
1493
- );
1494
- }
1495
- const UNSAFE_COLOR_GROUPS = Array.from(process.env.UNSAFE_COLOR_GROUPS?.split(",") ?? []);
1496
- if (UNSAFE_COLOR_GROUPS.length > 0) {
1497
- console.warn(
1498
- pc3.yellow(
1499
- `
1500
- \u26A0\uFE0F UNSAFE_COLOR_GROUPS is set to ${pc3.blue(`[${UNSAFE_COLOR_GROUPS.join(", ")}]`)}. This will override the default color groups.`
1501
- )
1502
- );
1503
- }
1504
- const colorGroups = UNSAFE_COLOR_GROUPS.length > 0 ? UNSAFE_COLOR_GROUPS : [colorCategories.main, colorCategories.support].map((c) => `${c}-color`);
1505
- buildOptions = options;
1506
- buildOptions.defaultColor = UNSAFE_DEFAULT_COLOR;
1507
- buildOptions.colorGroups = colorGroups;
1508
- if (!buildOptions.defaultColor) {
1509
- const customColors = getCustomColors(processed$themes, colorGroups);
1510
- const firstMainColor = R15.head(customColors);
1511
- buildOptions.defaultColor = firstMainColor;
1512
- }
1513
- if (buildOptions.defaultColor) {
1514
- console.log(`
1515
- \u{1F3A8} Using ${pc3.blue(buildOptions.defaultColor)} as default color`);
1516
- }
1517
- const sizeModes = processed$themes.filter((x) => x.group === "size").map((x) => x.name);
1518
- buildOptions.sizeModes = sizeModes;
1519
- if (!buildOptions.defaultSize) {
1520
- const defaultSize = R15.head(sizeModes);
1521
- buildOptions.defaultSize = defaultSize;
1522
- }
1523
- if (buildOptions.defaultSize) {
1524
- console.log(`
1525
- \u{1F4CF} Using ${pc3.blue(buildOptions.defaultSize)} as default size`);
1526
- }
1527
- const buildAndSdConfigs = R15.map((buildConfig) => {
1528
- const sdConfigs = getConfigsForThemeDimensions(buildConfig.getConfig, processed$themes, buildConfig.dimensions, {
1529
- tokensDir,
1530
- tokenSets
1531
- });
1532
- const unknownConfigs = buildConfig.dimensions.map(
1533
- (dimension) => sdConfigs.filter((x) => x.permutation[dimension] === "unknown")
1534
- );
1535
- for (const unknowns of unknownConfigs) {
1536
- if (unknowns.length === sdConfigs.length) {
1537
- buildConfig.enabled = () => false;
1538
- }
1539
- }
1540
- return {
1541
- buildConfig,
1542
- sdConfigs
1543
- };
1544
- }, buildConfigs);
1545
- const processedBuilds = {
1546
- "color-scheme": [initResult],
1547
- "main-color": [initResult],
1548
- "support-color": [initResult],
1549
- "neutral-color": [initResult],
1550
- "success-color": [initResult],
1551
- "danger-color": [initResult],
1552
- "warning-color": [initResult],
1553
- "info-color": [initResult],
1554
- semantic: [initResult],
1555
- typography: [initResult],
1556
- sizeMode: [initResult],
1557
- size: [initResult],
1558
- typeScale: [initResult]
1559
- };
1560
- try {
1561
- for (const [buildName, { buildConfig, sdConfigs }] of R15.toPairs(buildAndSdConfigs)) {
1562
- if (!(buildConfig.enabled?.() ?? true)) {
1563
- continue;
1564
- }
1565
- if (sdConfigs.length > 0) {
1566
- console.log(`
1567
- \u{1F371} Building ${pc3.green(buildConfig.name ?? buildName)}`);
1568
- const results = await Promise.all(
1569
- sdConfigs.map(async (sdConfig) => {
1570
- const { config, permutation } = sdConfig;
1571
- const modes = ["theme", ...buildConfig.dimensions];
1572
- const modeMessage = modes.map((x) => permutation[x]).join(" - ");
1573
- const logMessage = R15.isNil(buildConfig.log) ? modeMessage : buildConfig?.log(sdConfig);
1574
- console.log(logMessage);
1575
- const sdOptions = { cache: true };
1576
- const sdExtended = await sd.extend(config);
1577
- const formatted = await sdExtended.formatPlatform(platform, sdOptions);
1578
- const tokens = (await sdExtended.getPlatformTokens(platform, sdOptions)).allTokens;
1579
- const result = {
1580
- permutation,
1581
- formatted,
1582
- tokens
1583
- };
1584
- return Promise.resolve(result);
1585
- })
1586
- );
1587
- processedBuilds[buildName] = results;
1588
- }
1589
- }
1590
- } catch (err) {
1591
- if (err instanceof Error) {
1592
- err.message = err.message.replace('log.verbosity "verbose" or use ', "");
1593
- }
1594
- throw err;
1595
- }
1596
- return processedBuilds;
1597
- }
1598
-
1599
- // src/tokens/process/output/declarations.ts
1600
- var defaultFileHeader = `build: v${package_default.version}`;
1601
- var createTypeDeclarationFiles = (processed$themes) => {
1602
- const colorGroups = buildOptions?.colorGroups || [];
1603
- const customColors = getCustomColors(processed$themes, colorGroups);
1604
- const typeDeclaration = createColorTypeDeclaration([...customColors, "neutral"]);
1605
- return [
1606
- {
1607
- output: `/* This file is deprecated and will be removed in a future release. Use types.d.ts instead */
1608
- ${typeDeclaration}`,
1609
- destination: "colors.d.ts"
1610
- },
1611
- {
1612
- output: typeDeclaration,
1613
- destination: "types.d.ts"
1614
- }
1615
- ];
1616
- };
1617
- function createColorTypeDeclaration(colors) {
1618
- console.log(`
1619
- \u{1F371} Building ${pc4.green("type declarations")}`);
1620
- const typeDeclaration = `
1621
- /* ${defaultFileHeader} */
1622
- import type {} from '@digdir/designsystemet-types';
1623
-
1624
- // Augment types based on theme
1625
- declare module '@digdir/designsystemet-types' {
1626
- export interface ColorDefinitions {
1627
- ${colors.map((color) => ` ${color.includes("-") ? `'${color}'` : color}: never;`).join("\n")}
1628
- }
1629
- export interface SeverityColorDefinitions {
1630
- info: never;
1631
- success: never;
1632
- warning: never;
1633
- danger: never;
1634
- }
1635
- }
1636
- `.trimStart();
1637
- return typeDeclaration;
1638
- }
1639
-
1640
- // src/tokens/process/output/tailwind.ts
1641
- var createTailwindCSSFiles = (cssFiles) => {
1642
- console.log("\n\u{1F371} Creating Tailwind Config");
1643
- return cssFiles.map((file) => {
1644
- if (file.destination) {
1645
- const tailwindConfig = generateTailwind(file.output);
1646
- const tailwindFile = {
1647
- destination: file.destination.replace(".css", ".tailwind.css"),
1648
- output: tailwindConfig
1649
- };
1650
- return tailwindFile;
1651
- }
1652
- return void 0;
1653
- }).filter((item) => item !== void 0);
1654
- };
1655
- var generateTailwind = (css) => {
1656
- const tailwind = ["--font-sans: var(--ds-font-family)"];
1657
- const tokens = Array.from(new Set(css.match(/--ds-[^:)]+/g)), (m) => m).sort(
1658
- (a, b) => a.localeCompare(b, void 0, { numeric: true, sensitivity: "base" })
1659
- );
1660
- for (const token of tokens) {
1661
- if (token.startsWith("--ds-color-") && !token.startsWith("--ds-color-focus")) {
1662
- tailwind.push(`--color-${token.replace("--ds-color-", "")}: var(${token})`);
1663
- } else if (token.startsWith("--ds-font-weight-")) {
1664
- tailwind.push(`--font-weight-${token.replace("--ds-font-weight-", "")}: var(${token})`);
1665
- } else if (token.match(/--ds-border-radius-(sm|md|lg|xl)/)) {
1666
- tailwind.push(`--radius-${token.replace("--ds-border-radius-", "")}: var(${token})`);
1667
- } else if (token.match(/--ds-body-(sm|mg|lg)-body-font-size/)) {
1668
- tailwind.push(`--text-${token.replace("--ds-body-", "").replace("-font-size", "")}: var(${token})`);
1669
- } else if (token.match(/^--ds-size-\d+$/)) {
1670
- tailwind.push(`--spacing-${token.replace("--ds-size-", "")}: var(${token})`);
1671
- }
1672
- }
1673
- const dynamicColors = `[data-color] {
1674
- --color-background-default: var(--ds-color-background-default);
1675
- --color-background-tinted: var(--ds-color-background-tinted);
1676
- --color-surface-default: var(--ds-color-surface-default);
1677
- --color-surface-tinted: var(--ds-color-surface-tinted);
1678
- --color-surface-hover: var(--ds-color-surface-hover);
1679
- --color-surface-active: var(--ds-color-surface-active);
1680
- --color-border-subtle: var(--ds-color-border-subtle);
1681
- --color-border-default: var(--ds-color-border-default);
1682
- --color-border-strong: var(--ds-color-border-strong);
1683
- --color-text-subtle: var(--ds-color-text-subtle);
1684
- --color-text-default: var(--ds-color-text-default);
1685
- --color-base-default: var(--ds-color-base-default);
1686
- --color-base-hover: var(--ds-color-base-hover);
1687
- --color-base-active: var(--ds-color-base-active);
1688
- --color-base-contrast-subtle: var(--ds-color-base-contrast-subtle);
1689
- --color-base-contrast-default: var(--ds-color-base-contrast-default);
1690
- }`;
1691
- return `@theme {${tailwind.map((str) => `
1692
- ${str};`).join("")}
1693
- }
1694
- ${dynamicColors}`;
1695
- };
1696
-
1697
- // src/tokens/process/output/theme.ts
1698
- import pc5 from "picocolors";
1699
- import * as R16 from "ramda";
1700
- var defaultFileHeader2 = `build: v${package_default.version}`;
1701
- var getFileNameWithoutExtension = (path2) => {
1702
- const pathSegments = path2.split("/");
1703
- return pathSegments[pathSegments.length - 1].split(".").slice(0, -1).join(".");
1704
- };
1705
- var createThemeCSSFiles = ({
1706
- processedBuilds,
1707
- fileHeader = defaultFileHeader2
1708
- }) => {
1709
- const groupedByTheme = {};
1710
- for (const [_, buildResults] of Object.entries(processedBuilds)) {
1711
- for (const buildResult of buildResults) {
1712
- const themeName = buildResult.permutation.theme;
1713
- const newOutputs = buildResult.formatted;
1714
- if (R16.isNotEmpty(newOutputs)) {
1715
- const currentOutputs = groupedByTheme[themeName] ?? [];
1716
- groupedByTheme[themeName] = R16.concat(currentOutputs, newOutputs);
1717
- }
1718
- }
1719
- }
1720
- const sortOrder = [
1721
- "size-mode/",
1722
- "type-scale",
1723
- "color-scheme/light",
1724
- "typography/secondary",
1725
- "size",
1726
- "semantic",
1727
- "color-scheme/dark",
1728
- "color-scheme/contrast",
1729
- "typography/primary",
1730
- "color/"
1731
- ];
1732
- const sortByDefinedOrder = R16.sortBy((file) => {
1733
- const filePath = file.destination || "";
1734
- const sortIndex = sortOrder.findIndex((sortElement) => {
1735
- if (sortElement.endsWith("/")) {
1736
- return filePath.includes(sortElement);
1737
- }
1738
- return filePath.includes(`${sortElement}.css`);
1739
- });
1740
- if (sortIndex === -1) {
1741
- console.error(
1742
- pc5.yellow(`WARNING: CSS section does not have a defined sort order: ${filePath.replace(".css", "")}`)
1743
- );
1744
- console.log(
1745
- pc5.dim(
1746
- `
1747
- The section will currently be added to the end of the entry file, but the exact
1748
- order may change due to nondeterminism.`.trim()
1749
- )
1750
- );
1751
- return Infinity;
1752
- }
1753
- return sortIndex;
1754
- });
1755
- const header = `@charset "UTF-8";
1756
- /*
1757
- ${fileHeader}
1758
- */
1759
-
1760
- `;
1761
- const sortAlphabetically = R16.sort(R16.ascend((x) => x.destination || ""));
1762
- const sortBySize = R16.sortBy(
1763
- R16.pipe((s) => getFileNameWithoutExtension(s.destination ?? ""), sizeComparator)
1764
- );
1765
- const pickOutputs = R16.map(R16.view(R16.lensProp("output")));
1766
- const themeCSSFile = R16.pipe(
1767
- sortAlphabetically,
1768
- sortBySize,
1769
- sortByDefinedOrder,
1770
- pickOutputs,
1771
- R16.join("\n"),
1772
- (content) => header + content
1773
- );
1774
- const themeCSSFiles = Object.entries(groupedByTheme).map(([theme, files]) => ({
1775
- destination: `${theme}.css`,
1776
- output: themeCSSFile(files)
1777
- }));
1778
- return themeCSSFiles;
1779
- };
1780
-
1781
- // src/tokens/build.ts
1782
- var buildTokens = async (options) => {
1783
- const tokensDir = options.tokensDir;
1784
- const $themes = JSON.parse(await dsfs.readFile(`${tokensDir}/$themes.json`));
1785
- const processed$themes = $themes.map(processThemeObject);
1786
- let $designsystemet;
1787
- try {
1788
- const $designsystemetContent = await dsfs.readFile(`${tokensDir}/$designsystemet.jsonc`);
1789
- $designsystemet = JSON.parse($designsystemetContent);
1790
- } catch (_error) {
1791
- }
1792
- console.log(`
1793
- \u{1F3D7}\uFE0F Start building tokens in ${pc6.green(tokensDir)}`);
1794
- const processedBuilds = await processPlatform({
1795
- ...options,
1796
- tokensDir,
1797
- type: "build",
1798
- processed$themes,
1799
- buildTokenFormats: {}
1800
- });
1801
- const fileHeader = R17.join("")([
1802
- defaultFileHeader2,
1803
- $designsystemet ? `
1804
- design-tokens: v${$designsystemet.version}` : ""
1805
- ]);
1806
- let files = [];
1807
- const declarationFiles = createTypeDeclarationFiles(processed$themes);
1808
- const cssFiles = createThemeCSSFiles({ processedBuilds, fileHeader });
1809
- files = [...declarationFiles, ...cssFiles];
1810
- if (options.tailwind) {
1811
- const tailwindFiles = createTailwindCSSFiles(cssFiles);
1812
- files = files.concat(tailwindFiles.filter(Boolean));
1813
- }
1814
- return files;
1815
- };
1816
- export {
1817
- buildTokens
1818
- };
9
+ //#region src/tokens/build.ts
10
+ const buildTokens = async (options) => {
11
+ const tokensDir = options.tokensDir;
12
+ const processed$themes = JSON.parse(await dsfs.readFile(`${tokensDir}/$themes.json`)).map(processThemeObject);
13
+ let $designsystemet;
14
+ try {
15
+ const $designsystemetContent = await dsfs.readFile(`${tokensDir}/$designsystemet.jsonc`);
16
+ $designsystemet = JSON.parse($designsystemetContent);
17
+ } catch (_error) {}
18
+ console.log(`\nšŸ—ļø Start building tokens in ${pc.green(tokensDir)}`);
19
+ const processedBuilds = await processPlatform({
20
+ ...options,
21
+ tokensDir,
22
+ type: "build",
23
+ processed$themes,
24
+ buildTokenFormats: {}
25
+ });
26
+ const fileHeader = R.join("")([defaultFileHeader, $designsystemet ? `\ndesign-tokens: v${$designsystemet.version}` : ""]);
27
+ let files = [];
28
+ const declarationFiles = createTypeDeclarationFiles(processed$themes);
29
+ const cssFiles = createThemeCSSFiles({
30
+ processedBuilds,
31
+ fileHeader
32
+ });
33
+ files = [...declarationFiles, ...cssFiles];
34
+ if (options.tailwind) {
35
+ const tailwindFiles = createTailwindCSSFiles(cssFiles);
36
+ files = files.concat(tailwindFiles.filter(Boolean));
37
+ }
38
+ return files;
39
+ };
40
+ //#endregion
41
+ export { buildTokens };