@yahoo/uds 3.142.0 → 3.143.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.
- package/dist/components/client/Popover/UDSPopoverConfigProvider.d.cts +1 -1
- package/dist/components/client/Popover/UDSPopoverConfigProvider.d.ts +1 -1
- package/dist/styles/styler.d.cts +3 -3
- package/dist/styles/styler.d.ts +3 -3
- package/dist/tailwind/dist/automated-config/dist/mapTextVariantFixtureToValue.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/properties.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/utils/assertUnreachable.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/utils/generateDefaultClassName.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/utils/generateSchemaKey.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/utils/index.js.map +1 -1
- package/dist/tailwind/dist/automated-config/dist/utils/mapColorFixtureToValue.js.map +1 -1
- package/dist/tailwind/dist/cli/dist/lib/logger.js.map +1 -1
- package/dist/tailwind/dist/cli/dist/lib/print.js.map +1 -1
- package/dist/tailwind/dist/cli/dist/lib/spinner.js.map +1 -1
- package/dist/tailwind/dist/commands/css.helpers.js.map +1 -1
- package/dist/tailwind/dist/commands/css.js.map +1 -1
- package/dist/tailwind/dist/commands/generateComponentData.js.map +1 -1
- package/dist/tailwind/dist/commands/generatePurgeCSSData.js.map +1 -1
- package/dist/tailwind/dist/commands/purge.js.map +1 -1
- package/dist/tailwind/dist/css/generate.helpers.js.map +1 -1
- package/dist/tailwind/dist/css/generate.js.map +1 -1
- package/dist/tailwind/dist/css/nodeUtils.js.map +1 -1
- package/dist/tailwind/dist/css/perf.js.map +1 -1
- package/dist/tailwind/dist/css/postcss.helpers.js.map +1 -1
- package/dist/tailwind/dist/css/postcss.js.map +1 -1
- package/dist/tailwind/dist/css/purgeWorker.js.map +1 -1
- package/dist/tailwind/dist/css/runner.helpers.js.map +1 -1
- package/dist/tailwind/dist/css/runner.js.map +1 -1
- package/dist/tailwind/dist/css/utils.js.map +1 -1
- package/dist/tailwind/dist/css/workerPool.js.map +1 -1
- package/dist/tailwind/dist/css-tokens/dist/index.js.map +1 -1
- package/dist/tailwind/dist/fixtures/dist/index.cjs +0 -10
- package/dist/tailwind/dist/fixtures/dist/index.js +0 -10
- package/dist/tailwind/dist/fixtures/dist/index.js.map +1 -1
- package/dist/tailwind/dist/modes/dist/index.cjs +1 -0
- package/dist/tailwind/dist/modes/dist/index.js +1 -0
- package/dist/tailwind/dist/modes/dist/index.js.map +1 -1
- package/dist/tailwind/dist/plugin.js.map +1 -1
- package/dist/tailwind/dist/purger/legacy/purgeCSS.js.map +1 -1
- package/dist/tailwind/dist/purger/legacy/purgeFromCode.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/ast/expressions.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/purge.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/purgeFromCode.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/utils/componentAnalyzer.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/utils/files.js.map +1 -1
- package/dist/tailwind/dist/purger/optimized/utils/safelist.js.map +1 -1
- package/dist/tailwind/dist/runtimeConfig/hookMetadata.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addColorModeVars.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addColorModeVarsV2.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addFontFaceDeclarations.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addFontVars.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addMotionVars.js.map +1 -1
- package/dist/tailwind/dist/tailwind/base/addScaleModeVars.js.map +1 -1
- package/dist/tailwind/dist/tailwind/components/getFocusRingStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/components/getHitTargetStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/components/getIconStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/components/getInputStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/components/getResponsiveTextStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/a11y.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/blurBgFallback.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/borderRadius.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/borderWidth.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/breakpoints.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/colors.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/components.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/elevation.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/getTailwindAsUdsColors.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/icons.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/input.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/motion.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/nestedBorderRadius.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/scaleMode.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/shadows.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/sizing.js.map +1 -1
- package/dist/tailwind/dist/tailwind/plugins/typography.js.map +1 -1
- package/dist/tailwind/dist/tailwind/theme/getFontFamilyTheme.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/addFontsPlugin.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/composeTailwindPlugins.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getColorModeStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getElevationStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getFontFaceDeclarations.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getFontStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getMotionStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getNestedBorderRadiusUtilities.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getScaleModeStyles.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getShadowPresetValues.js.map +1 -1
- package/dist/tailwind/dist/tailwind/utils/getShadowStyles.js.map +1 -1
- package/dist/tailwind/dist/utils/assertUnreachable.js.map +1 -1
- package/dist/tailwind/dist/utils/entries.js.map +1 -1
- package/dist/tailwind/dist/utils/entryPoints.js.map +1 -1
- package/dist/tailwind/dist/utils/fromEntries.js.map +1 -1
- package/dist/tailwind/dist/utils/generatePurgeCSSData.js.map +1 -1
- package/dist/tailwind/dist/utils/mapValues.js.map +1 -1
- package/dist/tailwind/dist/utils/opacity.js.map +1 -1
- package/dist/tailwind/dist/utils/optimizeCSS.js.map +1 -1
- package/dist/tailwind/dist/utils/parseTokens.js.map +1 -1
- package/dist/tailwind/dist/utils/postcssPreserveVars.js.map +1 -1
- package/dist/tailwind/dist/utils/tsMorph.js.map +1 -1
- package/dist/uds/generated/componentData.cjs +1311 -1311
- package/dist/uds/generated/componentData.js +1311 -1311
- package/dist/uds/generated/tailwindPurge.cjs +3 -0
- package/dist/uds/generated/tailwindPurge.js +3 -0
- package/dist/uds/package.cjs +2 -2
- package/dist/uds/package.js +2 -2
- package/generated/componentData.json +1692 -1692
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateComponentData.js","names":[],"sources":["../../src/commands/generateComponentData.ts"],"sourcesContent":["/**\n * Pre-generates component analysis data at build time.\n * Keep src/purger/optimized/README.md in sync when this metadata shape changes.\n * This data is used by the optimized purger to know:\n * - Default prop values for each component\n * - Hardcoded literals in getStyles() calls\n * - Internal component dependencies\n * - Literal props passed to internal components\n */\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { print } from '@yahoo/uds-cli/lib';\nimport type { Project } from 'ts-morph';\n\nimport type { ComponentInfo } from '../purger/optimized/utils/componentAnalyzer';\nimport { analyzeComponent, scanComponentFiles } from '../purger/optimized/utils/componentAnalyzer';\n\ninterface SerializedComponentInfo {\n name: string;\n defaultProps: Record<string, string>;\n getStylesLiterals: Record<string, string>;\n cxLiterals: string[];\n internalComponents: string[];\n internalComponentProps: Record<string, Record<string, string[]>>;\n propToVariantKeys: Record<string, string[]>;\n runtimeConfigDefaultProps: Record<string, string>;\n runtimeConfigGetStyles: Record<string, string[]>;\n runtimeConfigInternalComponentProps: Record<string, Record<string, string[]>>;\n motionVarPrefixes: string[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface GenerateComponentDataProps extends Props {\n // options: PurgeOptions;\n}\n\ntype Context = {\n project: Project;\n componentsDir: string;\n outputFile: string;\n};\n\nconst makeGenerateComponentDataCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'generateComponentData',\n description: `Generates component data for UDS components. This is an internal command used to by the optimized purger.`,\n tag: 'hidden',\n\n run: async (_props: GenerateComponentDataProps) => {\n const { project, componentsDir, outputFile } = await getContext();\n\n print('Scanning components in:', componentsDir);\n\n const componentPaths = await scanComponentFiles(componentsDir);\n\n print(`Found ${componentPaths.size} components`);\n\n const componentDataEntries = await Promise.all(\n [...componentPaths].map(async ([name, filePath]) => {\n try {\n project.addSourceFileAtPath(filePath);\n const info = analyzeComponent(project, filePath);\n\n return info ? ([name, serializeComponentInfo(info)] as const) : null;\n } catch (error) {\n console.warn(`Warning: Could not analyze ${name}:`, error);\n return null;\n }\n }),\n );\n\n const componentData = Object.fromEntries(\n componentDataEntries.filter((entry): entry is readonly [string, SerializedComponentInfo] =>\n Boolean(entry),\n ),\n );\n\n // Write the data\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, JSON.stringify(componentData, null, 2));\n\n print(`Generated component data for ${Object.keys(componentData).length} components`);\n print(`Output written to: ${outputFile}`);\n\n // Print some stats\n const totals = Object.values(componentData).reduce(\n (acc, comp) => ({\n totalDefaults: acc.totalDefaults + Object.keys(comp.defaultProps).length,\n totalLiterals: acc.totalLiterals + Object.keys(comp.getStylesLiterals).length,\n totalInternalComponents: acc.totalInternalComponents + comp.internalComponents.length,\n }),\n { totalDefaults: 0, totalLiterals: 0, totalInternalComponents: 0 },\n );\n\n print('\\nStats:');\n print(` Default props: ${totals.totalDefaults}`);\n print(` getStyles literals: ${totals.totalLiterals}`);\n print(` Internal component refs: ${totals.totalInternalComponents}`);\n },\n});\n\nconst serializeComponentInfo = (info: ComponentInfo): SerializedComponentInfo => ({\n name: info.name,\n defaultProps: Object.fromEntries(info.defaultProps),\n getStylesLiterals: Object.fromEntries(info.getStylesLiterals),\n cxLiterals: info.cxLiterals,\n internalComponents: info.internalComponents,\n internalComponentProps: Object.fromEntries(\n [...info.internalComponentProps.entries()].map(([key, propsMap]) => [\n key,\n Object.fromEntries(propsMap),\n ]),\n ),\n propToVariantKeys: Object.fromEntries(info.propToVariantKeys),\n runtimeConfigDefaultProps: Object.fromEntries(info.runtimeConfigDefaultProps),\n runtimeConfigGetStyles: Object.fromEntries(\n [...info.runtimeConfigGetStyles.entries()].map(([key, selectors]) => [key, selectors]),\n ),\n runtimeConfigInternalComponentProps: Object.fromEntries(\n [...info.runtimeConfigInternalComponentProps.entries()].map(([key, propsMap]) => [\n key,\n Object.fromEntries(propsMap),\n ]),\n ),\n motionVarPrefixes: info.motionVarPrefixes,\n});\n\nexport { makeGenerateComponentDataCommand };\nexport type { SerializedComponentInfo };\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,MAAM,oCAAoC,gBAAiD;CACzF,MAAM;CACN,aAAa;CACb,KAAK;CAEL,KAAK,OAAO,WAAuC;EACjD,MAAM,EAAE,SAAS,eAAe,eAAe,MAAM,YAAY;
|
|
1
|
+
{"version":3,"file":"generateComponentData.js","names":[],"sources":["../../src/commands/generateComponentData.ts"],"sourcesContent":["/**\n * Pre-generates component analysis data at build time.\n * Keep src/purger/optimized/README.md in sync when this metadata shape changes.\n * This data is used by the optimized purger to know:\n * - Default prop values for each component\n * - Hardcoded literals in getStyles() calls\n * - Internal component dependencies\n * - Literal props passed to internal components\n */\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { print } from '@yahoo/uds-cli/lib';\nimport type { Project } from 'ts-morph';\n\nimport type { ComponentInfo } from '../purger/optimized/utils/componentAnalyzer';\nimport { analyzeComponent, scanComponentFiles } from '../purger/optimized/utils/componentAnalyzer';\n\ninterface SerializedComponentInfo {\n name: string;\n defaultProps: Record<string, string>;\n getStylesLiterals: Record<string, string>;\n cxLiterals: string[];\n internalComponents: string[];\n internalComponentProps: Record<string, Record<string, string[]>>;\n propToVariantKeys: Record<string, string[]>;\n runtimeConfigDefaultProps: Record<string, string>;\n runtimeConfigGetStyles: Record<string, string[]>;\n runtimeConfigInternalComponentProps: Record<string, Record<string, string[]>>;\n motionVarPrefixes: string[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface GenerateComponentDataProps extends Props {\n // options: PurgeOptions;\n}\n\ntype Context = {\n project: Project;\n componentsDir: string;\n outputFile: string;\n};\n\nconst makeGenerateComponentDataCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'generateComponentData',\n description: `Generates component data for UDS components. This is an internal command used to by the optimized purger.`,\n tag: 'hidden',\n\n run: async (_props: GenerateComponentDataProps) => {\n const { project, componentsDir, outputFile } = await getContext();\n\n print('Scanning components in:', componentsDir);\n\n const componentPaths = await scanComponentFiles(componentsDir);\n\n print(`Found ${componentPaths.size} components`);\n\n const componentDataEntries = await Promise.all(\n [...componentPaths].map(async ([name, filePath]) => {\n try {\n project.addSourceFileAtPath(filePath);\n const info = analyzeComponent(project, filePath);\n\n return info ? ([name, serializeComponentInfo(info)] as const) : null;\n } catch (error) {\n console.warn(`Warning: Could not analyze ${name}:`, error);\n return null;\n }\n }),\n );\n\n const componentData = Object.fromEntries(\n componentDataEntries.filter((entry): entry is readonly [string, SerializedComponentInfo] =>\n Boolean(entry),\n ),\n );\n\n // Write the data\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, JSON.stringify(componentData, null, 2));\n\n print(`Generated component data for ${Object.keys(componentData).length} components`);\n print(`Output written to: ${outputFile}`);\n\n // Print some stats\n const totals = Object.values(componentData).reduce(\n (acc, comp) => ({\n totalDefaults: acc.totalDefaults + Object.keys(comp.defaultProps).length,\n totalLiterals: acc.totalLiterals + Object.keys(comp.getStylesLiterals).length,\n totalInternalComponents: acc.totalInternalComponents + comp.internalComponents.length,\n }),\n { totalDefaults: 0, totalLiterals: 0, totalInternalComponents: 0 },\n );\n\n print('\\nStats:');\n print(` Default props: ${totals.totalDefaults}`);\n print(` getStyles literals: ${totals.totalLiterals}`);\n print(` Internal component refs: ${totals.totalInternalComponents}`);\n },\n});\n\nconst serializeComponentInfo = (info: ComponentInfo): SerializedComponentInfo => ({\n name: info.name,\n defaultProps: Object.fromEntries(info.defaultProps),\n getStylesLiterals: Object.fromEntries(info.getStylesLiterals),\n cxLiterals: info.cxLiterals,\n internalComponents: info.internalComponents,\n internalComponentProps: Object.fromEntries(\n [...info.internalComponentProps.entries()].map(([key, propsMap]) => [\n key,\n Object.fromEntries(propsMap),\n ]),\n ),\n propToVariantKeys: Object.fromEntries(info.propToVariantKeys),\n runtimeConfigDefaultProps: Object.fromEntries(info.runtimeConfigDefaultProps),\n runtimeConfigGetStyles: Object.fromEntries(\n [...info.runtimeConfigGetStyles.entries()].map(([key, selectors]) => [key, selectors]),\n ),\n runtimeConfigInternalComponentProps: Object.fromEntries(\n [...info.runtimeConfigInternalComponentProps.entries()].map(([key, propsMap]) => [\n key,\n Object.fromEntries(propsMap),\n ]),\n ),\n motionVarPrefixes: info.motionVarPrefixes,\n});\n\nexport { makeGenerateComponentDataCommand };\nexport type { SerializedComponentInfo };\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,MAAM,oCAAoC,gBAAi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kD;CAChF,MAAM,KAAK;CACX,cAAc,OAAO,YAAY,KAAK,aAAa;CACnD,mBAAmB,OAAO,YAAY,KAAK,kBAAkB;CAC7D,YAAY,KAAK;CACjB,oBAAoB,KAAK;CACzB,wBAAwB,OAAO,YAC7B,CAAC,GAAG,KAAK,uBAAuB,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,cAAc,CAClE,KACA,OAAO,YAAY,SAAS,CAC7B,CAAC,CACH;CACD,mBAAmB,OAAO,YAAY,KAAK,kBAAkB;CAC7D,2BAA2B,OAAO,YAAY,KAAK,0BAA0B;CAC7E,wBAAwB,OAAO,YAC7B,CAAC,GAAG,KAAK,uBAAuB,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,eAAe,CAAC,KAAK,UAAU,CAAC,CACvF;CACD,qCAAqC,OAAO,YAC1C,CAAC,GAAG,KAAK,oCAAoC,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,cAAc,CAC/E,KACA,OAAO,YAAY,SAAS,CAC7B,CAAC,CACH;CACD,mBAAmB,KAAK;CACzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generatePurgeCSSData.js","names":[],"sources":["../../src/commands/generatePurgeCSSData.ts"],"sourcesContent":["import path from 'node:path';\n\nimport type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { green, print } from '@yahoo/uds-cli/lib';\nimport type { Project } from 'ts-morph';\n\nimport {\n addAutoVariantsToComponentClasses,\n convertVariantsIntoTailwindClass,\n getComponentsDependencies,\n getComponentsProps,\n getExportedComponents,\n getExportsToFilePath,\n getTwClassesInComponent,\n} from '../utils/generatePurgeCSSData';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface GeneratePurgeCSSDataProps extends Props {\n // options: PurgeOptions;\n}\n\ntype Context = {\n project: Project;\n\n variants: Record<string, Record<string, string>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n UDS: Record<string, any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n UDS_EXPERIMENTAL: Record<string, any>;\n};\n\nexport const makeGeneratePurgeCSSDataCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'generatePurgeCSSData',\n description: `Generates purge CSS data for UDS components. This is an internal command used to generate the data needed to purge unused CSS in UDS. It should not be used directly by users.`,\n tag: 'hidden',\n\n run: async (_props: GeneratePurgeCSSDataProps) => {\n const { project, variants, UDS, UDS_EXPERIMENTAL } = await getContext();\n\n // 1. Get all the exported components form UDS as a list\n const exportedComponents = getExportedComponents(UDS, UDS_EXPERIMENTAL);\n const exportsToFilePath = getExportsToFilePath(project);\n // 2. Convert the CVA variants list into something we can easily work with\n const variantsList = convertVariantsIntoTailwindClass(variants);\n // 3. Get the styling props for each component\n const componentToVariants = getComponentsProps(\n project,\n exportedComponents,\n variants,\n variantsList,\n exportsToFilePath,\n );\n // 4. Get components dependencies\n const componentsDependencies = getComponentsDependencies(\n project,\n exportedComponents,\n exportsToFilePath,\n );\n // 5. Get the inline TW classes per component\n let componentToTwClasses = await getTwClassesInComponent(exportedComponents, exportsToFilePath);\n // 6. Add auto variants to component classes\n // NOTE: this is temporary while we work on a proper solution to purge the YOS components\n componentToTwClasses = addAutoVariantsToComponentClasses(componentToTwClasses);\n // 7. Save everything under UDS\n const outputFilePath = path.resolve(process.cwd(), './generated/tailwindPurge.ts');\n const fileContent = `\n//! This file is generated by \\`uds purge\\` from @yahoo/uds\n//! Do not edit directly\n//! If there is issue with this file please report to #ask-uds\n\nexport type PropToUsedOptions = [string, string[]];\nexport type ComponentToVariants = { [key: string]: PropToUsedOptions[] };\nexport type VariantsList = string[];\nexport type ComponentDependencies = { [key: string]: string[] };\nexport type ComponentToTwClasses = { [key: string]: string };\n\nexport const variantsList: VariantsList = ${JSON.stringify(variantsList)};\nexport const componentToVariants: ComponentToVariants = ${JSON.stringify(componentToVariants)};\nexport const componentToTwClasses: ComponentToTwClasses = ${JSON.stringify(componentToTwClasses)};\nexport const componentsDependencies: ComponentDependencies = ${JSON.stringify(componentsDependencies)};\n`;\n\n await Bun.write(outputFilePath, fileContent);\n\n print(green(`✅ Purge CSS Data saved ${outputFilePath}`));\n },\n});\n"],"mappings":";;;;;;AA+BA,MAAa,mCAAmC,gBAAiD;CAC/F,MAAM;CACN,aAAa;CACb,KAAK;CAEL,KAAK,OAAO,WAAsC;EAChD,MAAM,EAAE,SAAS,UAAU,KAAK,qBAAqB,MAAM,YAAY;EAGvE,MAAM,qBAAqB,sBAAsB,KAAK,iBAAiB;EACvE,MAAM,oBAAoB,qBAAqB,QAAQ;EAEvD,MAAM,eAAe,iCAAiC,SAAS;EAE/D,MAAM,sBAAsB,mBAC1B,SACA,oBACA,UACA,cACA,kBACD;EAED,MAAM,yBAAyB,0BAC7B,SACA,oBACA,kBACD;EAED,IAAI,uBAAuB,MAAM,wBAAwB,oBAAoB,kBAAkB;
|
|
1
|
+
{"version":3,"file":"generatePurgeCSSData.js","names":[],"sources":["../../src/commands/generatePurgeCSSData.ts"],"sourcesContent":["import path from 'node:path';\n\nimport type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { green, print } from '@yahoo/uds-cli/lib';\nimport type { Project } from 'ts-morph';\n\nimport {\n addAutoVariantsToComponentClasses,\n convertVariantsIntoTailwindClass,\n getComponentsDependencies,\n getComponentsProps,\n getExportedComponents,\n getExportsToFilePath,\n getTwClassesInComponent,\n} from '../utils/generatePurgeCSSData';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface GeneratePurgeCSSDataProps extends Props {\n // options: PurgeOptions;\n}\n\ntype Context = {\n project: Project;\n\n variants: Record<string, Record<string, string>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n UDS: Record<string, any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n UDS_EXPERIMENTAL: Record<string, any>;\n};\n\nexport const makeGeneratePurgeCSSDataCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'generatePurgeCSSData',\n description: `Generates purge CSS data for UDS components. This is an internal command used to generate the data needed to purge unused CSS in UDS. It should not be used directly by users.`,\n tag: 'hidden',\n\n run: async (_props: GeneratePurgeCSSDataProps) => {\n const { project, variants, UDS, UDS_EXPERIMENTAL } = await getContext();\n\n // 1. Get all the exported components form UDS as a list\n const exportedComponents = getExportedComponents(UDS, UDS_EXPERIMENTAL);\n const exportsToFilePath = getExportsToFilePath(project);\n // 2. Convert the CVA variants list into something we can easily work with\n const variantsList = convertVariantsIntoTailwindClass(variants);\n // 3. Get the styling props for each component\n const componentToVariants = getComponentsProps(\n project,\n exportedComponents,\n variants,\n variantsList,\n exportsToFilePath,\n );\n // 4. Get components dependencies\n const componentsDependencies = getComponentsDependencies(\n project,\n exportedComponents,\n exportsToFilePath,\n );\n // 5. Get the inline TW classes per component\n let componentToTwClasses = await getTwClassesInComponent(exportedComponents, exportsToFilePath);\n // 6. Add auto variants to component classes\n // NOTE: this is temporary while we work on a proper solution to purge the YOS components\n componentToTwClasses = addAutoVariantsToComponentClasses(componentToTwClasses);\n // 7. Save everything under UDS\n const outputFilePath = path.resolve(process.cwd(), './generated/tailwindPurge.ts');\n const fileContent = `\n//! This file is generated by \\`uds purge\\` from @yahoo/uds\n//! Do not edit directly\n//! If there is issue with this file please report to #ask-uds\n\nexport type PropToUsedOptions = [string, string[]];\nexport type ComponentToVariants = { [key: string]: PropToUsedOptions[] };\nexport type VariantsList = string[];\nexport type ComponentDependencies = { [key: string]: string[] };\nexport type ComponentToTwClasses = { [key: string]: string };\n\nexport const variantsList: VariantsList = ${JSON.stringify(variantsList)};\nexport const componentToVariants: ComponentToVariants = ${JSON.stringify(componentToVariants)};\nexport const componentToTwClasses: ComponentToTwClasses = ${JSON.stringify(componentToTwClasses)};\nexport const componentsDependencies: ComponentDependencies = ${JSON.stringify(componentsDependencies)};\n`;\n\n await Bun.write(outputFilePath, fileContent);\n\n print(green(`✅ Purge CSS Data saved ${outputFilePath}`));\n },\n});\n"],"mappings":";;;;;;AA+BA,MAAa,mCAAmC,gBAAiD;CAC/F,MAAM;CACN,aAAa;CACb,KAAK;CAEL,KAAK,OAAO,WAAsC;EAChD,MAAM,EAAE,SAAS,UAAU,KAAK,qBAAqB,MAAM,YAAY;EAGvE,MAAM,qBAAqB,sBAAsB,KAAK,iBAAiB;EACvE,MAAM,oBAAoB,qBAAqB,QAAQ;EAEvD,MAAM,eAAe,iCAAiC,SAAS;EAE/D,MAAM,sBAAsB,mBAC1B,SACA,oBACA,UACA,cACA,kBACD;EAED,MAAM,yBAAyB,0BAC7B,SACA,oBACA,kBACD;EAED,IAAI,uBAAuB,MAAM,wBAAwB,oBAAoB,kBAAkB;EAG/F,uBAAuB,kCAAkC,qBAAqB;EAE9E,MAAM,iBAAiB,KAAK,QAAQ,QAAQ,KAAK,EAAE,+BAA+B;EAClF,MAAM,cAAc;;;;;;;;;;;4CAWoB,KAAK,UAAU,aAAa,CAAC;0DACf,KAAK,UAAU,oBAAoB,CAAC;4DAClC,KAAK,UAAU,qBAAqB,CAAC;+DAClC,KAAK,UAAU,uBAAuB,CAAC;;EAGlG,MAAM,IAAI,MAAM,gBAAgB,YAAY;EAE5C,MAAM,MAAM,0BAA0B,iBAAiB,CAAC;;CAE3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"purge.js","names":[],"sources":["../../src/commands/purge.ts"],"sourcesContent":["import type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { print, spinStart, spinStop } from '@yahoo/uds-cli/lib';\n\nimport type { GeneratedPurgeCSSData, PurgeOptions } from '../purger/legacy/purgeCSS';\nimport { purge } from '../purger/legacy/purgeCSS';\nimport { purgeOptimized } from '../purger/optimized';\nimport type { SerializedComponentInfo } from './generateComponentData';\n\ntype Context = {\n variants: Record<string, Record<string, string>>;\n autoVariants: Record<string, Record<string, string>>;\n componentData: Record<string, SerializedComponentInfo>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJson: Record<string, any>;\n generatedPurgeCssData: GeneratedPurgeCSSData;\n};\n\nexport const makePurgeCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'purge',\n description: `Purge unused CSS`,\n\n run: async (props: Props) => {\n const { entry, output, optimized, config } = props.options as Props['options'] & PurgeOptions;\n const useOptimized = optimized === 'true' || optimized === true;\n\n const { variants, autoVariants, packageJson, generatedPurgeCssData, componentData } =\n await getContext();\n\n if (useOptimized) {\n spinStart('Purging CSS with optimized purger...');\n try {\n const result = await purgeOptimized({\n entry: typeof entry === 'string' || Array.isArray(entry) ? entry : undefined,\n output: typeof output === 'string' ? output : undefined,\n variants,\n autoVariants,\n componentData,\n });\n\n spinStop(\n '✅',\n `Purging done (optimized)! Generated ${result.stats.classesGenerated} classes in ${result.stats.timeMs}ms`,\n );\n print(` Files scanned: ${result.stats.filesScanned}`);\n print(` Spreads traced: ${result.stats.spreadsTraced}`);\n print(` Expressions resolved: ${result.stats.expressionsResolved}`);\n // await trackEvent('purge', { optimized: true });\n return;\n } catch (error) {\n if (error instanceof Error) {\n spinStop('❌', error.message);\n } else {\n spinStop('❌', 'Purging css failed! Please reach out to #uds-ask channel for support.');\n }\n process.exitCode = 1;\n }\n } else {\n spinStart('Purging css started...');\n try {\n await purge(variants, packageJson, generatedPurgeCssData, {\n config: typeof config === 'string' ? config : undefined,\n entry: typeof entry === 'string' || Array.isArray(entry) ? entry : undefined,\n output: typeof output === 'string' ? output : undefined,\n });\n spinStop('✅', 'Purging css done!');\n // await trackEvent('purge');\n return;\n } catch (error) {\n if (error instanceof Error) {\n spinStop('❌', error.message);\n } else {\n spinStop('❌', 'Purging css failed! Please reach out to #uds-ask channel for support.');\n }\n process.exitCode = 1;\n }\n }\n },\n});\n"],"mappings":";;;;;;AAiBA,MAAa,oBAAoB,gBAAiD;CAChF,MAAM;CACN,aAAa;CAEb,KAAK,OAAO,UAAiB;EAC3B,MAAM,EAAE,OAAO,QAAQ,WAAW,WAAW,MAAM;EACnD,MAAM,eAAe,cAAc,UAAU,cAAc;EAE3D,MAAM,EAAE,UAAU,cAAc,aAAa,uBAAuB,kBAClE,MAAM,YAAY;
|
|
1
|
+
{"version":3,"file":"purge.js","names":[],"sources":["../../src/commands/purge.ts"],"sourcesContent":["import type { Command, Props } from '@yahoo/uds-cli/lib';\nimport { print, spinStart, spinStop } from '@yahoo/uds-cli/lib';\n\nimport type { GeneratedPurgeCSSData, PurgeOptions } from '../purger/legacy/purgeCSS';\nimport { purge } from '../purger/legacy/purgeCSS';\nimport { purgeOptimized } from '../purger/optimized';\nimport type { SerializedComponentInfo } from './generateComponentData';\n\ntype Context = {\n variants: Record<string, Record<string, string>>;\n autoVariants: Record<string, Record<string, string>>;\n componentData: Record<string, SerializedComponentInfo>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJson: Record<string, any>;\n generatedPurgeCssData: GeneratedPurgeCSSData;\n};\n\nexport const makePurgeCommand = (getContext: () => Promise<Context>): Command => ({\n name: 'purge',\n description: `Purge unused CSS`,\n\n run: async (props: Props) => {\n const { entry, output, optimized, config } = props.options as Props['options'] & PurgeOptions;\n const useOptimized = optimized === 'true' || optimized === true;\n\n const { variants, autoVariants, packageJson, generatedPurgeCssData, componentData } =\n await getContext();\n\n if (useOptimized) {\n spinStart('Purging CSS with optimized purger...');\n try {\n const result = await purgeOptimized({\n entry: typeof entry === 'string' || Array.isArray(entry) ? entry : undefined,\n output: typeof output === 'string' ? output : undefined,\n variants,\n autoVariants,\n componentData,\n });\n\n spinStop(\n '✅',\n `Purging done (optimized)! Generated ${result.stats.classesGenerated} classes in ${result.stats.timeMs}ms`,\n );\n print(` Files scanned: ${result.stats.filesScanned}`);\n print(` Spreads traced: ${result.stats.spreadsTraced}`);\n print(` Expressions resolved: ${result.stats.expressionsResolved}`);\n // await trackEvent('purge', { optimized: true });\n return;\n } catch (error) {\n if (error instanceof Error) {\n spinStop('❌', error.message);\n } else {\n spinStop('❌', 'Purging css failed! Please reach out to #uds-ask channel for support.');\n }\n process.exitCode = 1;\n }\n } else {\n spinStart('Purging css started...');\n try {\n await purge(variants, packageJson, generatedPurgeCssData, {\n config: typeof config === 'string' ? config : undefined,\n entry: typeof entry === 'string' || Array.isArray(entry) ? entry : undefined,\n output: typeof output === 'string' ? output : undefined,\n });\n spinStop('✅', 'Purging css done!');\n // await trackEvent('purge');\n return;\n } catch (error) {\n if (error instanceof Error) {\n spinStop('❌', error.message);\n } else {\n spinStop('❌', 'Purging css failed! Please reach out to #uds-ask channel for support.');\n }\n process.exitCode = 1;\n }\n }\n },\n});\n"],"mappings":";;;;;;AAiBA,MAAa,oBAAoB,gBAAiD;CAChF,MAAM;CACN,aAAa;CAEb,KAAK,OAAO,UAAiB;EAC3B,MAAM,EAAE,OAAO,QAAQ,WAAW,WAAW,MAAM;EACnD,MAAM,eAAe,cAAc,UAAU,cAAc;EAE3D,MAAM,EAAE,UAAU,cAAc,aAAa,uBAAuB,kBAClE,MAAM,YAAY;EAEpB,IAAI,cAAc;GAChB,UAAU,uCAAuC;GACjD,IAAI;IACF,MAAM,SAAS,MAAM,eAAe;KAClC,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,GAAG,QAAQ,KAAA;KACnE,QAAQ,OAAO,WAAW,WAAW,SAAS,KAAA;KAC9C;KACA;KACA;KACD,CAAC;IAEF,SACE,KACA,uCAAuC,OAAO,MAAM,iBAAiB,cAAc,OAAO,MAAM,OAAO,IACxG;IACD,MAAM,qBAAqB,OAAO,MAAM,eAAe;IACvD,MAAM,sBAAsB,OAAO,MAAM,gBAAgB;IACzD,MAAM,4BAA4B,OAAO,MAAM,sBAAsB;IAErE;YACO,OAAO;IACd,IAAI,iBAAiB,OACnB,SAAS,KAAK,MAAM,QAAQ;SAE5B,SAAS,KAAK,wEAAwE;IAExF,QAAQ,WAAW;;SAEhB;GACL,UAAU,yBAAyB;GACnC,IAAI;IACF,MAAM,MAAM,UAAU,aAAa,uBAAuB;KACxD,QAAQ,OAAO,WAAW,WAAW,SAAS,KAAA;KAC9C,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,GAAG,QAAQ,KAAA;KACnE,QAAQ,OAAO,WAAW,WAAW,SAAS,KAAA;KAC/C,CAAC;IACF,SAAS,KAAK,oBAAoB;IAElC;YACO,OAAO;IACd,IAAI,iBAAiB,OACnB,SAAS,KAAK,MAAM,QAAQ;SAE5B,SAAS,KAAK,wEAAwE;IAExF,QAAQ,WAAW;;;;CAI1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.helpers.js","names":[],"sources":["../../src/css/generate.helpers.ts"],"sourcesContent":["import path from 'node:path';\n\nimport type { UniversalTokensConfig } from '@yahoo/uds-config';\nimport autoprefixer from 'autoprefixer';\nimport postcss from 'postcss';\n// @ts-expect-error - no types\nimport pruneVar from 'postcss-prune-var';\nimport postcssScope from 'postcss-scope';\nimport tailwindcss from 'tailwindcss';\nimport type { SafelistConfig } from 'tailwindcss/types/config';\n\n// eslint-disable-next-line import/no-relative-packages\nimport { iconPruneVarsSafelist } from '../../../icons/src/safelist';\nimport { getInternalSafelistClasses } from '../purger/optimized/utils/safelist';\nimport { getIconStyles } from '../tailwind/components/getIconStyles';\nimport { tailwindPlugin } from '../tailwind/tailwindPlugin';\nimport { hasAllowedEntryFileExtension } from '../utils/entryPoints';\nimport type { OptimizeCSSOptions } from '../utils/optimizeCSS';\nimport { optimizeCSS } from '../utils/optimizeCSS';\nimport { preserveVars, preserveVarsCleanup } from '../utils/postcssPreserveVars';\nimport { fixScopedColorModeSelectorsPlugin, fixScopedSelfOrParentSelectorsPlugin } from './postcss';\nimport { formatCssDuration } from './runner.helpers';\nimport type { UDSCSSOptimizationOptions, UDSCSSVarSafelistPattern } from './theme';\nimport { formatBytes } from './utils';\n\ntype CssOptimizationOptions = UDSCSSOptimizationOptions;\n\ntype CssOptionsLike = {\n preflight?: boolean;\n fontFaceDeclarations?: boolean;\n optimization?: CssOptimizationOptions;\n};\n\ntype CssFeatureFlags = {\n enablePreflight: boolean;\n enableFontFaceDeclarations: boolean;\n shouldOptimize: boolean;\n shouldPruneVars: boolean;\n};\n\nconst getPruneVarSafelist = (cssOptions?: CssOptionsLike): UDSCSSVarSafelistPattern[] => {\n const pruneVars = cssOptions?.optimization?.pruneVars;\n const configuredSafelist =\n pruneVars && typeof pruneVars === 'object' ? (pruneVars.safelist ?? []) : [];\n\n return [...iconPruneVarsSafelist, ...configuredSafelist];\n};\n\nconst getCssFeatureFlags = (cssOptions?: CssOptionsLike): CssFeatureFlags => {\n const optimizationConfig = cssOptions?.optimization;\n const shouldOptimize = optimizationConfig?.enabled !== false;\n const pruneVars = optimizationConfig?.pruneVars;\n\n return {\n enablePreflight: cssOptions?.preflight !== false,\n enableFontFaceDeclarations: cssOptions?.fontFaceDeclarations !== false,\n shouldOptimize,\n shouldPruneVars: shouldOptimize && pruneVars !== false,\n };\n};\n\nconst getContentGlobs = (contentDir: string | string[]): string[] => {\n const contentDirs = Array.isArray(contentDir) ? contentDir : [contentDir];\n\n return contentDirs.map((dir) =>\n hasAllowedEntryFileExtension(dir) ? dir : path.join(dir, '**/*.{js,jsx,mjs,cjs,ts,tsx}'),\n );\n};\n\nconst getRawContentEntries = (rawContents: string[]): Array<{ raw: string; extension: 'html' }> =>\n rawContents.map((rawContent) => ({ raw: rawContent, extension: 'html' }));\n\nconst getInternalSafelistRawContent = (safelist: SafelistConfig[]): string[] => {\n const internalClasses = new Set(getInternalSafelistClasses());\n const matchedInternalClasses = safelist.filter(\n (entry): entry is string => typeof entry === 'string' && internalClasses.has(entry),\n );\n\n if (matchedInternalClasses.length === 0) {\n return [];\n }\n\n return [`<div class=\"${matchedInternalClasses.join(' ')}\"></div>`];\n};\n\nconst getInternalIconModeCss = (scopeClass?: string): string => {\n const iconStyles = getIconStyles();\n\n return Object.entries(iconStyles)\n .map(([selector, declarations]) => {\n const scopedSelector = scopeClass ? `${scopeClass} ${selector}` : selector;\n const declarationString = Object.entries(declarations)\n .map(([property, value]) => `${property}: ${value};`)\n .join(' ');\n\n return `${scopedSelector} { ${declarationString} }`;\n })\n .join(' ');\n};\n\nconst createTailwindPlugin = (options: {\n contentDir: string | string[];\n rawContents?: string[];\n safelist: SafelistConfig[];\n config: UniversalTokensConfig;\n enablePreflight: boolean;\n enableFontFaceDeclarations: boolean;\n}): postcss.AcceptedPlugin => {\n const plugin = tailwindcss({\n content: [\n ...getContentGlobs(options.contentDir),\n ...getRawContentEntries(getInternalSafelistRawContent(options.safelist)),\n ...getRawContentEntries(options.rawContents ?? []),\n ],\n safelist: options.safelist,\n corePlugins: { preflight: options.enablePreflight },\n plugins: [\n tailwindPlugin({\n config: options.config,\n disableFontFaceDeclarations: !options.enableFontFaceDeclarations,\n ignorePluginSafelists: true,\n }),\n ],\n });\n\n return plugin as postcss.AcceptedPlugin;\n};\n\nconst getPruneVarPlugins = (\n safeVarPrefixes: UDSCSSVarSafelistPattern[],\n): postcss.AcceptedPlugin[] => {\n if (safeVarPrefixes.length === 0) {\n return [pruneVar() as postcss.AcceptedPlugin];\n }\n\n return [\n preserveVars({ preserve: safeVarPrefixes }) as postcss.AcceptedPlugin,\n pruneVar() as postcss.AcceptedPlugin,\n preserveVarsCleanup() as postcss.AcceptedPlugin,\n ];\n};\n\nconst buildPostcssPlugins = (options: {\n tailwindPlugin: postcss.AcceptedPlugin;\n shouldPruneVars: boolean;\n safeVarPrefixes: UDSCSSVarSafelistPattern[];\n scopeClass?: string;\n}): postcss.AcceptedPlugin[] => {\n const plugins: postcss.AcceptedPlugin[] = [options.tailwindPlugin, autoprefixer()];\n\n if (options.shouldPruneVars) {\n plugins.push(...getPruneVarPlugins(options.safeVarPrefixes));\n }\n\n if (options.scopeClass) {\n plugins.push(postcssScope(options.scopeClass) as postcss.AcceptedPlugin);\n }\n\n return plugins;\n};\n\nconst applyScopedColorModeFix = async (css: string, scopeClass?: string): Promise<string> => {\n if (!scopeClass) {\n return css;\n }\n\n const fixResult = await postcss([\n fixScopedSelfOrParentSelectorsPlugin(scopeClass),\n fixScopedColorModeSelectorsPlugin(scopeClass),\n ]).process(css, {\n from: undefined,\n });\n\n return fixResult.css;\n};\n\nconst optimizeGeneratedCss = async (options: {\n css: string;\n shouldOptimize: boolean;\n optimizationConfig?: CssOptimizationOptions;\n referenceCss?: string;\n scopeClass?: string;\n}): Promise<{\n css: string;\n optimizationStats?: {\n originalSize: number;\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n}> => {\n if (!options.shouldOptimize) {\n return { css: options.css };\n }\n\n const optimizationOptions: OptimizeCSSOptions = {\n removeUnusedFonts: options.optimizationConfig?.removeUnusedFonts,\n removeEmptyRules: options.optimizationConfig?.removeEmptyRules,\n aggregateDuplicateSelectors: options.optimizationConfig?.aggregateDuplicateSelectors,\n referenceCss: options.referenceCss,\n scopeClass: options.scopeClass,\n };\n\n const optimized = await optimizeCSS(options.css, optimizationOptions);\n return {\n css: optimized.css,\n optimizationStats: {\n originalSize: optimized.stats.originalSize,\n originalSizeGzip: optimized.stats.originalSizeGzip,\n fontFacesRemoved: optimized.stats.fontFacesRemoved,\n emptyRulesRemoved: optimized.stats.emptyRulesRemoved,\n validationErrors: optimized.validation.errors,\n },\n };\n};\n\nconst printSimpleModeStats = (options: {\n cwd: string;\n outputPath: string;\n totalFilesScanned: number;\n scannedFilePaths?: string[];\n classCount: number;\n sizeBytes: number;\n sizeGzipBytes: number;\n duration: number;\n scope?: string;\n verbose?: boolean;\n optimizationStats?: {\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n print: (value: string) => void;\n magenta: (value: string) => string;\n cyan: (value: string) => string;\n yellow: (value: string) => string;\n}): void => {\n const { print, magenta, cyan, yellow } = options;\n const getDisplayPath = (targetPath: string): string => {\n const relativePath = path.relative(options.cwd, targetPath);\n return relativePath.length === 0 ? '.' : relativePath;\n };\n\n print('');\n print(`${magenta('Output:')} ${cyan(getDisplayPath(options.outputPath))}`);\n print(`${magenta('Stats:')}`);\n print(` Files scanned: ${options.totalFilesScanned}`);\n if (options.verbose && options.scannedFilePaths && options.scannedFilePaths.length > 0) {\n [...new Set(options.scannedFilePaths)]\n .sort((left, right) => left.localeCompare(right))\n .forEach((filePath) => print(` • ${cyan(getDisplayPath(filePath))}`));\n }\n print(` Classes: ${options.classCount}`);\n print(\n ` Size: ${formatBytes(options.sizeBytes)} (${formatBytes(options.sizeGzipBytes)} gzipped)`,\n );\n\n const optimizationStats = options.optimizationStats;\n if (optimizationStats) {\n const savedBytesGzip = optimizationStats.originalSizeGzip - options.sizeGzipBytes;\n if (savedBytesGzip > 0) {\n if (optimizationStats.fontFacesRemoved > 0) {\n print(` • removed ${optimizationStats.fontFacesRemoved} unused @font-face`);\n }\n if (optimizationStats.emptyRulesRemoved > 0) {\n print(` • removed ${optimizationStats.emptyRulesRemoved} empty rules`);\n }\n }\n\n if (optimizationStats.validationErrors.length > 0) {\n print(` ${yellow('Validation warnings:')}`);\n optimizationStats.validationErrors.forEach((error) => print(` ${yellow('•')} ${error}`));\n }\n }\n\n print(` Time: ${formatCssDuration(options.duration)}`);\n if (options.scope) {\n print(` Scope: ${cyan(options.scope)}`);\n }\n};\n\nexport {\n applyScopedColorModeFix,\n buildPostcssPlugins,\n createTailwindPlugin,\n getContentGlobs,\n getCssFeatureFlags,\n getInternalIconModeCss,\n getInternalSafelistRawContent,\n getPruneVarSafelist,\n optimizeGeneratedCss,\n printSimpleModeStats,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwCA,MAAM,uBAAuB,eAA4D;CACvF,MAAM,YAAY,YAAY,cAAc;CAC5C,MAAM,qBACJ,aAAa,OAAO,cAAc,WAAY,UAAU,YAAY,EAAE,GAAI,EAAE;AAE9E,QAAO,CAAC,GAAG,uBAAuB,GAAG,mBAAmB;;AAG1D,MAAM,sBAAsB,eAAiD;CAC3E,MAAM,qBAAqB,YAAY;CACvC,MAAM,iBAAiB,oBAAoB,YAAY;CACvD,MAAM,YAAY,oBAAoB;AAEtC,QAAO;EACL,iBAAiB,YAAY,cAAc;EAC3C,4BAA4B,YAAY,y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AAS,QAAQ,KAAK,WAAW;AAC3D,SAAO,aAAa,WAAW,IAAI,MAAM;;AAG3C,OAAM,GAAG;AACT,OAAM,GAAG,QAAQ,UAAU,CAAC,GAAG,KAAK,eAAe,QAAQ,WAAW,CAAC,GAAG;AAC1E,OAAM,GAAG,QAAQ,SAAS,GAAG;AAC7B,OAAM,qBAAqB,QAAQ,oBAAoB;AACvD,KAAI,QAAQ,WAAW,QAAQ,oBAAoB,QAAQ,iBAAiB,SAAS,EACnF,EAAC,GAAG,IAAI,IAAI,QAAQ,iBAAiB,CAAC,CACnC,MAAM,MAAM,UAAU,KAAK,cAAc,MAAM,CAAC,CAChD,SAAS,aAAa,MAAM,WAAW,KAAK,eAAe,SAAS,CAAC,GAAG,CAAC;AAE9E,OAAM,eAAe,QAAQ,aAAa;AAC1C,OACE,YAAY,YAAY,QAAQ,UAAU,CAAC,IAAI,YAAY,QAAQ,cAAc,CAAC,WACnF;CAED,MAAM,oBAAoB,QAAQ;AAClC,KAAI,mBAAmB;AAErB,MADuB,kBAAkB,mBAAmB,QAAQ,gBAC/C,GAAG;AACtB,OAAI,kBAAkB,mBAAmB,EACvC,OAAM,mBAAmB,kBAAkB,iBAAiB,oBAAoB;AAElF,OAAI,kBAAkB,oBAAoB,EACxC,OAAM,mBAAmB,kBAAkB,kBAAkB,cAAc;;AAI/E,MAAI,kBAAkB,iBAAiB,SAAS,GAAG;AACjD,SAAM,MAAM,OAAO,uBAAuB,GAAG;AAC7C,qBAAkB,iBAAiB,SAAS,UAAU,MAAM,SAAS,OAAO,IAAI,CAAC,GAAG,QAAQ,CAAC;;;AAIjG,OAAM,YAAY,kBAAkB,QAAQ,SAAS,GAAG;AACxD,KAAI,QAAQ,MACV,OAAM,aAAa,KAAK,QAAQ,MAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"generate.helpers.js","names":[],"sources":["../../src/css/generate.helpers.ts"],"sourcesContent":["import path from 'node:path';\n\nimport type { UniversalTokensConfig } from '@yahoo/uds-config';\nimport autoprefixer from 'autoprefixer';\nimport postcss from 'postcss';\n// @ts-expect-error - no types\nimport pruneVar from 'postcss-prune-var';\nimport postcssScope from 'postcss-scope';\nimport tailwindcss from 'tailwindcss';\nimport type { SafelistConfig } from 'tailwindcss/types/config';\n\n// eslint-disable-next-line import/no-relative-packages\nimport { iconPruneVarsSafelist } from '../../../icons/src/safelist';\nimport { getInternalSafelistClasses } from '../purger/optimized/utils/safelist';\nimport { getIconStyles } from '../tailwind/components/getIconStyles';\nimport { tailwindPlugin } from '../tailwind/tailwindPlugin';\nimport { hasAllowedEntryFileExtension } from '../utils/entryPoints';\nimport type { OptimizeCSSOptions } from '../utils/optimizeCSS';\nimport { optimizeCSS } from '../utils/optimizeCSS';\nimport { preserveVars, preserveVarsCleanup } from '../utils/postcssPreserveVars';\nimport { fixScopedColorModeSelectorsPlugin, fixScopedSelfOrParentSelectorsPlugin } from './postcss';\nimport { formatCssDuration } from './runner.helpers';\nimport type { UDSCSSOptimizationOptions, UDSCSSVarSafelistPattern } from './theme';\nimport { formatBytes } from './utils';\n\ntype CssOptimizationOptions = UDSCSSOptimizationOptions;\n\ntype CssOptionsLike = {\n preflight?: boolean;\n fontFaceDeclarations?: boolean;\n optimization?: CssOptimizationOptions;\n};\n\ntype CssFeatureFlags = {\n enablePreflight: boolean;\n enableFontFaceDeclarations: boolean;\n shouldOptimize: boolean;\n shouldPruneVars: boolean;\n};\n\nconst getPruneVarSafelist = (cssOptions?: CssOptionsLike): UDSCSSVarSafelistPattern[] => {\n const pruneVars = cssOptions?.optimization?.pruneVars;\n const configuredSafelist =\n pruneVars && typeof pruneVars === 'object' ? (pruneVars.safelist ?? []) : [];\n\n return [...iconPruneVarsSafelist, ...configuredSafelist];\n};\n\nconst getCssFeatureFlags = (cssOptions?: CssOptionsLike): CssFeatureFlags => {\n const optimizationConfig = cssOptions?.optimization;\n const shouldOptimize = optimizationConfig?.enabled !== false;\n const pruneVars = optimizationConfig?.pruneVars;\n\n return {\n enablePreflight: cssOptions?.preflight !== false,\n enableFontFaceDeclarations: cssOptions?.fontFaceDeclarations !== false,\n shouldOptimize,\n shouldPruneVars: shouldOptimize && pruneVars !== false,\n };\n};\n\nconst getContentGlobs = (contentDir: string | string[]): string[] => {\n const contentDirs = Array.isArray(contentDir) ? contentDir : [contentDir];\n\n return contentDirs.map((dir) =>\n hasAllowedEntryFileExtension(dir) ? dir : path.join(dir, '**/*.{js,jsx,mjs,cjs,ts,tsx}'),\n );\n};\n\nconst getRawContentEntries = (rawContents: string[]): Array<{ raw: string; extension: 'html' }> =>\n rawContents.map((rawContent) => ({ raw: rawContent, extension: 'html' }));\n\nconst getInternalSafelistRawContent = (safelist: SafelistConfig[]): string[] => {\n const internalClasses = new Set(getInternalSafelistClasses());\n const matchedInternalClasses = safelist.filter(\n (entry): entry is string => typeof entry === 'string' && internalClasses.has(entry),\n );\n\n if (matchedInternalClasses.length === 0) {\n return [];\n }\n\n return [`<div class=\"${matchedInternalClasses.join(' ')}\"></div>`];\n};\n\nconst getInternalIconModeCss = (scopeClass?: string): string => {\n const iconStyles = getIconStyles();\n\n return Object.entries(iconStyles)\n .map(([selector, declarations]) => {\n const scopedSelector = scopeClass ? `${scopeClass} ${selector}` : selector;\n const declarationString = Object.entries(declarations)\n .map(([property, value]) => `${property}: ${value};`)\n .join(' ');\n\n return `${scopedSelector} { ${declarationString} }`;\n })\n .join(' ');\n};\n\nconst createTailwindPlugin = (options: {\n contentDir: string | string[];\n rawContents?: string[];\n safelist: SafelistConfig[];\n config: UniversalTokensConfig;\n enablePreflight: boolean;\n enableFontFaceDeclarations: boolean;\n}): postcss.AcceptedPlugin => {\n const plugin = tailwindcss({\n content: [\n ...getContentGlobs(options.contentDir),\n ...getRawContentEntries(getInternalSafelistRawContent(options.safelist)),\n ...getRawContentEntries(options.rawContents ?? []),\n ],\n safelist: options.safelist,\n corePlugins: { preflight: options.enablePreflight },\n plugins: [\n tailwindPlugin({\n config: options.config,\n disableFontFaceDeclarations: !options.enableFontFaceDeclarations,\n ignorePluginSafelists: true,\n }),\n ],\n });\n\n return plugin as postcss.AcceptedPlugin;\n};\n\nconst getPruneVarPlugins = (\n safeVarPrefixes: UDSCSSVarSafelistPattern[],\n): postcss.AcceptedPlugin[] => {\n if (safeVarPrefixes.length === 0) {\n return [pruneVar() as postcss.AcceptedPlugin];\n }\n\n return [\n preserveVars({ preserve: safeVarPrefixes }) as postcss.AcceptedPlugin,\n pruneVar() as postcss.AcceptedPlugin,\n preserveVarsCleanup() as postcss.AcceptedPlugin,\n ];\n};\n\nconst buildPostcssPlugins = (options: {\n tailwindPlugin: postcss.AcceptedPlugin;\n shouldPruneVars: boolean;\n safeVarPrefixes: UDSCSSVarSafelistPattern[];\n scopeClass?: string;\n}): postcss.AcceptedPlugin[] => {\n const plugins: postcss.AcceptedPlugin[] = [options.tailwindPlugin, autoprefixer()];\n\n if (options.shouldPruneVars) {\n plugins.push(...getPruneVarPlugins(options.safeVarPrefixes));\n }\n\n if (options.scopeClass) {\n plugins.push(postcssScope(options.scopeClass) as postcss.AcceptedPlugin);\n }\n\n return plugins;\n};\n\nconst applyScopedColorModeFix = async (css: string, scopeClass?: string): Promise<string> => {\n if (!scopeClass) {\n return css;\n }\n\n const fixResult = await postcss([\n fixScopedSelfOrParentSelectorsPlugin(scopeClass),\n fixScopedColorModeSelectorsPlugin(scopeClass),\n ]).process(css, {\n from: undefined,\n });\n\n return fixResult.css;\n};\n\nconst optimizeGeneratedCss = async (options: {\n css: string;\n shouldOptimize: boolean;\n optimizationConfig?: CssOptimizationOptions;\n referenceCss?: string;\n scopeClass?: string;\n}): Promise<{\n css: string;\n optimizationStats?: {\n originalSize: number;\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n}> => {\n if (!options.shouldOptimize) {\n return { css: options.css };\n }\n\n const optimizationOptions: OptimizeCSSOptions = {\n removeUnusedFonts: options.optimizationConfig?.removeUnusedFonts,\n removeEmptyRules: options.optimizationConfig?.removeEmptyRules,\n aggregateDuplicateSelectors: options.optimizationConfig?.aggregateDuplicateSelectors,\n referenceCss: options.referenceCss,\n scopeClass: options.scopeClass,\n };\n\n const optimized = await optimizeCSS(options.css, optimizationOptions);\n return {\n css: optimized.css,\n optimizationStats: {\n originalSize: optimized.stats.originalSize,\n originalSizeGzip: optimized.stats.originalSizeGzip,\n fontFacesRemoved: optimized.stats.fontFacesRemoved,\n emptyRulesRemoved: optimized.stats.emptyRulesRemoved,\n validationErrors: optimized.validation.errors,\n },\n };\n};\n\nconst printSimpleModeStats = (options: {\n cwd: string;\n outputPath: string;\n totalFilesScanned: number;\n scannedFilePaths?: string[];\n classCount: number;\n sizeBytes: number;\n sizeGzipBytes: number;\n duration: number;\n scope?: string;\n verbose?: boolean;\n optimizationStats?: {\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n print: (value: string) => void;\n magenta: (value: string) => string;\n cyan: (value: string) => string;\n yellow: (value: string) => string;\n}): void => {\n const { print, magenta, cyan, yellow } = options;\n const getDisplayPath = (targetPath: string): string => {\n const relativePath = path.relative(options.cwd, targetPath);\n return relativePath.length === 0 ? '.' : relativePath;\n };\n\n print('');\n print(`${magenta('Output:')} ${cyan(getDisplayPath(options.outputPath))}`);\n print(`${magenta('Stats:')}`);\n print(` Files scanned: ${options.totalFilesScanned}`);\n if (options.verbose && options.scannedFilePaths && options.scannedFilePaths.length > 0) {\n [...new Set(options.scannedFilePaths)]\n .sort((left, right) => left.localeCompare(right))\n .forEach((filePath) => print(` • ${cyan(getDisplayPath(filePath))}`));\n }\n print(` Classes: ${options.classCount}`);\n print(\n ` Size: ${formatBytes(options.sizeBytes)} (${formatBytes(options.sizeGzipBytes)} gzipped)`,\n );\n\n const optimizationStats = options.optimizationStats;\n if (optimizationStats) {\n const savedBytesGzip = optimizationStats.originalSizeGzip - options.sizeGzipBytes;\n if (savedBytesGzip > 0) {\n if (optimizationStats.fontFacesRemoved > 0) {\n print(` • removed ${optimizationStats.fontFacesRemoved} unused @font-face`);\n }\n if (optimizationStats.emptyRulesRemoved > 0) {\n print(` • removed ${optimizationStats.emptyRulesRemoved} empty rules`);\n }\n }\n\n if (optimizationStats.validationErrors.length > 0) {\n print(` ${yellow('Validation warnings:')}`);\n optimizationStats.validationErrors.forEach((error) => print(` ${yellow('•')} ${error}`));\n }\n }\n\n print(` Time: ${formatCssDuration(options.duration)}`);\n if (options.scope) {\n print(` Scope: ${cyan(options.scope)}`);\n }\n};\n\nexport {\n applyScopedColorModeFix,\n buildPostcssPlugins,\n createTailwindPlugin,\n getContentGlobs,\n getCssFeatureFlags,\n getInternalIconModeCss,\n getInternalSafelistRawContent,\n getPruneVarSafelist,\n optimizeGeneratedCss,\n printSimpleModeStats,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwCA,MAAM,uBAAuB,eAA4D;CACvF,MAAM,YAAY,YAAY,cAAc;CAC5C,MAAM,qBACJ,aAAa,OAAO,cAAc,WAAY,UAAU,YAAY,EAAE,GAAI,EAAE;CAE9E,OAAO,CAAC,GAAG,uBAAuB,GAAG,mBAAmB;;AAG1D,MAAM,sBAAsB,eAAiD;CAC3E,MAAM,qBAAqB,YAAY;CACvC,MAAM,iBAAiB,oBAAoB,YAAY;CACvD,MAAM,YAAY,oBAAoB;CAEtC,OAAO;EACL,iBAAiB,YAAY,cAAc;EAC3C,4BAA4B,YAAY,yBAAyB;EACjE;EACA,iBAAiB,kBAAkB,cAAc;EAClD;;AAGH,MAAM,mBAAmB,eAA4C;CAGnE,QAFoB,MAAM,QAAQ,WAAW,GAAG,aAAa,CAAC,WAAW,EAEtD,KAAK,QACtB,6BAA6B,IAAI,GAAG,MAAM,KAAK,KAAK,KAAK,+BAA+B,CACzF;;AAGH,MAAM,wBAAwB,gBAC5B,YAAY,KAAK,gBAAgB;CAAE,KAAK;CAAY,WAAW;CAAQ,EAAE;AAE3E,MAAM,iCAAiC,aAAyC;CAC9E,MAAM,kBAAkB,IAAI,I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,MAAM,MAAM,UAAU,KAAK,cAAc,MAAM,CAAC,CAChD,SAAS,aAAa,MAAM,WAAW,KAAK,eAAe,SAAS,CAAC,GAAG,CAAC;CAE9E,MAAM,eAAe,QAAQ,aAAa;CAC1C,MACE,YAAY,YAAY,QAAQ,UAAU,CAAC,IAAI,YAAY,QAAQ,cAAc,CAAC,WACnF;CAED,MAAM,oBAAoB,QAAQ;CAClC,IAAI,mBAAmB;EAErB,IADuB,kBAAkB,mBAAmB,QAAQ,gBAC/C,GAAG;GACtB,IAAI,kBAAkB,mBAAmB,GACvC,MAAM,mBAAmB,kBAAkB,iBAAiB,oBAAoB;GAElF,IAAI,kBAAkB,oBAAoB,GACxC,MAAM,mBAAmB,kBAAkB,kBAAkB,cAAc;;EAI/E,IAAI,kBAAkB,iBAAiB,SAAS,GAAG;GACjD,MAAM,MAAM,OAAO,uBAAuB,GAAG;GAC7C,kBAAkB,iBAAiB,SAAS,UAAU,MAAM,SAAS,OAAO,IAAI,CAAC,GAAG,QAAQ,CAAC;;;CAIjG,MAAM,YAAY,kBAAkB,QAAQ,SAAS,GAAG;CACxD,IAAI,QAAQ,OACV,MAAM,aAAa,KAAK,QAAQ,MAAM,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","names":[],"sources":["../../src/css/generate.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { gzipSync } from 'node:zlib';\n\nimport { cyan, magenta, print, spinStop, yellow } from '@yahoo/uds-cli/lib';\nimport type { UniversalTokensConfig } from '@yahoo/uds-config';\nimport { defaultTokensConfig } from '@yahoo/uds-config';\nimport postcss from 'postcss';\nimport type { SafelistConfig } from 'tailwindcss/types/config';\n\nimport type { SerializedComponentInfo } from '../commands/generateComponentData';\nimport {\n deduplicateSafelist,\n getInternalSafelistClasses,\n getThemeAndScaleClasses,\n} from '../purger/optimized';\nimport type { EntryValue } from '../utils/entryPoints';\nimport { resolveEntryPaths } from '../utils/entryPoints';\nimport {\n applyScopedColorModeFix,\n buildPostcssPlugins,\n createTailwindPlugin,\n getCssFeatureFlags,\n getInternalIconModeCss,\n optimizeGeneratedCss,\n printSimpleModeStats,\n} from './generate.helpers';\nimport { loadConfigFile, scanDirectoriesForSafelist } from './nodeUtils';\nimport { measureAsync } from './perf';\nimport type { UDSCSSOptimizationOptions, UDSCSSVarSafelistPattern } from './theme';\nimport {\n extractRuntimeConfigValues,\n extractVariantDefaults,\n getConfigurableCssVariables,\n getMotionVarPrefixes,\n} from './utils';\n\n/**\n * Result from generating CSS\n */\ninterface CSSResult {\n css: string;\n sizeBytes: number;\n sizeGzipBytes: number;\n classCount: number;\n optimizationStats?: {\n originalSize: number;\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n}\n\n/**\n * CSS generation options for uds.theme.ts\n */\ninterface UDSCSSOptions {\n /** CSS scope wrapper class (optional) */\n scope?: string;\n /** Safelist of CSS classes to always include */\n safelist?: SafelistConfig[];\n /** CSS optimization settings */\n optimization?: UDSCSSOptimizationOptions;\n /** Include Tailwind preflight/reset styles (default: true) */\n preflight?: boolean;\n /** Include @font-face declarations (default: true) */\n fontFaceDeclarations?: boolean;\n /** Debounce delay (ms) for watch mode regenerations */\n watchDebounce?: number;\n}\n\n/**\n * Options for generateCSS function\n */\ninterface GenerateCSSOptions {\n /** CSS scope wrapper class */\n scope?: string;\n /** Directory to scan for arbitrary Tailwind classes (className props) */\n contentDir?: string | string[];\n /** CSS generation options from theme config */\n cssOptions?: UDSCSSOptions;\n /** Reference CSS to deduplicate font-faces against (for scoped CSS) */\n referenceCss?: string;\n /** CSS variable prefixes or patterns to preserve during pruning */\n safeVarPrefixes?: UDSCSSVarSafelistPattern[];\n}\n\nconst normalizeScope = (scope?: string): string | undefined => {\n const trimmedScope = scope?.trim();\n return trimmedScope ? trimmedScope : undefined;\n};\n\nconst getArbitrarySafelistRawContent = (safelist: SafelistConfig[]): string[] => {\n const arbitraryClasses = safelist.filter(\n (entry): entry is string => typeof entry === 'string' && entry.includes('['),\n );\n\n if (arbitraryClasses.length === 0) {\n return [];\n }\n\n return [`<div class=\"${arbitraryClasses.join(' ')}\"></div>`];\n};\n\n/**\n * Generate CSS from a safelist using Tailwind + PostCSS\n * @param safelist - UDS component classes to include\n * @param config - Token configuration\n * @param options - Additional options\n */\nconst generateCSS = async (\n safelist: SafelistConfig[],\n config: UniversalTokensConfig,\n options?: GenerateCSSOptions,\n): Promise<CSSResult> => {\n // Do we need base?\n const sourceCSS = '@tailwind base; @tailwind components; @tailwind utilities';\n\n const contentDir = options?.contentDir ?? path.join(process.cwd(), 'src');\n const cssFlags = getCssFeatureFlags(options?.cssOptions);\n const optimizationConfig = options?.cssOptions?.optimization;\n const scopeClass = normalizeScope(options?.scope) ?? normalizeScope(options?.cssOptions?.scope);\n const twPlugin = createTailwindPlugin({\n contentDir,\n rawContents: getArbitrarySafelistRawContent(safelist),\n safelist,\n config,\n enablePreflight: cssFlags.enablePreflight,\n enableFontFaceDeclarations: cssFlags.enableFontFaceDeclarations,\n });\n const plugins = buildPostcssPlugins({\n tailwindPlugin: twPlugin,\n shouldPruneVars: cssFlags.shouldPruneVars,\n safeVarPrefixes: options?.safeVarPrefixes ?? [],\n scopeClass,\n });\n\n const result = await measureAsync('gen:postcss', () =>\n postcss(plugins).process(sourceCSS, { from: undefined }),\n );\n let css = await measureAsync('gen:scoped-color-fix', () =>\n applyScopedColorModeFix(result.css, scopeClass),\n );\n if (!css.includes('uds-light-mode-icon') || !css.includes('uds-dark-mode-icon')) {\n css = `${css} ${getInternalIconModeCss(scopeClass)}`.trim();\n }\n const optimizedCss = await measureAsync('gen:optimize', () =>\n optimizeGeneratedCss({\n css,\n shouldOptimize: cssFlags.shouldOptimize,\n optimizationConfig,\n referenceCss: options?.referenceCss,\n scopeClass,\n }),\n );\n css = optimizedCss.css;\n\n const sizeBytes = Buffer.byteLength(css, 'utf8');\n const sizeGzipBytes = gzipSync(css).length;\n\n return {\n css,\n sizeBytes,\n sizeGzipBytes,\n classCount: safelist.length,\n optimizationStats: optimizedCss.optimizationStats,\n };\n};\n\n/**\n * Generate CSS in simple mode (no uds.theme.ts)\n */\nconst generateSimpleModeCSS = async (options: {\n workspaceDir: string;\n entry: EntryValue;\n outFile: string;\n variants: Record<string, Record<string, string>>;\n autoVariants: Record<string, Record<string, string>>;\n componentData: Record<string, SerializedComponentInfo>;\n scope?: string;\n configPath?: string;\n isWatch?: boolean;\n silent?: boolean;\n verbose?: boolean;\n}): Promise<{ success: boolean; outputPath: string; packageDirs?: string[] }> => {\n const isWatch = options.isWatch === true;\n const isSilent = options.silent === true;\n const shouldLogStats = !isSilent && !isWatch;\n const startTime = performance.now();\n const colorModes: ('dark' | 'light')[] = ['dark']; // Light mode is already in :root\n\n // Load config if provided, otherwise use default\n let tokensConfig: UniversalTokensConfig = defaultTokensConfig;\n if (options.configPath) {\n const loadedConfig = await loadConfigFile<UniversalTokensConfig>(options.configPath);\n if (loadedConfig) {\n tokensConfig = loadedConfig;\n } else if (shouldLogStats) {\n spinStop('⚠️', `Config file not found: ${options.configPath}, using defaults`);\n }\n }\n\n // Extract variant defaults from config for auto-variant class generation\n const variantDefaults = extractVariantDefaults(tokensConfig);\n const runtimeConfigValues = extractRuntimeConfigValues(tokensConfig);\n\n const resolvedEntries = resolveEntryPaths(options.entry, options.workspaceDir);\n const entryDirs = resolvedEntries.map((entry) => entry.absolutePath);\n const scanResult = await scanDirectoriesForSafelist(\n entryDirs,\n colorModes,\n options.variants,\n options.autoVariants,\n options.componentData,\n variantDefaults,\n runtimeConfigValues,\n );\n\n const totalFilesScanned = scanResult.filesScanned;\n const allClasses: string[] = [...scanResult.safelist];\n const allComponents = new Set<string>(scanResult.components);\n const packageDirs: string[] = [\n ...new Set(\n resolvedEntries.map((entry) =>\n entry.kind === 'directory' ? entry.absolutePath : entry.watchDirectory,\n ),\n ),\n ];\n\n // Add color mode classes\n const fullSafelist = [\n ...allClasses,\n ...getThemeAndScaleClasses(colorModes),\n ...getInternalSafelistClasses(),\n ];\n const finalSafelist = deduplicateSafelist(fullSafelist);\n\n // Generate CSS (Tailwind will scan entry dir for arbitrary classes on className props)\n const cssResult = await generateCSS(finalSafelist, tokensConfig, {\n scope: options.scope,\n contentDir: entryDirs,\n safeVarPrefixes: [\n ...getMotionVarPrefixes(options.componentData, [...allComponents]),\n ...getConfigurableCssVariables(),\n ],\n });\n\n // Write output\n const outputPath = path.isAbsolute(options.outFile)\n ? options.outFile\n : path.join(options.workspaceDir, options.outFile);\n const outputDir = path.dirname(outputPath);\n\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n fs.writeFileSync(outputPath, cssResult.css);\n\n const duration = Math.round(performance.now() - startTime);\n\n if (shouldLogStats) {\n printSimpleModeStats({\n cwd: options.workspaceDir,\n outputPath,\n totalFilesScanned,\n scannedFilePaths: scanResult.filePaths,\n classCount: cssResult.classCount,\n sizeBytes: cssResult.sizeBytes,\n sizeGzipBytes: cssResult.sizeGzipBytes,\n duration,\n scope: options.scope,\n verbose: options.verbose,\n optimizationStats: cssResult.optimizationStats,\n print,\n magenta,\n cyan,\n yellow,\n });\n }\n\n return { success: true, outputPath, packageDirs };\n};\n\nexport { generateCSS, generateSimpleModeCSS };\nexport type { UDSCSSOptions };\n"],"mappings":";;;;;;;;;;;;;;;;AAwFA,MAAM,kBAAkB,UAAuC;CAC7D,MAAM,eAAe,OAAO,MAAM;AAClC,QAAO,eAAe,eAAe,KAAA;;AAGvC,MAAM,kCAAkC,aAAyC;CAC/E,MAAM,mBAAmB,SAAS,QAC/B,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,CAC7E;AAED,KAAI,iBAAiB,WAAW,EAC9B,QAAO,EAAE;AAGX,QAAO,CAAC,eAAe,iBAAiB,KAAK,IAAI,CAAC,UAAU;;;;;;;;AAS9D,MAAM,cAAc,OAClB,UACA,QACA,YACuB;CAEvB,MAAM,YAAY;CAElB,M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B;EACnB,KAAK,QAAQ;EACb;EACA;EACA,kBAAkB,WAAW;EAC7B,YAAY,UAAU;EACtB,WAAW,UAAU;EACrB,eAAe,UAAU;EACzB;EACA,OAAO,QAAQ;EACf,SAAS,QAAQ;EACjB,mBAAmB,UAAU;EAC7B;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO;EAAE,SAAS;EAAM;EAAY;EAAa"}
|
|
1
|
+
{"version":3,"file":"generate.js","names":[],"sources":["../../src/css/generate.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { gzipSync } from 'node:zlib';\n\nimport { cyan, magenta, print, spinStop, yellow } from '@yahoo/uds-cli/lib';\nimport type { UniversalTokensConfig } from '@yahoo/uds-config';\nimport { defaultTokensConfig } from '@yahoo/uds-config';\nimport postcss from 'postcss';\nimport type { SafelistConfig } from 'tailwindcss/types/config';\n\nimport type { SerializedComponentInfo } from '../commands/generateComponentData';\nimport {\n deduplicateSafelist,\n getInternalSafelistClasses,\n getThemeAndScaleClasses,\n} from '../purger/optimized';\nimport type { EntryValue } from '../utils/entryPoints';\nimport { resolveEntryPaths } from '../utils/entryPoints';\nimport {\n applyScopedColorModeFix,\n buildPostcssPlugins,\n createTailwindPlugin,\n getCssFeatureFlags,\n getInternalIconModeCss,\n optimizeGeneratedCss,\n printSimpleModeStats,\n} from './generate.helpers';\nimport { loadConfigFile, scanDirectoriesForSafelist } from './nodeUtils';\nimport { measureAsync } from './perf';\nimport type { UDSCSSOptimizationOptions, UDSCSSVarSafelistPattern } from './theme';\nimport {\n extractRuntimeConfigValues,\n extractVariantDefaults,\n getConfigurableCssVariables,\n getMotionVarPrefixes,\n} from './utils';\n\n/**\n * Result from generating CSS\n */\ninterface CSSResult {\n css: string;\n sizeBytes: number;\n sizeGzipBytes: number;\n classCount: number;\n optimizationStats?: {\n originalSize: number;\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n validationErrors: string[];\n };\n}\n\n/**\n * CSS generation options for uds.theme.ts\n */\ninterface UDSCSSOptions {\n /** CSS scope wrapper class (optional) */\n scope?: string;\n /** Safelist of CSS classes to always include */\n safelist?: SafelistConfig[];\n /** CSS optimization settings */\n optimization?: UDSCSSOptimizationOptions;\n /** Include Tailwind preflight/reset styles (default: true) */\n preflight?: boolean;\n /** Include @font-face declarations (default: true) */\n fontFaceDeclarations?: boolean;\n /** Debounce delay (ms) for watch mode regenerations */\n watchDebounce?: number;\n}\n\n/**\n * Options for generateCSS function\n */\ninterface GenerateCSSOptions {\n /** CSS scope wrapper class */\n scope?: string;\n /** Directory to scan for arbitrary Tailwind classes (className props) */\n contentDir?: string | string[];\n /** CSS generation options from theme config */\n cssOptions?: UDSCSSOptions;\n /** Reference CSS to deduplicate font-faces against (for scoped CSS) */\n referenceCss?: string;\n /** CSS variable prefixes or patterns to preserve during pruning */\n safeVarPrefixes?: UDSCSSVarSafelistPattern[];\n}\n\nconst normalizeScope = (scope?: string): string | undefined => {\n const trimmedScope = scope?.trim();\n return trimmedScope ? trimmedScope : undefined;\n};\n\nconst getArbitrarySafelistRawContent = (safelist: SafelistConfig[]): string[] => {\n const arbitraryClasses = safelist.filter(\n (entry): entry is string => typeof entry === 'string' && entry.includes('['),\n );\n\n if (arbitraryClasses.length === 0) {\n return [];\n }\n\n return [`<div class=\"${arbitraryClasses.join(' ')}\"></div>`];\n};\n\n/**\n * Generate CSS from a safelist using Tailwind + PostCSS\n * @param safelist - UDS component classes to include\n * @param config - Token configuration\n * @param options - Additional options\n */\nconst generateCSS = async (\n safelist: SafelistConfig[],\n config: UniversalTokensConfig,\n options?: GenerateCSSOptions,\n): Promise<CSSResult> => {\n // Do we need base?\n const sourceCSS = '@tailwind base; @tailwind components; @tailwind utilities';\n\n const contentDir = options?.contentDir ?? path.join(process.cwd(), 'src');\n const cssFlags = getCssFeatureFlags(options?.cssOptions);\n const optimizationConfig = options?.cssOptions?.optimization;\n const scopeClass = normalizeScope(options?.scope) ?? normalizeScope(options?.cssOptions?.scope);\n const twPlugin = createTailwindPlugin({\n contentDir,\n rawContents: getArbitrarySafelistRawContent(safelist),\n safelist,\n config,\n enablePreflight: cssFlags.enablePreflight,\n enableFontFaceDeclarations: cssFlags.enableFontFaceDeclarations,\n });\n const plugins = buildPostcssPlugins({\n tailwindPlugin: twPlugin,\n shouldPruneVars: cssFlags.shouldPruneVars,\n safeVarPrefixes: options?.safeVarPrefixes ?? [],\n scopeClass,\n });\n\n const result = await measureAsync('gen:postcss', () =>\n postcss(plugins).process(sourceCSS, { from: undefined }),\n );\n let css = await measureAsync('gen:scoped-color-fix', () =>\n applyScopedColorModeFix(result.css, scopeClass),\n );\n if (!css.includes('uds-light-mode-icon') || !css.includes('uds-dark-mode-icon')) {\n css = `${css} ${getInternalIconModeCss(scopeClass)}`.trim();\n }\n const optimizedCss = await measureAsync('gen:optimize', () =>\n optimizeGeneratedCss({\n css,\n shouldOptimize: cssFlags.shouldOptimize,\n optimizationConfig,\n referenceCss: options?.referenceCss,\n scopeClass,\n }),\n );\n css = optimizedCss.css;\n\n const sizeBytes = Buffer.byteLength(css, 'utf8');\n const sizeGzipBytes = gzipSync(css).length;\n\n return {\n css,\n sizeBytes,\n sizeGzipBytes,\n classCount: safelist.length,\n optimizationStats: optimizedCss.optimizationStats,\n };\n};\n\n/**\n * Generate CSS in simple mode (no uds.theme.ts)\n */\nconst generateSimpleModeCSS = async (options: {\n workspaceDir: string;\n entry: EntryValue;\n outFile: string;\n variants: Record<string, Record<string, string>>;\n autoVariants: Record<string, Record<string, string>>;\n componentData: Record<string, SerializedComponentInfo>;\n scope?: string;\n configPath?: string;\n isWatch?: boolean;\n silent?: boolean;\n verbose?: boolean;\n}): Promise<{ success: boolean; outputPath: string; packageDirs?: string[] }> => {\n const isWatch = options.isWatch === true;\n const isSilent = options.silent === true;\n const shouldLogStats = !isSilent && !isWatch;\n const startTime = performance.now();\n const colorModes: ('dark' | 'light')[] = ['dark']; // Light mode is already in :root\n\n // Load config if provided, otherwise use default\n let tokensConfig: UniversalTokensConfig = defaultTokensConfig;\n if (options.configPath) {\n const loadedConfig = await loadConfigFile<UniversalTokensConfig>(options.configPath);\n if (loadedConfig) {\n tokensConfig = loadedConfig;\n } else if (shouldLogStats) {\n spinStop('⚠️', `Config file not found: ${options.configPath}, using defaults`);\n }\n }\n\n // Extract variant defaults from config for auto-variant class generation\n const variantDefaults = extractVariantDefaults(tokensConfig);\n const runtimeConfigValues = extractRuntimeConfigValues(tokensConfig);\n\n const resolvedEntries = resolveEntryPaths(options.entry, options.workspaceDir);\n const entryDirs = resolvedEntries.map((entry) => entry.absolutePath);\n const scanResult = await scanDirectoriesForSafelist(\n entryDirs,\n colorModes,\n options.variants,\n options.autoVariants,\n options.componentData,\n variantDefaults,\n runtimeConfigValues,\n );\n\n const totalFilesScanned = scanResult.filesScanned;\n const allClasses: string[] = [...scanResult.safelist];\n const allComponents = new Set<string>(scanResult.components);\n const packageDirs: string[] = [\n ...new Set(\n resolvedEntries.map((entry) =>\n entry.kind === 'directory' ? entry.absolutePath : entry.watchDirectory,\n ),\n ),\n ];\n\n // Add color mode classes\n const fullSafelist = [\n ...allClasses,\n ...getThemeAndScaleClasses(colorModes),\n ...getInternalSafelistClasses(),\n ];\n const finalSafelist = deduplicateSafelist(fullSafelist);\n\n // Generate CSS (Tailwind will scan entry dir for arbitrary classes on className props)\n const cssResult = await generateCSS(finalSafelist, tokensConfig, {\n scope: options.scope,\n contentDir: entryDirs,\n safeVarPrefixes: [\n ...getMotionVarPrefixes(options.componentData, [...allComponents]),\n ...getConfigurableCssVariables(),\n ],\n });\n\n // Write output\n const outputPath = path.isAbsolute(options.outFile)\n ? options.outFile\n : path.join(options.workspaceDir, options.outFile);\n const outputDir = path.dirname(outputPath);\n\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n fs.writeFileSync(outputPath, cssResult.css);\n\n const duration = Math.round(performance.now() - startTime);\n\n if (shouldLogStats) {\n printSimpleModeStats({\n cwd: options.workspaceDir,\n outputPath,\n totalFilesScanned,\n scannedFilePaths: scanResult.filePaths,\n classCount: cssResult.classCount,\n sizeBytes: cssResult.sizeBytes,\n sizeGzipBytes: cssResult.sizeGzipBytes,\n duration,\n scope: options.scope,\n verbose: options.verbose,\n optimizationStats: cssResult.optimizationStats,\n print,\n magenta,\n cyan,\n yellow,\n });\n }\n\n return { success: true, outputPath, packageDirs };\n};\n\nexport { generateCSS, generateSimpleModeCSS };\nexport type { UDSCSSOptions };\n"],"mappings":";;;;;;;;;;;;;;;;AAwFA,MAAM,kBAAkB,UAAuC;CAC7D,MAAM,eAAe,OAAO,MAAM;CAClC,OAAO,eAAe,eAAe,KAAA;;AAGvC,MAAM,kCAAkC,aAAyC;CAC/E,MAAM,mBAAmB,SAAS,QAC/B,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,CAC7E;CAED,IAAI,iBAAiB,WAAW,GAC9B,OAAO,EAAE;CAGX,OAAO,CAAC,eAAe,iBAAiB,KAAK,IAAI,CAAC,UAAU;;;;;;;;AAS9D,MAAM,cAAc,OAClB,UACA,QACA,YACuB;CAEvB,MAAM,YAAY;CAElB,MAAM,aAAa,SAAS,cAAc,KAAK,KAAK,QAAQ,KAAK,EAAE,MAAM;CACzE,MAAM,WAAW,mBAAmB,SAAS,WAAW;CACxD,MAAM,qBAAqB,SAAS,YAAY;CAChD,MAAM,aAAa,eAAe,SAAS,MAAM,IAAI,eAAe,SAAS,YAAY,MAAM;CAS/F,MAAM,UAAU,oBAAoB;EAClC,gBATe,qBAAqB;GACpC;GACA,aAAa,+BAA+B,SAAS;GACrD;GACA;GACA,iBAAiB,SAAS;GAC1B,4BAA4B,SAAS;GACtC,CAEyB;EACxB,iBAAiB,SAAS;EAC1B,iBAAiB,SAAS,mBAAmB,EAAE;EAC/C;EACD,CAAC;CAEF,MAAM,SAAS,MAAM,aAAa,qBAChC,QAAQ,QAAQ,CAAC,QAAQ,WAAW,EAAE,MAAM,KAAA,GAAW,CAAC,CACzD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MAAM,cAAwB,CAC5B,GAAG,IAAI,IACL,gBAAgB,KAAK,UACnB,MAAM,SAAS,cAAc,MAAM,eAAe,MAAM,eACzD,CACF,CACF;CAWD,MAAM,YAAY,MAAM,YAHF,oBAAoB;EAJxC,GAAG;EACH,GAAG,wBAAwB,WAAW;EACtC,GAAG,4BAA4B;EAEqB,CAGL,EAAE,cAAc;EAC/D,OAAO,QAAQ;EACf,YAAY;EACZ,iBAAiB,CACf,GAAG,qBAAqB,QAAQ,eAAe,CAAC,GAAG,cAAc,CAAC,EAClE,GAAG,6BAA6B,CACjC;EACF,CAAC;CAGF,MAAM,aAAa,KAAK,WAAW,QAAQ,QAAQ,GAC/C,QAAQ,UACR,KAAK,KAAK,QAAQ,cAAc,QAAQ,QAAQ;CACpD,MAAM,YAAY,KAAK,QAAQ,WAAW;CAE1C,IAAI,CAAC,GAAG,WAAW,UAAU,EAC3B,GAAG,UAAU,WAAW,EAAE,WAAW,MAAM,CAAC;CAG9C,GAAG,cAAc,YAAY,UAAU,IAAI;CAE3C,MAAM,WAAW,KAAK,MAAM,YAAY,KAAK,GAAG,UAAU;CAE1D,IAAI,gBACF,qBAAqB;EACnB,KAAK,QAAQ;EACb;EACA;EACA,kBAAkB,WAAW;EAC7B,YAAY,UAAU;EACtB,WAAW,UAAU;EACrB,eAAe,UAAU;EACzB;EACA,OAAO,QAAQ;EACf,SAAS,QAAQ;EACjB,mBAAmB,UAAU;EAC7B;EACA;EACA;EACA;EACD,CAAC;CAGJ,OAAO;EAAE,SAAS;EAAM;EAAY;EAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeUtils.js","names":[],"sources":["../../src/css/nodeUtils.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { cyan, green, magenta, print, red } from '@yahoo/uds-cli/lib';\nimport fg from 'fast-glob';\n\nimport type { SerializedComponentInfo } from '../commands/generateComponentData';\nimport type { RuntimeConfigValues, VariantDefaults } from '../purger/optimized/purgeFromCode';\nimport { purgeFromCodeOptimized } from '../purger/optimized/purgeFromCode';\nimport type { EntryValue } from '../utils/entryPoints';\nimport { formatEntryValue } from '../utils/entryPoints';\nimport { measureAsync } from './perf';\nimport type { WorkerPool } from './workerPool';\n\ntype SafelistScanResult = {\n safelist: string[];\n components: string[];\n filesScanned: number;\n filesWithComponents: number;\n filePaths: string[];\n};\n\nconst loadConfigFile = async <T>(configPath: string): Promise<T | null> => {\n const absolutePath = path.isAbsolute(configPath)\n ? configPath\n : path.join(process.cwd(), configPath);\n\n if (!fs.existsSync(absolutePath)) {\n return null;\n }\n\n try {\n const module = await import(absolutePath);\n return module.default ?? module.config ?? module;\n } catch (error) {\n throw new Error(\n `Failed to load config file: ${absolutePath}\\n${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n};\n\nconst scanDirectoryForSafelist = async (\n dir: string,\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n pool?: WorkerPool,\n): Promise<SafelistScanResult> => {\n const files = await measureAsync('scan:glob', () =>\n fg('**/*.{js,jsx,mjs,cjs,ts,tsx}', {\n cwd: dir,\n absolute: true,\n ignore: ['**/node_modules/**'],\n }).then((f) => f.sort((left, right) => left.localeCompare(right))),\n );\n\n const processFile = (filePath: string) => {\n const code = fs.readFileSync(filePath, 'utf-8');\n if (pool) {\n return pool.processFile({\n code,\n filePath,\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n });\n }\n return purgeFromCodeOptimized(code, {\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n variants,\n autoVariants,\n componentData,\n includeAllClassNamePrimitives,\n filePath,\n });\n };\n\n const results = await measureAsync('scan:purge-all-files', () =>\n Promise.all(files.map(processFile)),\n );\n\n const allClasses = results.flatMap((result) => result.safelist);\n const allComponents = new Set(results.flatMap((result) => result.components));\n const filesWithComponents = results.filter((result) => result.components.length > 0).length;\n\n return {\n safelist: allClasses,\n components: [...allComponents],\n filesScanned: files.length,\n filesWithComponents,\n filePaths: files,\n };\n};\n\nconst scanFileForSafelist = async (\n filePath: string,\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n): Promise<SafelistScanResult> => {\n const code = fs.readFileSync(filePath, 'utf-8');\n const result = await purgeFromCodeOptimized(code, {\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n variants,\n autoVariants,\n componentData,\n includeAllClassNamePrimitives,\n });\n\n return {\n safelist: result.safelist,\n components: result.components,\n filesScanned: 1,\n filesWithComponents: result.components.length > 0 ? 1 : 0,\n filePaths: [filePath],\n };\n};\n\nconst scanDirectoriesForSafelist = async (\n dirs: string[],\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n pool?: WorkerPool,\n): Promise<SafelistScanResult> => {\n const results = await Promise.all(\n dirs.map((dir) => {\n if (fs.existsSync(dir) && fs.statSync(dir).isFile()) {\n return scanFileForSafelist(\n dir,\n colorModes,\n variants,\n autoVariants,\n componentData,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n );\n }\n\n return scanDirectoryForSafelist(\n dir,\n colorModes,\n variants,\n autoVariants,\n componentData,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n pool,\n );\n }),\n );\n\n return {\n safelist: results.flatMap((result) => result.safelist),\n components: [...new Set(results.flatMap((result) => result.components))],\n filesScanned: results.reduce((total, result) => total + result.filesScanned, 0),\n filesWithComponents: results.reduce((total, result) => total + result.filesWithComponents, 0),\n filePaths: results\n .flatMap((result) => result.filePaths)\n .sort((left, right) => left.localeCompare(right)),\n };\n};\n\nconst findMonorepoRoot = (startDir: string): string | null => {\n const findUp = (currentDir: string): string | null => {\n if (fs.existsSync(path.join(currentDir, 'packages'))) {\n return currentDir;\n }\n\n const parentDir = path.dirname(currentDir);\n return parentDir === currentDir ? null : findUp(parentDir);\n };\n\n return findUp(startDir);\n};\n\nconst readPackageName = (packageJsonPath: string): string | null => {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string };\n return typeof pkgJson.name === 'string' ? pkgJson.name : null;\n } catch {\n return null;\n }\n};\n\nconst findPackageRootFromResolvedEntry = (\n resolvedEntryPath: string,\n packageName: string,\n): string | null => {\n let currentPath = fs.statSync(resolvedEntryPath).isDirectory()\n ? resolvedEntryPath\n : path.dirname(resolvedEntryPath);\n\n while (true) {\n const packageJsonPath = path.join(currentPath, 'package.json');\n if (fs.existsSync(packageJsonPath) && readPackageName(packageJsonPath) === packageName) {\n return currentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n};\n\nconst findPackageRootInNodeModules = (startDir: string, packageName: string): string | null => {\n let currentDir = startDir;\n\n while (true) {\n const packageJsonPath = path.join(currentDir, 'node_modules', packageName, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n return path.dirname(packageJsonPath);\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n};\n\nconst resolvePackageRoot = (workspaceDir: string, packageName: string): string | null => {\n const requireFromWorkspace = createRequire(path.join(workspaceDir, 'package.json'));\n\n try {\n const resolvedPackageJson = requireFromWorkspace.resolve(\n path.join(packageName, 'package.json'),\n );\n return path.dirname(resolvedPackageJson);\n } catch {\n try {\n const resolvedPackageEntry = requireFromWorkspace.resolve(packageName);\n const packageRoot = findPackageRootFromResolvedEntry(resolvedPackageEntry, packageName);\n if (packageRoot) {\n return packageRoot;\n }\n } catch {\n // Fall through to explicit node_modules lookup below.\n }\n\n return findPackageRootInNodeModules(workspaceDir, packageName);\n }\n};\n\ntype PackageJsonShape = {\n uds?: {\n scope?: string;\n };\n};\n\nconst findPackageRootInMonorepo = (monorepoRoot: string, packageName: string): string | null => {\n const packageJsonPaths = fg.sync('packages/**/package.json', {\n cwd: monorepoRoot,\n absolute: true,\n ignore: ['**/node_modules/**', '**/dist/**'],\n });\n\n const matchingPath = packageJsonPaths.find((pkgJsonPath) => {\n return readPackageName(pkgJsonPath) === packageName;\n });\n\n return matchingPath ? path.dirname(matchingPath) : null;\n};\n\nconst findPackageRoot = (packageName: string): string | null => {\n const workspaceDir = process.cwd();\n const monorepoRoot = findMonorepoRoot(workspaceDir);\n\n let packageRoot = resolvePackageRoot(workspaceDir, packageName);\n if (!packageRoot && monorepoRoot) {\n packageRoot = findPackageRootInMonorepo(monorepoRoot, packageName);\n }\n\n return packageRoot;\n};\n\nconst buildPackageSourceCandidates = (\n workspaceDir: string,\n packageName: string,\n packageRoot: string | null,\n): string[] => {\n return [\n packageRoot ? path.join(packageRoot, 'src') : null,\n packageRoot ? path.join(packageRoot, 'lib') : null,\n packageRoot ? path.join(packageRoot, 'dist') : null,\n packageRoot,\n path.join(workspaceDir, 'node_modules', packageName, 'src'),\n path.join(workspaceDir, 'node_modules', packageName, 'lib'),\n path.join(workspaceDir, 'node_modules', packageName, 'dist'),\n path.join(workspaceDir, 'node_modules', packageName),\n ].filter(Boolean) as string[];\n};\n\nconst getFirstExistingPath = (candidates: string[]): string | null =>\n candidates.find((candidate) => fs.existsSync(candidate)) ?? null;\n\nconst findPackageSourceDir = (packageName: string): string | null => {\n const workspaceDir = process.cwd();\n const packageRoot = findPackageRoot(packageName);\n\n return getFirstExistingPath(buildPackageSourceCandidates(workspaceDir, packageName, packageRoot));\n};\n\nconst getPackageUdsScope = (packageName: string): string | null => {\n const packageRoot = findPackageRoot(packageName);\n if (!packageRoot) {\n return null;\n }\n\n const packageJsonPath = path.join(packageRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as PackageJsonShape;\n const scope = packageJson.uds?.scope;\n return typeof scope === 'string' && scope.trim().length > 0 ? scope.trim() : null;\n } catch {\n return null;\n }\n};\n\nconst scaffoldThemeConfig = async (options: {\n outputPath?: string;\n configPath?: string;\n entry?: EntryValue;\n force?: boolean;\n}): Promise<void> => {\n const workspaceDir = process.cwd();\n const outputPath = options.outputPath ?? 'uds.theme.ts';\n const absoluteOutputPath = path.isAbsolute(outputPath)\n ? outputPath\n : path.join(workspaceDir, outputPath);\n\n if (fs.existsSync(absoluteOutputPath) && !options.force) {\n print(red(`Error: ${outputPath} already exists. Use --force to overwrite.`));\n process.exitCode = 1;\n return;\n }\n\n const configPath = options.configPath ?? './uds.config.ts';\n const entry = options.entry ?? './src';\n const serializedEntry = formatEntryValue(entry);\n\n const template = `import { defineTheme } from '@yahoo/uds';\n\n/**\n * UDS Theme Configuration\n * \n * This file configures CSS generation for your app and shared packages.\n * Run \\`uds css\\` to generate optimized CSS.\n */\nexport default defineTheme({\n // Path to your uds.config.ts file\n config: '${configPath}',\n\n // Entry directory or .tsx file path for scanning your app code\n entry: ${serializedEntry},\n\n // Color modes to include (light mode is always in :root)\n colorModes: ['dark'],\n\n // Packages that inherit your app's theme (merged into main uds.css)\n // inherit: ['@your-org/shared-ui'],\n\n // Packages that generate separate scoped CSS outputs.\n // Scope class is discovered from each package.json uds.scope.\n // When entry is omitted, the package is scanned the same way as inherit.\n // scoped: {\n // '@your-org/shared-ui': './packages/shared-ui/uds.config.ts'\n // }\n //\n // Or use the expanded form for custom output paths:\n // scoped: {\n // '@your-org/shared-ui': {\n // config: './packages/shared-ui/uds.config.ts',\n // entry: './src',\n // // outFile defaults to dist/shared-ui.css\n // outFile: 'dist/shared-ui.css'\n // },\n // },\n\n // CSS generation options (all optional)\n // css: {\n // safelist: [],\n // preflight: true,\n // fontFaceDeclarations: true,\n // optimization: {\n // removeUnusedFonts: false,\n // removeEmptyRules: true,\n // deduplicateScopedCss: true\n // }\n // }\n});\n`;\n\n fs.writeFileSync(absoluteOutputPath, template);\n\n print('');\n print(green('✅ Created uds.theme.ts'));\n print('');\n print(`${magenta('Next steps:')}`);\n print(` 1. Review and customize ${cyan(outputPath)}`);\n print(` 2. Run ${cyan('uds css')} to generate CSS`);\n print('');\n};\n\nexport {\n findPackageRoot,\n findPackageSourceDir,\n getPackageUdsScope,\n loadConfigFile,\n scaffoldThemeConfig,\n scanDirectoriesForSafelist,\n scanDirectoryForSafelist,\n};\nexport type { SafelistScanResult };\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,iBAAiB,OAAU,eAA0C;CACzE,MAAM,eAAe,KAAK,WAAW,WAAW,GAC5C,aACA,KAAK,KAAK,QAAQ,KAAK,EAAE,WAAW;AAExC,KAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,QAAO;AAGT,KAAI;EACF,MAAM,SAAS,MAAM,OAAO;AAC5B,SAAO,OAAO,WAAW,OAAO,UAAU;UACnC,OAAO;AACd,QAAM,IAAI,MACR,+BAA+B,aAAa,IAAI,iBAAiB,QAAQ,MAAM,UAAU,kBAC1F;;;AAIL,MAAM,2BAA2B,OAC/B,KACA,YACA,UACA,cACA,eACA,iBACA,qBACA,gCAAgC,OAChC,SACgC;CAChC,MAAM,QAAQ,MAAM,aAAa,mBAC/B,GAAG,gCAAgC;EACjC,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,qBAAqB;EAC/B,CAAC,CAAC,MAAM,MAAM,EAAE,MAAM,MAAM,UAAU,KAAK,cAAc,MAAM,CAAC,CAAC,CACnE;CAED,MAAM,eAAe,aAAqB;EACxC,MAAM,OAAO,GAAG,aAAa,U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AA8B,KAAK,WAAW,GAAG;AACvD,OAAM,aAAa,KAAK,UAAU,CAAC,kBAAkB;AACrD,OAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"nodeUtils.js","names":[],"sources":["../../src/css/nodeUtils.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { cyan, green, magenta, print, red } from '@yahoo/uds-cli/lib';\nimport fg from 'fast-glob';\n\nimport type { SerializedComponentInfo } from '../commands/generateComponentData';\nimport type { RuntimeConfigValues, VariantDefaults } from '../purger/optimized/purgeFromCode';\nimport { purgeFromCodeOptimized } from '../purger/optimized/purgeFromCode';\nimport type { EntryValue } from '../utils/entryPoints';\nimport { formatEntryValue } from '../utils/entryPoints';\nimport { measureAsync } from './perf';\nimport type { WorkerPool } from './workerPool';\n\ntype SafelistScanResult = {\n safelist: string[];\n components: string[];\n filesScanned: number;\n filesWithComponents: number;\n filePaths: string[];\n};\n\nconst loadConfigFile = async <T>(configPath: string): Promise<T | null> => {\n const absolutePath = path.isAbsolute(configPath)\n ? configPath\n : path.join(process.cwd(), configPath);\n\n if (!fs.existsSync(absolutePath)) {\n return null;\n }\n\n try {\n const module = await import(absolutePath);\n return module.default ?? module.config ?? module;\n } catch (error) {\n throw new Error(\n `Failed to load config file: ${absolutePath}\\n${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n};\n\nconst scanDirectoryForSafelist = async (\n dir: string,\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n pool?: WorkerPool,\n): Promise<SafelistScanResult> => {\n const files = await measureAsync('scan:glob', () =>\n fg('**/*.{js,jsx,mjs,cjs,ts,tsx}', {\n cwd: dir,\n absolute: true,\n ignore: ['**/node_modules/**'],\n }).then((f) => f.sort((left, right) => left.localeCompare(right))),\n );\n\n const processFile = (filePath: string) => {\n const code = fs.readFileSync(filePath, 'utf-8');\n if (pool) {\n return pool.processFile({\n code,\n filePath,\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n });\n }\n return purgeFromCodeOptimized(code, {\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n variants,\n autoVariants,\n componentData,\n includeAllClassNamePrimitives,\n filePath,\n });\n };\n\n const results = await measureAsync('scan:purge-all-files', () =>\n Promise.all(files.map(processFile)),\n );\n\n const allClasses = results.flatMap((result) => result.safelist);\n const allComponents = new Set(results.flatMap((result) => result.components));\n const filesWithComponents = results.filter((result) => result.components.length > 0).length;\n\n return {\n safelist: allClasses,\n components: [...allComponents],\n filesScanned: files.length,\n filesWithComponents,\n filePaths: files,\n };\n};\n\nconst scanFileForSafelist = async (\n filePath: string,\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n): Promise<SafelistScanResult> => {\n const code = fs.readFileSync(filePath, 'utf-8');\n const result = await purgeFromCodeOptimized(code, {\n colorModes,\n variantDefaults,\n runtimeConfigValues,\n variants,\n autoVariants,\n componentData,\n includeAllClassNamePrimitives,\n });\n\n return {\n safelist: result.safelist,\n components: result.components,\n filesScanned: 1,\n filesWithComponents: result.components.length > 0 ? 1 : 0,\n filePaths: [filePath],\n };\n};\n\nconst scanDirectoriesForSafelist = async (\n dirs: string[],\n colorModes: ('dark' | 'light')[],\n variants: Record<string, Record<string, string>>,\n autoVariants: Record<string, Record<string, string>>,\n componentData: Record<string, SerializedComponentInfo>,\n variantDefaults?: VariantDefaults,\n runtimeConfigValues?: RuntimeConfigValues,\n includeAllClassNamePrimitives = false,\n pool?: WorkerPool,\n): Promise<SafelistScanResult> => {\n const results = await Promise.all(\n dirs.map((dir) => {\n if (fs.existsSync(dir) && fs.statSync(dir).isFile()) {\n return scanFileForSafelist(\n dir,\n colorModes,\n variants,\n autoVariants,\n componentData,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n );\n }\n\n return scanDirectoryForSafelist(\n dir,\n colorModes,\n variants,\n autoVariants,\n componentData,\n variantDefaults,\n runtimeConfigValues,\n includeAllClassNamePrimitives,\n pool,\n );\n }),\n );\n\n return {\n safelist: results.flatMap((result) => result.safelist),\n components: [...new Set(results.flatMap((result) => result.components))],\n filesScanned: results.reduce((total, result) => total + result.filesScanned, 0),\n filesWithComponents: results.reduce((total, result) => total + result.filesWithComponents, 0),\n filePaths: results\n .flatMap((result) => result.filePaths)\n .sort((left, right) => left.localeCompare(right)),\n };\n};\n\nconst findMonorepoRoot = (startDir: string): string | null => {\n const findUp = (currentDir: string): string | null => {\n if (fs.existsSync(path.join(currentDir, 'packages'))) {\n return currentDir;\n }\n\n const parentDir = path.dirname(currentDir);\n return parentDir === currentDir ? null : findUp(parentDir);\n };\n\n return findUp(startDir);\n};\n\nconst readPackageName = (packageJsonPath: string): string | null => {\n try {\n const pkgJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string };\n return typeof pkgJson.name === 'string' ? pkgJson.name : null;\n } catch {\n return null;\n }\n};\n\nconst findPackageRootFromResolvedEntry = (\n resolvedEntryPath: string,\n packageName: string,\n): string | null => {\n let currentPath = fs.statSync(resolvedEntryPath).isDirectory()\n ? resolvedEntryPath\n : path.dirname(resolvedEntryPath);\n\n while (true) {\n const packageJsonPath = path.join(currentPath, 'package.json');\n if (fs.existsSync(packageJsonPath) && readPackageName(packageJsonPath) === packageName) {\n return currentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n};\n\nconst findPackageRootInNodeModules = (startDir: string, packageName: string): string | null => {\n let currentDir = startDir;\n\n while (true) {\n const packageJsonPath = path.join(currentDir, 'node_modules', packageName, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n return path.dirname(packageJsonPath);\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n};\n\nconst resolvePackageRoot = (workspaceDir: string, packageName: string): string | null => {\n const requireFromWorkspace = createRequire(path.join(workspaceDir, 'package.json'));\n\n try {\n const resolvedPackageJson = requireFromWorkspace.resolve(\n path.join(packageName, 'package.json'),\n );\n return path.dirname(resolvedPackageJson);\n } catch {\n try {\n const resolvedPackageEntry = requireFromWorkspace.resolve(packageName);\n const packageRoot = findPackageRootFromResolvedEntry(resolvedPackageEntry, packageName);\n if (packageRoot) {\n return packageRoot;\n }\n } catch {\n // Fall through to explicit node_modules lookup below.\n }\n\n return findPackageRootInNodeModules(workspaceDir, packageName);\n }\n};\n\ntype PackageJsonShape = {\n uds?: {\n scope?: string;\n };\n};\n\nconst findPackageRootInMonorepo = (monorepoRoot: string, packageName: string): string | null => {\n const packageJsonPaths = fg.sync('packages/**/package.json', {\n cwd: monorepoRoot,\n absolute: true,\n ignore: ['**/node_modules/**', '**/dist/**'],\n });\n\n const matchingPath = packageJsonPaths.find((pkgJsonPath) => {\n return readPackageName(pkgJsonPath) === packageName;\n });\n\n return matchingPath ? path.dirname(matchingPath) : null;\n};\n\nconst findPackageRoot = (packageName: string): string | null => {\n const workspaceDir = process.cwd();\n const monorepoRoot = findMonorepoRoot(workspaceDir);\n\n let packageRoot = resolvePackageRoot(workspaceDir, packageName);\n if (!packageRoot && monorepoRoot) {\n packageRoot = findPackageRootInMonorepo(monorepoRoot, packageName);\n }\n\n return packageRoot;\n};\n\nconst buildPackageSourceCandidates = (\n workspaceDir: string,\n packageName: string,\n packageRoot: string | null,\n): string[] => {\n return [\n packageRoot ? path.join(packageRoot, 'src') : null,\n packageRoot ? path.join(packageRoot, 'lib') : null,\n packageRoot ? path.join(packageRoot, 'dist') : null,\n packageRoot,\n path.join(workspaceDir, 'node_modules', packageName, 'src'),\n path.join(workspaceDir, 'node_modules', packageName, 'lib'),\n path.join(workspaceDir, 'node_modules', packageName, 'dist'),\n path.join(workspaceDir, 'node_modules', packageName),\n ].filter(Boolean) as string[];\n};\n\nconst getFirstExistingPath = (candidates: string[]): string | null =>\n candidates.find((candidate) => fs.existsSync(candidate)) ?? null;\n\nconst findPackageSourceDir = (packageName: string): string | null => {\n const workspaceDir = process.cwd();\n const packageRoot = findPackageRoot(packageName);\n\n return getFirstExistingPath(buildPackageSourceCandidates(workspaceDir, packageName, packageRoot));\n};\n\nconst getPackageUdsScope = (packageName: string): string | null => {\n const packageRoot = findPackageRoot(packageName);\n if (!packageRoot) {\n return null;\n }\n\n const packageJsonPath = path.join(packageRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as PackageJsonShape;\n const scope = packageJson.uds?.scope;\n return typeof scope === 'string' && scope.trim().length > 0 ? scope.trim() : null;\n } catch {\n return null;\n }\n};\n\nconst scaffoldThemeConfig = async (options: {\n outputPath?: string;\n configPath?: string;\n entry?: EntryValue;\n force?: boolean;\n}): Promise<void> => {\n const workspaceDir = process.cwd();\n const outputPath = options.outputPath ?? 'uds.theme.ts';\n const absoluteOutputPath = path.isAbsolute(outputPath)\n ? outputPath\n : path.join(workspaceDir, outputPath);\n\n if (fs.existsSync(absoluteOutputPath) && !options.force) {\n print(red(`Error: ${outputPath} already exists. Use --force to overwrite.`));\n process.exitCode = 1;\n return;\n }\n\n const configPath = options.configPath ?? './uds.config.ts';\n const entry = options.entry ?? './src';\n const serializedEntry = formatEntryValue(entry);\n\n const template = `import { defineTheme } from '@yahoo/uds';\n\n/**\n * UDS Theme Configuration\n * \n * This file configures CSS generation for your app and shared packages.\n * Run \\`uds css\\` to generate optimized CSS.\n */\nexport default defineTheme({\n // Path to your uds.config.ts file\n config: '${configPath}',\n\n // Entry directory or .tsx file path for scanning your app code\n entry: ${serializedEntry},\n\n // Color modes to include (light mode is always in :root)\n colorModes: ['dark'],\n\n // Packages that inherit your app's theme (merged into main uds.css)\n // inherit: ['@your-org/shared-ui'],\n\n // Packages that generate separate scoped CSS outputs.\n // Scope class is discovered from each package.json uds.scope.\n // When entry is omitted, the package is scanned the same way as inherit.\n // scoped: {\n // '@your-org/shared-ui': './packages/shared-ui/uds.config.ts'\n // }\n //\n // Or use the expanded form for custom output paths:\n // scoped: {\n // '@your-org/shared-ui': {\n // config: './packages/shared-ui/uds.config.ts',\n // entry: './src',\n // // outFile defaults to dist/shared-ui.css\n // outFile: 'dist/shared-ui.css'\n // },\n // },\n\n // CSS generation options (all optional)\n // css: {\n // safelist: [],\n // preflight: true,\n // fontFaceDeclarations: true,\n // optimization: {\n // removeUnusedFonts: false,\n // removeEmptyRules: true,\n // deduplicateScopedCss: true\n // }\n // }\n});\n`;\n\n fs.writeFileSync(absoluteOutputPath, template);\n\n print('');\n print(green('✅ Created uds.theme.ts'));\n print('');\n print(`${magenta('Next steps:')}`);\n print(` 1. Review and customize ${cyan(outputPath)}`);\n print(` 2. Run ${cyan('uds css')} to generate CSS`);\n print('');\n};\n\nexport {\n findPackageRoot,\n findPackageSourceDir,\n getPackageUdsScope,\n loadConfigFile,\n scaffoldThemeConfig,\n scanDirectoriesForSafelist,\n scanDirectoryForSafelist,\n};\nexport type { SafelistScanResult };\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,iBAAiB,OAAU,eAA0C;CACzE,MAAM,eAAe,KAAK,WAAW,WAAW,GAC5C,aACA,KAAK,KAAK,QAAQ,KAAK,EAAE,WAAW;CAExC,IAAI,CAAC,GAAG,WAAW,aAAa,EAC9B,OAAO;CAGT,IAAI;EACF,MAAM,SAAS,MAAM,OAAO;EAC5B,OAAO,OAAO,WAAW,OAAO,UAAU;UACnC,OAAO;EACd,MAAM,IAAI,MACR,+BAA+B,aAAa,IAAI,iBAAiB,QAAQ,MAAM,UAAU,kBAC1F;;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A4C,CAAC;EAC5E,QAAQ,WAAW;EACnB;;CAOF,MAAM,WAAW;;;;;;;;;;aAJE,QAAQ,cAAc,kBAcnB;;;WAZE,iBADV,QAAQ,SAAS,QAgBP,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCzB,GAAG,cAAc,oBAAoB,SAAS;CAE9C,MAAM,GAAG;CACT,MAAM,MAAM,yBAAyB,CAAC;CACtC,MAAM,GAAG;CACT,MAAM,GAAG,QAAQ,cAAc,GAAG;CAClC,MAAM,8BAA8B,KAAK,WAAW,GAAG;CACvD,MAAM,aAAa,KAAK,UAAU,CAAC,kBAAkB;CACrD,MAAM,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"perf.js","names":[],"sources":["../../src/css/perf.ts"],"sourcesContent":["import { performance } from 'node:perf_hooks';\n\nconst PERF_PREFIX = 'uds:css:';\n\nconst isPerfEnabled = (): boolean => process.env.UDS_PERF === '1';\n\n// --- Types ---\n\ntype MemorySnapshot = {\n label: string;\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n timestamp: number;\n};\n\ntype TimingEntry = {\n name: string;\n durationMs: number;\n startTime: number;\n detail?: unknown;\n};\n\ntype PerfData = {\n timings: TimingEntry[];\n memory: MemorySnapshot[];\n};\n\n// --- Memory tracking ---\n\nconst memorySnapshots: MemorySnapshot[] = [];\n\nconst captureMemory = (label: string): void => {\n if (!isPerfEnabled()) {\n return;\n }\n\n const mem = process.memoryUsage();\n memorySnapshots.push({\n label,\n rss: mem.rss,\n heapUsed: mem.heapUsed,\n heapTotal: mem.heapTotal,\n external: mem.external,\n timestamp: performance.now(),\n });\n};\n\n// --- Synchronous measurement ---\n\nconst measureSync = <T>(name: string, fn: () => T, detail?: unknown): T => {\n if (!isPerfEnabled()) {\n return fn();\n }\n\n const markName = `${PERF_PREFIX}${name}`;\n const startMark = `${markName}:start`;\n const endMark = `${markName}:end`;\n\n performance.mark(startMark, { detail });\n const result = fn();\n performance.mark(endMark);\n performance.measure(markName, startMark, endMark);\n\n return result;\n};\n\n// --- Asynchronous measurement ---\n\nconst measureAsync = async <T>(\n name: string,\n fn: () => Promise<T>,\n detail?: unknown,\n): Promise<T> => {\n if (!isPerfEnabled()) {\n return fn();\n }\n\n const markName = `${PERF_PREFIX}${name}`;\n const startMark = `${markName}:start`;\n const endMark = `${markName}:end`;\n\n performance.mark(startMark, { detail });\n const result = await fn();\n performance.mark(endMark);\n performance.measure(markName, startMark, endMark);\n\n return result;\n};\n\n// --- Collecting results ---\n\nconst collectTimings = (): TimingEntry[] => {\n return performance\n .getEntriesByType('measure')\n .filter((entry) => entry.name.startsWith(PERF_PREFIX))\n .map((entry) => ({\n name: entry.name.slice(PERF_PREFIX.length),\n durationMs: Math.round(entry.duration * 100) / 100,\n startTime: Math.round(entry.startTime * 100) / 100,\n detail: (entry as PerformanceMeasure).detail,\n }));\n};\n\nconst collectPerfData = (): PerfData => ({\n timings: collectTimings(),\n memory: [...memorySnapshots],\n});\n\nconst clearTimings = (): void => {\n performance.clearMarks();\n performance.clearMeasures();\n memorySnapshots.length = 0;\n};\n\n// --- Formatting ---\n\nconst formatMs = (ms: number): string => {\n if (ms < 1000) {\n return `${Math.round(ms)}ms`;\n }\n\n return `${(ms / 1000).toFixed(1)}s`;\n};\n\nconst formatMemoryMB = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(0)} MB`;\n\nconst formatTimingTree = (timings: TimingEntry[], totalMs: number): string => {\n const lines: string[] = [];\n const grouped = new Map<string, TimingEntry[]>();\n\n // Group by first segment (e.g., \"scan\", \"gen\", \"opt\")\n for (const entry of timings) {\n const segments = entry.name.split(':');\n const group = segments[0] ?? 'other';\n const existing = grouped.get(group) ?? [];\n existing.push(entry);\n grouped.set(group, existing);\n }\n\n for (const [group, entries] of grouped) {\n // Find the top-level entry for this group (shortest name)\n const topLevel = entries\n .filter((e) => e.name === group || e.name.split(':').length === 1)\n .sort((a, b) => b.durationMs - a.durationMs)[0];\n\n const subEntries = entries.filter((e) => e.name !== group && e.name.startsWith(`${group}:`));\n\n if (topLevel) {\n const pct = totalMs > 0 ? ((topLevel.durationMs / totalMs) * 100).toFixed(1) : '0.0';\n lines.push(` ${group}: ${formatMs(topLevel.durationMs)} (${pct}%)`);\n }\n\n for (const sub of subEntries.sort((a, b) => b.durationMs - a.durationMs)) {\n const subName = sub.name.slice(group.length + 1);\n lines.push(` ├─ ${subName}: ${formatMs(sub.durationMs)}`);\n }\n }\n\n return lines.join('\\n');\n};\n\nconst printPerfSummary = (totalMs: number): void => {\n if (!isPerfEnabled()) {\n return;\n }\n\n const data = collectPerfData();\n\n console.log('\\n\\x1b[35mPhase breakdown:\\x1b[0m');\n console.log(formatTimingTree(data.timings, totalMs));\n\n if (data.memory.length > 0) {\n const peak = data.memory.reduce(\n (max, snap) => (snap.rss > max.rss ? snap : max),\n data.memory[0]!,\n );\n console.log(\n ` Peak memory: ${formatMemoryMB(peak.rss)} RSS, ${formatMemoryMB(peak.heapUsed)} heap`,\n );\n }\n\n console.log('');\n};\n\nexport {\n captureMemory,\n clearTimings,\n collectPerfData,\n collectTimings,\n formatMemoryMB,\n formatMs,\n formatTimingTree,\n isPerfEnabled,\n measureAsync,\n measureSync,\n PERF_PREFIX,\n printPerfSummary,\n};\n\nexport type { MemorySnapshot, PerfData, TimingEntry };\n"],"mappings":";;;AAEA,MAAM,cAAc;AAEpB,MAAM,sBAA+B,QAAQ,IAAI,aAAa;AA2B9D,MAAM,kBAAoC,EAAE;AAE5C,MAAM,iBAAiB,UAAwB;
|
|
1
|
+
{"version":3,"file":"perf.js","names":[],"sources":["../../src/css/perf.ts"],"sourcesContent":["import { performance } from 'node:perf_hooks';\n\nconst PERF_PREFIX = 'uds:css:';\n\nconst isPerfEnabled = (): boolean => process.env.UDS_PERF === '1';\n\n// --- Types ---\n\ntype MemorySnapshot = {\n label: string;\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n timestamp: number;\n};\n\ntype TimingEntry = {\n name: string;\n durationMs: number;\n startTime: number;\n detail?: unknown;\n};\n\ntype PerfData = {\n timings: TimingEntry[];\n memory: MemorySnapshot[];\n};\n\n// --- Memory tracking ---\n\nconst memorySnapshots: MemorySnapshot[] = [];\n\nconst captureMemory = (label: string): void => {\n if (!isPerfEnabled()) {\n return;\n }\n\n const mem = process.memoryUsage();\n memorySnapshots.push({\n label,\n rss: mem.rss,\n heapUsed: mem.heapUsed,\n heapTotal: mem.heapTotal,\n external: mem.external,\n timestamp: performance.now(),\n });\n};\n\n// --- Synchronous measurement ---\n\nconst measureSync = <T>(name: string, fn: () => T, detail?: unknown): T => {\n if (!isPerfEnabled()) {\n return fn();\n }\n\n const markName = `${PERF_PREFIX}${name}`;\n const startMark = `${markName}:start`;\n const endMark = `${markName}:end`;\n\n performance.mark(startMark, { detail });\n const result = fn();\n performance.mark(endMark);\n performance.measure(markName, startMark, endMark);\n\n return result;\n};\n\n// --- Asynchronous measurement ---\n\nconst measureAsync = async <T>(\n name: string,\n fn: () => Promise<T>,\n detail?: unknown,\n): Promise<T> => {\n if (!isPerfEnabled()) {\n return fn();\n }\n\n const markName = `${PERF_PREFIX}${name}`;\n const startMark = `${markName}:start`;\n const endMark = `${markName}:end`;\n\n performance.mark(startMark, { detail });\n const result = await fn();\n performance.mark(endMark);\n performance.measure(markName, startMark, endMark);\n\n return result;\n};\n\n// --- Collecting results ---\n\nconst collectTimings = (): TimingEntry[] => {\n return performance\n .getEntriesByType('measure')\n .filter((entry) => entry.name.startsWith(PERF_PREFIX))\n .map((entry) => ({\n name: entry.name.slice(PERF_PREFIX.length),\n durationMs: Math.round(entry.duration * 100) / 100,\n startTime: Math.round(entry.startTime * 100) / 100,\n detail: (entry as PerformanceMeasure).detail,\n }));\n};\n\nconst collectPerfData = (): PerfData => ({\n timings: collectTimings(),\n memory: [...memorySnapshots],\n});\n\nconst clearTimings = (): void => {\n performance.clearMarks();\n performance.clearMeasures();\n memorySnapshots.length = 0;\n};\n\n// --- Formatting ---\n\nconst formatMs = (ms: number): string => {\n if (ms < 1000) {\n return `${Math.round(ms)}ms`;\n }\n\n return `${(ms / 1000).toFixed(1)}s`;\n};\n\nconst formatMemoryMB = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(0)} MB`;\n\nconst formatTimingTree = (timings: TimingEntry[], totalMs: number): string => {\n const lines: string[] = [];\n const grouped = new Map<string, TimingEntry[]>();\n\n // Group by first segment (e.g., \"scan\", \"gen\", \"opt\")\n for (const entry of timings) {\n const segments = entry.name.split(':');\n const group = segments[0] ?? 'other';\n const existing = grouped.get(group) ?? [];\n existing.push(entry);\n grouped.set(group, existing);\n }\n\n for (const [group, entries] of grouped) {\n // Find the top-level entry for this group (shortest name)\n const topLevel = entries\n .filter((e) => e.name === group || e.name.split(':').length === 1)\n .sort((a, b) => b.durationMs - a.durationMs)[0];\n\n const subEntries = entries.filter((e) => e.name !== group && e.name.startsWith(`${group}:`));\n\n if (topLevel) {\n const pct = totalMs > 0 ? ((topLevel.durationMs / totalMs) * 100).toFixed(1) : '0.0';\n lines.push(` ${group}: ${formatMs(topLevel.durationMs)} (${pct}%)`);\n }\n\n for (const sub of subEntries.sort((a, b) => b.durationMs - a.durationMs)) {\n const subName = sub.name.slice(group.length + 1);\n lines.push(` ├─ ${subName}: ${formatMs(sub.durationMs)}`);\n }\n }\n\n return lines.join('\\n');\n};\n\nconst printPerfSummary = (totalMs: number): void => {\n if (!isPerfEnabled()) {\n return;\n }\n\n const data = collectPerfData();\n\n console.log('\\n\\x1b[35mPhase breakdown:\\x1b[0m');\n console.log(formatTimingTree(data.timings, totalMs));\n\n if (data.memory.length > 0) {\n const peak = data.memory.reduce(\n (max, snap) => (snap.rss > max.rss ? snap : max),\n data.memory[0]!,\n );\n console.log(\n ` Peak memory: ${formatMemoryMB(peak.rss)} RSS, ${formatMemoryMB(peak.heapUsed)} heap`,\n );\n }\n\n console.log('');\n};\n\nexport {\n captureMemory,\n clearTimings,\n collectPerfData,\n collectTimings,\n formatMemoryMB,\n formatMs,\n formatTimingTree,\n isPerfEnabled,\n measureAsync,\n measureSync,\n PERF_PREFIX,\n printPerfSummary,\n};\n\nexport type { MemorySnapshot, PerfData, TimingEntry };\n"],"mappings":";;;AAEA,MAAM,cAAc;AAEpB,MAAM,sBAA+B,QAAQ,IAAI,aAAa;AA2B9D,MAAM,kBAAoC,EAAE;AAE5C,MAAM,iBAAiB,UAAwB;CAC7C,IAAI,CAAC,eAAe,EAClB;CAGF,MAAM,MAAM,QAAQ,aAAa;CACjC,gBAAgB,KAAK;EACnB;EACA,KAAK,IAAI;EACT,UAAU,IAAI;EACd,WAAW,IAAI;EACf,UAAU,IAAI;EACd,WAAW,YAAY,KAAK;EAC7B,CAAC;;AAwBJ,MAAM,eAAe,OACnB,MACA,IACA,WACe;CACf,IAAI,CAAC,eAAe,EAClB,OAAO,IAAI;CAGb,MAAM,WAAW,GAAG,cAAc;CAClC,MAAM,YAAY,GAAG,SAAS;CAC9B,MAAM,UAAU,GAAG,SAAS;CAE5B,YAAY,KAAK,WAAW,EAAE,QAAQ,CAAC;CACvC,MAAM,SAAS,MAAM,IAAI;CACzB,YAAY,KAAK,QAAQ;CACzB,YAAY,QAAQ,UAAU,WAAW,QAAQ;CAEjD,OAAO;;AAKT,MAAM,uBAAsC;CAC1C,OAAO,YACJ,iBAAiB,UAAU,CAC3B,QAAQ,UAAU,MAAM,KAAK,WAAW,YAAY,CAAC,CACrD,KAAK,WAAW;EACf,MAAM,MAAM,KAAK,MAAM,EAAmB;EAC1C,YAAY,KAAK,MAAM,MAAM,WAAW,IAAI,GAAG;EAC/C,WAAW,KAAK,MAAM,MAAM,YAAY,IAAI,GAAG;EAC/C,QAAS,MAA6B;EACvC,EAAE;;AAGP,MAAM,yBAAmC;CACvC,SAAS,gBAAgB;CACzB,QAAQ,CAAC,GAAG,gBAAgB;CAC7B;AAED,MAAM,qBAA2B;CAC/B,YAAY,YAAY;CACxB,YAAY,eAAe;CAC3B,gBAAgB,SAAS;;AAK3B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CAAC,eAAe,EAClB;CAGF,MAAM,OAAO,iBAAiB;CAE9B,QAAQ,IAAI,oCAAoC;CAChD,QAAQ,IAAI,iBAAiB,KAAK,SAAS,QAAQ,CAAC;CAEpD,IAAI,KAAK,OAAO,SAAS,GAAG;EAC1B,MAAM,OAAO,KAAK,OAAO,QACtB,KAAK,SAAU,KAAK,MAAM,IAAI,MAAM,OAAO,KAC5C,KAAK,OAAO,GACb;EACD,QAAQ,IACN,kBAAkB,eAAe,KAAK,IAAI,CAAC,QAAQ,eAAe,KAAK,SAAS,CAAC,OAClF;;CAGH,QAAQ,IAAI,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postcss.helpers.js","names":[],"sources":["../../src/css/postcss.helpers.ts"],"sourcesContent":["const COLOR_MODE_RE = /^(\\.(uds-color-mode-(?:dark|light)))(\\s+.+)?$/;\n\nconst escapeForRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\ntype ScopedColorModeSelectorVariant = 'descendant' | 'same-element';\n\nconst SCOPED_SELF_OR_PARENT_RE = /^(\\.[^\\s>+~]+)(.*)$/;\n\nconst getScopedColorModeAlternativeSelector = (\n selector: string,\n scopeClass: string,\n variant: ScopedColorModeSelectorVariant = 'descendant',\n): string | null => {\n const scopeMatch = selector.match(new RegExp(`^(${escapeForRegExp(scopeClass)})\\\\s+(.+)$`));\n\n if (!scopeMatch) {\n return null;\n }\n\n const afterScope = scopeMatch[2];\n const colorModeMatch = afterScope.match(COLOR_MODE_RE);\n if (!colorModeMatch) {\n return null;\n }\n\n const colorModeClass = colorModeMatch[1];\n const rest = colorModeMatch[3] ?? '';\n return variant === 'same-element'\n ? `${colorModeClass}${scopeClass}${rest}`\n : `${colorModeClass} ${scopeClass}${rest}`;\n};\n\nconst buildScopedColorModeSelectorList = (ruleSelector: string, scopeClass: string): string => {\n const selectors = ruleSelector.split(',').map((value) => value.trim());\n const nextSelectors = selectors.reduce<string[]>((acc, selector) => {\n const altSelectors = [\n getScopedColorModeAlternativeSelector(selector, scopeClass),\n getScopedColorModeAlternativeSelector(selector, scopeClass, 'same-element'),\n ].filter((value): value is string => Boolean(value));\n const nextAltSelectors = altSelectors.filter(\n (altSelector) => !selectors.includes(altSelector) && !acc.includes(altSelector),\n );\n\n return [...acc, selector, ...nextAltSelectors];\n }, []);\n\n return nextSelectors.join(', ');\n};\n\nconst getScopedSelfOrParentAlternativeSelector = (\n selector: string,\n scopeClass: string,\n): string | null => {\n const scopeMatch = selector.match(new RegExp(`^(${escapeForRegExp(scopeClass)})\\\\s+(.+)$`));\n\n if (!scopeMatch) {\n return null;\n }\n\n const afterScope = scopeMatch[2];\n const targetMatch = afterScope.match(SCOPED_SELF_OR_PARENT_RE);\n if (!targetMatch) {\n return null;\n }\n\n const scopedTarget = targetMatch[1];\n if (/^\\.uds-color-mode-(?:dark|light)(?:$|[.#[:])/.test(scopedTarget)) {\n return null;\n }\n\n return `${scopeClass}${scopedTarget}${targetMatch[2]}`;\n};\n\nconst buildScopedSelfOrParentSelectorList = (ruleSelector: string, scopeClass: string): string => {\n const selectors = ruleSelector.split(',').map((value) => value.trim());\n const nextSelectors = selectors.reduce<string[]>((acc, selector) => {\n const sameElementSelector = getScopedSelfOrParentAlternativeSelector(selector, scopeClass);\n const nextAltSelectors: string[] = [];\n\n if (\n sameElementSelector &&\n !selectors.includes(sameElementSelector) &&\n !acc.includes(sameElementSelector)\n ) {\n nextAltSelectors.push(sameElementSelector);\n }\n\n return [...acc, selector, ...nextAltSelectors];\n }, []);\n\n return nextSelectors.join(', ');\n};\n\nexport {\n buildScopedColorModeSelectorList,\n buildScopedSelfOrParentSelectorList,\n getScopedColorModeAlternativeSelector,\n getScopedSelfOrParentAlternativeSelector,\n};\n"],"mappings":";;AAAA,MAAM,gBAAgB;AAEtB,MAAM,mBAAmB,UAA0B,MAAM,QAAQ,uBAAuB,OAAO;AAI/F,MAAM,2BAA2B;AAEjC,MAAM,yCACJ,UACA,YACA,UAA0C,iBACxB;CAClB,MAAM,aAAa,SAAS,MAAM,IAAI,OAAO,KAAK,gBAAgB,WAAW,CAAC,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"postcss.helpers.js","names":[],"sources":["../../src/css/postcss.helpers.ts"],"sourcesContent":["const COLOR_MODE_RE = /^(\\.(uds-color-mode-(?:dark|light)))(\\s+.+)?$/;\n\nconst escapeForRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\ntype ScopedColorModeSelectorVariant = 'descendant' | 'same-element';\n\nconst SCOPED_SELF_OR_PARENT_RE = /^(\\.[^\\s>+~]+)(.*)$/;\n\nconst getScopedColorModeAlternativeSelector = (\n selector: string,\n scopeClass: string,\n variant: ScopedColorModeSelectorVariant = 'descendant',\n): string | null => {\n const scopeMatch = selector.match(new RegExp(`^(${escapeForRegExp(scopeClass)})\\\\s+(.+)$`));\n\n if (!scopeMatch) {\n return null;\n }\n\n const afterScope = scopeMatch[2];\n const colorModeMatch = afterScope.match(COLOR_MODE_RE);\n if (!colorModeMatch) {\n return null;\n }\n\n const colorModeClass = colorModeMatch[1];\n const rest = colorModeMatch[3] ?? '';\n return variant === 'same-element'\n ? `${colorModeClass}${scopeClass}${rest}`\n : `${colorModeClass} ${scopeClass}${rest}`;\n};\n\nconst buildScopedColorModeSelectorList = (ruleSelector: string, scopeClass: string): string => {\n const selectors = ruleSelector.split(',').map((value) => value.trim());\n const nextSelectors = selectors.reduce<string[]>((acc, selector) => {\n const altSelectors = [\n getScopedColorModeAlternativeSelector(selector, scopeClass),\n getScopedColorModeAlternativeSelector(selector, scopeClass, 'same-element'),\n ].filter((value): value is string => Boolean(value));\n const nextAltSelectors = altSelectors.filter(\n (altSelector) => !selectors.includes(altSelector) && !acc.includes(altSelector),\n );\n\n return [...acc, selector, ...nextAltSelectors];\n }, []);\n\n return nextSelectors.join(', ');\n};\n\nconst getScopedSelfOrParentAlternativeSelector = (\n selector: string,\n scopeClass: string,\n): string | null => {\n const scopeMatch = selector.match(new RegExp(`^(${escapeForRegExp(scopeClass)})\\\\s+(.+)$`));\n\n if (!scopeMatch) {\n return null;\n }\n\n const afterScope = scopeMatch[2];\n const targetMatch = afterScope.match(SCOPED_SELF_OR_PARENT_RE);\n if (!targetMatch) {\n return null;\n }\n\n const scopedTarget = targetMatch[1];\n if (/^\\.uds-color-mode-(?:dark|light)(?:$|[.#[:])/.test(scopedTarget)) {\n return null;\n }\n\n return `${scopeClass}${scopedTarget}${targetMatch[2]}`;\n};\n\nconst buildScopedSelfOrParentSelectorList = (ruleSelector: string, scopeClass: string): string => {\n const selectors = ruleSelector.split(',').map((value) => value.trim());\n const nextSelectors = selectors.reduce<string[]>((acc, selector) => {\n const sameElementSelector = getScopedSelfOrParentAlternativeSelector(selector, scopeClass);\n const nextAltSelectors: string[] = [];\n\n if (\n sameElementSelector &&\n !selectors.includes(sameElementSelector) &&\n !acc.includes(sameElementSelector)\n ) {\n nextAltSelectors.push(sameElementSelector);\n }\n\n return [...acc, selector, ...nextAltSelectors];\n }, []);\n\n return nextSelectors.join(', ');\n};\n\nexport {\n buildScopedColorModeSelectorList,\n buildScopedSelfOrParentSelectorList,\n getScopedColorModeAlternativeSelector,\n getScopedSelfOrParentAlternativeSelector,\n};\n"],"mappings":";;AAAA,MAAM,gBAAgB;AAEtB,MAAM,mBAAmB,UAA0B,MAAM,QAAQ,uBAAuB,OAAO;AAI/F,MAAM,2BAA2B;AAEjC,MAAM,yCACJ,UACA,YACA,UAA0C,iBACxB;CAClB,MAAM,aAAa,SAAS,MAAM,IAAI,OAAO,KAAK,gBAAgB,WAAW,CAAC,YAAY,CAAC;CAE3F,IAAI,CAAC,YACH,OAAO;CAIT,MAAM,iBADa,WAAW,GACI,MAAM,cAAc;CACtD,IAAI,CAAC,gBACH,OAAO;CAGT,MAAM,iBAAiB,eAAe;CACtC,MAAM,OAAO,eAAe,MAAM;CAClC,OAAO,YAAY,iBACf,GAAG,iBAAiB,aAAa,SACjC,GAAG,eAAe,GAAG,aAAa;;AAGxC,MAAM,oCAAoC,cAAsB,eAA+B;CAC7F,MAAM,YAAY,aAAa,MAAM,IAAI,CAAC,KAAK,UAAU,MAAM,MAAM,CAAC;CAatE,OAZsB,UAAU,QAAkB,KAAK,aAAa;EAKlE,MAAM,mBAJe,CACnB,sCAAsC,UAAU,WAAW,EAC3D,sCAAsC,UAAU,YAAY,eAAe,CAC5E,CAAC,QAAQ,UAA2B,QAAQ,MAAM,CACd,CAAC,QACnC,gBAAgB,CAAC,UAAU,SAAS,YAAY,IAAI,CAAC,IAAI,SAAS,YAAY,CAChF;EAED,OAAO;GAAC,GAAG;GAAK;GAAU,GAAG;GAAiB;IAC7C,EAAE,CAEe,CAAC,KAAK,KAAK;;AAGjC,MAAM,4CACJ,UACA,eACkB;CAClB,MAAM,aAAa,SAAS,MAAM,IAAI,OAAO,KAAK,gBAAgB,WAAW,CAAC,YAAY,CAAC;CAE3F,IAAI,CAAC,YACH,OAAO;CAIT,MAAM,cADa,WAAW,GACC,MAAM,yBAAyB;CAC9D,IAAI,CAAC,aACH,OAAO;CAGT,MAAM,eAAe,YAAY;CACjC,IAAI,+CAA+C,KAAK,aAAa,EACnE,OAAO;CAGT,OAAO,GAAG,aAAa,eAAe,YAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postcss.js","names":[],"sources":["../../src/css/postcss.ts"],"sourcesContent":["import type postcss from 'postcss';\n\nimport {\n buildScopedColorModeSelectorList,\n getScopedSelfOrParentAlternativeSelector,\n} from './postcss.helpers';\n\nconst fixScopedSelfOrParentSelectorsPlugin = (scopeClass: string): postcss.Plugin => {\n return {\n postcssPlugin: 'fix-scoped-self-or-parent-selectors',\n Once(root) {\n root.walkRules((rule) => {\n if (!rule.selector.includes(scopeClass)) {\n return;\n }\n\n const nextSelectors = rule.selectors.reduce<string[]>((acc, selector) => {\n const sameElementSelector = getScopedSelfOrParentAlternativeSelector(\n selector,\n scopeClass,\n );\n\n if (sameElementSelector && !rule.selectors.includes(sameElementSelector)) {\n return [...acc, selector, sameElementSelector];\n }\n\n return [...acc, selector];\n }, []);\n\n if (nextSelectors.length !== rule.selectors.length) {\n rule.selectors = nextSelectors;\n }\n });\n },\n };\n};\n\n/**\n * PostCSS plugin to fix color mode selectors for scoped CSS.\n *\n * postcss-scope converts selectors like:\n * `.uds-color-mode-dark .foo` → `.scope .uds-color-mode-dark .foo`\n *\n * But the color mode class is typically on <html> or <body>, which is an\n * ANCESTOR of the scope, not a descendant. This plugin adds alternative\n * selectors so color modes work correctly:\n *\n * `.scope .uds-color-mode-dark .foo` → `.scope .uds-color-mode-dark .foo, .uds-color-mode-dark .scope .foo, .uds-color-mode-dark.scope .foo`\n *\n * This ensures styles apply whether the color mode class is inside or outside the scope.\n */\nconst fixScopedColorModeSelectorsPlugin = (scopeClass: string): postcss.Plugin => {\n const colorModePattern = /\\.(uds-color-mode-(?:dark|light))/;\n\n return {\n postcssPlugin: 'fix-scoped-color-mode-selectors',\n // Use Once to process all rules after parsing is complete\n Once(root) {\n root.walkRules((rule) => {\n // Skip if selector doesn't contain both scope and color mode\n if (!rule.selector.includes(scopeClass) || !colorModePattern.test(rule.selector)) {\n return;\n }\n\n const nextSelector = buildScopedColorModeSelectorList(rule.selector, scopeClass);\n if (nextSelector !== rule.selector) {\n rule.selector = nextSelector;\n }\n });\n },\n };\n};\nexport { fixScopedColorModeSelectorsPlugin, fixScopedSelfOrParentSelectorsPlugin };\n"],"mappings":";;;AAOA,MAAM,wCAAwC,eAAuC;
|
|
1
|
+
{"version":3,"file":"postcss.js","names":[],"sources":["../../src/css/postcss.ts"],"sourcesContent":["import type postcss from 'postcss';\n\nimport {\n buildScopedColorModeSelectorList,\n getScopedSelfOrParentAlternativeSelector,\n} from './postcss.helpers';\n\nconst fixScopedSelfOrParentSelectorsPlugin = (scopeClass: string): postcss.Plugin => {\n return {\n postcssPlugin: 'fix-scoped-self-or-parent-selectors',\n Once(root) {\n root.walkRules((rule) => {\n if (!rule.selector.includes(scopeClass)) {\n return;\n }\n\n const nextSelectors = rule.selectors.reduce<string[]>((acc, selector) => {\n const sameElementSelector = getScopedSelfOrParentAlternativeSelector(\n selector,\n scopeClass,\n );\n\n if (sameElementSelector && !rule.selectors.includes(sameElementSelector)) {\n return [...acc, selector, sameElementSelector];\n }\n\n return [...acc, selector];\n }, []);\n\n if (nextSelectors.length !== rule.selectors.length) {\n rule.selectors = nextSelectors;\n }\n });\n },\n };\n};\n\n/**\n * PostCSS plugin to fix color mode selectors for scoped CSS.\n *\n * postcss-scope converts selectors like:\n * `.uds-color-mode-dark .foo` → `.scope .uds-color-mode-dark .foo`\n *\n * But the color mode class is typically on <html> or <body>, which is an\n * ANCESTOR of the scope, not a descendant. This plugin adds alternative\n * selectors so color modes work correctly:\n *\n * `.scope .uds-color-mode-dark .foo` → `.scope .uds-color-mode-dark .foo, .uds-color-mode-dark .scope .foo, .uds-color-mode-dark.scope .foo`\n *\n * This ensures styles apply whether the color mode class is inside or outside the scope.\n */\nconst fixScopedColorModeSelectorsPlugin = (scopeClass: string): postcss.Plugin => {\n const colorModePattern = /\\.(uds-color-mode-(?:dark|light))/;\n\n return {\n postcssPlugin: 'fix-scoped-color-mode-selectors',\n // Use Once to process all rules after parsing is complete\n Once(root) {\n root.walkRules((rule) => {\n // Skip if selector doesn't contain both scope and color mode\n if (!rule.selector.includes(scopeClass) || !colorModePattern.test(rule.selector)) {\n return;\n }\n\n const nextSelector = buildScopedColorModeSelectorList(rule.selector, scopeClass);\n if (nextSelector !== rule.selector) {\n rule.selector = nextSelector;\n }\n });\n },\n };\n};\nexport { fixScopedColorModeSelectorsPlugin, fixScopedSelfOrParentSelectorsPlugin };\n"],"mappings":";;;AAOA,MAAM,wCAAwC,eAAuC;CACnF,OAAO;EACL,eAAe;EACf,KAAK,MAAM;GACT,KAAK,WAAW,SAAS;IACvB,IAAI,CAAC,KAAK,SAAS,SAAS,WAAW,EACrC;IAGF,MAAM,gBAAgB,KAAK,UAAU,QAAkB,KAAK,aAAa;KACvE,MAAM,sBAAsB,yCAC1B,UACA,WACD;KAED,IAAI,uBAAuB,CAAC,KAAK,UAAU,SAAS,oBAAoB,EACtE,OAAO;MAAC,GAAG;MAAK;MAAU;MAAoB;KAGhD,OAAO,CAAC,GAAG,KAAK,SAAS;OACxB,EAAE,CAAC;IAEN,IAAI,cAAc,WAAW,KAAK,UAAU,QAC1C,KAAK,YAAY;KAEnB;;EAEL;;;;;;;;;;;;;;;;AAiBH,MAAM,qCAAqC,eAAuC;CAChF,MAAM,mBAAmB;CAEzB,OAAO;EACL,eAAe;EAEf,KAAK,MAAM;GACT,KAAK,WAAW,SAAS;IAEvB,IAAI,CAAC,KAAK,SAAS,SAAS,WAAW,IAAI,CAAC,iBAAiB,KAAK,KAAK,SAAS,EAC9E;IAGF,MAAM,eAAe,iCAAiC,KAAK,UAAU,WAAW;IAChF,IAAI,iBAAiB,KAAK,UACxB,KAAK,WAAW;KAElB;;EAEL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"purgeWorker.js","names":[],"sources":["../../src/css/purgeWorker.ts"],"sourcesContent":["import { parentPort } from 'node:worker_threads';\n\nimport type { PurgeFromCodeOptions } from '../purger/optimized/purgeFromCode';\nimport { purgeFromCodeOptimized } from '../purger/optimized/purgeFromCode';\n\ntype SharedConfig = Pick<PurgeFromCodeOptions, 'variants' | 'autoVariants' | 'componentData'>;\n\ntype InitMessage = {\n type: 'init';\n config: SharedConfig;\n};\n\ntype TaskMessage = {\n type: 'task';\n id: number;\n code: string;\n filePath: string;\n colorModes?: ('dark' | 'light')[];\n variantDefaults?: PurgeFromCodeOptions['variantDefaults'];\n runtimeConfigValues?: PurgeFromCodeOptions['runtimeConfigValues'];\n includeAllClassNamePrimitives?: boolean;\n};\n\ntype DoneMessage = {\n type: 'done';\n};\n\ntype WorkerMessage = DoneMessage | InitMessage | TaskMessage;\n\nlet sharedConfig: SharedConfig | null = null;\n\nparentPort?.on('message', async (msg: WorkerMessage) => {\n if (msg.type === 'init') {\n sharedConfig = msg.config;\n parentPort?.postMessage({ type: 'ready' });\n return;\n }\n\n if (msg.type === 'task') {\n if (!sharedConfig) {\n parentPort?.postMessage({ type: 'error', id: msg.id, error: 'Worker not initialized' });\n return;\n }\n\n try {\n const result = await purgeFromCodeOptimized(msg.code, {\n ...sharedConfig,\n colorModes: msg.colorModes,\n variantDefaults: msg.variantDefaults,\n runtimeConfigValues: msg.runtimeConfigValues,\n includeAllClassNamePrimitives: msg.includeAllClassNamePrimitives,\n filePath: msg.filePath,\n });\n parentPort?.postMessage({ type: 'result', id: msg.id, result });\n } catch (error) {\n parentPort?.postMessage({\n type: 'error',\n id: msg.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return;\n }\n\n if (msg.type === 'done') {\n process.exit(0);\n }\n});\n"],"mappings":";;;;AA6BA,IAAI,eAAoC;AAExC,YAAY,GAAG,WAAW,OAAO,QAAuB;
|
|
1
|
+
{"version":3,"file":"purgeWorker.js","names":[],"sources":["../../src/css/purgeWorker.ts"],"sourcesContent":["import { parentPort } from 'node:worker_threads';\n\nimport type { PurgeFromCodeOptions } from '../purger/optimized/purgeFromCode';\nimport { purgeFromCodeOptimized } from '../purger/optimized/purgeFromCode';\n\ntype SharedConfig = Pick<PurgeFromCodeOptions, 'variants' | 'autoVariants' | 'componentData'>;\n\ntype InitMessage = {\n type: 'init';\n config: SharedConfig;\n};\n\ntype TaskMessage = {\n type: 'task';\n id: number;\n code: string;\n filePath: string;\n colorModes?: ('dark' | 'light')[];\n variantDefaults?: PurgeFromCodeOptions['variantDefaults'];\n runtimeConfigValues?: PurgeFromCodeOptions['runtimeConfigValues'];\n includeAllClassNamePrimitives?: boolean;\n};\n\ntype DoneMessage = {\n type: 'done';\n};\n\ntype WorkerMessage = DoneMessage | InitMessage | TaskMessage;\n\nlet sharedConfig: SharedConfig | null = null;\n\nparentPort?.on('message', async (msg: WorkerMessage) => {\n if (msg.type === 'init') {\n sharedConfig = msg.config;\n parentPort?.postMessage({ type: 'ready' });\n return;\n }\n\n if (msg.type === 'task') {\n if (!sharedConfig) {\n parentPort?.postMessage({ type: 'error', id: msg.id, error: 'Worker not initialized' });\n return;\n }\n\n try {\n const result = await purgeFromCodeOptimized(msg.code, {\n ...sharedConfig,\n colorModes: msg.colorModes,\n variantDefaults: msg.variantDefaults,\n runtimeConfigValues: msg.runtimeConfigValues,\n includeAllClassNamePrimitives: msg.includeAllClassNamePrimitives,\n filePath: msg.filePath,\n });\n parentPort?.postMessage({ type: 'result', id: msg.id, result });\n } catch (error) {\n parentPort?.postMessage({\n type: 'error',\n id: msg.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return;\n }\n\n if (msg.type === 'done') {\n process.exit(0);\n }\n});\n"],"mappings":";;;;AA6BA,IAAI,eAAoC;AAExC,YAAY,GAAG,WAAW,OAAO,QAAuB;CACtD,IAAI,IAAI,SAAS,QAAQ;EACvB,eAAe,IAAI;EACnB,YAAY,YAAY,EAAE,MAAM,SAAS,CAAC;EAC1C;;CAGF,IAAI,IAAI,SAAS,QAAQ;EACvB,IAAI,CAAC,cAAc;GACjB,YAAY,YAAY;IAAE,MAAM;IAAS,IAAI,IAAI;IAAI,OAAO;IAA0B,CAAC;GACvF;;EAGF,IAAI;GACF,MAAM,SAAS,MAAM,uBAAuB,IAAI,MAAM;IACpD,GAAG;IACH,YAAY,IAAI;IAChB,iBAAiB,IAAI;IACrB,qBAAqB,IAAI;IACzB,+BAA+B,IAAI;IACnC,UAAU,IAAI;IACf,CAAC;GACF,YAAY,YAAY;IAAE,MAAM;IAAU,IAAI,IAAI;IAAI;IAAQ,CAAC;WACxD,OAAO;GACd,YAAY,YAAY;IACtB,MAAM;IACN,IAAI,IAAI;IACR,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;IAC9D,CAAC;;EAEJ;;CAGF,IAAI,IAAI,SAAS,QACf,QAAQ,KAAK,EAAE;EAEjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.helpers.js","names":[],"sources":["../../src/css/runner.helpers.ts"],"sourcesContent":["import path from 'node:path';\n\ntype OptimizationStats = {\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n};\n\ntype MainCssSummaryOptions = {\n sizeGzipBytes: number;\n optimizationStats?: OptimizationStats;\n formatBytes: (bytes: number) => string;\n};\n\ntype CssSummaryOptions = MainCssSummaryOptions & {\n label: string;\n};\n\ntype CssSummaryMessage = {\n summaryLine: string;\n detailLines: string[];\n};\n\ntype OutputFileSection = {\n label: string;\n paths: string[];\n};\n\ntype ScanSummaryOptions = {\n label: string;\n filesScanned: number;\n filesWithComponents: number;\n componentCount: number;\n mode: 'app' | 'inherit' | 'scoped';\n};\n\nconst getDisplayPath = (cwd: string, targetPath: string): string => {\n const relativePath = path.relative(cwd, targetPath);\n return relativePath.length === 0 ? '.' : relativePath;\n};\n\nconst getVerboseScanFileList = (cwd: string, filePaths: string[]): string[] =>\n [...new Set(filePaths.map((filePath) => getDisplayPath(cwd, filePath)))].sort((left, right) =>\n left.localeCompare(right),\n );\n\nconst getOptimizationDetailLines = (optimizationStats: OptimizationStats): string[] => {\n const detailLines: string[] = [];\n\n if (optimizationStats.fontFacesRemoved > 0) {\n detailLines.push(` • removed ${optimizationStats.fontFacesRemoved} unused @font-face`);\n }\n\n if (optimizationStats.emptyRulesRemoved > 0) {\n detailLines.push(` • removed ${optimizationStats.emptyRulesRemoved} empty rules`);\n }\n\n return detailLines;\n};\n\nconst formatCssDuration = (durationMs: number): string => {\n const seconds = Math.floor(durationMs / 100) / 10;\n return `${seconds.toFixed(1)}s`;\n};\n\nconst getCssSummaryMessage = (options: CssSummaryOptions): CssSummaryMessage => {\n const { label, optimizationStats, sizeGzipBytes, formatBytes } = options;\n const summaryLine = `${label}: ${formatBytes(sizeGzipBytes)} gzip`;\n\n if (!optimizationStats) {\n return {\n summaryLine,\n detailLines: [],\n };\n }\n\n const { originalSizeGzip, fontFacesRemoved, emptyRulesRemoved } = optimizationStats;\n const savedBytesGzip = originalSizeGzip - sizeGzipBytes;\n\n if (savedBytesGzip <= 0) {\n return {\n summaryLine,\n detailLines: [],\n };\n }\n\n return {\n summaryLine,\n detailLines: getOptimizationDetailLines({\n originalSizeGzip,\n fontFacesRemoved,\n emptyRulesRemoved,\n }),\n };\n};\n\nconst getMainCssSummaryMessage = (options: MainCssSummaryOptions): CssSummaryMessage => {\n return getCssSummaryMessage({\n label: 'Main CSS',\n ...options,\n });\n};\n\nconst getScopedCssSummaryMessage = (\n packageName: string,\n options: MainCssSummaryOptions,\n): CssSummaryMessage =>\n getCssSummaryMessage({\n label: `${packageName} CSS`,\n ...options,\n });\n\nconst getOutputFileSection = (cwd: string, outputPaths: string[]): OutputFileSection => ({\n label: 'Output files:',\n paths: outputPaths.map((outputPath) => getDisplayPath(cwd, outputPath)),\n});\n\nconst getScanSummaryMessage = (options: ScanSummaryOptions): string => {\n const nonComponentFileCount = Math.max(options.filesScanned - options.filesWithComponents, 0);\n const fileLabel = nonComponentFileCount === 1 ? 'file' : 'files';\n const componentLabel = options.componentCount === 1 ? 'component' : 'components';\n return `${options.label}: ${nonComponentFileCount} ${fileLabel}, ${options.componentCount} ${componentLabel} (${options.mode})`;\n};\n\nconst getWatchDirectoryGroups = (entryDirs: string[], dirs: string[]) => {\n const watchDirs = [\n ...new Set(dirs.filter((dir) => !dir.split(path.sep).includes('node_modules'))),\n ];\n const filteredPackageDirs = watchDirs.filter((dir) => !entryDirs.includes(dir));\n\n return {\n watchDirs,\n filteredPackageDirs,\n };\n};\n\nexport {\n formatCssDuration,\n getDisplayPath,\n getMainCssSummaryMessage,\n getOutputFileSection,\n getScanSummaryMessage,\n getScopedCssSummaryMessage,\n getVerboseScanFileList,\n getWatchDirectoryGroups,\n};\n"],"mappings":";;;AAoCA,MAAM,kBAAkB,KAAa,eAA+B;CAClE,MAAM,eAAe,KAAK,SAAS,KAAK,WAAW;
|
|
1
|
+
{"version":3,"file":"runner.helpers.js","names":[],"sources":["../../src/css/runner.helpers.ts"],"sourcesContent":["import path from 'node:path';\n\ntype OptimizationStats = {\n originalSizeGzip: number;\n fontFacesRemoved: number;\n emptyRulesRemoved: number;\n};\n\ntype MainCssSummaryOptions = {\n sizeGzipBytes: number;\n optimizationStats?: OptimizationStats;\n formatBytes: (bytes: number) => string;\n};\n\ntype CssSummaryOptions = MainCssSummaryOptions & {\n label: string;\n};\n\ntype CssSummaryMessage = {\n summaryLine: string;\n detailLines: string[];\n};\n\ntype OutputFileSection = {\n label: string;\n paths: string[];\n};\n\ntype ScanSummaryOptions = {\n label: string;\n filesScanned: number;\n filesWithComponents: number;\n componentCount: number;\n mode: 'app' | 'inherit' | 'scoped';\n};\n\nconst getDisplayPath = (cwd: string, targetPath: string): string => {\n const relativePath = path.relative(cwd, targetPath);\n return relativePath.length === 0 ? '.' : relativePath;\n};\n\nconst getVerboseScanFileList = (cwd: string, filePaths: string[]): string[] =>\n [...new Set(filePaths.map((filePath) => getDisplayPath(cwd, filePath)))].sort((left, right) =>\n left.localeCompare(right),\n );\n\nconst getOptimizationDetailLines = (optimizationStats: OptimizationStats): string[] => {\n const detailLines: string[] = [];\n\n if (optimizationStats.fontFacesRemoved > 0) {\n detailLines.push(` • removed ${optimizationStats.fontFacesRemoved} unused @font-face`);\n }\n\n if (optimizationStats.emptyRulesRemoved > 0) {\n detailLines.push(` • removed ${optimizationStats.emptyRulesRemoved} empty rules`);\n }\n\n return detailLines;\n};\n\nconst formatCssDuration = (durationMs: number): string => {\n const seconds = Math.floor(durationMs / 100) / 10;\n return `${seconds.toFixed(1)}s`;\n};\n\nconst getCssSummaryMessage = (options: CssSummaryOptions): CssSummaryMessage => {\n const { label, optimizationStats, sizeGzipBytes, formatBytes } = options;\n const summaryLine = `${label}: ${formatBytes(sizeGzipBytes)} gzip`;\n\n if (!optimizationStats) {\n return {\n summaryLine,\n detailLines: [],\n };\n }\n\n const { originalSizeGzip, fontFacesRemoved, emptyRulesRemoved } = optimizationStats;\n const savedBytesGzip = originalSizeGzip - sizeGzipBytes;\n\n if (savedBytesGzip <= 0) {\n return {\n summaryLine,\n detailLines: [],\n };\n }\n\n return {\n summaryLine,\n detailLines: getOptimizationDetailLines({\n originalSizeGzip,\n fontFacesRemoved,\n emptyRulesRemoved,\n }),\n };\n};\n\nconst getMainCssSummaryMessage = (options: MainCssSummaryOptions): CssSummaryMessage => {\n return getCssSummaryMessage({\n label: 'Main CSS',\n ...options,\n });\n};\n\nconst getScopedCssSummaryMessage = (\n packageName: string,\n options: MainCssSummaryOptions,\n): CssSummaryMessage =>\n getCssSummaryMessage({\n label: `${packageName} CSS`,\n ...options,\n });\n\nconst getOutputFileSection = (cwd: string, outputPaths: string[]): OutputFileSection => ({\n label: 'Output files:',\n paths: outputPaths.map((outputPath) => getDisplayPath(cwd, outputPath)),\n});\n\nconst getScanSummaryMessage = (options: ScanSummaryOptions): string => {\n const nonComponentFileCount = Math.max(options.filesScanned - options.filesWithComponents, 0);\n const fileLabel = nonComponentFileCount === 1 ? 'file' : 'files';\n const componentLabel = options.componentCount === 1 ? 'component' : 'components';\n return `${options.label}: ${nonComponentFileCount} ${fileLabel}, ${options.componentCount} ${componentLabel} (${options.mode})`;\n};\n\nconst getWatchDirectoryGroups = (entryDirs: string[], dirs: string[]) => {\n const watchDirs = [\n ...new Set(dirs.filter((dir) => !dir.split(path.sep).includes('node_modules'))),\n ];\n const filteredPackageDirs = watchDirs.filter((dir) => !entryDirs.includes(dir));\n\n return {\n watchDirs,\n filteredPackageDirs,\n };\n};\n\nexport {\n formatCssDuration,\n getDisplayPath,\n getMainCssSummaryMessage,\n getOutputFileSection,\n getScanSummaryMessage,\n getScopedCssSummaryMessage,\n getVerboseScanFileList,\n getWatchDirectoryGroups,\n};\n"],"mappings":";;;AAoCA,MAAM,kBAAkB,KAAa,eAA+B;CAClE,MAAM,eAAe,KAAK,SAAS,KAAK,WAAW;CACnD,OAAO,aAAa,WAAW,IAAI,MAAM;;AAG3C,M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