@lark-apaas/miaoda-cli 0.1.6 → 0.1.7-alpha.8d26572

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 (44) hide show
  1. package/dist/api/deploy/schemas.js +3 -0
  2. package/dist/cli/commands/app/index.js +69 -14
  3. package/dist/cli/commands/index.js +36 -1
  4. package/dist/cli/commands/skills/index.js +23 -7
  5. package/dist/cli/handlers/app/index.js +4 -1
  6. package/dist/cli/handlers/app/init.js +58 -9
  7. package/dist/cli/handlers/app/sync.js +266 -0
  8. package/dist/cli/handlers/plugin/plugin-local.js +1 -1
  9. package/dist/cli/handlers/skills/sync.js +8 -0
  10. package/dist/config/fullstack-cli-pin.js +13 -0
  11. package/dist/config/sync-configs/design-stack.js +98 -0
  12. package/dist/config/sync-configs/index.js +62 -0
  13. package/dist/config/sync-configs/nestjs-react-fullstack.js +177 -0
  14. package/dist/config/sync.js +14 -0
  15. package/dist/services/app/init/install.js +44 -13
  16. package/dist/services/app/init/template.js +23 -6
  17. package/dist/utils/coding-steering.js +107 -28
  18. package/dist/utils/file-ops.js +45 -0
  19. package/dist/utils/githooks.js +73 -0
  20. package/dist/utils/merge-json.js +63 -0
  21. package/dist/utils/platform-sync.js +160 -0
  22. package/dist/utils/sync-rule.js +295 -0
  23. package/package.json +7 -4
  24. package/upgrade/templates/README.md +34 -0
  25. package/upgrade/templates/design-stack/templates/.githooks/pre-commit +4 -0
  26. package/upgrade/templates/design-stack/templates/scripts/dev-local.js +84 -0
  27. package/upgrade/templates/design-stack/templates/scripts/dev.sh +24 -0
  28. package/upgrade/templates/design-stack/templates/scripts/hooks/run-precommit.js +37 -0
  29. package/upgrade/templates/nestjs-react-fullstack/templates/.githooks/pre-commit +4 -0
  30. package/upgrade/templates/nestjs-react-fullstack/templates/.gitignore.append +8 -0
  31. package/upgrade/templates/nestjs-react-fullstack/templates/.spark_project +16 -0
  32. package/upgrade/templates/nestjs-react-fullstack/templates/drizzle.config.ts +55 -0
  33. package/upgrade/templates/nestjs-react-fullstack/templates/helper/gen-openapi.ts +34 -0
  34. package/upgrade/templates/nestjs-react-fullstack/templates/nest-cli.json +25 -0
  35. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/build.sh +207 -0
  36. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/dev-local.js +113 -0
  37. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/dev.js +295 -0
  38. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/dev.sh +24 -0
  39. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/hooks/run-precommit.js +37 -0
  40. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/lint.js +150 -0
  41. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/prune-smart.js +330 -0
  42. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/run.sh +8 -0
  43. package/upgrade/templates/nestjs-react-fullstack/templates/server/global.d.ts +19 -0
  44. package/upgrade/templates/nestjs-react-fullstack/templates/tsconfig.node.json +5 -0
@@ -9,67 +9,146 @@ const node_path_1 = __importDefault(require("node:path"));
9
9
  const npm_pack_1 = require("../utils/npm-pack");
10
10
  const logger_1 = require("../utils/logger");
11
11
  const STEERING_PACKAGE = '@lark-apaas/coding-steering';
