@salty-css/core 0.1.0-alpha.4 → 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/astro-component-5hrNTCJ5.js +4 -0
  2. package/astro-component-Dj3enX6K.cjs +4 -0
  3. package/bin/commands/build.d.ts +2 -0
  4. package/bin/commands/generate.d.ts +2 -0
  5. package/bin/commands/init.d.ts +2 -0
  6. package/bin/commands/update.d.ts +2 -0
  7. package/bin/commands/version.d.ts +2 -0
  8. package/bin/context.d.ts +19 -0
  9. package/bin/detection/css-file.d.ts +5 -0
  10. package/bin/frameworks/astro.d.ts +4 -0
  11. package/bin/frameworks/index.d.ts +13 -0
  12. package/bin/frameworks/react.d.ts +2 -0
  13. package/bin/frameworks/types.d.ts +25 -0
  14. package/bin/integrations/astro.d.ts +11 -0
  15. package/bin/integrations/eslint.d.ts +6 -0
  16. package/bin/integrations/index.d.ts +13 -0
  17. package/bin/integrations/next.d.ts +9 -0
  18. package/bin/integrations/types.d.ts +17 -0
  19. package/bin/integrations/vite.d.ts +8 -0
  20. package/bin/main.cjs +545 -332
  21. package/bin/main.d.ts +8 -0
  22. package/bin/main.js +545 -332
  23. package/bin/package-json.d.ts +21 -0
  24. package/bin/saltyrc.d.ts +30 -0
  25. package/bin/templates.d.ts +14 -0
  26. package/compiler/salty-compiler.cjs +1 -1
  27. package/compiler/salty-compiler.js +1 -1
  28. package/css/dynamic-styles.cjs +15 -0
  29. package/css/dynamic-styles.d.ts +10 -0
  30. package/css/dynamic-styles.js +15 -0
  31. package/css/index.cjs +3 -0
  32. package/css/index.d.ts +1 -0
  33. package/css/index.js +3 -0
  34. package/package.json +5 -1
  35. package/styled-file-BzmB9_Ez.cjs +12 -0
  36. package/{react-styled-file-U02jek-B.cjs → styled-file-CPd_rTW2.cjs} +2 -2
  37. package/{react-styled-file-B99mwk0w.js → styled-file-Cda3EeR6.js} +2 -2
  38. package/styled-file-DLcgYmGN.js +12 -0
  39. package/{react-vanilla-file-D9px70iK.js → vanilla-file-1kOqbCIM.js} +2 -2
  40. package/{react-vanilla-file-Bj6XC8GS.cjs → vanilla-file-r0fp2q_m.cjs} +2 -2
package/bin/main.cjs CHANGED
@@ -2,16 +2,45 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const commander = require("commander");
4
4
  const fs = require("fs");
5
- const promises = require("fs/promises");
6
- const path = require("path");
7
- const ejs = require("ejs");
8
- const pascalCase = require("../pascal-case-By_l58S-.cjs");
9
5
  const compiler_saltyCompiler = require("../compiler/salty-compiler.cjs");
6
+ const compiler_helpers = require("../compiler/helpers.cjs");
7
+ const shouldRestart = require("../should-restart-CQsyHls3.cjs");
8
+ const path = require("path");
9
+ const promises = require("fs/promises");
10
10
  const child_process = require("child_process");
11
11
  const ora = require("ora");
12
- const shouldRestart = require("../should-restart-CQsyHls3.cjs");
13
- const compiler_helpers = require("../compiler/helpers.cjs");
12
+ const pascalCase = require("../pascal-case-By_l58S-.cjs");
13
+ const ejs = require("ejs");
14
14
  var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
