@lark-apaas/miaoda-cli 0.1.31 → 0.1.33-alpha.0e32e59

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 (27) hide show
  1. package/README.md +24 -2
  2. package/dist/cli/commands/app/index.js +64 -0
  3. package/dist/cli/commands/deploy/modern.js +6 -5
  4. package/dist/cli/commands/registry/index.js +6 -6
  5. package/dist/cli/handlers/app/export-standalone.js +216 -0
  6. package/dist/cli/handlers/app/index.js +4 -1
  7. package/dist/cli/handlers/registry/add.js +3 -2
  8. package/dist/cli/handlers/registry/list.js +3 -8
  9. package/dist/cli/handlers/registry/shared.js +8 -4
  10. package/dist/services/app/export-standalone/archive.js +33 -0
  11. package/dist/services/app/export-standalone/copy-tree.js +51 -0
  12. package/dist/services/app/export-standalone/download.js +52 -0
  13. package/dist/services/app/export-standalone/index.js +23 -0
  14. package/dist/services/app/export-standalone/inline-babel.js +91 -0
  15. package/dist/services/app/export-standalone/naming.js +65 -0
  16. package/dist/services/app/export-standalone/rewrite.js +80 -0
  17. package/dist/services/app/export-standalone/scan.js +72 -0
  18. package/dist/services/app/export-standalone/strategies.js +214 -0
  19. package/dist/services/deploy/modern/patch/actions.js +6 -4
  20. package/dist/services/deploy/modern/patch/html-title.js +75 -0
  21. package/dist/services/deploy/modern/patch/index.js +1 -1
  22. package/dist/services/deploy/modern/patch/routes.js +13 -3
  23. package/dist/services/deploy/modern/patch/source-scan.js +3 -40
  24. package/dist/utils/exclude-patterns.js +49 -0
  25. package/dist/utils/sandbox-skills.js +13 -1
  26. package/package.json +1 -1
  27. package/upgrade/templates/nestjs-react-fullstack/templates/scripts/lint.js +43 -7
package/README.md CHANGED
@@ -48,14 +48,36 @@ miaoda file ls --output json
48
48
  | `miaoda observability ...` | 线上日志、链路、前端源码堆栈反查、监控指标、运营指标 |
49
49
  | `miaoda comment ...` | 应用评论:查看评论列表、解决评论(仅 design-html 场景开放) |
50
50
  | `miaoda registry ...` | 组件 registry:列出 / copy-in SDK 文件(本地执行) |
51
+ | `miaoda app ...` | 应用生命周期:元数据、初始化、平台同步、源码导出、静态产物导出 |
51
52
 
52
53
  完整命令通过 `miaoda --help` 或 `miaoda <domain> --help` 查看。
53
54
 
55
+ ## 导出可本地访问的静态产物
56
+
57
+ `miaoda app export-standalone` 把当前应用构建成一份自包含静态产物,可脱离妙搭平台本地打开。
58
+
59
+ ```bash
60
+ miaoda app export-standalone # → dist/standalone/ + dist/standalone.zip
61
+ miaoda app export-standalone --out dist/share
62
+ miaoda app export-standalone --json
63
+ ```
64
+
65
+ 支持 `design-html` / `html` / `vite-react` / `nestjs-react-fullstack`。页面与代码里字面以
66
+ `/spark/app` 开头的存储图片会经沙箱网关(localhost:8080)下载到 `images/` 并改写成相对路径。
67
+
68
+ 默认输出落在 `dist/` 下是刻意的:`dist` 已在部署扫描的 EXCLUDES 与各模板 `.gitignore` 中,
69
+ 产物不会污染部署包、不会被误提交;代价是下一次构建会清掉它。
70
+
71
+ **只保证纯静态可看** —— 接口调用会失败,不做数据快照。多路由 SPA 在 `file://` 下不可用
72
+ (`BrowserRouter` 匹配不上路径),需用本地 HTTP server 打开,命令会在 `warnings` 里提示。
73
+
74
+ > 与 `miaoda app export` **语义无关**:后者导出的是源码归档(创意应用升级链路的只读参考物)。
75
+
54
76
  ## 组件 registry
55
77
 
56
78
  `miaoda registry` 提供 shadcn 式的「组件 registry」:把 SDK 文件**拷进**当前项目(copy-in),而非作为依赖安装。registry 是独立 npm 包,按运行时分发(design-html / html → buildless runtime → `@lark-apaas/coding-registry-buildless`)。
57
79
 
58
- 前置:当前目录(或 `--dir`)已走过 `miaoda app init`,且 `.spark/meta.json` 的 `stack` 有对应 registry 包(当前支持 `design-html` / `html`);其余 stack 执行时报 `REGISTRY_STACK_UNSUPPORTED` 并提示支持列表。
80
+ 前置:当前工作目录已走过 `miaoda app init`,且 `.spark/meta.json` 的 `stack` 有对应 registry 包(当前支持 `design-html` / `html`);其余 stack 执行时报 `REGISTRY_STACK_UNSUPPORTED` 并提示支持列表。meta 一律从 cwd 读取,不随 `--dir` 走。
59
81
 
