@telegraph/style-engine 0.1.8 → 0.1.9

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @telegraph/style-engine
2
2
 
3
+ ## 0.1.9
4
+
5
+ ### Patch Changes
6
+
7
+ - [#428](https://github.com/knocklabs/telegraph/pull/428) [`c738dff`](https://github.com/knocklabs/telegraph/commit/c738dff0c3686f72cb366d4dd001fbc467dec132) Thanks [@kylemcd](https://github.com/kylemcd)! - adds style-engine post css plugin
8
+
9
+ - Updated dependencies [[`c738dff`](https://github.com/knocklabs/telegraph/commit/c738dff0c3686f72cb366d4dd001fbc467dec132)]:
10
+ - @telegraph/tokens@0.0.20
11
+
3
12
  ## 0.1.8
4
13
 
5
14
  ### Patch Changes
@@ -0,0 +1,2 @@
1
+ "use strict";const a=require("path"),l=require("fs"),m=require("postcss");function y(n=process.cwd()){let e=n,s=!0;for(;s;){const t=a.join(e,"package.json");if(l.existsSync(t))try{if(JSON.parse(l.readFileSync(t,"utf8")).workspaces)return e}catch{}const r=a.dirname(e);r===e&&(s=!1),e=r}throw new Error('Could not find monorepo root (no package.json with "workspaces" found)')}const h=(n,e)=>{var s;if(!(!n.dependencies||((s=Object.keys(n.dependencies))==null?void 0:s.length)===0))return Object.entries(n.dependencies).reduce((t,[r,c])=>(r.startsWith("@telegraph/")&&(t[r]={name:r,version:c,path:a.resolve(e,"node_modules",r)}),t),{})};function j(){const n=a.resolve(process.cwd(),"package.json"),e=JSON.parse(l.readFileSync(n,"utf8")),s=h(e,process.cwd()),t=y(),r=c=>{if(!c||Object.keys(c).length===0)return c;const i={...c};for(const u of Object.values(c)){let o,p;u.version.includes("workspace:")&&t?(o=a.resolve(t,"node_modules",u.name,"package.json"),p=t):(o=a.resolve(process.cwd(),"node_modules",u.name,"package.json"),p=process.cwd());try{const d=JSON.parse(l.readFileSync(o,"utf8")),g=h(d,p);if(Object.assign(i,g),g){const k=r(g);Object.assign(i,k)}}catch{continue}}return i};return s?r(s):{}}function f({fileName:n="default.css",path:e}){try{const s=`${e}/dist/css/${n}`,t=a.resolve(s);return l.existsSync(t)?l.readFileSync(t,"utf8"):null}catch{return null}}const v=async({root:n,config:e})=>{const s=j(),t=e.components===!0?Object.values(s).filter(o=>!o.name.includes("@telegraph/tokens")):[],r=e.tokens.length>0?Object.values(s).filter(o=>o.name.includes("@telegraph/tokens")):[],c=t.map(o=>f({path:o.path})).filter(Boolean),i=e.tokens.map(o=>r.map(d=>f({path:d.path,fileName:`${o}.css`})).filter(Boolean)).filter(Boolean),u=[...c,...i];for(const o of u){const p=m.parse(o);n.append(p)}},w=()=>({postcssPlugin:"@telegraph/style-engine",plugins:[{postcssPlugin:"style-engine",async Once(n){const e={tokens:[],components:!1};n.walkAtRules("telegraph",s=>{s.params==="components"&&(e.components=!0,s.remove()),s.params==="tokens-light"&&(e.tokens.push("light"),s.remove()),s.params==="tokens-dark"&&(e.tokens.push("dark"),s.remove()),s.params==="tokens"&&(e.tokens.push("default"),s.remove())}),await v({root:n,config:{tokens:e.tokens,components:e.components}})}}]}),O=Object.assign(w,{postcss:!0});module.exports=O;
2
+ //# sourceMappingURL=postcss.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postcss.js","sources":["../../src/plugins/postcss.ts"],"sourcesContent":["import { type AcceptedPlugin, type PluginCreator, type Root } from \"postcss\";\n\n// Using require() instead of import to prevent ESM-related bugs in PostCSS.\n// ESM = ECMAScript Modules (the import/export syntax)\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst nodePath = require(\"path\");\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst nodeFs = require(\"fs\");\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst postcss = require(\"postcss\");\n\ntype PkgJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\ntype DepObject = Record<\n string,\n {\n name: string;\n version: string;\n path: string;\n }\n>;\n\n/**\n * Traverses up the directory tree to find the root of the monorepo by looking for a package.json with workspaces.\n * This is needed to properly resolve workspace dependencies in a monorepo setup.\n */\nfunction findMonorepoRoot(start = process.cwd()): string {\n let current = start;\n let run = true;\n\n while (run) {\n const pkgJsonPath = nodePath.join(current, \"package.json\");\n if (nodeFs.existsSync(pkgJsonPath)) {\n try {\n const pkg = JSON.parse(nodeFs.readFileSync(pkgJsonPath, \"utf8\"));\n if (pkg.workspaces) {\n return current;\n }\n } catch {\n // malformed package.json, skip\n }\n }\n\n const parent = nodePath.dirname(current);\n if (parent === current) run = false;\n current = parent;\n }\n\n throw new Error(\n 'Could not find monorepo root (no package.json with \"workspaces\" found)',\n );\n}\n\n/**\n * Extracts all @telegraph/* dependencies from a package.json file and returns them with their paths.\n * This is used to find all Telegraph packages that might contain CSS we need to include.\n */\nconst getTelegraphDepsFromPackageJson = (\n pkg: PkgJson,\n pkgPath: string,\n): DepObject | undefined => {\n if (!pkg.dependencies || Object.keys(pkg.dependencies)?.length === 0) return;\n\n return Object.entries(pkg.dependencies).reduce((acc, [dep, version]) => {\n if (dep.startsWith(\"@telegraph/\")) {\n acc[dep] = {\n name: dep,\n version,\n path: nodePath.resolve(pkgPath, \"node_modules\", dep),\n };\n }\n return acc;\n }, {} as DepObject);\n};\n\n/**\n * Gets all Telegraph dependencies recursively, including dependencies of dependencies.\n * Handles both normal npm dependencies and workspace dependencies in a monorepo.\n */\nfunction getTelegraphDeps(): DepObject {\n const pkgPath = nodePath.resolve(process.cwd(), \"package.json\");\n const pkg = JSON.parse(nodeFs.readFileSync(pkgPath, \"utf8\"));\n const topLevelDeps = getTelegraphDepsFromPackageJson(pkg, process.cwd());\n const monorepoRoot = findMonorepoRoot();\n\n const recursivelyGetTelegraphDeps = (deps: DepObject): DepObject => {\n if (!deps || Object.keys(deps).length === 0) {\n return deps;\n }\n\n const allDeps = { ...deps };\n\n for (const dep of Object.values(deps)) {\n let pkgJsonPath: string;\n let searchPath: string;\n\n if (dep.version.includes(\"workspace:\") && monorepoRoot) {\n pkgJsonPath = nodePath.resolve(\n monorepoRoot,\n \"node_modules\",\n dep.name,\n \"package.json\",\n );\n searchPath = monorepoRoot;\n } else {\n pkgJsonPath = nodePath.resolve(\n process.cwd(),\n \"node_modules\",\n dep.name,\n \"package.json\",\n );\n searchPath = process.cwd();\n }\n\n try {\n const pkgJson = JSON.parse(nodeFs.readFileSync(pkgJsonPath, \"utf8\"));\n const deps = getTelegraphDepsFromPackageJson(pkgJson, searchPath);\n\n // Merge new dependencies into allDeps\n Object.assign(allDeps, deps);\n\n if (deps) {\n // Recursively get dependencies of dependencies\n const nestedDeps = recursivelyGetTelegraphDeps(deps);\n Object.assign(allDeps, nestedDeps);\n }\n } catch (err) {\n // Skip if package.json cannot be read\n continue;\n }\n }\n\n return allDeps;\n };\n\n if (topLevelDeps) {\n return recursivelyGetTelegraphDeps(topLevelDeps);\n }\n\n return {};\n}\n\ntype GetCssStylesParams = {\n fileName?: string;\n path: string;\n};\n\n/**\n * Reads CSS file content from a Telegraph package's dist/css directory.\n * Returns null if the file doesn't exist or can't be read.\n */\nfunction getCssStyles({\n fileName = \"default.css\",\n path,\n}: GetCssStylesParams): string | null {\n try {\n const cssPath = `${path}/dist/css/${fileName}`;\n const pkgPath = nodePath.resolve(cssPath);\n\n if (nodeFs.existsSync(pkgPath)) {\n return nodeFs.readFileSync(pkgPath, \"utf8\");\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\ntype BuildTelegraphCssParams = {\n root: Root;\n config: {\n tokens: Array<\"light\" | \"dark\" | \"default\">;\n components: boolean;\n };\n};\n\n/**\n * Main function that builds the final CSS by:\n * 1. Getting all Telegraph dependencies\n * 2. Filtering for either token packages or component packages based on config\n * 3. Reading their CSS files\n * 4. Appending all CSS to the PostCSS Root node\n */\nconst buildTelegraphCss = async ({ root, config }: BuildTelegraphCssParams) => {\n const deps = getTelegraphDeps();\n\n const depsWithoutTokens =\n config.components === true\n ? Object.values(deps).filter(\n (dep) => !dep.name.includes(\"@telegraph/tokens\"),\n )\n : [];\n\n const tokensDeps =\n config.tokens.length > 0\n ? Object.values(deps).filter((dep) =>\n dep.name.includes(\"@telegraph/tokens\"),\n )\n : [];\n\n const cssFiles = depsWithoutTokens\n .map((dep) => getCssStyles({ path: dep.path }))\n .filter(Boolean) as Array<string>;\n\n const tokensCssFiles = config.tokens\n .map((token) => {\n const cssFile = tokensDeps.map((dep) =>\n getCssStyles({ path: dep.path, fileName: `${token}.css` }),\n );\n\n return cssFile.filter(Boolean) as Array<string>;\n })\n .filter(Boolean);\n\n const allCssFiles = [...cssFiles, ...tokensCssFiles];\n\n for (const content of allCssFiles) {\n const parsed = postcss.parse(content);\n root.append(parsed);\n }\n};\n\n/**\n * PostCSS plugin that processes @telegraph rules in CSS files.\n * It looks for @telegraph tokens, @telegraph tokens-light, @telegraph tokens-dark,\n * and @telegraph components rules and includes the appropriate CSS from Telegraph packages.\n */\nconst styleEnginePostCssPlugin = (): AcceptedPlugin => {\n return {\n postcssPlugin: \"@telegraph/style-engine\",\n plugins: [\n {\n postcssPlugin: \"style-engine\",\n async Once(root) {\n const run = {\n tokens: [] as BuildTelegraphCssParams[\"config\"][\"tokens\"],\n components: false,\n };\n root.walkAtRules(\"telegraph\", (atRule) => {\n if (atRule.params === \"components\") {\n run.components = true;\n atRule.remove();\n }\n\n if (atRule.params === \"tokens-light\") {\n run.tokens.push(\"light\");\n atRule.remove();\n }\n\n if (atRule.params === \"tokens-dark\") {\n run.tokens.push(\"dark\");\n atRule.remove();\n }\n\n if (atRule.params === \"tokens\") {\n run.tokens.push(\"default\");\n atRule.remove();\n }\n });\n\n await buildTelegraphCss({\n root,\n config: {\n tokens: run.tokens,\n components: run.components,\n },\n });\n },\n },\n ],\n };\n};\n\nexport default Object.assign(styleEnginePostCssPlugin, {\n postcss: true,\n}) as PluginCreator<Record<string, never>>;\n"],"names":["nodePath","nodeFs","postcss","findMonorepoRoot","start","current","run","pkgJsonPath","parent","getTelegraphDepsFromPackageJson","pkg","pkgPath","_a","acc","dep","version","getTelegraphDeps","topLevelDeps","monorepoRoot","recursivelyGetTelegraphDeps","deps","allDeps","searchPath","pkgJson","nestedDeps","getCssStyles","fileName","path","cssPath","buildTelegraphCss","root","config","depsWithoutTokens","tokensDeps","cssFiles","tokensCssFiles","token","allCssFiles","content","parsed","styleEnginePostCssPlugin","atRule","postcss$1"],"mappings":"aAKA,MAAMA,EAAW,QAAQ,MAAM,EAEzBC,EAAS,QAAQ,IAAI,EAErBC,EAAU,QAAQ,SAAS,EAoBjC,SAASC,EAAiBC,EAAQ,QAAQ,MAAe,CACvD,IAAIC,EAAUD,EACVE,EAAM,GAEV,KAAOA,GAAK,CACV,MAAMC,EAAcP,EAAS,KAAKK,EAAS,cAAc,EACrD,GAAAJ,EAAO,WAAWM,CAAW,EAC3B,GAAA,CAEF,GADY,KAAK,MAAMN,EAAO,aAAaM,EAAa,MAAM,CAAC,EACvD,WACC,OAAAF,CACT,MACM,CAAA,CAKJ,MAAAG,EAASR,EAAS,QAAQK,CAAO,EACnCG,IAAWH,IAAeC,EAAA,IACpBD,EAAAG,CAAA,CAGZ,MAAM,IAAI,MACR,wEACF,CACF,CAMA,MAAMC,EAAkC,CACtCC,EACAC,IAC0B,OACtB,GAAA,GAACD,EAAI,gBAAgBE,EAAA,OAAO,KAAKF,EAAI,YAAY,IAA5B,YAAAE,EAA+B,UAAW,GAE5D,OAAA,OAAO,QAAQF,EAAI,YAAY,EAAE,OAAO,CAACG,EAAK,CAACC,EAAKC,CAAO,KAC5DD,EAAI,WAAW,aAAa,IAC9BD,EAAIC,CAAG,EAAI,CACT,KAAMA,EACN,QAAAC,EACA,KAAMf,EAAS,QAAQW,EAAS,eAAgBG,CAAG,CACrD,GAEKD,GACN,EAAe,CACpB,EAMA,SAASG,GAA8B,CACrC,MAAML,EAAUX,EAAS,QAAQ,QAAQ,MAAO,cAAc,EACxDU,EAAM,KAAK,MAAMT,EAAO,aAAaU,EAAS,MAAM,CAAC,EACrD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rD,QAAS,EACX,CAAC"}
@@ -0,0 +1,111 @@
1
+ const a = require("path"), l = require("fs"), m = require("postcss");
2
+ function y(n = process.cwd()) {
3
+ let e = n, s = !0;
4
+ for (; s; ) {
5
+ const t = a.join(e, "package.json");
6
+ if (l.existsSync(t))
7
+ try {
8
+ if (JSON.parse(l.readFileSync(t, "utf8")).workspaces)
9
+ return e;
10
+ } catch {
11
+ }
12
+ const r = a.dirname(e);
13
+ r === e && (s = !1), e = r;
14
+ }
15
+ throw new Error(
16
+ 'Could not find monorepo root (no package.json with "workspaces" found)'
17
+ );
18
+ }
19
+ const g = (n, e) => {
20
+ var s;
21
+ if (!(!n.dependencies || ((s = Object.keys(n.dependencies)) == null ? void 0 : s.length) === 0))
22
+ return Object.entries(n.dependencies).reduce((t, [r, c]) => (r.startsWith("@telegraph/") && (t[r] = {
23
+ name: r,
24
+ version: c,
25
+ path: a.resolve(e, "node_modules", r)
26
+ }), t), {});
27
+ };
28
+ function j() {
29
+ const n = a.resolve(process.cwd(), "package.json"), e = JSON.parse(l.readFileSync(n, "utf8")), s = g(e, process.cwd()), t = y(), r = (c) => {
30
+ if (!c || Object.keys(c).length === 0)
31
+ return c;
32
+ const i = { ...c };
33
+ for (const u of Object.values(c)) {
34
+ let o, p;
35
+ u.version.includes("workspace:") && t ? (o = a.resolve(
36
+ t,
37
+ "node_modules",
38
+ u.name,
39
+ "package.json"
40
+ ), p = t) : (o = a.resolve(
41
+ process.cwd(),
42
+ "node_modules",
43
+ u.name,
44
+ "package.json"
45
+ ), p = process.cwd());
46
+ try {
47
+ const d = JSON.parse(l.readFileSync(o, "utf8")), f = g(d, p);
48
+ if (Object.assign(i, f), f) {
49
+ const k = r(f);
50
+ Object.assign(i, k);
51
+ }
52
+ } catch {
53
+ continue;
54
+ }
55
+ }
56
+ return i;
57
+ };
58
+ return s ? r(s) : {};
59
+ }
60
+ function h({
61
+ fileName: n = "default.css",
62
+ path: e
63
+ }) {
64
+ try {
65
+ const s = `${e}/dist/css/${n}`, t = a.resolve(s);
66
+ return l.existsSync(t) ? l.readFileSync(t, "utf8") : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ const v = async ({ root: n, config: e }) => {
72
+ const s = j(), t = e.components === !0 ? Object.values(s).filter(
73
+ (o) => !o.name.includes("@telegraph/tokens")
74
+ ) : [], r = e.tokens.length > 0 ? Object.values(s).filter(
75
+ (o) => o.name.includes("@telegraph/tokens")
76
+ ) : [], c = t.map((o) => h({ path: o.path })).filter(Boolean), i = e.tokens.map((o) => r.map(
77
+ (d) => h({ path: d.path, fileName: `${o}.css` })
78
+ ).filter(Boolean)).filter(Boolean), u = [...c, ...i];
79
+ for (const o of u) {
80
+ const p = m.parse(o);
81
+ n.append(p);
82
+ }
83
+ }, w = () => ({
84
+ postcssPlugin: "@telegraph/style-engine",
85
+ plugins: [
86
+ {
87
+ postcssPlugin: "style-engine",
88
+ async Once(n) {
89
+ const e = {
90
+ tokens: [],
91
+ components: !1
92
+ };
93
+ n.walkAtRules("telegraph", (s) => {
94
+ s.params === "components" && (e.components = !0, s.remove()), s.params === "tokens-light" && (e.tokens.push("light"), s.remove()), s.params === "tokens-dark" && (e.tokens.push("dark"), s.remove()), s.params === "tokens" && (e.tokens.push("default"), s.remove());
95
+ }), await v({
96
+ root: n,
97
+ config: {
98
+ tokens: e.tokens,
99
+ components: e.components
100
+ }
101
+ });
102
+ }
103
+ }
104
+ ]
105
+ }), O = Object.assign(w, {
106
+ postcss: !0
107
+ });
108
+ export {
109
+ O as default
110
+ };
111
+ //# sourceMappingURL=postcss.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postcss.mjs","sources":["../../src/plugins/postcss.ts"],"sourcesContent":["import { type AcceptedPlugin, type PluginCreator, type Root } from \"postcss\";\n\n// Using require() instead of import to prevent ESM-related bugs in PostCSS.\n// ESM = ECMAScript Modules (the import/export syntax)\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst nodePath = require(\"path\");\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst nodeFs = require(\"fs\");\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst postcss = require(\"postcss\");\n\ntype PkgJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\ntype DepObject = Record<\n string,\n {\n name: string;\n version: string;\n path: string;\n }\n>;\n\n/**\n * Traverses up the directory tree to find the root of the monorepo by looking for a package.json with workspaces.\n * This is needed to properly resolve workspace dependencies in a monorepo setup.\n */\nfunction findMonorepoRoot(start = process.cwd()): string {\n let current = start;\n let run = true;\n\n while (run) {\n const pkgJsonPath = nodePath.join(current, \"package.json\");\n if (nodeFs.existsSync(pkgJsonPath)) {\n try {\n const pkg = JSON.parse(nodeFs.readFileSync(pkgJsonPath, \"utf8\"));\n if (pkg.workspaces) {\n return current;\n }\n } catch {\n // malformed package.json, skip\n }\n }\n\n const parent = nodePath.dirname(current);\n if (parent === current) run = false;\n current = parent;\n }\n\n throw new Error(\n 'Could not find monorepo root (no package.json with \"workspaces\" found)',\n );\n}\n\n/**\n * Extracts all @telegraph/* dependencies from a package.json file and returns them with their paths.\n * This is used to find all Telegraph packages that might contain CSS we need to include.\n */\nconst getTelegraphDepsFromPackageJson = (\n pkg: PkgJson,\n pkgPath: string,\n): DepObject | undefined => {\n if (!pkg.dependencies || Object.keys(pkg.dependencies)?.length === 0) return;\n\n return Object.entries(pkg.dependencies).reduce((acc, [dep, version]) => {\n if (dep.startsWith(\"@telegraph/\")) {\n acc[dep] = {\n name: dep,\n version,\n path: nodePath.resolve(pkgPath, \"node_modules\", dep),\n };\n }\n return acc;\n }, {} as DepObject);\n};\n\n/**\n * Gets all Telegraph dependencies recursively, including dependencies of dependencies.\n * Handles both normal npm dependencies and workspace dependencies in a monorepo.\n */\nfunction getTelegraphDeps(): DepObject {\n const pkgPath = nodePath.resolve(process.cwd(), \"package.json\");\n const pkg = JSON.parse(nodeFs.readFileSync(pkgPath, \"utf8\"));\n const topLevelDeps = getTelegraphDepsFromPackageJson(pkg, process.cwd());\n const monorepoRoot = findMonorepoRoot();\n\n const recursivelyGetTelegraphDeps = (deps: DepObject): DepObject => {\n if (!deps || Object.keys(deps).length === 0) {\n return deps;\n }\n\n const allDeps = { ...deps };\n\n for (const dep of Object.values(deps)) {\n let pkgJsonPath: string;\n let searchPath: string;\n\n if (dep.version.includes(\"workspace:\") && monorepoRoot) {\n pkgJsonPath = nodePath.resolve(\n monorepoRoot,\n \"node_modules\",\n dep.name,\n \"package.json\",\n );\n searchPath = monorepoRoot;\n } else {\n pkgJsonPath = nodePath.resolve(\n process.cwd(),\n \"node_modules\",\n dep.name,\n \"package.json\",\n );\n searchPath = process.cwd();\n }\n\n try {\n const pkgJson = JSON.parse(nodeFs.readFileSync(pkgJsonPath, \"utf8\"));\n const deps = getTelegraphDepsFromPackageJson(pkgJson, searchPath);\n\n // Merge new dependencies into allDeps\n Object.assign(allDeps, deps);\n\n if (deps) {\n // Recursively get dependencies of dependencies\n const nestedDeps = recursivelyGetTelegraphDeps(deps);\n Object.assign(allDeps, nestedDeps);\n }\n } catch (err) {\n // Skip if package.json cannot be read\n continue;\n }\n }\n\n return allDeps;\n };\n\n if (topLevelDeps) {\n return recursivelyGetTelegraphDeps(topLevelDeps);\n }\n\n return {};\n}\n\ntype GetCssStylesParams = {\n fileName?: string;\n path: string;\n};\n\n/**\n * Reads CSS file content from a Telegraph package's dist/css directory.\n * Returns null if the file doesn't exist or can't be read.\n */\nfunction getCssStyles({\n fileName = \"default.css\",\n path,\n}: GetCssStylesParams): string | null {\n try {\n const cssPath = `${path}/dist/css/${fileName}`;\n const pkgPath = nodePath.resolve(cssPath);\n\n if (nodeFs.existsSync(pkgPath)) {\n return nodeFs.readFileSync(pkgPath, \"utf8\");\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\ntype BuildTelegraphCssParams = {\n root: Root;\n config: {\n tokens: Array<\"light\" | \"dark\" | \"default\">;\n components: boolean;\n };\n};\n\n/**\n * Main function that builds the final CSS by:\n * 1. Getting all Telegraph dependencies\n * 2. Filtering for either token packages or component packages based on config\n * 3. Reading their CSS files\n * 4. Appending all CSS to the PostCSS Root node\n */\nconst buildTelegraphCss = async ({ root, config }: BuildTelegraphCssParams) => {\n const deps = getTelegraphDeps();\n\n const depsWithoutTokens =\n config.components === true\n ? Object.values(deps).filter(\n (dep) => !dep.name.includes(\"@telegraph/tokens\"),\n )\n : [];\n\n const tokensDeps =\n config.tokens.length > 0\n ? Object.values(deps).filter((dep) =>\n dep.name.includes(\"@telegraph/tokens\"),\n )\n : [];\n\n const cssFiles = depsWithoutTokens\n .map((dep) => getCssStyles({ path: dep.path }))\n .filter(Boolean) as Array<string>;\n\n const tokensCssFiles = config.tokens\n .map((token) => {\n const cssFile = tokensDeps.map((dep) =>\n getCssStyles({ path: dep.path, fileName: `${token}.css` }),\n );\n\n return cssFile.filter(Boolean) as Array<string>;\n })\n .filter(Boolean);\n\n const allCssFiles = [...cssFiles, ...tokensCssFiles];\n\n for (const content of allCssFiles) {\n const parsed = postcss.parse(content);\n root.append(parsed);\n }\n};\n\n/**\n * PostCSS plugin that processes @telegraph rules in CSS files.\n * It looks for @telegraph tokens, @telegraph tokens-light, @telegraph tokens-dark,\n * and @telegraph components rules and includes the appropriate CSS from Telegraph packages.\n */\nconst styleEnginePostCssPlugin = (): AcceptedPlugin => {\n return {\n postcssPlugin: \"@telegraph/style-engine\",\n plugins: [\n {\n postcssPlugin: \"style-engine\",\n async Once(root) {\n const run = {\n tokens: [] as BuildTelegraphCssParams[\"config\"][\"tokens\"],\n components: false,\n };\n root.walkAtRules(\"telegraph\", (atRule) => {\n if (atRule.params === \"components\") {\n run.components = true;\n atRule.remove();\n }\n\n if (atRule.params === \"tokens-light\") {\n run.tokens.push(\"light\");\n atRule.remove();\n }\n\n if (atRule.params === \"tokens-dark\") {\n run.tokens.push(\"dark\");\n atRule.remove();\n }\n\n if (atRule.params === \"tokens\") {\n run.tokens.push(\"default\");\n atRule.remove();\n }\n });\n\n await buildTelegraphCss({\n root,\n config: {\n tokens: run.tokens,\n components: run.components,\n },\n });\n },\n },\n ],\n };\n};\n\nexport default Object.assign(styleEnginePostCssPlugin, {\n postcss: true,\n}) as PluginCreator<Record<string, never>>;\n"],"names":["nodePath","nodeFs","postcss","findMonorepoRoot","start","current","run","pkgJsonPath","parent","getTelegraphDepsFromPackageJson","pkg","pkgPath","_a","acc","dep","version","getTelegraphDeps","topLevelDeps","monorepoRoot","recursivelyGetTelegraphDeps","deps","allDeps","searchPath","pkgJson","nestedDeps","getCssStyles","fileName","path","cssPath","buildTelegraphCss","root","config","depsWithoutTokens","tokensDeps","cssFiles","tokensCssFiles","token","allCssFiles","content","parsed","styleEnginePostCssPlugin","atRule","postcss$1"],"mappings":"AAKA,MAAMA,IAAW,QAAQ,MAAM,GAEzBC,IAAS,QAAQ,IAAI,GAErBC,IAAU,QAAQ,SAAS;AAoBjC,SAASC,EAAiBC,IAAQ,QAAQ,OAAe;AACvD,MAAIC,IAAUD,GACVE,IAAM;AAEV,SAAOA,KAAK;AACV,UAAMC,IAAcP,EAAS,KAAKK,GAAS,cAAc;AACrD,QAAAJ,EAAO,WAAWM,CAAW;AAC3B,UAAA;AAEF,YADY,KAAK,MAAMN,EAAO,aAAaM,GAAa,MAAM,CAAC,EACvD;AACC,iBAAAF;AAAA,MACT,QACM;AAAA,MAAA;AAKJ,UAAAG,IAASR,EAAS,QAAQK,CAAO;AACnC,IAAAG,MAAWH,MAAeC,IAAA,KACpBD,IAAAG;AAAA,EAAA;AAGZ,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;AAMA,MAAMC,IAAkC,CACtCC,GACAC,MAC0B;AA1D5B,MAAAC;AA2DM,MAAA,GAACF,EAAI,kBAAgBE,IAAA,OAAO,KAAKF,EAAI,YAAY,MAA5B,gBAAAE,EAA+B,YAAW;AAE5D,WAAA,OAAO,QAAQF,EAAI,YAAY,EAAE,OAAO,CAACG,GAAK,CAACC,GAAKC,CAAO,OAC5DD,EAAI,WAAW,aAAa,M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AA,UACV,QAAQ,CAAC;AAAA,UACT,YAAY;AAAA,QACd;AACK,QAAAwB,EAAA,YAAY,aAAa,CAACW,MAAW;AACpC,UAAAA,EAAO,WAAW,iBACpBnC,EAAI,aAAa,IACjBmC,EAAO,OAAO,IAGZA,EAAO,WAAW,mBAChBnC,EAAA,OAAO,KAAK,OAAO,GACvBmC,EAAO,OAAO,IAGZA,EAAO,WAAW,kBAChBnC,EAAA,OAAO,KAAK,MAAM,GACtBmC,EAAO,OAAO,IAGZA,EAAO,WAAW,aAChBnC,EAAA,OAAO,KAAK,SAAS,GACzBmC,EAAO,OAAO;AAAA,QAChB,CACD,GAED,MAAMZ,EAAkB;AAAA,UACtB,MAAAC;AAAA,UACA,QAAQ;AAAA,YACN,QAAQxB,EAAI;AAAA,YACZ,YAAYA,EAAI;AAAA,UAAA;AAAA,QAClB,CACD;AAAA,MAAA;AAAA,IACH;AAAA,EACF;AAEJ,IAGFoC,IAAe,OAAO,OAAOF,GAA0B;AAAA,EACrD,SAAS;AACX,CAAC;"}
@@ -0,0 +1,5 @@
1
+ import { PluginCreator } from 'postcss';
2
+
3
+ declare const _default: PluginCreator<Record<string, never>>;
4
+ export default _default;
5
+ //# sourceMappingURL=postcss.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postcss.d.ts","sourceRoot":"","sources":["../../../src/plugins/postcss.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,aAAa,EAAa,MAAM,SAAS,CAAC;wBAuRvE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAF1C,wBAE2C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telegraph/style-engine",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "A wrappar around vanilla extract to style telegraph",
5
5
  "repository": "https://github.com/knocklabs/telegraph/tree/main/packages/style-engine",
6
6
  "author": "@knocklabs",
@@ -15,6 +15,11 @@
15
15
  "types": "./dist/types/index.d.ts",
16
16
  "default": "./dist/css/default.css"
17
17
  },
18
+ "./postcss": {
19
+ "import": "./dist/esm/postcss.mjs",
20
+ "require": "./dist/cjs/postcss.js",
21
+ "types": "./dist/types/plugins/postcss.d.ts"
22
+ },
18
23
  "./default.css": "./dist/css/default.css"
19
24
  },
20
25
  "files": [
@@ -32,18 +37,23 @@
32
37
  "preview": "vite preview"
33
38
  },
34
39
  "dependencies": {
35
- "@telegraph/tokens": "^0.0.19",
40
+ "@telegraph/tokens": "^0.0.20",
36
41
  "@vanilla-extract/css": "^1.15.3",
37
42
  "@vanilla-extract/recipes": "^0.5.3",
38
- "@vanilla-extract/sprinkles": "^1.6.2"
43
+ "@vanilla-extract/sprinkles": "^1.6.2",
44
+ "postcss": "^8.5.3"
39
45
  },
40
46
  "devDependencies": {
41
47
  "@knocklabs/eslint-config": "^0.0.3",
42
48
  "@knocklabs/typescript-config": "^0.0.2",
43
49
  "@telegraph/prettier-config": "^0.0.7",
44
50
  "@telegraph/vite-config": "^0.0.14",
51
+ "@types/node": "^22.13.11",
52
+ "@types/postcss-import": "^14.0.3",
45
53
  "@types/react": "^18.3.18",
46
54
  "eslint": "^8.56.0",
55
+ "globby": "^14.1.0",
56
+ "lightningcss": "^1.29.3",
47
57
  "react": "^18.3.1",
48
58
  "react-dom": "^18.3.1",
49
59
  "typescript": "^5.7.3",