@yahoo/uds 3.96.0 → 3.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/cli/commands/purge.cjs +26 -0
  2. package/dist/cli/commands/purge.d.cts +15 -0
  3. package/dist/cli/commands/purge.d.ts +15 -0
  4. package/dist/cli/commands/purge.js +25 -0
  5. package/dist/cli/commands/sync.cjs +96 -0
  6. package/dist/cli/commands/sync.d.cts +16 -0
  7. package/dist/cli/commands/sync.d.ts +16 -0
  8. package/dist/cli/commands/sync.js +93 -0
  9. package/dist/cli/commands/utils/purgeCSS.cjs +258 -0
  10. package/dist/cli/commands/utils/purgeCSS.d.cts +59 -0
  11. package/dist/cli/commands/utils/purgeCSS.d.ts +59 -0
  12. package/dist/cli/commands/utils/purgeCSS.js +244 -0
  13. package/dist/cli/commands/utils/sortKeys.cjs +23 -0
  14. package/dist/cli/commands/utils/sortKeys.d.cts +5 -0
  15. package/dist/cli/commands/utils/sortKeys.d.ts +5 -0
  16. package/dist/cli/commands/utils/sortKeys.js +21 -0
  17. package/dist/cli/commands/version.cjs +21 -0
  18. package/dist/cli/commands/version.d.cts +7 -0
  19. package/dist/cli/commands/version.d.ts +7 -0
  20. package/dist/cli/commands/version.js +18 -0
  21. package/dist/cli/dist/cli.cjs +78 -0
  22. package/dist/cli/dist/cli.js +78 -0
  23. package/dist/cli/dist/commands/codemod/codemod.cjs +81 -0
  24. package/dist/cli/dist/commands/codemod/codemod.js +79 -0
  25. package/dist/cli/dist/commands/editor-rules.cjs +107 -0
  26. package/dist/cli/dist/commands/editor-rules.js +106 -0
  27. package/dist/cli/dist/lib/args.cjs +32 -0
  28. package/dist/cli/dist/lib/args.js +31 -0
  29. package/dist/cli/dist/lib/colors.cjs +26 -0
  30. package/dist/cli/dist/lib/colors.js +18 -0
  31. package/dist/cli/dist/lib/print.cjs +13 -0
  32. package/dist/cli/dist/lib/print.js +12 -0
  33. package/dist/cli/dist/lib/spinner.cjs +59 -0
  34. package/dist/cli/dist/lib/spinner.js +57 -0
  35. package/dist/cli/dist/utils/analytics.cjs +33 -0
  36. package/dist/cli/dist/utils/analytics.js +32 -0
  37. package/dist/cli/dist/utils/getCommandHelp.cjs +58 -0
  38. package/dist/cli/dist/utils/getCommandHelp.js +56 -0
  39. package/dist/cli/dist/utils/getDirChoices.cjs +27 -0
  40. package/dist/cli/dist/utils/getDirChoices.js +25 -0
  41. package/dist/cli/dist/utils/rules/config.cjs +56 -0
  42. package/dist/cli/dist/utils/rules/config.js +53 -0
  43. package/dist/cli/runner.cjs +14 -0
  44. package/dist/cli/runner.d.cts +2 -0
  45. package/dist/cli/runner.d.ts +2 -0
  46. package/dist/cli/runner.js +14 -0
  47. package/dist/styles/styler.d.cts +32 -32
  48. package/dist/styles/styler.d.ts +32 -32
  49. package/dist/tailwind/tailwindPlugin.d.cts +1 -1
  50. package/dist/tailwind/tailwindPlugin.d.ts +1 -1
  51. package/dist/tailwind/utils/getShadowStyles.d.cts +4 -4
  52. package/dist/tailwind/utils/getShadowStyles.d.ts +4 -4
  53. package/dist/uds/scripts/utils/tsMorph.cjs +1 -1
  54. package/dist/uds/scripts/utils/tsMorph.d.cts +1 -1
  55. package/dist/uds/scripts/utils/tsMorph.d.ts +1 -1
  56. package/package.json +5 -8
  57. package/uds.js +11 -1
  58. package/dist/cli.mjs +0 -897
