zixulu 1.69.2 → 1.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -293,19 +293,16 @@ async function installDependceny(config) {
293
293
  }
294
294
  return true;
295
295
  }
296
- function getTsConfigJsonPath(path) {
297
- return join(path ?? external_process_cwd(), "tsconfig.json");
298
- }
299
- async function readTsConfig(path) {
300
- try {
301
- const result = json5.parse(await readFile(getTsConfigJsonPath(path), "utf-8"));
302
- return result;
303
- } catch (error) {
304
- consola.fail("\u8BFB\u53D6 tsconfig.json \u5931\u8D25");
305
- throw error;
306
- }
307
- }
308
- const originalConfig = `// @ts-check
296
+ const ignoreConfig = `node_modules
297
+ public
298
+ dist
299
+ build
300
+ generated
301
+ .next
302
+ .vscode
303
+ .generated
304
+ `;
305
+ const prettierConfig = `// @ts-check
309
306
 
310
307
  /**
311
308
  * @type {import("prettier").Options}
@@ -316,147 +313,125 @@ const config = {
316
313
  arrowParens: "avoid",
317
314
  printWidth: 160,
318
315
  endOfLine: "lf",
319
- plugins: ["prettier-plugin-organize-imports"],
316
+ plugins: ["./prettier-plugin-sort-imports.mjs"],
320
317
  }
321
318
 
322
319
  export default config
323
320
  `;
324
- const ignoreConfig = `node_modules
325
- public
326
- dist
327
- build
328
- generated
329
- .next
330
- .vscode
331
- .generated
332
- `;
333
- function getPrettierConfig({ tailwind, atAlias, next, react }) {
334
- const plugins = [
335
- "@ianvs/prettier-plugin-sort-imports"
336
- ];
337
- if (tailwind) plugins.push("prettier-plugin-tailwindcss");
338
- const prettierConfigText = `// @ts-check
339
- ${atAlias ? `
340
- import { readFileSync } from "fs"` : ""}
341
- import { parse } from "path"
342
- import { globSync } from "glob"
321
+ function getPluginConfig({ isTailwind, isReact }) {
322
+ const config = `// @ts-check
343
323
 
324
+ import { readFileSync } from "fs"
325
+ import { builtinModules } from "module"
326
+
327
+ import { createPlugin } from "@1adybug/prettier-plugin-sort-imports"
328
+ import JSON5 from "json5"
329
+ import blockPadding from "prettier-plugin-block-padding"${isTailwind ? `
330
+ import * as tailwindcss from "prettier-plugin-tailwindcss"` : ""}
331
+ ${isReact ? `
344
332
  /**
345
- * \u{6570}\u{7EC4}\u{53BB}\u{91CD}
346
- * @template T - \u{6570}\u{7EC4}\u{7684}\u{5143}\u{7D20}\u{7C7B}\u{578B}
347
- * @param {T[]} array - \u{8F93}\u{5165}\u{7684}\u{6570}\u{7EC4}
348
- * @return {T[]} \u{65B0}\u{6570}\u{7EC4}
333
+ * @param {string} path
349
334
  */
