-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathpatch-next-write-atomic.js
More file actions
66 lines (54 loc) · 2.11 KB
/
Copy pathpatch-next-write-atomic.js
File metadata and controls
66 lines (54 loc) · 2.11 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
#!/usr/bin/env node
/**
* Patch Next.js writeFileAtomic to create parent directories before writing.
*
* Turbopack's writeFileAtomic creates a temp file in the same directory as the
* target, but sometimes the directory (.next/static/<buildId>/) doesn't yet
* exist at that point, causing ENOENT. This patch adds a mkdirSync call.
*
* Lives in project root so .vercelignore (which strips scripts/*) can't remove it.
*/
const fs = require('fs');
const path = require('path');
const FILES_TO_PATCH = [
'node_modules/next/dist/lib/fs/write-atomic.js',
'node_modules/next/dist/esm/lib/fs/write-atomic.js',
];
let patched = 0;
for (const relPath of FILES_TO_PATCH) {
const filePath = path.resolve(__dirname, relPath);
if (!fs.existsSync(filePath)) continue;
let content = fs.readFileSync(filePath, 'utf-8');
// Skip if already patched
if (content.includes('mkdirSync')) {
continue;
}
// CJS version
content = content.replace(
/const _fs = require\("fs"\);\nconst _rename = require\("\.\/rename"\);/,
'const _fs = require("fs");\nconst _path = require("path");\nconst _rename = require("./rename");'
);
// ESM version
content = content.replace(
/import \{ unlinkSync, writeFileSync \} from 'fs';/,
"import { mkdirSync, unlinkSync, writeFileSync } from 'fs';\nimport { dirname } from 'path';"
);
// CJS: add mkdirSync before writeFileSync
content = content.replace(
/(\s+try \{\n\s+)\(0, _fs\.writeFileSync\)\(tempPath,/,
'$1const dir = _path.dirname(tempPath);\n (0, _fs.mkdirSync)(dir, { recursive: true });\n (0, _fs.writeFileSync)(tempPath,'
);
// ESM: add mkdirSync before writeFileSync
content = content.replace(
/(\s+try \{\n\s+)writeFileSync\(tempPath,/,
'$1mkdirSync(dirname(tempPath), { recursive: true });\n writeFileSync(tempPath,'
);
fs.writeFileSync(filePath, content, 'utf-8');
patched++;
console.log(`[patch-next] Patched ${relPath}`);
}
if (patched > 0) {
console.log(`[patch-next] ${patched} file(s) patched successfully`);
} else {
console.log('[patch-next] No files needed patching (already patched or not found)');
}