@@ -0,0 +1,26 @@
1
+ /*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
+ const require_analytics = require('../dist/utils/analytics.cjs');
4
+ const require_spinner = require('../dist/lib/spinner.cjs');
5
+ const require_cli_commands_utils_purgeCSS = require('./utils/purgeCSS.cjs');
6
+
7
+ //#region src/cli/commands/purge.ts
8
+ const purgeCommand = {
9
+ name: "purge",
10
+ description: `Purge unused CSS`,
11
+ run: async (props) => {
12
+ require_spinner.spinStart("Purging css started...");
13
+ try {
14
+ await require_cli_commands_utils_purgeCSS.purge(props.options);
15
+ require_spinner.spinStop("✅", "Purging css done!");
16
+ return await require_analytics.trackEvent("purge");
17
+ } catch (error) {
18
+ if (error instanceof Error) require_spinner.spinStop("❌", error.message);
19
+ else require_spinner.spinStop("❌", "Purging css failed! Please reach out to #uds-ask channel for support.");
20
+ process.exitCode = 1;
21
+ }
22
+ }
23
+ };
24
+
25
+ //#endregion
26
+ exports.purgeCommand = purgeCommand;
@@ -0,0 +1,15 @@
1
+
2
+ import { PurgeOptions } from "./utils/purgeCSS.cjs";
3
+ import { Props } from "@yahoo/uds-cli";
4
+
5
+ //#region src/cli/commands/purge.d.ts
6
+ interface PurgeProps extends Props {
7
+ options: PurgeOptions;
8
+ }
9
+ declare const purgeCommand: {
10
+ name: string;
11
+ description: string;
12
+ run: (props: PurgeProps) => Promise<void>;
13
+ };
14
+ //#endregion
15
+ export { purgeCommand };
@@ -0,0 +1,15 @@
1
+
2
+ import { PurgeOptions } from "./utils/purgeCSS.js";
3
+ import { Props } from "@yahoo/uds-cli";
4
+
5
+ //#region src/cli/commands/purge.d.ts
6
+ interface PurgeProps extends Props {
7
+ options: PurgeOptions;
8
+ }
9
+ declare const purgeCommand: {
10
+ name: string;
11
+ description: string;
12
+ run: (props: PurgeProps) => Promise<void>;
13
+ };
14
+ //#endregion
15
+ export { purgeCommand };
@@ -0,0 +1,25 @@
1
+ /*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
2
+ import { trackEvent } from "../dist/utils/analytics.js";
3
+ import { spinStart, spinStop } from "../dist/lib/spinner.js";
4
+ import { purge } from "./utils/purgeCSS.js";
5
+
6
+ //#region src/cli/commands/purge.ts
7
+ const purgeCommand = {
8
+ name: "purge",
9
+ description: `Purge unused CSS`,
10
+ run: async (props) => {
11
+ spinStart("Purging css started...");
12
+ try {
13
+ await purge(props.options);
14
+ spinStop("✅", "Purging css done!");
15
+ return await trackEvent("purge");
16
+ } catch (error) {
17
+ if (error instanceof Error) spinStop("❌", error.message);
18
+ else spinStop("❌", "Purging css failed! Please reach out to #uds-ask channel for support.");
19
+ process.exitCode = 1;
20
+ }
21
+ }
22
+ };
23
+
24
+ //#endregion
25
+ export { purgeCommand };
@@ -0,0 +1,96 @@
1
+ /*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
4
+ const require_defaultTokensConfig = require('../../defaultTokensConfig.cjs');
5
+ const require_runtime_breakpointsConfig = require('../../runtime/breakpointsConfig.cjs');
6
+ const require_runtime_toastConfig = require('../../runtime/toastConfig.cjs');
7
+ const require_analytics = require('../dist/utils/analytics.cjs');
8
+ const require_colors = require('../dist/lib/colors.cjs');
9
+ const require_print = require('../dist/lib/print.cjs');
10
+ const require_cli_commands_utils_sortKeys = require('./utils/sortKeys.cjs');
11
+ let node_fs = require("node:fs");
12
+ let node_path = require("node:path");
13
+ node_path = require_runtime.__toESM(node_path);
14
+
15
+ //#region src/cli/commands/sync.ts
16
+ const PRODUCTION_ENDPOINT = "https://config.uds.build/api/config";
17
+ const STAGING_ENDPOINT = "https://staging.config.uds.build/api/config";
18
+ function getConfigEndpoint() {
19
+ if (process.env.DATABASE === "staging") return STAGING_ENDPOINT;
20
+ if (process.env.DATABASE === "local") return `http://localhost:${process.env.PORT || 4001}/api/config`;
21
+ return PRODUCTION_ENDPOINT;
22
+ }
23
+ const syncCommand = {
24
+ name: "sync",
25
+ description: "🔄 Update to latest design config 🎨",
26
+ aliases: ["update"],
27
+ run: async ({ name, commandPath, options }) => {
28
+ const id = options.id || process.env.UDS_ID;
29
+ const outFile = options.outFile || process.env.UDS_OUT_FILE;
30
+ if (!id || typeof id === "boolean") {
31
+ console.error("\nMissing config ID. Please pass an --id flag or set the UDS_ID env variable.\n");
32
+ require_print.print(`${require_colors.magenta("Usage:")} ${name} ${commandPath} --id <config-id>\n`);
33
+ return;
34
+ }
35
+ const outputPath = outFile ?? "./uds.config.ts";
36
+ const outFileExtension = outputPath.split(".").pop()?.toLowerCase();
37
+ if (outFileExtension !== "ts" && outFileExtension !== "js") {
38
+ require_print.print(require_colors.red("❌ Output file must be a TypeScript or JavaScript file."));
39
+ process.exitCode = 1;
40
+ return;
41
+ }
42
+ try {
43
+ const fetchUrl = `${getConfigEndpoint()}?id=${id}`;
44
+ const fullPath = node_path.default.resolve(process.cwd(), outputPath);
45
+ require_print.print(require_colors.yellow("Fetching from configurator..."));
46
+ let config;
47
+ if (process.env.DATABASE === "test") config = require_defaultTokensConfig.defaultTokensConfig;
48
+ else {
49
+ const resp = await fetch(fetchUrl);
50
+ if (!resp.ok) {
51
+ if (resp.status === 401) throw new Error(`${resp.status} error: ${resp.statusText}\nYou're not authorized to fetch from ${fetchUrl}\nMake sure you have a valid VERCEL_PROTECTION_BYPASS token in your root .env.local`);
52
+ throw new Error(`Error fetching config id '${id}'. Does it exist in the Configurator?`);
53
+ }
54
+ config = (await resp.json()).config;
55
+ }
56
+ if (!config) throw new Error("Config JSON could not be parsed.");
57
+ const sortedConfig = require_cli_commands_utils_sortKeys.sortKeys(config);
58
+ const importsTS = [`import type { UniversalTokensConfig } from '@yahoo/uds';`];
59
+ const exportsTS = [`export const config: UniversalTokensConfig = ${JSON.stringify(sortedConfig, null, 2)};`];
60
+ const exportsJS = [`export const config = ${JSON.stringify(sortedConfig, null, 2)};`];
61
+ const runtimeConfigs = {
62
+ breakpoints: [require_runtime_breakpointsConfig.configToBreakpointsConfigContext(sortedConfig), "UDSBreakpointsConfigContextType"],
63
+ toast: [require_runtime_toastConfig.configToToastConfigContext(sortedConfig), "UDSToastConfigContextType"]
64
+ };
65
+ const runtimeTypeImports = [];
66
+ for (const [name, [json, type]] of Object.entries(runtimeConfigs)) {
67
+ const content = require_cli_commands_utils_sortKeys.sortKeys(json);
68
+ runtimeTypeImports.push(type);
69
+ exportsTS.push(`export const ${name}RuntimeConfig: ${type} = ${JSON.stringify(content, null, 2)};`);
70
+ exportsJS.push(`export const ${name}RuntimeConfig = ${JSON.stringify(content, null, 2)};`);
71
+ }
72
+ runtimeTypeImports.push("UDSConfigContextType");
73
+ importsTS.push(`import type { ${runtimeTypeImports.sort().join(", ")} } from '@yahoo/uds/runtime';`);
74
+ exportsTS.push(`export const runtimeConfig: UDSConfigContextType = {
75
+ breakpoints: breakpointsRuntimeConfig,
76
+ toast: toastRuntimeConfig,
77
+ };`);
78
+ exportsJS.push(`export const runtimeConfig = {
79
+ breakpoints: breakpointsRuntimeConfig,
80
+ toast: toastRuntimeConfig,
81
+ };`);
82
+ const configContentTs = `${importsTS.join("\n")}\n\n${exportsTS.join("\n\n")}\n`;
83
+ const configContentJs = `${exportsJS.join("\n\n")}\n`;
84
+ (0, node_fs.writeFileSync)(fullPath, outFileExtension === "js" ? configContentJs : configContentTs);
85
+ require_print.print(require_colors.green(`✅ Synced UDS config ${id} to ${fullPath}`));
86
+ await require_analytics.trackEvent("sync", { id });
87
+ } catch (error) {
88
+ require_print.print(require_colors.red(`❌ ${error.message}`));
89
+ require_print.print(require_colors.yellow("Please reach out to #uds-ask channel for support."));
90
+ process.exitCode = 1;
91
+ }
92
+ }
93
+ };
94
+
95
+ //#endregion
96
+ exports.syncCommand = syncCommand;
@@ -0,0 +1,16 @@
1
+
2
+ import { Props } from "@yahoo/uds-cli";
3
+
4
+ //#region src/cli/commands/sync.d.ts
5
+ declare const syncCommand: {
6
+ name: string;
7
+ description: string;
8
+ aliases: string[];
9
+ run: ({
10
+ name,
11
+ commandPath,
12
+ options
13
+ }: Props) => Promise<void>;
14
+ };
15
+ //#endregion
16
+ export { syncCommand };
@@ -0,0 +1,16 @@
1
+
2
+ import { Props } from "@yahoo/uds-cli";
3
+
4
+ //#region src/cli/commands/sync.d.ts
5
+ declare const syncCommand: {
6
+ name: string;
7
+ description: string;
8
+ aliases: string[];
9
+ run: ({
10
+ name,
11
+ commandPath,
12
+ options
13
+ }: Props) => Promise<void>;
14
+ };
15
+ //#endregion
16
+ export { syncCommand };
@@ -0,0 +1,93 @@
1
+ /*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
2
+ import { defaultTokensConfig } from "../../defaultTokensConfig.js";
3
+ import { configToBreakpointsConfigContext } from "../../runtime/breakpointsConfig.js";
4
+ import { configToToastConfigContext } from "../../runtime/toastConfig.js";
5
+ import { trackEvent } from "../dist/utils/analytics.js";
6
+ import { green, magenta, red, yellow } from "../dist/lib/colors.js";
7
+ import { print } from "../dist/lib/print.js";
8
+ import { sortKeys } from "./utils/sortKeys.js";
9
+ import { writeFileSync } from "node:fs";
10
+ import path from "node:path";
11
+
12
+ //#region src/cli/commands/sync.ts
13
+ const PRODUCTION_ENDPOINT = "https://config.uds.build/api/config";
14
+ const STAGING_ENDPOINT = "https://staging.config.uds.build/api/config";
15
+ function getConfigEndpoint() {
16
+ if (process.env.DATABASE === "staging") return STAGING_ENDPOINT;
17
+ if (process.env.DATABASE === "local") return `http://localhost:${process.env.PORT || 4001}/api/config`;
18
+ return PRODUCTION_ENDPOINT;
19
+ }
20
+ const syncCommand = {
21
+ name: "sync",
22
+ description: "🔄 Update to latest design config 🎨",
23
+ aliases: ["update"],
24
+ run: async ({ name, commandPath, options }) => {
25
+ const id = options.id || process.env.UDS_ID;
26
+ const outFile = options.outFile || process.env.UDS_OUT_FILE;
27
+ if (!id || typeof id === "boolean") {
28
+ console.error("\nMissing config ID. Please pass an --id flag or set the UDS_ID env variable.\n");
29
+ print(`${magenta("Usage:")} ${name} ${commandPath} --id <config-id>\n`);
30
+ return;
31
+ }
32
+ const outputPath = outFile ?? "./uds.config.ts";
33
+ const outFileExtension = outputPath.split(".").pop()?.toLowerCase();
34
+ if (outFileExtension !== "ts" && outFileExtension !== "js") {
35
+ print(red("❌ Output file must be a TypeScript or JavaScript file."));
36
+ process.exitCode = 1;
37
+ return;
38
+ }
39
+ try {
40
+ const fetchUrl = `${getConfigEndpoint()}?id=${id}`;
41
+ const fullPath = path.resolve(process.cwd(), outputPath);
42
+ print(yellow("Fetching from configurator..."));
43
+ let config;
44
+ if (process.env.DATABASE === "test") config = defaultTokensConfig;
45
+ else {
46
+ const resp = await fetch(fetchUrl);
47
+ if (!resp.ok) {
48
+ if (resp.status === 401) throw new Error(`${resp.status} error: ${resp.statusText}\nYou're not authorized to fetch from ${fetchUrl}\nMake sure you have a valid VERCEL_PROTECTION_BYPASS token in your root .env.local`);
49
+ throw new Error(`Error fetching config id '${id}'. Does it exist in the Configurator?`);
50
+ }
51
+ config = (await resp.json()).config;
52
+ }
53
+ if (!config) throw new Error("Config JSON could not be parsed.");
54
+ const sortedConfig = sortKeys(config);
55
+ const importsTS = [`import type { UniversalTokensConfig } from '@yahoo/uds';`];
56
+ const exportsTS = [`export const config: UniversalTokensConfig = ${JSON.stringify(sortedConfig, null, 2)};`];
57
+ const exportsJS = [`export const config = ${JSON.stringify(sortedConfig, null, 2)};`];
58
+ const runtimeConfigs = {
59
+ breakpoints: [configToBreakpointsConfigContext(sortedConfig), "UDSBreakpointsConfigContextType"],
60
+ toast: [configToToastConfigContext(sortedConfig), "UDSToastConfigContextType"]
61
+ };
62
+ const runtimeTypeImports = [];
63
+ for (const [name, [json, type]] of Object.entries(runtimeConfigs)) {
64
+ const content = sortKeys(json);
65
+ runtimeTypeImports.push(type);
66
+ exportsTS.push(`export const ${name}RuntimeConfig: ${type} = ${JSON.stringify(content, null, 2)};`);
67
+ exportsJS.push(`export const ${name}RuntimeConfig = ${JSON.stringify(content, null, 2)};`);
68
+ }
69
+ runtimeTypeImports.push("UDSConfigContextType");
70
+ importsTS.push(`import type { ${runtimeTypeImports.sort().join(", ")} } from '@yahoo/uds/runtime';`);
71
+ exportsTS.push(`export const runtimeConfig: UDSConfigContextType = {
72
+ breakpoints: breakpointsRuntimeConfig,
73
+ toast: toastRuntimeConfig,
74
+ };`);
75
+ exportsJS.push(`export const runtimeConfig = {
76
+ breakpoints: breakpointsRuntimeConfig,
77
+ toast: toastRuntimeConfig,
78
+ };`);
79
+ const configContentTs = `${importsTS.join("\n")}\n\n${exportsTS.join("\n\n")}\n`;
80
+ const configContentJs = `${exportsJS.join("\n\n")}\n`;
81
+ writeFileSync(fullPath, outFileExtension === "js" ? configContentJs : configContentTs);
82
+ print(green(`✅ Synced UDS config ${id} to ${fullPath}`));
83
+ await trackEvent("sync", { id });
84
+ } catch (error) {
85
+ print(red(`❌ ${error.message}`));
86
+ print(yellow("Please reach out to #uds-ask channel for support."));
87
+ process.exitCode = 1;
88
+ }
89
+ }
90
+ };
91
+
92
+ //#endregion
93
+ export { syncCommand };
@@ -0,0 +1,258 @@
1
+ /*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
+ const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
4
+ const require_index = require('../../../css-tokens/dist/index.cjs');
5
+ const require_styles_variants = require('../../../styles/variants.cjs');
6
+ const require_print = require('../../dist/lib/print.cjs');
7
+ const require_spinner = require('../../dist/lib/spinner.cjs');
8
+ const require_tailwindPurge = require('../../../uds/generated/tailwindPurge.cjs');
9
+ const require_tsMorph = require('../../../uds/scripts/utils/tsMorph.cjs');
10
+ let node_fs = require("node:fs");
11
+ let node_path = require("node:path");
12
+ node_path = require_runtime.__toESM(node_path);
13
+ let _yahoo_uds_package_json = require("@yahoo/uds/package.json");
14
+ _yahoo_uds_package_json = require_runtime.__toESM(_yahoo_uds_package_json);
15
+ let fast_glob = require("fast-glob");
16
+ fast_glob = require_runtime.__toESM(fast_glob);
17
+ let ts_morph = require("ts-morph");
18
+
19
+ //#region src/cli/commands/utils/purgeCSS.ts
20
+ const scaleModeToClass = {
21
+ large: require_index.LARGE_SCALE_MODE_CLASSNAME,
22
+ medium: require_index.MEDIUM_SCALE_MODE_CLASSNAME,
23
+ small: require_index.SMALL_SCALE_MODE_CLASSNAME,
24
+ xLarge: require_index.XLARGE_SCALE_MODE_CLASSNAME,
25
+ xSmall: require_index.XSMALL_SCALE_MODE_CLASSNAME,
26
+ xxLarge: require_index.XXLARGE_SCALE_MODE_CLASSNAME,
27
+ xxxLarge: require_index.XXXLARGE_SCALE_MODE_CLASSNAME
28
+ };
29
+ const colorModeToClass = {
30
+ dark: require_index.DARK_COLOR_MODE_CLASSNAME,
31
+ light: require_index.LIGHT_COLOR_MODE_CLASSNAME
32
+ };
33
+ const getFiles = async (entry) => {
34
+ try {
35
+ const workspaceDir = process.env.PWD || process.cwd();
36
+ if (!workspaceDir) throw new Error("Workspace directory not found.");
37
+ return await (0, fast_glob.default)(["**/*.jsx", "**/*.tsx"], {
38
+ cwd: node_path.default.join(workspaceDir, entry),
39
+ absolute: true
40
+ });
41
+ } catch {
42
+ throw new Error(`Couldn't find the entry directory: ${entry}. Please make sure it exists.`);
43
+ }
44
+ };
45
+ /**
46
+ * Find all JSX references for a named import.
47
+ *
48
+ * @example
49
+ * const references = findNamedImportReferences(project, '@yahoo/uds', 'HStack')
50
+ */
51
+ function findNamedImportReferences(project, moduleSpecifierValue, namedImportName) {
52
+ const references = [];
53
+ for (const sourceFile of project.getSourceFiles()) for (const importDeclaration of sourceFile.getImportDeclarations()) if (importDeclaration.getModuleSpecifierValue() === moduleSpecifierValue) {
54
+ for (const namedImport of importDeclaration.getNamedImports()) if (namedImport.getName() === namedImportName) {
55
+ const identifier = namedImport.getFirstDescendantByKindOrThrow(ts_morph.ts.SyntaxKind.Identifier);
56
+ references.push(...require_tsMorph.findReferencesAsJsxElements(identifier));
57
+ }
58
+ }
59
+ return references;
60
+ }
61
+ /**
62
+ * Given a file it returns the list of imports from @yahoo/uds
63
+ */
64
+ const parseFiles = (project, files) => {
65
+ const importsSet = /* @__PURE__ */ new Set();
66
+ files.map((file) => {
67
+ return project.getSourceFile(file)?.getImportDeclarations().filter((declaration) => {
68
+ return declaration.getModuleSpecifier().getText().includes("@yahoo/uds") || declaration.getModuleSpecifier().getText().includes("@yahoo/uds/experimental");
69
+ }).map((declaration) => {
70
+ return declaration.getNamedImports().map((namedImport) => namedImport.getName());
71
+ }).flat() ?? [];
72
+ }).flat().forEach((item) => {
73
+ if (!importsSet.has(item)) importsSet.add(item);
74
+ });
75
+ return Array.from(importsSet);
76
+ };
77
+ const getTailwindSafelist = (project, componentList) => {
78
+ const safeList = [];
79
+ const validVariants = new Set(require_tailwindPurge.variantsList);
80
+ const usedProps = /* @__PURE__ */ new Map();
81
+ componentList.forEach((component) => {
82
+ if (isUDSComponent(component)) {
83
+ require_tailwindPurge.componentToVariants[component].forEach(([propName, usedValues]) => {
84
+ if (validVariants.has(propName)) {
85
+ const options = usedProps.get(propName) ?? /* @__PURE__ */ new Set();
86
+ usedValues.forEach((val) => options.add(val));
87
+ usedProps.set(propName, options);
88
+ }
89
+ });
90
+ getUsedProps(project, component).forEach(([propName, usedValues]) => {
91
+ if (validVariants.has(propName)) {
92
+ if (usedValues.length === 0) usedValues = Object.keys(require_styles_variants.variants[propName]);
93
+ const options = usedProps.get(propName) ?? /* @__PURE__ */ new Set();
94
+ usedValues.forEach((val) => options.add(val));
95
+ usedProps.set(propName, options);
96
+ }
97
+ });
98
+ safeList.push(...require_tailwindPurge.componentToTwClasses[component].replaceAll("\\", "").split(" "));
99
+ }
100
+ });
101
+ for (const [propName, usedValues] of usedProps) {
102
+ const variantGroup = require_styles_variants.variants[propName];
103
+ if (variantGroup) usedValues.forEach((option) => {
104
+ const variantClass = variantGroup[option];
105
+ if (variantClass) safeList.push(variantClass.replaceAll("\\", ""));
106
+ });
107
+ }
108
+ for (const [variant, variantOptions] of scanGetStylesReferences(project)) {
109
+ const variantGroup = require_styles_variants.variants[variant];
110
+ if (variantGroup) variantOptions.forEach((option) => {
111
+ const variantClass = variantGroup[option];
112
+ if (variantClass) safeList.push(variantClass.replaceAll("\\", ""));
113
+ });
114
+ }
115
+ return Array.from(new Set(safeList)).filter(Boolean);
116
+ };
117
+ /**
118
+ * Get the used props for a given component.
119
+ *
120
+ * @example
121
+ * const usedProps = getUsedProps(project, 'HStack');
122
+ */
123
+ const getUsedProps = (project, component) => {
124
+ const references = [];
125
+ references.push(...findNamedImportReferences(project, _yahoo_uds_package_json.default.name, component));
126
+ references.push(...findNamedImportReferences(project, `${_yahoo_uds_package_json.default.name}/experimental`, component));
127
+ return references.map((reference) => require_tsMorph.getUsedPropsInReference(reference)).flat();
128
+ };
129
+ const isUDSComponent = (component) => {
130
+ return !!require_tailwindPurge.componentToVariants[component];
131
+ };
132
+ const saveToFile = (safeList, outputPath) => {
133
+ const fileContent = `
134
+ //! This file is generated by purgeCSS.ts from @yahoo/uds
135
+ //! Do not edit directly
136
+ //! If there is issue with this file please report to #ask-uds
137
+ export const safelist = ${JSON.stringify(safeList)};
138
+ `;
139
+ (0, node_fs.mkdirSync)(node_path.default.dirname(outputPath), { recursive: true });
140
+ (0, node_fs.writeFileSync)(outputPath, fileContent);
141
+ };
142
+ const getComponentsToConvertToTW = (udsImport) => {
143
+ const components = udsImport.filter((importedItem) => !!require_tailwindPurge.componentToVariants[importedItem]);
144
+ const set = /* @__PURE__ */ new Set();
145
+ components.forEach((component) => {
146
+ if (!set.has(component)) set.add(component);
147
+ if (require_tailwindPurge.componentsDependencies[component]) require_tailwindPurge.componentsDependencies[component].forEach((dependent) => {
148
+ if (!set.has(dependent)) set.add(dependent);
149
+ });
150
+ });
151
+ return Array.from(set);
152
+ };
153
+ /**
154
+ * Get the classes that corresponds to the used modes
155
+ */
156
+ const getClassesForEnabledThemesAndScales = () => {
157
+ const classes = [];
158
+ if (process.env.ENABLED_SCALE_AND_COLOR_MODES) process.env.ENABLED_SCALE_AND_COLOR_MODES.split(",").map((mode) => {
159
+ mode = mode.trim();
160
+ if (colorModeToClass[mode]) classes.push(colorModeToClass[mode]);
161
+ else if (scaleModeToClass[mode]) classes.push(scaleModeToClass[mode]);
162
+ });
163
+ else {
164
+ classes.push(colorModeToClass.dark);
165
+ classes.push(colorModeToClass.light);
166
+ classes.push(scaleModeToClass.large);
167
+ }
168
+ return classes;
169
+ };
170
+ /**
171
+ * Scan the source code for all `getStyles` references
172
+ *
173
+ * Note: This currently only works if we are passing a literal object to getStyles.
174
+ *
175
+ * Explanation: They we are able to enfer what css to include is by looking at the properties of the object passed.
176
+ * If something other than an object is passed, we can fallback on the Type, but that would require handling
177
+ * a lot of edge cases (function return type, spread operator, ternary, ...) and each one of these cases will
178
+ * most likely have a sub case. Falling back to the Type will complicate the code a lot is error prone as there
179
+ * is only so much info we can get out of the types as the Users are free to use `any` on their project which will
180
+ * provide no value for us. Hence why having a literal object passed is the best and probably the only sane way
181
+ * to go about this.
182
+ */
183
+ const scanGetStylesReferences = (project) => {
184
+ const references = [];
185
+ for (const sourceFile of project.getSourceFiles()) for (const importDeclaration of sourceFile.getImportDeclarations()) if (importDeclaration.getModuleSpecifierValue() === _yahoo_uds_package_json.default.name) {
186
+ for (const namedImport of importDeclaration.getNamedImports()) if (namedImport.getName() === "getStyles") {
187
+ const identifier = namedImport.getFirstDescendantByKindOrThrow(ts_morph.ts.SyntaxKind.Identifier);
188
+ for (const reference of identifier.findReferencesAsNodes()) {
189
+ const node = reference.getFirstAncestor((node) => {
190
+ return ts_morph.Node.isCallExpression(node);
191
+ });
192
+ if (node) references.push(node);
193
+ }
194
+ }
195
+ }
196
+ const usedProps = /* @__PURE__ */ new Map();
197
+ for (const reference of references) {
198
+ const objectLiteralExpression = reference.getFirstChildByKindOrThrow(ts_morph.SyntaxKind.ObjectLiteralExpression);
199
+ const propertyAssignments = objectLiteralExpression.getDescendantsOfKind(ts_morph.SyntaxKind.PropertyAssignment);
200
+ const shorthandPropertyAssignments = objectLiteralExpression.getDescendantsOfKind(ts_morph.SyntaxKind.ShorthandPropertyAssignment);
201
+ propertyAssignments.forEach((propertyAssigment) => {
202
+ const identifier = propertyAssigment.getFirstChildByKind(ts_morph.SyntaxKind.Identifier)?.getText();
203
+ const stringLiteral = propertyAssigment.getFirstChildByKind(ts_morph.SyntaxKind.StringLiteral)?.getLiteralText();
204
+ if (identifier && !stringLiteral) {
205
+ const fallback = !!require_styles_variants.variants[identifier] ? Object.keys(require_styles_variants.variants[identifier]) : [];
206
+ usedProps.set(identifier, new Set(fallback));
207
+ }
208
+ if (identifier && stringLiteral) {
209
+ let options;
210
+ if (usedProps.has(identifier)) options = usedProps.get(identifier);
211
+ else options = /* @__PURE__ */ new Set();
212
+ options.add(stringLiteral);
213
+ usedProps.set(identifier, options);
214
+ }
215
+ });
216
+ shorthandPropertyAssignments.forEach((propertyAssigment) => {
217
+ const identifier = propertyAssigment.getFirstChildByKind(ts_morph.SyntaxKind.Identifier)?.getText();
218
+ if (identifier) usedProps.set(identifier, /* @__PURE__ */ new Set());
219
+ });
220
+ }
221
+ return usedProps;
222
+ };
223
+ async function purge({ config: configPath = process.env.UDS_OUT_FILE ?? "./uds.config.ts", output = "dist/safelist.ts", entry = "/src/" }) {
224
+ const workspaceDir = process.env.PWD || process.cwd();
225
+ if (!workspaceDir) throw new Error("Workspace directory not found.");
226
+ const project = new ts_morph.Project({ tsConfigFilePath: node_path.default.join(workspaceDir, "/tsconfig.json") });
227
+ const outputFilePath = node_path.default.join(workspaceDir, output);
228
+ const configAbsolutePath = node_path.default.join(workspaceDir, configPath);
229
+ try {
230
+ await import(configAbsolutePath);
231
+ } catch {
232
+ throw new Error("Couldn't load the UDS config. Make sure you have uds.config.ts in the root of your project.");
233
+ }
234
+ require_spinner.spinStart("Getting used UDS components...");
235
+ require_print.print("Loading the project...");
236
+ const files = await getFiles(entry);
237
+ require_print.print("Going through the imports...");
238
+ const udsImports = parseFiles(project, files);
239
+ require_print.print("Finding all the components imported from UDS...");
240
+ const udsComponents = getComponentsToConvertToTW(udsImports);
241
+ require_print.print("🧑‍🍳 Cooking...");
242
+ const safeList = getTailwindSafelist(project, udsComponents);
243
+ const themesAndScalesClasses = getClassesForEnabledThemesAndScales();
244
+ saveToFile(safeList.concat(themesAndScalesClasses), outputFilePath);
245
+ require_spinner.spinStop("Generated your safelist!");
246
+ }
247
+
248
+ //#endregion
249
+ exports.findNamedImportReferences = findNamedImportReferences;
250
+ exports.getClassesForEnabledThemesAndScales = getClassesForEnabledThemesAndScales;
251
+ exports.getComponentsToConvertToTW = getComponentsToConvertToTW;
252
+ exports.getFiles = getFiles;
253
+ exports.getTailwindSafelist = getTailwindSafelist;
254
+ exports.getUsedProps = getUsedProps;
255
+ exports.isUDSComponent = isUDSComponent;
256
+ exports.parseFiles = parseFiles;
257
+ exports.purge = purge;
258
+ exports.scanGetStylesReferences = scanGetStylesReferences;
@@ -0,0 +1,59 @@
1
+
2
+ import { JsxOpeningElement, JsxSelfClosingElement, Project } from "ts-morph";
3
+
4
+ //#region src/cli/commands/utils/purgeCSS.d.ts
5
+ type SafeList = string[];
6
+ type ImportsList = string[];
7
+ type Files = string[];
8
+ declare const getFiles: (entry: string) => Promise<Files>;
9
+ /**
10
+ * Find all JSX references for a named import.
11
+ *
12
+ * @example
13
+ * const references = findNamedImportReferences(project, '@yahoo/uds', 'HStack')
14
+ */
15
+ declare function findNamedImportReferences(project: Project, moduleSpecifierValue: string, namedImportName: string): (JsxOpeningElement | JsxSelfClosingElement)[];
16
+ /**
17
+ * Given a file it returns the list of imports from @yahoo/uds
18
+ */
19
+ declare const parseFiles: (project: Project, files: Files) => ImportsList;
20
+ declare const getTailwindSafelist: (project: Project, componentList: string[]) => SafeList;
21
+ /**
22
+ * Get the used props for a given component.
23
+ *
24
+ * @example
25
+ * const usedProps = getUsedProps(project, 'HStack');
26
+ */
27
+ declare const getUsedProps: (project: Project, component: string) => Array<[string, string[]]>;
28
+ declare const isUDSComponent: (component: string) => boolean;
29
+ declare const getComponentsToConvertToTW: (udsImport: ImportsList) => string[];
30
+ /**
31
+ * Get the classes that corresponds to the used modes
32
+ */
33
+ declare const getClassesForEnabledThemesAndScales: () => string[];
34
+ /**
35
+ * Scan the source code for all `getStyles` references
36
+ *
37
+ * Note: This currently only works if we are passing a literal object to getStyles.
38
+ *
39
+ * Explanation: They we are able to enfer what css to include is by looking at the properties of the object passed.
40
+ * If something other than an object is passed, we can fallback on the Type, but that would require handling
41
+ * a lot of edge cases (function return type, spread operator, ternary, ...) and each one of these cases will
42
+ * most likely have a sub case. Falling back to the Type will complicate the code a lot is error prone as there
43
+ * is only so much info we can get out of the types as the Users are free to use `any` on their project which will
44
+ * provide no value for us. Hence why having a literal object passed is the best and probably the only sane way
45
+ * to go about this.
46
+ */
47
+ declare const scanGetStylesReferences: (project: Project) => Map<string, Set<string>>;
48
+ type PurgeOptions = {
49
+ config?: string;
50
+ output?: string;
51
+ entry?: string;
52
+ };
53
+ declare function purge({
54
+ config: configPath,
55
+ output: output,
56
+ entry: entry
57
+ }: PurgeOptions): Promise<void>;
58
+ //#endregion
59
+ export { type PurgeOptions, findNamedImportReferences, getClassesForEnabledThemesAndScales, getComponentsToConvertToTW, getFiles, getTailwindSafelist, getUsedProps, isUDSComponent, parseFiles, purge, scanGetStylesReferences };