@coze-arch/cli 0.1.8-alpha.4500b5 → 0.1.8-alpha.5d5f9d
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.
- package/README.md +18 -0
- package/lib/__templates__/expo/.cozeproj/scripts/prepare-node-modules.sh +180 -10
- package/lib/__templates__/expo/pnpm-lock.yaml +5 -5
- package/lib/__templates__/expo/server/package.json +1 -1
- package/lib/__templates__/native-static/.coze +2 -2
- package/lib/__templates__/nextjs/.coze +1 -1
- package/lib/__templates__/nextjs/README.md +18 -0
- package/lib/__templates__/nextjs/package.json +1 -1
- package/lib/__templates__/nextjs/pnpm-lock.yaml +5 -5
- package/lib/__templates__/nextjs/scripts/dev.sh +16 -34
- package/lib/__templates__/nextjs/scripts/local-workspace.cjs +302 -0
- package/lib/__templates__/nextjs/scripts/prepare-next-dev-output.sh +122 -0
- package/lib/__templates__/nextjs/scripts/prepare-node-modules.sh +180 -10
- package/lib/__templates__/nextjs/scripts/prepare.sh +10 -2
- package/lib/__templates__/nextjs/scripts/validate.sh +11 -1
- package/lib/__templates__/nextjs/template.config.js +21 -7
- package/lib/__templates__/nextjs/tsconfig.json +0 -1
- package/lib/__templates__/nuxt-vue/.coze +1 -1
- package/lib/__templates__/nuxt-vue/README.md +20 -2
- package/lib/__templates__/nuxt-vue/package.json +1 -1
- package/lib/__templates__/nuxt-vue/pnpm-lock.yaml +5 -5
- package/lib/__templates__/nuxt-vue/scripts/dev.sh +10 -4
- package/lib/__templates__/nuxt-vue/scripts/local-workspace.cjs +302 -0
- package/lib/__templates__/nuxt-vue/scripts/prepare-node-modules.sh +180 -10
- package/lib/__templates__/nuxt-vue/scripts/prepare.sh +10 -2
- package/lib/__templates__/nuxt-vue/scripts/validate.sh +11 -1
- package/lib/__templates__/pi-agent/package.json +1 -1
- package/lib/__templates__/pi-agent/pnpm-lock.yaml +5 -5
- package/lib/__templates__/taro/.cozeproj/scripts/prepare-node-modules.sh +180 -10
- package/lib/__templates__/taro/pnpm-lock.yaml +5 -5
- package/lib/__templates__/taro/server/package.json +1 -1
- package/lib/__templates__/vite/.coze +1 -1
- package/lib/__templates__/vite/README.md +20 -0
- package/lib/__templates__/vite/package.json +1 -1
- package/lib/__templates__/vite/pnpm-lock.yaml +5 -5
- package/lib/__templates__/vite/scripts/dev.sh +10 -4
- package/lib/__templates__/vite/scripts/local-workspace.cjs +302 -0
- package/lib/__templates__/vite/scripts/prepare-node-modules.sh +180 -10
- package/lib/__templates__/vite/scripts/prepare.sh +10 -2
- package/lib/__templates__/vite/scripts/validate.sh +7 -1
- package/lib/__templates__/vite/template.config.js +21 -7
- package/lib/cli.js +365 -184
- package/package.json +2 -1
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Keep Next development output off Coze Drive without moving production output.
|
|
3
|
+
set -euo pipefail
|
|
4
|
+
|
|
5
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
|
|
6
|
+
if [ "$(basename "$(dirname "$SCRIPT_DIR")")" = ".cozeproj" ]; then
|
|
7
|
+
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd -P)"
|
|
8
|
+
else
|
|
9
|
+
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
|
10
|
+
fi
|
|
11
|
+
|
|
12
|
+
DRIVE_ROOT="${COZE_DRIVE_ROOT:-/Coze/Drive}"
|
|
13
|
+
if [ -d "$DRIVE_ROOT" ]; then
|
|
14
|
+
DRIVE_ROOT="$(cd "$DRIVE_ROOT" && pwd -P)"
|
|
15
|
+
else
|
|
16
|
+
DRIVE_ROOT="${DRIVE_ROOT%/}"
|
|
17
|
+
fi
|
|
18
|
+
case "$PROJECT_ROOT" in
|
|
19
|
+
"$DRIVE_ROOT"|"$DRIVE_ROOT"/*) ;;
|
|
20
|
+
*) exit 0 ;;
|
|
21
|
+
esac
|
|
22
|
+
|
|
23
|
+
# Next writes every on-demand development build into .next/dev. On Coze Drive each of
|
|
24
|
+
# those writes goes through the sync daemon, so only that subtree moves to local disk.
|
|
25
|
+
# Production output stays in the project directory, which keeps `next build` and
|
|
26
|
+
# deployment unchanged.
|
|
27
|
+
#
|
|
28
|
+
# One local directory per project, shared with prepare-node-modules.sh: node_modules and
|
|
29
|
+
# this cache sit side by side under WORK_DIR. The caches subdirectory is the slot that
|
|
30
|
+
# script reserves for output that must survive an install, so nothing here is cleaned up
|
|
31
|
+
# behind our back. PROJECT_ID has to stay identical to the one it computes.
|
|
32
|
+
NM_ROOT="/tmp/nm"
|
|
33
|
+
PROJECT_ID="$(basename "$PROJECT_ROOT")-$(printf '%s' "$PROJECT_ROOT" | cksum | awk '{print $1}')"
|
|
34
|
+
WORK_DIR="$NM_ROOT/$PROJECT_ID"
|
|
35
|
+
NEXT_ROOT="$PROJECT_ROOT/.next"
|
|
36
|
+
NEXT_DEV="$NEXT_ROOT/dev"
|
|
37
|
+
LEGACY_NEXT_ROOT="$WORK_DIR/.next"
|
|
38
|
+
LOCAL_NEXT_DEV="$WORK_DIR/caches/next-dev"
|
|
39
|
+
|
|
40
|
+
case "$LOCAL_NEXT_DEV" in
|
|
41
|
+
"$DRIVE_ROOT"|"$DRIVE_ROOT"/*)
|
|
42
|
+
echo "[next] local development output must not be on Coze Drive: $LOCAL_NEXT_DEV" >&2
|
|
43
|
+
exit 1
|
|
44
|
+
;;
|
|
45
|
+
esac
|
|
46
|
+
|
|
47
|
+
# Coze Drive sync does not preserve symlinks: a synced copy of a link arrives as a
|
|
48
|
+
# regular file holding the link target. Recognize the links this scheme creates so a
|
|
49
|
+
# project that came back from sync repairs itself instead of failing to start.
|
|
50
|
+
is_flattened_managed_link() {
|
|
51
|
+
local candidate="$1" content=""
|
|
52
|
+
[ -f "$candidate" ] || return 1
|
|
53
|
+
[ ! -L "$candidate" ] || return 1
|
|
54
|
+
[ "$(wc -c < "$candidate")" -le 4096 ] || return 1
|
|
55
|
+
content="$(tr -d '\r\n' < "$candidate")"
|
|
56
|
+
case "$content" in
|
|
57
|
+
"$NM_ROOT"/*) return 0 ;;
|
|
58
|
+
esac
|
|
59
|
+
return 1
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
# Earlier versions linked the whole .next directory. Bring any production build made
|
|
63
|
+
# back then into the project; from here on only .next/dev is redirected.
|
|
64
|
+
restore_legacy_next_root() {
|
|
65
|
+
local entry
|
|
66
|
+
rm -f "$NEXT_ROOT"
|
|
67
|
+
mkdir -p "$NEXT_ROOT"
|
|
68
|
+
if [ -d "$LEGACY_NEXT_ROOT" ]; then
|
|
69
|
+
while IFS= read -r -d '' entry; do
|
|
70
|
+
mv "$entry" "$NEXT_ROOT/"
|
|
71
|
+
done < <(find -P "$LEGACY_NEXT_ROOT" -mindepth 1 -maxdepth 1 -print0)
|
|
72
|
+
rmdir "$LEGACY_NEXT_ROOT" 2>/dev/null || true
|
|
73
|
+
fi
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if [ -L "$NEXT_ROOT" ]; then
|
|
77
|
+
case "$(readlink "$NEXT_ROOT")" in
|
|
78
|
+
"$NM_ROOT"/*)
|
|
79
|
+
echo "[next] Restoring legacy .next output to the project directory."
|
|
80
|
+
restore_legacy_next_root
|
|
81
|
+
;;
|
|
82
|
+
*)
|
|
83
|
+
echo "[next] refusing to replace unmanaged .next symlink: $NEXT_ROOT" >&2
|
|
84
|
+
exit 1
|
|
85
|
+
;;
|
|
86
|
+
esac
|
|
87
|
+
elif is_flattened_managed_link "$NEXT_ROOT"; then
|
|
88
|
+
echo "[next] Recovering .next flattened by Coze Drive sync."
|
|
89
|
+
restore_legacy_next_root
|
|
90
|
+
elif [ -e "$NEXT_ROOT" ] && [ ! -d "$NEXT_ROOT" ]; then
|
|
91
|
+
echo "[next] refusing to replace non-directory Next output: $NEXT_ROOT" >&2
|
|
92
|
+
exit 1
|
|
93
|
+
fi
|
|
94
|
+
|
|
95
|
+
mkdir -p "$NEXT_ROOT" "$LOCAL_NEXT_DEV"
|
|
96
|
+
|
|
97
|
+
if [ -L "$NEXT_DEV" ]; then
|
|
98
|
+
if [ "$(readlink "$NEXT_DEV")" = "$LOCAL_NEXT_DEV" ]; then
|
|
99
|
+
exit 0
|
|
100
|
+
fi
|
|
101
|
+
case "$(readlink "$NEXT_DEV")" in
|
|
102
|
+
"$NM_ROOT"/*) rm "$NEXT_DEV" ;;
|
|
103
|
+
*)
|
|
104
|
+
echo "[next] refusing to replace unmanaged .next/dev symlink: $NEXT_DEV" >&2
|
|
105
|
+
exit 1
|
|
106
|
+
;;
|
|
107
|
+
esac
|
|
108
|
+
elif [ -e "$NEXT_DEV" ]; then
|
|
109
|
+
# .next/dev holds development output only, and Next regenerates it on demand.
|
|
110
|
+
rm -rf "$NEXT_DEV"
|
|
111
|
+
fi
|
|
112
|
+
|
|
113
|
+
# A second dev start can win the race between the removal above and this link.
|
|
114
|
+
if ! ln -s "$LOCAL_NEXT_DEV" "$NEXT_DEV" 2>/dev/null; then
|
|
115
|
+
if [ -L "$NEXT_DEV" ] && [ "$(readlink "$NEXT_DEV")" = "$LOCAL_NEXT_DEV" ]; then
|
|
116
|
+
exit 0
|
|
117
|
+
fi
|
|
118
|
+
echo "[next] failed to link development output: $NEXT_DEV" >&2
|
|
119
|
+
exit 1
|
|
120
|
+
fi
|
|
121
|
+
|
|
122
|
+
echo "[next] Development output linked to $LOCAL_NEXT_DEV"
|
|
@@ -98,6 +98,7 @@ printf '%s\n' "$$" > "$LOCK_DIR/pid"
|
|
|
98
98
|
trap release_lock EXIT
|
|
99
99
|
|
|
100
100
|
mkdir -p "$WORK_DIR"
|
|
101
|
+
INSTALL_STATE_FILE="$WORK_DIR/.install-state"
|
|
101
102
|
|
|
102
103
|
# Previous versions mirrored the whole project into WORK_DIR. That gives pnpm
|
|
103
104
|
# and framework dev servers two paths for the same source tree, which breaks
|
|
@@ -118,12 +119,15 @@ cleanup_legacy_workspace() {
|
|
|
118
119
|
done < <(find "$workspace_dir" -mindepth 1 -maxdepth 1 -print0)
|
|
119
120
|
}
|
|
120
121
|
|
|
122
|
+
# caches is reserved for the sibling prepare scripts of this project. They keep
|
|
123
|
+
# regenerable framework output there (the Next helper points .next/dev into it), and that
|
|
124
|
+
# output has to outlive an install, so this cleanup must not read it as leftover.
|
|
121
125
|
cleanup_legacy_shadow_project() {
|
|
122
126
|
local entry name
|
|
123
127
|
while IFS= read -r -d '' entry; do
|
|
124
128
|
name="$(basename "$entry")"
|
|
125
129
|
case "$name" in
|
|
126
|
-
node_modules|client|server) continue ;;
|
|
130
|
+
node_modules|client|server|caches|.install-state) continue ;;
|
|
127
131
|
esac
|
|
128
132
|
rm -rf "$entry"
|
|
129
133
|
done < <(find "$WORK_DIR" -mindepth 1 -maxdepth 1 -print0)
|
|
@@ -141,6 +145,162 @@ link_install_entry() {
|
|
|
141
145
|
fi
|
|
142
146
|
}
|
|
143
147
|
|
|
148
|
+
hash_install_input() {
|
|
149
|
+
if command -v sha256sum >/dev/null 2>&1; then
|
|
150
|
+
sha256sum | awk '{print $1}'
|
|
151
|
+
elif command -v shasum >/dev/null 2>&1; then
|
|
152
|
+
shasum -a 256 | awk '{print $1}'
|
|
153
|
+
else
|
|
154
|
+
cksum | awk '{print $1 "-" $2}'
|
|
155
|
+
fi
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
append_file_to_install_fingerprint() {
|
|
159
|
+
local relative_path="$1"
|
|
160
|
+
local source_path="$PROJECT_ROOT/$relative_path"
|
|
161
|
+
printf 'path=%s\n' "$relative_path"
|
|
162
|
+
if [ -f "$source_path" ]; then
|
|
163
|
+
cat "$source_path"
|
|
164
|
+
else
|
|
165
|
+
printf '<missing>\n'
|
|
166
|
+
fi
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
append_directory_to_install_fingerprint() {
|
|
170
|
+
local relative_path="$1"
|
|
171
|
+
local source_path="$PROJECT_ROOT/$relative_path"
|
|
172
|
+
local file
|
|
173
|
+
printf 'path=%s\n' "$relative_path"
|
|
174
|
+
if [ ! -d "$source_path" ]; then
|
|
175
|
+
printf '<missing>\n'
|
|
176
|
+
return
|
|
177
|
+
fi
|
|
178
|
+
|
|
179
|
+
while IFS= read -r file; do
|
|
180
|
+
printf 'file=%s\n' "${file#"${PROJECT_ROOT}/"}"
|
|
181
|
+
cat "$file"
|
|
182
|
+
done < <(find -P "$source_path" -type f -print | LC_ALL=C sort)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
# Everything that can change the resolved dependency tree. The leading version marker
|
|
186
|
+
# invalidates every stored state when this scheme itself changes.
|
|
187
|
+
calculate_install_fingerprint() {
|
|
188
|
+
local filename workspace argument
|
|
189
|
+
{
|
|
190
|
+
printf 'prepare-node-modules-install-state=1\n'
|
|
191
|
+
printf 'node-version=%s\n' "$(node --version)"
|
|
192
|
+
printf 'pnpm-version=%s\n' "$(pnpm --version)"
|
|
193
|
+
printf 'node-env=%s\n' "${NODE_ENV:-}"
|
|
194
|
+
printf 'npm-config-production=%s\n' "${npm_config_production:-}"
|
|
195
|
+
printf 'npm-config-production-upper=%s\n' "${NPM_CONFIG_PRODUCTION:-}"
|
|
196
|
+
printf 'pnpm-config-production=%s\n' "${PNPM_CONFIG_PRODUCTION:-}"
|
|
197
|
+
for argument in "$@"; do
|
|
198
|
+
printf 'install-argument=%s\n' "$argument"
|
|
199
|
+
done
|
|
200
|
+
for filename in package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc; do
|
|
201
|
+
append_file_to_install_fingerprint "$filename"
|
|
202
|
+
done
|
|
203
|
+
for workspace in client server; do
|
|
204
|
+
append_file_to_install_fingerprint "$workspace/package.json"
|
|
205
|
+
done
|
|
206
|
+
append_directory_to_install_fingerprint patches
|
|
207
|
+
} | hash_install_input
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
install_requires_refresh() {
|
|
211
|
+
local argument
|
|
212
|
+
for argument in "$@"; do
|
|
213
|
+
case "$argument" in
|
|
214
|
+
--force|-f|--lockfile-only|--fix-lockfile) return 0 ;;
|
|
215
|
+
esac
|
|
216
|
+
done
|
|
217
|
+
return 1
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
# Reuse skips pnpm install entirely, so it must not skip side effects that live outside
|
|
221
|
+
# node_modules. preinstall is exempt: it only guards which package manager may run, and
|
|
222
|
+
# there is no install to guard when the tree is already in place.
|
|
223
|
+
package_has_install_lifecycle() {
|
|
224
|
+
local package_path="$1"
|
|
225
|
+
node - "$package_path" <<'NODE'
|
|
226
|
+
const fs = require('node:fs');
|
|
227
|
+
const [packagePath] = process.argv.slice(2);
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
|
231
|
+
const scripts = packageJson && typeof packageJson.scripts === 'object' && packageJson.scripts
|
|
232
|
+
? packageJson.scripts
|
|
233
|
+
: {};
|
|
234
|
+
const hasLifecycle = ['install', 'postinstall', 'prepare'].some(
|
|
235
|
+
name => typeof scripts[name] === 'string' && scripts[name].trim() !== '',
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
process.exit(hasLifecycle ? 0 : 1);
|
|
239
|
+
} catch {
|
|
240
|
+
process.exit(0);
|
|
241
|
+
}
|
|
242
|
+
NODE
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
install_reuse_is_safe() {
|
|
246
|
+
local workspace package_path
|
|
247
|
+
for package_path in "$PROJECT_ROOT/.pnpmfile.cjs" "$PROJECT_ROOT/.pnpmfile.js"; do
|
|
248
|
+
if [ -e "$package_path" ]; then
|
|
249
|
+
echo "[node_modules] Reinstalling because pnpm hooks are present: $package_path"
|
|
250
|
+
return 1
|
|
251
|
+
fi
|
|
252
|
+
done
|
|
253
|
+
|
|
254
|
+
if [ -f "$PROJECT_ROOT/.npmrc" ] && grep -Eq '^[[:space:]]*pnpmfile[[:space:]]*=' "$PROJECT_ROOT/.npmrc"; then
|
|
255
|
+
echo "[node_modules] Reinstalling because .npmrc configures a pnpm hook."
|
|
256
|
+
return 1
|
|
257
|
+
fi
|
|
258
|
+
|
|
259
|
+
for workspace in . client server; do
|
|
260
|
+
package_path="$PROJECT_ROOT/$workspace/package.json"
|
|
261
|
+
[ -f "$package_path" ] || continue
|
|
262
|
+
if package_has_install_lifecycle "$package_path"; then
|
|
263
|
+
echo "[node_modules] Reinstalling because $package_path has an install lifecycle script."
|
|
264
|
+
return 1
|
|
265
|
+
fi
|
|
266
|
+
done
|
|
267
|
+
return 0
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
dependencies_are_ready() {
|
|
271
|
+
local workspace
|
|
272
|
+
[ -f "$WORK_DIR/node_modules/.modules.yaml" ] || return 1
|
|
273
|
+
for workspace in client server; do
|
|
274
|
+
if [ -f "$PROJECT_ROOT/$workspace/package.json" ] &&
|
|
275
|
+
[ ! -f "$WORK_DIR/$workspace/node_modules/.modules.yaml" ]; then
|
|
276
|
+
return 1
|
|
277
|
+
fi
|
|
278
|
+
done
|
|
279
|
+
return 0
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
# 判断顺序按代价从小到大排。指纹要读云盘上的 lockfile 和整个 patches/,所以放最后:只有其余
|
|
283
|
+
# 条件都满足、确实可能复用时才付这份开销。build.sh 和 prepare.sh 不设开关,第一行就返回了。
|
|
284
|
+
install_can_be_reused() {
|
|
285
|
+
local installed_fingerprint=""
|
|
286
|
+
|
|
287
|
+
[ "${COZE_REUSE_NODE_MODULES:-}" = "1" ] || return 1
|
|
288
|
+
install_requires_refresh "$@" && return 1
|
|
289
|
+
[ -f "$INSTALL_STATE_FILE" ] || return 1
|
|
290
|
+
IFS= read -r installed_fingerprint < "$INSTALL_STATE_FILE" || return 1
|
|
291
|
+
dependencies_are_ready || return 1
|
|
292
|
+
install_reuse_is_safe || return 1
|
|
293
|
+
[ "$installed_fingerprint" = "$(calculate_install_fingerprint "$@")" ] || return 1
|
|
294
|
+
return 0
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
write_install_state() {
|
|
298
|
+
local fingerprint="$1" temporary_state
|
|
299
|
+
temporary_state="$(mktemp "$WORK_DIR/.install-state.XXXXXX")"
|
|
300
|
+
printf '%s\n' "$fingerprint" > "$temporary_state"
|
|
301
|
+
mv -f "$temporary_state" "$INSTALL_STATE_FILE"
|
|
302
|
+
}
|
|
303
|
+
|
|
144
304
|
copy_install_metadata() {
|
|
145
305
|
local filename source_file target_file workspace
|
|
146
306
|
for filename in pnpm-lock.yaml pnpm-workspace.yaml .npmrc; do
|
|
@@ -190,16 +350,26 @@ link_node_modules() {
|
|
|
190
350
|
cleanup_legacy_shadow_project
|
|
191
351
|
copy_install_metadata
|
|
192
352
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
353
|
+
if install_can_be_reused "$@"; then
|
|
354
|
+
echo "[node_modules] Reusing unchanged dependencies in $WORK_DIR"
|
|
355
|
+
else
|
|
356
|
+
# A stale state file must not survive a failed install.
|
|
357
|
+
rm -f "$INSTALL_STATE_FILE"
|
|
358
|
+
echo "[node_modules] Installing dependencies in $WORK_DIR"
|
|
359
|
+
if ! (cd "$WORK_DIR" && pnpm install "$@"); then
|
|
360
|
+
exit 1
|
|
361
|
+
fi
|
|
362
|
+
|
|
363
|
+
if [ -f "$WORK_DIR/pnpm-lock.yaml" ]; then
|
|
364
|
+
temporary_lockfile="$(mktemp "$PROJECT_ROOT/.pnpm-lock.yaml.XXXXXX")"
|
|
365
|
+
cp "$WORK_DIR/pnpm-lock.yaml" "$temporary_lockfile"
|
|
366
|
+
chmod 0644 "$temporary_lockfile"
|
|
367
|
+
mv -f "$temporary_lockfile" "$PROJECT_ROOT/pnpm-lock.yaml"
|
|
368
|
+
fi
|
|
197
369
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
chmod 0644 "$temporary_lockfile"
|
|
202
|
-
mv -f "$temporary_lockfile" "$PROJECT_ROOT/pnpm-lock.yaml"
|
|
370
|
+
# pnpm may have rewritten the lockfile, so record the fingerprint of the tree as it
|
|
371
|
+
# now stands. Otherwise the next run would see a changed input and reinstall.
|
|
372
|
+
write_install_state "$(calculate_install_fingerprint "$@")"
|
|
203
373
|
fi
|
|
204
374
|
|
|
205
375
|
link_node_modules "$PROJECT_ROOT" "$WORK_DIR/node_modules"
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
#!/bin/bash
|
|
2
2
|
set -Eeuo pipefail
|
|
3
3
|
|
|
4
|
-
|
|
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" prepare "$@"
|
|
9
|
+
fi
|
|
10
|
+
COZE_WORKSPACE_PATH="${PROJECT_ROOT}"
|
|
5
11
|
|
|
6
12
|
cd "${COZE_WORKSPACE_PATH}"
|
|
7
13
|
|
|
8
14
|
echo "Installing dependencies..."
|
|
9
|
-
|
|
15
|
+
if [[ "${COZE_WEB_LOCAL_MIRROR:-}" != "1" ]]; then
|
|
16
|
+
bash "$COZE_WORKSPACE_PATH/scripts/prepare-node-modules.sh" --prefer-frozen-lockfile --prefer-offline --loglevel debug --reporter=append-only
|
|
17
|
+
fi
|