12
+ function inferMode() {
13
+ // process.env.SANDBOX_ID 非空 → 沙箱;其他(undefined / 空串)→ 本地
14
+ return process.env.SANDBOX_ID ? 'sandbox' : 'local';
15
+ }
12
16
  /**
13
- * 把 coding-steering 包内 _common/skills + <stack>/skills 同步到 <targetDir>/.agent/steering/skills/,
14
- * 同名 stack 子目录覆盖 _common。tech.md 存在时也同步到 .agent/steering/tech.md。
17
+ * 把 coding-steering 包内 <stack>/skills_common + 专有层(skills 或 skills_local)同步到
18
+ * user app。
19
+ *
20
+ * 包内目录约定(每个 stack 三层):
21
+ * <stack>/skills_common → 沙箱 + 本地都下发的共有层
22
+ * <stack>/skills → 沙箱专有(沙箱端 update-skills.sh / SANDBOX_ID 非空时拿)
23
+ * <stack>/skills_local → 本地专有(本地 dev / agent 环境拿)
24
+ *
25
+ * 下发组合(mode):
26
+ * mode='sandbox' → skills_common + skills
27
+ * mode='local' → skills_common + skills_local
28
+ *
29
+ * 目标路径形态(outputLayout):
30
+ * 'nested' (默认,向后兼容):拷到 .agent/skills/steering/<stack>/skills/,tech.md 同目录
31
+ * 'flat':拷到 .agents/skills/(平铺),tech.md → .agents/tech.md,并创建 .claude/skills
32
+ * 软链指向 ../.agents/skills 让 Claude Code 识别同一份
33
+ *
34
+ * 同名 skill 覆盖顺序:common < 专有(专有覆盖 common 同名)。mode 缺省按 SANDBOX_ID env
35
+ * 推断(沙箱平台运行时注入应用所属沙箱 ID;空 / undefined 则视为本地)。
15
36
  *
16
37
  * 纯本地 atom(pull npm package + 拷贝文件),不属于任何 cli 域;放在 utils 让
17
38
  * app init handler 与独立 skills sync handler 都能复用。
18
39
  */
