-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch-update.js
More file actions
416 lines (376 loc) · 17.9 KB
/
Copy pathpatch-update.js
File metadata and controls
416 lines (376 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/**
* Patch cloudcli's update endpoint to work on Windows.
*
* 1. Replaces hardcoded `spawn('sh', ...)` with platform-aware `cmd.exe` / `sh`.
* 2. Replaces `npm install -g` (global) with local `npm install` so the project's
* own node_modules gets updated, not the global prefix.
* 3. Fixes cwd to process.cwd() on Windows so npm installs into the correct
* project root instead of inside node_modules (which creates nested installs).
* 4. Adds /api/system/version endpoint for upgrade verification.
* 5. Changes static asset cache to must-revalidate so browser picks up new
* frontend bundle after upgrade.
* 6. Adds .updating sentinel file around the update process so the watchdog
* doesn't kill the server while npm install is still running.
* 7. Enables SO_REUSEADDR on the server socket to prevent EADDRINUSE crash
* loops on Windows (TIME_WAIT prevents immediate port reuse).
* 8. Appends `&& node patch-update.js` to the npm/git update commands so
* patches survive a UI-triggered update (postinstall only fires on bare
* `npm install`, not `npm install <package>`).
* 9. Patches sw.js asset strategy from cache-first to stale-while-revalidate
* so the browser picks up new bundles after an app update.
* 10. Sets GIT_HTTP_PROTOCOL_VERSION=1 at server startup so all spawned git
* processes use HTTP/1.1, working around Windows schannel HTTP/2 issues
* that cause "server closed abruptly" errors on GitHub clones.
*
* Runs after every `npm install` to survive dependency reinstall.
*/
import { readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const targets = [
join(__dirname, 'node_modules', '@cloudcli-ai', 'cloudcli', 'server', 'index.js'),
join(__dirname, 'node_modules', '@cloudcli-ai', 'cloudcli', 'dist-server', 'server', 'index.js'),
];
// ---------------------------------------------------------------------------
// Patch 1 — spawn shell
// ---------------------------------------------------------------------------
const oldSpawn = "spawn('sh', ['-c', updateCommand], {";
const newSpawn = "spawn(process.platform === 'win32' ? 'cmd.exe' : 'sh', [process.platform === 'win32' ? '/c' : '-c', updateCommand], {";
// ---------------------------------------------------------------------------
// Patch 2 — npm install (drop -g, add --force)
// ---------------------------------------------------------------------------
const oldNpmInstall = "npm install -g @cloudcli-ai/cloudcli@latest'";
const newNpmInstall = "npm install @cloudcli-ai/cloudcli@latest --force'";
// ---------------------------------------------------------------------------
// Patch 3 — cwd: use process.cwd() on Windows instead of projectRoot
// projectRoot points inside node_modules, which confuses npm
// about where to install the updated package (it creates a
// nested node_modules instead of updating the top-level one).
// ---------------------------------------------------------------------------
const oldCwd =
"const updateCwd = IS_PLATFORM || installMode === 'git'\n" +
' ? projectRoot\n' +
' : os.homedir();';
const patchedCwd =
"const updateCwd = process.platform === 'win32'\n" +
' ? process.cwd()\n' +
" : IS_PLATFORM || installMode === 'git'\n" +
' ? projectRoot\n' +
' : os.homedir();';
// ---------------------------------------------------------------------------
// Patch 3b — cwd: already has Windows check but uses projectRoot.
// Replace projectRoot with process.cwd() on the Windows branch.
// ---------------------------------------------------------------------------
const oldPatchedCwdPart =
"const updateCwd = process.platform === 'win32'\n" +
" ? projectRoot";
const newPatchedCwdPart =
"const updateCwd = process.platform === 'win32'\n" +
" ? process.cwd()";
// ---------------------------------------------------------------------------
// Patch 4 — Add /api/system/version endpoint after /health
// Two variants: server/index.js has an empty line after "});",
// dist-server/server/index.js doesn't.
// ---------------------------------------------------------------------------
const oldHealthEnd =
" installMode\n" +
" });\n" +
"});\n" +
"// Optional API key validation (if configured)";
const oldHealthEndExtraLine =
" installMode\n" +
" });\n" +
"});\n" +
"\n" +
"// Optional API key validation (if configured)";
const newHealthEnd =
" installMode\n" +
" });\n" +
"});\n" +
"// --- patch: version endpoint ---\n" +
"app.get('/api/system/version', (req, res) => {\n" +
" try {\n" +
" const p = JSON.parse(fs.readFileSync(path.join(APP_ROOT, 'package.json'), 'utf8'));\n" +
" res.json({ version: p.version, installMode });\n" +
" } catch {\n" +
" res.json({ version: 'unknown', installMode });\n" +
" }\n" +
"});\n" +
"// --- end patch ---\n" +
"// Optional API key validation (if configured)";
// ---------------------------------------------------------------------------
// Patch 5 — Fix static asset caching: ensure JS/CSS etc. always revalidate
// so the browser picks up the new frontend bundle after upgrade.
// ---------------------------------------------------------------------------
const oldCache =
" // Cache static assets for 1 year (they have hashed names)\n" +
" res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');";
const newCache =
" // Cache for 1 year but always revalidate via ETag, so after upgrade\n" +
" // the browser fetches the new bundle instead of serving stale cache.\n" +
" res.setHeader('Cache-Control', 'public, max-age=31536000, must-revalidate');";
// ---------------------------------------------------------------------------
// Patch 6 — Sentinel file (.updating) to prevent watchdog killing server mid-update
// ---------------------------------------------------------------------------
const sentinelFile = "try { fs.writeFileSync(path.join(process.cwd(), '.updating'), '1'); } catch {}";
// 6a — insert sentinel creation before spawn
const oldSpawnLine =
" const child = spawn(process.platform === 'win32' ? 'cmd.exe' : 'sh', [process.platform === 'win32' ? '/c' : '-c', updateCommand], {";
const newSpawnLine =
" " + sentinelFile + "\n const child = spawn(process.platform === 'win32' ? 'cmd.exe' : 'sh', [process.platform === 'win32' ? '/c' : '-c', updateCommand], {";
// 6b — insert sentinel deletion at the start of close handler
const oldCloseStart =
" child.on('close', (code) => {\n if (code === 0) {";
const newCloseStart =
" child.on('close', (code) => {\n try { fs.unlinkSync(path.join(process.cwd(), '.updating')); } catch {}\n if (code === 0) {";
// 6c — insert sentinel deletion at the start of error handler
const oldErrorStart =
" child.on('error', (error) => {\n console.error('Update process error:', error);";
const newErrorStart =
" child.on('error', (error) => {\n try { fs.unlinkSync(path.join(process.cwd(), '.updating')); } catch {}\n console.error('Update process error:', error);";
// ---------------------------------------------------------------------------
// Patch 7 — SO_REUSEADDR on server socket (fix EADDRINUSE crash loop on Windows)
// ---------------------------------------------------------------------------
const oldListen =
"server.listen(SERVER_PORT, HOST, async () => {";
const newListen =
"server.listen({ port: SERVER_PORT, host: HOST, reuseAddr: true }, async () => {";
// ---------------------------------------------------------------------------
// Patch 8 — Append `&& node patch-update.js` to both update commands so the
// patches survive npm update (postinstall only fires on `npm install`
// without arguments, not on `npm install <package>`).
// ---------------------------------------------------------------------------
const oldNpmInstallCmd =
" : 'npm install @cloudcli-ai/cloudcli@latest --force';";
const newNpmInstallCmd =
" : 'npm install @cloudcli-ai/cloudcli@latest --force && node patch-update.js';";
const oldGitInstallCmd =
" ? 'git checkout main && git pull && npm install'";
const newGitInstallCmd =
" ? 'git checkout main && git pull && npm install && node patch-update.js'";
// ---------------------------------------------------------------------------
// Patch 9 — Patch sw.js: change cache-first strategy for /assets/ to
// stale-while-revalidate so updated bundles are picked up after
// an app update even when the SW itself hasn't changed.
// ---------------------------------------------------------------------------
const swPath = join(__dirname, 'node_modules', '@cloudcli-ai', 'cloudcli', 'dist', 'sw.js');
const oldSwAssetBlock =
" // Hashed assets (JS/CSS in /assets/) — cache-first since filenames change per build\n" +
" if (url.includes('/assets/')) {\n" +
" event.respondWith(\n" +
" caches.match(event.request).then(cached => {\n" +
" if (cached) return cached;\n" +
" return fetch(event.request).then(response => {\n" +
" const clone = response.clone();\n" +
" caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));\n" +
" return response;\n" +
" });\n" +
" })\n" +
" );\n" +
" return;\n" +
" }";
const newSwAssetBlock =
" // Hashed assets (JS/CSS in /assets/) — stale-while-revalidate.\n" +
" // Return cached version instantly, background-fetch the latest from network\n" +
" // so the next page load always gets fresh code after an app update.\n" +
" if (url.includes('/assets/')) {\n" +
" event.respondWith(\n" +
" caches.match(event.request).then(cached => {\n" +
" const fetchPromise = fetch(event.request).then(response => {\n" +
" const clone = response.clone();\n" +
" caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));\n" +
" return response;\n" +
" });\n" +
" return cached || fetchPromise;\n" +
" })\n" +
" );\n" +
" return;\n" +
" }";
// ---------------------------------------------------------------------------
// Patch 10 — Force GIT_HTTP_PROTOCOL_VERSION=1 at server startup so all
// spawned git processes use HTTP/1.1 instead of HTTP/2. Works
// around Windows schannel SSL HTTP/2 issues ("server closed
// abruptly / missing close_notify") when cloning from GitHub.
// ---------------------------------------------------------------------------
const oldGitProto =
"const APP_ROOT = findAppRoot(__dirname);\n" +
"const installMode";
const newGitProto =
"const APP_ROOT = findAppRoot(__dirname);\n" +
"// Force git HTTP/1.1 on Windows to avoid schannel HTTP/2 close_notify issues\n" +
"process.env.GIT_HTTP_PROTOCOL_VERSION = '1';\n" +
"const installMode";
let patched = 0;
for (const file of targets) {
try {
let code = readFileSync(file, 'utf-8');
const original = code;
// Patch 1 — spawn shell
if (code.includes(oldSpawn)) {
code = code.replace(oldSpawn, newSpawn);
console.log(` ✓ spawn shell → ${file}`);
patched++;
} else if (code.includes(newSpawn)) {
console.log(` → spawn shell already patched: ${file}`);
} else {
console.log(` ⚠ spawn pattern not found: ${file}`);
}
// Patch 2 — npm install
if (code.includes(oldNpmInstall)) {
code = code.replace(oldNpmInstall, newNpmInstall);
console.log(` ✓ npm local install → ${file}`);
patched++;
} else if (code.includes(newNpmInstall)) {
console.log(` → npm local install already patched: ${file}`);
} else {
console.log(` ⚠ npm install pattern not found: ${file}`);
}
// Patch 3 — cwd (original: uses os.homedir, needs full replacement)
if (code.includes(oldCwd)) {
code = code.replace(oldCwd, patchedCwd);
console.log(` ✓ cwd (full) → ${file}`);
patched++;
} else if (code.includes(patchedCwd)) {
console.log(` → cwd already patched: ${file}`);
} else {
// Patch 3b — cwd (already has Windows check but uses projectRoot)
if (code.includes(oldPatchedCwdPart)) {
code = code.replace(oldPatchedCwdPart, newPatchedCwdPart);
console.log(` ✓ cwd (partial) → ${file}`);
patched++;
} else {
console.log(` ⚠ cwd pattern not found: ${file}`);
}
}
// Patch 4 — version endpoint
if (code.includes(oldHealthEnd)) {
code = code.replace(oldHealthEnd, newHealthEnd);
console.log(` ✓ version endpoint → ${file}`);
patched++;
} else if (code.includes(oldHealthEndExtraLine)) {
code = code.replace(oldHealthEndExtraLine, newHealthEnd);
console.log(` ✓ version endpoint (extra line) → ${file}`);
patched++;
} else if (code.includes(newHealthEnd)) {
console.log(` → version endpoint already patched: ${file}`);
} else {
console.log(` ⚠ version endpoint pattern not found: ${file}`);
}
// Patch 5 — static asset cache
if (code.includes(oldCache)) {
code = code.replace(oldCache, newCache);
console.log(` ✓ cache headers → ${file}`);
patched++;
} else if (code.includes(newCache)) {
console.log(` → cache headers already patched: ${file}`);
} else {
console.log(` ⚠ cache pattern not found: ${file}`);
}
// Patch 6 — sentinel file (.updating) for watchdog
// 6a — create .updating before spawn
if (code.includes(oldSpawnLine)) {
code = code.replace(oldSpawnLine, newSpawnLine);
console.log(` ✓ sentinel (spawn) → ${file}`);
patched++;
} else if (code.includes(newSpawnLine)) {
console.log(` → sentinel (spawn) already patched: ${file}`);
} else {
console.log(` ⚠ sentinel (spawn) pattern not found: ${file}`);
}
// 6b — delete .updating in close handler
if (code.includes(oldCloseStart)) {
code = code.replace(oldCloseStart, newCloseStart);
console.log(` ✓ sentinel (close) → ${file}`);
patched++;
} else if (code.includes(newCloseStart)) {
console.log(` → sentinel (close) already patched: ${file}`);
} else {
console.log(` ⚠ sentinel (close) pattern not found: ${file}`);
}
// 6c — delete .updating in error handler
if (code.includes(oldErrorStart)) {
code = code.replace(oldErrorStart, newErrorStart);
console.log(` ✓ sentinel (error) → ${file}`);
patched++;
} else if (code.includes(newErrorStart)) {
console.log(` → sentinel (error) already patched: ${file}`);
} else {
console.log(` ⚠ sentinel (error) pattern not found: ${file}`);
}
// Patch 7 — SO_REUSEADDR on server socket
if (code.includes(oldListen)) {
code = code.replace(oldListen, newListen);
console.log(` ✓ reuseAddr → ${file}`);
patched++;
} else if (code.includes(newListen)) {
console.log(` → reuseAddr already patched: ${file}`);
} else {
console.log(` ⚠ reuseAddr pattern not found: ${file}`);
}
// Patch 8 — append `&& node patch-update.js` to update commands
// 8a — npm install command
if (code.includes(oldNpmInstallCmd)) {
code = code.replace(oldNpmInstallCmd, newNpmInstallCmd);
console.log(` ✓ npm cmd + patch-update → ${file}`);
patched++;
} else if (code.includes(newNpmInstallCmd)) {
console.log(` → npm cmd + patch-update already patched: ${file}`);
} else {
console.log(` ⚠ npm cmd + patch-update pattern not found: ${file}`);
}
// 8b — git install command
if (code.includes(oldGitInstallCmd)) {
code = code.replace(oldGitInstallCmd, newGitInstallCmd);
console.log(` ✓ git cmd + patch-update → ${file}`);
patched++;
} else if (code.includes(newGitInstallCmd)) {
console.log(` → git cmd + patch-update already patched: ${file}`);
} else {
console.log(` ⚠ git cmd + patch-update pattern not found: ${file}`);
}
// Patch 10 — GIT_HTTP_PROTOCOL_VERSION=1 at server startup
if (code.includes(oldGitProto)) {
code = code.replace(oldGitProto, newGitProto);
console.log(` ✓ GIT_HTTP_PROTOCOL_VERSION=1 → ${file}`);
patched++;
} else if (code.includes(newGitProto)) {
console.log(` → GIT_HTTP_PROTOCOL_VERSION=1 already patched: ${file}`);
} else {
console.log(` ⚠ GIT_HTTP_PROTOCOL_VERSION=1 pattern not found: ${file}`);
}
if (code !== original) {
writeFileSync(file, code, 'utf-8');
}
} catch (err) {
if (err.code === 'ENOENT') {
console.log(` - skipped (not found): ${file}`);
} else {
console.error(` ✗ error ${file}: ${err.message}`);
}
}
}
if (patched > 0) {
console.log(`Update patch applied (${patched} change${patched > 1 ? 's' : ''}).`);
}
// ---------------------------------------------------------------------------
// Patch 9 — sw.js: asset caching strategy → stale-while-revalidate
// ---------------------------------------------------------------------------
try {
let swCode = readFileSync(swPath, 'utf-8');
if (swCode.includes(oldSwAssetBlock)) {
swCode = swCode.replace(oldSwAssetBlock, newSwAssetBlock);
writeFileSync(swPath, swCode, 'utf-8');
console.log(' ✓ sw.js asset strategy → stale-while-revalidate');
} else if (swCode.includes(newSwAssetBlock)) {
console.log(' → sw.js already patched');
} else {
console.log(' ⚠ sw.js pattern not found');
}
} catch (err) {
if (err.code === 'ENOENT') {
console.log(' - skipped (not found): sw.js');
} else {
console.error(` ✗ error sw.js: ${err.message}`);
}
}