@icebreakers/monorepo 3.2.18 → 4.0.1

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.
@@ -1,1513 +0,0 @@
1
- import gitUrlParse from "git-url-parse";
2
- import { simpleGit } from "simple-git";
3
- import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
4
- import { findWorkspacePackages } from "@pnpm/workspace.find-packages";
5
- import { readWorkspaceManifest } from "@pnpm/workspace.read-manifest";
6
- import path from "pathe";
7
- import process from "node:process";
8
- import { access, cp, mkdir, mkdtemp, open, readFile, rm, stat, writeFile } from "node:fs/promises";
9
- import { createConsola } from "consola";
10
- import { assetsDir, checkbox, ensureTemplateAssetsPrepared, execaCommand, getAssetTargets, isGitignoreFile, scaffoldTemplate, templatesDir, toPublishGitignorePath, toWorkspaceGitignorePath } from "@icebreakers/monorepo-templates";
11
- import YAML, { isSeq, parseDocument } from "yaml";
12
- import crypto from "node:crypto";
13
- import { loadConfig } from "c12";
14
- import os from "node:os";
15
- import * as path$1 from "node:path";
16
- import { fileURLToPath } from "node:url";
17
- import pc from "picocolors";
18
- import "@pnpm/types";
19
- import { parse, stringify } from "comment-json";
20
- import PQueue from "p-queue";
21
- import klaw from "klaw";
22
- import { Buffer } from "node:buffer";
23
- import { coerce, gte, minVersion } from "semver";
24
- //#region src/core/git.ts
25
- /**
26
- * 对 simple-git 的轻量封装,集中处理配置缓存与常用查询。
27
- */
28
- var GitClient = class {
29
- client;
30
- #config;
31
- constructor(options = {}) {
32
- this.client = simpleGit(options);
33
- }
34
- /**
35
- * 读取 Git 的 config 列表,原样返回 simple-git 的结果。
36
- */
37
- listConfig() {
38
- return this.client.listConfig();
39
- }
40
- /**
41
- * 初始化配置缓存,避免多次访问 Git 产生的性能损耗。
42
- */
43
- async init() {
44
- this.#config = (await this.listConfig()).all;
45
- return this.#config;
46
- }
47
- /**
48
- * 获取缓存的配置,若未初始化则自动触发 init。
49
- */
50
- async getConfig() {
51
- if (this.#config) return this.#config;
52
- else return await this.init();
53
- }
54
- /**
55
- * 解析 remote.origin.url,返回 git-url-parse 的结构,便于获取仓库元信息。
56
- */
57
- async getGitUrl() {
58
- const x = (await this.getConfig())["remote.origin.url"];
59
- if (typeof x === "string") return gitUrlParse(x);
60
- }
61
- /**
62
- * 组合 owner/name,生成常用的仓库名表达。
63
- */
64
- async getRepoName() {
65
- const url = await this.getGitUrl();
66
- if (url) return `${url.owner}/${url.name}`;
67
- }
68
- /**
69
- * 从 Git 配置中提取用户信息,用于填充 package.json author 字段。
70
- */
71
- async getUser() {
72
- const config = await this.getConfig();
73
- return {
74
- name: config["user.name"],
75
- email: config["user.email"]
76
- };
77
- }
78
- /**
79
- * 获取当前仓库的顶层目录路径。
80
- */
81
- async getRepoRoot() {
82
- try {
83
- const root = await this.client.revparse(["--show-toplevel"]);
84
- return typeof root === "string" ? root.trim() : void 0;
85
- } catch {
86
- return;
87
- }
88
- }
89
- };
90
- //#endregion
91
- //#region ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
92
- function isPlainObject$1(value) {
93
- if (value === null || typeof value !== "object") return false;
94
- const prototype = Object.getPrototypeOf(value);
95
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
96
- if (Symbol.iterator in value) return false;
97
- if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
98
- return true;
99
- }
100
- function _defu(baseObject, defaults, namespace = ".", merger) {
101
- if (!isPlainObject$1(defaults)) return _defu(baseObject, {}, namespace, merger);
102
- const object = Object.assign({}, defaults);
103
- for (const key in baseObject) {
104
- if (key === "__proto__" || key === "constructor") continue;
105
- const value = baseObject[key];
106
- if (value === null || value === void 0) continue;
107
- if (merger && merger(object, key, value, namespace)) continue;
108
- if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
109
- else if (isPlainObject$1(value) && isPlainObject$1(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
110
- else object[key] = value;
111
- }
112
- return object;
113
- }
114
- function createDefu(merger) {
115
- return (...arguments_) => arguments_.reduce((p, c) => _defu(p, c, "", merger), {});
116
- }
117
- const defu = createDefu();
118
- createDefu((object, key, currentValue) => {
119
- if (object[key] !== void 0 && typeof currentValue === "function") {
120
- object[key] = currentValue(object[key]);
121
- return true;
122
- }
123
- });
124
- createDefu((object, key, currentValue) => {
125
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
126
- object[key] = currentValue(object[key]);
127
- return true;
128
- }
129
- });
130
- //#endregion
131
- //#region src/core/workspace.ts
132
- /**
133
- * 读取 pnpm workspace 下的所有包,并根据配置过滤与补充字段。
134
- */
135
- async function getWorkspacePackages(workspaceDir, options) {
136
- const { ignoreRootPackage, ignorePrivatePackage, patterns } = defu(options, {
137
- ignoreRootPackage: true,
138
- ignorePrivatePackage: true
139
- });
140
- const manifest = await readWorkspaceManifest(workspaceDir);
141
- const workspacePatterns = patterns ?? manifest?.packages;
142
- let pkgs = (await findWorkspacePackages(workspaceDir, workspacePatterns ? { patterns: workspacePatterns } : {})).filter((x) => {
143
- if (ignorePrivatePackage && x.manifest.private) return false;
144
- return true;
145
- }).map((project) => {
146
- const pkgJsonPath = path.resolve(project.rootDir, "package.json");
147
- return {
148
- ...project,
149
- pkgJsonPath
150
- };
151
- });
152
- if (ignoreRootPackage) pkgs = pkgs.filter((x) => {
153
- return x.rootDir !== workspaceDir;
154
- });
155
- return pkgs;
156
- }
157
- /**
158
- * 将工作区绝对路径、包列表与当前 cwd 打包返回,方便调用方一次获取所有信息。
159
- */
160
- async function getWorkspaceData(cwd, options) {
161
- const workspaceDir = await findWorkspaceDir(cwd) ?? cwd;
162
- return {
163
- cwd,
164
- workspaceDir,
165
- packages: await getWorkspacePackages(workspaceDir, options)
166
- };
167
- }
168
- //#endregion
169
- //#region src/utils/fs.ts
170
- function stringifyJson(data, options) {
171
- return JSON.stringify(data, void 0, options?.spaces);
172
- }
173
- async function ensureParentDir(targetPath) {
174
- await mkdir(path.dirname(targetPath), { recursive: true });
175
- }
176
- async function pathExists(targetPath) {
177
- try {
178
- await access(targetPath);
179
- return true;
180
- } catch {
181
- return false;
182
- }
183
- }
184
- const exists = pathExists;
185
- async function ensureDir(targetPath) {
186
- await mkdir(targetPath, { recursive: true });
187
- }
188
- async function ensureFile(targetPath) {
189
- await ensureParentDir(targetPath);
190
- await (await open(targetPath, "a")).close();
191
- }
192
- async function remove(targetPath) {
193
- await rm(targetPath, {
194
- recursive: true,
195
- force: true,
196
- maxRetries: 3,
197
- retryDelay: 100
198
- });
199
- }
200
- async function copy(sourcePath, targetPath) {
201
- await cp(sourcePath, targetPath, {
202
- recursive: true,
203
- force: true
204
- });
205
- }
206
- async function outputFile(targetPath, data, options) {
207
- await ensureParentDir(targetPath);
208
- await writeFile(targetPath, data, options);
209
- }
210
- async function readJson(targetPath) {
211
- return JSON.parse(await readFile(targetPath, "utf8"));
212
- }
213
- const readJSON = readJson;
214
- async function writeJson(targetPath, data, options) {
215
- await writeFile(targetPath, stringifyJson(data, options), "utf8");
216
- }
217
- const writeJSON = writeJson;
218
- async function outputJson(targetPath, data, options) {
219
- await ensureParentDir(targetPath);
220
- await writeJson(targetPath, data, options);
221
- }
222
- const outputJSON = outputJson;
223
- /**
224
- * 判断是否为可忽略的文件系统错误。
225
- * - ENOENT: 文件已被删除
226
- * - EBUSY: Windows 中资源被系统占用
227
- */
228
- function isIgnorableFsError(error) {
229
- if (!error) return false;
230
- const code = error.code;
231
- return code === "ENOENT" || code === "EBUSY" || code === "EEXIST";
232
- }
233
- const fs = {
234
- copy,
235
- ensureDir,
236
- ensureFile,
237
- exists,
238
- mkdtemp,
239
- outputFile,
240
- outputJSON,
241
- outputJson,
242
- pathExists,
243
- readFile,
244
- readJSON,
245
- readJson,
246
- remove,
247
- stat,
248
- writeFile,
249
- writeJSON,
250
- writeJson
251
- };
252
- //#endregion
253
- //#region src/core/logger.ts
254
- /**
255
- * 统一的日志实例,便于在命令行中输出带有前缀和颜色的消息。
256
- */
257
- const logger = createConsola();
258
- //#endregion
259
- //#region src/commands/ai.ts
260
- const agenticSections = [
261
- "目标/产物",
262
- "约束(性能/风格/兼容/不可改动范围)",
263
- "验收标准(要跑的命令、预期输出/文件)",
264
- "仓库路径",
265
- "允许操作(可/不可写文件,可运行的命令清单,可否联网)",
266
- "上下文线索(日志/文件/模块/相关 issue)",
267
- "里程碑(根因→设计→实现→验证)"
268
- ];
269
- const defaultAgenticBaseDir = "agentic/prompts";
270
- function renderMarkdownTemplate() {
271
- return `${agenticSections.map((title) => `## ${title}\n- `).join("\n\n")}\n`;
272
- }
273
- function renderJsonTemplate() {
274
- const payload = {};
275
- for (const title of agenticSections) payload[title] = "";
276
- return `${JSON.stringify(payload, null, 2)}\n`;
277
- }
278
- function createTimestampFolderName(date = /* @__PURE__ */ new Date()) {
279
- const pad = (value) => value.toString().padStart(2, "0");
280
- return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`;
281
- }
282
- /**
283
- * 生成 Agentic 任务提示词模板,默认写入 agentic/prompts/<timestamp>/prompt.md,可自定义输出路径。
284
- */
285
- async function generateAgenticTemplate(options = {}) {
286
- const cwd = options.cwd ?? process.cwd();
287
- const format = options.format ?? "md";
288
- const baseDir = options.baseDir ?? "agentic/prompts";
289
- if (format !== "md" && format !== "json") throw new Error(`不支持的模板格式:${format}`);
290
- const template = format === "md" ? renderMarkdownTemplate() : renderJsonTemplate();
291
- const ext = format === "json" ? "json" : "md";
292
- let outputPath = options.output;
293
- if (!outputPath && options.name) outputPath = path.join(baseDir, `${options.name}.${ext}`);
294
- if (!outputPath) {
295
- const folderName = options.folderName ?? createTimestampFolderName();
296
- outputPath = path.join(baseDir, folderName, `prompt.${ext}`);
297
- }
298
- const targetPath = path.resolve(cwd, outputPath);
299
- const targetDir = path.dirname(targetPath);
300
- await fs.ensureDir(targetDir);
301
- const exists = await fs.pathExists(targetPath);
302
- if (exists && !options.force) throw new Error(`目标文件已存在:${path.relative(cwd, targetPath)}`);
303
- await fs.outputFile(targetPath, template, "utf8");
304
- const actionLabel = exists ? "已覆盖模板" : "已生成模板";
305
- logger.success(`${actionLabel}:${path.relative(cwd, targetPath)}`);
306
- return template;
307
- }
308
- async function loadAgenticTasks(filePath, cwd) {
309
- const fullPath = path.resolve(cwd, filePath);
310
- const tasks = await fs.readJson(fullPath);
311
- if (!Array.isArray(tasks)) throw new TypeError("任务清单需要是数组");
312
- return tasks;
313
- }
314
- async function generateAgenticTemplates(tasks, defaults = {}) {
315
- const results = [];
316
- for (const task of tasks) {
317
- const normalized = typeof task === "string" ? {
318
- ...defaults,
319
- name: task
320
- } : {
321
- ...defaults,
322
- ...task
323
- };
324
- results.push(await generateAgenticTemplate(normalized));
325
- }
326
- return results;
327
- }
328
- //#endregion
329
- //#region src/utils/github.ts
330
- /**
331
- * 将 Issue 模版里的 discussions 链接同步为当前仓库的 discussions 地址。
332
- */
333
- function updateIssueTemplateConfig(source, repoName) {
334
- if (!repoName) return source;
335
- let doc;
336
- try {
337
- doc = parseDocument(source);
338
- } catch {
339
- return source;
340
- }
341
- const contactLinks = doc.get("contact_links");
342
- if (!isSeq(contactLinks)) return source;
343
- const nextUrl = `https://github.com/${repoName}/discussions`;
344
- let changed = false;
345
- contactLinks.items.forEach((_, index) => {
346
- const url = doc.getIn([
347
- "contact_links",
348
- index,
349
- "url"
350
- ]);
351
- if (typeof url !== "string") return;
352
- if (!url.includes("/discussions")) return;
353
- if (url === nextUrl) return;
354
- doc.setIn([
355
- "contact_links",
356
- index,
357
- "url"
358
- ], nextUrl);
359
- changed = true;
360
- });
361
- if (!changed) return source;
362
- return doc.toString();
363
- }
364
- //#endregion
365
- //#region src/utils/hash.ts
366
- /**
367
- * 生成给定二进制内容的 md5 摘要,用于快速比较文件内容。
368
- */
369
- function getFileHash(data) {
370
- const hashSum = crypto.createHash("md5");
371
- hashSum.update(data);
372
- return hashSum.digest("hex");
373
- }
374
- /**
375
- * 对比两个文件的 md5,如果不一致则认为内容有变化。
376
- */
377
- function isFileChanged(src, dest) {
378
- try {
379
- return getFileHash(src) !== getFileHash(dest);
380
- } catch (err) {
381
- logger.error("Error calculating file hash:", err);
382
- return false;
383
- }
384
- }
385
- //#endregion
386
- //#region src/utils/object.ts
387
- const arrayIndexPattern = /^\d+$/;
388
- function isArrayIndex(value) {
389
- return arrayIndexPattern.test(value);
390
- }
391
- function parsePath(input) {
392
- const segments = [];
393
- let current = "";
394
- let escaped = false;
395
- for (const char of input) {
396
- if (escaped) {
397
- current += char;
398
- escaped = false;
399
- continue;
400
- }
401
- if (char === "\\") {
402
- escaped = true;
403
- continue;
404
- }
405
- if (char === ".") {
406
- segments.push(current);
407
- current = "";
408
- continue;
409
- }
410
- current += char;
411
- }
412
- segments.push(current);
413
- return segments;
414
- }
415
- function setByPath(target, path, value) {
416
- const segments = typeof path === "string" ? parsePath(path) : [...path];
417
- if (!segments.length) return target;
418
- let current = target;
419
- for (let index = 0; index < segments.length - 1; index++) {
420
- const segment = segments[index];
421
- const nextSegment = segments[index + 1];
422
- const key = Array.isArray(current) && isArrayIndex(segment) ? Number(segment) : segment;
423
- const existing = current[key];
424
- if (typeof existing !== "object" || existing === null) current[key] = isArrayIndex(nextSegment) ? [] : {};
425
- current = current[key];
426
- }
427
- const lastSegment = segments.at(-1);
428
- const lastKey = Array.isArray(current) && isArrayIndex(lastSegment) ? Number(lastSegment) : lastSegment;
429
- current[lastKey] = value;
430
- return target;
431
- }
432
- //#endregion
433
- //#region src/utils/regexp.ts
434
- const regexpSpecialCharacterPattern = /[|\\{}()[\]^$+*?.]/g;
435
- const hyphenPattern = /-/g;
436
- /**
437
- * 逃逸正则表达式中所有特殊字符,避免被当做模式解析。
438
- */
439
- function escapeStringRegexp(str) {
440
- return str.replace(regexpSpecialCharacterPattern, "\\$&").replace(hyphenPattern, "\\x2d");
441
- }
442
- /**
443
- * 判断字符串是否命中任意一个正则,用于过滤要同步的资产文件。
444
- */
445
- function isMatch(str, arr) {
446
- for (const reg of arr) if (reg.test(str)) return true;
447
- return false;
448
- }
449
- //#endregion
450
- //#region src/core/config.ts
451
- /**
452
- * 简单的内存缓存,避免同一次命令中重复走磁盘加载配置。
453
- */
454
- const cache = /* @__PURE__ */ new Map();
455
- /**
456
- * 基于 c12 的通用配置加载逻辑,支持多种配置文件格式。
457
- */
458
- async function loadConfigInternal(cwd) {
459
- const { config, configFile } = await loadConfig({
460
- name: "monorepo",
461
- cwd,
462
- rcFile: false,
463
- defaults: {},
464
- globalRc: false,
465
- packageJson: false
466
- });
467
- return {
468
- file: configFile ? path.resolve(configFile) : null,
469
- config: config ?? {}
470
- };
471
- }
472
- /**
473
- * 提供类型提示的辅助函数,供外部定义配置时使用。
474
- */
475
- function defineMonorepoConfig(config) {
476
- return config;
477
- }
478
- /**
479
- * 加载指定目录的 monorepo 配置,并利用缓存提升性能。
480
- */
481
- async function loadMonorepoConfig(cwd) {
482
- const key = path.resolve(cwd);
483
- if (!cache.has(key)) cache.set(key, loadConfigInternal(key));
484
- const { config } = await cache.get(key);
485
- return config;
486
- }
487
- /**
488
- * 获取命令对应的合并配置,若未配置则返回空对象,保证调用端逻辑简单。
489
- */
490
- async function resolveCommandConfig(name, cwd) {
491
- return ((await loadMonorepoConfig(cwd)).commands ?? {})[name] ?? {};
492
- }
493
- //#endregion
494
- //#region package.json
495
- var name = "@icebreakers/monorepo";
496
- var version = "3.2.18";
497
- //#endregion
498
- //#region src/constants.ts
499
- /**
500
- * 还原出 package.json 所在的绝对路径,方便后续按目录组织资源文件。
501
- */
502
- const packageJsonPath = fileURLToPath(new URL("../package.json", import.meta.url));
503
- /**
504
- * @icebreakers/monorepo 包的根目录。
505
- */
506
- const packageDir = path$1.dirname(packageJsonPath);
507
- /**
508
- * monorepo 根目录,方便需要跳出当前包的逻辑(例如定位工作区文件)。
509
- */
510
- const rootDir = path$1.resolve(packageDir, "..", "..");
511
- //#endregion
512
- //#region src/commands/skills.ts
513
- const skillName = "icebreakers-monorepo-cli";
514
- const skillTargets = ["codex", "claude"];
515
- const skillSourceDir = path.join(packageDir, "resources", "skills", skillName);
516
- function getSkillTargetPaths(homeDir = os.homedir()) {
517
- return {
518
- codex: path.join(homeDir, ".codex", "skills", skillName),
519
- claude: path.join(homeDir, ".claude", "skills", skillName)
520
- };
521
- }
522
- function normalizeTargets(values) {
523
- if (!values?.length) return;
524
- return [...new Set(values)];
525
- }
526
- async function syncSkills(options = {}) {
527
- const cwd = options.cwd ?? process.cwd();
528
- if (!await fs.pathExists(skillSourceDir)) {
529
- const relative = path.relative(cwd, skillSourceDir);
530
- throw new Error(`未找到技能目录:${relative || skillSourceDir}`);
531
- }
532
- let targets = normalizeTargets(options.targets);
533
- if (!targets?.length) targets = normalizeTargets(await checkbox({
534
- message: "请选择需要同步的技能目标",
535
- choices: skillTargets.map((target) => ({
536
- name: target,
537
- value: target,
538
- checked: true
539
- }))
540
- }));
541
- if (!targets?.length) return [];
542
- const targetPaths = getSkillTargetPaths();
543
- const results = [];
544
- for (const target of targets) {
545
- const dest = targetPaths[target];
546
- await fs.remove(dest);
547
- await fs.ensureDir(path.dirname(dest));
548
- await fs.copy(skillSourceDir, dest);
549
- results.push({
550
- target,
551
- dest
552
- });
553
- }
554
- return results;
555
- }
556
- //#endregion
557
- //#region src/commands/clean.ts
558
- function mergeCleanConfig(base, overrides) {
559
- const normalizedBase = base ?? {};
560
- if (!overrides) return normalizedBase;
561
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== void 0));
562
- return {
563
- ...normalizedBase,
564
- ...definedOverrides
565
- };
566
- }
567
- /**
568
- * 交互式清理被选中的包目录,同时重写根 package.json 中的 @icebreakers/monorepo 版本。
569
- */
570
- async function cleanProjects(cwd, overrides) {
571
- const cleanConfig = mergeCleanConfig(await resolveCommandConfig("clean", cwd), overrides);
572
- const { packages, workspaceDir } = await getWorkspaceData(cwd, cleanConfig?.includePrivate ?? true ? { ignorePrivatePackage: false } : void 0);
573
- const filteredPackages = packages.filter((pkg) => {
574
- const name = pkg.manifest.name ?? "";
575
- if (!name) return true;
576
- if (!cleanConfig?.ignorePackages?.length) return true;
577
- return !cleanConfig.ignorePackages.includes(name);
578
- });
579
- let cleanDirs = [];
580
- if (cleanConfig?.autoConfirm) cleanDirs = filteredPackages.map((pkg) => pkg.rootDir);
581
- else cleanDirs = await checkbox({
582
- message: "请选择需要清理的目录",
583
- choices: filteredPackages.map((x) => {
584
- const baseChoice = {
585
- name: path.relative(workspaceDir, x.rootDir),
586
- value: x.rootDir,
587
- checked: true
588
- };
589
- return x.manifest.name ? {
590
- ...baseChoice,
591
- description: x.manifest.name
592
- } : baseChoice;
593
- })
594
- });
595
- const readmeZh = path.resolve(workspaceDir, "README.zh-CN.md");
596
- const qoderDir = path.resolve(workspaceDir, ".qoder");
597
- const docsPlansDir = path.resolve(workspaceDir, "docs/plans");
598
- const skillTargets = Object.values(getSkillTargetPaths());
599
- const candidates = [...new Set([
600
- ...cleanDirs.filter(Boolean),
601
- readmeZh,
602
- qoderDir,
603
- docsPlansDir,
604
- ...skillTargets
605
- ])];
606
- await Promise.all(candidates.map(async (dir) => {
607
- if (await fs.pathExists(dir)) await fs.remove(dir);
608
- }));
609
- const name = path.resolve(workspaceDir, "package.json");
610
- const pkgJson = await fs.readJson(name);
611
- setByPath(pkgJson, "devDependencies.@icebreakers/monorepo", cleanConfig?.pinnedVersion ?? "latest");
612
- await fs.outputJson(name, pkgJson, { spaces: 2 });
613
- }
614
- //#endregion
615
- //#region src/commands/create.ts
616
- /**
617
- * 内置模板映射表,source 指向 templates 根目录下的来源目录,target 为生成路径。
618
- */
619
- const templateMap = {
620
- "tsup": {
621
- source: "tsup",
622
- target: "packages/tsup"
623
- },
624
- "tsdown": {
625
- source: "tsdown",
626
- target: "packages/tsdown"
627
- },
628
- "unbuild": {
629
- source: "unbuild",
630
- target: "packages/unbuild"
631
- },
632
- "vue-lib": {
633
- source: "vue-lib",
634
- target: "packages/vue-lib"
635
- },
636
- "hono-server": {
637
- source: "server",
638
- target: "apps/server"
639
- },
640
- "vue-hono": {
641
- source: "client",
642
- target: "apps/client"
643
- },
644
- "vitepress": {
645
- source: "vitepress",
646
- target: "apps/website"
647
- },
648
- "cli": {
649
- source: "cli",
650
- target: "apps/cli"
651
- }
652
- };
653
- function normalizeTemplateDefinition(value) {
654
- if (typeof value === "string") return {
655
- source: value,
656
- target: value
657
- };
658
- return value;
659
- }
660
- const defaultTemplate = "unbuild";
661
- /**
662
- * 交互式选择模板时的默认选项列表。
663
- */
664
- const baseChoices = [
665
- {
666
- name: "unbuild 打包",
667
- value: "unbuild"
668
- },
669
- {
670
- name: "tsup 打包",
671
- value: "tsup"
672
- },
673
- {
674
- name: "tsdown 打包",
675
- value: "tsdown"
676
- },
677
- {
678
- name: "vue 组件",
679
- value: "vue-lib"
680
- },
681
- {
682
- name: "vue hono 全栈",
683
- value: "vue-hono"
684
- },
685
- {
686
- name: "hono 模板",
687
- value: "hono-server"
688
- },
689
- {
690
- name: "vitepress 文档",
691
- value: "vitepress"
692
- },
693
- {
694
- name: "cli 模板",
695
- value: "cli"
696
- }
697
- ];
698
- /**
699
- * 若配置中提供 choices 则优先使用,否则退回默认预设。
700
- */
701
- function getCreateChoices(choices) {
702
- if (choices?.length) return choices;
703
- return [...baseChoices];
704
- }
705
- /**
706
- * 合并内置与自定义模板映射,允许扩展新的模板类型。
707
- */
708
- function getTemplateMap(extra) {
709
- const base = Object.fromEntries(Object.entries(templateMap).map(([key, value]) => [key, normalizeTemplateDefinition(value)]));
710
- if (extra && Object.keys(extra).length) for (const [key, value] of Object.entries(extra)) base[key] = normalizeTemplateDefinition(value);
711
- return base;
712
- }
713
- async function applyGitMetadata(pkgJson, repoDir, targetDir) {
714
- try {
715
- const git = new GitClient({ baseDir: repoDir });
716
- const repoName = await git.getRepoName();
717
- if (!repoName) return;
718
- setByPath(pkgJson, ["bugs", "url"], `https://github.com/${repoName}/issues`);
719
- const repository = {
720
- type: "git",
721
- url: `git+https://github.com/${repoName}.git`
722
- };
723
- const directoryBase = await git.getRepoRoot() ?? repoDir;
724
- const relative = path.relative(directoryBase, targetDir);
725
- if (relative && relative !== ".") repository.directory = relative.split(path.sep).join("/");
726
- setByPath(pkgJson, "repository", repository);
727
- const gitUser = await git.getUser();
728
- if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
729
- } catch {}
730
- }
731
- /**
732
- * 根据提供的参数或配置生成新工程目录,并可自动改写 package.json。
733
- */
734
- async function createNewProject(options) {
735
- const cwd = options?.cwd ?? process.cwd();
736
- const createConfig = await resolveCommandConfig("create", cwd);
737
- const renameJson = options?.renameJson ?? createConfig?.renameJson ?? false;
738
- const rawName = options?.name ?? createConfig?.name;
739
- const name = typeof rawName === "string" ? rawName.trim() : void 0;
740
- const requestedTemplate = options?.type ?? createConfig?.type ?? createConfig?.defaultTemplate ?? "unbuild";
741
- const templateDefinitions = getTemplateMap(createConfig?.templateMap);
742
- const templatesRoot = createConfig?.templatesDir ? path.resolve(cwd, createConfig.templatesDir) : templatesDir;
743
- const fallbackTemplate = createConfig?.defaultTemplate ?? "unbuild";
744
- const bundlerName = typeof requestedTemplate === "string" && templateDefinitions[requestedTemplate] ? requestedTemplate : fallbackTemplate;
745
- const templateDefinition = templateDefinitions[bundlerName];
746
- if (!templateDefinition) throw new Error(`未找到名为 ${bundlerName} 的模板,请检查 monorepo.config.ts`);
747
- const from = path.join(templatesRoot, templateDefinition.source);
748
- const targetName = name && name.length > 0 ? name : templateDefinition.target;
749
- const to = path.join(cwd, targetName);
750
- if (await fs.pathExists(to)) throw new Error(`${pc.red("目标目录已存在")}: ${path.relative(cwd, to)}`);
751
- await fs.ensureDir(to);
752
- const sourceJsonPath = path.resolve(from, "package.json");
753
- const hasPackageJson = await fs.pathExists(sourceJsonPath);
754
- await scaffoldTemplate({
755
- sourceDir: from,
756
- targetDir: to,
757
- skipRootBasenames: ["package.json"]
758
- });
759
- if (hasPackageJson) {
760
- const sourceJson = await fs.readJson(sourceJsonPath);
761
- setByPath(sourceJson, "version", "0.0.0");
762
- setByPath(sourceJson, "name", name?.startsWith("@") ? name : path.basename(targetName));
763
- await applyGitMetadata(sourceJson, cwd, to);
764
- await fs.outputJson(path.resolve(to, renameJson ? "package.mock.json" : "package.json"), sourceJson, { spaces: 2 });
765
- }
766
- logger.success(`${pc.bgGreenBright(pc.white(`[${bundlerName}]`))} ${targetName} 项目创建成功!`);
767
- }
768
- //#endregion
769
- //#region src/core/context.ts
770
- /**
771
- * 构建命令执行上下文,封装常用的工作区、Git、配置等信息。
772
- */
773
- async function createContext(cwd) {
774
- const { packages, workspaceDir } = await getWorkspaceData(cwd);
775
- const git = new GitClient({ baseDir: workspaceDir });
776
- const workspaceFilepath = path.resolve(workspaceDir, "pnpm-workspace.yaml");
777
- return {
778
- cwd,
779
- git,
780
- gitUrl: await git.getGitUrl(),
781
- gitUser: await git.getUser(),
782
- workspaceDir,
783
- workspaceFilepath,
784
- packages,
785
- config: await loadMonorepoConfig(workspaceDir)
786
- };
787
- }
788
- //#endregion
789
- //#region src/commands/init/setChangeset.ts
790
- /**
791
- * 将 changeset 配置中的仓库地址指向当前项目,方便自动生成变更日志链接。
792
- */
793
- async function setChangeset_default(ctx) {
794
- const { gitUrl, workspaceFilepath } = ctx;
795
- if (gitUrl && await fs.exists(workspaceFilepath)) {
796
- const changesetConfigPath = path.resolve(path.dirname(workspaceFilepath), ".changeset/config.json");
797
- if (await fs.exists(changesetConfigPath)) {
798
- const changesetConfig = await fs.readJson(changesetConfigPath);
799
- if (gitUrl.full_name) {
800
- setByPath(changesetConfig, "changelog.1.repo", gitUrl.full_name);
801
- await fs.outputJson(changesetConfigPath, changesetConfig, { spaces: 2 });
802
- }
803
- }
804
- }
805
- }
806
- //#endregion
807
- //#region src/commands/init/setIssueTemplateConfig.ts
808
- /**
809
- * 同步 Issue 模版里的 discussions 链接到当前仓库。
810
- */
811
- async function setIssueTemplateConfig_default(ctx) {
812
- const repoName = ctx.gitUrl?.full_name;
813
- if (!repoName) return;
814
- const configPath = path.resolve(ctx.cwd, ".github/ISSUE_TEMPLATE/config.yml");
815
- if (!await fs.pathExists(configPath)) return;
816
- const source = await fs.readFile(configPath, "utf8");
817
- const next = updateIssueTemplateConfig(source, repoName);
818
- if (next !== source) await fs.writeFile(configPath, next, "utf8");
819
- }
820
- //#endregion
821
- //#region src/commands/init/setPkgJson.ts
822
- /**
823
- * 根据当前仓库信息同步 package.json 的仓库、作者等字段。
824
- */
825
- async function setPkgJson_default(ctx) {
826
- const { gitUrl, gitUser, packages, cwd, workspaceFilepath } = ctx;
827
- const workspaceExists = await fs.pathExists(workspaceFilepath);
828
- if (gitUrl && workspaceExists) await Promise.all(packages.map(async (pkg) => {
829
- if (!await fs.pathExists(pkg.pkgJsonPath)) return;
830
- const pkgJson = JSON.parse(JSON.stringify(pkg.manifest));
831
- const directory = path.relative(cwd, pkg.rootDir);
832
- setByPath(pkgJson, ["bugs", "url"], `https://github.com/${gitUrl.full_name}/issues`);
833
- const repository = {
834
- type: "git",
835
- url: `git+https://github.com/${gitUrl.full_name}.git`
836
- };
837
- if (directory) repository.directory = directory;
838
- setByPath(pkgJson, "repository", repository);
839
- if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
840
- const nextContent = `${JSON.stringify(pkgJson, void 0, 2)}\n`;
841
- if (await fs.readFile(pkg.pkgJsonPath, "utf8") !== nextContent) await fs.writeFile(pkg.pkgJsonPath, nextContent, "utf8");
842
- }));
843
- }
844
- //#endregion
845
- //#region src/commands/init/setReadme.ts
846
- async function getRows(ctx) {
847
- const { packages, gitUrl, gitUser, cwd } = ctx;
848
- const rows = [];
849
- if (gitUrl) rows.push(`# ${gitUrl.name}\n`);
850
- rows.push("## Packages\n");
851
- const sortedPackages = packages.toSorted((a, b) => {
852
- const left = a.manifest.name ?? "";
853
- const right = b.manifest.name ?? "";
854
- return left.localeCompare(right);
855
- });
856
- for (const pkg of sortedPackages) {
857
- const p = path.relative(cwd, pkg.rootDirRealPath);
858
- if (p) {
859
- const description = pkg.manifest.description ? `- ${pkg.manifest.description}` : "";
860
- rows.push(`- [${pkg.manifest.name}](${p}) ${description}`);
861
- }
862
- }
863
- if (gitUrl) {
864
- rows.push("\n## Contributing\n");
865
- rows.push("Contributions Welcome! You can contribute in the following ways.");
866
- rows.push("");
867
- rows.push("- Create an Issue - Propose a new feature. Report a bug.");
868
- rows.push("- Pull Request - Fix a bug and typo. Refactor the code.");
869
- rows.push("- Create third-party middleware - Instruct below.");
870
- rows.push("- Share - Share your thoughts on the Blog, X, and others.");
871
- rows.push(`- Make your application - Please try to use ${gitUrl.name}.`);
872
- rows.push("");
873
- rows.push("For more details, see [CONTRIBUTING.md](CONTRIBUTING.md).");
874
- rows.push("\n## Contributors\n");
875
- rows.push(`Thanks to [all contributors](https://github.com/${gitUrl.full_name}/graphs/contributors)!`);
876
- }
877
- rows.push("\n## Authors\n");
878
- if (gitUser?.name && gitUser?.email) rows.push(`${gitUser.name} <${gitUser.email}>`);
879
- rows.push("\n## License\n");
880
- rows.push("Distributed under the MIT License. See [LICENSE](LICENSE) for more information.");
881
- return rows;
882
- }
883
- /**
884
- * 生成标准化的 README 草稿,列出所有子包并补充贡献者、作者信息。
885
- */
886
- async function setReadme_default(ctx) {
887
- const rows = await getRows(ctx);
888
- await fs.writeFile(path.resolve(ctx.cwd, "README.md"), `${rows.join("\n")}\n`);
889
- }
890
- //#endregion
891
- //#region src/commands/init/index.ts
892
- /**
893
- * 初始化命令入口,根据配置逐步生成基础文件。
894
- */
895
- async function init(cwd) {
896
- const ctx = await createContext(cwd);
897
- const initConfig = ctx.config.commands?.init ?? {};
898
- if (!initConfig.skipChangeset) await setChangeset_default(ctx);
899
- if (!initConfig.skipPkgJson) await setPkgJson_default(ctx);
900
- if (!initConfig.skipReadme) await setReadme_default(ctx);
901
- if (!initConfig.skipIssueTemplateConfig) await setIssueTemplateConfig_default(ctx);
902
- }
903
- //#endregion
904
- //#region src/commands/mirror/sources.ts
905
- const chinaMirrorsEnvs = {
906
- COREPACK_NPM_REGISTRY: "https://registry.npmmirror.com",
907
- EDGEDRIVER_CDNURL: "https://npmmirror.com/mirrors/edgedriver",
908
- NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
909
- NVM_NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
910
- PHANTOMJS_CDNURL: "https://cdn.npmmirror.com/binaries/phantomjs",
911
- CHROMEDRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/chromedriver",
912
- OPERADRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/operadriver",
913
- CYPRESS_DOWNLOAD_PATH_TEMPLATE: "https://cdn.npmmirror.com/binaries/cypress/${version}/${platform}-${arch}/cypress.zip",
914
- ELECTRON_MIRROR: "https://cdn.npmmirror.com/binaries/electron/",
915
- ELECTRON_BUILDER_BINARIES_MIRROR: "https://cdn.npmmirror.com/binaries/electron-builder-binaries/",
916
- SASS_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-sass",
917
- SWC_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-swc",
918
- NWJS_URLBASE: "https://cdn.npmmirror.com/binaries/nwjs/v",
919
- PUPPETEER_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
920
- PUPPETEER_DOWNLOAD_BASE_URL: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
921
- PLAYWRIGHT_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/playwright",
922
- SENTRYCLI_CDNURL: "https://cdn.npmmirror.com/binaries/sentry-cli",
923
- SAUCECTL_INSTALL_BINARY_MIRROR: "https://cdn.npmmirror.com/binaries/saucectl",
924
- RE2_DOWNLOAD_MIRROR: "https://cdn.npmmirror.com/binaries/node-re2",
925
- RE2_DOWNLOAD_SKIP_PATH: "true",
926
- PRISMA_ENGINES_MIRROR: "https://cdn.npmmirror.com/binaries/prisma",
927
- npm_config_better_sqlite3_binary_host: "https://cdn.npmmirror.com/binaries/better-sqlite3",
928
- npm_config_keytar_binary_host: "https://cdn.npmmirror.com/binaries/keytar",
929
- npm_config_sharp_binary_host: "https://cdn.npmmirror.com/binaries/sharp",
930
- npm_config_sharp_libvips_binary_host: "https://cdn.npmmirror.com/binaries/sharp-libvips",
931
- npm_config_robotjs_binary_host: "https://cdn.npmmirror.com/binaries/robotjs"
932
- };
933
- //#endregion
934
- //#region src/commands/mirror/utils.ts
935
- /**
936
- * 在 vscode 里面设置镜像下载地址的环境变量,避免下载缓慢
937
- */
938
- function setMirror(obj, envs = chinaMirrorsEnvs) {
939
- const platforms = [
940
- "linux",
941
- "windows",
942
- "osx"
943
- ];
944
- const prefix = "terminal.integrated.env";
945
- if (typeof obj === "object" && obj) for (const platform of platforms) setByPath(obj, [prefix, platform].join(".").replaceAll(".", "\\."), envs);
946
- }
947
- //#endregion
948
- //#region src/commands/mirror/binaryMirror.ts
949
- /**
950
- * 根据中国大陆镜像源,自动向 VSCode settings.json 注入终端环境变量。
951
- */
952
- async function setVscodeBinaryMirror(cwd) {
953
- const mirrorConfig = await resolveCommandConfig("mirror", cwd);
954
- const targetJsonPath = path.resolve(cwd, ".vscode/settings.json");
955
- await fs.ensureFile(targetJsonPath);
956
- const json = parse(await fs.readFile(targetJsonPath, "utf8"), void 0, false);
957
- const env = mirrorConfig?.env ? {
958
- ...chinaMirrorsEnvs,
959
- ...mirrorConfig.env
960
- } : chinaMirrorsEnvs;
961
- json && typeof json === "object" && setMirror(json, env);
962
- await fs.writeFile(targetJsonPath, `${stringify(json, void 0, 2)}\n`, "utf8");
963
- }
964
- //#endregion
965
- //#region src/commands/sync.ts
966
- function renderCommand(template, pkgName) {
967
- return template.replaceAll("{name}", pkgName);
968
- }
969
- /**
970
- * 批量执行 `cnpm sync`(或自定义命令),将所有包同步到 npmmirror。
971
- */
972
- async function syncNpmMirror(cwd, options) {
973
- const { concurrency: configConcurrency, command: configCommand, packages: packageFilter, ...workspaceOverrides } = await resolveCommandConfig("sync", cwd) ?? {};
974
- const { packages, workspaceDir } = await getWorkspaceData(cwd, {
975
- ...workspaceOverrides,
976
- ...options ?? {}
977
- });
978
- logger.info(`[当前工作区Repo]:\n${packages.map((x) => `- ${pc.green(x.manifest.name)} : ${path.relative(workspaceDir, x.rootDir)}`).join("\n")}\n`);
979
- const set = new Set(packages.map((x) => x.manifest.name));
980
- if (packageFilter?.length) {
981
- for (const name of [...set]) if (!name || !packageFilter.includes(name)) set.delete(name);
982
- }
983
- logger.info(`[即将同步的包]:\n${Array.from(set, (x) => `- ${pc.green(x ?? "")}`).join("\n")}\n`);
984
- const queue = new PQueue({ concurrency: configConcurrency ?? Math.max(os.cpus().length, 1) });
985
- const template = configCommand ?? "cnpm sync {name}";
986
- const tasks = [];
987
- for (const pkgName of set) {
988
- if (!pkgName) continue;
989
- tasks.push(queue.add(async () => {
990
- return execaCommand(renderCommand(template, pkgName), { stdio: "inherit" });
991
- }));
992
- }
993
- await Promise.all(tasks);
994
- }
995
- //#endregion
996
- //#region src/commands/upgrade/agents.ts
997
- const crlfPattern$1 = /\r\n/g;
998
- const h2HeadingPrefixPattern = /^##\s+/;
999
- function normalizeEol$1(input) {
1000
- return input.replace(crlfPattern$1, "\n");
1001
- }
1002
- function normalizeComparableContent(input) {
1003
- return normalizeEol$1(input).trimEnd();
1004
- }
1005
- function normalizeHeadingKey(line) {
1006
- return line.replace(h2HeadingPrefixPattern, "").trim().toLowerCase();
1007
- }
1008
- function trimEdgeEmptyLines(lines) {
1009
- const next = [...lines];
1010
- while (next.length) {
1011
- const first = next[0];
1012
- if (first === void 0 || first.trim().length > 0) break;
1013
- next.shift();
1014
- }
1015
- while (next.length) {
1016
- const last = next.at(-1);
1017
- if (last === void 0 || last.trim().length > 0) break;
1018
- next.pop();
1019
- }
1020
- return next;
1021
- }
1022
- function parseMarkdownByH2(content) {
1023
- const lines = normalizeEol$1(content).split("\n");
1024
- const preamble = [];
1025
- const sections = [];
1026
- let current;
1027
- for (const line of lines) {
1028
- if (h2HeadingPrefixPattern.test(line)) {
1029
- if (current) sections.push(current);
1030
- current = {
1031
- key: normalizeHeadingKey(line),
1032
- lines: [line]
1033
- };
1034
- continue;
1035
- }
1036
- if (current) {
1037
- current.lines.push(line);
1038
- continue;
1039
- }
1040
- preamble.push(line);
1041
- }
1042
- if (current) sections.push(current);
1043
- return {
1044
- preamble,
1045
- sections
1046
- };
1047
- }
1048
- function mergePlainText(source, target) {
1049
- const sourceLines = trimEdgeEmptyLines(normalizeEol$1(source).split("\n"));
1050
- const result = trimEdgeEmptyLines(normalizeEol$1(target).split("\n"));
1051
- const seen = new Set(result);
1052
- for (const line of sourceLines) {
1053
- if (!line.trim()) continue;
1054
- if (seen.has(line)) continue;
1055
- seen.add(line);
1056
- result.push(line);
1057
- }
1058
- return `${result.join("\n")}\n`;
1059
- }
1060
- function getSectionSignature(section) {
1061
- return `${section.key}\n${trimEdgeEmptyLines(section.lines).join("\n")}`;
1062
- }
1063
- /**
1064
- * Merge AGENTS instructions by keeping existing sections and filling missing sections
1065
- * from source defaults. This avoids destructive overwrite while still syncing updates.
1066
- */
1067
- function mergeAgentsMarkdown(source, target) {
1068
- const sourceParsed = parseMarkdownByH2(source);
1069
- const targetParsed = parseMarkdownByH2(target);
1070
- if (!sourceParsed.sections.length || !targetParsed.sections.length) return mergePlainText(source, target);
1071
- const sourceSectionKeys = new Set(sourceParsed.sections.map((section) => section.key));
1072
- const targetSectionMap = new Map(targetParsed.sections.map((section) => [section.key, section]));
1073
- const mergedSections = [];
1074
- for (const section of sourceParsed.sections) mergedSections.push(targetSectionMap.get(section.key) ?? section);
1075
- const seenTargetOnlySectionSignatures = /* @__PURE__ */ new Set();
1076
- for (const section of targetParsed.sections) if (!sourceSectionKeys.has(section.key)) {
1077
- const signature = getSectionSignature(section);
1078
- if (seenTargetOnlySectionSignatures.has(signature)) continue;
1079
- seenTargetOnlySectionSignatures.add(signature);
1080
- mergedSections.push(section);
1081
- }
1082
- const preamble = trimEdgeEmptyLines(targetParsed.preamble.length ? targetParsed.preamble : sourceParsed.preamble);
1083
- const blocks = [];
1084
- if (preamble.length) blocks.push(preamble.join("\n"));
1085
- for (const section of mergedSections) blocks.push(trimEdgeEmptyLines(section.lines).join("\n"));
1086
- return `${blocks.filter(Boolean).join("\n\n")}\n`;
1087
- }
1088
- /**
1089
- * Compare AGENTS markdown with normalized EOL and trailing newline differences ignored.
1090
- */
1091
- function isAgentsMarkdownEquivalent(left, right) {
1092
- return normalizeComparableContent(left) === normalizeComparableContent(right);
1093
- }
1094
- //#endregion
1095
- //#region src/commands/upgrade/overwrite.ts
1096
- function asBuffer(data) {
1097
- return typeof data === "string" ? Buffer.from(data) : data;
1098
- }
1099
- async function evaluateWriteIntent(targetPath, options) {
1100
- const { skipOverwrite, source } = options;
1101
- if (!await fs.pathExists(targetPath)) return {
1102
- type: "write",
1103
- reason: "missing"
1104
- };
1105
- if (skipOverwrite) return {
1106
- type: "skip",
1107
- reason: "skipOverwrite"
1108
- };
1109
- const src = asBuffer(source);
1110
- let destSize = 0;
1111
- try {
1112
- destSize = (await fs.stat(targetPath)).size;
1113
- } catch {
1114
- return {
1115
- type: "write",
1116
- reason: "missing"
1117
- };
1118
- }
1119
- if (destSize !== src.length) return {
1120
- type: "prompt",
1121
- reason: "changed"
1122
- };
1123
- if (!isFileChanged(src, await fs.readFile(targetPath))) return {
1124
- type: "skip",
1125
- reason: "identical"
1126
- };
1127
- return {
1128
- type: "prompt",
1129
- reason: "changed"
1130
- };
1131
- }
1132
- async function scheduleOverwrite(intent, options) {
1133
- const { relPath, targetPath, action, pending } = options;
1134
- if (intent.type === "write") {
1135
- await action();
1136
- return;
1137
- }
1138
- if (intent.type === "prompt") pending.push({
1139
- relPath,
1140
- targetPath,
1141
- action
1142
- });
1143
- }
1144
- async function flushPendingOverwrites(pending) {
1145
- if (!pending.length) return;
1146
- const selected = await checkbox({
1147
- message: "检测到以下文件内容与当前仓库不同,选择需要覆盖的文件",
1148
- choices: pending.map((item) => ({
1149
- name: pc.greenBright(item.relPath),
1150
- value: item.targetPath,
1151
- checked: false
1152
- })),
1153
- loop: false
1154
- });
1155
- const selectedSet = new Set(selected);
1156
- for (const item of pending) if (selectedSet.has(item.targetPath)) await item.action();
1157
- }
1158
- const scriptsEntries = Object.entries({
1159
- "script:init": "monorepo init",
1160
- "script:sync": "monorepo sync",
1161
- "script:clean": "monorepo clean",
1162
- "script:mirror": "monorepo mirror",
1163
- "commitlint": "commitlint --edit"
1164
- });
1165
- //#endregion
1166
- //#region src/commands/upgrade/pkg-json.ts
1167
- const NON_OVERRIDABLE_PREFIXES = ["workspace:", "catalog:"];
1168
- function parseVersion(input) {
1169
- if (typeof input !== "string" || input.trim().length === 0) return null;
1170
- try {
1171
- return minVersion(input) ?? coerce(input);
1172
- } catch {
1173
- return null;
1174
- }
1175
- }
1176
- function hasNonOverridablePrefix(version) {
1177
- if (typeof version !== "string") return false;
1178
- return NON_OVERRIDABLE_PREFIXES.some((prefix) => version.startsWith(prefix));
1179
- }
1180
- function shouldAssignVersion(currentVersion, nextVersion) {
1181
- if (typeof currentVersion !== "string" || currentVersion.trim().length === 0) return true;
1182
- if (currentVersion === nextVersion) return false;
1183
- const current = parseVersion(currentVersion);
1184
- const next = parseVersion(nextVersion);
1185
- if (!current || !next) return true;
1186
- return !gte(current, next);
1187
- }
1188
- /**
1189
- * 将内置 package.json 内容合并进目标工程:
1190
- * - 同步依赖(保留 workspace: 前缀的版本)
1191
- * - 确保 @icebreakers/monorepo 使用最新版本
1192
- * - 写入预置脚本
1193
- */
1194
- function setPkgJson(sourcePkgJson, targetPkgJson, options) {
1195
- const packageManager = sourcePkgJson.packageManager ?? "";
1196
- const sourceDeps = sourcePkgJson.dependencies ?? {};
1197
- const sourceDevDeps = sourcePkgJson.devDependencies ?? {};
1198
- const targetDeps = { ...targetPkgJson.dependencies ?? {} };
1199
- const targetDevDeps = { ...targetPkgJson.devDependencies ?? {} };
1200
- if (packageManager) targetPkgJson.packageManager = packageManager;
1201
- for (const [depName, depVersion] of Object.entries(sourceDeps)) {
1202
- if (typeof depVersion !== "string") continue;
1203
- const targetVersion = targetDeps[depName];
1204
- if (hasNonOverridablePrefix(targetVersion)) continue;
1205
- if (shouldAssignVersion(targetVersion, depVersion)) targetDeps[depName] = depVersion;
1206
- }
1207
- if (Object.keys(targetDeps).length) targetPkgJson.dependencies = targetDeps;
1208
- for (const [depName, depVersion] of Object.entries(sourceDevDeps)) {
1209
- if (typeof depVersion !== "string") continue;
1210
- if (depName === name) {
1211
- const nextVersion = `^${version}`;
1212
- const targetVersion = targetDevDeps[depName];
1213
- if (!hasNonOverridablePrefix(targetVersion) && shouldAssignVersion(targetVersion, nextVersion)) targetDevDeps[depName] = nextVersion;
1214
- } else {
1215
- const targetVersion = targetDevDeps[depName];
1216
- if (hasNonOverridablePrefix(targetVersion)) continue;
1217
- if (shouldAssignVersion(targetVersion, depVersion)) targetDevDeps[depName] = depVersion;
1218
- }
1219
- }
1220
- if (Object.keys(targetDevDeps).length) targetPkgJson.devDependencies = targetDevDeps;
1221
- const scriptPairs = options?.scripts ? Object.entries(options.scripts) : scriptsEntries;
1222
- if (scriptPairs.length) {
1223
- const scripts = { ...targetPkgJson.scripts ?? {} };
1224
- for (const [scriptName, scriptCmd] of scriptPairs) scripts[scriptName] = scriptCmd;
1225
- targetPkgJson.scripts = scripts;
1226
- }
1227
- }
1228
- //#endregion
1229
- //#region src/commands/upgrade/workspace.ts
1230
- function isPlainObject(value) {
1231
- return typeof value === "object" && value !== null && !Array.isArray(value);
1232
- }
1233
- function normalizeQuotedString(value) {
1234
- const trimmed = value.trim();
1235
- const first = trimmed[0];
1236
- if ((first === "'" || first === "\"") && trimmed.endsWith(first)) return trimmed.slice(1, -1);
1237
- return trimmed;
1238
- }
1239
- function normalizeWorkspaceManifest(manifest) {
1240
- if (isPlainObject(manifest)) return { ...manifest };
1241
- return {};
1242
- }
1243
- function mergeUniqueArray(target, source) {
1244
- const seen = new Set(target.map((item) => {
1245
- return typeof item === "string" ? normalizeQuotedString(item) : item;
1246
- }));
1247
- const result = [...target];
1248
- for (const item of source) {
1249
- const key = typeof item === "string" ? normalizeQuotedString(item) : item;
1250
- if (!seen.has(key)) {
1251
- seen.add(key);
1252
- result.push(item);
1253
- }
1254
- }
1255
- return result;
1256
- }
1257
- /**
1258
- * Merge pnpm workspace manifests by filling missing fields only.
1259
- * Existing values take precedence; arrays are deduped while keeping target order.
1260
- */
1261
- function mergeWorkspaceManifest(source, target) {
1262
- const normalizedSource = normalizeWorkspaceManifest(source);
1263
- const normalizedTarget = normalizeWorkspaceManifest(target);
1264
- const result = { ...normalizedTarget };
1265
- for (const [key, value] of Object.entries(normalizedSource)) {
1266
- const current = normalizedTarget[key];
1267
- if (current === void 0) {
1268
- result[key] = value;
1269
- continue;
1270
- }
1271
- if (Array.isArray(current) && Array.isArray(value)) {
1272
- result[key] = mergeUniqueArray(current, value);
1273
- continue;
1274
- }
1275
- if (isPlainObject(current) && isPlainObject(value)) {
1276
- result[key] = mergeWorkspaceManifest(value, current);
1277
- continue;
1278
- }
1279
- result[key] = current;
1280
- }
1281
- return result;
1282
- }
1283
- //#endregion
1284
- //#region src/commands/upgrade/index.ts
1285
- const crlfPattern = /\r\n/g;
1286
- function normalizeEol(input) {
1287
- return input.replace(crlfPattern, "\n");
1288
- }
1289
- function normalizeGitignoreLine(line) {
1290
- const trimmed = line.trim();
1291
- if (!trimmed) return "";
1292
- if (trimmed.startsWith("#")) return `#${trimmed.slice(1).trim()}`;
1293
- return trimmed;
1294
- }
1295
- function isTextEquivalent(left, right) {
1296
- return normalizeEol(left).trimEnd() === normalizeEol(right).trimEnd();
1297
- }
1298
- function mergeGitignore(source, target) {
1299
- const sourceLines = normalizeEol(source).split("\n");
1300
- const result = normalizeEol(target).split("\n");
1301
- const seen = new Set(result.map((line) => normalizeGitignoreLine(line)).filter(Boolean));
1302
- for (const line of sourceLines) {
1303
- const normalized = normalizeGitignoreLine(line);
1304
- if (!normalized || seen.has(normalized)) continue;
1305
- seen.add(normalized);
1306
- result.push(line);
1307
- }
1308
- while (result.length) {
1309
- const last = result.at(-1);
1310
- if (last === void 0 || last.trim().length > 0) break;
1311
- result.pop();
1312
- }
1313
- return `${result.join("\n")}\n`;
1314
- }
1315
- /**
1316
- * 将 assets 目录的模版文件同步到工程中,实现一键升级脚手架能力。
1317
- */
1318
- async function upgradeMonorepo(opts) {
1319
- await ensureTemplateAssetsPrepared();
1320
- const cwd = opts.cwd ?? process.cwd();
1321
- const upgradeConfig = await resolveCommandConfig("upgrade", cwd);
1322
- const merged = {
1323
- cwd,
1324
- outDir: "",
1325
- ...upgradeConfig ?? {},
1326
- ...opts
1327
- };
1328
- const outDir = merged.outDir ?? "";
1329
- const absOutDir = path.isAbsolute(outDir) ? outDir : path.join(cwd, outDir);
1330
- const repoName = await new GitClient({ baseDir: cwd }).getRepoName();
1331
- const useCoreAssets = merged.core ?? false;
1332
- merged.core = useCoreAssets;
1333
- const baseTargets = getAssetTargets(useCoreAssets);
1334
- const configTargets = upgradeConfig?.targets ?? [];
1335
- const mergeTargets = upgradeConfig?.mergeTargets;
1336
- let targets = configTargets.length ? mergeTargets === false ? [...configTargets] : [...new Set([...baseTargets, ...configTargets])] : baseTargets;
1337
- if (merged.interactive) targets = await checkbox({
1338
- message: "选择你需要的文件",
1339
- choices: targets.map((x) => {
1340
- return {
1341
- value: x,
1342
- checked: true
1343
- };
1344
- })
1345
- });
1346
- const regexpArr = targets.map((x) => {
1347
- return new RegExp(`^${escapeStringRegexp(x)}`);
1348
- });
1349
- const skipChangesetMarkdown = upgradeConfig?.skipChangesetMarkdown ?? true;
1350
- const scriptOverrides = upgradeConfig?.scripts;
1351
- const skipOverwrite = merged.skipOverwrite;
1352
- const buildWriteIntentOptions = (source) => {
1353
- return skipOverwrite === void 0 ? { source } : {
1354
- skipOverwrite,
1355
- source
1356
- };
1357
- };
1358
- const pendingOverwrites = [];
1359
- for await (const file of klaw(assetsDir, { filter(p) {
1360
- return isMatch(toWorkspaceGitignorePath(path.relative(assetsDir, p)), regexpArr);
1361
- } })) {
1362
- if (!file.stats.isFile()) continue;
1363
- const relPath = toWorkspaceGitignorePath(path.relative(assetsDir, file.path));
1364
- if (skipChangesetMarkdown && relPath.startsWith(".changeset/") && relPath.endsWith(".md")) continue;
1365
- const targetPath = path.resolve(absOutDir, relPath);
1366
- try {
1367
- if (relPath === "package.json") {
1368
- if (!await fs.pathExists(targetPath)) continue;
1369
- const sourcePkgJson = await fs.readJson(file.path);
1370
- const targetPkgJson = await fs.readJson(targetPath);
1371
- setPkgJson(sourcePkgJson, targetPkgJson, scriptOverrides ? { scripts: scriptOverrides } : void 0);
1372
- const data = `${JSON.stringify(targetPkgJson, void 0, 2)}\n`;
1373
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1374
- const action = async () => {
1375
- await fs.outputFile(targetPath, data, "utf8");
1376
- logger.success(targetPath);
1377
- };
1378
- await scheduleOverwrite(intent, {
1379
- relPath,
1380
- targetPath,
1381
- action,
1382
- pending: pendingOverwrites
1383
- });
1384
- continue;
1385
- }
1386
- if (relPath === "pnpm-workspace.yaml") {
1387
- const sourceManifest = normalizeWorkspaceManifest(YAML.parse(await fs.readFile(file.path, "utf8")));
1388
- const exists = await fs.pathExists(targetPath);
1389
- const targetManifest = exists ? normalizeWorkspaceManifest(YAML.parse(await fs.readFile(targetPath, "utf8"))) : normalizeWorkspaceManifest({});
1390
- const mergedManifest = exists ? mergeWorkspaceManifest(sourceManifest, targetManifest) : sourceManifest;
1391
- const data = YAML.stringify(mergedManifest, { singleQuote: true });
1392
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1393
- const action = async () => {
1394
- await fs.outputFile(targetPath, data, "utf8");
1395
- logger.success(targetPath);
1396
- };
1397
- await scheduleOverwrite(intent, {
1398
- relPath,
1399
- targetPath,
1400
- action,
1401
- pending: pendingOverwrites
1402
- });
1403
- continue;
1404
- }
1405
- if (relPath === ".gitignore") {
1406
- const source = await fs.readFile(file.path, "utf8");
1407
- const exists = await fs.pathExists(targetPath);
1408
- const target = exists ? await fs.readFile(targetPath, "utf8") : "";
1409
- const data = exists ? mergeGitignore(source, target) : source;
1410
- if (exists && isTextEquivalent(target, data)) continue;
1411
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1412
- const action = async () => {
1413
- await fs.outputFile(targetPath, data, "utf8");
1414
- logger.success(targetPath);
1415
- };
1416
- await scheduleOverwrite(intent, {
1417
- relPath,
1418
- targetPath,
1419
- action,
1420
- pending: pendingOverwrites
1421
- });
1422
- continue;
1423
- }
1424
- if (relPath === "AGENTS.md") {
1425
- const source = await fs.readFile(file.path, "utf8");
1426
- const exists = await fs.pathExists(targetPath);
1427
- const target = exists ? await fs.readFile(targetPath, "utf8") : "";
1428
- const data = exists ? mergeAgentsMarkdown(source, target) : source;
1429
- if (exists && isAgentsMarkdownEquivalent(target, data)) continue;
1430
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1431
- const action = async () => {
1432
- await fs.outputFile(targetPath, data, "utf8");
1433
- logger.success(targetPath);
1434
- };
1435
- await scheduleOverwrite(intent, {
1436
- relPath,
1437
- targetPath,
1438
- action,
1439
- pending: pendingOverwrites
1440
- });
1441
- continue;
1442
- }
1443
- if (relPath === ".changeset/config.json" && repoName) {
1444
- const changesetJson = await fs.readJson(file.path);
1445
- setByPath(changesetJson, "changelog.1.repo", repoName);
1446
- const data = `${JSON.stringify(changesetJson, void 0, 2)}\n`;
1447
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1448
- const action = async () => {
1449
- await fs.outputFile(targetPath, data, "utf8");
1450
- logger.success(targetPath);
1451
- };
1452
- await scheduleOverwrite(intent, {
1453
- relPath,
1454
- targetPath,
1455
- action,
1456
- pending: pendingOverwrites
1457
- });
1458
- continue;
1459
- }
1460
- if (relPath === "LICENSE") {
1461
- const source = await fs.readFile(file.path);
1462
- const intent = await evaluateWriteIntent(targetPath, {
1463
- skipOverwrite: true,
1464
- source
1465
- });
1466
- const action = async () => {
1467
- await fs.outputFile(targetPath, source);
1468
- logger.success(targetPath);
1469
- };
1470
- await scheduleOverwrite(intent, {
1471
- relPath,
1472
- targetPath,
1473
- action,
1474
- pending: pendingOverwrites
1475
- });
1476
- continue;
1477
- }
1478
- if (relPath === ".github/ISSUE_TEMPLATE/config.yml") {
1479
- const data = updateIssueTemplateConfig(await fs.readFile(file.path, "utf8"), repoName);
1480
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
1481
- const action = async () => {
1482
- await fs.outputFile(targetPath, data);
1483
- logger.success(targetPath);
1484
- };
1485
- await scheduleOverwrite(intent, {
1486
- relPath,
1487
- targetPath,
1488
- action,
1489
- pending: pendingOverwrites
1490
- });
1491
- continue;
1492
- }
1493
- const source = await fs.readFile(file.path);
1494
- const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(source));
1495
- const action = async () => {
1496
- await fs.outputFile(targetPath, source);
1497
- logger.success(targetPath);
1498
- };
1499
- await scheduleOverwrite(intent, {
1500
- relPath,
1501
- targetPath,
1502
- action,
1503
- pending: pendingOverwrites
1504
- });
1505
- } catch (error) {
1506
- if (isIgnorableFsError(error)) continue;
1507
- throw error;
1508
- }
1509
- }
1510
- await flushPendingOverwrites(pendingOverwrites);
1511
- }
1512
- //#endregion
1513
- export { getWorkspaceData as $, toPublishGitignorePath as A, ensureDir as B, resolveCommandConfig as C, getFileHash as D, setByPath as E, generateAgenticTemplate as F, outputJSON as G, exists as H, generateAgenticTemplates as I, readJSON as J, outputJson as K, loadAgenticTasks as L, updateIssueTemplateConfig as M, createTimestampFolderName as N, isFileChanged as O, defaultAgenticBaseDir as P, writeJson as Q, logger as R, loadMonorepoConfig as S, isMatch as T, isIgnorableFsError as U, ensureFile as V, outputFile as W, remove as X, readJson as Y, writeJSON as Z, rootDir as _, createContext as a, version as b, getCreateChoices as c, cleanProjects as d, getWorkspacePackages as et, getSkillTargetPaths as f, packageDir as g, assetsDir as h, init as i, toWorkspaceGitignorePath as j, isGitignoreFile as k, getTemplateMap as l, syncSkills as m, syncNpmMirror as n, createNewProject as o, skillTargets as p, pathExists as q, setVscodeBinaryMirror as r, defaultTemplate as s, upgradeMonorepo as t, GitClient as tt, templateMap as u, templatesDir as v, escapeStringRegexp as w, defineMonorepoConfig as x, name as y, copy as z };