@recursica/mantine-adapter 0.9.2 → 0.9.4

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 (48) hide show
  1. package/dist/adapter/generateBorderRadiusType.d.ts +3 -0
  2. package/dist/adapter/generateBorderRadiusType.d.ts.map +1 -0
  3. package/dist/adapter/generateColorTypes.d.ts +6 -0
  4. package/dist/adapter/generateColorTypes.d.ts.map +1 -0
  5. package/dist/adapter/generateIcons.d.ts +8 -0
  6. package/dist/adapter/generateIcons.d.ts.map +1 -0
  7. package/dist/adapter/generateMantineTheme.d.ts +19 -0
  8. package/dist/adapter/generateMantineTheme.d.ts.map +1 -0
  9. package/dist/adapter/generatePrettierignore.d.ts +3 -0
  10. package/dist/adapter/generatePrettierignore.d.ts.map +1 -0
  11. package/dist/adapter/generateRecursicaObject.d.ts +7 -0
  12. package/dist/adapter/generateRecursicaObject.d.ts.map +1 -0
  13. package/dist/adapter/generateRecursicaThemes.d.ts +12 -0
  14. package/dist/adapter/generateRecursicaThemes.d.ts.map +1 -0
  15. package/dist/adapter/generateRecursicaTokens.d.ts +3 -0
  16. package/dist/adapter/generateRecursicaTokens.d.ts.map +1 -0
  17. package/dist/adapter/generateSpacersType.d.ts +3 -0
  18. package/dist/adapter/generateSpacersType.d.ts.map +1 -0
  19. package/dist/adapter/generateUiKit.d.ts +8 -0
  20. package/dist/adapter/generateUiKit.d.ts.map +1 -0
  21. package/dist/adapter/generateVanillaExtractThemes.d.ts +12 -0
  22. package/dist/adapter/generateVanillaExtractThemes.d.ts.map +1 -0
  23. package/dist/adapter/index.d.ts +44 -0
  24. package/dist/adapter/index.d.ts.map +1 -0
  25. package/dist/cli.d.ts +6 -0
  26. package/dist/cli.d.ts.map +1 -0
  27. package/dist/index.d.ts +8 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +921 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/main.cjs +928 -0
  32. package/dist/main.cjs.map +1 -0
  33. package/dist/main.d.ts +2 -0
  34. package/dist/main.d.ts.map +1 -0
  35. package/dist/main.js +926 -0
  36. package/dist/main.js.map +1 -0
  37. package/dist/shared/processTokens.d.ts +22 -0
  38. package/dist/shared/processTokens.d.ts.map +1 -0
  39. package/dist/types.d.ts +62 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/utils/fileCheck.d.ts +8 -0
  42. package/dist/utils/fileCheck.d.ts.map +1 -0
  43. package/dist/utils/loadConfig.d.ts +24 -0
  44. package/dist/utils/loadConfig.d.ts.map +1 -0
  45. package/dist/webworker.d.ts +2 -0
  46. package/dist/webworker.d.ts.map +1 -0
  47. package/dist/webworker.js +791 -0
  48. package/package.json +1 -1
