File size: 8,589 Bytes
3a65265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { setupGitHooks } from "./setup-git-hooks.js";

function detectPackageManager(ua = process.env.npm_config_user_agent ?? "") {
  // Examples:
  // - "pnpm/10.23.0 npm/? node/v22.21.1 darwin arm64"
  // - "npm/10.9.4 node/v22.12.0 linux x64"
  // - "bun/1.2.2"
  const normalized = String(ua).trim();
  if (normalized.startsWith("pnpm/")) return "pnpm";
  if (normalized.startsWith("bun/")) return "bun";
  if (normalized.startsWith("npm/")) return "npm";
  if (normalized.startsWith("yarn/")) return "yarn";
  return "unknown";
}

function shouldApplyPnpmPatchedDependenciesFallback(pm = detectPackageManager()) {
  // pnpm already applies pnpm.patchedDependencies itself; re-applying would fail.
  return pm !== "pnpm";
}

function getRepoRoot() {
  const here = path.dirname(fileURLToPath(import.meta.url));
  return path.resolve(here, "..");
}

function ensureExecutable(targetPath) {
  if (process.platform === "win32") return;
  if (!fs.existsSync(targetPath)) return;
  try {
    const mode = fs.statSync(targetPath).mode & 0o777;
    if (mode & 0o100) return;
    fs.chmodSync(targetPath, 0o755);
  } catch (err) {
    console.warn(`[postinstall] chmod failed: ${err}`);
  }
}

function hasGit(repoRoot) {
  const result = spawnSync("git", ["--version"], { cwd: repoRoot, stdio: "ignore" });
  return result.status === 0;
}

function extractPackageName(key) {
  if (key.startsWith("@")) {
    const idx = key.indexOf("@", 1);
    if (idx === -1) return key;
    return key.slice(0, idx);
  }
  const idx = key.lastIndexOf("@");
  if (idx <= 0) return key;
  return key.slice(0, idx);
}

function stripPrefix(p) {
  if (p.startsWith("a/") || p.startsWith("b/")) return p.slice(2);
  return p;
}

function parseRange(segment) {
  // segment: "-12,5" or "+7"
  const [startRaw, countRaw] = segment.slice(1).split(",");
  const start = Number.parseInt(startRaw, 10);
  const count = countRaw ? Number.parseInt(countRaw, 10) : 1;
  if (Number.isNaN(start) || Number.isNaN(count)) {
    throw new Error(`invalid hunk range: ${segment}`);
  }
  return { start, count };
}

function parsePatch(patchText) {
  const lines = patchText.split("\n");
  const files = [];
  let i = 0;

  while (i < lines.length) {
    if (!lines[i].startsWith("diff --git ")) {
      i += 1;
      continue;
    }

    const file = { oldPath: null, newPath: null, hunks: [] };
    i += 1;

    // Skip index line(s)
    while (i < lines.length && lines[i].startsWith("index ")) i += 1;

    if (i < lines.length && lines[i].startsWith("--- ")) {
      file.oldPath = stripPrefix(lines[i].slice(4).trim());
      i += 1;
    }
    if (i < lines.length && lines[i].startsWith("+++ ")) {
      file.newPath = stripPrefix(lines[i].slice(4).trim());
      i += 1;
    }

    while (i < lines.length && lines[i].startsWith("@@")) {
      const header = lines[i];
      const match = /^@@\s+(-\d+(?:,\d+)?)\s+(\+\d+(?:,\d+)?)\s+@@/.exec(header);
      if (!match) throw new Error(`invalid hunk header: ${header}`);
      const oldRange = parseRange(match[1]);
      const newRange = parseRange(match[2]);
      i += 1;

      const hunkLines = [];
      while (i < lines.length) {
        const line = lines[i];
        if (line.startsWith("@@") || line.startsWith("diff --git ")) break;
        if (line === "") {
          i += 1;
          continue;
        }
        if (line.startsWith("\\ No newline at end of file")) {
          i += 1;
          continue;
        }
        hunkLines.push(line);
        i += 1;
      }

      file.hunks.push({
        oldStart: oldRange.start,
        oldLines: oldRange.count,
        newStart: newRange.start,
        newLines: newRange.count,
        lines: hunkLines,
      });
    }

    if (file.newPath && file.hunks.length > 0) {
      files.push(file);
    }
  }

  return files;
}

function readFileLines(targetPath) {
  if (!fs.existsSync(targetPath)) {
    throw new Error(`target file missing: ${targetPath}`);
  }
  const raw = fs.readFileSync(targetPath, "utf-8");
  const hasTrailingNewline = raw.endsWith("\n");
  const parts = raw.split("\n");
  if (hasTrailingNewline) parts.pop();
  return { lines: parts, hasTrailingNewline };
}