350
- function unique(array) {
351
- return Array.from(new Set(array))
335
+ function isReact(path) {
336
+ return /^@?react\\b/.test(path)
337
+ }
338
+ ` : ""}
339
+ /**
340
+ * @param {string} path
341
+ */
342
+ function isBuiltin(path) {
343
+ return path.startsWith("node:") || builtinModules.includes(path)
352
344
  }
353
345
 
354
- const jsExts = [".js", ".jsx", ".ts", ".tsx", ".cjs", ".mjs", ".cts", ".mts", ".vue"]
355
-
356
- const assetExts = unique(
357
- globSync("**/*", { ignore: ["node_modules/**"${next ? ', ".next/**"' : ""}], withFileTypes: true, cwd: import.meta.dirname })
358
- .filter(path => path.isFile() && !jsExts.some(ext => path.name.toLowerCase().endsWith(ext)))
359
- .map(path => parse(path.name).ext.slice(1))
360
- .filter(ext => ext !== ""),
361
- )
346
+ /** @type {string[]} */
347
+ let pathAlias = []
362
348
 
363
- const assetExtsRegStr = \`\\\\.(\${assetExts.join("|")}|\${assetExts.join("|").toUpperCase()})\`
349
+ try {
350
+ const tsConfig = JSON5.parse(readFileSync("tsconfig.json", "utf-8"))
351
+ pathAlias = Object.keys(tsConfig.compilerOptions?.paths ?? {})
352
+ .map(item => item.match(/^(@.*\\/)\\*/))
353
+ .filter(Boolean)
354
+ .map(item => /** @type {string} */ (item?.[1]))
355
+ } catch {}
364
356
 
365
- const assetQueryRegStr = "(\\\\?[a-zA-Z0-9]+)?"
366
- ${atAlias ? `
367
- const namespaces = unique(
368
- unique(
369
- globSync("**/package.json", { withFileTypes: true, cwd: import.meta.dirname })
370
- .filter(path => path.isFile())
371
- .map(path => path.fullpath()),
372
- )
373
- .map(path => JSON.parse(readFileSync(path, "utf8")))
374
- .map(json =>
375
- Object.keys({
376
- ...json.dependencies,
377
- ...json.devDependencies,
378
- ...json.peerDependencies,
379
- ...json.optionalDependencies,
380
- }),
381
- )
382
- .flat()
383
- .filter(dep => dep.startsWith("@"))
384
- .map(dep => dep.split("/")[0].slice(1)),
385
- )
386
- ` : ""}
387
- const folders = unique(
388
- globSync("**/*", { withFileTypes: true, cwd: import.meta.dirname, ignore: ["node_modules/**"${next ? ', ".next/**"' : ""}] })
389
- .filter(path => path.isDirectory())
390
- .map(path => path.name),
391
- ).sort()
357
+ /**
358
+ * @param {string} path
359
+ */
360
+ function isAbsolute(path) {
361
+ return pathAlias.some(item => path.startsWith(item))
362
+ }
392
363
 
393
364
  /**
394
- * @type {import("prettier").Options}
365
+ * @param {string} path
395
366
  */
396
- const config = {
397
- semi: false,
398
- tabWidth: 4,
399
- arrowParens: "avoid",
400
- printWidth: 160,
401
- endOfLine: "lf",
402
- plugins: [${plugins.map((plugin)=>`"${plugin}"`).join(", ")}],
403
- importOrder: [${react ? `
404
- "^react(/.+)?$",
405
- "^react-dom(/.+)?$",
406
- "^react-native(/.+)?$",` : ""}
407
- "<BUILTIN_MODULES>",
408
- ${atAlias ? '`^@(${namespaces.join("|")})/`,' : '"^@[^/]",'}
409
- "<THIRD_PARTY_MODULES>",
410
- ...folders.map(folder => ["", \`^@/?\${folder}(.+?(?<!\${assetExtsRegStr}\${assetQueryRegStr}))?$\`]).flat(),
411
- "",
412
- \`^@/.+?(?<!\${assetExtsRegStr}\${assetQueryRegStr})$\`,
413
- \`^\\\\.{1,2}/.+?(?<!\${assetExtsRegStr}\${assetQueryRegStr})$\`,
414
- "",
415
- \`^@/.+?\${assetExtsRegStr}\${assetQueryRegStr}$\`,
416
- \`^\\\\.{1,2}/.+?\${assetExtsRegStr}\${assetQueryRegStr}$\`,
417
- ],
418
- importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"],
419
- importOrderTypeScriptVersion: "5.0.0",
420
- importOrderCaseSensitive: true,
367
+ function isRelative(path) {
368
+ return path.startsWith("./") || path.startsWith("../")
421
369
  }
422
370
 
423
- export default config
371
+ /**
372
+ * @param {string} a
373
+ * @param {string} b
374
+ */
375
+ function compareGroupName(a, b) {
376
+ const orders = [${isReact ? '"react", ' : ""}"builtin", "third-party", "absolute", "relative"]
377
+
378
+ a = a.replace(/-side-effect$/, "")
379
+ b = b.replace(/-side-effect$/, "")
380
+ return orders.indexOf(a) - orders.indexOf(b) || a.localeCompare(b)
381
+ }
382
+
383
+ export default createPlugin({
384
+ getGroup({ path, isSideEffect }) {
385
+ if (isSideEffect) {${isReact ? `
386
+ if (isReact(path)) return "react-side-effect"` : ""}
387
+ if (isBuiltin(path)) return "builtin-side-effect"
388
+ if (isAbsolute(path)) return "absolute-side-effect"
389
+ if (isRelative(path)) return "relative-side-effect"
390
+ return "third-party-side-effect"
391
+ }
392
+ ${isReact ? `
393
+ if (isReact(path)) return "react"` : ""}
394
+ if (isBuiltin(path)) return "builtin"
395
+ if (isAbsolute(path)) return "absolute"
396
+ if (isRelative(path)) return "relative"
397
+ return "third-party"
398
+ },
399
+ sortGroup(a, b) {
400
+ return Number(a.isSideEffect) - Number(b.isSideEffect) || compareGroupName(a.name, b.name)
401
+ },
402
+ separator: "",
403
+ sortSideEffect: true,
404
+ removeUnusedImports: true,
405
+ otherPlugins: [blockPadding${isTailwind ? ", tailwindcss" : ""}],
406
+ })
424
407
  `;
425
- return prettierConfigText;
408
+ return config;
426
409
  }
