@coze-arch/cli 0.1.5 → 0.1.8-alpha.2ee669

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 (63) hide show
  1. package/README.md +18 -0
  2. package/docs/deploy.md +12 -1
  3. package/lib/__templates__/expo/.cozeproj/scripts/dev_build.sh +3 -3
  4. package/lib/__templates__/expo/.cozeproj/scripts/dev_run.sh +11 -3
  5. package/lib/__templates__/expo/.cozeproj/scripts/prepare-node-modules.sh +380 -0
  6. package/lib/__templates__/expo/.cozeproj/scripts/prod_build.sh +3 -3
  7. package/lib/__templates__/expo/client/components/Screen.tsx +65 -25
  8. package/lib/__templates__/expo/client/heroui/components/toast/toast.tsx +6 -2
  9. package/lib/__templates__/expo/client/heroui/helpers/internal/hooks/use-controllable-state.ts +1 -1
  10. package/lib/__templates__/native-static/.coze +2 -2
  11. package/lib/__templates__/nextjs/.coze +1 -1
  12. package/lib/__templates__/nextjs/README.md +18 -0
  13. package/lib/__templates__/nextjs/eslint.config.mjs +11 -5
  14. package/lib/__templates__/nextjs/next.config.ts +10 -0
  15. package/lib/__templates__/nextjs/package.json +2 -5
  16. package/lib/__templates__/nextjs/pnpm-lock.yaml +14 -945
  17. package/lib/__templates__/nextjs/scripts/build.ps1 +1 -1
  18. package/lib/__templates__/nextjs/scripts/build.sh +1 -1
  19. package/lib/__templates__/nextjs/scripts/dev.ps1 +2 -2
  20. package/lib/__templates__/nextjs/scripts/dev.sh +70 -12
  21. package/lib/__templates__/nextjs/scripts/local-workspace.cjs +302 -0
  22. package/lib/__templates__/nextjs/scripts/prepare-node-modules.sh +380 -0
  23. package/lib/__templates__/nextjs/scripts/prepare.sh +9 -4
  24. package/lib/__templates__/nextjs/scripts/validate.sh +11 -1
  25. package/lib/__templates__/nextjs/src/app/layout.tsx +0 -4
  26. package/lib/__templates__/nextjs/src/server.ts +1 -1
  27. package/lib/__templates__/nextjs/template.config.js +20 -6
  28. package/lib/__templates__/nextjs/tsconfig.json +0 -1
  29. package/lib/__templates__/nuxt-vue/.coze +1 -1
  30. package/lib/__templates__/nuxt-vue/README.md +20 -2
  31. package/lib/__templates__/nuxt-vue/scripts/dev.sh +21 -7
  32. package/lib/__templates__/nuxt-vue/scripts/local-workspace.cjs +302 -0
  33. package/lib/__templates__/nuxt-vue/scripts/prepare-node-modules.sh +380 -0
  34. package/lib/__templates__/nuxt-vue/scripts/prepare.sh +9 -4
  35. package/lib/__templates__/nuxt-vue/scripts/validate.sh +11 -1
  36. package/lib/__templates__/taro/.coze +2 -2
  37. package/lib/__templates__/taro/.cozeproj/scripts/deploy_build.sh +10 -1
  38. package/lib/__templates__/taro/.cozeproj/scripts/deploy_run.sh +4 -0
  39. package/lib/__templates__/taro/.cozeproj/scripts/dev_build.sh +12 -0
  40. package/lib/__templates__/taro/.cozeproj/scripts/dev_run.ps1 +4 -2
  41. package/lib/__templates__/taro/.cozeproj/scripts/dev_run.sh +84 -10
  42. package/lib/__templates__/taro/.cozeproj/scripts/init_env.sh +4 -0
  43. package/lib/__templates__/taro/.cozeproj/scripts/local-workspace.cjs +351 -0
  44. package/lib/__templates__/taro/.cozeproj/scripts/pack.ps1 +3 -1
  45. package/lib/__templates__/taro/.cozeproj/scripts/pack.sh +24 -6
  46. package/lib/__templates__/taro/.cozeproj/scripts/prepare-node-modules.sh +380 -0
  47. package/lib/__templates__/taro/.cozeproj/scripts/taro-build.cjs +66 -0
  48. package/lib/__templates__/taro/.cozeproj/scripts/validate.ps1 +3 -1
  49. package/lib/__templates__/taro/.cozeproj/scripts/validate.sh +7 -0
  50. package/lib/__templates__/taro/_gitignore +1 -0
  51. package/lib/__templates__/taro/package.json +5 -5
  52. package/lib/__templates__/vite/.coze +1 -1
  53. package/lib/__templates__/vite/README.md +20 -0
  54. package/lib/__templates__/vite/scripts/dev.ps1 +2 -2
  55. package/lib/__templates__/vite/scripts/dev.sh +21 -7
  56. package/lib/__templates__/vite/scripts/local-workspace.cjs +302 -0
  57. package/lib/__templates__/vite/scripts/prepare-node-modules.sh +380 -0
  58. package/lib/__templates__/vite/scripts/prepare.sh +9 -4
  59. package/lib/__templates__/vite/scripts/validate.sh +7 -1
  60. package/lib/__templates__/vite/template.config.js +20 -6
  61. package/lib/cli.js +511 -199
  62. package/package.json +3 -2
  63. package/lib/__templates__/nextjs/.babelrc +0 -15
