@whoj/eslint-config 2.4.1 → 7.4.30

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/bin/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli.mjs';
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/cli.mjs ADDED
@@ -0,0 +1,444 @@
1
+ import process from "node:process";
2
+ import fs from "node:fs/promises";
3
+ import fs$1 from "node:fs";
4
+ import path from "node:path";
5
+ import c, { green } from "ansis";
6
+ import { cac } from "cac";
7
+ import * as p from "@clack/prompts";
8
+ import { execSync } from "node:child_process";
9
+ import parse from "parse-gitignore";
10
+ import { deepMerge } from "@whoj/utils-core";
11
+ import { XMLBuilder, XMLParser } from "fast-xml-parser";
12
+
13
+ //#region src/cli/utils.ts
14
+ function isGitClean() {
15
+ try {
16
+ execSync("git diff-index --quiet HEAD --");
17
+ return true;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+ function getEslintConfigContent(mainConfig, additionalConfigs) {
23
+ return `
24
+ import whoj from '@whoj/eslint-config'
25
+
26
+ export default whoj({
27
+ ${mainConfig}
28
+ }${additionalConfigs?.map((config) => `,{\n${config}\n}`)})
29
+ `.trimStart();
30
+ }
31
+ function getJetbrainsEslintConfigContent(configFrom) {
32
+ return `
33
+ import whoj from "${configFrom}"
34
+
35
+ export default whoj.clone().overrides({
36
+ 'whoj/javascript/rules': {
37
+ rules: {
38
+ 'prefer-const': 'warn',
39
+ 'unused-imports/no-unused-imports': 'warn',
40
+ },
41
+ },
42
+ 'whoj/test/rules': {
43
+ rules: {
44
+ 'test/no-only-tests': 'warn',
45
+ 'test/consistent-test-it': ['error', { fn: 'it', withinDescribe: 'it' }],
46
+ },
47
+ },
48
+ }).disableRulesFix([
49
+ 'unused-imports/no-unused-imports',
50
+ 'test/no-only-tests',
51
+ 'prefer-const',
52
+ ], {
53
+ builtinRules: () => import(['eslint', 'use-at-your-own-risk'].join('/')).then(r => r.builtinRules),
54
+ })
55
+ `.trimStart();
56
+ }
57
+
58
+ //#endregion
59
+ //#region src/cli/stages/update-eslint-files.ts
60
+ async function updateEslintFiles(result) {
61
+ const cwd = process.cwd();
62
+ const pathESLintIgnore = path.join(cwd, ".eslintignore");
63
+ const pathPackageJSON = path.join(cwd, "package.json");
64
+ const pkgContent = await fs.readFile(pathPackageJSON, "utf-8");
65
+ const configFileName = JSON.parse(pkgContent).type === "module" ? "eslint.config.js" : "eslint.config.mjs";
66
+ const pathFlatConfig = path.join(cwd, configFileName);
67
+ const eslintIgnores = [];
68
+ if (fs$1.existsSync(pathESLintIgnore)) {
69
+ p.log.step(c.cyan`Migrating existing .eslintignore`);
70
+ const globs = parse(await fs.readFile(pathESLintIgnore, "utf-8")).globs();
71
+ for (const glob of globs) if (glob.type === "ignore") eslintIgnores.push(...glob.patterns);
72
+ else if (glob.type === "unignore") eslintIgnores.push(...glob.patterns.map((pattern) => `!${pattern}`));
73
+ }
74
+ const configLines = [];
75
+ if (eslintIgnores.length) configLines.push(`ignores: ${JSON.stringify(eslintIgnores)},`);
76
+ if (result.extra.includes("formatter")) configLines.push("formatters: true,");
77
+ if (result.extra.includes("unocss")) configLines.push("unocss: true,");
78
+ for (const framework of result.frameworks) configLines.push(`${framework}: true,`);
79
+ const eslintConfigContent = getEslintConfigContent(configLines.map((i) => ` ${i}`).join("\n"), []);
80
+ await fs.writeFile(pathFlatConfig, eslintConfigContent);
81
+ p.log.success(c.green`Created ${configFileName}`);
82
+ const files = fs$1.readdirSync(cwd);
83
+ const legacyConfig = [];
84
+ files.forEach((file) => {
85
+ if (/eslint|prettier/.test(file) && !/eslint\.config\./.test(file)) legacyConfig.push(file);
86
+ });
87
+ if (legacyConfig.length) p.note(c.dim(legacyConfig.join(", ")), "You can now remove those files manually");
88
+ return configFileName;
89
+ }
90
+
91
+ //#endregion
92
+ //#region src/cli/constants.ts
93
+ const vscodeSettingsString = `
94
+ // Disable the default formatter, use eslint instead
95
+ "prettier.enable": false,
96
+ "editor.formatOnSave": false,
97
+
98
+ // Auto fix
99
+ "editor.codeActionsOnSave": {
100
+ "source.fixAll.eslint": "explicit",
101
+ "source.organizeImports": "never"
102
+ },
103
+
104
+ // Silent the stylistic rules in your IDE, but still auto fix them
105
+ "eslint.rules.customizations": [
106
+ { "rule": "style/*", "severity": "off", "fixable": true },
107
+ { "rule": "format/*", "severity": "off", "fixable": true },
108
+ { "rule": "*-indent", "severity": "off", "fixable": true },
109
+ { "rule": "*-spacing", "severity": "off", "fixable": true },
110
+ { "rule": "*-spaces", "severity": "off", "fixable": true },
111
+ { "rule": "*-order", "severity": "off", "fixable": true },
112
+ { "rule": "*-dangle", "severity": "off", "fixable": true },
113
+ { "rule": "*-newline", "severity": "off", "fixable": true },
114
+ { "rule": "*quotes", "severity": "off", "fixable": true },
115
+ { "rule": "*semi", "severity": "off", "fixable": true }
116
+ ],
117
+
118
+ // Enable eslint for all supported languages
119
+ "eslint.validate": [
120
+ "javascript",
121
+ "javascriptreact",
122
+ "typescript",
123
+ "typescriptreact",
124
+ "vue",
125
+ "html",
126
+ "markdown",
127
+ "json",
128
+ "json5",
129
+ "jsonc",
130
+ "yaml",
131
+ "toml",
132
+ "xml",
133
+ "gql",
134
+ "graphql",
135
+ "astro",
136
+ "svelte",
137
+ "css",
138
+ "less",
139
+ "scss",
140
+ "pcss",
141
+ "postcss"
142
+ ]
143
+ `;
144
+ const frameworkOptions = [
145
+ {
146
+ value: "vue",
147
+ label: c.green("Vue")
148
+ },
149
+ {
150
+ value: "react",
151
+ label: c.cyan("React")
152
+ },
153
+ {
154
+ value: "svelte",
155
+ label: c.red("Svelte")
156
+ },
157
+ {
158
+ value: "astro",
159
+ label: c.magenta("Astro")
160
+ },
161
+ {
162
+ value: "solid",
163
+ label: c.cyan("Solid")
164
+ },
165
+ {
166
+ value: "slidev",
167
+ label: c.blue("Slidev")
168
+ }
169
+ ];
170
+ const frameworks = frameworkOptions.map(({ value }) => value);
171
+ const extraOptions = [{
172
+ value: "formatter",
173
+ label: c.red("Formatter"),
174
+ hint: "Use external formatters (Prettier and/or dprint) to format files that ESLint cannot handle yet (.css, .html, etc)"
175
+ }, {
176
+ value: "unocss",
177
+ label: c.cyan("UnoCSS")
178
+ }];
179
+ const extra = extraOptions.map(({ value }) => value);
180
+ const dependenciesMap = {
181
+ vue: [],
182
+ solid: ["eslint-plugin-solid"],
183
+ unocss: ["@unocss/eslint-plugin"],
184
+ slidev: ["prettier-plugin-slidev"],
185
+ formatter: ["eslint-plugin-format"],
186
+ nextjs: ["@next/eslint-plugin-next"],
187
+ formatterAstro: ["prettier-plugin-astro"],
188
+ astro: ["eslint-plugin-astro", "astro-eslint-parser"],
189
+ svelte: ["eslint-plugin-svelte", "svelte-eslint-parser"],
190
+ react: [
191
+ "@eslint-react/eslint-plugin",
192
+ "eslint-plugin-react-hooks",
193
+ "eslint-plugin-react-refresh"
194
+ ]
195
+ };
196
+ const jetbrainsSettingsObj = {
197
+ "?xml": {
198
+ version: "1.0",
199
+ encoding: "UTF-8"
200
+ },
201
+ "project": {
202
+ version: "4",
203
+ component: {
204
+ "name": "EslintConfiguration",
205
+ "extra-options": { value: "--cache" },
206
+ "option": {
207
+ value: "true",
208
+ name: "fix-on-save"
209
+ },
210
+ "custom-configuration-file": {
211
+ used: "true",
212
+ path: "$PROJECT_DIR$/eslint.config.js"
213
+ }
214
+ }
215
+ }
216
+ };
217
+
218
+ //#endregion
219
+ //#region package.json
220
+ var version = "7.4.30";
221
+
222
+ //#endregion
223
+ //#region src/cli/constants-generated.ts
224
+ const versionsMap = {
225
+ "@eslint-react/eslint-plugin": "^2.12.4",
226
+ "@next/eslint-plugin-next": "^16.1.6",
227
+ "@unocss/eslint-plugin": "^66.6.0",
228
+ "astro-eslint-parser": "^1.2.2",
229
+ "eslint": "^9.39.2",
230
+ "eslint-plugin-astro": "^1.5.0",
231
+ "eslint-plugin-format": "^1.4.0",
232
+ "eslint-plugin-react-hooks": "^7.0.1",
233
+ "eslint-plugin-react-refresh": "^0.5.0",
234
+ "eslint-plugin-solid": "^0.14.5",
235
+ "eslint-plugin-svelte": "^3.15.0",
236
+ "prettier-plugin-astro": "^0.14.1",
237
+ "prettier-plugin-slidev": "^1.0.5",
238
+ "svelte-eslint-parser": "^1.4.1"
239
+ };
240
+
241
+ //#endregion
242
+ //#region src/cli/stages/update-package-json.ts
243
+ async function updatePackageJson(result) {
244
+ const cwd = process.cwd();
245
+ const pathPackageJSON = path.join(cwd, "package.json");
246
+ p.log.step(c.cyan`Bumping @whoj/eslint-config to v${version}`);
247
+ const pkgContent = await fs.readFile(pathPackageJSON, "utf-8");
248
+ const pkg = JSON.parse(pkgContent);
249
+ pkg.devDependencies ??= {};
250
+ pkg.devDependencies["@whoj/eslint-config"] = `^${version}`;
251
+ pkg.devDependencies.eslint ??= versionsMap.eslint;
252
+ const addedPackages = [];
253
+ if (result.extra.length) result.extra.forEach((item) => {
254
+ switch (item) {
255
+ case "unocss":
256
+ dependenciesMap.unocss.forEach((f) => {
257
+ pkg.devDependencies[f] = versionsMap[f];
258
+ addedPackages.push(f);
259
+ });
260
+ break;
261
+ case "formatter":
262
+ [...dependenciesMap.formatter, ...result.frameworks.includes("astro") ? dependenciesMap.formatterAstro : []].forEach((f) => {
263
+ if (!f) return;
264
+ pkg.devDependencies[f] = versionsMap[f];
265
+ addedPackages.push(f);
266
+ });
267
+ break;
268
+ }
269
+ });
270
+ for (const framework of result.frameworks) {
271
+ const deps = dependenciesMap[framework];
272
+ if (deps) deps.forEach((f) => {
273
+ pkg.devDependencies[f] = versionsMap[f];
274
+ addedPackages.push(f);
275
+ });
276
+ }
277
+ if (addedPackages.length) p.note(c.dim(addedPackages.join(", ")), "Added packages");
278
+ await fs.writeFile(pathPackageJSON, JSON.stringify(pkg, null, 2));
279
+ p.log.success(c.green`Changes wrote to package.json`);
280
+ }
281
+
282
+ //#endregion
283
+ //#region src/cli/stages/update-jetbrains-idea.ts
284
+ async function updateJetbrainsIdea(result, configFileName) {
285
+ if (!result.updateJetbrainsIdea) return;
286
+ const xmlParser = new XMLParser({
287
+ ignoreAttributes: false,
288
+ attributeNamePrefix: ""
289
+ });
290
+ const xmlBuilder = new XMLBuilder({
291
+ format: true,
292
+ ignoreAttributes: false,
293
+ attributeNamePrefix: "",
294
+ suppressEmptyNode: true
295
+ });
296
+ const cwd = process.cwd();
297
+ const ideaDir = path.join(cwd, ".idea");
298
+ const jsLintersDir = path.join(ideaDir, "jsLinters");
299
+ if (!fs$1.existsSync(ideaDir)) fs$1.mkdirSync(ideaDir, { recursive: true });
300
+ if (!fs$1.existsSync(jsLintersDir)) fs$1.mkdirSync(jsLintersDir, { recursive: true });
301
+ const eslintXmlPath = path.join(jsLintersDir, "eslint.xml");
302
+ let settings;
303
+ if (fs$1.existsSync(eslintXmlPath)) {
304
+ const content = fs$1.readFileSync(eslintXmlPath, "utf-8");
305
+ settings = deepMerge(xmlParser.parse(content), jetbrainsSettingsObj);
306
+ p.log.step(c.cyan`Updating existing JetBrains ESLint configuration`);
307
+ } else {
308
+ settings = { ...jetbrainsSettingsObj };
309
+ p.log.step(c.cyan`Creating new JetBrains ESLint configuration`);
310
+ }
311
+ settings.project.component["custom-configuration-file"] = {
312
+ used: "true",
313
+ path: `$PROJECT_DIR$/.idea/jsLinters/${configFileName}`
314
+ };
315
+ const xml = xmlBuilder.build(settings);
316
+ fs$1.writeFileSync(eslintXmlPath, xml, "utf-8");
317
+ const jetbrainsConfigPath = path.join(jsLintersDir, configFileName);
318
+ const configContent = getJetbrainsEslintConfigContent(path.relative(jsLintersDir, path.join(cwd, configFileName)));
319
+ fs$1.writeFileSync(jetbrainsConfigPath, configContent, "utf-8");
320
+ p.log.success(c.green`JetBrains ESLint configuration updated`);
321
+ }
322
+
323
+ //#endregion
324
+ //#region src/cli/stages/update-vscode-settings.ts
325
+ async function updateVscodeSettings(result) {
326
+ const cwd = process.cwd();
327
+ if (!result.updateVscodeSettings) return;
328
+ const dotVscodePath = path.join(cwd, ".vscode");
329
+ const settingsPath = path.join(dotVscodePath, "settings.json");
330
+ if (!fs$1.existsSync(dotVscodePath)) await fs.mkdir(dotVscodePath, { recursive: true });
331
+ if (!fs$1.existsSync(settingsPath)) {
332
+ await fs.writeFile(settingsPath, `{${vscodeSettingsString}}\n`, "utf-8");
333
+ p.log.success(green`Created .vscode/settings.json`);
334
+ } else {
335
+ let settingsContent = await fs.readFile(settingsPath, "utf8");
336
+ settingsContent = settingsContent.trim().replace(/\s*\}$/, "");
337
+ settingsContent += settingsContent.endsWith(",") || settingsContent.endsWith("{") ? "" : ",";
338
+ settingsContent += `${vscodeSettingsString}}\n`;
339
+ await fs.writeFile(settingsPath, settingsContent, "utf-8");
340
+ p.log.success(green`Updated .vscode/settings.json`);
341
+ }
342
+ }
343
+
344
+ //#endregion
345
+ //#region src/cli/run.ts
346
+ async function run({ jetbrains, ...options } = {}) {
347
+ const argSkipPrompt = !!process.env.SKIP_PROMPT || options.yes;
348
+ const argTemplate = options.frameworks?.map((m) => m?.trim()).filter(Boolean);
349
+ const argExtra = options.extra?.map((m) => m?.trim()).filter(Boolean);
350
+ if (fs$1.existsSync(path.join(process.cwd(), "eslint.config.js"))) {
351
+ p.log.warn(c.yellow`eslint.config.js already exists, migration wizard exited.`);
352
+ return process.exit(1);
353
+ }
354
+ let result = {
355
+ extra: argExtra ?? [],
356
+ frameworks: argTemplate ?? [],
357
+ uncommittedConfirmed: false,
358
+ updateJetbrainsIdea: jetbrains ?? true,
359
+ updateVscodeSettings: true
360
+ };
361
+ if (!argSkipPrompt) {
362
+ result = await p.group({
363
+ uncommittedConfirmed: () => {
364
+ if (argSkipPrompt || isGitClean()) return Promise.resolve(true);
365
+ return p.confirm({
366
+ initialValue: false,
367
+ message: "There are uncommitted changes in the current repository, are you sure to continue?"
368
+ });
369
+ },
370
+ frameworks: ({ results }) => {
371
+ const isArgTemplateValid = typeof argTemplate === "string" && !!frameworks.includes(argTemplate);
372
+ if (!results.uncommittedConfirmed || isArgTemplateValid) return;
373
+ const message = !isArgTemplateValid && argTemplate ? `"${argTemplate}" isn't a valid template. Please choose from below: ` : "Select a framework:";
374
+ return p.multiselect({
375
+ message: c.reset(message),
376
+ options: frameworkOptions,
377
+ required: false
378
+ });
379
+ },
380
+ extra: ({ results }) => {
381
+ const isArgExtraValid = argExtra?.length && !argExtra.filter((element) => !extra.includes(element)).length;
382
+ if (!results.uncommittedConfirmed || isArgExtraValid) return;
383
+ const message = !isArgExtraValid && argExtra ? `"${argExtra}" isn't a valid extra util. Please choose from below: ` : "Select a extra utils:";
384
+ return p.multiselect({
385
+ message: c.reset(message),
386
+ options: extraOptions,
387
+ required: false
388
+ });
389
+ },
390
+ updateJetbrainsIdea: ({ results }) => {
391
+ if (!results.uncommittedConfirmed) return;
392
+ return p.confirm({
393
+ initialValue: true,
394
+ message: "Update JetBrain IDE's eslint configuration for better experience WebStorm / PhpStorm?"
395
+ });
396
+ },
397
+ updateVscodeSettings: ({ results }) => {
398
+ if (!results.uncommittedConfirmed) return;
399
+ return p.confirm({
400
+ initialValue: true,
401
+ message: "Update .vscode/settings.json for better VS Code experience?"
402
+ });
403
+ }
404
+ }, { onCancel: () => {
405
+ p.cancel("Operation cancelled.");
406
+ process.exit(0);
407
+ } });
408
+ if (!result.uncommittedConfirmed) return process.exit(1);
409
+ }
410
+ await updatePackageJson(result);
411
+ const configFileName = await updateEslintFiles(result);
412
+ await updateJetbrainsIdea(result, configFileName);
413
+ await updateVscodeSettings(result);
414
+ p.log.success(c.green`Setup completed`);
415
+ p.outro(`Now you can update the dependencies by run ${c.blue("pnpm install")} and run ${c.blue("eslint --fix")}\n`);
416
+ }
417
+
418
+ //#endregion
419
+ //#region src/cli/index.ts
420
+ function header() {
421
+ console.log("\n");
422
+ p.intro(`${c.green`@whoj/eslint-config `}${c.dim`v${version}`}`);
423
+ }
424
+ const cli = cac("@whoj/eslint-config");
425
+ cli.command("", "Run the initialization or migration").option("--yes, -y", "Skip prompts and use default values", { default: false }).option("--template, -t <template>", "Use the framework template for optimal customization: vue / react / svelte / astro", { type: [] }).option("--extra, -e <extra>", "Use the extra utils: formatter / perfectionist / unocss", { type: [] }).option("--jetbrains", "Configure eslint settings for better Jetbrains IDE. (WebStorm / PhpStorm) experience.", {
426
+ default: true,
427
+ type: "boolean",
428
+ alias: ["idea", "j"]
429
+ }).action(async (args) => {
430
+ header();
431
+ try {
432
+ await run(args);
433
+ } catch (error) {
434
+ p.log.error(c.inverse.red(" Failed to migrate "));
435
+ p.log.error(c.red`✘ ${String(error)}`);
436
+ process.exit(1);
437
+ }
438
+ });
439
+ cli.help();
440
+ cli.version(version);
441
+ cli.parse();
442
+
443
+ //#endregion
444
+ export { };