19
40
  function syncCodingSteering(opts) {
20
41
  const logPrefix = opts.logPrefix ?? 'skills';
21
- (0, logger_1.log)(logPrefix, `Fetching ${STEERING_PACKAGE}@${opts.version ?? 'latest'}...`);
42
+ const effectiveVersion = opts.version ?? 'latest';
43
+ const mode = opts.mode ?? inferMode();
44
+ const layout = opts.outputLayout ?? 'nested';
45
+ (0, logger_1.log)(logPrefix, `Fetching ${STEERING_PACKAGE}@${effectiveVersion} (mode=${mode}, layout=${layout})...`);
22
46
  const fetched = (0, npm_pack_1.fetchNpmPackage)({
23
47
  packageName: STEERING_PACKAGE,
24
- version: opts.version,
48
+ version: effectiveVersion,
25
49
  });
26
50
  try {
27
51
  const steeringRoot = node_path_1.default.join(fetched.extractDir, 'steering');
28
52
  const stackDir = node_path_1.default.join(steeringRoot, opts.stack);
29
- const commonSkillsDir = node_path_1.default.join(steeringRoot, '_common', 'skills');
30
- // steering 落到 .agent/skills/steering/<stack>/。.agent/skills/ 是 agent skills 的
31
- // 公共容器,steering 是其中一个 producer,<stack> 再做命名空间隔离。内部仍保留
32
- // 包内 steering/<stack>/skills/ 的结构,便于按"包内子目录 → 本地子目录"一一对应排查。
33
- const dstRoot = node_path_1.default.join(opts.targetDir, '.agent', 'skills', 'steering', opts.stack);
34
- const dstSkillsDir = node_path_1.default.join(dstRoot, 'skills');
53
+ // 目标路径按 layout 切:
54
+ // nested → .agent/skills/steering/<stack>/{skills, tech.md}(老链路、stack 命名空间)
55
+ // flat → .agents/{skills, tech.md}(平铺,无 stack 命名空间,跟 .claude/skills 软链对齐)
56
+ const { dstSkillsDir, dstTechPath } = layout === 'flat'
57
+ ? {
58
+ dstSkillsDir: node_path_1.default.join(opts.targetDir, '.agents', 'skills'),
59
+ dstTechPath: node_path_1.default.join(opts.targetDir, '.agents', 'tech.md'),
60
+ }
61
+ : {
62
+ dstSkillsDir: node_path_1.default.join(opts.targetDir, '.agent', 'skills', 'steering', opts.stack, 'skills'),
63
+ dstTechPath: node_path_1.default.join(opts.targetDir, '.agent', 'skills', 'steering', opts.stack, 'tech.md'),
64
+ };
35
65
  node_fs_1.default.mkdirSync(dstSkillsDir, { recursive: true });
36
66
  let techSynced = false;
37
67
  const techSrc = node_path_1.default.join(stackDir, 'tech.md');
38
68
  if (node_fs_1.default.existsSync(techSrc)) {
39
- node_fs_1.default.copyFileSync(techSrc, node_path_1.default.join(dstRoot, 'tech.md'));
69
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(dstTechPath), { recursive: true });
70
+ node_fs_1.default.copyFileSync(techSrc, dstTechPath);
40
71
  techSynced = true;
41
72
  }
42
73
  const synced = [];
43
- // 先拷 _common/skills/,再拷 <stack>/skills/。stack 同名覆盖 common
44
- if (node_fs_1.default.existsSync(commonSkillsDir)) {
45
- for (const name of node_fs_1.default.readdirSync(commonSkillsDir)) {
46
- const src = node_path_1.default.join(commonSkillsDir, name);
47
- if (!node_fs_1.default.statSync(src).isDirectory())
48
- continue;
49
- copyDir(src, node_path_1.default.join(dstSkillsDir, name));
50
- synced.push(`_common/skills/${name}`);
51
- }
52
- }
53
- const stackSkillsDir = node_path_1.default.join(stackDir, 'skills');
54
- if (node_fs_1.default.existsSync(stackSkillsDir)) {
55
- for (const name of node_fs_1.default.readdirSync(stackSkillsDir)) {
56
- const src = node_path_1.default.join(stackSkillsDir, name);
74
+ // 顺序拷贝,后者覆盖前者:skills_common 铺底,专有层(skills 或 skills_local)覆盖同名
75
+ const exclusiveLayer = mode === 'sandbox' ? 'skills' : 'skills_local';
76
+ const layers = [
77
+ { dir: node_path_1.default.join(stackDir, 'skills_common'), label: `${opts.stack}/skills_common` },
78
+ { dir: node_path_1.default.join(stackDir, exclusiveLayer), label: `${opts.stack}/${exclusiveLayer}` },
79
+ ];
80
+ for (const layer of layers) {
81
+ if (!node_fs_1.default.existsSync(layer.dir))
82
+ continue;
83
+ for (const name of node_fs_1.default.readdirSync(layer.dir)) {
84
+ const src = node_path_1.default.join(layer.dir, name);
57
85
  if (!node_fs_1.default.statSync(src).isDirectory())
58
86
  continue;
59
87
  const dst = node_path_1.default.join(dstSkillsDir, name);
60
88
  if (node_fs_1.default.existsSync(dst))
61
89
  node_fs_1.default.rmSync(dst, { recursive: true, force: true });
62
90
  copyDir(src, dst);
63
- synced.push(`${opts.stack}/skills/${name}`);
91
+ synced.push(`${layer.label}/${name}`);
64
92
  }
65
93
  }
66
- (0, logger_1.log)(logPrefix, `Synced ${String(synced.length)} skill(s), tech.md ${techSynced ? 'yes' : 'no'}`);
67
- return { version: fetched.version, syncedSkills: synced, techSynced };
94
+ let claudeSkillsLink;
95
+ if (layout === 'flat') {
96
+ claudeSkillsLink = ensureClaudeSkillsSymlink(opts.targetDir, logPrefix);
97
+ }
98
+ (0, logger_1.log)(logPrefix, `Synced ${String(synced.length)} skill(s), tech.md ${techSynced ? 'yes' : 'no'} (mode=${mode}, layout=${layout})`);
99
+ return {
100
+ version: fetched.version,
101
+ syncedSkills: synced,
102
+ techSynced,
103
+ ...(claudeSkillsLink !== undefined ? { claudeSkillsLink } : {}),
104
+ };
68
105
  }
69
106
  finally {
70
107
  fetched.cleanup();
71
108
  }
72
109
  }
110
+ /**
111
+ * flat layout 下创建 `<targetDir>/.claude/skills` 软链 → `../.agents/skills`,让 Claude Code
112
+ * 默认的 skills 加载路径跟 user app 的 .agents/skills 是同一份内容。
113
+ *
114
+ * 用相对路径软链(不是 absolute)—— user app 移动目录 / clone 到别处不会断链。
115
+ *
116
+ * 处理 4 种已有状态:
117
+ * - 已是软链且指向对的:noop
118
+ * - 已是软链但指错地方:删旧的,建新的(updated)
119
+ * - 已是普通目录 / 文件:不覆盖,警告并跳过(conflict)—— 用户可能手动放了别的 skills
120
+ * - 不存在:建新的(created)
121
+ */
122
+ function ensureClaudeSkillsSymlink(targetDir, logPrefix) {
123
+ const linkPath = node_path_1.default.join(targetDir, '.claude', 'skills');
124
+ const linkTarget = node_path_1.default.join('..', '.agents', 'skills');
125
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(linkPath), { recursive: true });
126
+ let existing = null;
127
+ try {
128
+ existing = node_fs_1.default.lstatSync(linkPath);
129
+ }
130
+ catch (err) {
131
+ if (err.code !== 'ENOENT')
132
+ throw err;
133
+ }
134
+ if (existing === null) {
135
+ node_fs_1.default.symlinkSync(linkTarget, linkPath, 'dir');
136
+ (0, logger_1.log)(logPrefix, ` ✓ .claude/skills → ${linkTarget} (symlink created)`);
137
+ return 'created';
138
+ }
139
+ if (existing.isSymbolicLink()) {
140
+ const current = node_fs_1.default.readlinkSync(linkPath);
141
+ if (current === linkTarget) {
142
+ return 'noop';
143
+ }
144
+ node_fs_1.default.unlinkSync(linkPath);
145
+ node_fs_1.default.symlinkSync(linkTarget, linkPath, 'dir');
146
+ (0, logger_1.log)(logPrefix, ` ✓ .claude/skills → ${linkTarget} (symlink updated, was → ${current})`);
147
+ return 'updated';
148
+ }
149
+ (0, logger_1.log)(logPrefix, ` ⚠ .claude/skills 已是普通目录/文件,跳过软链创建`);
150
+ return 'conflict';
151
+ }
73
152
  function copyDir(src, dest) {
74
153
  node_fs_1.default.mkdirSync(dest, { recursive: true });
75
154
  for (const entry of node_fs_1.default.readdirSync(src, { withFileTypes: true })) {
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.removeLineFromFile = removeLineFromFile;
7
+ exports.removeLineFromContent = removeLineFromContent;
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const logger_1 = require("./logger");
11
+ /**
12
+ * 从文件中移除匹配的行。
13
+ * 搬自 @lark-apaas/fullstack-cli/src/utils/file-ops.ts,行为完全对齐:精确匹配(trim 后)。
14
+ *
15
+ * @returns 是否真的移除过内容
16
+ */
17
+ function removeLineFromFile(filePath, pattern, logPrefix = 'sync') {
18
+ if (!node_fs_1.default.existsSync(filePath)) {
19
+ (0, logger_1.log)(logPrefix, ` ○ ${node_path_1.default.basename(filePath)} (not found)`);
20
+ return false;
21
+ }
22
+ const content = node_fs_1.default.readFileSync(filePath, 'utf-8');
23
+ const trimmed = pattern.trim();
24
+ const lines = content.split('\n');
25
+ const filtered = lines.filter((line) => line.trim() !== trimmed);
26
+ if (filtered.length === lines.length) {
27
+ (0, logger_1.log)(logPrefix, ` ○ ${node_path_1.default.basename(filePath)} (pattern not found: ${pattern})`);
28
+ return false;
29
+ }
30
+ node_fs_1.default.writeFileSync(filePath, filtered.join('\n'));
31
+ (0, logger_1.log)(logPrefix, ` ✓ ${node_path_1.default.basename(filePath)} (removed: ${pattern})`);
32
+ return true;
33
+ }
34
+ /**
35
+ * 纯函数版本:便于单测,不读写文件。
36
+ */
37
+ function removeLineFromContent(content, pattern) {
38
+ const trimmed = pattern.trim();
39
+ const lines = content.split('\n');
40
+ const filtered = lines.filter((line) => line.trim() !== trimmed);
41
+ return {
42
+ result: filtered.join('\n'),
43
+ changed: filtered.length !== lines.length,
44
+ };
45
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateGitHooks = activateGitHooks;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const node_child_process_1 = require("node:child_process");
10
+ const logger_1 = require("../utils/logger");
11
+ const GIT_LEAKED_ENV_KEYS = new Set([
12
+ 'GIT_DIR',
13
+ 'GIT_WORK_TREE',
14
+ 'GIT_INDEX_FILE',
15
+ 'GIT_COMMON_DIR',
16
+ 'GIT_PREFIX',
17
+ 'GIT_OBJECT_DIRECTORY',
18
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
19
+ 'GIT_CONFIG',
20
+ 'GIT_CONFIG_PARAMETERS',
21
+ 'GIT_CONFIG_COUNT',
22
+ ]);
23
+ function envWithoutGitLeaks() {
24
+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !GIT_LEAKED_ENV_KEYS.has(key)));
25
+ }
26
+ /**
27
+ * 把 `.githooks/` 注册为本仓库的 git hooks 目录,让 pre-commit 等 hook 立即生效。
28
+ *
29
+ * 三件事,都先检查再写(幂等):
30
+ * 1. `.git` 存在(非 git 仓库直接跳)
31
+ * 2. `.githooks/pre-commit` 存在(没 hook 文件直接跳,且不写 git config 防止误指空目录)
32
+ * 3. `core.hooksPath` 是 `.githooks`(已经是就短路)
33
+ *
34
+ * 镜像 fullstack-cli `src/commands/sync/activate-hooks.ts`,逻辑保持一致;本地用户
35
+ * 通过 `miaoda app upgrade` 走的这一份,沙箱用户走 `npm run upgrade`(fullstack-cli sync)
36
+ * 那一份,两条通道结果应等价。
37
+ */
38
+ function activateGitHooks(targetDir) {
39
+ if (!node_fs_1.default.existsSync(node_path_1.default.join(targetDir, '.git'))) {
40
+ return { action: 'skipped-no-git' };
41
+ }
42
+ const hookFile = node_path_1.default.join(targetDir, '.githooks', 'pre-commit');
43
+ if (!node_fs_1.default.existsSync(hookFile)) {
44
+ return { action: 'skipped-no-hook-file' };
45
+ }
46
+ // copyFileSync 不保留 mode,确保 +x(重要:没 +x 时 git 不会执行 hook)
47
+ const currentMode = node_fs_1.default.statSync(hookFile).mode & 0o777;
48
+ if ((currentMode & 0o111) !== 0o111) {
49
+ node_fs_1.default.chmodSync(hookFile, 0o755);
50
+ }
51
+ const env = envWithoutGitLeaks();
52
+ const probe = (0, node_child_process_1.spawnSync)('git', ['config', '--get', 'core.hooksPath'], {
53
+ cwd: targetDir,
54
+ env,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ });
57
+ const currentHooksPath = probe.stdout.toString().trim();
58
+ if (currentHooksPath === '.githooks') {
59
+ return { action: 'already-active' };
60
+ }
61
+ const res = (0, node_child_process_1.spawnSync)('git', ['config', 'core.hooksPath', '.githooks'], {
62
+ cwd: targetDir,
63
+ env,
64
+ stdio: ['ignore', 'ignore', 'pipe'],
65
+ });
66
+ if (res.status !== 0) {
67
+ const stderr = res.stderr.toString().trim();
68
+ (0, logger_1.log)('githooks', `⚠️ failed to set core.hooksPath: ${stderr}`);
69
+ return { action: 'skipped-no-git' };
70
+ }
71
+ (0, logger_1.log)('githooks', `activated: core.hooksPath = .githooks`);
72
+ return { action: 'activated' };
73
+ }
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * Deep merge JSON 对象,支持按 key 去重合并数组。
4
+ *
5
+ * 搬自 @lark-apaas/fullstack-cli/src/utils/merge-json.ts,行为完全对齐:
6
+ * - scalar(string / number / boolean / null):template 覆盖
7
+ * - object:递归 merge(template 字段覆盖,user 多出的字段保留)
8
+ * - 在 arrayMerge 配置里的 array:按指定 key 去重合并(template item 覆盖同 key 的 user item,
9
+ * user 多出的 item 保留)
10
+ * - 不在 arrayMerge 配置里的 array:template 覆盖
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.deepMergeJson = deepMergeJson;
14
+ function isPlainObject(value) {
15
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
16
+ }
17
+ function mergeArrayByKey(userArr, templateArr, key) {
18
+ const result = [...userArr];
19
+ for (const templateItem of templateArr) {
20
+ if (!isPlainObject(templateItem))
21
+ continue;
22
+ const templateKey = templateItem[key];
23
+ const existingIndex = result.findIndex((item) => isPlainObject(item) && item[key] === templateKey);
24
+ if (existingIndex >= 0) {
25
+ result[existingIndex] = templateItem;
26
+ }
27
+ else {
28
+ result.push(templateItem);
29
+ }
30
+ }
31
+ return result;
32
+ }
33
+ function deepMergeJson(user, template, arrayMerge = {}, currentPath = '') {
34
+ const result = { ...user };
35
+ for (const key of Object.keys(template)) {
36
+ const fullPath = currentPath ? `${currentPath}.${key}` : key;
37
+ const templateValue = template[key];
38
+ const userValue = user[key];
39
+ if (Array.isArray(templateValue)) {
40
+ const cfg = Object.prototype.hasOwnProperty.call(arrayMerge, fullPath)
41
+ ? arrayMerge[fullPath]
42
+ : undefined;
43
+ if (cfg !== undefined && Array.isArray(userValue)) {
44
+ result[key] = mergeArrayByKey(userValue, templateValue, cfg.key);
45
+ }
46
+ else {
47
+ result[key] = templateValue;
48
+ }
49
+ }
50
+ else if (isPlainObject(templateValue)) {
51
+ if (isPlainObject(userValue)) {
52
+ result[key] = deepMergeJson(userValue, templateValue, arrayMerge, fullPath);
53
+ }
54
+ else {
55
+ result[key] = templateValue;
56
+ }
57
+ }
58
+ else {
59
+ result[key] = templateValue;
60
+ }
61
+ }
62
+ return result;
63
+ }
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.syncPlatformControlled = syncPlatformControlled;
40
+ const node_fs_1 = __importDefault(require("node:fs"));
41
+ const node_path_1 = __importDefault(require("node:path"));
42
+ const jsonc = __importStar(require("jsonc-parser"));
43
+ const logger_1 = require("../utils/logger");
44
+ function syncPlatformControlled(opts) {
45
+ const logPrefix = opts.logPrefix ?? 'app-sync';
46
+ const cliRoot = opts.cliRoot ?? resolveCliRoot();
47
+ const stackDir = node_path_1.default.join(cliRoot, 'upgrade', 'templates', opts.stack);
48
+ if (!node_fs_1.default.existsSync(stackDir)) {
49
+ return { stackFound: false, syncedFiles: [], mergedJsonFiles: [] };
50
+ }
51
+ (0, logger_1.log)(logPrefix, `Syncing upgrade/templates/${opts.stack}/ → ${opts.targetDir}`);
52
+ const syncedFiles = syncFilesDir(node_path_1.default.join(stackDir, 'files'), opts.targetDir, logPrefix);
53
+ const mergedJsonFiles = applyJsonPatches(node_path_1.default.join(stackDir, 'patches'), opts.targetDir, logPrefix);
54
+ return {
55
+ stackFound: true,
56
+ syncedFiles,
57
+ mergedJsonFiles,
58
+ };
59
+ }
60
+ /** 推断 cli 安装根:dist/utils/platform-sync.js 上溯两级即仓根 */
61
+ function resolveCliRoot() {
62
+ return node_path_1.default.resolve(__dirname, '..', '..');
63
+ }
64
+ /** 递归同步 srcDir 下所有文件到 destDir,保持相对路径;.sh 文件 +x。返回 dest 相对路径列表 */
65
+ function syncFilesDir(srcDir, destDir, logPrefix) {
66
+ if (!node_fs_1.default.existsSync(srcDir))
67
+ return [];
68
+ const synced = [];
69
+ walk(srcDir, srcDir, destDir, (rel, srcPath, destPath) => {
70
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(destPath), { recursive: true });
71
+ node_fs_1.default.copyFileSync(srcPath, destPath);
72
+ if (rel.endsWith('.sh')) {
73
+ node_fs_1.default.chmodSync(destPath, 0o755);
74
+ }
75
+ synced.push(rel);
76
+ (0, logger_1.log)(logPrefix, ` + ${rel}`);
77
+ });
78
+ return synced;
79
+ }
80
+ /** 递归遍历 patchesDir 下每个 JSON 文件,deep merge 到 destDir 对应路径 */
81
+ function applyJsonPatches(patchesDir, destDir, logPrefix) {
82
+ if (!node_fs_1.default.existsSync(patchesDir))
83
+ return [];
84
+ const merged = [];
85
+ walk(patchesDir, patchesDir, destDir, (rel, patchPath, destPath) => {
86
+ if (!rel.endsWith('.json')) {
87
+ (0, logger_1.log)(logPrefix, ` (skip non-json patch: ${rel})`);
88
+ return;
89
+ }
90
+ if (!node_fs_1.default.existsSync(destPath)) {
91
+ throw new Error(`[${logPrefix}] target JSON not found: ${destPath} ` +
92
+ `(patches/${rel} 要求项目根含同路径文件;app init 应该先创建它)`);
93
+ }
94
+ const patch = readJson(patchPath);
95
+ const target = readJson(destPath);
96
+ if (!isPlainObject(patch) || !isPlainObject(target)) {
97
+ throw new Error(`[${logPrefix}] patch 与 target 必须都是 JSON object: ${rel}`);
98
+ }
99
+ const changed = [];
100
+ for (const key of Object.keys(patch)) {
101
+ const before = JSON.stringify(target[key]);
102
+ target[key] = deepMerge(target[key], patch[key]);
103
+ const after = JSON.stringify(target[key]);
104
+ if (before !== after)
105
+ changed.push(key);
106
+ }
107
+ if (changed.length > 0) {
108
+ node_fs_1.default.writeFileSync(destPath, JSON.stringify(target, null, 2) + '\n', 'utf-8');
109
+ merged.push({ path: rel, keys: changed });
110
+ (0, logger_1.log)(logPrefix, ` ~ ${rel} (keys: ${changed.join(', ')})`);
111
+ }
112
+ else {
113
+ (0, logger_1.log)(logPrefix, ` = ${rel} (unchanged)`);
114
+ }
115
+ });
116
+ return merged;
117
+ }
118
+ /** 通用递归遍历:对 rootSrc 下每个文件调 visit(rel, srcAbsPath, destAbsPath) */
119
+ function walk(rootSrc, curSrc, destDir, visit) {
120
+ for (const name of node_fs_1.default.readdirSync(curSrc)) {
121
+ const srcPath = node_path_1.default.join(curSrc, name);
122
+ const stat = node_fs_1.default.statSync(srcPath);
123
+ if (stat.isDirectory()) {
124
+ walk(rootSrc, srcPath, destDir, visit);
125
+ continue;
126
+ }
127
+ const rel = node_path_1.default.relative(rootSrc, srcPath);
128
+ const destPath = node_path_1.default.join(destDir, rel);
129
+ visit(rel, srcPath, destPath);
130
+ }
131
+ }
132
+ function readJson(filePath) {
133
+ // 用 jsonc 解析以兼容 tsconfig*/nest-cli.json 等允许注释和 trailing comma 的配置;
134
+ // 我们仓自带的 patches/*.json 是严格 JSON,jsonc 也读得通。
135
+ // 写回时仍走 JSON.stringify,注释和 trailing comma 会丢——user app 的 tsconfig 经过
136
+ // 一次 deep merge 后会变成严格 JSON,可接受(tsc 同样读得动)。
137
+ const text = node_fs_1.default.readFileSync(filePath, 'utf-8');
138
+ const errors = [];
139
+ const parsed = jsonc.parse(text, errors, { allowTrailingComma: true });
140
+ if (errors.length > 0) {
141
+ const first = errors[0];
142
+ const code = jsonc.printParseErrorCode(first.error);
143
+ throw new Error(`${filePath}: jsonc parse error ${code} at offset ${String(first.offset)}`);
144
+ }
145
+ return parsed;
146
+ }
147
+ function isPlainObject(v) {
148
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
149
+ }
150
+ /** value 是 object 时递归 merge,其它(包括数组)直接以 patch 覆盖 */
151
+ function deepMerge(target, patch) {
152
+ if (isPlainObject(patch) && isPlainObject(target)) {
153
+ const merged = { ...target };
154
+ for (const k of Object.keys(patch)) {
155
+ merged[k] = deepMerge(target[k], patch[k]);
156
+ }
157
+ return merged;
158
+ }
159
+ return patch;
160
+ }