@@ -8,7 +8,7 @@ Write-Host "Installing dependencies..."
8
8
  if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
9
9
 
10
10
  Write-Host "Building the Next.js project..."
11
- & pnpm next build
11
+ & pnpm next build --webpack
12
12
  if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
13
13
 
14
14
  Write-Host "Bundling server with tsup..."
@@ -9,7 +9,7 @@ echo "Installing dependencies..."
9
9
  pnpm install --prefer-frozen-lockfile --prefer-offline --loglevel debug --reporter=append-only
10
10
 
11
11
  echo "Building the Next.js project..."
12
- pnpm next build
12
+ pnpm next build --webpack
13
13
 
14
14
  echo "Bundling server with tsup..."
15
15
  pnpm tsup src/server.ts --format cjs --platform node --target node20 --outDir dist --no-splitting --no-minify
@@ -28,7 +28,7 @@ Stop-ListeningProcess $port
28
28
 
29
29
  <% if (process.env.NODE_ENV === 'test') { %>
30
30
  $env:PORT = "$port"
31
- & pnpm tsx watch src/server.ts
31
+ & pnpm next dev --webpack --hostname 0.0.0.0 --port $port
32
32
  exit $LASTEXITCODE
33
33
  <% } else { %>
34
34
  $logDirectory = if ($env:COZE_LOG_DIR) { $env:COZE_LOG_DIR } else { Join-Path $workspace "logs" }
@@ -45,7 +45,7 @@ if (Test-Path $pidFile) {
45
45
  $previousPort = $env:PORT
46
46
  $env:PORT = "$port"
47
47
  try {
48
- $process = Start-Process -FilePath $env:ComSpec -ArgumentList @("/d", "/s", "/c", "pnpm tsx watch src/server.ts") -WorkingDirectory $workspace -RedirectStandardOutput $logFile -RedirectStandardError $errorLogFile -PassThru
48
+ $process = Start-Process -FilePath $env:ComSpec -ArgumentList @("/d", "/s", "/c", "pnpm next dev --webpack --hostname 0.0.0.0 --port $port") -WorkingDirectory $workspace -RedirectStandardOutput $logFile -RedirectStandardError $errorLogFile -PassThru
49
49
  } finally {
50
50
  if ($null -eq $previousPort) { Remove-Item Env:PORT -ErrorAction SilentlyContinue } else { $env:PORT = $previousPort }
51
51
  }
@@ -1,14 +1,20 @@
1
1
  #!/bin/bash
2
2
  set -Eeuo pipefail
3
3
 
4
+ # Resolve the source project from this script, then let the Web runner choose its local mirror.
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
6
+ PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd -P)"
7
+ if [[ "${COZE_WEB_LOCAL_ACTIVE:-}" != "${PROJECT_ROOT}" ]]; then
8
+ exec node "${SCRIPT_DIR}/local-workspace.cjs" dev "$@"
9
+ fi
10
+ COZE_WORKSPACE_PATH="${PROJECT_ROOT}"
11
+
4
12
  <% if (process.env.NODE_ENV === 'test') { %>
5
13
  # 测试环境:支持环境变量覆盖端口
6
14
  PORT="${PORT:-<%= port %>}"
7
- COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-$(pwd)}"
8
15
  DEPLOY_RUN_PORT="${DEPLOY_RUN_PORT:-${PORT}}"
9
16
  <% } else { %>
10
17
  PORT="${DEPLOY_RUN_PORT:-${PORT:-<%= port %>}}"
11
- COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-$(pwd)}"
12
18
  DEPLOY_RUN_PORT="${DEPLOY_RUN_PORT:-${PORT}}"