15
+ const defaultPackageJsonPath = path.join(process.cwd(), "package.json");
16
+ const readPackageJson = async (filePath = defaultPackageJsonPath) => {
17
+ const content = await promises.readFile(filePath, "utf-8").then(JSON.parse).catch(() => void 0);
18
+ if (!content) throw "Could not read package.json file!";
19
+ return content;
20
+ };
21
+ const updatePackageJson = async (content, filePath = defaultPackageJsonPath) => {
22
+ if (typeof content === "object") content = JSON.stringify(content, null, 2);
23
+ await promises.writeFile(filePath, content);
24
+ };
25
+ const readThisPackageJson = async () => {
26
+ const packageJsonPath = new URL("../package.json", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("bin/main.cjs", document.baseURI).href);
27
+ return readPackageJson(packageJsonPath);
28
+ };
29
+ const corePackages = {
30
+ core: (version) => `@salty-css/core@${version}`,
31
+ eslintConfigCore: (version) => `@salty-css/eslint-config-core@${version}`
32
+ };
33
+ const addPrepareScript = (pkg) => {
34
+ if (!pkg.scripts) pkg.scripts = {};
35
+ const current = pkg.scripts["prepare"];
36
+ if (current) {
37
+ if (current.includes("salty-css")) return { changed: false, pkg };
38
+ pkg.scripts["prepare"] = current + " && npx salty-css build";
39
+ } else {
40
+ pkg.scripts["prepare"] = "npx salty-css build";
41
+ }
42
+ return { changed: true, pkg };
43
+ };
15
44
  const execAsync = (command) => {
16
45
  return new Promise((resolve, reject) => {
17
46
  child_process.exec(command, (error) => {
@@ -40,365 +69,539 @@ async function formatWithPrettier(filePath) {
40
69
  compiler_saltyCompiler.logger.error(`Error formatting ${filePath} with Prettier:`, error);
41
70
  }
42
71
  }
43
- async function main() {
44
- const program = new commander.Command();
45
- program.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");
46
- const files = {
47
- // Core files
48
- "salty.config.ts": Promise.resolve().then(() => require("../salty.config-cqavVm2t.cjs")),
49
- "saltygen/index.css": Promise.resolve().then(() => require("../index-ByR0nfaf.cjs")),
50
- // React
51
- "react/react-styled-file.ts": Promise.resolve().then(() => require("../react-styled-file-U02jek-B.cjs")),
52
- "react/react-vanilla-file.ts": Promise.resolve().then(() => require("../react-vanilla-file-Bj6XC8GS.cjs"))
53
- };
54
- const readTemplate = async (fileName, options) => {
55
- const { default: file } = await files[fileName];
56
- const content = ejs.render(file, options);
57
- return { fileName, content };
58
- };
59
- const readRCFile = async () => {
60
- const rcPath = path.join(process.cwd(), ".saltyrc.json");
61
- const rcContent = await promises.readFile(rcPath, "utf-8").then(JSON.parse).catch(() => ({}));
62
- return rcContent;
63
- };
64
- const defaultPackageJsonPath = path.join(process.cwd(), "package.json");
65
- const readPackageJson = async (filePath = defaultPackageJsonPath) => {
66
- const packageJsonContent = await promises.readFile(filePath, "utf-8").then(JSON.parse).catch(() => void 0);
67
- if (!packageJsonContent) throw "Could not read package.json file!";
68
- return packageJsonContent;
69
- };
70
- const updatePackageJson = async (content, filePath = defaultPackageJsonPath) => {
71
- if (typeof content === "object") content = JSON.stringify(content, null, 2);
72
- await promises.writeFile(filePath, content);
73
- };
74
- const readThisPackageJson = async () => {
75
- const packageJsonPath = new URL("../package.json", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("bin/main.cjs", document.baseURI).href);
76
- return readPackageJson(packageJsonPath);
77
- };
78
- const getDefaultProject = async () => {
79
- const rcContent = await readRCFile();
80
- return rcContent.defaultProject;
81
- };
82
- const defaultProject = await getDefaultProject();
83
- const currentPackageJson = await readThisPackageJson();
84
- const packages = {
85
- core: `@salty-css/core@${currentPackageJson.version}`,
86
- react: `@salty-css/react@${currentPackageJson.version}`,
87
- eslintConfigCore: `@salty-css/eslint-config-core@${currentPackageJson.version}`,
88
- vite: `@salty-css/vite@${currentPackageJson.version}`,
89
- next: `@salty-css/next@${currentPackageJson.version}`
90
- };
91
- const resolveProjectDir = (dir) => {
92
- const dirName = dir === "." ? "" : dir;
93
- const rootDir = process.cwd();
94
- const projectDir = path.join(rootDir, dirName);
95
- return projectDir;
96
- };
97
- program.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>", "Project directory to initialize the project in.").option("--css-file <css-file>", "Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install", "Skip installing dependencies.").action(async function(_dir = ".") {
98
- const packageJson = await readPackageJson().catch(() => void 0);
99
- if (!packageJson) return compiler_saltyCompiler.logError("Salty CSS project must be initialized in a directory with a package.json file.");
100
- compiler_saltyCompiler.logger.info("Initializing a new Salty-CSS project!");
101
- const { dir = _dir, cssFile, skipInstall } = this.opts();
102
- if (!dir) return compiler_saltyCompiler.logError("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");
103
- if (!skipInstall) await npmInstall(packages.core, packages.react);
104
- const rootDir = process.cwd();
105
- const projectDir = resolveProjectDir(dir);
106
- const projectFiles = await Promise.all([readTemplate("salty.config.ts"), readTemplate("saltygen/index.css")]);
107
- const saltyCompiler = new compiler_saltyCompiler.SaltyCompiler(projectDir);
108
- await promises.mkdir(projectDir, { recursive: true });
109
- const writeFiles = projectFiles.map(async ({ fileName, content }) => {
110
- const filePath = path.join(projectDir, fileName);
111
- const existingContent = await promises.readFile(filePath, "utf-8").catch(() => void 0);
112
- if (existingContent !== void 0) {
113
- compiler_saltyCompiler.logger.debug("File already exists: " + filePath);
114
- return;
115
- }
116
- const additionalFolders = fileName.split("/").slice(0, -1).join("/");
117
- if (additionalFolders) await promises.mkdir(path.join(projectDir, additionalFolders), { recursive: true });
118
- compiler_saltyCompiler.logger.info("Creating file: " + filePath);
119
- await promises.writeFile(filePath, content);
120
- await formatWithPrettier(filePath);
121
- });
122
- await Promise.all(writeFiles);
123
- const relativeProjectPath = path.relative(rootDir, projectDir) || ".";
124
- const saltyrcPath = path.join(rootDir, ".saltyrc.json");
125
- const existingSaltyrc = await promises.readFile(saltyrcPath, "utf-8").catch(() => void 0);
126
- if (existingSaltyrc === void 0) {
127
- compiler_saltyCompiler.logger.info("Creating file: " + saltyrcPath);
128
- const rcContent = {
129
- $schema: "./node_modules/@salty-css/core/.saltyrc.schema.json",
130
- info: "This file is used to define projects and their configurations for Salty CSS cli. Do not delete, modify or add this file to .gitignore.",
131
- defaultProject: relativeProjectPath,
132
- projects: [
133
- {
134
- dir: relativeProjectPath,
135
- framework: "react"
136
- }
137
- ]
138
- };
139
- const content = JSON.stringify(rcContent, null, 2);
140
- await promises.writeFile(saltyrcPath, content);
141
- await formatWithPrettier(saltyrcPath);
142
- } else {
143
- const rcContent = JSON.parse(existingSaltyrc);
144
- const projects = (rcContent == null ? void 0 : rcContent.projects) || [];
145
- const projectIndex = projects.findIndex((p) => p.dir === relativeProjectPath);
146
- if (projectIndex === -1) {
147
- projects.push({ dir: relativeProjectPath, framework: "react" });
148
- rcContent.projects = [...projects];
149
- const content = JSON.stringify(rcContent, null, 2);
150
- if (content !== existingSaltyrc) {
151
- compiler_saltyCompiler.logger.info("Edit file: " + saltyrcPath);
152
- await promises.writeFile(saltyrcPath, content);
153
- await formatWithPrettier(saltyrcPath);
154
- }
155
- }
156
- }
157
- const gitIgnorePath = path.join(rootDir, ".gitignore");
158
- const gitIgnoreContent = await promises.readFile(gitIgnorePath, "utf-8").catch(() => void 0);
159
- if (gitIgnoreContent !== void 0) {
160
- const alreadyIgnoresSaltygen = gitIgnoreContent.includes("saltygen");
161
- if (!alreadyIgnoresSaltygen) {
162
- compiler_saltyCompiler.logger.info("Edit file: " + gitIgnorePath);
163
- await promises.writeFile(gitIgnorePath, gitIgnoreContent + "\n\n# Salty-CSS\nsaltygen\n");
164
- }
165
- }
166
- const cssFileFoldersToLookFor = ["src", "public", "assets", "styles", "css", "app"];
167
- const secondLevelFolders = ["styles", "css", "app", "pages"];
168
- const cssFilesToLookFor = ["index", "styles", "main", "app", "global", "globals"];
169
- const cssFileExtensions = [".css", ".scss", ".sass"];
170
- const getTargetCssFile = async () => {
171
- if (cssFile) return cssFile;
172
- for (const folder of cssFileFoldersToLookFor) {
173
- for (const file of cssFilesToLookFor) {
174
- for (const ext of cssFileExtensions) {
175
- const filePath = path.join(projectDir, folder, file + ext);
176
- const fileContent = await promises.readFile(filePath, "utf-8").catch(() => void 0);
177
- if (fileContent !== void 0) return path.relative(projectDir, filePath);
178
- for (const secondLevelFolder of secondLevelFolders) {
179
- const filePath2 = path.join(projectDir, folder, secondLevelFolder, file + ext);
180
- const fileContent2 = await promises.readFile(filePath2, "utf-8").catch(() => void 0);
181
- if (fileContent2 !== void 0) return path.relative(projectDir, filePath2);
182
- }
183
- }
184
- }
185
- }
186
- return void 0;
187
- };
188
- const targetCSSFile = await getTargetCssFile();
189
- if (targetCSSFile) {
190
- const cssFilePath = path.join(projectDir, targetCSSFile);
191
- const cssFileContent = await promises.readFile(cssFilePath, "utf-8").catch(() => void 0);
192
- if (cssFileContent !== void 0) {
193
- const alreadyImportsSaltygen = cssFileContent.includes("saltygen");
194
- if (!alreadyImportsSaltygen) {
195
- const cssFileFolder = path.join(cssFilePath, "..");
196
- const relativePath = path.relative(cssFileFolder, path.join(projectDir, "saltygen/index.css"));
197
- const importStatement = `@import '${relativePath}';`;
198
- compiler_saltyCompiler.logger.info("Adding global import statement to CSS file: " + cssFilePath);
199
- await promises.writeFile(cssFilePath, importStatement + "\n" + cssFileContent);
200
- await formatWithPrettier(cssFilePath);
201
- }
202
- }
203
- } else {
204
- compiler_saltyCompiler.logger.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");
205
- }
206
- const eslintConfigs = {
207
- projectJs: path.join(projectDir, "eslint.config.js"),
208
- rootJs: path.join(rootDir, "eslint.config.js"),
209
- projectMjs: path.join(projectDir, "eslint.config.mjs"),
210
- rootMjs: path.join(rootDir, "eslint.config.mjs"),
211
- projectJson: path.join(projectDir, ".eslintrc.json"),
212
- rootJson: path.join(rootDir, ".eslintrc.json")
72
+ const SALTYRC_FILENAME = ".saltyrc.json";
73
+ const SALTYRC_SCHEMA = "./node_modules/@salty-css/core/.saltyrc.schema.json";
74
+ const SALTYRC_INFO = "This file is used to define projects and their configurations for Salty CSS cli. Do not delete, modify or add this file to .gitignore.";
75
+ const saltyrcPath = (rootDir = process.cwd()) => path.join(rootDir, SALTYRC_FILENAME);
76
+ const readRc = async (rootDir = process.cwd()) => {
77
+ const content = await promises.readFile(saltyrcPath(rootDir), "utf-8").then(JSON.parse).catch(() => ({}));
78
+ return content;
79
+ };
80
+ const readRawRc = async (rootDir = process.cwd()) => {
81
+ return promises.readFile(saltyrcPath(rootDir), "utf-8").catch(() => void 0);
82
+ };
83
+ const getDefaultProject = async (rootDir = process.cwd()) => {
84
+ const rc = await readRc(rootDir);
85
+ return rc.defaultProject;
86
+ };
87
+ const upsertProjectInRc = (existingRaw, relativeProjectPath, framework) => {
88
+ if (existingRaw === void 0) {
89
+ const fresh = {
90
+ $schema: SALTYRC_SCHEMA,
91
+ info: SALTYRC_INFO,
92
+ defaultProject: relativeProjectPath,
93
+ projects: [{ dir: relativeProjectPath, framework }]
213
94
  };
214
- const eslintConfigToUse = Object.values(eslintConfigs).find((path2) => fs.existsSync(path2));
215
- if (eslintConfigToUse) {
216
- if (!skipInstall) await npmInstall(packages.eslintConfigCore);
217
- const eslintConfigContent = await promises.readFile(eslintConfigToUse, "utf-8").catch(() => void 0);
218
- if (!eslintConfigContent) return compiler_saltyCompiler.logError("Could not read ESLint config file.");
219
- const alreadyHasSaltyConfig = eslintConfigContent.includes("salty-css");
220
- if (!alreadyHasSaltyConfig) {
221
- compiler_saltyCompiler.logger.info("Edit file: " + eslintConfigToUse);
222
- if (eslintConfigToUse.endsWith("js")) {
223
- const importStatement = 'import saltyCss from "@salty-css/eslint-config-core/flat";';
224
- let newContent = `${importStatement}
225
- ${eslintConfigContent}`;
226
- const isTsEslint = eslintConfigContent.includes("typescript-eslint");
227
- if (isTsEslint) {
228
- if (newContent.includes(".config(")) newContent = newContent.replace(".config(", ".config(saltyCss,");
229
- else compiler_saltyCompiler.logger.warn("Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually.");
230
- } else {
231
- if (newContent.includes("export default [")) newContent = newContent.replace("export default [", "export default [ saltyCss,");
232
- else if (newContent.includes("eslintConfig = [")) newContent = newContent.replace("eslintConfig = [", "eslintConfig = [ saltyCss,");
233
- else compiler_saltyCompiler.logger.warn("Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually.");
234
- }
235
- await promises.writeFile(eslintConfigToUse, newContent);
236
- await formatWithPrettier(eslintConfigToUse);
237
- } else {
238
- const eslintConfigJson = JSON.parse(eslintConfigContent);
239
- if (!eslintConfigJson.extends) eslintConfigJson.extends = [];
240
- eslintConfigJson.extends.push("@salty-css/core");
241
- const modifiedEslintConfigContent = JSON.stringify(eslintConfigJson, null, 2);
242
- await promises.writeFile(eslintConfigToUse, modifiedEslintConfigContent);
243
- await formatWithPrettier(eslintConfigToUse);
244
- }
245
- }
246
- }
247
- const viteConfigPath = path.join(projectDir, "vite.config.ts");
248
- const viteConfigContent = await promises.readFile(viteConfigPath, "utf-8").catch(() => void 0);
249
- if (viteConfigContent !== void 0) {
250
- const alreadyHasPlugin = viteConfigContent.includes("saltyPlugin");
251
- if (!alreadyHasPlugin) {
252
- compiler_saltyCompiler.logger.info("Edit file: " + viteConfigPath);
253
- const pluginImport = "import { saltyPlugin } from '@salty-css/vite';\n";
254
- const pluginConfig = "saltyPlugin(__dirname),";
255
- const newContent = viteConfigContent.replace(/(plugins: \[)/, `$1
256
- ${pluginConfig}`);
257
- if (!skipInstall) await npmInstall(`-D ${packages.vite}`);
258
- compiler_saltyCompiler.logger.info("Adding Salty-CSS plugin to Vite config...");
259
- await promises.writeFile(viteConfigPath, pluginImport + newContent);
260
- await formatWithPrettier(viteConfigPath);
261
- }
262
- }
263
- const nextConfigFiles = ["next.config.js", "next.config.cjs", "next.config.ts", "next.config.mjs"];
264
- const nextConfigPath = nextConfigFiles.map((file) => path.join(projectDir, file)).find((path2) => fs.existsSync(path2));
265
- if (nextConfigPath) {
266
- let nextConfigContent = await promises.readFile(nextConfigPath, "utf-8").catch(() => void 0);
267
- if (nextConfigContent !== void 0) {
268
- const alreadyHasPlugin = nextConfigContent.includes("withSaltyCss");
269
- if (!alreadyHasPlugin) {
270
- let saltyCssAppended = false;
271
- const hasPluginsArray = /\splugins([^=]*)=[^[]\[/.test(nextConfigContent);
272
- if (hasPluginsArray && !saltyCssAppended) {
273
- nextConfigContent = nextConfigContent.replace(/\splugins([^=]*)=[^[]\[/, (_, config) => {
274
- return ` plugins${config}= [withSaltyCss,`;
275
- });
276
- saltyCssAppended = true;
277
- }
278
- const useRequire = nextConfigContent.includes("module.exports");
279
- const pluginImport = useRequire ? "const { withSaltyCss } = require('@salty-css/next');\n" : "import { withSaltyCss } from '@salty-css/next';\n";
280
- if (useRequire && !saltyCssAppended) {
281
- nextConfigContent = nextConfigContent.replace(/module.exports = ([^;]+)/, (_, config) => {
282
- return `module.exports = withSaltyCss(${config})`;
283
- });
284
- saltyCssAppended = true;
285
- } else if (!saltyCssAppended) {
286
- nextConfigContent = nextConfigContent.replace(/export default ([^;]+)/, (_, config) => {
287
- return `export default withSaltyCss(${config})`;
288
- });
289
- }
290
- if (!skipInstall) await npmInstall(`-D ${packages.next}`);
291
- compiler_saltyCompiler.logger.info("Adding Salty-CSS plugin to Next.js config...");
292
- await promises.writeFile(nextConfigPath, pluginImport + nextConfigContent);
293
- await formatWithPrettier(nextConfigPath);
294
- }
295
- }
296
- }
297
- const packageJsonContent = await readPackageJson().catch(() => compiler_saltyCompiler.logError("Could not read package.json file.")).then((content) => {
298
- if (!content.scripts) content.scripts = {};
299
- if (content.scripts.prepare) {
300
- const alreadyHasSaltyCss = content.scripts.prepare.includes("salty-css");
301
- if (!alreadyHasSaltyCss) {
302
- compiler_saltyCompiler.logger.info("Edit file: " + defaultPackageJsonPath);
303
- content.scripts.prepare = content.scripts.prepare + " && npx salty-css build";
304
- }
305
- } else {
306
- compiler_saltyCompiler.logger.info("Edit file: " + defaultPackageJsonPath);
307
- content.scripts.prepare = "npx salty-css build";
308
- }
309
- return content;
310
- });
311
- await updatePackageJson(packageJsonContent);
312
- compiler_saltyCompiler.logger.info("Running the build to generate initial CSS...");
313
- await saltyCompiler.generateCss();
314
- compiler_saltyCompiler.logger.info("🎉 Salty CSS project initialized successfully!");
315
- compiler_saltyCompiler.logger.info("Next steps:");
316
- compiler_saltyCompiler.logger.info("1. Configure variables and templates in `salty.config.ts`");
317
- compiler_saltyCompiler.logger.info("2. Create a new component with `npx salty-css generate [component-name]`");
318
- compiler_saltyCompiler.logger.info("3. Run `npx salty-css build` to generate the CSS");
319
- compiler_saltyCompiler.logger.info("4. Read about the features in the documentation: https://salty-css.dev");
320
- compiler_saltyCompiler.logger.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
321
- });
95
+ return { content: JSON.stringify(fresh, null, 2), changed: true, created: true };
96
+ }
97
+ const rc = JSON.parse(existingRaw);
98
+ const projects = rc.projects || [];
99
+ const exists = projects.some((p) => p.dir === relativeProjectPath);
100
+ if (exists) return { content: existingRaw, changed: false, created: false };
101
+ projects.push({ dir: relativeProjectPath, framework });
102
+ rc.projects = [...projects];
103
+ const next = JSON.stringify(rc, null, 2);
104
+ return { content: next, changed: next !== existingRaw, created: false };
105
+ };
106
+ const writeProjectToRc = async (rootDir, relativeProjectPath, framework) => {
107
+ const path2 = saltyrcPath(rootDir);
108
+ const existing = await readRawRc(rootDir);
109
+ const { content, changed, created } = upsertProjectInRc(existing, relativeProjectPath, framework);
110
+ if (!changed) return false;
111
+ if (created) compiler_saltyCompiler.logger.info("Creating file: " + path2);
112
+ else compiler_saltyCompiler.logger.info("Edit file: " + path2);
113
+ await promises.writeFile(path2, content);
114
+ await formatWithPrettier(path2);
115
+ return true;
116
+ };
117
+ const getProjectFramework = (rc, relativeProjectPath) => {
118
+ const projects = rc.projects || [];
119
+ const entry = projects.find((p) => p.dir === relativeProjectPath);
120
+ return entry == null ? void 0 : entry.framework;
121
+ };
122
+ const resolveProjectDir = (dir, rootDir = process.cwd()) => {
123
+ const dirName = dir === "." ? "" : dir;
124
+ return path.join(rootDir, dirName);
125
+ };
126
+ const buildContext = async (opts) => {
127
+ const rootDir = process.cwd();
128
+ const projectDir = resolveProjectDir(opts.dir, rootDir);
129
+ const relativeProjectPath = path.relative(rootDir, projectDir) || ".";
130
+ const packageJson = await readPackageJson().catch(() => void 0);
131
+ if (opts.requirePackageJson !== false && !packageJson) {
132
+ throw new Error("Salty CSS project must be initialized in a directory with a package.json file.");
133
+ }
134
+ const rcFile = await readRc(rootDir);
135
+ const cliPackageJson = await readThisPackageJson();
136
+ return {
137
+ rootDir,
138
+ projectDir,
139
+ relativeProjectPath,
140
+ packageJson,
141
+ rcFile,
142
+ cliVersion: cliPackageJson.version || "0.0.0",
143
+ skipInstall: !!opts.skipInstall
144
+ };
145
+ };
146
+ const registerBuildCommand = (program, defaultProject) => {
322
147
  program.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>", "Project directory to build the project in.").option("--watch", "Watch for changes and rebuild the project.").action(async function(_dir = defaultProject) {
323
148
  compiler_saltyCompiler.logger.info("Building the Salty-CSS project...");
324
149
  const { dir = _dir, watch } = this.opts();
325
- if (!dir) return compiler_saltyCompiler.logError("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");
326
- const projectDir = resolveProjectDir(dir);
327
- const saltyCompiler = new compiler_saltyCompiler.SaltyCompiler(projectDir);
328
- await saltyCompiler.generateCss();
150
+ const resolved = dir ?? await getDefaultProject();
151
+ if (!resolved) return compiler_saltyCompiler.logError("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");
152
+ const projectDir = resolveProjectDir(resolved);
153
+ const compiler = new compiler_saltyCompiler.SaltyCompiler(projectDir);
154
+ await compiler.generateCss();
329
155
  if (watch) {
330
156
  compiler_saltyCompiler.logger.info("Watching for changes in the project directory...");
331
- fs.watch(projectDir, { recursive: true }, async (event, filePath) => {
157
+ fs.watch(projectDir, { recursive: true }, async (_event, filePath) => {
332
158
  const shouldRestart$1 = await shouldRestart.checkShouldRestart(filePath);
333
159
  if (shouldRestart$1) {
334
- await saltyCompiler.generateCss(false);
335
- } else {
336
- const saltyFile = compiler_helpers.isSaltyFile(filePath);
337
- if (saltyFile) await saltyCompiler.generateFile(filePath);
160
+ await compiler.generateCss(false);
161
+ } else if (compiler_helpers.isSaltyFile(filePath)) {
162
+ await compiler.generateFile(filePath);
338
163
  }
339
164
  });
340
165
  }
341
166
  });
342
- program.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-r, --reactComponent", "Generate a React component as well.").action(async function(_file, _dir = defaultProject) {
167
+ };
168
+ const astroConfigFiles = ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.cjs"];
169
+ const findAstroConfig = (projectDir) => {
170
+ for (const name of astroConfigFiles) {
171
+ const path$1 = path.join(projectDir, name);
172
+ if (fs.existsSync(path$1)) return path$1;
173
+ }
174
+ return null;
175
+ };
176
+ const hasAstroDependency = (ctx) => {
177
+ const pkg = ctx.packageJson;
178
+ if (!pkg) return false;
179
+ const all = { ...pkg.dependencies, ...pkg.devDependencies };
180
+ return Object.prototype.hasOwnProperty.call(all, "astro");
181
+ };
182
+ const astroFramework = {
183
+ name: "astro",
184
+ detect: (ctx) => Boolean(findAstroConfig(ctx.projectDir)) || hasAstroDependency(ctx),
185
+ runtimePackage: (version) => `@salty-css/astro@${version}`,
186
+ templates: {
187
+ styled: "astro/styled-file.ts",
188
+ component: {
189
+ styled: "astro/styled-file.ts",
190
+ wrapper: "astro/component.astro",
191
+ wrapperExt: ".astro"
192
+ }
193
+ }
194
+ };
195
+ const reactFramework = {
196
+ name: "react",
197
+ detect: () => true,
198
+ // default fallback — evaluated last in the registry
199
+ runtimePackage: (version) => `@salty-css/react@${version}`,
200
+ templates: {
201
+ styled: "react/styled-file.ts",
202
+ component: {
203
+ styled: "react/styled-file.ts",
204
+ wrapper: "react/vanilla-file.ts",
205
+ wrapperExt: ".tsx"
206
+ }
207
+ }
208
+ };
209
+ const frameworkRegistry = [astroFramework, reactFramework];
210
+ const frameworksByName = {
211
+ astro: astroFramework,
212
+ react: reactFramework
213
+ };
214
+ const detectFramework = async (ctx) => {
215
+ for (const adapter of frameworkRegistry) {
216
+ if (await adapter.detect(ctx)) return adapter;
217
+ }
218
+ return reactFramework;
219
+ };
220
+ const getFramework = (name) => {
221
+ if (!name) return void 0;
222
+ return frameworksByName[name];
223
+ };
224
+ const templateLoaders = {
225
+ "salty.config.ts": () => Promise.resolve().then(() => require("../salty.config-cqavVm2t.cjs")),
226
+ "saltygen/index.css": () => Promise.resolve().then(() => require("../index-ByR0nfaf.cjs")),
227
+ "react/styled-file.ts": () => Promise.resolve().then(() => require("../styled-file-CPd_rTW2.cjs")),
228
+ "react/vanilla-file.ts": () => Promise.resolve().then(() => require("../vanilla-file-r0fp2q_m.cjs")),
229
+ "astro/styled-file.ts": () => Promise.resolve().then(() => require("../styled-file-BzmB9_Ez.cjs")),
230
+ "astro/component.astro": () => Promise.resolve().then(() => require("../astro-component-Dj3enX6K.cjs"))
231
+ };
232
+ const readTemplate = async (key, options) => {
233
+ const { default: file } = await templateLoaders[key]();
234
+ const content = ejs.render(file, options);
235
+ return { fileName: key, content };
236
+ };
237
+ const registerGenerateCommand = (program, defaultProject) => {
238
+ program.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-r, --reactComponent", "Generate a wrapper component file alongside the styled definition.").action(async function(_file, _dir = defaultProject) {
343
239
  const { file = _file, dir = _dir, tag, name, className, reactComponent = false } = this.opts();
344
240
  if (!file) return compiler_saltyCompiler.logError("File to generate must be provided. Add it as the first argument after generate command or use the --file option.");
345
241
  if (!dir) return compiler_saltyCompiler.logError("Project directory must be provided. Add it as the second argument after generate command or use the --dir option.");
346
- const projectDir = resolveProjectDir(dir);
242
+ let ctx;
243
+ try {
244
+ ctx = await buildContext({ dir, requirePackageJson: false });
245
+ } catch (err) {
246
+ return compiler_saltyCompiler.logError(err instanceof Error ? err.message : String(err));
247
+ }
248
+ const rcFramework = getFramework(getProjectFramework(ctx.rcFile, ctx.relativeProjectPath));
249
+ const framework = rcFramework ?? await detectFramework(ctx);
347
250
  const additionalFolders = file.split("/").slice(0, -1).join("/");
348
- if (additionalFolders) await promises.mkdir(path.join(projectDir, additionalFolders), { recursive: true });
349
- const filePath = path.join(projectDir, file);
251
+ if (additionalFolders) await promises.mkdir(path.join(ctx.projectDir, additionalFolders), { recursive: true });
252
+ const filePath = path.join(ctx.projectDir, file);
350
253
  const parsedFilePath = path.parse(filePath);
351
- if (!parsedFilePath.ext) {
352
- parsedFilePath.ext = ".ts";
353
- }
354
- if (!parsedFilePath.name.endsWith(".css")) {
355
- parsedFilePath.name = parsedFilePath.name + ".css";
356
- }
254
+ if (!parsedFilePath.ext) parsedFilePath.ext = ".ts";
255
+ if (!parsedFilePath.name.endsWith(".css")) parsedFilePath.name = parsedFilePath.name + ".css";
357
256
  parsedFilePath.base = parsedFilePath.name + parsedFilePath.ext;
358
257
  const formattedStyledFilePath = path.format(parsedFilePath);
359
258
  const alreadyExists = await promises.readFile(formattedStyledFilePath, "utf-8").catch(() => void 0);
360
259
  if (alreadyExists !== void 0) {
361
- compiler_saltyCompiler.logger.error("File already exists:", formattedStyledFilePath);
260
+ compiler_saltyCompiler.logger.error("File already exists: " + formattedStyledFilePath);
362
261
  return;
363
262
  }
364
263
  let styledComponentName = pascalCase.pascalCase(name || parsedFilePath.base.replace(/\.css\.\w+$/, ""));
365
264
  if (reactComponent) {
265
+ if (!framework.templates.component) {
266
+ return compiler_saltyCompiler.logError(`--reactComponent is not supported for the ${framework.name} framework.`);
267
+ }
366
268
  const componentName = styledComponentName + "Component";
367
269
  styledComponentName = styledComponentName + "Wrapper";
368
270
  const fileName = parsedFilePath.base.replace(/\.css\.\w+$/, "");
369
- const { content: reactContent } = await readTemplate("react/react-vanilla-file.ts", { tag, componentName, styledComponentName, className, fileName });
271
+ const { content: wrapperContent } = await readTemplate(framework.templates.component.wrapper, {
272
+ tag,
273
+ componentName,
274
+ styledComponentName,
275
+ className,
276
+ fileName
277
+ });
370
278
  parsedFilePath.name = fileName.replace(/\.css$/, "");
371
- parsedFilePath.ext = ".tsx";
279
+ parsedFilePath.ext = framework.templates.component.wrapperExt;
372
280
  parsedFilePath.base = parsedFilePath.name + parsedFilePath.ext;
373
- const formattedReactFilePath = path.format(parsedFilePath);
374
- compiler_saltyCompiler.logger.info("Generating a new file: " + formattedReactFilePath);
375
- await promises.writeFile(formattedReactFilePath, reactContent);
376
- await formatWithPrettier(formattedReactFilePath);
281
+ const formattedWrapperPath = path.format(parsedFilePath);
282
+ compiler_saltyCompiler.logger.info("Generating a new file: " + formattedWrapperPath);
283
+ await promises.writeFile(formattedWrapperPath, wrapperContent);
284
+ await formatWithPrettier(formattedWrapperPath);
377
285
  }
378
- const { content } = await readTemplate("react/react-styled-file.ts", { tag, name: styledComponentName, className });
286
+ const styledKey = reactComponent && framework.templates.component ? framework.templates.component.styled : framework.templates.styled;
287
+ const { content } = await readTemplate(styledKey, { tag, name: styledComponentName, className });
379
288
  compiler_saltyCompiler.logger.info("Generating a new file: " + formattedStyledFilePath);
380
289
  await promises.writeFile(formattedStyledFilePath, content);
381
290
  await formatWithPrettier(formattedStyledFilePath);
382
291
  });
383
- const getSaltyCssPackages = async () => {
384
- const packageJSONPath = path.join(process.cwd(), "package.json");
385
- const packageJson = await readPackageJson(packageJSONPath).catch((err) => compiler_saltyCompiler.logError(err));
386
- if (!packageJson) return compiler_saltyCompiler.logError("Could not read package.json file.");
387
- const allDependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
388
- const saltyCssPackages = Object.entries(allDependencies).filter(([name]) => name === "salty-css" || name.startsWith("@salty-css/"));
389
- if (!saltyCssPackages.length) {
390
- return compiler_saltyCompiler.logError(
391
- "No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: " + packageJSONPath
392
- );
292
+ };
293
+ const CSS_FILE_FOLDERS = ["src", "public", "assets", "styles", "css", "app"];
294
+ const CSS_SECOND_LEVEL_FOLDERS = ["styles", "css", "app", "pages"];
295
+ const CSS_FILE_NAMES = ["index", "styles", "main", "app", "global", "globals"];
296
+ const CSS_FILE_EXTENSIONS = [".css", ".scss", ".sass"];
297
+ const findGlobalCssFile = async (projectDir) => {
298
+ for (const folder of CSS_FILE_FOLDERS) {
299
+ for (const file of CSS_FILE_NAMES) {
300
+ for (const ext of CSS_FILE_EXTENSIONS) {
301
+ const filePath = path.join(projectDir, folder, file + ext);
302
+ const fileContent = await promises.readFile(filePath, "utf-8").catch(() => void 0);
303
+ if (fileContent !== void 0) return path.relative(projectDir, filePath);
304
+ for (const second of CSS_SECOND_LEVEL_FOLDERS) {
305
+ const nestedPath = path.join(projectDir, folder, second, file + ext);
306
+ const nestedContent = await promises.readFile(nestedPath, "utf-8").catch(() => void 0);
307
+ if (nestedContent !== void 0) return path.relative(projectDir, nestedPath);
308
+ }
309
+ }
393
310
  }
394
- return saltyCssPackages;
395
- };
311
+ }
312
+ return void 0;
313
+ };
314
+ const astroPackage = (version) => `@salty-css/astro@${version}`;
315
+ const SALTY_ASTRO_IMPORT = "import saltyIntegration from '@salty-css/astro/integration';\n";
316
+ const editAstroConfig = (existing) => {
317
+ if (existing.includes("@salty-css/astro")) return { content: null };
318
+ let next = existing;
319
+ let inserted = false;
320
+ if (/integrations\s*:\s*\[/.test(next)) {
321
+ next = next.replace(/integrations\s*:\s*\[/, (m) => `${m}saltyIntegration(),`);
322
+ inserted = true;
323
+ } else if (/defineConfig\s*\(\s*\{/.test(next)) {
324
+ next = next.replace(/defineConfig\s*\(\s*\{/, (m) => `${m}
325
+ integrations: [saltyIntegration()],`);
326
+ inserted = true;
327
+ }
328
+ if (!inserted) {
329
+ return {
330
+ content: null,
331
+ warning: "Could not find a place to add saltyIntegration() in the Astro config. Please add it manually."
332
+ };
333
+ }
334
+ return { content: SALTY_ASTRO_IMPORT + next };
335
+ };
336
+ const astroIntegration = {
337
+ name: "astro",
338
+ detect: (ctx) => findAstroConfig(ctx.projectDir),
339
+ apply: async (ctx, configPath) => {
340
+ const existing = await promises.readFile(configPath, "utf-8").catch(() => void 0);
341
+ if (existing === void 0) return { changed: false };
342
+ const result = editAstroConfig(existing);
343
+ if (result.warning) compiler_saltyCompiler.logger.warn(result.warning);
344
+ if (result.content === null) return { changed: false };
345
+ if (!ctx.skipInstall) await npmInstall(`-D ${astroPackage(ctx.cliVersion)}`);
346
+ compiler_saltyCompiler.logger.info("Adding Salty-CSS integration to Astro config: " + configPath);
347
+ await promises.writeFile(configPath, result.content);
348
+ await formatWithPrettier(configPath);
349
+ return { changed: true };
350
+ }
351
+ };
352
+ const ESLINT_CONFIG_CANDIDATES = [
353
+ // Project-local candidates first, then root-level.
354
+ ["projectJs", "eslint.config.js"],
355
+ ["rootJs", "eslint.config.js"],
356
+ ["projectMjs", "eslint.config.mjs"],
357
+ ["rootMjs", "eslint.config.mjs"],
358
+ ["projectJson", ".eslintrc.json"],
359
+ ["rootJson", ".eslintrc.json"]
360
+ ];
361
+ const eslintConfigCandidates = (projectDir, rootDir) => {
362
+ return ESLINT_CONFIG_CANDIDATES.map(([scope, name]) => {
363
+ const base = scope.startsWith("root") ? rootDir : projectDir;
364
+ return path.join(base, name);
365
+ });
366
+ };
367
+ const editEslintConfig = (existing, isJsFlat) => {
368
+ if (existing.includes("salty-css")) return { content: null };
369
+ if (isJsFlat) {
370
+ const importStatement = 'import saltyCss from "@salty-css/eslint-config-core/flat";';
371
+ let newContent = `${importStatement}
372
+ ${existing}`;
373
+ const isTsEslint = existing.includes("typescript-eslint");
374
+ if (isTsEslint) {
375
+ if (newContent.includes(".config(")) {
376
+ newContent = newContent.replace(".config(", ".config(saltyCss,");
377
+ } else {
378
+ return {
379
+ content: null,
380
+ warning: "Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually."
381
+ };
382
+ }
383
+ } else {
384
+ if (newContent.includes("export default [")) {
385
+ newContent = newContent.replace("export default [", "export default [ saltyCss,");
386
+ } else if (newContent.includes("eslintConfig = [")) {
387
+ newContent = newContent.replace("eslintConfig = [", "eslintConfig = [ saltyCss,");
388
+ } else {
389
+ return {
390
+ content: null,
391
+ warning: "Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually."
392
+ };
393
+ }
394
+ }
395
+ return { content: newContent };
396
+ }
397
+ const json = JSON.parse(existing);
398
+ if (!json.extends) json.extends = [];
399
+ if (!json.extends.includes("@salty-css/core")) json.extends.push("@salty-css/core");
400
+ return { content: JSON.stringify(json, null, 2) };
401
+ };
402
+ const eslintIntegration = {
403
+ name: "eslint",
404
+ detect: (ctx) => {
405
+ const candidates = eslintConfigCandidates(ctx.projectDir, ctx.rootDir);
406
+ return candidates.find((p) => fs.existsSync(p)) ?? null;
407
+ },
408
+ apply: async (ctx, configPath) => {
409
+ const existing = await promises.readFile(configPath, "utf-8").catch(() => void 0);
410
+ if (existing === void 0) {
411
+ compiler_saltyCompiler.logger.error("Could not read ESLint config file.");
412
+ return { changed: false };
413
+ }
414
+ if (!ctx.skipInstall) await npmInstall(corePackages.eslintConfigCore(ctx.cliVersion));
415
+ const result = editEslintConfig(existing, configPath.endsWith("js"));
416
+ if (result.warning) compiler_saltyCompiler.logger.warn(result.warning);
417
+ if (result.content === null) return { changed: false };
418
+ compiler_saltyCompiler.logger.info("Edit file: " + configPath);
419
+ await promises.writeFile(configPath, result.content);
420
+ await formatWithPrettier(configPath);
421
+ return { changed: true };
422
+ }
423
+ };
424
+ const nextConfigFiles = ["next.config.js", "next.config.cjs", "next.config.ts", "next.config.mjs"];
425
+ const nextPackage = (version) => `@salty-css/next@${version}`;
426
+ const editNextConfig = (existing) => {
427
+ if (existing.includes("withSaltyCss")) return { content: null };
428
+ let next = existing;
429
+ let saltyCssAppended = false;
430
+ const hasPluginsArray = /\splugins([^=]*)=[^[]\[/.test(next);
431
+ if (hasPluginsArray) {
432
+ next = next.replace(/\splugins([^=]*)=[^[]\[/, (_, config) => ` plugins${config}= [withSaltyCss,`);
433
+ saltyCssAppended = true;
434
+ }
435
+ const useRequire = next.includes("module.exports");
436
+ const pluginImport = useRequire ? "const { withSaltyCss } = require('@salty-css/next');\n" : "import { withSaltyCss } from '@salty-css/next';\n";
437
+ if (useRequire && !saltyCssAppended) {
438
+ next = next.replace(/module.exports = ([^;]+)/, (_, config) => `module.exports = withSaltyCss(${config})`);
439
+ saltyCssAppended = true;
440
+ } else if (!saltyCssAppended) {
441
+ next = next.replace(/export default ([^;]+)/, (_, config) => `export default withSaltyCss(${config})`);
442
+ }
443
+ return { content: pluginImport + next };
444
+ };
445
+ const nextIntegration = {
446
+ name: "next",
447
+ detect: (ctx) => {
448
+ const found = nextConfigFiles.map((file) => path.join(ctx.projectDir, file)).find((p) => fs.existsSync(p));
449
+ return found ?? null;
450
+ },
451
+ apply: async (ctx, configPath) => {
452
+ const existing = await promises.readFile(configPath, "utf-8").catch(() => void 0);
453
+ if (existing === void 0) return { changed: false };
454
+ const { content } = editNextConfig(existing);
455
+ if (content === null) return { changed: false };
456
+ if (!ctx.skipInstall) await npmInstall(`-D ${nextPackage(ctx.cliVersion)}`);
457
+ compiler_saltyCompiler.logger.info("Adding Salty-CSS plugin to Next.js config...");
458
+ await promises.writeFile(configPath, content);
459
+ await formatWithPrettier(configPath);
460
+ return { changed: true };
461
+ }
462
+ };
463
+ const vitePackage = (version) => `@salty-css/vite@${version}`;
464
+ const editViteConfig = (existing) => {
465
+ if (existing.includes("saltyPlugin")) return { content: null };
466
+ const pluginImport = "import { saltyPlugin } from '@salty-css/vite';\n";
467
+ const pluginConfig = "saltyPlugin(__dirname),";
468
+ const withPlugin = existing.replace(/(plugins: \[)/, `$1
469
+ ${pluginConfig}`);
470
+ return { content: pluginImport + withPlugin };
471
+ };
472
+ const viteIntegration = {
473
+ name: "vite",
474
+ detect: (ctx) => {
475
+ const path$1 = path.join(ctx.projectDir, "vite.config.ts");
476
+ return fs.existsSync(path$1) ? path$1 : null;
477
+ },
478
+ apply: async (ctx, configPath) => {
479
+ const existing = await promises.readFile(configPath, "utf-8").catch(() => void 0);
480
+ if (existing === void 0) return { changed: false };
481
+ const { content } = editViteConfig(existing);
482
+ if (content === null) return { changed: false };
483
+ compiler_saltyCompiler.logger.info("Edit file: " + configPath);
484
+ if (!ctx.skipInstall) await npmInstall(`-D ${vitePackage(ctx.cliVersion)}`);
485
+ compiler_saltyCompiler.logger.info("Adding Salty-CSS plugin to Vite config...");
486
+ await promises.writeFile(configPath, content);
487
+ await formatWithPrettier(configPath);
488
+ return { changed: true };
489
+ }
490
+ };
491
+ const buildIntegrationRegistry = [eslintIntegration, viteIntegration, nextIntegration, astroIntegration];
492
+ const detectAndApplyIntegrations = async (ctx) => {
493
+ const results = [];
494
+ for (const integration of buildIntegrationRegistry) {
495
+ const configPath = await integration.detect(ctx);
496
+ if (!configPath) continue;
497
+ const result = await integration.apply(ctx, configPath);
498
+ results.push({ name: integration.name, configPath, changed: result.changed });
499
+ }
500
+ return results;
501
+ };
502
+ const writeProjectFile = async (projectDir, fileName, content) => {
503
+ const filePath = path.join(projectDir, fileName);
504
+ if (fs.existsSync(filePath)) {
505
+ compiler_saltyCompiler.logger.debug("File already exists: " + filePath);
506
+ return;
507
+ }
508
+ const additionalFolders = fileName.split("/").slice(0, -1).join("/");
509
+ if (additionalFolders) await promises.mkdir(path.join(projectDir, additionalFolders), { recursive: true });
510
+ compiler_saltyCompiler.logger.info("Creating file: " + filePath);
511
+ await promises.writeFile(filePath, content);
512
+ await formatWithPrettier(filePath);
513
+ };
514
+ const ensureGitignoreSaltygen = async (rootDir) => {
515
+ const path$1 = path.join(rootDir, ".gitignore");
516
+ const existing = await promises.readFile(path$1, "utf-8").catch(() => void 0);
517
+ if (existing === void 0) return;
518
+ if (existing.includes("saltygen")) return;
519
+ compiler_saltyCompiler.logger.info("Edit file: " + path$1);
520
+ await promises.writeFile(path$1, existing + "\n\n# Salty-CSS\nsaltygen\n");
521
+ };
522
+ const importSaltygenIntoCss = async (projectDir, explicitCssFile) => {
523
+ const target = explicitCssFile ?? await findGlobalCssFile(projectDir);
524
+ if (!target) {
525
+ compiler_saltyCompiler.logger.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");
526
+ return;
527
+ }
528
+ const cssFilePath = path.join(projectDir, target);
529
+ const cssFileContent = await promises.readFile(cssFilePath, "utf-8").catch(() => void 0);
530
+ if (cssFileContent === void 0) return;
531
+ if (cssFileContent.includes("saltygen")) return;
532
+ const cssFileFolder = path.join(cssFilePath, "..");
533
+ const relPath = path.relative(cssFileFolder, path.join(projectDir, "saltygen/index.css"));
534
+ compiler_saltyCompiler.logger.info("Adding global import statement to CSS file: " + cssFilePath);
535
+ await promises.writeFile(cssFilePath, `@import '${relPath}';
536
+ ` + cssFileContent);
537
+ await formatWithPrettier(cssFilePath);
538
+ };
539
+ const wirePrepareScript = async () => {
540
+ const pkg = await readPackageJson().catch(() => {
541
+ compiler_saltyCompiler.logError("Could not read package.json file.");
542
+ return void 0;
543
+ });
544
+ if (!pkg) return;
545
+ const { pkg: next } = addPrepareScript(pkg);
546
+ await updatePackageJson(next);
547
+ };
548
+ const registerInitCommand = (program) => {
549
+ program.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>", "Project directory to initialize the project in.").option("--css-file <css-file>", "Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install", "Skip installing dependencies.").action(async function(_dir = ".") {
550
+ try {
551
+ const opts = this.opts();
552
+ const dir = opts.dir ?? _dir;
553
+ if (!dir) return compiler_saltyCompiler.logError("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");
554
+ const ctx = await buildContext({ dir, skipInstall: opts.skipInstall });
555
+ compiler_saltyCompiler.logger.info("Initializing a new Salty-CSS project!");
556
+ const framework = await detectFramework(ctx);
557
+ compiler_saltyCompiler.logger.info(`Detected framework: ${framework.name}`);
558
+ if (!ctx.skipInstall) {
559
+ await npmInstall(corePackages.core(ctx.cliVersion), framework.runtimePackage(ctx.cliVersion));
560
+ }
561
+ const projectFiles = await Promise.all([readTemplate("salty.config.ts"), readTemplate("saltygen/index.css")]);
562
+ await promises.mkdir(ctx.projectDir, { recursive: true });
563
+ await Promise.all(projectFiles.map(({ fileName, content }) => writeProjectFile(ctx.projectDir, fileName, content)));
564
+ await writeProjectToRc(ctx.rootDir, ctx.relativeProjectPath, framework.name);
565
+ await ensureGitignoreSaltygen(ctx.rootDir);
566
+ await importSaltygenIntoCss(ctx.projectDir, opts.cssFile);
567
+ await detectAndApplyIntegrations(ctx);
568
+ await wirePrepareScript();
569
+ compiler_saltyCompiler.logger.info("Running the build to generate initial CSS...");
570
+ const compiler = new compiler_saltyCompiler.SaltyCompiler(ctx.projectDir);
571
+ await compiler.generateCss();
572
+ compiler_saltyCompiler.logger.info("🎉 Salty CSS project initialized successfully!");
573
+ compiler_saltyCompiler.logger.info("Next steps:");
574
+ compiler_saltyCompiler.logger.info("1. Configure variables and templates in `salty.config.ts`");
575
+ compiler_saltyCompiler.logger.info("2. Create a new component with `npx salty-css generate [component-name]`");
576
+ compiler_saltyCompiler.logger.info("3. Run `npx salty-css build` to generate the CSS");
577
+ compiler_saltyCompiler.logger.info("4. Read about the features in the documentation: https://salty-css.dev");
578
+ compiler_saltyCompiler.logger.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
579
+ } catch (err) {
580
+ return compiler_saltyCompiler.logError(err instanceof Error ? err.message : String(err));
581
+ }
582
+ });
583
+ };
584
+ const getSaltyCssPackages = async () => {
585
+ const packageJSONPath = path.join(process.cwd(), "package.json");
586
+ const packageJson = await readPackageJson(packageJSONPath).catch((err) => compiler_saltyCompiler.logError(err));
587
+ if (!packageJson) return compiler_saltyCompiler.logError("Could not read package.json file.");
588
+ const allDependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
589
+ const saltyCssPackages = Object.entries(allDependencies).filter(([name]) => name === "salty-css" || name.startsWith("@salty-css/"));
590
+ if (!saltyCssPackages.length) {
591
+ return compiler_saltyCompiler.logError(
592
+ "No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: " + packageJSONPath
593
+ );
594
+ }
595
+ return saltyCssPackages;
596
+ };
597
+ const registerUpdateCommand = (program) => {
396
598
  program.command("update [version]").alias("up").description("Update Salty-CSS packages to the latest or specified version.").option("-v, --version <version>", "Version to update to.").option("--legacy-peer-deps <legacyPeerDeps>", "Use legacy peer dependencies (not recommended).", false).action(async function(_version = "latest") {
397
599
  const { legacyPeerDeps, version = _version } = this.opts();
398
600
  const saltyCssPackages = await getSaltyCssPackages();
399
601
  if (!saltyCssPackages) return compiler_saltyCompiler.logError("Could not update Salty-CSS packages as any were found in package.json.");
602
+ const cli = await readThisPackageJson();
400
603
  const packagesToUpdate = saltyCssPackages.map(([name]) => {
401
- if (version === "@") return `${name}@${currentPackageJson.version}`;
604
+ if (version === "@") return `${name}@${cli.version}`;
402
605
  return `${name}@${version.replace(/^@/, "")}`;
403
606
  });
404
607
  if (legacyPeerDeps) {
@@ -416,19 +619,19 @@ ${eslintConfigContent}`;
416
619
  }, {});
417
620
  const versionsCount = Object.keys(mappedByVersions).length;
418
621
  if (versionsCount === 1) {
419
- const version2 = Object.keys(mappedByVersions)[0];
420
- const versionString = version2.replace(/^\^/, "");
421
- compiler_saltyCompiler.logger.info(`Updated to all Salty CSS packages successfully to ${versionString}`);
622
+ const v = Object.keys(mappedByVersions)[0];
623
+ compiler_saltyCompiler.logger.info(`Updated to all Salty CSS packages successfully to ${v.replace(/^\^/, "")}`);
422
624
  } else {
423
- for (const [version2, names] of Object.entries(mappedByVersions)) {
424
- const versionString = version2.replace(/^\^/, "");
425
- compiler_saltyCompiler.logger.info(`Updated to ${versionString}: ${names.join(", ")}`);
625
+ for (const [v, names] of Object.entries(mappedByVersions)) {
626
+ compiler_saltyCompiler.logger.info(`Updated to ${v.replace(/^\^/, "")}: ${names.join(", ")}`);
426
627
  }
427
628
  }
428
629
  });
630
+ };
631
+ const registerVersionOption = (program) => {
429
632
  program.option("-v, --version", "Show the current version of Salty-CSS.").action(async function() {
430
- const currentPackageJson2 = await readThisPackageJson();
431
- compiler_saltyCompiler.logger.info("CLI is running: " + currentPackageJson2.version);
633
+ const cli = await readThisPackageJson();
634
+ compiler_saltyCompiler.logger.info("CLI is running: " + cli.version);
432
635
  const packageJSONPath = path.join(process.cwd(), "package.json");
433
636
  const packageJson = await readPackageJson(packageJSONPath).catch((err) => compiler_saltyCompiler.logError(err));
434
637
  if (!packageJson) return;
@@ -443,6 +646,16 @@ ${eslintConfigContent}`;
443
646
  compiler_saltyCompiler.logger.info(`${dep}: ${allDependencies[dep]}`);
444
647
  }
445
648
  });
649
+ };
650
+ async function main() {
651
+ const program = new commander.Command();
652
+ program.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");
653
+ const defaultProject = await getDefaultProject();
654
+ registerInitCommand(program);
655
+ registerBuildCommand(program, defaultProject);
656
+ registerGenerateCommand(program, defaultProject);
657
+ registerUpdateCommand(program);
658
+ registerVersionOption(program);
446
659
  program.parseAsync(process.argv);
447
660
  }
448
661
  exports.main = main;