427
410
  async function addPrettier() {
428
411
  consola.start("\u5F00\u59CB\u6DFB\u52A0 prettier \u914D\u7F6E");
429
412
  const packageJson = await readPackageJson();
430
- const tailwind = Object.keys(packageJson.dependencies ?? {}).includes("tailwindcss") || Object.keys(packageJson.devDependencies ?? {}).includes("tailwindcss");
431
- let atAlias = false;
432
- try {
433
- const config = await readTsConfig();
434
- atAlias = Object.keys(config.compilerOptions?.paths ?? {}).some((path)=>/^@[a-zA-Z]/.test(path));
435
- } catch {}
436
- const next = await hasDependency("next");
437
- const react = await hasDependency("react");
438
- await writeFile("prettier.config.mjs", originalConfig, "utf-8");
439
- await writeFile(".prettierrc.mjs", getPrettierConfig({
440
- tailwind,
441
- atAlias,
442
- next,
443
- react
413
+ const isTailwind = Object.keys(packageJson.dependencies ?? {}).includes("tailwindcss") || Object.keys(packageJson.devDependencies ?? {}).includes("tailwindcss");
414
+ const isReact = await hasDependency("react");
415
+ await writeFile("prettier-plugin-sort-imports.mjs", getPluginConfig({
416
+ isTailwind,
417
+ isReact
444
418
  }), "utf-8");
419
+ await writeFile("prettier.config.mjs", prettierConfig, "utf-8");
445
420
  await writeFile(".prettierignore", ignoreConfig, "utf-8");
446
421
  const config2 = {
447
422
  package: [
448
423
  "prettier",
449
- "@ianvs/prettier-plugin-sort-imports",
450
- "glob",
451
- "prettier-plugin-organize-imports"
424
+ "@1adybug/prettier-plugin-sort-imports",
425
+ "prettier-plugin-block-padding",
426
+ "json5"
452
427
  ],
453
428
  type: "devDependencies"
454
429
  };
455
- if (tailwind) config2.package.push("prettier-plugin-tailwindcss");
430
+ if (isTailwind) config2.package.push("prettier-plugin-tailwindcss");
456
431
  await addDependency(config2);
457
432
  const packageJson2 = await readPackageJson();
458
433
  packageJson2.scripts ??= {};
459
- packageJson2.scripts.format = "prettier --config prettier.config.mjs --write . && prettier --config .prettierrc.mjs --write .";
434
+ packageJson2.scripts.format = "prettier --write .";
460
435
  packageJson2.scripts.fg = 'npm run format && git add . && git commit -m "\u2728feature: format"';
461
436
  await writePackageJson({
462
437
  data: packageJson2
@@ -759,6 +734,18 @@ function getTsFile(path) {
759
734
  };
760
735
  throw new Error(`\u{627E}\u{4E0D}\u{5230} ${path} \u{5BF9}\u{5E94}\u{7684} ts \u{6216} tsx \u{6587}\u{4EF6}`);
761
736
  }
737
+ function getTsConfigJsonPath(path) {
738
+ return join(path ?? external_process_cwd(), "tsconfig.json");
739
+ }
740
+ async function readTsConfig(path) {
741
+ try {
742
+ const result = json5.parse(await readFile(getTsConfigJsonPath(path), "utf-8"));
743
+ return result;
744
+ } catch (error) {
745
+ consola.fail("\u8BFB\u53D6 tsconfig.json \u5931\u8D25");
746
+ throw error;
747
+ }
748
+ }
762
749
  async function writeTsConfig(config) {
763
750
  return await writeFile(getTsConfigJsonPath(), JSON.stringify(config, void 0, 4), "utf-8");
764
751
  }
@@ -2673,10 +2660,17 @@ async function upgradeDependency(config) {
2673
2660
  await installDependceny();
2674
2661
  return getCommitMessage("feature", `upgrade dependencies: ${upgradeLogs.join(", ")}`);
2675
2662
  }
2676
- async function addGitCommit(message) {
2663
+ async function addGitCommit(messageOrParams) {
2664
+ const { message, cwd } = "string" == typeof messageOrParams ? {
2665
+ message: messageOrParams
2666
+ } : messageOrParams;
2677
2667
  consola.start("\u63D0\u4EA4\u4EE3\u7801");
2678
- await execAsync("git add .");
2679
- await execAsync(`git commit -m "${message}"`);
2668
+ await execAsync("git add .", {
2669
+ cwd
2670
+ });
2671
+ await execAsync(`git commit -m "${message}"`, {
2672
+ cwd
2673
+ });
2680
2674
  }
2681
2675
  function actionWithBackup(action, message) {
2682
2676
  return async (...args)=>{
@@ -4393,11 +4387,13 @@ async function syncEditorSetting() {
4393
4387
  message: "\u9009\u62E9\u540C\u6B65\u76EE\u6807",
4394
4388
  choices: [
4395
4389
  "Code",
4396
- "Cursor"
4390
+ "Cursor",
4391
+ "Online"
4397
4392
  ].filter((v)=>v !== source),
4398
4393
  default: (setting.syncEditor?.targets ?? [
4399
4394
  "Code",
4400
- "Cursor"
4395
+ "Cursor",
4396
+ "Online"
4401
4397
  ]).filter((v)=>v !== source)
4402
4398
  },
4403
4399
  {
@@ -4418,10 +4414,19 @@ async function syncEditorSetting() {
4418
4414
  ]);
4419
4415
  setting.syncEditor.targets = targets;
4420
4416
  setting.syncEditor.types = types;
4421
- await writeZixuluSetting(setting);
4417
+ if (targets.includes("Online")) {
4418
+ const { onlinePath } = await inquirer_0.prompt({
4419
+ type: "input",
4420
+ name: "onlinePath",
4421
+ message: "\u8BF7\u8F93\u5165 blog \u6587\u4EF6\u5939\u7684\u8DEF\u5F84",
4422
+ default: setting.syncEditor?.onlinePath ?? "C:\\Users\\lenovo\\Desktop\\workspace\\blog"
4423
+ });
4424
+ setting.syncEditor.onlinePath = onlinePath;
4425
+ }
4426
+ const onlinePath = setting.syncEditor.onlinePath;
4422
4427
  const configs = types.filter((item)=>"extensions" !== item).map((fileType)=>targets.map((target)=>({
4423
4428
  source: fileSourceMap[fileType][source],
4424
- target: fileSourceMap[fileType][target]
4429
+ target: "Online" === target ? join(onlinePath, "static", "settings" === fileType ? "settings.json" : "global.code-snippets") : fileSourceMap[fileType][target]
4425
4430
  }))).flat();
4426
4431
  for (const config of configs)await syncEditorFile(config);
4427
4432
  if (types.includes("extensions")) {
@@ -4467,7 +4472,15 @@ async function syncEditorSetting() {
4467
4472
  console.error(`${ext} \u{5378}\u{8F7D}\u{5931}\u{8D25}`);
4468
4473
  }
4469
4474
  }
4475
+ if (targets.includes("Online")) await writeFile(join(onlinePath, "static", "extensions.json"), JSON.stringify(Array.from(sourceExtensions), null, 4));
4470
4476
  }
4477
+ if (targets.includes("Online")) {
4478
+ if (await hasChangeNoCommit(onlinePath)) await addGitCommit({
4479
+ message: getCommitMessage("feature", "sync editor setting"),
4480
+ cwd: onlinePath
4481
+ });
4482
+ }
4483
+ await writeZixuluSetting(setting);
4471
4484
  }
4472
4485
  async function tailwindPatch() {
4473
4486
  const version = await getPackageVersionInDependcy("tailwindcss");