package/dist/index.js ADDED
@@ -0,0 +1,921 @@
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) {
374
+ if (!config?.include?.names?.includes(cleanIconName)) {
375
+ continue;
376
+ }
377
+ }
378
+ // detect if the iconName starts with a number, if so, add an underscore to the beginning
379
+ if (cleanIconName.match(/^\d/)) {
380
+ cleanIconName = `_${cleanIconName}`;
381
+ }
382
+ const cleanVariant = variant.replace("]", "").replace("Style=", "");
383
+ const codedVariant = cleanVariant.replaceAll(" ", "_");
384
+ // check if the codedVariant is in the variants array, if not, skip
385
+ if (config?.include) {
386
+ if (!config?.include?.variants?.includes(codedVariant)) {
387
+ continue;
388
+ }
389
+ }
390
+ const finalIconName = `${cleanIconName}_${codedVariant}`;
391
+ exportedIcons.push({
392
+ content: iconPath
393
+ .replaceAll('fill="black"', "")
394
+ .replaceAll('fill="none"', ""),
395
+ path: `${svgPath}/${finalIconName}.svg`,
396
+ filename: `${finalIconName}`,
397
+ });
398
+ }
399
+ // Generate icon exports file
400
+ const exportsPath = iconsPath + "/icon_exports.ts";
401
+ let exportsContent = `${autoGeneratedFile()}
402
+ /// <reference types="vite-plugin-svgr/client" />\n`;
403
+ for (const icon of exportedIcons) {
404
+ exportsContent += `import ${icon.filename} from './Svg/${icon.filename}.svg?react';\n`;
405
+ exportsContent += `export { ${icon.filename} };\n`;
406
+ }
407
+ // Generate icon map file
408
+ const mapPath = iconsPath + "/icon_resource_map.ts";
409
+ let mapContent = `${autoGeneratedFile()}\nimport * as IconExports from './icon_exports';\n\n`;
410
+ mapContent += "export const IconResourceMap = {";
411
+ mapContent += exportedIcons
412
+ .map((icon) => `\n\t'${icon.filename}': IconExports.${icon.filename},`)
413
+ .join("");
414
+ mapContent += "\n};\n";
415
+ return {
416
+ exportedIcons,
417
+ iconExports: {
418
+ content: exportsContent,
419
+ path: exportsPath,
420
+ filename: "icon_exports.ts",
421
+ },
422
+ iconResourceMap: {
423
+ content: mapContent,
424
+ path: mapPath,
425
+ filename: "icon_resource_map.ts",
426
+ },
427
+ };
428
+ }
429
+
430
+ function generateSpacersType(spacerTokens, outputPath) {
431
+ const spacersType = `${autoGeneratedFile()}
432
+ export type RecursicaSpacersType = \n\t"${spacerTokens.join('" |\n\t"')}";\n`;
433
+ return {
434
+ content: spacersType,
435
+ path: `${outputPath}/RecursicaSpacersType.ts`,
436
+ filename: "RecursicaSpacersType.ts",
437
+ };
438
+ }
439
+
440
+ function generateBorderRadiusType(borderRadius, outputPath) {
441
+ const borderRadiusTypeContent = `${autoGeneratedFile()}
442
+ export type RecursicaBorderRadiusType = ${borderRadius
443
+ .map((key) => `'${key}'`)
444
+ .join(" | ")};
445
+ `;
446
+ return {
447
+ content: borderRadiusTypeContent,
448
+ path: `${outputPath}/RecursicaBorderRadiusType.ts`,
449
+ filename: "RecursicaBorderRadiusType.ts",
450
+ };
451
+ }
452
+
453
+ /**
454
+ * Generates the RecursicaThemes.ts file that contains the THEMES constant
455
+ * based on the theme dictionary
456
+ */
457
+ function generateRecursicaThemes({ outputPath, themes, }) {
458
+ const themeDef = {};
459
+ // Build themeDef object similar to generateVanillaExtractThemes
460
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
461
+ for (const [key] of Object.entries(currentTheme)) {
462
+ const currentThemeName = capitalize(rawThemeName);
463
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
464
+ themeDef[currentThemeName] ?? (themeDef[currentThemeName] = {});
465
+ themeDef[currentThemeName][themeKey] = currentThemeName;
466
+ }
467
+ }
468
+ const content = `/* prettier-ignore */
469
+ /* eslint-disable */
470
+ /* tslint:disable */
471
+ /*
472
+ Auto-generated by Recursica.
473
+ Do NOT edit these files directly
474
+
475
+ For more information about Recursica, go to https://recursica.com
476
+ */
477
+
478
+ // Auto-generated THEMES constant from ThemeType
479
+ export const THEMES = {
480
+ ${Object.entries(themeDef)
481
+ .map(([key]) => ` ${key}: '${key}'`)
482
+ .join(",\n")}
483
+ } as const;
484
+ `;
485
+ return {
486
+ content,
487
+ path: outputPath + "/RecursicaThemes.ts",
488
+ filename: "RecursicaThemes.ts",
489
+ };
490
+ }
491
+
492
+ function generatePrettierignore() {
493
+ return {
494
+ filename: ".prettierignore",
495
+ path: ".prettierignore",
496
+ content: `recursica/
497
+ recursica.json
498
+ recursica-bundle.json
499
+ recursica-icons.json
500
+ icon_exports.ts
501
+ icon_resource_map.ts`,
502
+ };
503
+ }
504
+
505
+ function runAdapter({ rootPath, overrides, srcPath, project, icons, iconsConfig, processTokens, }) {
506
+ const outputPath = srcPath + "/recursica";
507
+ const recursicaTokens = generateRecursicaTokens(processTokens.tokens, {
508
+ outputPath,
509
+ project,
510
+ });
511
+ const vanillaExtractThemes = generateVanillaExtractThemes(processTokens.tokens, processTokens.themes, recursicaTokens.filename, {
512
+ outputPath,
513
+ project,
514
+ });
515
+ const mantineTheme = generateMantineTheme({
516
+ mantineThemeOverride: overrides?.mantineTheme,
517
+ tokens: processTokens.tokens,
518
+ breakpoints: processTokens.breakpoints,
519
+ contractTokens: {
520
+ tokens: vanillaExtractThemes.contractTokens,
521
+ filename: vanillaExtractThemes.themeContract.filename,
522
+ },
523
+ exportingProps: {
524
+ outputPath,
525
+ project,
526
+ rootPath,
527
+ },
528
+ });
529
+ const uiKitObject = generateUiKit(processTokens.uiKit, {
530
+ recursicaTokensFilename: recursicaTokens.filename,
531
+ themeContractFilename: vanillaExtractThemes.themeContract.filename,
532
+ }, { outputPath, project });
533
+ const recursicaObject = createRecursicaObject(project, outputPath);
534
+ const colorsType = generateColorsType(processTokens.colors, outputPath);
535
+ const spacersType = generateSpacersType(processTokens.spacers, outputPath);
536
+ const borderRadiusType = generateBorderRadiusType(processTokens.borderRadius, outputPath);
537
+ let iconsObject;
538
+ if (icons) {
539
+ iconsObject = generateIcons(icons, srcPath, iconsConfig);
540
+ }
541
+ const recursicaThemes = generateRecursicaThemes({
542
+ outputPath,
543
+ themes: processTokens.themes,
544
+ });
545
+ const prettierignore = generatePrettierignore();
546
+ const fileContents = {
547
+ recursicaTokens,
548
+ vanillaExtractThemes,
549
+ mantineTheme,
550
+ uiKitObject,
551
+ recursicaObject,
552
+ colorsType,
553
+ spacersType,
554
+ borderRadiusType,
555
+ iconsObject,
556
+ recursicaThemes,
557
+ prettierignore,
558
+ };
559
+ return fileContents;
560
+ }
561
+
562
+ /**
563
+ * Checks if a given directory contains files with either theme-tokens or ui-kit suffix
564
+ * @param directoryPath - The path to check for files
565
+ * @returns FileCheckResult - Object containing boolean result and array of matching files with full paths
566
+ */
567
+ function hasThemeOrKitFiles(directoryPath) {
568
+ try {
569
+ const files = fs.readdirSync(directoryPath);
570
+ const matchingFiles = files.find((file) => {
571
+ const fileName = file.toLowerCase();
572
+ return fileName === "recursica-bundle.json";
573
+ });
574
+ return matchingFiles ? path.join(directoryPath, matchingFiles) : undefined;
575
+ }
576
+ catch (error) {
577
+ console.error(`Error checking directory ${directoryPath}:`, error);
578
+ return undefined;
579
+ }
580
+ }
581
+ function hasIconsJsonFiles(directoryPath) {
582
+ try {
583
+ const files = fs.readdirSync(directoryPath);
584
+ const matchingFiles = files
585
+ .filter((file) => {
586
+ const fileName = file.toLowerCase();
587
+ return fileName === "recursica-icons.json";
588
+ })
589
+ .map((file) => path.join(directoryPath, file));
590
+ return matchingFiles.length > 0 ? matchingFiles[0] : undefined;
591
+ }
592
+ catch (error) {
593
+ console.error(`Error checking directory ${directoryPath}:`, error);
594
+ return undefined;
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Loads and validates the configuration from recursicaConfig.json
600
+ *
601
+ * @throws {Error} If the config file is not found or required fields are missing
602
+ * @returns {Object} Configuration object with the following properties:
603
+ * - jsons: Path to the themes-tokens and ui-kit directories
604
+ * - srcPath: Path to the source directory
605
+ * - project: Project name
606
+ */
607
+ function loadConfig() {
608
+ let rootPath = getRootPath();
609
+ const configPath = path.join(rootPath, "recursica.json");
610
+ if (!fs.existsSync(configPath)) {
611
+ throw new Error("Config file not found at: " + configPath);
612
+ }
613
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
614
+ if (typeof config.project === "object" && config.project?.root) {
615
+ rootPath = path.join(rootPath, config.project.root);
616
+ }
617
+ const bundledJson = hasThemeOrKitFiles(rootPath);
618
+ const iconsJson = hasIconsJsonFiles(rootPath);
619
+ const project = config.project;
620
+ if (!project) {
621
+ throw new Error("project is required in config file");
622
+ }
623
+ return {
624
+ rootPath,
625
+ srcPath: path.join(rootPath, "src"),
626
+ project,
627
+ bundledJson,
628
+ iconsJson,
629
+ overrides: config.overrides,
630
+ iconsConfig: config.icons,
631
+ };
632
+ }
633
+ function getRootPath() {
634
+ // recursively search for the package.json file starting from the current working directory
635
+ let currentDir = process.cwd();
636
+ let level = 0;
637
+ while (!fs.existsSync(path.join(currentDir, "recursica.json"))) {
638
+ currentDir = path.join(currentDir, "..");
639
+ level++;
640
+ if (level > 10) {
641
+ throw new Error("Could not find recursica.json");
642
+ }
643
+ }
644
+ return currentDir;
645
+ }
646
+
647
+ class ProcessTokens {
648
+ constructor(overrides) {
649
+ this.tokens = {};
650
+ this.themes = {};
651
+ this.breakpoints = {};
652
+ this.colors = [];
653
+ this.spacers = [];
654
+ this.borderRadius = [];
655
+ this.uiKit = {};
656
+ this.processValue = (target, token) => {
657
+ if (typeof token.value === "string") {
658
+ target[token.name] = token.value;
659
+ return true;
660
+ }
661
+ if (typeof token.value === "number") {
662
+ target[token.name] = `${token.value}px`;
663
+ return true;
664
+ }
665
+ if (typeof token.value === "object") {
666
+ target[token.name] = token.value;
667
+ return true;
668
+ }
669
+ return false;
670
+ };
671
+ this.overrides = overrides;
672
+ }
673
+ processTokenValue(token, modeName, jsonThemeName) {
674
+ if (token.collection === "Breakpoints") {
675
+ this.processValue(this.breakpoints, token);
676
+ // Add breakpoints to uiKit with 'breakpoints/' prefix
677
+ const uiKitTarget = {};
678
+ this.processValue(uiKitTarget, token);
679
+ Object.entries(uiKitTarget).forEach(([key, value]) => {
680
+ // Ensure we only store string values
681
+ if (typeof value === "string") {
682
+ this.uiKit[`breakpoint/${key}`] = value;
683
+ }
684
+ else if (typeof value === "number") {
685
+ this.uiKit[`breakpoint/${key}`] = `${value.toString()}px`;
686
+ }
687
+ });
688
+ }
689
+ else if (token.collection === "UI Kit") {
690
+ this.processValue(this.uiKit, token);
691
+ }
692
+ else if (token.collection === "Tokens") {
693
+ this.processValue(this.tokens, token);
694
+ }
695
+ else {
696
+ if (!jsonThemeName)
697
+ return;
698
+ if (!this.themes[jsonThemeName])
699
+ this.themes[jsonThemeName] = {};
700
+ if (!this.themes[jsonThemeName][modeName])
701
+ this.themes[jsonThemeName][modeName] = {};
702
+ this.processValue(this.themes[jsonThemeName][modeName], token);
703
+ }
704
+ }
705
+ processTokens(variables, jsonThemeName) {
706
+ // Process tokens collection
707
+ for (const token of Object.values(variables)) {
708
+ if (isFontFamilyToken(token)) {
709
+ if (!jsonThemeName)
710
+ continue;
711
+ if (!this.tokens[jsonThemeName])
712
+ this.tokens[jsonThemeName] = {};
713
+ if (typeof this.tokens[jsonThemeName] !== "object")
714
+ this.tokens[jsonThemeName] = {};
715
+ this.tokens[jsonThemeName][`typography/${token.variableName}`] =
716
+ this.overrides?.fontFamily?.[token.fontFamily] ?? token.fontFamily;
717
+ this.tokens[jsonThemeName][`typography/${token.variableName}-size`] =
718
+ `${token.fontSize.toString()}px`;
719
+ // check if overrides.fontWeight is defined
720
+ if (this.overrides?.fontWeight) {
721
+ const weight = this.overrides.fontWeight.find((weight) => weight.alias === token.fontWeight.alias &&
722
+ weight.fontFamily === token.fontFamily);
723
+ // check if there's a weight that matches the alias and fontFamily
724
+ // if there is, use the value from the overrides
725
+ // if there isn't, use the value from the token
726
+ if (weight) {
727
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = weight.value.toString();
728
+ }
729
+ else {
730
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
731
+ }
732
+ }
733
+ else {
734
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
735
+ }
736
+ if (token.lineHeight.unit === "PERCENT") {
737
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = `${token.lineHeight.value.toString()}%`;
738
+ }
739
+ else {
740
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = "1.2";
741
+ }
742
+ this.tokens[jsonThemeName][`typography/${token.variableName}-letter-spacing`] =
743
+ token.letterSpacing.unit === "PIXELS"
744
+ ? `${token.letterSpacing.value.toString()}px`
745
+ : `${token.letterSpacing.value.toString()}%`;
746
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-case`] = token.textCase;
747
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-decoration`] = token.textDecoration;
748
+ continue;
749
+ }
750
+ if (isEffectToken(token)) {
751
+ const effectValue = [];
752
+ token.effects.forEach((effect) => {
753
+ const { color: { r, g, b, a }, offset: { x, y }, radius, spread, } = effect;
754
+ effectValue.push(`${x.toString()}px ${y.toString()}px ${radius.toString()}px ${spread.toString()}px rgba(${r.toString()}, ${g.toString()}, ${b.toString()}, ${a.toString()})`);
755
+ });
756
+ this.tokens[`effect/${token.variableName}`] = effectValue.join(", ");
757
+ continue;
758
+ }
759
+ if (isColorOrFloatToken(token)) {
760
+ const modeName = capitalize(token.mode)
761
+ .replace(/[()/]/g, "-")
762
+ .replace(/\s/g, "")
763
+ .replace(/-$/, "");
764
+ if (modeName !== "mode1")
765
+ this.themes[modeName] = {};
766
+ if (token.type === "color" && !this.colors.includes(token.name)) {
767
+ this.colors.push(token.name);
768
+ }
769
+ if (token.name.startsWith("size/spacer/") &&
770
+ !this.spacers.includes(token.name)) {
771
+ this.spacers.push(token.name);
772
+ }
773
+ if (token.name.startsWith("size/border-radius/") &&
774
+ !this.borderRadius.includes(token.name)) {
775
+ this.borderRadius.push(token.name);
776
+ }
777
+ this.processTokenValue(token, modeName, jsonThemeName);
778
+ }
779
+ else {
780
+ console.warn(`${JSON.stringify(token, null, 2)} could not be processed`);
781
+ }
782
+ }
783
+ }
784
+ }
785
+
786
+ /**
787
+ * Processes JSON content and creates ProcessTokens instance
788
+ * This is shared logic between CLI and WebWorker
789
+ */
790
+ function processJsonContent(jsonFileContent, { project, overrides }) {
791
+ const jsonContent = JSON.parse(jsonFileContent);
792
+ const jsonProjectId = jsonContent.projectId;
793
+ if (!jsonProjectId) {
794
+ throw new Error("project-id is required in the json file");
795
+ }
796
+ if (jsonProjectId.toLowerCase() !==
797
+ (typeof project === "string"
798
+ ? project.toLowerCase()
799
+ : project.name?.toLowerCase())) {
800
+ throw new Error("project-id does not match the project in the config file");
801
+ }
802
+ const processTokens = new ProcessTokens(overrides);
803
+ processTokens.processTokens(jsonContent.tokens);
804
+ for (const theme of Object.keys(jsonContent.themes)) {
805
+ processTokens.processTokens(jsonContent.themes[theme], theme);
806
+ }
807
+ processTokens.processTokens(jsonContent.uiKit);
808
+ return processTokens;
809
+ }
810
+ /**
811
+ * Processes icons JSON content and returns icons object
812
+ * This is shared logic between CLI and WebWorker
813
+ */
814
+ function processIcons(iconsJsonContent) {
815
+ const icons = {};
816
+ const iconsJsonParsed = JSON.parse(iconsJsonContent);
817
+ for (const [iconName, iconPath] of Object.entries(iconsJsonParsed)) {
818
+ icons[iconName] = iconPath;
819
+ }
820
+ return icons;
821
+ }
822
+ /**
823
+ * Core adapter processing logic shared between CLI and WebWorker
824
+ * This function handles the main processing workflow
825
+ */
826
+ function processAdapter({ rootPath, bundledJsonContent, project, overrides, srcPath, iconsJsonContent, iconsConfig, }) {
827
+ let icons = {};
828
+ // Process icons if provided
829
+ if (iconsJsonContent) {
830
+ icons = processIcons(iconsJsonContent);
831
+ }
832
+ if (!bundledJsonContent) {
833
+ throw new Error("bundledJson content not found");
834
+ }
835
+ // Process the main JSON content
836
+ const processTokens = processJsonContent(bundledJsonContent, {
837
+ project,
838
+ overrides,
839
+ });
840
+ // Run the adapter
841
+ const files = runAdapter({
842
+ rootPath,
843
+ overrides,
844
+ srcPath,
845
+ icons,
846
+ processTokens,
847
+ project,
848
+ iconsConfig,
849
+ });
850
+ return files;
851
+ }
852
+
853
+ /**
854
+ * Main CLI function that can be called programmatically
855
+ * This is the same logic as main.ts but exported as a function
856
+ */
857
+ async function runMain() {
858
+ try {
859
+ const { rootPath, bundledJson, srcPath, project, iconsJson, overrides, iconsConfig, } = loadConfig();
860
+ if (!bundledJson)
861
+ throw new Error("bundledJson not found");
862
+ // Read file contents
863
+ const bundledJsonContent = fs.readFileSync(bundledJson, "utf-8");
864
+ const iconsJsonContent = iconsJson
865
+ ? fs.readFileSync(iconsJson, "utf-8")
866
+ : undefined;
867
+ // Use shared processing logic
868
+ const files = processAdapter({
869
+ bundledJsonContent,
870
+ project,
871
+ overrides,
872
+ rootPath,
873
+ srcPath,
874
+ iconsJsonContent,
875
+ iconsConfig,
876
+ });
877
+ const { recursicaTokens, vanillaExtractThemes, mantineTheme, uiKitObject, recursicaObject, colorsType, iconsObject, spacersType, borderRadiusType, recursicaThemes, prettierignore, } = files;
878
+ const filesToWrite = [
879
+ recursicaTokens,
880
+ vanillaExtractThemes.availableThemes,
881
+ vanillaExtractThemes.themeContract,
882
+ vanillaExtractThemes.themesFileContent,
883
+ vanillaExtractThemes.typeDefinitions,
884
+ mantineTheme.mantineTheme,
885
+ mantineTheme.postCss,
886
+ uiKitObject,
887
+ recursicaObject,
888
+ colorsType,
889
+ spacersType,
890
+ borderRadiusType,
891
+ recursicaThemes,
892
+ prettierignore,
893
+ ];
894
+ // check if src/recursica folder exists, if not create it
895
+ const outputPath = srcPath + "/recursica";
896
+ if (!fs.existsSync(outputPath)) {
897
+ fs.mkdirSync(outputPath);
898
+ }
899
+ for (const file of filesToWrite) {
900
+ fs.writeFileSync(file.path, file.content);
901
+ }
902
+ for (const theme of vanillaExtractThemes.vanillaExtractThemes) {
903
+ fs.writeFileSync(theme.path, theme.content);
904
+ }
905
+ if (iconsObject) {
906
+ fs.writeFileSync(iconsObject.iconExports.path, iconsObject.iconExports.content);
907
+ fs.writeFileSync(iconsObject.iconResourceMap.path, iconsObject.iconResourceMap.content);
908
+ for (const icon of iconsObject.exportedIcons) {
909
+ fs.writeFileSync(icon.path, icon.content);
910
+ }
911
+ }
912
+ console.log("Theme generated successfully");
913
+ }
914
+ catch (error) {
915
+ console.error("Error generating theme:", error);
916
+ throw error;
917
+ }
918
+ }
919
+
920
+ export { ProcessTokens, capitalize, isColorOrFloatToken, isEffectToken, isFontFamilyToken, loadConfig, processJsonContent, runAdapter, runMain };
921
+ //# sourceMappingURL=index.js.map