function writeFileLines(targetPath, lines, hadTrailingNewline) {
  const content = lines.join("\n") + (hadTrailingNewline ? "\n" : "");
  fs.writeFileSync(targetPath, content, "utf-8");
}

function applyHunk(lines, hunk, offset) {
  let cursor = hunk.oldStart - 1 + offset;
  const expected = [];
  for (const raw of hunk.lines) {
    const marker = raw[0];
    if (marker === " " || marker === "+") {
      expected.push(raw.slice(1));
    }
  }
  if (cursor >= 0 && cursor + expected.length <= lines.length) {
    let alreadyApplied = true;
    for (let i = 0; i < expected.length; i += 1) {
      if (lines[cursor + i] !== expected[i]) {
        alreadyApplied = false;
        break;
      }
    }
    if (alreadyApplied) {
      const delta = hunk.newLines - hunk.oldLines;
      return offset + delta;
    }
  }

  for (const raw of hunk.lines) {
    const marker = raw[0];
    const text = raw.slice(1);
    if (marker === " ") {
      if (lines[cursor] !== text) {
        throw new Error(
          `context mismatch at line ${cursor + 1}: expected "${text}", found "${lines[cursor] ?? "<eof>"}"`,
        );
      }
      cursor += 1;
    } else if (marker === "-") {
      if (lines[cursor] !== text) {
        throw new Error(
          `delete mismatch at line ${cursor + 1}: expected "${text}", found "${lines[cursor] ?? "<eof>"}"`,
        );
      }
      lines.splice(cursor, 1);
    } else if (marker === "+") {
      lines.splice(cursor, 0, text);
      cursor += 1;
    } else {
      throw new Error(`unexpected hunk marker: ${marker}`);
    }
  }

  const delta = hunk.newLines - hunk.oldLines;
  return offset + delta;
}

function applyPatchToFile(targetDir, filePatch) {
  if (filePatch.newPath === "/dev/null") {
    // deletion not needed for our patches
    return;
  }
  const relPath = stripPrefix(filePatch.newPath ?? filePatch.oldPath ?? "");
  const targetPath = path.join(targetDir, relPath);
  const { lines, hasTrailingNewline } = readFileLines(targetPath);

  let offset = 0;
  for (const hunk of filePatch.hunks) {
    offset = applyHunk(lines, hunk, offset);
  }

  writeFileLines(targetPath, lines, hasTrailingNewline);
}

function applyPatchSet({ patchText, targetDir }) {
  let resolvedTarget = path.resolve(targetDir);
  if (!fs.existsSync(resolvedTarget) || !fs.statSync(resolvedTarget).isDirectory()) {
    console.warn(`[postinstall] skip missing target: ${resolvedTarget}`);
    return;
  }
  resolvedTarget = fs.realpathSync(resolvedTarget);

  const files = parsePatch(patchText);
  if (files.length === 0) return;

  for (const filePatch of files) {
    applyPatchToFile(resolvedTarget, filePatch);
  }
}

function applyPatchFile({ patchPath, targetDir }) {
  const absPatchPath = path.resolve(patchPath);
  if (!fs.existsSync(absPatchPath)) {
    throw new Error(`missing patch: ${absPatchPath}`);
  }
  const patchText = fs.readFileSync(absPatchPath, "utf-8");
  applyPatchSet({ patchText, targetDir });
}

function main() {
  const repoRoot = getRepoRoot();
  process.chdir(repoRoot);

  ensureExecutable(path.join(repoRoot, "dist", "entry.js"));
  setupGitHooks({ repoRoot });

  if (!shouldApplyPnpmPatchedDependenciesFallback()) {
    return;
  }

  const pkgPath = path.join(repoRoot, "package.json");
  const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
  const patched = pkg?.pnpm?.patchedDependencies ?? {};

  // Bun does not support pnpm.patchedDependencies. Apply these patch files to
  // node_modules packages as a best-effort compatibility layer.
  for (const [key, relPatchPath] of Object.entries(patched)) {
    if (typeof relPatchPath !== "string" || !relPatchPath.trim()) continue;
    const pkgName = extractPackageName(String(key));
    if (!pkgName) continue;
    applyPatchFile({
      targetDir: path.join("node_modules", ...pkgName.split("/")),
      patchPath: relPatchPath,
    });
  }
}

try {
  const skip =
    process.env.CLAWDBOT_SKIP_POSTINSTALL === "1" ||
    process.env.VITEST === "true" ||
    process.env.NODE_ENV === "test";

  if (!skip) {
    main();
  }
} catch (err) {
  console.error(String(err));
  process.exit(1);
}

export {
  applyPatchFile,
  applyPatchSet,
  applyPatchToFile,
  detectPackageManager,
  parsePatch,
  shouldApplyPnpmPatchedDependenciesFallback,
};