13
19
  <% } %>
14
20
 
@@ -52,24 +58,52 @@ kill_port_if_listening() {
52
58
  echo "Port ${DEPLOY_RUN_PORT} cleared."
53
59
  }
54
60
 
61
+ # Next 的路由清单由 watchpack 每次启动重新扫 src 下的 app/pages 目录现算,而 watchpack
62
+ # 不会进入软链目录,软链子树里的 page/route 会被静默跳过:既不注册路由,也不打任何日志,
63
+ # 表现为该路由一直 404 而 .next 里没有它的产物。这里只做提示,不改动源码。
64
+ warn_source_symlinks() {
65
+ local source_dir="${COZE_WORKSPACE_PATH}/src"
66
+ local links link
67
+ if [[ ! -e "${source_dir}" ]]; then
68
+ return
69
+ fi
70
+ links=$(find "${source_dir}" -type l 2>/dev/null || true)
71
+ if [[ -z "${links}" ]]; then
72
+ return
73
+ fi
74
+ echo "Warning: 以下路径是软链,Next 不会进入其中,里面的 page/route 不会被编译:" >&2
75
+ while IFS= read -r link; do
76
+ echo " ${link}" >&2
77
+ done <<< "${links}"
78
+ }
79
+
55
80
  <% if (process.env.NODE_ENV === 'test') { %>
56
81
  echo "Clearing port ${DEPLOY_RUN_PORT} before start."
57
82
  kill_port_if_listening
83
+ if [[ "${COZE_WEB_LOCAL_MIRROR:-}" != "1" ]]; then
84
+ COZE_REUSE_NODE_MODULES=1 bash "${COZE_WORKSPACE_PATH}/scripts/prepare-node-modules.sh" --prefer-frozen-lockfile --prefer-offline --loglevel debug --reporter=append-only
85
+ fi
86
+ warn_source_symlinks
58
87
  echo "Starting HTTP service on port ${DEPLOY_RUN_PORT} for dev..."
59
88
 
60
89
  # 测试环境保持服务为前台进程,便于 e2e 收集输出并停止进程。
61
- exec env PORT="${DEPLOY_RUN_PORT}" pnpm tsx watch src/server.ts
90
+ # 开发环境直接使用 Next dev CLI,避免云盘文件事件在 custom server 链路中丢失。
91
+ exec node "${SCRIPT_DIR}/local-workspace.cjs" watch pnpm next dev --webpack --hostname 0.0.0.0 --port "${DEPLOY_RUN_PORT}"
62
92
  <% } else { %>
63
93
  LOG_DIR="${COZE_LOG_DIR:-${COZE_WORKSPACE_PATH}/logs}"
64
94
  LOG_FILE="${LOG_DIR}/app.log"
65
95
  PID_FILE="${LOG_DIR}/server.pid"
66
96
 
67
97
  # detached 出去的进程没人负责回收,超过这个时长就自己退出,避免端口与内存长期泄露。
68
- MAX_RUNTIME_SECONDS=1200
98
+ MAX_RUNTIME_SECONDS=3600
99
+
100
+ timeout_watchdog_enabled() {
101
+ [[ -z "${COZE_EVAL:-}" && -z "${COZE_PROJECT_TYPE:-}" ]]
102
+ }
69
103
 
70
104
  # 真正被 detach 的是这层 bash wrapper:它是进程组 leader,组内 watchdog 到点回收整组
71
- # (wrapper -> pnpm -> tsx -> node);被包的进程自己先退出时也顺手清空进程组,不留残余。
72
- RUN_WITH_TIMEOUT='
105
+ # (wrapper -> pnpm -> next -> node);被包的进程自己先退出时也顺手清空进程组,不留残余。
106
+ RUN_WITH_TIMEOUT="$(declare -f timeout_watchdog_enabled)"'
73
107
  timeout_seconds=$1
74
108
  shift
75
109
 
@@ -77,6 +111,7 @@ shift
77
111
  child_pid=$!
78
112
 
79
113
  # 先忽略 TERM,才能在向整组发 TERM(自己也在组里)之后存活下来补一发 KILL。
114
+ if timeout_watchdog_enabled; then
80
115
  ( trap "" TERM
81
116
  sleep "${timeout_seconds}"
82
117
  echo "[dev] 后台进程运行超过 ${timeout_seconds}s,回收进程组 $$。"
@@ -84,6 +119,7 @@ child_pid=$!
84
119
  sleep 5
85
120
  kill -KILL -- "-$$" 2>/dev/null || true
86
121
  ) &
122
+ fi
87
123
 
88
124
  wait "${child_pid}"
89
125
  kill -KILL -- "-$$" 2>/dev/null || true
@@ -132,7 +168,7 @@ stop_detached() {
132
168
  kill -KILL -- "-${pid}" 2>/dev/null || true
133
169
  }
134
170
 
135
- READY_RETRIES=10
171
+ READY_RETRIES=30
136
172
  READY_PROBE_HOSTS=("127.0.0.1" "::1")
137
173
  LOG_TAIL_LINES=40
138
174
 
@@ -142,6 +178,21 @@ dump_log() {
142
178
  echo "---- end of ${LOG_FILE} ----" >&2
143
179
  }
144
180
 
181
+ # 服务刚就绪时 app-paths-manifest.json 还是空的(dev 按需编译,没请求就没产物),
182
+ # 但 .next/dev/types/routes.d.ts 已经写出了本次启动发现到的全部路由。把它落进日志,
183
+ # 排查时才能区分“路由没被发现”和“路由发现了但还没编译”。
184
+ dump_discovered_routes() {
185
+ local route_types="${COZE_WORKSPACE_PATH}/.next/dev/types/routes.d.ts"
186
+ if [[ ! -f "${route_types}" ]]; then
187
+ return
188
+ fi
189
+ {
190
+ echo "---- discovered routes (${route_types}) ----"
191
+ grep -E '^type (AppRoutes|AppRouteHandlerRoutes|PageRoutes) ' "${route_types}" || true
192
+ echo "---- end of discovered routes ----"
193
+ } >> "${LOG_FILE}"
194
+ }
195
+
145
196
  # 仅用于无 ss/lsof 时的兜底探测。服务可能只 bind IPv4 loopback、只 bind IPv6 loopback
146
197
  # (server.listen(port, 'localhost') 会变成 ::1 独占),或 bind 双栈通配地址,
147
198
  port_connectable() {
@@ -215,7 +266,7 @@ wait_for_ready() {
215
266
  return 2
216
267
  }
217
268
 
218
- # 监听端口的是孙进程(pnpm -> tsx -> node),只清端口会漏掉上层 pnpm/tsx
269
+ # 监听端口的是孙进程(pnpm -> next -> node),只清端口会漏掉上层 pnpm/next
219
270
  # 所以先按上次记录的 PID 把整个进程组回收掉。
220
271
  if [[ -f "${PID_FILE}" ]]; then
221
272
  stop_detached "$(cat "${PID_FILE}" 2>/dev/null || true)"
@@ -224,6 +275,10 @@ fi
224
275
 
225
276
  echo "Clearing port ${DEPLOY_RUN_PORT} before start."
226
277
  kill_port_if_listening
278
+ if [[ "${COZE_WEB_LOCAL_MIRROR:-}" != "1" ]]; then
279
+ COZE_REUSE_NODE_MODULES=1 bash "${COZE_WORKSPACE_PATH}/scripts/prepare-node-modules.sh" --prefer-frozen-lockfile --prefer-offline --loglevel debug --reporter=append-only
280
+ fi
281
+ warn_source_symlinks
227
282
  echo "Starting HTTP service on port ${DEPLOY_RUN_PORT} for dev..."
228
283
 
229
284
  mkdir -p "${LOG_DIR}"
@@ -231,7 +286,7 @@ mkdir -p "${LOG_DIR}"
231
286
 
232
287
  export PORT="${DEPLOY_RUN_PORT}"
233
288
  server_pid="$(spawn_detached "${COZE_WORKSPACE_PATH}" "${LOG_FILE}" \
234
- "$(command -v pnpm)" tsx watch src/server.ts)"
289
+ "$(command -v node)" "${SCRIPT_DIR}/local-workspace.cjs" watch "$(command -v pnpm)" next dev --webpack --hostname 0.0.0.0 --port "${DEPLOY_RUN_PORT}")"
235
290
  if [[ -z "${server_pid}" ]]; then