60
82
  ```bash
61
83
  # 列出可用 SDK 条目(输出各文件 USAGE 注释块原文,便于 Agent 直接读用法)
@@ -76,7 +98,7 @@ miaoda registry add deck-slide --overwrite # 目标已存在时覆盖(
76
98
  - **拍平落地**:所有文件**拍平**到项目根(`scripts/deck-slide.js` → 项目 `deck-slide.js`,不保留子目录);闭包内同名 basename 撞车时后者覆盖前者。
77
99
  - **skip-by-disk**:项目已有同名(拍平后的 basename)文件默认跳过,`--overwrite` 才覆盖;不写任何安装记账文件,项目文件树即状态。
78
100
  - **add 回执带 usage**:`add` 结果的 `entries` 只列**你请求的条目**(不含被 `Depends` 传递拉进来的依赖——依赖照常落地在 `added`/`skipped`,但那是"管道"),逐条给出 `usage`(USAGE 块原文)与 `dependsOn`,Agent `add` 完即可直接读用法,无需再 `registry list`。请求的条目即使已存在被跳过也回带 usage(`status` 标 `added`/`skipped`,据此判断磁盘上是 registry 版还是你改过的旧版)。`--json` 结构为 `{registryVersion, added, skipped, dryRun, entries}`;pretty(默认)输出 `registry@<ver>` + `added:`/`skipped:` 逗号列表 + 各请求条目的 USAGE 块,稳定 label、无 JSON 数组、无截断,对 Agent 与人同样可读。
79
- - `--version <ver>` 指定 registry 包版本或 dist-tag(缺省 `latest`),`--dir <path>` 指定项目目录(缺省当前目录)。
101
+ - `--version <ver>` 指定 registry 包版本或 dist-tag(缺省 `latest`);`add` 的 `--dir <path>` 指定 copy-in 落地目录(缺省当前目录),不影响 `.spark/meta.json` 读取。
80
102
 
81
103
  ## 全局参数
82
104
 
@@ -22,6 +22,7 @@ function registerAppCommands(program, opts = {}) {
22
22
  registerAppGet(appCmd);
23
23
  registerAppUpdate(appCmd);
24
24
  registerAppExport(appCmd);
25
+ registerAppExportStandalone(appCmd);
25
26
  if (opts.includeInit) {
26
27
  registerAppInit(appCmd);
27
28
  registerAppSync(appCmd);
@@ -127,6 +128,10 @@ function registerAppExport(parent) {
127
128
  .option('--out <dir>', '输出目录(相对当前目录)', 'source_package/creative')
128
129
  .option('--checkpoint <n>', '按检查点版本导出;缺省为最新提交(HEAD)')
129
130
  .addHelpText('after', `
131
+ 与 'miaoda app export-standalone' 的区别(**两个命令语义无关,别选错**)
132
+ app export 导出源码归档(本命令)
133
+ app export-standalone 导出可本地访问的构建产物
134
+
130
135
  说明
131
136
  从服务端导出源应用(可以不是当前应用)的源码归档并解压到 --out 目录,导出完成后写
132
137
  --out/.upgrade-manifest.json(含 sourceAppId / 导出时间 / 文件数),供升级链路幂等
@@ -173,6 +178,65 @@ JSON 输出
173
178
  });
174
179
  }));
175
180
  }
