@lark-apaas/miaoda-cli 0.1.48 → 0.1.50

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.
@@ -0,0 +1,327 @@
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.FILE_COUNT_KEYS = void 0;
7
+ exports.collectFiles = collectFiles;
8
+ exports.normalizeEntries = normalizeEntries;
9
+ exports.listProjectUiComponents = listProjectUiComponents;
10
+ exports.mapSourcePath = mapSourcePath;
11
+ exports.buildImportPlan = buildImportPlan;
12
+ exports.applyImportPlan = applyImportPlan;
13
+ const node_fs_1 = __importDefault(require("node:fs"));
14
+ const node_path_1 = __importDefault(require("node:path"));
15
+ const error_1 = require("../../../utils/error");
16
+ const rules_1 = require("./rules");
17
+ exports.FILE_COUNT_KEYS = [
18
+ 'client/src',
19
+ 'client/public',
20
+ 'shared',
21
+ rules_1.SOURCE_PACKAGE_DIR,
22
+ ];
23
+ /** 递归列出目录下的普通文件(posix 相对路径)。符号链接一律跳过,防止 zip 里的链接把工程外文件带进来。 */
24
+ function collectFiles(rootDir) {
25
+ const out = [];
26
+ const walk = (rel) => {
27
+ for (const entry of node_fs_1.default.readdirSync(node_path_1.default.join(rootDir, rel), { withFileTypes: true })) {
28
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
29
+ if (entry.isDirectory())
30
+ walk(childRel);
31
+ else if (entry.isFile())
32
+ out.push(childRel);
33
+ }
34
+ };
35
+ walk('');
36
+ return out.sort();
37
+ }
38
+ /**
39
+ * 规范化导入条目(对齐 merger.go extractZip + normalizeImportedFiles):
40
+ * 1. 丢弃含 ".."、__MACOSX/、.DS_Store
41
+ * 2. 非 gemini:剥公共顶层目录(getImportedPrefix);gemini 保留原始路径
42
+ * 3. 超长路径段 hash 截断
43
+ * 4. 丢弃 .git 元数据与 node_modules / dist / build 目录
44
+ */
45
+ function normalizeEntries(rawPaths, platform) {
46
+ const kept = rawPaths.filter((p) => !(0, rules_1.isRawEntrySkipped)(p));
47
+ const prefix = platform === 'gemini' ? '' : (0, rules_1.getImportedPrefix)(kept);
48
+ const entries = [];
49
+ const renamed = [];
50
+ for (const raw of kept) {
51
+ if ((0, rules_1.isGitRepoDir)(raw))
52
+ continue;
53
+ const stripped = (0, rules_1.removePrefix)(prefix, raw);
54
+ if (!stripped)
55
+ continue;
56
+ const normalized = (0, rules_1.sanitizePathSegments)(stripped);
57
+ if (normalized !== stripped)
58
+ renamed.push({ from: stripped, to: normalized });
59
+ if ((0, rules_1.isGitRepoDir)(normalized) || (0, rules_1.hasSkippedDirSegment)(normalized))
60
+ continue;
61
+ entries.push({ raw, normalized });
62
+ }
63
+ return { entries, renamed };
64
+ }
65
+ const UI_PREFIX_SRC = 'src/components/ui/';
66
+ const UI_PREFIX_PROJECT = 'client/src/components/ui/';
67
+ const JS_EXTS = new Set(['.js', '.jsx']);
68
+ const TS_EXTS = new Set(['.ts', '.tsx']);
69
+ function stripExt(name) {
70
+ const ext = node_path_1.default.posix.extname(name);
71
+ return ext ? name.slice(0, -ext.length) : name;
72
+ }
73
+ /** 工程已有的 UI 组件:basename(去扩展名)→ 相对工程根路径(仅 ui/ 直接子文件)。 */
74
+ function listProjectUiComponents(projectDir) {
75
+ const result = new Map();
76
+ const uiDir = node_path_1.default.join(projectDir, ...UI_PREFIX_PROJECT.split('/'));
77
+ let names;
78
+ try {
79
+ names = node_fs_1.default.readdirSync(uiDir, { withFileTypes: true });
80
+ }
81
+ catch {
82
+ return result;
83
+ }
84
+ for (const d of names) {
85
+ if (!d.isFile())
86
+ continue;
87
+ const base = stripExt(d.name);
88
+ const list = result.get(base) ?? [];
89
+ list.push(`${UI_PREFIX_PROJECT}${d.name}`);
90
+ result.set(base, list);
91
+ }
92
+ return result;
93
+ }
94
+ function mapByPrefix(src, from, to) {
95
+ return src.startsWith(from) ? to + src.slice(from.length) : undefined;
96
+ }
97
+ /** 按平台把规范化源路径映射到工程目标路径(对齐 merger.go 各 merge* 分支)。 */
98
+ function mapSourcePath(src, platform, rules, uiComponents) {
99
+ const fallback = `${rules_1.SOURCE_PACKAGE_DIR}/${src}`;
100
+ switch (platform) {
101
+ case 'lovable': {
102
+ if (src.startsWith('src/')) {
103
+ if ((0, rules_1.isExcludedPath)(src, rules.excludedPaths))
104
+ return { target: fallback, excluded: true };
105
+ return { target: `client/${src}`, excluded: false };
106
+ }
107
+ const pub = mapByPrefix(src, 'public/', 'client/public/');
108
+ return { target: pub ?? fallback, excluded: false };
109
+ }
110
+ case 'replit': {
111
+ if (src.startsWith('client/src/')) {
112
+ if ((0, rules_1.isExcludedPath)(src, rules.excludedPaths))
113
+ return { target: fallback, excluded: true };
114
+ return { target: src, excluded: false };
115
+ }
116
+ if (src.startsWith('shared/'))
117
+ return { target: src, excluded: false };
118
+ const assets = mapByPrefix(src, 'attached_assets/', 'client/public/assets/');
119
+ return { target: assets ?? fallback, excluded: false };
120
+ }
121
+ case 'gemini': {
122
+ const mapped = mapByPrefix(src, 'components/', 'client/src/components/') ??
123
+ mapByPrefix(src, 'services/', 'client/src/services/') ??
124
+ (src === 'types.ts' ? 'client/src/types.ts' : undefined) ??
125
+ (src === 'constants.ts' ? 'client/src/constants.ts' : undefined);
126
+ return { target: mapped ?? fallback, excluded: false };
127
+ }
128
+ case 'zip': {
129
+ if (src.startsWith('src/')) {
130
+ if (src.startsWith(UI_PREFIX_SRC)) {
131
+ const rest = src.slice(UI_PREFIX_SRC.length);
132
+ if (!rest.includes('/')) {
133
+ const existing = uiComponents.get(stripExt(rest));
134
+ if (existing && existing.length > 0) {
135
+ // 模板业务组件依赖 TS 版 UI 组件的类型,JS 版替换后会类型报错,保留模板版本
136
+ const tsVersion = existing.find((p) => TS_EXTS.has(node_path_1.default.posix.extname(p)));
137
+ if (tsVersion && JS_EXTS.has(node_path_1.default.posix.extname(rest))) {
138
+ return { target: fallback, excluded: false, uiKept: tsVersion };
139
+ }
140
+ return { target: `client/${src}`, excluded: false, uiReplaced: existing };
141
+ }
142
+ }
143
+ }
144
+ if ((0, rules_1.isExcludedPath)(src, rules.excludedPaths))
145
+ return { target: fallback, excluded: true };
146
+ return { target: `client/${src}`, excluded: false };
147
+ }
148
+ const pub = mapByPrefix(src, 'public/', 'client/public/');
149
+ return { target: pub ?? fallback, excluded: false };
150
+ }
151
+ }
152
+ }
153
+ function countKey(target) {
154
+ for (const key of exports.FILE_COUNT_KEYS) {
155
+ if (target === key || target.startsWith(`${key}/`))
156
+ return key;
157
+ }
158
+ return undefined;
159
+ }
160
+ /** 计算完整放置计划(纯计算 + 只读工程目录,不写任何文件)。 */
161
+ function buildImportPlan(opts) {
162
+ const uiComponents = opts.platform === 'zip'
163
+ ? listProjectUiComponents(opts.projectDir)
164
+ : new Map();
165
+ const byTarget = new Map();
166
+ const excludedPaths = [];
167
+ const protectedConflicts = [];
168
+ const replaced = new Set();
169
+ const warnings = [];
170
+ for (const entry of opts.entries) {
171
+ const src = entry.normalized;
172
+ const mapped = mapSourcePath(src, opts.platform, opts.rules, uiComponents);
173
+ let target = mapped.target;
174
+ if (mapped.excluded)
175
+ excludedPaths.push(src);
176
+ if ((0, rules_1.isProtectedTarget)(target)) {
177
+ const placedAt = `${rules_1.SOURCE_PACKAGE_DIR}/${src}`;
178
+ protectedConflicts.push({ source: src, target, placedAt });
179
+ target = placedAt;
180
+ }
181
+ else if (mapped.uiKept) {
182
+ protectedConflicts.push({ source: src, target: mapped.uiKept, placedAt: target });
183
+ }
184
+ else if (mapped.uiReplaced) {
185
+ for (const p of mapped.uiReplaced)
186
+ replaced.add(p);
187
+ }
188
+ if (byTarget.has(target)) {
189
+ warnings.push(`多个导入文件映射到同一目标,后者覆盖前者:${target}`);
190
+ }
191
+ byTarget.set(target, { source: src, raw: entry.raw, target });
192
+ }
193
+ const placements = [...byTarget.values()];
194
+ const fileCounts = {
195
+ 'client/src': 0,
196
+ 'client/public': 0,
197
+ shared: 0,
198
+ source_package: 0,
199
+ };
200
+ for (const p of placements) {
201
+ const key = countKey(p.target);
202
+ if (key)
203
+ fileCounts[key] += 1;
204
+ }
205
+ const replacedTemplateFiles = [...replaced].sort();
206
+ const deletions = replacedTemplateFiles.filter((p) => !byTarget.has(p));
207
+ const hasSourcePackageJson = byTarget.has(`${rules_1.SOURCE_PACKAGE_DIR}/package.json`);
208
+ const overwrites = placements
209
+ .map((p) => p.target)
210
+ .filter((t) => !replaced.has(t) && node_fs_1.default.existsSync(node_path_1.default.join(opts.projectDir, ...t.split('/'))))
211
+ .sort();
212
+ return {
213
+ placements,
214
+ replacedTemplateFiles,
215
+ deletions,
216
+ excludedPaths,
217
+ protectedConflicts,
218
+ fileCounts,
219
+ hasSourcePackageJson,
220
+ overwrites,
221
+ warnings,
222
+ };
223
+ }
224
+ function writeFailed(stage, err) {
225
+ return new error_1.AppError('WRITE_FAILED', `导入写入失败(${stage}):${err instanceof Error ? err.message : String(err)}`, { next_actions: ['检查磁盘空间 / 目录权限后重试 miaoda app import'] });
226
+ }
227
+ /**
228
+ * 预检移入目标:rename 遇到「目标已是目录」或「父路径上有普通文件」必然失败,
229
+ * 在动工程之前拦下,避免移入到一半才报错。
230
+ */
231
+ function preflightTargets(plan, projectDir) {
232
+ for (const p of plan.placements) {
233
+ const segs = p.target.split('/');
234
+ for (let i = 1; i < segs.length; i += 1) {
235
+ const parent = node_path_1.default.join(projectDir, ...segs.slice(0, i));
236
+ if (node_fs_1.default.existsSync(parent) && !node_fs_1.default.statSync(parent).isDirectory()) {
237
+ throw writeFailed('preflight', new Error(`目标父路径是文件:${segs.slice(0, i).join('/')}(${p.target})`));
238
+ }
239
+ }
240
+ const dest = node_path_1.default.join(projectDir, ...segs);
241
+ if (node_fs_1.default.existsSync(dest) && node_fs_1.default.statSync(dest).isDirectory()) {
242
+ throw writeFailed('preflight', new Error(`目标路径已是目录:${p.target}`));
243
+ }
244
+ }
245
+ }
246
+ /** 把工程里已有的 rel 挪进 backupDir,返回暂存位置;不存在则返回 undefined。 */
247
+ function backupExisting(projectDir, backupDir, rel) {
248
+ const dest = node_path_1.default.join(projectDir, ...rel.split('/'));
249
+ if (!node_fs_1.default.existsSync(dest))
250
+ return undefined;
251
+ const backup = node_path_1.default.join(backupDir, ...rel.split('/'));
252
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(backup), { recursive: true });
253
+ node_fs_1.default.renameSync(dest, backup);
254
+ return backup;
255
+ }
256
+ /** 逆序撤回已执行的移入 / 删除;返回撤回失败的路径(尽力而为,不中断)。 */
257
+ function rollbackMoves(records) {
258
+ const failed = [];
259
+ for (const r of [...records].reverse()) {
260
+ try {
261
+ node_fs_1.default.rmSync(r.dest, { force: true });
262
+ if (r.backup) {
263
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(r.dest), { recursive: true });
264
+ node_fs_1.default.renameSync(r.backup, r.dest);
265
+ }
266
+ }
267
+ catch {
268
+ failed.push(r.dest);
269
+ }
270
+ }
271
+ return failed;
272
+ }
273
+ /**
274
+ * 三阶段落盘:
275
+ * 1. 全部文件先拷进 stagingDir(工程不动);任一失败 → 清理暂存,工程保持原样
276
+ * 2. 预检所有移入目标(目标已是目录 / 父路径是文件);不通过 → 工程保持原样
277
+ * 3. 逐个移入工程、删被替换的模板 UI 组件;被覆盖或删除的原文件先挪进暂存目录下的备份,
278
+ * 中途失败按逆序回滚,工程恢复原样(只可能留下新建的空目录)
279
+ * 失败一律抛 WRITE_FAILED,调用方不写 manifest,重跑会重新导入。
280
+ */
281
+ function applyImportPlan(opts) {
282
+ const { plan, extractDir, projectDir, stagingDir } = opts;
283
+ // 备份放暂存目录下(同一文件系统,rename 不跨设备),finally 一并清理;
284
+ // 放置目标都以 client/ shared/ source_package/ 开头,不会与它重名。
285
+ const backupDir = node_path_1.default.join(stagingDir, '.backup');
286
+ try {
287
+ try {
288
+ for (const p of plan.placements) {
289
+ const staged = node_path_1.default.join(stagingDir, ...p.target.split('/'));
290
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(staged), { recursive: true });
291
+ node_fs_1.default.copyFileSync(node_path_1.default.join(extractDir, ...p.raw.split('/')), staged);
292
+ }
293
+ }
294
+ catch (err) {
295
+ throw writeFailed('stage', err);
296
+ }
297
+ preflightTargets(plan, projectDir);
298
+ const records = [];
299
+ try {
300
+ for (const p of plan.placements) {
301
+ const staged = node_path_1.default.join(stagingDir, ...p.target.split('/'));
302
+ const dest = node_path_1.default.join(projectDir, ...p.target.split('/'));
303
+ const backup = backupExisting(projectDir, backupDir, p.target);
304
+ records.push({ dest, backup });
305
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(dest), { recursive: true });
306
+ node_fs_1.default.renameSync(staged, dest);
307
+ }
308
+ for (const rel of plan.deletions) {
309
+ const backup = backupExisting(projectDir, backupDir, rel);
310
+ if (backup)
311
+ records.push({ dest: node_path_1.default.join(projectDir, ...rel.split('/')), backup });
312
+ }
313
+ }
314
+ catch (err) {
315
+ const notRestored = rollbackMoves(records);
316
+ if (notRestored.length > 0) {
317
+ throw writeFailed('move', new Error(`${err instanceof Error ? err.message : String(err)};回滚未完成:${notRestored
318
+ .map((d) => node_path_1.default.relative(projectDir, d))
319
+ .join(', ')}`));
320
+ }
321
+ throw writeFailed('move', err);
322
+ }
323
+ }
324
+ finally {
325
+ node_fs_1.default.rmSync(stagingDir, { recursive: true, force: true });
326
+ }
327
+ }
@@ -0,0 +1,293 @@
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.PROJECT_ROOT_DIRS = exports.BUILD_CHAIN_PATTERNS = exports.DEFAULT_IMPORT_RULES = exports.PLATFORM_IMPORT_RULES = exports.MAX_PATH_SEGMENT_BYTES = exports.SOURCE_PACKAGE_DIR = exports.DEFAULT_IMPORT_PLATFORM = exports.IMPORT_PLATFORMS = void 0;
7
+ exports.isBuildChainDependency = isBuildChainDependency;
8
+ exports.isPlatformManagedDependency = isPlatformManagedDependency;
9
+ exports.parsePlatform = parsePlatform;
10
+ exports.resolveImportRules = resolveImportRules;
11
+ exports.isGitRepoDir = isGitRepoDir;
12
+ exports.isRawEntrySkipped = isRawEntrySkipped;
13
+ exports.hasSkippedDirSegment = hasSkippedDirSegment;
14
+ exports.getImportedPrefix = getImportedPrefix;
15
+ exports.removePrefix = removePrefix;
16
+ exports.sanitizePathSegments = sanitizePathSegments;
17
+ exports.isExcludedPath = isExcludedPath;
18
+ exports.isProtectedTarget = isProtectedTarget;
19
+ const node_crypto_1 = __importDefault(require("node:crypto"));
20
+ const node_path_1 = __importDefault(require("node:path"));
21
+ const error_1 = require("../../../utils/error");
22
+ const import_source_1 = require("../../../services/app/init/import-source");
23
+ /**
24
+ * 外部平台导入规则(移植自 studio_server import_svc/merger.go + tcc/import_merger_config.go)。
25
+ *
26
+ * 本文件只放纯函数与常量:路径规范化、平台排除清单、受保护目标、构建链依赖识别。
27
+ * 不做 IO,便于逐条对齐服务端 merger 的单测口径。
28
+ */
29
+ exports.IMPORT_PLATFORMS = ['lovable', 'replit', 'gemini', 'zip'];
30
+ exports.DEFAULT_IMPORT_PLATFORM = 'zip';
31
+ /** 不进模板工程的文件统一落到这里(用户原 package.json 也在此:source_package/package.json)。 */
32
+ exports.SOURCE_PACKAGE_DIR = 'source_package';
33
+ /** 单个路径段字节上限;超过则 hash 截断重命名,避免沙箱解压 ENAMETOOLONG(对齐 merger.go)。 */
34
+ exports.MAX_PATH_SEGMENT_BYTES = 60;
35
+ /**
36
+ * 平台排除路径(取线上 TCC ImportMergerConfig 的 excluded_paths,而非代码兜底值)。
37
+ * 实际生效 = 平台清单 + DEFAULT 清单(对齐 tcc.GetImportExcludedPaths)。
38
+ *
39
+ * 不再有排除依赖清单:导入不合并 package.json,依赖由 Coding Agent 参考 manifest 自行安装、
40
+ * 遇到冲突自行处理。
41
+ */
42
+ exports.PLATFORM_IMPORT_RULES = {
43
+ lovable: {
44
+ excludedPaths: [
45
+ 'src/App.tsx',
46
+ 'src/main.tsx',
47
+ 'src/index.css',
48
+ 'src/hooks/use-mobile.tsx',
49
+ 'src/integrations/supabase',
50
+ 'src/lib/supabase.ts',
51
+ ],
52
+ },
53
+ replit: {
54
+ excludedPaths: [
55
+ 'client/src/App.tsx',
56
+ 'client/src/main.tsx',
57
+ 'client/src/index.css',
58
+ 'client/src/hooks/use-mobile.tsx',
59
+ ],
60
+ },
61
+ gemini: {
62
+ excludedPaths: [],
63
+ },
64
+ zip: {
65
+ excludedPaths: [
66
+ 'src/db/',
67
+ 'src/integrations/',
68
+ 'src/hooks/use-supabase-upload.ts',
69
+ 'src/hooks/use-mobile.tsx',
70
+ 'src/App.tsx',
71
+ 'src/main.tsx',
72
+ 'src/index.css',
73
+ 'src/App.jsx',
74
+ 'src/main.jsx',
75
+ ],
76
+ },
77
+ };
78
+ exports.DEFAULT_IMPORT_RULES = {
79
+ excludedPaths: [],
80
+ };
81
+ /**
82
+ * 构建链 / 工具链依赖:模板已有自己的构建体系,用户包里的这类依赖通常不需要装。
83
+ * 支持精确名与 `*` 通配(只在末尾或 scope 内使用),集中在此一处便于扩展。
84
+ */
85
+ exports.BUILD_CHAIN_PATTERNS = [
86
+ 'vite',
87
+ '@vitejs/*',
88
+ 'vite-plugin-*',
89
+ '@vite-pwa/*',
90
+ 'rollup',
91
+ 'rollup-plugin-*',
92
+ '@rollup/*',
93
+ 'esbuild',
94
+ 'webpack',
95
+ 'webpack-*',
96
+ '@babel/*',
97
+ 'babel-*',
98
+ 'eslint',
99
+ 'eslint-*',
100
+ '@eslint/*',
101
+ '@typescript-eslint/*',
102
+ 'typescript-eslint',
103
+ 'typescript',
104
+ 'tailwindcss',
105
+ '@tailwindcss/*',
106
+ 'postcss',
107
+ 'postcss-*',
108
+ 'autoprefixer',
109
+ 'prettier',
110
+ 'prettier-*',
111
+ 'jest',
112
+ '@jest/*',
113
+ 'ts-jest',
114
+ 'vitest',
115
+ '@vitest/*',
116
+ 'react-scripts',
117
+ '@vue/cli-*',
118
+ '@types/*',
119
+ 'lovable-tagger',
120
+ 'miaoda-sc-plugin',
121
+ '@builder.io/vite-plugin-jsx-loc',
122
+ ];
123
+ function globToRegExp(pattern) {
124
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\/]/g, '\\$&').replace(/\*/g, '.*');
125
+ return new RegExp(`^${escaped}$`);
126
+ }
127
+ const BUILD_CHAIN_REGEXPS = exports.BUILD_CHAIN_PATTERNS.map(globToRegExp);
128
+ function isBuildChainDependency(name) {
129
+ return BUILD_CHAIN_REGEXPS.some((re) => re.test(name));
130
+ }
131
+ /** @lark-apaas/* 是平台托管依赖,版本由模板 / sync 管,不能按用户包装。 */
132
+ function isPlatformManagedDependency(name) {
133
+ return name.startsWith('@lark-apaas/');
134
+ }
135
+ function parsePlatform(raw) {
136
+ const value = (raw ?? exports.DEFAULT_IMPORT_PLATFORM).trim().toLowerCase();
137
+ if (exports.IMPORT_PLATFORMS.includes(value))
138
+ return value;
139
+ throw new error_1.AppError('ARGS_INVALID', `--platform 取值非法:${raw ?? ''}(可选 ${exports.IMPORT_PLATFORMS.join(' / ')})`);
140
+ }
141
+ function isStringArray(v) {
142
+ return Array.isArray(v) && v.every((x) => typeof x === 'string');
143
+ }
144
+ /**
145
+ * 解析生效规则:平台清单 + DEFAULT 清单;`--rules-json` 提供的字段整体替换对应默认值
146
+ * (未提供的字段保留默认)。
147
+ */
148
+ function resolveImportRules(platform, rulesJson) {
149
+ const rules = {
150
+ excludedPaths: [
151
+ ...exports.PLATFORM_IMPORT_RULES[platform].excludedPaths,
152
+ ...exports.DEFAULT_IMPORT_RULES.excludedPaths,
153
+ ],
154
+ };
155
+ if (rulesJson === undefined || rulesJson.trim() === '')
156
+ return rules;
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(rulesJson);
160
+ }
161
+ catch (err) {
162
+ const msg = err instanceof Error ? err.message : String(err);
163
+ throw new error_1.AppError('ARGS_INVALID', `--rules-json 必须是合法 JSON:${msg}`);
164
+ }
165
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
166
+ throw new error_1.AppError('ARGS_INVALID', '--rules-json 必须是 JSON 对象');
167
+ }
168
+ const obj = parsed;
169
+ for (const key of ['excludedPaths']) {
170
+ const v = obj[key];
171
+ if (v === undefined)
172
+ continue;
173
+ if (!isStringArray(v)) {
174
+ throw new error_1.AppError('ARGS_INVALID', `--rules-json.${key} 必须是字符串数组`);
175
+ }
176
+ rules[key] = [...v];
177
+ }
178
+ return rules;
179
+ }
180
+ // ── 路径规范化(对齐 merger.go) ────────────
181
+ /** .git 元数据:精确 .git、.git/ 前缀、嵌套 /.git/。不误伤 .gitignore / .github / .gitattributes。 */
182
+ function isGitRepoDir(p) {
183
+ return p === '.git' || p.startsWith('.git/') || p.includes('/.git/');
184
+ }
185
+ /** zip 解出来的原始条目里需要直接丢弃的(merger.go extractZip 的过滤口径)。 */
186
+ function isRawEntrySkipped(p) {
187
+ if (p.includes('..'))
188
+ return true;
189
+ if (p.startsWith('__MACOSX/'))
190
+ return true;
191
+ if (p.endsWith('.DS_Store'))
192
+ return true;
193
+ return false;
194
+ }
195
+ /** 目录段命中 node_modules / dist / build(任意层级)即跳过;与 `app init --source-path` 同口径。 */
196
+ function hasSkippedDirSegment(p) {
197
+ const segments = p.split('/');
198
+ segments.pop();
199
+ return segments.some((seg) => seg !== '.git' && import_source_1.IMPORT_SKIP_DIRS.has(seg));
200
+ }
201
+ /**
202
+ * 放置规则本身认识的工程目录名。用户只压了这些目录(如只打包 src/)时,公共首段就是工程目录本身,
203
+ * 不是外层包裹目录,不能剥——否则 src/** 会整体落进 source_package/(服务端 merger.go 的同款缺陷,此处修正)。
204
+ */
205
+ exports.PROJECT_ROOT_DIRS = new Set([
206
+ 'src',
207
+ 'public',
208
+ 'client',
209
+ 'server',
210
+ 'shared',
211
+ 'components',
212
+ 'services',
213
+ 'attached_assets',
214
+ ]);
215
+ /**
216
+ * 导入包的公共顶层目录:所有条目都至少两段、首段一致且首段不含 ".",并且首段不是工程目录名
217
+ * (PROJECT_ROOT_DIRS),才认为是包裹目录。否则返回 ""(不剥前缀)。
218
+ */
219
+ function getImportedPrefix(paths) {
220
+ let common = '';
221
+ let first = true;
222
+ for (const p of paths) {
223
+ const idx = p.indexOf('/');
224
+ if (idx < 0)
225
+ return '';
226
+ const head = p.slice(0, idx);
227
+ if (head.includes('.'))
228
+ return '';
229
+ if (first) {
230
+ common = head;
231
+ first = false;
232
+ }
233
+ else if (head !== common) {
234
+ return '';
235
+ }
236
+ }
237
+ return exports.PROJECT_ROOT_DIRS.has(common) ? '' : common;
238
+ }
239
+ function removePrefix(prefix, p) {
240
+ if (!prefix)
241
+ return p;
242
+ return p.startsWith(`${prefix}/`) ? p.slice(prefix.length + 1) : p;
243
+ }
244
+ /** 超过 60 字节的路径段改名为 truncated-<sha256 前 8 字节 hex><ext>(ext 长度 ≤ 20 才保留)。 */
245
+ function sanitizePathSegments(p) {
246
+ const segments = p.split('/');
247
+ let rewritten = false;
248
+ for (let i = 0; i < segments.length; i += 1) {
249
+ const seg = segments[i];
250
+ if (Buffer.byteLength(seg, 'utf-8') <= exports.MAX_PATH_SEGMENT_BYTES)
251
+ continue;
252
+ let ext = node_path_1.default.posix.extname(seg);
253
+ if (Buffer.byteLength(ext, 'utf-8') > 20)
254
+ ext = '';
255
+ const sum = node_crypto_1.default.createHash('sha256').update(seg, 'utf-8').digest('hex');
256
+ segments[i] = `truncated-${sum.slice(0, 16)}${ext}`;
257
+ rewritten = true;
258
+ }
259
+ return rewritten ? segments.join('/') : p;
260
+ }
261
+ function isExcludedPath(p, excludedPaths) {
262
+ return excludedPaths.some((prefix) => prefix !== '' && p.startsWith(prefix));
263
+ }
264
+ // ── 受保护目标 ────────────
265
+ const PROTECTED_ROOT_FILES = new Set([
266
+ 'package.json',
267
+ 'package-lock.json',
268
+ '.npmrc',
269
+ 'AGENTS.md',
270
+ 'server/main.ts',
271
+ 'client/src/index.tsx',
272
+ ]);
273
+ const PROTECTED_ROOT_DIRS = ['.githooks/', 'scripts/', '.spark/', 'node_modules/'];
274
+ const PROTECTED_ROOT_PATTERNS = [
275
+ /^tsconfig.*\.json$/,
276
+ /^vite\.config\..+$/,
277
+ /^eslint\.config\..+$/,
278
+ ];
279
+ /**
280
+ * 工程内模板托管、导入绝不能新建 / 覆盖的目标路径(相对工程根)。
281
+ * source_package/ 是导入的分流目录,本身不受保护。
282
+ */
283
+ function isProtectedTarget(target) {
284
+ if (target.startsWith(`${exports.SOURCE_PACKAGE_DIR}/`))
285
+ return false;
286
+ if (PROTECTED_ROOT_FILES.has(target))
287
+ return true;
288
+ if (PROTECTED_ROOT_DIRS.some((d) => target.startsWith(d)))
289
+ return true;
290
+ if (!target.includes('/') && PROTECTED_ROOT_PATTERNS.some((re) => re.test(target)))
291
+ return true;
292
+ return false;
293
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/miaoda-cli",
3
- "version": "0.1.48",
3
+ "version": "0.1.50",
4
4
  "description": "Miaoda 平台命令行工具,面向 Agent 调用",
5
5
  "type": "commonjs",
6
6
  "bin": {