236
291
  echo "Dev server failed to start: 未获取到后台进程 PID。" >&2
237
292
  dump_log
@@ -247,8 +302,7 @@ fi
247
302
 
248
303
  if [[ "${ready_status}" -ne 0 ]]; then
249
304
  if [[ "${ready_status}" -eq 2 ]]; then
250
- # 进程还活着但迟迟没监听端口:多半是编译/运行时报错后 tsx watch 驻留,日志里有真正原因。
251
- echo "Dev server 在 ${READY_RETRIES} 次探测(每次 1s)内未就绪于端口 ${DEPLOY_RUN_PORT}(进程 ${server_pid} 仍在运行,已回收)。" >&2
305
+ echo "Dev server did not listen on port ${DEPLOY_RUN_PORT} after ${READY_RETRIES} attempts; stopping PID ${server_pid}." >&2
252
306
  else
253
307
  echo "Dev server failed to start. See ${LOG_FILE}." >&2
254
308
  fi
@@ -259,8 +313,12 @@ if [[ "${ready_status}" -ne 0 ]]; then
259
313
  exit 1
260
314
  fi
261
315
 
316
+ dump_discovered_routes
317
+
262
318
  echo "Dev server started (PID: ${server_pid}), listening on port ${DEPLOY_RUN_PORT}."
