@recursica/mantine-adapter 0.9.2 → 0.9.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.
package/dist/index.js ADDED
@@ -0,0 +1,917 @@
1
+ import path from 'path';
2
+ import fs from 'fs';
3
+
4
+ /**
5
+ * Type guard function to check if a token is a FontFamilyToken
6
+ *
7
+ * @param token - The token to check
8
+ * @returns True if the token has fontFamily and variableName properties, indicating it's a FontFamilyToken
9
+ */
10
+ function isFontFamilyToken(token) {
11
+ return "fontFamily" in token && "variableName" in token;
12
+ }
13
+ /**
14
+ * Type guard function to check if a token is an EffectToken
15
+ *
16
+ * @param token - The token to check
17
+ * @returns True if the token has effects and variableName properties, indicating it's an EffectToken
18
+ */
19
+ function isEffectToken(token) {
20
+ return "effects" in token && "variableName" in token;
21
+ }
22
+ /**
23
+ * Type guard function to check if a token is a basic Token (color or float)
24
+ *
25
+ * @param token - The token to check
26
+ * @returns True if the token has mode, type, name, and value properties, indicating it's a basic Token
27
+ */
28
+ function isColorOrFloatToken(token) {
29
+ return ("mode" in token && "type" in token && "name" in token && "value" in token);
30
+ }
31
+
32
+ function autoGeneratedFile() {
33
+ return `/* prettier-ignore */
34
+ /* eslint-disable */
35
+ /* tslint:disable */
36
+ /*
37
+ Auto-generated by Recursica.
38
+ Do NOT edit these files directly\n
39
+ For more information about Recursica, go to https://recursica.com
40
+ */
41
+ `;
42
+ }
43
+
44
+ function capitalize(str) {
45
+ return str.replace(/-/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
46
+ }
47
+
48
+ function parseValue(value, recursicaTokens) {
49
+ if (typeof value === "object") {
50
+ if (value.collection === "Tokens") {
51
+ return `${recursicaTokens}["${value.name}"]`;
52
+ }
53
+ if (value.collection === "Themes") {
54
+ return `themeVars["${value.name}"]`;
55
+ }
56
+ }
57
+ else if (!isNaN(Number(value))) {
58
+ return `"${value}"`;
59
+ }
60
+ return `"${value.toString()}"`;
61
+ }
62
+ function generateTypeDefinitions(themeDef) {
63
+ // Extract all unique theme modes from themeDef
64
+ const allThemeModes = new Set();
65
+ Object.values(themeDef).forEach((themeVariants) => {
66
+ Object.keys(themeVariants).forEach((mode) => {
67
+ allThemeModes.add(mode);
68
+ });
69
+ });
70
+ // Generate the ThemeVariant interface dynamically
71
+ const themeVariantProperties = Array.from(allThemeModes)
72
+ .sort() // Sort for consistent output
73
+ .map((mode) => ` ${mode}: string;`)
74
+ .join("\n");
75
+ return `${autoGeneratedFile()}
76
+ import { THEMES } from "./RecursicaThemes";
77
+
78
+ export interface ThemeVariant {
79
+ ${themeVariantProperties}
80
+ }
81
+
82
+ // TypeScript will automatically infer this as a union of literal types
83
+ export type ThemeType = typeof THEMES[keyof typeof THEMES];
84
+
85
+ export type ThemeDictionary = Record<ThemeType, ThemeVariant>;
86
+ `;
87
+ }
88
+ function generateVanillaExtractThemes(tokens, themes, recursicaTokensFilename, { outputPath, project }) {
89
+ const themesContent = [];
90
+ // Contract tokens
91
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
92
+ const themeContractFilename = `Recursica${projectName}ContractTheme.css`;
93
+ const contractThemeOutputPath = outputPath + "/" + `${themeContractFilename}.ts`;
94
+ const contractTokens = {};
95
+ const themeDef = {};
96
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
97
+ for (const [key, theme] of Object.entries(currentTheme)) {
98
+ const currentThemeName = capitalize(rawThemeName);
99
+ const recursicaTokens = `Recursica${projectName}Tokens`;
100
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
101
+ const themeName = `${currentThemeName}${themeKey}Theme`;
102
+ if (!themeDef[currentThemeName]) {
103
+ themeDef[currentThemeName] = {};
104
+ }
105
+ themeDef[currentThemeName][themeKey] = themeName;
106
+ const generatedThemeContent = `${autoGeneratedFile()}
107
+ import { createTheme } from '@vanilla-extract/css';
108
+
109
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
110
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
111
+
112
+ export const ${themeName} = createTheme(themeVars,{
113
+ ${Object.entries(theme)
114
+ .map(([key, value]) => {
115
+ contractTokens[key] = null;
116
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
117
+ })
118
+ .join(",\n\t")},
119
+ ${Object.entries(tokens?.[rawThemeName] ?? {})
120
+ .map(([key, value]) => {
121
+ contractTokens[key] = null;
122
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
123
+ })
124
+ .join(",\n\t")}
125
+ })`;
126
+ themesContent.push({
127
+ name: themeName,
128
+ content: generatedThemeContent,
129
+ });
130
+ }
131
+ }
132
+ let themesFileContent = autoGeneratedFile();
133
+ const vanillaExtractThemes = [];
134
+ for (const theme of themesContent) {
135
+ const themeName = `Recursica${projectName}${theme.name}`;
136
+ const autoGeneratedThemeFilename = `${themeName}.css.ts`;
137
+ const themeFilePath = outputPath + "/" + autoGeneratedThemeFilename;
138
+ vanillaExtractThemes.push({
139
+ content: theme.content,
140
+ path: themeFilePath,
141
+ filename: autoGeneratedThemeFilename,
142
+ });
143
+ // generate a theme.css.ts where we import all the themes using just 1 variables (1 export)
144
+ themesFileContent += `export { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
145
+ themesFileContent += `import { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
146
+ }
147
+ themesFileContent += `\nexport const Themes = {
148
+ ${Object.entries(themeDef)
149
+ .map(([key, value]) => `'${key}': {
150
+ ${Object.entries(value)
151
+ .map(([key, value]) => `'${key}': ${value}`)
152
+ .join(",\n\t\t")}`)
153
+ .join("\n\t},\n\t")}
154
+ }
155
+ }`;
156
+ // create the themes.ts file
157
+ const availableThemesContent = `${autoGeneratedFile()}
158
+ export const AvailableThemes = [${themesContent.map((theme) => `"${theme.name}"`).join(", ")}] as const;
159
+ export type AvailableThemesType = (typeof AvailableThemes)[number];
160
+ `;
161
+ const availableThemesPath = outputPath + "/types.ts";
162
+ const themeContractContent = `${autoGeneratedFile()}
163
+ import { createThemeContract } from '@vanilla-extract/css';
164
+
165
+ export const themeVars = createThemeContract(${JSON.stringify(contractTokens, null, 2)});
166
+ `;
167
+ const themesFilename = `Recursica${projectName}Themes.css.ts`;
168
+ const themesFilePath = outputPath + "/" + themesFilename;
169
+ // Generate type definitions in types.d.ts
170
+ const typeDefinitionsContent = generateTypeDefinitions(themeDef);
171
+ const typesPath = outputPath + "/types.d.ts";
172
+ return {
173
+ typeDefinitions: {
174
+ content: typeDefinitionsContent,
175
+ path: typesPath,
176
+ filename: "types.d.ts",
177
+ },
178
+ themesFileContent: {
179
+ content: themesFileContent,
180
+ path: themesFilePath,
181
+ filename: themesFilename,
182
+ },
183
+ availableThemes: {
184
+ content: availableThemesContent,
185
+ path: availableThemesPath,
186
+ filename: "types.ts",
187
+ },
188
+ vanillaExtractThemes,
189
+ themeContract: {
190
+ content: themeContractContent,
191
+ path: contractThemeOutputPath,
192
+ filename: themeContractFilename,
193
+ },
194
+ contractTokens,
195
+ };
196
+ }
197
+
198
+ function generateRecursicaTokens(baseTokens, { outputPath, project }) {
199
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
200
+ const recursicaTokensFilename = `Recursica${projectName}Tokens.ts`;
201
+ const recursicaTokensPath = outputPath + "/" + recursicaTokensFilename;
202
+ const recursicaTokensContent = `${autoGeneratedFile()}
203
+ export const Recursica${projectName}Tokens = {
204
+ ${Object.entries(baseTokens)
205
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
206
+ .filter(([_, value]) => typeof value === "string")
207
+ .map(([key, value]) => `"${key}": "${value}"`)
208
+ .join(",\n ")}
209
+ };
210
+ `;
211
+ return {
212
+ content: recursicaTokensContent,
213
+ path: recursicaTokensPath,
214
+ filename: recursicaTokensFilename,
215
+ };
216
+ }
217
+
218
+ function generateUiKit(uiKit, { recursicaTokensFilename, themeContractFilename }, { outputPath, project }) {
219
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
220
+ const uiKitFilename = `Recursica${projectName}UiKit.ts`;
221
+ const uiKitPath = outputPath + "/" + uiKitFilename;
222
+ const recursicaTokens = `Recursica${projectName}Tokens`;
223
+ const uiKitContent = `${autoGeneratedFile()}
224
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
225
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
226
+
227
+ export const uiKit = {
228
+ ${Object.entries(uiKit)
229
+ .map(([key, value]) => `'${key}': ${parseValue(value, recursicaTokens)}`)
230
+ .join(",\n\t")}\n\t}`;
231
+ return {
232
+ content: uiKitContent,
233
+ path: uiKitPath,
234
+ filename: uiKitFilename,
235
+ };
236
+ }
237
+
238
+ function parseKey(key) {
239
+ return key.replaceAll("/", "-");
240
+ }
241
+ function generateMantineTheme({ mantineThemeOverride, tokens, breakpoints, contractTokens: { tokens: contractTokens, filename: contractFilename }, exportingProps: { outputPath, project, rootPath }, }) {
242
+ const themeTokens = {
243
+ colors: {},
244
+ radius: {},
245
+ fontSizes: {},
246
+ primaryColor: mantineThemeOverride?.["1-scale"],
247
+ white: mantineThemeOverride?.background,
248
+ };
249
+ for (const [key, value] of Object.entries(tokens)) {
250
+ if (typeof value === "object")
251
+ continue;
252
+ if (key.includes("border-radius")) {
253
+ themeTokens.radius[parseKey(key)] = value;
254
+ }
255
+ if (key.includes("font/size")) {
256
+ themeTokens.fontSizes[parseKey(key)] = `"${value}"`;
257
+ }
258
+ }
259
+ for (const [key] of Object.entries(contractTokens)) {
260
+ if (key.includes("color/") || key.includes("color-on/")) {
261
+ themeTokens.colors[parseKey(key)] = `themeVars['${key}']`;
262
+ }
263
+ if (/font\/(\w+)\/size/.test(key)) {
264
+ themeTokens.fontSizes[parseKey(key)] = `themeVars['${key}']`;
265
+ }
266
+ }
267
+ const postCssFilename = "postcss.config.cjs";
268
+ let postCssContent = `${autoGeneratedFile()}\n`;
269
+ postCssContent += `module.exports = {
270
+ plugins: {
271
+ 'postcss-preset-mantine': {},
272
+ 'postcss-simple-vars': {
273
+ variables: {`;
274
+ for (const [key, value] of Object.entries(breakpoints)) {
275
+ postCssContent += `\n\t\t\t\t'mantine-breakpoint-${key}': '${value}',`;
276
+ }
277
+ postCssContent += `
278
+ }
279
+ }
280
+ }
281
+ }`;
282
+ const postCssFileContent = {
283
+ content: postCssContent,
284
+ path: rootPath ? rootPath + "/" + postCssFilename : postCssFilename,
285
+ filename: postCssFilename,
286
+ };
287
+ const fileContent = `${autoGeneratedFile()}
288
+ import { colorsTuple, createTheme } from '@mantine/core'
289
+ import { themeVars } from './${contractFilename.replace(".ts", "")}'
290
+
291
+ export const mantineTheme = createTheme({
292
+ ${themeTokens.primaryColor ? `primaryColor: ${themeTokens.primaryColor},` : ""}
293
+ ${themeTokens.white ? `white: ${themeTokens.white},` : ""}
294
+ breakpoints: {
295
+ ${Object.entries(breakpoints)
296
+ .map(([key, value]) => `'${key}': '${value}'`)
297
+ .join(",\n\t\t")}
298
+ },
299
+ colors: {
300
+ ${Object.entries(themeTokens.colors)
301
+ .map(([key, value]) => `"${key}": colorsTuple(${value})`)
302
+ .join(",\n\t\t")}
303
+ },
304
+ radius: {
305
+ ${Object.entries(themeTokens.radius)
306
+ .map(([key, value]) => `"${key}": "${value}"`)
307
+ .join(",\n\t\t")}
308
+ },
309
+ fontSizes: {
310
+ ${Object.entries(themeTokens.fontSizes)
311
+ .map(([key, value]) => `"${key}": ${value}`)
312
+ .join(",\n\t\t")}
313
+ }
314
+ })`;
315
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
316
+ const filename = `Recursica${projectName}MantineTheme.ts`;
317
+ const mantineThemeFileContent = {
318
+ content: fileContent,
319
+ path: outputPath + "/" + filename,
320
+ filename,
321
+ };
322
+ return { mantineTheme: mantineThemeFileContent, postCss: postCssFileContent };
323
+ }
324
+
325
+ function createRecursicaObject(project, outputPath) {
326
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
327
+ const tokens = `Recursica${projectName}Tokens`;
328
+ const contract = `Recursica${projectName}ContractTheme`;
329
+ const uiKit = `Recursica${projectName}UiKit`;
330
+ const recursicaObjectContent = `${autoGeneratedFile()}
331
+ import { ${tokens} } from './${tokens}';
332
+ import { themeVars } from './${contract}.css';
333
+ import { uiKit } from './${uiKit}';
334
+
335
+ export const recursica = {
336
+ ...uiKit,
337
+ ...themeVars,
338
+ ...${tokens},
339
+ }
340
+ `;
341
+ return {
342
+ content: recursicaObjectContent,
343
+ path: outputPath + "/Recursica.ts",
344
+ filename: "Recursica.ts",
345
+ };
346
+ }
347
+
348
+ function generateColorsType(colorTokens, outputPath) {
349
+ const colorsType = `${autoGeneratedFile()}
350
+ export type RecursicaColors = \n\t"${colorTokens.join('" |\n\t"')}";\n`;
351
+ return {
352
+ content: colorsType,
353
+ path: `${outputPath}/RecursicaColorsType.ts`,
354
+ filename: "RecursicaColorsType.ts",
355
+ };
356
+ }
357
+
358
+ function generateIcons(icons, srcPath, config) {
359
+ let iconsPath;
360
+ if (!config?.output) {
361
+ iconsPath = srcPath + "/components" + "/Icons";
362
+ }
363
+ else {
364
+ iconsPath = srcPath + "/" + config.output;
365
+ }
366
+ const svgPath = iconsPath + "/Svg";
367
+ const exportedIcons = [];
368
+ // Generate svg files
369
+ for (const [rawIconName, iconPath] of Object.entries(icons)) {
370
+ const [iconName, variant] = rawIconName.split("[");
371
+ let cleanIconName = iconName.replaceAll("-", "_");
372
+ // check if the iconName is in the names array, if not, skip
373
+ if (!config?.include?.names?.includes(cleanIconName)) {
374
+ continue;
375
+ }
376
+ // detect if the iconName starts with a number, if so, add an underscore to the beginning
377
+ if (cleanIconName.match(/^\d/)) {
378
+ cleanIconName = `_${cleanIconName}`;
379
+ }
380
+ const cleanVariant = variant.replace("]", "").replace("Style=", "");
381
+ const codedVariant = cleanVariant.replaceAll(" ", "_");
382
+ // check if the codedVariant is in the variants array, if not, skip
383
+ if (!config?.include?.variants?.includes(codedVariant)) {
384
+ continue;
385
+ }
386
+ const finalIconName = `${cleanIconName}_${codedVariant}`;
387
+ exportedIcons.push({
388
+ content: iconPath
389
+ .replaceAll('fill="black"', "")
390
+ .replaceAll('fill="none"', ""),
391
+ path: `${svgPath}/${finalIconName}.svg`,
392
+ filename: `${finalIconName}`,
393
+ });
394
+ }
395
+ // Generate icon exports file
396
+ const exportsPath = iconsPath + "/icon_exports.ts";
397
+ let exportsContent = `${autoGeneratedFile()}
398
+ /// <reference types="vite-plugin-svgr/client" />\n`;
399
+ for (const icon of exportedIcons) {
400
+ exportsContent += `import ${icon.filename} from './Svg/${icon.filename}.svg?react';\n`;
401
+ exportsContent += `export { ${icon.filename} };\n`;
402
+ }
403
+ // Generate icon map file
404
+ const mapPath = iconsPath + "/icon_resource_map.ts";
405
+ let mapContent = `${autoGeneratedFile()}\nimport * as IconExports from './icon_exports';\n\n`;
406
+ mapContent += "export const IconResourceMap = {";
407
+ mapContent += exportedIcons
408
+ .map((icon) => `\n\t'${icon.filename}': IconExports.${icon.filename},`)
409
+ .join("");
410
+ mapContent += "\n};\n";
411
+ return {
412
+ exportedIcons,
413
+ iconExports: {
414
+ content: exportsContent,
415
+ path: exportsPath,
416
+ filename: "icon_exports.ts",
417
+ },
418
+ iconResourceMap: {
419
+ content: mapContent,
420
+ path: mapPath,
421
+ filename: "icon_resource_map.ts",
422
+ },
423
+ };
424
+ }
425
+
426
+ function generateSpacersType(spacerTokens, outputPath) {
427
+ const spacersType = `${autoGeneratedFile()}
428
+ export type RecursicaSpacersType = \n\t"${spacerTokens.join('" |\n\t"')}";\n`;
429
+ return {
430
+ content: spacersType,
431
+ path: `${outputPath}/RecursicaSpacersType.ts`,
432
+ filename: "RecursicaSpacersType.ts",
433
+ };
434
+ }
435
+
436
+ function generateBorderRadiusType(borderRadius, outputPath) {
437
+ const borderRadiusTypeContent = `${autoGeneratedFile()}
438
+ export type RecursicaBorderRadiusType = ${borderRadius
439
+ .map((key) => `'${key}'`)
440
+ .join(" | ")};
441
+ `;
442
+ return {
443
+ content: borderRadiusTypeContent,
444
+ path: `${outputPath}/RecursicaBorderRadiusType.ts`,
445
+ filename: "RecursicaBorderRadiusType.ts",
446
+ };
447
+ }
448
+
449
+ /**
450
+ * Generates the RecursicaThemes.ts file that contains the THEMES constant
451
+ * based on the theme dictionary
452
+ */
453
+ function generateRecursicaThemes({ outputPath, themes, }) {
454
+ const themeDef = {};
455
+ // Build themeDef object similar to generateVanillaExtractThemes
456
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
457
+ for (const [key] of Object.entries(currentTheme)) {
458
+ const currentThemeName = capitalize(rawThemeName);
459
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
460
+ themeDef[currentThemeName] ?? (themeDef[currentThemeName] = {});
461
+ themeDef[currentThemeName][themeKey] = currentThemeName;
462
+ }
463
+ }
464
+ const content = `/* prettier-ignore */
465
+ /* eslint-disable */
466
+ /* tslint:disable */
467
+ /*
468
+ Auto-generated by Recursica.
469
+ Do NOT edit these files directly
470
+
471
+ For more information about Recursica, go to https://recursica.com
472
+ */
473
+
474
+ // Auto-generated THEMES constant from ThemeType
475
+ export const THEMES = {
476
+ ${Object.entries(themeDef)
477
+ .map(([key]) => ` ${key}: '${key}'`)
478
+ .join(",\n")}
479
+ } as const;
480
+ `;
481
+ return {
482
+ content,
483
+ path: outputPath + "/RecursicaThemes.ts",
484
+ filename: "RecursicaThemes.ts",
485
+ };
486
+ }
487
+
488
+ function generatePrettierignore() {
489
+ return {
490
+ filename: ".prettierignore",
491
+ path: ".prettierignore",
492
+ content: `recursica/
493
+ recursica.json
494
+ recursica-bundle.json
495
+ recursica-icons.json
496
+ icon_exports.ts
497
+ icon_resource_map.ts`,
498
+ };
499
+ }
500
+
501
+ function runAdapter({ rootPath, overrides, srcPath, project, icons, iconsConfig, processTokens, }) {
502
+ const outputPath = srcPath + "/recursica";
503
+ const recursicaTokens = generateRecursicaTokens(processTokens.tokens, {
504
+ outputPath,
505
+ project,
506
+ });
507
+ const vanillaExtractThemes = generateVanillaExtractThemes(processTokens.tokens, processTokens.themes, recursicaTokens.filename, {
508
+ outputPath,
509
+ project,
510
+ });
511
+ const mantineTheme = generateMantineTheme({
512
+ mantineThemeOverride: overrides?.mantineTheme,
513
+ tokens: processTokens.tokens,
514
+ breakpoints: processTokens.breakpoints,
515
+ contractTokens: {
516
+ tokens: vanillaExtractThemes.contractTokens,
517
+ filename: vanillaExtractThemes.themeContract.filename,
518
+ },
519
+ exportingProps: {
520
+ outputPath,
521
+ project,
522
+ rootPath,
523
+ },
524
+ });
525
+ const uiKitObject = generateUiKit(processTokens.uiKit, {
526
+ recursicaTokensFilename: recursicaTokens.filename,
527
+ themeContractFilename: vanillaExtractThemes.themeContract.filename,
528
+ }, { outputPath, project });
529
+ const recursicaObject = createRecursicaObject(project, outputPath);
530
+ const colorsType = generateColorsType(processTokens.colors, outputPath);
531
+ const spacersType = generateSpacersType(processTokens.spacers, outputPath);
532
+ const borderRadiusType = generateBorderRadiusType(processTokens.borderRadius, outputPath);
533
+ let iconsObject;
534
+ if (icons) {
535
+ iconsObject = generateIcons(icons, srcPath, iconsConfig);
536
+ }
537
+ const recursicaThemes = generateRecursicaThemes({
538
+ outputPath,
539
+ themes: processTokens.themes,
540
+ });
541
+ const prettierignore = generatePrettierignore();
542
+ const fileContents = {
543
+ recursicaTokens,
544
+ vanillaExtractThemes,
545
+ mantineTheme,
546
+ uiKitObject,
547
+ recursicaObject,
548
+ colorsType,
549
+ spacersType,
550
+ borderRadiusType,
551
+ iconsObject,
552
+ recursicaThemes,
553
+ prettierignore,
554
+ };
555
+ return fileContents;
556
+ }
557
+
558
+ /**
559
+ * Checks if a given directory contains files with either theme-tokens or ui-kit suffix
560
+ * @param directoryPath - The path to check for files
561
+ * @returns FileCheckResult - Object containing boolean result and array of matching files with full paths
562
+ */
563
+ function hasThemeOrKitFiles(directoryPath) {
564
+ try {
565
+ const files = fs.readdirSync(directoryPath);
566
+ const matchingFiles = files.find((file) => {
567
+ const fileName = file.toLowerCase();
568
+ return fileName === "recursica-bundle.json";
569
+ });
570
+ return matchingFiles ? path.join(directoryPath, matchingFiles) : undefined;
571
+ }
572
+ catch (error) {
573
+ console.error(`Error checking directory ${directoryPath}:`, error);
574
+ return undefined;
575
+ }
576
+ }
577
+ function hasIconsJsonFiles(directoryPath) {
578
+ try {
579
+ const files = fs.readdirSync(directoryPath);
580
+ const matchingFiles = files
581
+ .filter((file) => {
582
+ const fileName = file.toLowerCase();
583
+ return fileName === "recursica-icons.json";
584
+ })
585
+ .map((file) => path.join(directoryPath, file));
586
+ return matchingFiles.length > 0 ? matchingFiles[0] : undefined;
587
+ }
588
+ catch (error) {
589
+ console.error(`Error checking directory ${directoryPath}:`, error);
590
+ return undefined;
591
+ }
592
+ }
593
+
594
+ /**
595
+ * Loads and validates the configuration from recursicaConfig.json
596
+ *
597
+ * @throws {Error} If the config file is not found or required fields are missing
598
+ * @returns {Object} Configuration object with the following properties:
599
+ * - jsons: Path to the themes-tokens and ui-kit directories
600
+ * - srcPath: Path to the source directory
601
+ * - project: Project name
602
+ */
603
+ function loadConfig() {
604
+ let rootPath = getRootPath();
605
+ const configPath = path.join(rootPath, "recursica.json");
606
+ if (!fs.existsSync(configPath)) {
607
+ throw new Error("Config file not found at: " + configPath);
608
+ }
609
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
610
+ if (typeof config.project === "object" && config.project?.root) {
611
+ rootPath = path.join(rootPath, config.project.root);
612
+ }
613
+ const bundledJson = hasThemeOrKitFiles(rootPath);
614
+ const iconsJson = hasIconsJsonFiles(rootPath);
615
+ const project = config.project;
616
+ if (!project) {
617
+ throw new Error("project is required in config file");
618
+ }
619
+ return {
620
+ rootPath,
621
+ srcPath: path.join(rootPath, "src"),
622
+ project,
623
+ bundledJson,
624
+ iconsJson,
625
+ overrides: config.overrides,
626
+ iconsConfig: config.icons,
627
+ };
628
+ }
629
+ function getRootPath() {
630
+ // recursively search for the package.json file starting from the current working directory
631
+ let currentDir = process.cwd();
632
+ let level = 0;
633
+ while (!fs.existsSync(path.join(currentDir, "recursica.json"))) {
634
+ currentDir = path.join(currentDir, "..");
635
+ level++;
636
+ if (level > 10) {
637
+ throw new Error("Could not find recursica.json");
638
+ }
639
+ }
640
+ return currentDir;
641
+ }
642
+
643
+ class ProcessTokens {
644
+ constructor(overrides) {
645
+ this.tokens = {};
646
+ this.themes = {};
647
+ this.breakpoints = {};
648
+ this.colors = [];
649
+ this.spacers = [];
650
+ this.borderRadius = [];
651
+ this.uiKit = {};
652
+ this.processValue = (target, token) => {
653
+ if (typeof token.value === "string") {
654
+ target[token.name] = token.value;
655
+ return true;
656
+ }
657
+ if (typeof token.value === "number") {
658
+ target[token.name] = `${token.value}px`;
659
+ return true;
660
+ }
661
+ if (typeof token.value === "object") {
662
+ target[token.name] = token.value;
663
+ return true;
664
+ }
665
+ return false;
666
+ };
667
+ this.overrides = overrides;
668
+ }
669
+ processTokenValue(token, modeName, jsonThemeName) {
670
+ if (token.collection === "Breakpoints") {
671
+ this.processValue(this.breakpoints, token);
672
+ // Add breakpoints to uiKit with 'breakpoints/' prefix
673
+ const uiKitTarget = {};
674
+ this.processValue(uiKitTarget, token);
675
+ Object.entries(uiKitTarget).forEach(([key, value]) => {
676
+ // Ensure we only store string values
677
+ if (typeof value === "string") {
678
+ this.uiKit[`breakpoint/${key}`] = value;
679
+ }
680
+ else if (typeof value === "number") {
681
+ this.uiKit[`breakpoint/${key}`] = `${value.toString()}px`;
682
+ }
683
+ });
684
+ }
685
+ else if (token.collection === "UI Kit") {
686
+ this.processValue(this.uiKit, token);
687
+ }
688
+ else if (token.collection === "Tokens") {
689
+ this.processValue(this.tokens, token);
690
+ }
691
+ else {
692
+ if (!jsonThemeName)
693
+ return;
694
+ if (!this.themes[jsonThemeName])
695
+ this.themes[jsonThemeName] = {};
696
+ if (!this.themes[jsonThemeName][modeName])
697
+ this.themes[jsonThemeName][modeName] = {};
698
+ this.processValue(this.themes[jsonThemeName][modeName], token);
699
+ }
700
+ }
701
+ processTokens(variables, jsonThemeName) {
702
+ // Process tokens collection
703
+ for (const token of Object.values(variables)) {
704
+ if (isFontFamilyToken(token)) {
705
+ if (!jsonThemeName)
706
+ continue;
707
+ if (!this.tokens[jsonThemeName])
708
+ this.tokens[jsonThemeName] = {};
709
+ if (typeof this.tokens[jsonThemeName] !== "object")
710
+ this.tokens[jsonThemeName] = {};
711
+ this.tokens[jsonThemeName][`typography/${token.variableName}`] =
712
+ this.overrides?.fontFamily?.[token.fontFamily] ?? token.fontFamily;
713
+ this.tokens[jsonThemeName][`typography/${token.variableName}-size`] =
714
+ `${token.fontSize.toString()}px`;
715
+ // check if overrides.fontWeight is defined
716
+ if (this.overrides?.fontWeight) {
717
+ const weight = this.overrides.fontWeight.find((weight) => weight.alias === token.fontWeight.alias &&
718
+ weight.fontFamily === token.fontFamily);
719
+ // check if there's a weight that matches the alias and fontFamily
720
+ // if there is, use the value from the overrides
721
+ // if there isn't, use the value from the token
722
+ if (weight) {
723
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = weight.value.toString();
724
+ }
725
+ else {
726
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
727
+ }
728
+ }
729
+ else {
730
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
731
+ }
732
+ if (token.lineHeight.unit === "PERCENT") {
733
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = `${token.lineHeight.value.toString()}%`;
734
+ }
735
+ else {
736
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = "1.2";
737
+ }
738
+ this.tokens[jsonThemeName][`typography/${token.variableName}-letter-spacing`] =
739
+ token.letterSpacing.unit === "PIXELS"
740
+ ? `${token.letterSpacing.value.toString()}px`
741
+ : `${token.letterSpacing.value.toString()}%`;
742
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-case`] = token.textCase;
743
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-decoration`] = token.textDecoration;
744
+ continue;
745
+ }
746
+ if (isEffectToken(token)) {
747
+ const effectValue = [];
748
+ token.effects.forEach((effect) => {
749
+ const { color: { r, g, b, a }, offset: { x, y }, radius, spread, } = effect;
750
+ effectValue.push(`${x.toString()}px ${y.toString()}px ${radius.toString()}px ${spread.toString()}px rgba(${r.toString()}, ${g.toString()}, ${b.toString()}, ${a.toString()})`);
751
+ });
752
+ this.tokens[`effect/${token.variableName}`] = effectValue.join(", ");
753
+ continue;
754
+ }
755
+ if (isColorOrFloatToken(token)) {
756
+ const modeName = capitalize(token.mode)
757
+ .replace(/[()/]/g, "-")
758
+ .replace(/\s/g, "")
759
+ .replace(/-$/, "");
760
+ if (modeName !== "mode1")
761
+ this.themes[modeName] = {};
762
+ if (token.type === "color" && !this.colors.includes(token.name)) {
763
+ this.colors.push(token.name);
764
+ }
765
+ if (token.name.startsWith("size/spacer/") &&
766
+ !this.spacers.includes(token.name)) {
767
+ this.spacers.push(token.name);
768
+ }
769
+ if (token.name.startsWith("size/border-radius/") &&
770
+ !this.borderRadius.includes(token.name)) {
771
+ this.borderRadius.push(token.name);
772
+ }
773
+ this.processTokenValue(token, modeName, jsonThemeName);
774
+ }
775
+ else {
776
+ console.warn(`${JSON.stringify(token, null, 2)} could not be processed`);
777
+ }
778
+ }
779
+ }
780
+ }
781
+
782
+ /**
783
+ * Processes JSON content and creates ProcessTokens instance
784
+ * This is shared logic between CLI and WebWorker
785
+ */
786
+ function processJsonContent(jsonFileContent, { project, overrides }) {
787
+ const jsonContent = JSON.parse(jsonFileContent);
788
+ const jsonProjectId = jsonContent.projectId;
789
+ if (!jsonProjectId) {
790
+ throw new Error("project-id is required in the json file");
791
+ }
792
+ if (jsonProjectId.toLowerCase() !==
793
+ (typeof project === "string"
794
+ ? project.toLowerCase()
795
+ : project.name?.toLowerCase())) {
796
+ throw new Error("project-id does not match the project in the config file");
797
+ }
798
+ const processTokens = new ProcessTokens(overrides);
799
+ processTokens.processTokens(jsonContent.tokens);
800
+ for (const theme of Object.keys(jsonContent.themes)) {
801
+ processTokens.processTokens(jsonContent.themes[theme], theme);
802
+ }
803
+ processTokens.processTokens(jsonContent.uiKit);
804
+ return processTokens;
805
+ }
806
+ /**
807
+ * Processes icons JSON content and returns icons object
808
+ * This is shared logic between CLI and WebWorker
809
+ */
810
+ function processIcons(iconsJsonContent) {
811
+ const icons = {};
812
+ const iconsJsonParsed = JSON.parse(iconsJsonContent);
813
+ for (const [iconName, iconPath] of Object.entries(iconsJsonParsed)) {
814
+ icons[iconName] = iconPath;
815
+ }
816
+ return icons;
817
+ }
818
+ /**
819
+ * Core adapter processing logic shared between CLI and WebWorker
820
+ * This function handles the main processing workflow
821
+ */
822
+ function processAdapter({ rootPath, bundledJsonContent, project, overrides, srcPath, iconsJsonContent, iconsConfig, }) {
823
+ let icons = {};
824
+ // Process icons if provided
825
+ if (iconsJsonContent) {
826
+ icons = processIcons(iconsJsonContent);
827
+ }
828
+ if (!bundledJsonContent) {
829
+ throw new Error("bundledJson content not found");
830
+ }
831
+ // Process the main JSON content
832
+ const processTokens = processJsonContent(bundledJsonContent, {
833
+ project,
834
+ overrides,
835
+ });
836
+ // Run the adapter
837
+ const files = runAdapter({
838
+ rootPath,
839
+ overrides,
840
+ srcPath,
841
+ icons,
842
+ processTokens,
843
+ project,
844
+ iconsConfig,
845
+ });
846
+ return files;
847
+ }
848
+
849
+ /**
850
+ * Main CLI function that can be called programmatically
851
+ * This is the same logic as main.ts but exported as a function
852
+ */
853
+ async function runMain() {
854
+ try {
855
+ const { rootPath, bundledJson, srcPath, project, iconsJson, overrides, iconsConfig, } = loadConfig();
856
+ if (!bundledJson)
857
+ throw new Error("bundledJson not found");
858
+ // Read file contents
859
+ const bundledJsonContent = fs.readFileSync(bundledJson, "utf-8");
860
+ const iconsJsonContent = iconsJson
861
+ ? fs.readFileSync(iconsJson, "utf-8")
862
+ : undefined;
863
+ // Use shared processing logic
864
+ const files = processAdapter({
865
+ bundledJsonContent,
866
+ project,
867
+ overrides,
868
+ rootPath,
869
+ srcPath,
870
+ iconsJsonContent,
871
+ iconsConfig,
872
+ });
873
+ const { recursicaTokens, vanillaExtractThemes, mantineTheme, uiKitObject, recursicaObject, colorsType, iconsObject, spacersType, borderRadiusType, recursicaThemes, prettierignore, } = files;
874
+ const filesToWrite = [
875
+ recursicaTokens,
876
+ vanillaExtractThemes.availableThemes,
877
+ vanillaExtractThemes.themeContract,
878
+ vanillaExtractThemes.themesFileContent,
879
+ vanillaExtractThemes.typeDefinitions,
880
+ mantineTheme.mantineTheme,
881
+ mantineTheme.postCss,
882
+ uiKitObject,
883
+ recursicaObject,
884
+ colorsType,
885
+ spacersType,
886
+ borderRadiusType,
887
+ recursicaThemes,
888
+ prettierignore,
889
+ ];
890
+ // check if src/recursica folder exists, if not create it
891
+ const outputPath = srcPath + "/recursica";
892
+ if (!fs.existsSync(outputPath)) {
893
+ fs.mkdirSync(outputPath);
894
+ }
895
+ for (const file of filesToWrite) {
896
+ fs.writeFileSync(file.path, file.content);
897
+ }
898
+ for (const theme of vanillaExtractThemes.vanillaExtractThemes) {
899
+ fs.writeFileSync(theme.path, theme.content);
900
+ }
901
+ if (iconsObject) {
902
+ fs.writeFileSync(iconsObject.iconExports.path, iconsObject.iconExports.content);
903
+ fs.writeFileSync(iconsObject.iconResourceMap.path, iconsObject.iconResourceMap.content);
904
+ for (const icon of iconsObject.exportedIcons) {
905
+ fs.writeFileSync(icon.path, icon.content);
906
+ }
907
+ }
908
+ console.log("Theme generated successfully");
909
+ }
910
+ catch (error) {
911
+ console.error("Error generating theme:", error);
912
+ throw error;
913
+ }
914
+ }
915
+
916
+ export { ProcessTokens, capitalize, isColorOrFloatToken, isEffectToken, isFontFamilyToken, loadConfig, processJsonContent, runAdapter, runMain };
917
+ //# sourceMappingURL=index.js.map