181
+ function registerAppExportStandalone(parent) {
182
+ const cmd = parent
183
+ .command('export-standalone')
184
+ .description('把当前应用构建成自包含静态产物(目录 + zip),可脱离妙搭平台本地访问')
185
+ .option('--dir <path>', '项目目录,默认 cwd(需含 .spark/meta.json)')
186
+ .option('--out <dir>', '输出目录(相对项目根)', index_1.DEFAULT_STANDALONE_OUT)
187
+ .option('--dev-server <url>', '图片下载的请求前缀,默认沙箱网关 http://localhost:8080')
188
+ .addHelpText('after', `
189
+ 与 'miaoda app export' 的区别(**两个命令语义无关,别选错**)
190
+ app export 导出源码归档(创意应用升级链路的只读参考物)
191
+ app export-standalone 导出可本地访问的构建产物(本命令)
192
+
193
+ 支持的 stack
194
+ design-html / html / vite-react / nestjs-react-fullstack
195
+
196
+ 产物
197
+ <out>/ index.html + assets/ + images/(+ static/,vite 系有 shared/static 时)
198
+ <out>.zip 同内容的压缩包
199
+ 默认 <out> 是 dist/standalone —— 落在 dist/ 下是刻意的:dist 已在部署扫描的
200
+ EXCLUDES 与各模板 .gitignore 中,产物不会污染部署包、不会被误提交。
201
+ 代价:下一次构建会 rm -rf dist,导出产物是易失的。
202
+
203
+ 图片本地化
204
+ 只处理页面/代码里字面以 /spark/app 开头的 URL,经沙箱网关(localhost:8080)下载到
205
+ <out>/images/ 并改写成相对路径。其它挂载前缀(/spark/p/、/app/<id>、反代)不处理。
206
+ 接口运行时返回的 download_url 属动态 URL,静态扫描覆盖不到。
207
+
208
+ 已知限制
209
+ 只保证纯静态可看——接口调用会失败,不做数据快照。
210
+ 多路由 SPA 在 file:// 下不可用(BrowserRouter 匹配不上路径、pushState 抛 SecurityError),
211
+ 请用本地 HTTP server 打开;检测到时会在 warnings 里给 SPA_ROUTER_FILE_PROTOCOL。
212
+ design-html 的 cd-elements SDK 是 CDN 外链,断网打开自定义元素不渲染。
213
+
214
+ JSON 输出
215
+ {"data": {"appId": "...", "stack": "...", "out": "dist/standalone", "zip": "dist/standalone.zip",
216
+ "fileCount": N, "bytes": N,
217
+ "images": {"matched": N, "downloaded": N, "failed": [{"url": "...", "reason": "..."}]},
218
+ "rewrittenFiles": [...],
219
+ "warnings": [{"code": "...", "message": "..."}]}}
220
+
221
+ 失败
222
+ 单张图片下载失败 → 跳过并计入 images.failed + warnings,退出码 0。
223
+ 命中 > 0 但全部失败 → EXPORT_STANDALONE_IMAGE_ALL_FAILED,退出码 1(系统性问题)。
224
+ stack 不支持 → EXPORT_STANDALONE_STACK_UNSUPPORTED。
225
+ 构建失败 → EXPORT_STANDALONE_BUILD_FAILED。
226
+
227
+ 示例
228
+ $ miaoda app export-standalone
229
+ $ miaoda app export-standalone --out dist/share
230
+ $ miaoda app export-standalone --json
231
+ `);
232
+ cmd.action((0, shared_1.withHelp)(cmd, async (rawOpts) => {
233
+ await (0, index_1.handleAppExportStandalone)({
234
+ dir: rawOpts.dir,
235
+ out: rawOpts.out,
236
+ devServer: rawOpts.devServer,
237
+ });
238
+ }));
239
+ }
176
240
  function registerAppGet(parent) {
177
241
  const cmd = parent
178
242
  .command('get')
@@ -72,7 +72,7 @@ JSON 输出(stdout)
72
72
  }));
73
73
  const patchCmd = deployCmd
74
74
  .command('patch')
75
- .description('design-html 增量发布:按文件 create/update/delete,.html 增删时同步 routes.json')
75
+ .description('design-html 增量发布:按文件 create/update/delete,.html 变动时同步 routes.json')
76
76
  .option('--create <relpath>', '新增文件(可重复)', shared_1.collectRepeatedOption, [])
77
77
  .option('--update <relpath>', '覆盖已有文件(可重复)', shared_1.collectRepeatedOption, [])
78
78
  .option('--delete <relpath>', '删除文件(可重复)', shared_1.collectRepeatedOption, [])
@@ -80,10 +80,11 @@ JSON 输出(stdout)
80
80
  .addHelpText('after', `
81
81
  --dir 为项目目录(与 deploy 同名参数,默认当前目录)。
82
82
  仅支持 design-html(design_local_deploy)。路径为工程根相对路径(= 服务端 latest 下 key),
83
- 禁绝对路径与 ".."。--create/--update 的本地文件必须存在。.html 被新增/删除(路由集合变化)
84
- 时自动重算并随包更新 routes.json;纯 --update 现有 .html 只改内容,不动 routes.json。
85
- routes.json 每项为 {path, file}:path 为相对路径(不含 base 前缀,由消费侧拼接),file 为
86
- 对应源文件(如 / → index.html)。
83
+ 禁绝对路径与 ".."。--create/--update 的本地文件必须存在。改动里含任意 .html(增 / 改 / 删)
84
+ 时自动重算并随包更新 routes.json;纯非 .html 改动不动 routes.json。
85
+ routes.json 每项为 {path, file, name?}:path 为相对路径(不含 base 前缀,由消费侧拼接),
86
+ file 为对应源文件(如 / → index.html),name 为该 HTML 的 <title> 文本(方案名,可缺省,
87
+ 缺省时由消费侧 fallback 到 path)。
87
88
 
88
89
  JSON 输出
89
90
  {"data": {"upsertCount": <n>, "deleteCount": <n>, "actionsSent": <n>, "routesRegenerated": <bool>}}
@@ -33,8 +33,9 @@ function registerRegistryCommands(program) {
33
33
  - add 落地:拍平到项目根(包根 scripts/x.js → 项目 x.js);同名 basename 撞车时后者覆盖前者
34
34
 
35
35
  前置
36
- 当前目录(或 --dir)已走过 'miaoda app init',且 .spark/meta.json 的 stack 有对应
36
+ 当前工作目录已走过 'miaoda app init',且 .spark/meta.json 的 stack 有对应
37
37
  registry 包(当前支持 design-html / html);其余 stack 执行时报 REGISTRY_STACK_UNSUPPORTED
38
+ meta 一律从 cwd 读取,add 的 --dir 只影响 copy-in 落地目录
38
39
  `);