263
- echo "Auto stop after ${MAX_RUNTIME_SECONDS}s."
319
+ if timeout_watchdog_enabled; then
320
+ echo "Auto stop after ${MAX_RUNTIME_SECONDS}s."
321
+ fi
264
322
  echo "Log file: ${LOG_FILE}"
265
323
  echo "PID file: ${PID_FILE}"
266
324
  <% } %>
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+ // Web source is owned by Drive. Only these wrappers may write to the local mirror.
3
+ /* eslint-disable @typescript-eslint/no-require-imports -- Standalone CommonJS runtime shipped without CLI dependencies. */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const os = require('node:os');
7
+ const { createHash } = require('node:crypto');
8
+ const { spawn, execFileSync } = require('node:child_process');
9
+ const { setTimeout: delay } = require('node:timers/promises');
10
+
11
+ const scriptRoot = fs.realpathSync(path.resolve(__dirname, '..'));
12
+ const source = fs.realpathSync(
13
+ process.env.COZE_WEB_LOCAL_ACTIVE === scriptRoot && process.env.COZE_WEB_SOURCE_PATH
14
+ ? process.env.COZE_WEB_SOURCE_PATH : scriptRoot,
15
+ );
16
+ const drivePath = path.resolve(process.env.COZE_DRIVE_ROOT || '/Coze/Drive');
17
+ const drive = fs.existsSync(drivePath) ? fs.realpathSync(drivePath) : drivePath;
18
+ const inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path.sep}`);
19
+ const onDrive = inside(drive, source);
20
+ const digest = value => createHash('sha256').update(value).digest('hex');
21
+ // Separate from /tmp/nm: older dependency helpers clean unknown entries there.
22
+ const cacheRoot = path.join(os.tmpdir(), `coze-web-${process.getuid()}`);
23
+ const projectCache = path.join(cacheRoot, digest(source));
24
+ const exclusions = [
25
+ 'node_modules', '.git', '/logs', '.pnpm-store', '.next', '.nuxt', '.output',
26
+ '/dist', '/dist-server', '.cache', '.turbo', '*.tsbuildinfo',
27
+ '.eslintcache', '.stylelintcache', '/next-env.d.ts', '/tsconfig.json',
28
+ ];
29
+ const installArgs = ['install', '--prefer-frozen-lockfile', '--prefer-offline'];
30
+ let interrupted = false;
31
+ const children = new Set();
32
+
33
+ function stopTree(child) {
34
+ if (!child.pid || child.exitCode !== null) return;
35
+ // Keep descendants in the detached launcher's group so readiness ownership works.
36
+ // Also stop grandchildren when the test/foreground path is signalled directly.
37
+ let rows = [];
38
+ try {
39
+ rows = execFileSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8' })
40
+ .trim().split('\n').map(line => line.trim().split(/\s+/).map(Number));
41
+ } catch { /* The launcher still owns and reaps its process group. */ }
42
+ const pids = [child.pid];
43
+ for (let i = 0; i < pids.length; i++) {
44
+ for (const [pid, parent] of rows) if (parent === pids[i]) pids.push(pid);
45
+ }
46
+ for (const pid of pids.reverse()) {
47
+ try { process.kill(pid, 'SIGTERM'); } catch { /* Already exited. */ }
48
+ }
49
+ const timer = setTimeout(() => {
50
+ for (const pid of pids) {
51
+ try { process.kill(pid, 'SIGKILL'); } catch { /* Already exited. */ }
52
+ }
53
+ }, 2000);
54
+ timer.unref();
55
+ }
56
+
57
+ for (const signal of ['SIGINT', 'SIGTERM']) {
58
+ process.on(signal, () => {
59
+ interrupted = true;
60
+ process.exitCode = signal === 'SIGINT' ? 130 : 143;
61
+ for (const child of children) stopTree(child);
62
+ });
63
+ }
64
+
65
+ function run(command, args, cwd, env = process.env) {
66
+ if (interrupted) return Promise.reject(new Error('Interrupted'));
67
+ return new Promise((resolve, reject) => {
68
+ const child = spawn(command, args, { cwd, env, stdio: 'inherit' });
69
+ children.add(child);
70
+ child.once('error', error => { children.delete(child); reject(error); });
71
+ child.once('exit', (code, signal) => {
72
+ children.delete(child);
73
+ if (code === 0) resolve();
74
+ else reject(new Error(`${command} exited with ${signal || code}`));
75
+ });
76
+ });
77
+ }
78
+
79
+ function ensureCache() {
80
+ for (const dir of [cacheRoot, projectCache]) {
81
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
82
+ if (fs.lstatSync(dir).isSymbolicLink() || fs.statSync(dir).uid !== process.getuid()) {
83
+ throw new Error(`Refusing unmanaged workspace directory: ${dir}`);
84
+ }
85
+ if (inside(drive, fs.realpathSync(dir))) {
86
+ throw new Error(`Local workspace must be outside Coze Drive: ${dir}`);
87
+ }
88
+ }
89
+ }
90
+
91
+ async function locked(action, name = 'sync') {
92
+ const lock = path.join(projectCache, `${name}.lock`);
93
+ const started = Date.now();
94
+ let missingOwner = 0;
95
+ while (true) {
96
+ if (interrupted) throw new Error('Interrupted');
97
+ try { fs.mkdirSync(lock); break; } catch (error) {
98
+ if (error.code !== 'EEXIST') throw error;
99
+ }
100
+ let alive = false;
101
+ try {
102
+ const pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8'));
103
+ if (Number.isInteger(pid) && pid > 0) { process.kill(pid, 0); alive = true; }
104
+ } catch (error) { if (error.code === 'EPERM') alive = true; }
105
+ missingOwner = alive ? 0 : missingOwner + 1;
106
+ if (missingOwner >= 2) {
107
+ const stale = `${lock}.stale-${process.pid}`;
108
+ try {
109
+ fs.renameSync(lock, stale);
110
+ fs.rmSync(stale, { recursive: true });
111
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
112
+ missingOwner = 0;
113
+ continue;
114
+ }
115
+ if (Date.now() - started > 120000) throw new Error(`Timed out waiting for ${lock}`);
116
+ await delay(500);
117
+ }
118
+ fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
119
+ try { return await action(); }
120
+ finally { fs.rmSync(lock, { recursive: true, force: true }); }
121
+ }
122
+
123
+ async function sync(local) {
124
+ if (!fs.existsSync(path.join(source, 'package.json'))) {
125
+ throw new Error(`Source project is unavailable: ${source}`);
126
+ }
127
+ fs.mkdirSync(local, { recursive: true });
128
+ if (fs.realpathSync(local) !== local) throw new Error(`Refusing workspace symlink: ${local}`);
129
+ // Checksums catch same-size edits with unchanged/epoch Drive mtimes. Do not use -t:
130
+ // changed local files get fresh mtimes and unchanged files retain watcher snapshots.
131
+ // Materialize source links so the framework never follows them back onto Drive.
132
+ await run('rsync', [
133
+ '-rLp', '--checksum', '--delete', '--delay-updates',
134
+ ...exclusions.map(entry => `--exclude=${entry}`), `${source}/`, `${local}/`,
135
+ ], source);
136
+ // Next rewrites these inputs (dev/types vs types and tsconfig defaults). Preserve
137
+ // generated local changes until their canonical source content actually changes.
138
+ for (const file of ['next-env.d.ts', 'tsconfig.json']) {
139
+ const input = path.join(source, file);
140
+ const output = path.join(local, file);
141
+ const state = path.join(projectCache, `${path.basename(local)}.${file}.source`);
142
+ const fingerprint = fs.existsSync(input) ? digest(fs.readFileSync(input)) : 'missing';
143
+ if (readOptional(state).toString() !== fingerprint || !fs.existsSync(output)) {
144
+ if (fingerprint !== 'missing') fs.copyFileSync(input, output);
145
+ else fs.rmSync(output, { force: true });
146
+ fs.writeFileSync(state, fingerprint);
147
+ }
148
+ }
149
+ }
150
+
151
+ function readOptional(file) {
152
+ try { return fs.readFileSync(file); }
153
+ catch (error) { if (error.code === 'ENOENT') return Buffer.alloc(0); throw error; }
154
+ }
155
+
156
+ function installInput(root) {
157
+ const hash = createHash('sha256');
158
+ const visit = (dir, all = false) => {
159
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
160
+ if (['node_modules', '.git', 'logs', '.pnpm-store', '.next', '.nuxt', '.output', 'dist', 'dist-server', '.cache', '.turbo'].includes(entry.name)) continue;
161
+ const file = path.join(dir, entry.name);
162
+ // Follow source links just as rsync -L does, while detecting loops explicitly.
163
+ const real = fs.realpathSync(file);
164
+ if (entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(file).isDirectory())) {
165
+ if (ancestors.has(real)) throw new Error(`Source symlink cycle: ${file}`);
166
+ ancestors.add(real);
167
+ visit(file, all || entry.name === 'patches');
168
+ ancestors.delete(real);
169
+ }
170
+ else if (all || ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', '.pnpmfile.cjs', '.pnpmfile.js'].includes(entry.name)) {
171
+ hash.update(path.relative(root, file)).update('\0').update(readOptional(file)).update('\0');
172
+ }
173
+ }
174
+ };
175
+ const ancestors = new Set([fs.realpathSync(root)]);
176
+ visit(root);
177
+ return hash.digest('hex');
178
+ }
179
+
180
+ function localEnv(local) {
181
+ return {
182
+ ...process.env,
183
+ COZE_WEB_LOCAL_ACTIVE: local,
184
+ COZE_WEB_SOURCE_PATH: source,
185
+ COZE_WEB_LOCAL_MIRROR: onDrive ? '1' : '',
186
+ COZE_WORKSPACE_PATH: local,
187
+ // Keep the existing discoverable log/PID location in the source project.
188
+ COZE_LOG_DIR: process.env.COZE_LOG_DIR || path.join(source, 'logs'),
189
+ PWD: local,
190
+ INIT_CWD: local,
191
+ ...(onDrive ? { npm_config_store_dir: path.join(cacheRoot, 'store') } : {}),
192
+ };
193
+ }
194
+
195
+ async function install(local, mode) {
196
+ const state = path.join(projectCache, `${mode}.install`);
197
+ const version = execFileSync('pnpm', ['--version'], { encoding: 'utf8' }).trim();
198
+ const fingerprint = () => digest([
199
+ installInput(local), version, process.version, process.env.NODE_ENV,
200
+ process.env.npm_config_production, process.env.NPM_CONFIG_PRODUCTION,
201
+ process.env.PNPM_CONFIG_PRODUCTION,
202
+ ].join('\n'));
203
+ // Lifecycle scripts may generate files from arbitrary source, so do not reuse
204
+ // their install based on dependency metadata alone. Read manifests as text here
205
+ // (no executable hooks or private CLI dependencies in the standalone helper).
206
+ const manifest = readOptional(path.join(local, 'package.json')).toString();
207
+ const hasLifecycle = /"(?:install|postinstall|prepare)"\s*:/.test(manifest);
208
+ // Workspace and local file dependencies can run lifecycles outside the root.
209
+ // Let pnpm validate those installs instead of assuming the root marker is enough.
210
+ const hasLocalDependencies = fs.existsSync(path.join(local, 'pnpm-workspace.yaml')) ||
211
+ /"(?:workspace|file|link):/.test(manifest);
212
+ const hasHooks = ['.pnpmfile.cjs', '.pnpmfile.js'].some(file => fs.existsSync(path.join(local, file))) ||
213
+ /^\s*pnpmfile\s*=/m.test(readOptional(path.join(local, '.npmrc')).toString());
214
+ if (!hasLifecycle && !hasHooks && !hasLocalDependencies && readOptional(state).toString() === fingerprint() &&
215
+ fs.existsSync(path.join(local, 'node_modules', '.modules.yaml'))) return;
216
+ fs.rmSync(state, { force: true });
217
+ const before = installInput(source);
218
+ if (before !== installInput(local)) {
219
+ throw new Error('Dependency inputs changed during sync; rerun prepare.sh.');
220
+ }
221
+ await run('pnpm', [...installArgs, '--store-dir', path.join(cacheRoot, 'store')], local, localEnv(local));
222
+ if (before !== installInput(source)) {
223
+ throw new Error('Dependency inputs changed on Drive during installation; rerun prepare.sh. Lockfile was not overwritten.');
224
+ }
225
+ const lockfile = path.join(local, 'pnpm-lock.yaml');
226
+ if (fs.existsSync(lockfile) && !readOptional(lockfile).equals(readOptional(path.join(source, 'pnpm-lock.yaml')))) {
227
+ const temporary = path.join(source, `.pnpm-lock.yaml.${process.pid}.tmp`);
228
+ try {
229
+ fs.copyFileSync(lockfile, temporary);
230
+ fs.renameSync(temporary, path.join(source, 'pnpm-lock.yaml'));
231
+ } finally { fs.rmSync(temporary, { force: true }); }
232
+ }
233
+ fs.writeFileSync(state, fingerprint());
234
+ }
235
+
236
+ async function watch(args) {
237
+ const local = fs.realpathSync(process.env.COZE_WEB_LOCAL_ACTIVE || path.resolve(__dirname, '..'));
238
+ if (!onDrive) return run(args[0], args.slice(1), local);
239
+ ensureCache();
240
+ if (local !== path.join(fs.realpathSync(projectCache), 'dev')) {
241
+ throw new Error(`Refusing to watch an unmanaged workspace: ${local}`);
242
+ }
243
+ const preparedInput = installInput(local);
244
+ let running = true;
245
+ let syncError;
246
+ const command = run(args[0], args.slice(1), local).finally(() => { running = false; });
247
+ const poll = (async () => {
248
+ while (running && !interrupted) {
249
+ await delay(1000);
250
+ if (!running || interrupted) break;
251
+ try {
252
+ await locked(async () => {
253
+ await sync(local);
254
+ if (installInput(local) !== preparedInput) {
255
+ throw new Error('Dependency inputs changed; rerun prepare.sh and dev.sh before previewing.');
256
+ }
257
+ });
258
+ }
259
+ catch (error) {
260
+ syncError = error;
261
+ for (const child of children) stopTree(child);
262
+ break;
263
+ }
264
+ }
265
+ })();
266
+ const results = await Promise.allSettled([command, poll]);
267
+ if (syncError) throw syncError;
268
+ if (results[0].status === 'rejected') throw results[0].reason;
269
+ }
270
+
271
+ async function main() {
272
+ const [action, ...args] = process.argv.slice(2);
273
+ if (action === 'watch') return watch(args);
274
+ if (!['prepare', 'dev', 'validate'].includes(action)) throw new Error(`Unknown Web action: ${action}`);
275
+ if (!onDrive) {
276
+ return run('bash', [path.join(source, 'scripts', `${action}.sh`), ...args], source, localEnv(source));
277
+ }
278
+ ensureCache();
279
+ const mode = action === 'validate' ? 'check' : 'dev';
280
+ const local = path.join(fs.realpathSync(projectCache), mode);
281
+ console.log(`[web] Source: ${source}\n[web] Local ${mode} workspace: ${local}`);
282
+ if (action === 'validate') {
283
+ return locked(async () => {
284
+ await locked(async () => {
285
+ await sync(local);
286
+ await install(local, mode);
287
+ });
288
+ await run('bash', [path.join(local, 'scripts', 'validate.sh'), ...args], local, localEnv(local));
289
+ }, 'check');
290
+ } else {
291
+ await locked(async () => {
292
+ await sync(local);
293
+ await install(local, mode);
294
+ });
295
+ }
296
+ await run('bash', [path.join(local, 'scripts', `${action}.sh`), ...args], local, localEnv(local));
297
+ }
298
+
299
+ main().catch(error => {
300
+ console.error(`[web] ${error.message}`);
301
+ process.exitCode = process.exitCode || 1;
302
+ });