39
40
  registerRegistryList(registryCmd);
40
41
  registerRegistryAdd(registryCmd);
@@ -43,7 +44,6 @@ function registerRegistryList(parent) {
43
44
  const cmd = parent
44
45
  .command('list')
45
46
  .description('列出 registry 可用 SDK 条目,输出各文件的 USAGE 块原文')
46
- .option('--dir <path>', '项目目录,默认当前目录', '.')
47
47
  .option('--version <ver>', 'registry 包版本或 dist-tag,缺省 latest')
48
48
  .addHelpText('after', `
49
49
  输出
@@ -59,7 +59,6 @@ JSON 输出
59
59
  `);
60
60
  cmd.action((0, shared_1.withHelp)(cmd, async (rawOpts) => {
61
61
  await (0, index_1.handleRegistryList)({
62
- dir: rawOpts.dir,
63
62
  version: rawOpts.version,
64
63
  });
65
64
  }));
@@ -69,7 +68,7 @@ function registerRegistryAdd(parent) {
69
68
  .command('add')
70
69
  .description('把一个或多个 SDK 文件 copy-in 到当前项目(拍平到项目根,含 Depends 闭包)')
71
70
  .argument('<token...>', 'name / 完整文件名 / relPath,可传多个;同名多匹配全拉,Depends 自动传递解析')
72
- .option('--dir <path>', '项目目录,默认当前目录', '.')
71
+ .option('--dir <path>', 'copy-in 落地目录,默认当前目录(stack 一律读 cwd 的 .spark/meta.json)', '.')
73
72
  .option('--version <ver>', 'registry 包版本或 dist-tag,缺省 latest')
74
73
  .option('--overwrite', '目标文件已存在时覆盖(默认跳过以保护用户改动)', false)
75
74
  .option('--dry-run', '只报告将写 / 将跳哪些文件,不落盘', false)
@@ -77,8 +76,9 @@ function registerRegistryAdd(parent) {
77
76
  行为
78
77
  - token 寻址:name(foo)/ 完整文件名(foo.css)/ relPath(stylesheets/foo.css)任一形式
79
78
  - 多匹配全拉:token 命中多个同名条目时全部 copy-in;想只要其一就写完整文件名 / relPath
80
- - 解析 USAGE 块 Depends 传递闭包,把 SDK 文件**拍平**拷到项目根
81
- (包根 scripts/deck-stage.js → 项目 deck-stage.js;同名 basename 撞车时后者覆盖前者)
79
+ - 解析 USAGE 块 Depends 传递闭包,把 SDK 文件**拍平**拷到落地目录(--dir,默认当前目录)
80
+ (包根 scripts/deck-stage.js → 落地 deck-stage.js;同名 basename 撞车时后者覆盖前者)
81
+ - stack 一律读当前工作目录的 .spark/meta.json,--dir 不影响 meta 读取
82
82
  - skip-by-disk:目标文件已存在默认跳过;--overwrite 才覆盖
83
83
  - 不写任何安装记账文件(项目文件树即状态)
84
84
 
@@ -0,0 +1,216 @@
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.DEFAULT_STANDALONE_OUT = void 0;
7
+ exports.handleAppExportStandalone = handleAppExportStandalone;
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const exclude_patterns_1 = require("../../../utils/exclude-patterns");
11
+ const spark_meta_1 = require("../../../utils/spark-meta");
12
+ const error_1 = require("../../../utils/error");
13
+ const output_1 = require("../../../utils/output");
14
+ const logger_1 = require("../../../utils/logger");
15
+ const index_1 = require("../../../services/app/export-standalone/index");
16
+ exports.DEFAULT_STANDALONE_OUT = 'dist/standalone';
17
+ /** 校验相对输出路径:禁绝对路径、禁含 ".." 段(与 app export 的 normalizeOutDir 同口径)。 */
18
+ function normalizeOutDir(rel) {
19
+ if (node_path_1.default.isAbsolute(rel) || rel.startsWith('/')) {
20
+ throw new error_1.AppError('ARGS_INVALID', `输出目录不能是绝对路径:${rel}`);
21
+ }
22
+ const posix = rel.split(node_path_1.default.sep).join('/').replace(/^\.\//, '');
23
+ if (posix.split('/').includes('..')) {
24
+ throw new error_1.AppError('ARGS_INVALID', `输出目录不能包含 "..":${rel}`);
25
+ }
26
+ return posix;
27
+ }
28
+ /** 沙箱网关地址:它才是代理 `/spark/app` 的那个服务(响应头 `Server: openresty`)。 */
29
+ const SANDBOX_GATEWAY_BASE = 'http://localhost:8080';
30
+ /**
31
+ * 图片下载的请求前缀。
32
+ *
33
+ * **刻意写死 8080,不读 `CLIENT_DEV_PORT`。** 那个 env 表示的是「应用自己的 dev server
34
+ * 监听端口」,与「谁在代理 `/spark/app`」是两回事:design-html / html 用
35
+ * `coding-static-server`(默认 8001,纯静态、完全不代理),读了它会把请求打到静态
36
+ * server 上,稳定 404。真机踩过。
37
+ */
38
+ function resolveDevServerBase(explicit) {
39
+ if (explicit)
40
+ return explicit.replace(/\/+$/, '');
41
+ return SANDBOX_GATEWAY_BASE;
42
+ }
43
+ /** 遍历产物树里的文本文件,返回 posix 相对路径。 */
44
+ function* walkText(dir, rel = '') {
45
+ for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
46
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
47
+ const abs = node_path_1.default.join(dir, entry.name);
48
+ if (entry.isDirectory())
49
+ yield* walkText(abs, childRel);
50
+ else if (index_1.TEXT_EXTENSIONS.has(node_path_1.default.extname(entry.name).toLowerCase()))
51
+ yield childRel;
52
+ }
53
+ }
54
+ /** 统计产物树的文件数与总字节数。 */
55
+ function measure(dir) {
56
+ let fileCount = 0;
57
+ let bytes = 0;
58
+ const walk = (cur) => {
59
+ for (const entry of node_fs_1.default.readdirSync(cur, { withFileTypes: true })) {
60
+ const abs = node_path_1.default.join(cur, entry.name);
61
+ if (entry.isDirectory())
62
+ walk(abs);
63
+ else {
64
+ fileCount += 1;
65
+ bytes += node_fs_1.default.statSync(abs).size;
66
+ }
67
+ }
68
+ };
69
+ walk(dir);
70
+ return { fileCount, bytes };
71
+ }
72
+ /**
73
+ * 扫**项目源码**里是否用了 BrowserRouter。
74
+ *
75
+ * preset 在 standalone 下会把它编译期换成 HashRouter(`standaloneRouterPlugin`),
76
+ * 换完 file:// 下路由完全可用。这里保留检测是为了**覆盖不到时给提示**:插件只替换
77
+ * 用户源码里字面的 `BrowserRouter` / `createBrowserRouter`,碰不到的情况有——
78
+ * 用户二次封装(`export const Router = BrowserRouter`)、非 react-router 的路由库、
79
+ * 代码里硬编码 `window.location.href = '/about'`。
80
+ *
81
+ * 命中时只是提示"若路由异常请用本地 server",不代表一定坏。
82
+ *
83
+ * ⚠️ **必须扫源码,不能扫产物**:编译型 stack 的产物经过 minify,`BrowserRouter`
84
+ * 这个标识符会被改名,扫产物永远命中不了 —— 而那恰恰是最需要这条警告的场景。
85
+ * 真机踩过:vite-react 应用源码里明明有 BrowserRouter、产物首屏渲染成 404,
86
+ * 但因为扫的是产物,warnings 是空的。
87
+ *
88
+ * 扫描面套 EXCLUDES(跳过 node_modules / dist 等),四个 stack 统一按项目根扫。
89
+ */
90
+ function detectBrowserRouter(projectDir) {
91
+ const walk = (dir) => {
92
+ for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
93
+ if (exclude_patterns_1.EXCLUDES.has(entry.name))
94
+ continue;
95
+ const abs = node_path_1.default.join(dir, entry.name);
96
+ let isDir;
97
+ try {
98
+ isDir = node_fs_1.default.statSync(abs).isDirectory();
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ if (isDir) {
104
+ if (walk(abs))
105
+ return true;
106
+ continue;
107
+ }
108
+ if (!index_1.TEXT_EXTENSIONS.has(node_path_1.default.extname(entry.name).toLowerCase()))
109
+ continue;
110
+ if (/\b(BrowserRouter|createBrowserRouter)\b/.test(node_fs_1.default.readFileSync(abs, 'utf-8'))) {
111
+ return true;
112
+ }
113
+ }
114
+ return false;
115
+ };
116
+ return walk(projectDir);
117
+ }
118
+ /**
119
+ * miaoda app export-standalone [--out <dir>]
120
+ *
121
+ * 把当前应用构建成自包含静态产物:按 stack 走各自的 strategy 产出可静态服务的目录树,
122
+ * 再扫出 `/spark/app` 图片经 dev server 代理下载到 `images/` 并改写成相对路径,最后打 zip。
123
+ *
124
+ * 设计文档:docs/superpowers/specs/2026-08-19-app-export-standalone-design.md
125
+ */
126
+ async function handleAppExportStandalone(opts) {
127
+ const projectDir = node_path_1.default.resolve(opts.dir ?? process.cwd());
128
+ const meta = (0, spark_meta_1.readSparkMeta)(projectDir);
129
+ if (!meta.stack) {
130
+ throw new error_1.AppError('ARGS_INVALID', '.spark/meta.json 缺少 stack —— 请先跑 miaoda app init', {
131
+ next_actions: ['cd 到应用根目录后重试,或先执行 miaoda app init'],
132
+ });
133
+ }
134
+ const strategy = (0, index_1.resolveStrategy)(meta.stack);
135
+ const outRel = normalizeOutDir(opts.out ?? exports.DEFAULT_STANDALONE_OUT);
136
+ const outDir = node_path_1.default.join(projectDir, outRel);
137
+ const zipRel = `${outRel}.zip`;
138
+ const zipPath = node_path_1.default.join(projectDir, zipRel);
139
+ // 1. stack-specific:产出可静态服务的目录树
140
+ strategy({ projectDir, outDir });
141
+ if (!node_fs_1.default.existsSync(outDir) || node_fs_1.default.readdirSync(outDir).length === 0) {
142
+ throw new error_1.AppError('EXPORT_STANDALONE_EMPTY_OUTPUT', '构建产物为空', {
143
+ next_actions: ['先手动跑一次该 stack 的构建命令确认工程本身可构建'],
144
+ });
145
+ }
146
+ // 2. 扫描
147
+ const urls = [];
148
+ const seen = new Set();
149
+ for (const rel of walkText(outDir)) {
150
+ for (const url of (0, index_1.scanSparkAppUrls)(node_fs_1.default.readFileSync(node_path_1.default.join(outDir, rel), 'utf-8'))) {
151
+ if (seen.has(url))
152
+ continue;
153
+ seen.add(url);
154
+ urls.push(url);
155
+ }
156
+ }
157
+ // 3. 下载
158
+ const devServerBase = resolveDevServerBase(opts.devServer);
159
+ (0, logger_1.log)('export-standalone', `Matched ${String(urls.length)} image url(s), fetching via ${devServerBase}`);
160
+ const { mapping, failed } = await (0, index_1.downloadImages)(urls, {
161
+ imagesDir: node_path_1.default.join(outDir, 'images'),
162
+ devServerBase,
163
+ });
164
+ // 命中 > 0 且全部失败 = 系统性问题(代理挂了 / 路径口径错),静默成功会误导调用方
165
+ if (urls.length > 0 && mapping.size === 0) {
166
+ throw new error_1.AppError('EXPORT_STANDALONE_IMAGE_ALL_FAILED', `命中 ${String(urls.length)} 张图片但全部下载失败`, {
167
+ next_actions: [
168
+ '确认 dev server 正在运行且能代理 /spark/app 路径',
169
+ `首个失败:${failed[0]?.url ?? '?'} → ${failed[0]?.reason ?? 'unknown'}`,
170
+ ...(failed.length > 1
171
+ ? [`其余 ${String(failed.length - 1)} 条见 --verbose(每条请求地址都会打到 stderr)`]
172
+ : []),
173
+ `实际请求前缀:${devServerBase}${opts.devServer ? '(--dev-server 指定)' : '(沙箱网关默认)'}`,
174
+ '若端口不对,可用 --dev-server http://localhost:<port> 覆盖',
175
+ ],
176
+ });
177
+ }
178
+ // 4. 改写
179
+ const rewrittenFiles = (0, index_1.rewriteTree)(outDir, mapping);
180
+ // 5. 打包
181
+ (0, index_1.zipDir)(outDir, zipPath);
182
+ // 6. 输出
183
+ const warnings = [];
184
+ if (failed.length > 0) {
185
+ warnings.push({
186
+ code: 'IMAGE_DOWNLOAD_PARTIAL_FAILURE',
187
+ message: `${String(failed.length)} 张图片下载失败,产物中保留原始绝对路径(离线打不开)`,
188
+ });
189
+ }
190
+ if (detectBrowserRouter(projectDir)) {
191
+ warnings.push({
192
+ code: 'SPA_ROUTER_FILE_PROTOCOL',
193
+ message: '检测到 BrowserRouter:standalone 构建已自动换成 HashRouter,路由形如 index.html#/about。' +
194
+ '若你对 router 做过二次封装或用了非 react-router 的方案,替换可能覆盖不到 —— ' +
195
+ '此时产物在 file:// 下路由会失效(首屏落 404 页),请改用本地 HTTP server 并从 / 访问。',
196
+ });
197
+ }
198
+ const { fileCount, bytes } = measure(outDir);
199
+ (0, output_1.emit)({
200
+ data: {
201
+ appId: meta.app_id ?? '',
202
+ stack: meta.stack,
203
+ out: outRel,
204
+ zip: zipRel,
205
+ fileCount,
206
+ bytes,
207
+ images: {
208
+ matched: urls.length,
209
+ downloaded: mapping.size,
210
+ failed,
211
+ },
212
+ rewrittenFiles,
213
+ warnings,
214
+ },
215
+ });
216
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SUPPORTED_STACKS = exports.handleAppMigrate = exports.UPGRADE_MANIFEST_FILENAME = exports.DEFAULT_EXPORT_OUT = exports.handleAppExport = exports.handleAppUpgrade = exports.handleAppSync = exports.handleAppInit = exports.handleAppUpdate = exports.handleAppGet = void 0;
3
+ exports.DEFAULT_STANDALONE_OUT = exports.handleAppExportStandalone = exports.SUPPORTED_STACKS = exports.handleAppMigrate = exports.UPGRADE_MANIFEST_FILENAME = exports.DEFAULT_EXPORT_OUT = exports.handleAppExport = exports.handleAppUpgrade = exports.handleAppSync = exports.handleAppInit = exports.handleAppUpdate = exports.handleAppGet = void 0;
4
4
  var get_1 = require("./get");
5
5
  Object.defineProperty(exports, "handleAppGet", { enumerable: true, get: function () { return get_1.handleAppGet; } });
6
6
  var update_1 = require("./update");
@@ -19,3 +19,6 @@ Object.defineProperty(exports, "handleAppMigrate", { enumerable: true, get: func
19
19
  // commands 层渲染 help 时需要这份枚举;从 handler barrel 转发,避免 commands → services 越界
20
20
  var index_1 = require("../../../services/app/init/index");
21
21
  Object.defineProperty(exports, "SUPPORTED_STACKS", { enumerable: true, get: function () { return index_1.SUPPORTED_STACKS; } });
22
+ var export_standalone_1 = require("./export-standalone");
23
+ Object.defineProperty(exports, "handleAppExportStandalone", { enumerable: true, get: function () { return export_standalone_1.handleAppExportStandalone; } });
24
+ Object.defineProperty(exports, "DEFAULT_STANDALONE_OUT", { enumerable: true, get: function () { return export_standalone_1.DEFAULT_STANDALONE_OUT; } });
@@ -13,7 +13,8 @@ const output_1 = require("../../../utils/output");
13
13
  * miaoda registry add <name...> [--overwrite] [--dry-run] [--dir <path>] [--version <ver>]
14
14
  *
15
15
  * 解析 USAGE 块 Depends 传递闭包,把每个条目对应的 SDK 文件从 registry 包根的 <relPath>
16
- * **保留相对路径**拷到项目根(--dir 指定目录的根)。
16
+ * **保留相对路径**拷到落地目录(--dir,默认 cwd)。stack 一律从 <cwd>/.spark/meta.json 读,
17
+ * 不随 --dir 走。
17
18
  * skip-by-disk:目标已存在默认跳过,--overwrite 才覆盖。不写任何安装记账文件。
18
19
  */
19
20
  async function handleRegistryAdd(opts) {
@@ -22,7 +23,7 @@ async function handleRegistryAdd(opts) {
22
23
  throw new error_1.AppError('ARGS_INVALID', 'registry add 至少需要一个条目名');
23
24
  }
24
25
  const targetDir = node_path_1.default.resolve(opts.dir ?? process.cwd());
25
- const stack = (0, shared_1.resolveRegistryStack)(targetDir);
26
+ const stack = (0, shared_1.resolveRegistryStack)();
26
27
  const reg = (0, index_1.loadRegistry)({ stack, version: opts.version });
27
28
  try {
28
29
  const plan = (0, index_1.planAdd)({
@@ -1,17 +1,13 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.handleRegistryList = handleRegistryList;
7
- const node_path_1 = __importDefault(require("node:path"));
8
4
  const index_1 = require("../../../services/registry/index");
9
5
  const shared_1 = require("./shared");
10
6
  const output_1 = require("../../../utils/output");
11
7
  /**
12
- * miaoda registry list [--dir <path>] [--version <ver>]
8
+ * miaoda registry list [--version <ver>]
13
9
  *
14
- * 从 .spark/meta.json 读 stack → runtime → 包名,拉对应 registry 包,从包根递归扫含 USAGE 块的 SDK 文件。
10
+ * 从 <cwd>/.spark/meta.json 读 stack → runtime → 包名,拉对应 registry 包,从包根递归扫含 USAGE 块的 SDK 文件。
15
11
  *
16
12
  * - 默认(pretty):输出各条目 USAGE 块原文,带文件名分隔,给 Agent 直接读注释。
17
13
  * - --json:输出 [{name, file, usage(原文字符串), dependsOn[]}],usage 保持原文不解析成字段。
@@ -19,8 +15,7 @@ const output_1 = require("../../../utils/output");
19
15
  */
20
16
  async function handleRegistryList(opts) {
21
17
  await Promise.resolve();
22
- const targetDir = node_path_1.default.resolve(opts.dir ?? process.cwd());
23
- const stack = (0, shared_1.resolveRegistryStack)(targetDir);
18
+ const stack = (0, shared_1.resolveRegistryStack)();
24
19
  const reg = (0, index_1.loadRegistry)({ stack, version: opts.version });
25
20
  try {
26
21
  if ((0, output_1.isJsonMode)()) {
@@ -5,16 +5,20 @@ const spark_meta_1 = require("../../../utils/spark-meta");
5
5
  const index_1 = require("../../../services/registry/index");
6
6
  const error_1 = require("../../../utils/error");
7
7
  /**
8
- * 从 <targetDir>/.spark/meta.json 读 stack,校验该 stack 有组件 registry。
8
+ * 从 <cwd>/.spark/meta.json 读 stack,校验该 stack 有组件 registry。
9
+ * meta 只与当前工作目录相关(CLI 必须在 user app 根目录下运行),不随 --dir 走——
10
+ * --dir 只影响 add 的 copy-in 落地目录。
9
11
  * 缺 stack → 提示先 init;stack 无 registry(无对应 runtime / runtime 无 registry 包)→ 提示支持哪些 stack。
10
12
  *
11
13
  * 这里只做「stack 是否在支持列表」的早校验给用户友好提示;包名的两跳解析
12
14
  * (stack → runtime → 包)由 loadRegistry/resolveRegistryPackage 负责。
13
15
  */
14
- function resolveRegistryStack(targetDir) {
15
- const meta = (0, spark_meta_1.readSparkMeta)(targetDir);
16
+ function resolveRegistryStack() {
17
+ const meta = (0, spark_meta_1.readSparkMeta)(process.cwd());
16
18
  if (meta.stack === undefined || meta.stack === '') {
17
- throw new error_1.AppError('REGISTRY_META_INCOMPLETE', '.spark/meta.json missing stack — run `miaoda app init` first');
19
+ throw new error_1.AppError('REGISTRY_META_INCOMPLETE', '.spark/meta.json missing stack — run `miaoda app init` first', {
20
+ next_actions: ['meta 一律读当前工作目录(不随 --dir),请 cd 到 user app 根目录后重试'],
21
+ });
18
22
  }
19
23
  if (!index_1.REGISTRY_SUPPORTED_STACKS.includes(meta.stack)) {
20
24
  throw new error_1.AppError('REGISTRY_STACK_UNSUPPORTED', `stack "${meta.stack}" 没有组件 registry`, {
@@ -0,0 +1,33 @@
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.zipDir = zipDir;
7
+ const node_child_process_1 = require("node:child_process");
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const error_1 = require("../../../utils/error");
11
+ /**
12
+ * 把 `dir` 的**内容**打成 zip(解压后直接是 index.html,不多一层目录)。
13
+ *
14
+ * 走系统 `zip` 而非引 npm 依赖:仓库现有的 `app export` 也是 shell 出去调 `unzip`/`tar`,
15
+ * 保持一致,且避免为一个收尾动作增加运行时依赖。
16
+ *
17
+ * 覆盖语义:`zip` 默认是**增量更新**已存在的归档(会残留上次的文件),
18
+ * 所以先删掉目标文件再打,保证重跑导出幂等。
19
+ */
20
+ function zipDir(dir, zipPath) {
21
+ if (!node_fs_1.default.existsSync(dir)) {
22
+ throw new error_1.AppError('EXPORT_STANDALONE_ARCHIVE_FAILED', `待打包目录不存在:${dir}`);
23
+ }
24
+ node_fs_1.default.rmSync(zipPath, { force: true });
25
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(zipPath), { recursive: true });
26
+ try {
27
+ // cwd=dir + '.' → 归档内是目录内容而非目录本身
28
+ (0, node_child_process_1.execFileSync)('zip', ['-qr', zipPath, '.'], { cwd: dir, stdio: 'pipe' });
29
+ }
30
+ catch (err) {
31
+ throw new error_1.AppError('EXPORT_STANDALONE_ARCHIVE_FAILED', `zip failed: ${err.message}`, { next_actions: ['确认运行环境有 zip 命令(沙箱镜像应自带)'] });
32
+ }
33
+ }
@@ -0,0 +1,51 @@
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.copyTree = copyTree;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const error_1 = require("../../../utils/error");
10
+ /**
11
+ * 递归拷贝目录树到 `out`(先清空 out)。
12
+ *
13
+ * `design-html` 与 `html` 共用:两者的 standalone 构建都只是纯文件搬运,
14
+ * 差别仅在 `root`(项目根 vs `src/`)与 `excludes`(EXCLUDES vs 无)。
15
+ *
16
+ * 用 `statSync` 判目录以 **follow 符号链接**,与 `source-scan.ts` 的 `listSourceFiles`
17
+ * 同口径(design-html 的 `.claude/skills` 是指向 `.agents/skills` 的软链)。
18
+ */
19
+ function copyTree(root, out, excludes) {
20
+ if (!node_fs_1.default.existsSync(root)) {
21
+ throw new error_1.AppError('EXPORT_STANDALONE_EMPTY_OUTPUT', `源目录不存在:${root}`, {
22
+ next_actions: ['确认已在应用根目录下执行,且项目结构完整'],
23
+ });
24
+ }
25
+ node_fs_1.default.rmSync(out, { recursive: true, force: true });
26
+ node_fs_1.default.mkdirSync(out, { recursive: true });
27
+ const walk = (dir, rel) => {
28
+ for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
29
+ if (excludes?.has(entry.name))
30
+ continue;
31
+ const abs = node_path_1.default.join(dir, entry.name);
32
+ const childRel = rel ? node_path_1.default.join(rel, entry.name) : entry.name;
33
+ let isDir;
34
+ try {
35
+ isDir = node_fs_1.default.statSync(abs).isDirectory();
36
+ }
37
+ catch {
38
+ continue; // 断链等无法 stat 的条目跳过
39
+ }
40
+ if (isDir) {
41
+ walk(abs, childRel);
42
+ }
43
+ else {
44
+ const dest = node_path_1.default.join(out, childRel);
45
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(dest), { recursive: true });
46
+ node_fs_1.default.copyFileSync(abs, dest);
47
+ }
48
+ }
49
+ };
50
+ walk(root, '');
51
+ }