branch-lens 0.3.0 → 0.3.1

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 (62) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/cli.js +5620 -3272
  4. package/dist/cpuWorker.js +1988 -0
  5. package/dist/launcher.d.ts +68 -15
  6. package/dist/launcher.js +6966 -4617
  7. package/dist/web/assets/AiAnnotator-CCj1dKr0.js +1 -0
  8. package/dist/web/assets/ChronicleStage-Cznb0SLP.js +30 -0
  9. package/dist/web/assets/CodeDiffStage-BAkeoFAz.js +3 -0
  10. package/dist/web/assets/CodexSessionBindingFields-DkR0bGRW.js +1 -0
  11. package/dist/web/assets/CompareStage-6mAMGmE9.js +2 -0
  12. package/dist/web/assets/CompareStage-DMkd60zd.css +1 -0
  13. package/dist/web/assets/DoctorChecklist-cmvmLa4s.js +1 -0
  14. package/dist/web/assets/ExecutionTraceView-BuKMTJLz.js +1 -0
  15. package/dist/web/assets/LiquidSelect-BcHivJrw.js +1 -0
  16. package/dist/web/assets/LogDrawer-hywJ_5f2.js +1 -0
  17. package/dist/web/assets/{PrDraftModal-DpkvQrsw.js → PrDraftModal-CKdIoZTF.js} +2 -12
  18. package/dist/web/assets/ResponsiveMatrixStage-IZfS6JC4.js +1 -0
  19. package/dist/web/assets/RouteBar-CbnzrFM4.js +1 -0
  20. package/dist/web/assets/SafeMarkdownBody-DAg3yHJ5.js +1 -0
  21. package/dist/web/assets/SettingsModal-CfMz0_4F.js +4 -0
  22. package/dist/web/assets/{TaskComposer-EPlw68x5.js → TaskComposer-CO8tCqFg.js} +5 -5
  23. package/dist/web/assets/TaskPanel--8Ima6hX.js +5 -0
  24. package/dist/web/assets/VerificationSummaryCard-D5fnYeAl.js +1 -0
  25. package/dist/web/assets/VerificationView-OYxRYOMD.js +1 -0
  26. package/dist/web/assets/WelcomeDoctorView-DCmfWMhg.js +1 -0
  27. package/dist/web/assets/annotate-Cnu9ugkR.css +1 -0
  28. package/dist/web/assets/doctor-BvSbLVK8.css +1 -0
  29. package/dist/web/assets/index-B76NgI6o.css +1 -0
  30. package/dist/web/assets/index-CuRBE0Be.js +3 -0
  31. package/dist/web/assets/logs-_ws1o3oK.css +1 -0
  32. package/dist/web/assets/pickedElement-DWJDcr9q.js +1 -0
  33. package/dist/web/assets/settings-DaDpE3K8.css +1 -0
  34. package/dist/web/assets/stageCache-nD7q31wP.js +1 -0
  35. package/dist/web/assets/tasks-BYC2JuuF.css +1 -0
  36. package/dist/web/assets/vendor-icons-BeN0on9X.js +371 -0
  37. package/dist/web/assets/vendor-markdown-COdlM-u6.js +14 -0
  38. package/dist/web/assets/vendor-react-CIotE-6Q.js +49 -0
  39. package/dist/web/index.html +9 -2
  40. package/package.json +1 -1
  41. package/dist/web/assets/AiAnnotator-zRRz7Hd_.js +0 -21
  42. package/dist/web/assets/ChronicleStage-DU21HBDf.js +0 -30
  43. package/dist/web/assets/CodeDiffStage-DAhgBZQK.js +0 -23
  44. package/dist/web/assets/CodexSessionBindingFields-DiO2jbce.js +0 -1
  45. package/dist/web/assets/CompareStage-BJ8Jwxc8.js +0 -37
  46. package/dist/web/assets/DoctorChecklist-C6zhApVB.js +0 -11
  47. package/dist/web/assets/ExecutionTraceView-BJm89dCg.js +0 -21
  48. package/dist/web/assets/ResponsiveMatrixStage-Df2JDBnc.js +0 -6
  49. package/dist/web/assets/RouteBar-DgHUPTd-.js +0 -1
  50. package/dist/web/assets/SafeMarkdownBody-CqB1wBws.js +0 -14
  51. package/dist/web/assets/SettingsModal-BUP_V44u.js +0 -9
  52. package/dist/web/assets/VerificationView-CQZlUjOa.js +0 -1
  53. package/dist/web/assets/WelcomeDoctorView-Cdemm1Gq.js +0 -6
  54. package/dist/web/assets/book-open-J84boHt9.js +0 -6
  55. package/dist/web/assets/chevron-up-BNxyonTB.js +0 -6
  56. package/dist/web/assets/external-link-BOTi_FMk.js +0 -6
  57. package/dist/web/assets/git-commit-horizontal-fzBJ5V7a.js +0 -11
  58. package/dist/web/assets/index-DOHn8ygK.js +0 -254
  59. package/dist/web/assets/index-_5gNstnt.css +0 -1
  60. package/dist/web/assets/info-kubeg88y.js +0 -6
  61. package/dist/web/assets/pickedElement-p10cew5p.js +0 -11
  62. package/dist/web/assets/search-CZutG0ij.js +0 -6
@@ -0,0 +1,1988 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // server/workers/cpuPool.ts
12
+ import { existsSync } from "fs";
13
+ import { SHARE_ENV, Worker } from "worker_threads";
14
+ function findWorker() {
15
+ return [new URL("./cpuWorker.js", import.meta.url), new URL("./cpuWorker.ts", import.meta.url)].find((url) => existsSync(url));
16
+ }
17
+ function asBuffer(bytes) {
18
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
19
+ }
20
+ var MAX_WORKERS, IDLE_TIMEOUT_MS, CpuPool, sharedPool, getCpuPool;
21
+ var init_cpuPool = __esm({
22
+ "server/workers/cpuPool.ts"() {
23
+ "use strict";
24
+ MAX_WORKERS = 2;
25
+ IDLE_TIMEOUT_MS = 18e4;
26
+ CpuPool = class {
27
+ slots = /* @__PURE__ */ new Set();
28
+ queue = [];
29
+ idleTimeoutMs;
30
+ workerUrl;
31
+ warned = false;
32
+ disposed = false;
33
+ constructor({ idleTimeoutMs = IDLE_TIMEOUT_MS, workerUrl = findWorker() } = {}) {
34
+ this.idleTimeoutMs = idleTimeoutMs;
35
+ this.workerUrl = workerUrl && existsSync(workerUrl) ? workerUrl : void 0;
36
+ }
37
+ run(request, fallback) {
38
+ return new Promise((resolve, reject) => {
39
+ if (this.disposed) {
40
+ reject(new Error("CPU \u5DE5\u4F5C\u7EBF\u7A0B\u6C60\u5DF2\u5173\u95ED"));
41
+ return;
42
+ }
43
+ this.queue.push({
44
+ request,
45
+ resolve: (result) => resolve(result),
46
+ reject,
47
+ fallback: () => {
48
+ void Promise.resolve().then(fallback).then(resolve, reject);
49
+ }
50
+ });
51
+ this.drain();
52
+ });
53
+ }
54
+ drain() {
55
+ if (!this.queue.length || this.disposed) return;
56
+ if (!this.workerUrl) {
57
+ if (!this.warned) this.useMainThread();
58
+ for (const job of this.queue.splice(0)) job.fallback();
59
+ return;
60
+ }
61
+ while (this.queue.length) {
62
+ let slot = [...this.slots].find((item) => !item.job && !item.terminating);
63
+ if (!slot) {
64
+ if (this.slots.size >= MAX_WORKERS) return;
65
+ try {
66
+ slot = this.startWorker(this.workerUrl);
67
+ } catch (error) {
68
+ this.useMainThread(error);
69
+ this.drain();
70
+ return;
71
+ }
72
+ }
73
+ clearTimeout(slot.timer);
74
+ slot.worker.ref();
75
+ slot.job = this.queue.shift();
76
+ try {
77
+ slot.worker.postMessage(slot.job.request);
78
+ } catch (error) {
79
+ slot.job.reject(error);
80
+ this.setIdle(slot);
81
+ }
82
+ }
83
+ }
84
+ startWorker(url) {
85
+ const entry = url.pathname.endsWith(".ts") ? new URL("data:text/javascript," + encodeURIComponent(
86
+ `import { register } from ${JSON.stringify(import.meta.resolve("tsx/esm/api"))};
87
+ register();
88
+ await import(${JSON.stringify(url.href)});`
89
+ )) : url;
90
+ const execArgv = process.execArgv.filter((arg, index, args) => arg !== "--input-type" && !arg.startsWith("--input-type=") && args[index - 1] !== "--input-type");
91
+ const worker = new Worker(entry, { env: SHARE_ENV, execArgv });
92
+ const slot = { worker, ready: false };
93
+ this.slots.add(slot);
94
+ worker.on("message", (message) => {
95
+ if ("ready" in message) {
96
+ slot.ready = true;
97
+ return;
98
+ }
99
+ const job = slot.job;
100
+ if (!job) return;
101
+ if ("error" in message) job.reject(message.error);
102
+ else job.resolve(message.result);
103
+ this.setIdle(slot);
104
+ this.drain();
105
+ });
106
+ worker.on("error", (error) => {
107
+ this.failWorker(slot, error);
108
+ void this.terminate(slot);
109
+ });
110
+ worker.on("exit", (code) => {
111
+ this.slots.delete(slot);
112
+ clearTimeout(slot.timer);
113
+ if (slot.job) this.failWorker(slot, new Error(`CPU \u5DE5\u4F5C\u7EBF\u7A0B\u610F\u5916\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${code}\uFF09`));
114
+ this.drain();
115
+ });
116
+ return slot;
117
+ }
118
+ failWorker(slot, error) {
119
+ if (!slot.ready && !this.disposed) {
120
+ this.useMainThread(error);
121
+ slot.job?.fallback();
122
+ } else {
123
+ slot.job?.reject(error);
124
+ }
125
+ slot.job = void 0;
126
+ }
127
+ useMainThread(error) {
128
+ this.workerUrl = void 0;
129
+ if (this.warned) return;
130
+ this.warned = true;
131
+ console.warn("CPU \u5DE5\u4F5C\u7EBF\u7A0B\u4E0D\u53EF\u7528\uFF0C\u6539\u7528\u4E3B\u7EBF\u7A0B\u6267\u884C\u3002", error instanceof Error ? error.message : error ?? "");
132
+ }
133
+ setIdle(slot) {
134
+ slot.job = void 0;
135
+ slot.worker.unref();
136
+ slot.timer = setTimeout(() => {
137
+ void this.terminate(slot);
138
+ }, this.idleTimeoutMs).unref();
139
+ }
140
+ terminate(slot) {
141
+ clearTimeout(slot.timer);
142
+ return slot.terminating ??= slot.worker.terminate();
143
+ }
144
+ stats() {
145
+ const live = [...this.slots].filter((slot) => !slot.terminating);
146
+ const active = live.filter((slot) => slot.job).length;
147
+ return { active, idle: live.length - active, queued: this.queue.length, workerMode: this.workerUrl !== void 0 };
148
+ }
149
+ async dispose() {
150
+ this.disposed = true;
151
+ const error = new Error("CPU \u5DE5\u4F5C\u7EBF\u7A0B\u6C60\u5DF2\u5173\u95ED");
152
+ for (const job of this.queue.splice(0)) job.reject(error);
153
+ await Promise.all([...this.slots].map((slot) => {
154
+ slot.job?.reject(error);
155
+ slot.job = void 0;
156
+ return this.terminate(slot);
157
+ }));
158
+ }
159
+ };
160
+ getCpuPool = () => sharedPool ??= new CpuPool();
161
+ }
162
+ });
163
+
164
+ // server/ai/diffRegions.ts
165
+ var diffRegions_exports = {};
166
+ __export(diffRegions_exports, {
167
+ diffRegions: () => diffRegions,
168
+ diffRegionsAsync: () => diffRegionsAsync
169
+ });
170
+ import { PNG } from "pngjs";
171
+ import pixelmatch from "pixelmatch";
172
+ function diffRegions(baseBuffer, targetBuffer, baseDom = [], targetDom = []) {
173
+ const a = PNG.sync.read(baseBuffer), b = PNG.sync.read(targetBuffer);
174
+ const width = Math.max(a.width, b.width), height = Math.max(a.height, b.height);
175
+ const normalize = (p) => {
176
+ const n = new PNG({ width, height });
177
+ n.data.fill(255);
178
+ PNG.bitblt(p, n, 0, 0, p.width, p.height, 0, 0);
179
+ return n;
180
+ };
181
+ const sameSize = a.width === b.width && a.height === b.height;
182
+ const base = sameSize ? a : normalize(a), target = sameSize ? b : normalize(b), diff = new PNG({ width, height });
183
+ const count = pixelmatch(base.data, target.data, diff.data, width, height, {
184
+ threshold: 0.12,
185
+ includeAA: false,
186
+ diffMask: true
187
+ });
188
+ const cols = Math.ceil(width / 8), rows = Math.ceil(height / 8);
189
+ const cellCount = new Uint16Array(cols * rows);
190
+ const cellMinX = new Uint16Array(cellCount.length).fill(65535), cellMaxX = new Uint16Array(cellCount.length);
191
+ const cellMinY = new Uint16Array(cellCount.length).fill(65535), cellMaxY = new Uint16Array(cellCount.length);
192
+ for (let y = 0; y < height; y++)
193
+ for (let x = 0; x < width; x++) {
194
+ const idx = y * width + x;
195
+ if (diff.data[idx * 4 + 3]) {
196
+ const cell = Math.floor(y / 8) * cols + Math.floor(x / 8);
197
+ cellCount[cell]++;
198
+ cellMinX[cell] = Math.min(cellMinX[cell], x % 8);
199
+ cellMaxX[cell] = Math.max(cellMaxX[cell], x % 8);
200
+ cellMinY[cell] = Math.min(cellMinY[cell], y % 8);
201
+ cellMaxY[cell] = Math.max(cellMaxY[cell], y % 8);
202
+ }
203
+ }
204
+ const expanded = new Uint8Array(cellCount.length);
205
+ for (let y = 0; y < rows; y++)
206
+ for (let x = 0; x < cols; x++)
207
+ if (cellCount[y * cols + x])
208
+ for (let dy = -2; dy <= 2; dy++)
209
+ for (let dx = -2; dx <= 2; dx++) {
210
+ const xx = x + dx, yy = y + dy;
211
+ if (xx >= 0 && yy >= 0 && xx < cols && yy < rows)
212
+ expanded[yy * cols + xx] = 1;
213
+ }
214
+ const boxes = [];
215
+ for (let k = 0; k < expanded.length; k++)
216
+ if (expanded[k]) {
217
+ expanded[k] = 0;
218
+ const q = [k];
219
+ let minX = cols, minY = rows, maxX = 0, maxY = 0;
220
+ for (let j = 0; j < q.length; j++) {
221
+ const x = q[j] % cols, y = Math.floor(q[j] / cols);
222
+ minX = Math.min(minX, x);
223
+ maxX = Math.max(maxX, x);
224
+ minY = Math.min(minY, y);
225
+ maxY = Math.max(maxY, y);
226
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
227
+ const xx = x + dx, yy = y + dy, n = yy * cols + xx;
228
+ if (xx >= 0 && yy >= 0 && xx < cols && yy < rows && expanded[n]) {
229
+ expanded[n] = 0;
230
+ q.push(n);
231
+ }
232
+ }
233
+ }
234
+ const box = {
235
+ x: minX * 8,
236
+ y: minY * 8,
237
+ width: Math.min(width, (maxX + 1) * 8) - minX * 8,
238
+ height: Math.min(height, (maxY + 1) * 8) - minY * 8
239
+ };
240
+ if (!((box.width < 10 || box.height < 10) && box.width * box.height < 200))
241
+ boxes.push(box);
242
+ }
243
+ for (let i = 0; i < boxes.length; i++)
244
+ for (let j = i + 1; j < boxes.length; ) {
245
+ const a2 = boxes[i], b2 = boxes[j];
246
+ if (a2.x <= b2.x + b2.width + 20 && b2.x <= a2.x + a2.width + 20 && a2.y <= b2.y + b2.height + 20 && b2.y <= a2.y + a2.height + 20) {
247
+ const x = Math.min(a2.x, b2.x), y = Math.min(a2.y, b2.y);
248
+ a2.width = Math.max(a2.x + a2.width, b2.x + b2.width) - x;
249
+ a2.height = Math.max(a2.y + a2.height, b2.y + b2.height) - y;
250
+ a2.x = x;
251
+ a2.y = y;
252
+ boxes.splice(j, 1);
253
+ j = i + 1;
254
+ } else
255
+ j++;
256
+ }
257
+ const relevant = boxes.flatMap((box) => {
258
+ let n = 0, minX = width, maxX = 0, minY = height, maxY = 0;
259
+ for (let y = box.y / 8; y < Math.ceil((box.y + box.height) / 8); y++) {
260
+ for (let x = box.x / 8; x < Math.ceil((box.x + box.width) / 8); x++) {
261
+ const cell = y * cols + x;
262
+ if (!cellCount[cell]) continue;
263
+ n += cellCount[cell];
264
+ minX = Math.min(minX, x * 8 + cellMinX[cell]);
265
+ maxX = Math.max(maxX, x * 8 + cellMaxX[cell]);
266
+ minY = Math.min(minY, y * 8 + cellMinY[cell]);
267
+ maxY = Math.max(maxY, y * 8 + cellMaxY[cell]);
268
+ }
269
+ }
270
+ const w = maxX - minX + 1, h = maxY - minY + 1;
271
+ return n && (w < 10 || h < 10) && w * h < 200 ? [] : [{ box, n }];
272
+ });
273
+ relevant.sort((a2, b2) => a2.box.y - b2.box.y || a2.box.x - b2.box.x);
274
+ const annotated = new PNG({ width, height });
275
+ target.data.copy(annotated.data);
276
+ const set = (x, y, r, g, bl) => {
277
+ if (x >= 0 && y >= 0 && x < width && y < height) {
278
+ const p = (y * width + x) * 4;
279
+ annotated.data[p] = r;
280
+ annotated.data[p + 1] = g;
281
+ annotated.data[p + 2] = bl;
282
+ annotated.data[p + 3] = 255;
283
+ }
284
+ };
285
+ const regions = relevant.slice(0, 12).map(({ box, n }, index) => {
286
+ const right = box.x + box.width, bottom = box.y + box.height;
287
+ const topBorder = Math.min(bottom, box.y + 3), bottomBorder = Math.max(topBorder, bottom - 3);
288
+ const leftBorder = Math.min(right, box.x + 3), rightBorder = Math.max(leftBorder, right - 3);
289
+ for (let x = box.x; x < right; x++) {
290
+ for (let y = box.y; y < topBorder; y++) set(x, y, 245, 30, 35);
291
+ for (let y = bottomBorder; y < bottom; y++) set(x, y, 245, 30, 35);
292
+ }
293
+ for (let y = topBorder; y < bottomBorder; y++) {
294
+ for (let x = box.x; x < leftBorder; x++) set(x, y, 245, 30, 35);
295
+ for (let x = rightBorder; x < right; x++) set(x, y, 245, 30, 35);
296
+ }
297
+ const label = String(index + 1), bw = label.length * 8 + 6;
298
+ for (let y = box.y; y < Math.min(height, box.y + 17); y++)
299
+ for (let x = box.x; x < Math.min(width, box.x + bw); x++)
300
+ set(x, y, 245, 30, 35);
301
+ [...label].forEach((d, k) => digits[d].forEach((row, yy) => [...row].forEach((v, xx) => {
302
+ if (v === "1")
303
+ for (let sy = 0; sy < 2; sy++)
304
+ for (let sx = 0; sx < 2; sx++)
305
+ set(box.x + 3 + k * 8 + xx * 2 + sx, box.y + 3 + yy * 2 + sy, 255, 255, 255);
306
+ })));
307
+ const hits = (dom) => dom.filter((e) => e.rect.x < box.x + box.width && e.rect.x + e.rect.width > box.x && e.rect.y < box.y + box.height && e.rect.y + e.rect.height > box.y).map((e) => `${e.tag}\uFF1A${e.text}`);
308
+ const before = hits(baseDom), after = hits(targetDom);
309
+ const hints = [...before.filter((x) => !after.includes(x)).map((x) => `\u6D88\u5931\uFF1A${x}`), ...after.filter((x) => !before.includes(x)).map((x) => `\u65B0\u589E\uFF1A${x}`)].slice(0, 10);
310
+ return {
311
+ id: index + 1,
312
+ box,
313
+ normBox: {
314
+ x: box.x / width,
315
+ y: box.y / height,
316
+ width: box.width / width,
317
+ height: box.height / height
318
+ },
319
+ diffPixels: n,
320
+ diffRatio: n / (box.width * box.height),
321
+ category: "\u7EFC\u5408\u6539\u52A8",
322
+ title: "\u9875\u9762\u533A\u57DF\u53D1\u751F\u53D8\u5316",
323
+ description: "\u8BE5\u533A\u57DF\u5B58\u5728\u89C6\u89C9\u5DEE\u5F02\u3002",
324
+ relatedFiles: [],
325
+ domHints: hints
326
+ };
327
+ });
328
+ return {
329
+ width,
330
+ height,
331
+ totalDiffRatio: count / (width * height),
332
+ regions,
333
+ diffData: diff.data,
334
+ diffPng: PNG.sync.write(diff),
335
+ annotatedPng: PNG.sync.write(annotated),
336
+ basePng: sameSize ? baseBuffer : PNG.sync.write(base),
337
+ targetPng: sameSize ? targetBuffer : PNG.sync.write(target)
338
+ };
339
+ }
340
+ async function diffRegionsAsync(baseBuffer, targetBuffer, baseDom = [], targetDom = []) {
341
+ const result = await getCpuPool().run(
342
+ { kind: "diffRegions", base: baseBuffer, target: targetBuffer, baseDom, targetDom },
343
+ () => diffRegions(baseBuffer, targetBuffer, baseDom, targetDom)
344
+ );
345
+ if (!("sameSize" in result)) return result;
346
+ const { diffData, diffPng, annotatedPng, width, height, regions, totalDiffRatio } = result;
347
+ const { basePng, targetPng } = result.sameSize ? { basePng: baseBuffer, targetPng: targetBuffer } : { basePng: asBuffer(result.basePng), targetPng: asBuffer(result.targetPng) };
348
+ return {
349
+ width,
350
+ height,
351
+ regions,
352
+ totalDiffRatio,
353
+ diffData: asBuffer(diffData),
354
+ diffPng: asBuffer(diffPng),
355
+ annotatedPng: asBuffer(annotatedPng),
356
+ basePng,
357
+ targetPng
358
+ };
359
+ }
360
+ var digits;
361
+ var init_diffRegions = __esm({
362
+ "server/ai/diffRegions.ts"() {
363
+ "use strict";
364
+ init_cpuPool();
365
+ digits = {
366
+ "0": ["111", "101", "101", "101", "111"],
367
+ "1": ["010", "110", "010", "010", "111"],
368
+ "2": ["111", "001", "111", "100", "111"],
369
+ "3": ["111", "001", "111", "001", "111"],
370
+ "4": ["101", "101", "111", "001", "001"],
371
+ "5": ["111", "100", "111", "001", "111"],
372
+ "6": ["111", "100", "111", "101", "111"],
373
+ "7": ["111", "001", "010", "010", "010"],
374
+ "8": ["111", "101", "111", "101", "111"],
375
+ "9": ["111", "101", "111", "001", "111"]
376
+ };
377
+ }
378
+ });
379
+
380
+ // server/ai/capture.ts
381
+ import { execFile } from "child_process";
382
+ import { createHash } from "crypto";
383
+ import { promises as fs } from "fs";
384
+ import path from "path";
385
+ import { promisify } from "util";
386
+ import { chromium } from "playwright-core";
387
+ async function findChrome({
388
+ platform = process.platform,
389
+ env = process.env,
390
+ accessFn,
391
+ whichFn = async (command) => {
392
+ try {
393
+ return (await exec("which", [command], { env, timeout: 1500 })).stdout.trim().split(/\r?\n/, 1)[0] || null;
394
+ } catch (error) {
395
+ const { code } = error;
396
+ if (code === 1 || code === "ENOENT") return null;
397
+ throw error;
398
+ }
399
+ }
400
+ } = {}) {
401
+ async function firstAccessible(files2) {
402
+ for (const file of files2) {
403
+ try {
404
+ if (accessFn) await accessFn(file);
405
+ else {
406
+ if (!(await fs.stat(file)).isFile()) continue;
407
+ await fs.access(file, fs.constants.X_OK);
408
+ }
409
+ return file;
410
+ } catch (error) {
411
+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(error.code ?? "")) throw error;
412
+ }
413
+ }
414
+ return null;
415
+ }
416
+ if (env.BRANCH_LENS_CHROME_PATH) {
417
+ const override = await firstAccessible([env.BRANCH_LENS_CHROME_PATH]);
418
+ if (override) return override;
419
+ }
420
+ if (platform === "darwin") return firstAccessible(macBrowsers);
421
+ if (platform === "win32") {
422
+ const entries = Object.fromEntries(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
423
+ return firstAccessible(["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"].flatMap((name) => {
424
+ const root = entries[name];
425
+ return root ? windowsBrowsers.map((parts) => path.win32.join(root, ...parts)) : [];
426
+ }));
427
+ }
428
+ for (const command of pathBrowsers) {
429
+ const found = await whichFn(command);
430
+ if (found) return found;
431
+ }
432
+ return firstAccessible(posixBrowsers);
433
+ }
434
+ async function launchChromium() {
435
+ const executablePath = await findChrome();
436
+ if (!executablePath) throw new Error("\u672A\u627E\u5230 Chrome \u6216 Chromium\uFF0C\u8BF7\u8BBE\u7F6E BRANCH_LENS_CHROME_PATH");
437
+ try {
438
+ return await chromium.launch({ executablePath, headless: true });
439
+ } catch (error) {
440
+ throw new Error("\u65E0\u6CD5\u542F\u52A8\u622A\u56FE\u6D4F\u89C8\u5668\uFF0C\u8BF7\u68C0\u67E5 Chrome \u6216 Chromium \u5B89\u88C5", { cause: error });
441
+ }
442
+ }
443
+ function contextKey(origin, session) {
444
+ const state = session ? [session.cookies, session.localStorage, session.sessionStorage].map((values) => Object.entries(values).sort(([a], [b]) => a.localeCompare(b))) : [];
445
+ return createHash("sha256").update(JSON.stringify([origin, state])).digest("hex");
446
+ }
447
+ function createCaptureBrowser(launch, { idleTimeoutMs, reuseContexts = false } = {}) {
448
+ let active;
449
+ let pending;
450
+ let idle;
451
+ let inFlight = 0;
452
+ const contexts = /* @__PURE__ */ new Map();
453
+ function retireContext(key, entry) {
454
+ if (contexts.get(key) === entry) contexts.delete(key);
455
+ clearTimeout(entry.idle);
456
+ return entry.closing ??= entry.context.then((context) => context.close()).catch(() => {
457
+ });
458
+ }
459
+ function retireContexts(browser) {
460
+ return Promise.all([...contexts].flatMap(([key, entry]) => entry.browser === browser ? [retireContext(key, entry)] : []));
461
+ }
462
+ async function discard(browser) {
463
+ if (active !== browser) return;
464
+ active = void 0;
465
+ clearTimeout(idle);
466
+ await Promise.all([retireContexts(browser), browser.close().catch(() => {
467
+ })]);
468
+ }
469
+ return {
470
+ begin() {
471
+ clearTimeout(idle);
472
+ inFlight++;
473
+ },
474
+ end() {
475
+ if (--inFlight === 0 && active && idleTimeoutMs !== void 0) {
476
+ const browser = active;
477
+ idle = setTimeout(() => {
478
+ void discard(browser);
479
+ }, idleTimeoutMs).unref();
480
+ }
481
+ },
482
+ get() {
483
+ if (active?.isConnected()) return Promise.resolve(active);
484
+ if (active) void discard(active);
485
+ return pending ??= launch().then((browser) => {
486
+ active = browser;
487
+ browser.once("disconnected", () => {
488
+ if (active === browser) {
489
+ active = void 0;
490
+ clearTimeout(idle);
491
+ }
492
+ void retireContexts(browser);
493
+ });
494
+ return browser;
495
+ }).finally(() => {
496
+ pending = void 0;
497
+ });
498
+ },
499
+ async acquireContext(browser, origin, viewport, session) {
500
+ async function create() {
501
+ const context2 = await browser.newContext({ viewport });
502
+ try {
503
+ if (session) await applySession(context2, origin, session);
504
+ return context2;
505
+ } catch (error) {
506
+ await context2.close().catch(() => {
507
+ });
508
+ throw error;
509
+ }
510
+ }
511
+ const key = reuseContexts ? contextKey(origin, session) : "";
512
+ let entry = contexts.get(key);
513
+ if (entry?.browser !== browser) entry = void 0;
514
+ if (reuseContexts && !entry && contexts.size >= 8) {
515
+ const oldest = [...contexts].find(([, item]) => item.refCount === 0);
516
+ if (oldest) void retireContext(...oldest);
517
+ }
518
+ if (reuseContexts && (entry || contexts.size < 8)) {
519
+ const shared = entry ?? { browser, context: create(), refCount: 0 };
520
+ clearTimeout(shared.idle);
521
+ shared.refCount++;
522
+ contexts.delete(key);
523
+ contexts.set(key, shared);
524
+ try {
525
+ const context2 = await shared.context;
526
+ return { context: context2, shared: true, async release(failed) {
527
+ shared.refCount--;
528
+ if (failed) await retireContext(key, shared);
529
+ else if (shared.refCount === 0 && contexts.get(key) === shared) {
530
+ shared.idle = setTimeout(() => {
531
+ void retireContext(key, shared);
532
+ }, 6e4).unref();
533
+ }
534
+ } };
535
+ } catch (error) {
536
+ shared.refCount--;
537
+ await retireContext(key, shared);
538
+ throw error;
539
+ }
540
+ }
541
+ const context = await create();
542
+ return { context, shared: false, release: () => context.close().catch(() => {
543
+ }) };
544
+ },
545
+ discard,
546
+ async close() {
547
+ clearTimeout(idle);
548
+ const browser = active ?? await pending;
549
+ if (browser) await discard(browser);
550
+ }
551
+ };
552
+ }
553
+ async function applySession(context, origin, session) {
554
+ const cookieEntries = Object.entries(session.cookies);
555
+ if (cookieEntries.length > 0) {
556
+ await context.addCookies(cookieEntries.map(([name, value]) => ({ name, value, url: origin })));
557
+ }
558
+ const local = session.localStorage;
559
+ const sess = session.sessionStorage;
560
+ if (Object.keys(local).length > 0 || Object.keys(sess).length > 0) {
561
+ await context.addInitScript(({ l, s }) => {
562
+ for (const [k, v] of Object.entries(l)) window.localStorage.setItem(k, v);
563
+ for (const [k, v] of Object.entries(s)) window.sessionStorage.setItem(k, v);
564
+ }, { l: local, s: sess });
565
+ }
566
+ }
567
+ var exec, macBrowsers, windowsBrowsers, pathBrowsers, posixBrowsers, captureBrowser, closeBrowser;
568
+ var init_capture = __esm({
569
+ "server/ai/capture.ts"() {
570
+ "use strict";
571
+ exec = promisify(execFile);
572
+ macBrowsers = [
573
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
574
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
575
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
576
+ "/Applications/Chromium.app/Contents/MacOS/Chromium"
577
+ ];
578
+ windowsBrowsers = [
579
+ ["Google", "Chrome", "Application", "chrome.exe"],
580
+ ["Microsoft", "Edge", "Application", "msedge.exe"],
581
+ ["BraveSoftware", "Brave-Browser", "Application", "brave.exe"]
582
+ ];
583
+ pathBrowsers = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge", "brave-browser"];
584
+ posixBrowsers = ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/microsoft-edge", "/snap/bin/chromium"];
585
+ captureBrowser = createCaptureBrowser(launchChromium, { idleTimeoutMs: 5 * 60 * 1e3, reuseContexts: true });
586
+ closeBrowser = captureBrowser.close;
587
+ }
588
+ });
589
+
590
+ // server/agent/sessionBinding.ts
591
+ var init_sessionBinding = __esm({
592
+ "server/agent/sessionBinding.ts"() {
593
+ "use strict";
594
+ }
595
+ });
596
+
597
+ // server/core/input.ts
598
+ var init_input = __esm({
599
+ "server/core/input.ts"() {
600
+ "use strict";
601
+ }
602
+ });
603
+
604
+ // server/git/commitGraph.ts
605
+ import { execFile as execFile2 } from "child_process";
606
+ import { promisify as promisify2 } from "util";
607
+ var exec2;
608
+ var init_commitGraph = __esm({
609
+ "server/git/commitGraph.ts"() {
610
+ "use strict";
611
+ exec2 = promisify2(execFile2);
612
+ }
613
+ });
614
+
615
+ // server/git/fileClassifier.ts
616
+ function normalizePath(filePath) {
617
+ return filePath.replace(/\\/g, "/").replace(/^(?:\.\/)+/, "");
618
+ }
619
+ function classifyFile(filePath) {
620
+ const normalized = normalizePath(filePath);
621
+ return rules.find(([, patterns]) => patterns.some((pattern) => pattern.test(normalized)))?.[0] ?? "other";
622
+ }
623
+ function isVisualFrontendFile(filePath) {
624
+ const normalized = normalizePath(filePath);
625
+ if (classifyFile(normalized) !== "frontend") return false;
626
+ if (visualExtension.test(normalized)) return true;
627
+ return !/\.d\.ts$/i.test(normalized) && !/(?:^|\/)(?:types?|interfaces?|constants?|schemas?)\.[^/]+$/i.test(normalized) && !/(?:^|\/)(?:types|api|services|sdk|stores|utils|helpers|schemas|constants)\//i.test(normalized) && !/(?:^|\/)src\/client\//i.test(normalized);
628
+ }
629
+ function summarizeFileChanges(files2) {
630
+ const totalFiles = files2.length;
631
+ const frontend = files2.filter((f) => f.category === "frontend" || f.isFrontend);
632
+ const frontendFiles = frontend.length;
633
+ const visualFrontendFiles = frontend.filter((f) => !f.path || isVisualFrontendFile(f.path)).length;
634
+ const backendFiles = files2.filter((f) => f.category === "backend").length;
635
+ const configOrTestFiles = files2.filter((f) => f.category === "config" || f.category === "test" || f.category === "other").length;
636
+ const codeOnly = totalFiles > 0 && (frontendFiles === 0 || visualFrontendFiles === 0 && backendFiles > 0);
637
+ const mode = codeOnly ? "code" : visualFrontendFiles > 0 && backendFiles > 0 ? "mixed" : "visual";
638
+ return { totalFiles, frontendFiles, visualFrontendFiles, backendFiles, configOrTestFiles, mode };
639
+ }
640
+ var visualExtension, rules;
641
+ var init_fileClassifier = __esm({
642
+ "server/git/fileClassifier.ts"() {
643
+ "use strict";
644
+ visualExtension = /\.(?:tsx|jsx|vue|svelte|css|scss|sass|less|html|svg)$/i;
645
+ rules = [
646
+ ["test", [/\.(?:test|spec)\.[^/]+$/i, /(?:^|\/)(?:__tests__|tests?|e2e)\//i]],
647
+ ["backend", [
648
+ /^(?:server|backend|api|prisma|drizzle|migrations|supabase|scripts|cli|cmd|internal|services|workers|functions)\//i,
649
+ /(?:^|\/)app\/api\/(?:.*\/)?route\.[^/]+$/i,
650
+ /(?:^|\/)pages\/api\//i,
651
+ /(?:^|\/)(?:server|backend)\//i,
652
+ /(?:^|\/)tsup\.config\.[^/]+$/i,
653
+ /\.(?:py|go|rs|java|kt|kts|rb|php|cs|cpp|cc|c|h|hpp|sql|prisma|graphql|gql|proto|sh|zsh|bash)$/i
654
+ ]],
655
+ ["config", [
656
+ /(?:^|\/)(?:Dockerfile|docker-compose|\.env|bun\.lock)[^/]*$/i,
657
+ /(?:^|\/)\.github\//i,
658
+ /\.config\.[^/]+$/i,
659
+ /\.(?:toml|ya?ml|ini|md|mdx|txt|json|lock)$/i
660
+ ]],
661
+ ["frontend", [
662
+ visualExtension,
663
+ /^(?:web|client|frontend)\/.*\.(?:ts|js|mjs)$/i,
664
+ /^(?:(?:web|client|frontend|ui|renderer|apps\/[^/]+|packages\/[^/]+)\/)?(?:src|app|pages|components|hooks|stores|views|styles|public|assets)\/.*\.(?:ts|js|mjs)$/i
665
+ ]]
666
+ ];
667
+ }
668
+ });
669
+
670
+ // server/core/packageManifest.ts
671
+ import { readFile } from "fs/promises";
672
+ import path2 from "path";
673
+ var init_packageManifest = __esm({
674
+ "server/core/packageManifest.ts"() {
675
+ "use strict";
676
+ init_input();
677
+ }
678
+ });
679
+
680
+ // server/git/tree.ts
681
+ import { execFile as execFile3 } from "child_process";
682
+ import { promisify as promisify3 } from "util";
683
+ import { createHash as createHash2 } from "crypto";
684
+ import path3 from "path";
685
+ import { createReadStream, promises as fs2 } from "fs";
686
+ async function gitRaw(repo, ...args) {
687
+ return (await exec3("git", ["-C", repo, ...args], { maxBuffer: 20 * 1024 * 1024 })).stdout;
688
+ }
689
+ async function git(repo, ...args) {
690
+ return (await gitRaw(repo, ...args)).trimEnd();
691
+ }
692
+ async function mergeBase(repo, left, right, graph) {
693
+ if (graph?.has(left) && graph.has(right)) {
694
+ const bases = graph.mergeBases(left, right);
695
+ if (bases.length < 2) return bases[0] ?? "";
696
+ }
697
+ return git(repo, "merge-base", left, right).catch((error) => {
698
+ if (error.code === 1) return "";
699
+ throw error;
700
+ });
701
+ }
702
+ function validRef(ref) {
703
+ if (!ref || ref.startsWith("-") || /[\x00-\x20~^:?*\[\\]/.test(ref) || ref.includes("..") || ref.includes("@{"))
704
+ throw new Error("\u65E0\u6548\u7684 Git \u5F15\u7528");
705
+ }
706
+ async function workingFileDigest(repo, file) {
707
+ const fullPath = path3.join(repo, file);
708
+ const stat = await fs2.lstat(fullPath, { bigint: true }).catch((error) => {
709
+ if (error.code !== "ENOENT") throw error;
710
+ });
711
+ if (stat?.isSymbolicLink()) return fs2.readlink(fullPath);
712
+ if (!stat?.isFile()) return "";
713
+ const statKey = `${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
714
+ const hit = workingDigests.get(fullPath);
715
+ workingDigests.delete(fullPath);
716
+ if (hit?.statKey === statKey) {
717
+ workingDigests.set(fullPath, hit);
718
+ return hit.digest;
719
+ }
720
+ const digest = createHash2("sha256");
721
+ for await (const chunk of createReadStream(fullPath)) digest.update(chunk);
722
+ const hex = digest.digest("hex");
723
+ workingDigests.set(fullPath, { statKey, digest: hex });
724
+ if (workingDigests.size > 2e3) workingDigests.delete(workingDigests.keys().next().value);
725
+ return hex;
726
+ }
727
+ async function resolveRefToSha(repo, ref) {
728
+ if (ref === "__working__") {
729
+ const [head, status, raw, paths] = await Promise.all([
730
+ git(repo, "rev-parse", "HEAD"),
731
+ git(repo, "--no-optional-locks", "status", "--porcelain=v1", "-z"),
732
+ git(repo, "--no-optional-locks", "diff", "--raw", "--no-abbrev", "-z", "HEAD"),
733
+ git(repo, "ls-files", "--modified", "--others", "--deduplicate", "--exclude-standard", "-z")
734
+ ]);
735
+ const hash = createHash2("sha256").update(head).update(status).update(raw);
736
+ const names = paths.split("\0").filter(Boolean);
737
+ const digests = await mapLimit(names, 6, (name) => workingFileDigest(repo, name));
738
+ names.forEach((name, i) => hash.update("\0").update(name).update("\0").update(digests[i]));
739
+ return `working-${hash.digest("hex").slice(0, 16)}`;
740
+ }
741
+ validRef(ref);
742
+ return git(repo, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`).catch((error) => {
743
+ if (error.code === 1) throw new GitRefNotFoundError(`Git \u5F15\u7528\u4E0D\u5B58\u5728\u6216\u672A\u6307\u5411\u63D0\u4EA4\uFF1A${ref}`);
744
+ throw error;
745
+ });
746
+ }
747
+ function fileStat(filePath, status, additions = 0, deletions = 0) {
748
+ const category = classifyFile(filePath);
749
+ return { path: filePath, status, additions, deletions, category, isFrontend: category === "frontend" };
750
+ }
751
+ async function files(repo, args) {
752
+ const raw = await git(repo, "diff", "--raw", "--numstat", "-z", "--no-renames", ...args, "--");
753
+ const records = raw.split("\0");
754
+ const statuses = /* @__PURE__ */ new Map();
755
+ let i = 0;
756
+ while (records[i].startsWith(":")) {
757
+ statuses.set(records[i + 1], records[i].slice(-1));
758
+ i += 2;
759
+ }
760
+ return records.slice(i, -1).map((row) => {
761
+ const [added, deleted, ...name] = row.split(" ");
762
+ const p = name.join(" ");
763
+ return fileStat(p, statuses.get(p), Number(added) || 0, Number(deleted) || 0);
764
+ });
765
+ }
766
+ function diffArgs(base, target) {
767
+ validRef(base);
768
+ validRef(target);
769
+ if (base === "__working__") return ["-R", target];
770
+ return target === "__working__" ? [base] : [`${base}...${target}`];
771
+ }
772
+ async function readBranchDiff(repo, base, target, read) {
773
+ try {
774
+ return await read(diffArgs(base, target));
775
+ } catch (error) {
776
+ if (error.code !== 128) throw error;
777
+ const [left, right] = await Promise.all([base, target].map((ref) => ref === "__working__" ? void 0 : resolveRefToSha(repo, ref))).catch((cause) => {
778
+ if (!(cause instanceof GitRefNotFoundError)) throw cause;
779
+ throw new GitRefNotFoundError(`\u627E\u4E0D\u5230\u5BF9\u6BD4\u76EE\u6807\u5206\u652F\u6216\u63D0\u4EA4\uFF08${base} / ${target}\uFF09\uFF0C\u8BF7\u5237\u65B0\u5206\u652F\u5217\u8868\u540E\u91CD\u8BD5`);
780
+ });
781
+ if (left && right && !await mergeBase(repo, left, right)) return read([left, right]);
782
+ throw error;
783
+ }
784
+ }
785
+ async function untrackedPaths(repo, base, target, file) {
786
+ if (base !== "__working__" && target !== "__working__") return [];
787
+ const raw = await git(repo, "--literal-pathspecs", "ls-files", "--others", "--exclude-standard", "-z", "--", ...file ? [file] : []);
788
+ return raw.split("\0").filter((p) => p && !p.endsWith("/"));
789
+ }
790
+ async function withUntrackedFile(repo, file, regular, symlink) {
791
+ const fullPath = path3.join(repo, file);
792
+ try {
793
+ const stat = await fs2.lstat(fullPath);
794
+ if (stat.isSymbolicLink()) return symlink(await fs2.readlink(fullPath));
795
+ if (stat.isFile()) return await regular(fullPath, stat);
796
+ return null;
797
+ } catch (error) {
798
+ const { code, path: failedPath } = error;
799
+ if ((code === "ENOENT" || code === "ENOTDIR") && failedPath === fullPath) return null;
800
+ throw error;
801
+ }
802
+ }
803
+ async function countUntrackedLines(fullPath, stat) {
804
+ if (stat.size > 2 * 1024 * 1024) return 0;
805
+ let lines = 0;
806
+ let probeBytes = 8e3;
807
+ let lastByte = 10;
808
+ for await (const chunk of createReadStream(fullPath)) {
809
+ if (probeBytes > 0) {
810
+ const probe = chunk.subarray(0, probeBytes);
811
+ if (probe.includes(0)) return 0;
812
+ probeBytes -= probe.length;
813
+ }
814
+ for (let i = 0; i < chunk.length; i++) {
815
+ if (chunk[i] === 10) lines++;
816
+ }
817
+ lastByte = chunk[chunk.length - 1];
818
+ }
819
+ return lines + Number(lastByte !== 10);
820
+ }
821
+ async function untrackedStat(repo, p, reverse) {
822
+ const lines = await withUntrackedFile(repo, p, countUntrackedLines, () => 1);
823
+ return lines === null ? null : fileStat(p, "A", reverse ? 0 : lines, reverse ? lines : 0);
824
+ }
825
+ async function readChangedFiles(repo, args, baseRef, targetRef) {
826
+ const [tracked, untracked] = await Promise.all([files(repo, args), untrackedPaths(repo, baseRef, targetRef)]);
827
+ const added = (await mapLimit(untracked, 6, (p) => untrackedStat(repo, p, baseRef === "__working__"))).filter((f) => f !== null);
828
+ const byPath = new Map([...tracked, ...added].map((f) => [f.path, f]));
829
+ return { changedFiles: [...byPath.values()], untracked: added.map((f) => f.path) };
830
+ }
831
+ function tryResolveDiffCacheKey(repo, ref) {
832
+ const resolved = ref === "__working__" ? resolveRefToSha(repo, ref) : git(repo, "rev-parse", "--verify", "--quiet", ref);
833
+ return resolved.catch(() => null);
834
+ }
835
+ async function branchFileStats(repo, baseRef, targetRef) {
836
+ validRef(baseRef);
837
+ validRef(targetRef);
838
+ const [baseKey, targetKey] = await Promise.all([tryResolveDiffCacheKey(repo, baseRef), tryResolveDiffCacheKey(repo, targetRef)]);
839
+ const key = baseKey && targetKey ? `${repoHash(repo)}\0${baseKey}\0${targetKey}` : null;
840
+ if (key) {
841
+ const hit = changedFilesCache.get(key);
842
+ if (hit) {
843
+ changedFilesCache.delete(key);
844
+ changedFilesCache.set(key, hit);
845
+ return hit;
846
+ }
847
+ }
848
+ const base = key && baseRef !== "__working__" ? baseKey : baseRef;
849
+ const target = key && targetRef !== "__working__" ? targetKey : targetRef;
850
+ const stats = await readBranchDiff(repo, base, target, (args) => readChangedFiles(repo, args, baseRef, targetRef));
851
+ if (key) {
852
+ changedFilesCache.set(key, stats);
853
+ if (changedFilesCache.size > 64) changedFilesCache.delete(changedFilesCache.keys().next().value);
854
+ }
855
+ return stats;
856
+ }
857
+ async function getBranchChangedFiles(repo, baseRef, targetRef) {
858
+ if (baseRef === "__working__" && targetRef === baseRef) return [];
859
+ return (await branchFileStats(repo, baseRef, targetRef)).changedFiles.map((file) => ({ ...file }));
860
+ }
861
+ async function mapLimit(items, limit, fn) {
862
+ const out = new Array(items.length);
863
+ let idx = 0;
864
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
865
+ while (idx < items.length) {
866
+ const cur = idx++;
867
+ out[cur] = await fn(items[cur]);
868
+ }
869
+ });
870
+ await Promise.all(workers);
871
+ return out;
872
+ }
873
+ var exec3, repoHash, workingDigests, GitRefNotFoundError, filePatchLimit, fullPatchLimit, changedFilesCache;
874
+ var init_tree = __esm({
875
+ "server/git/tree.ts"() {
876
+ "use strict";
877
+ init_commitGraph();
878
+ init_fileClassifier();
879
+ init_packageManifest();
880
+ exec3 = promisify3(execFile3);
881
+ repoHash = (repo) => createHash2("sha1").update(repo).digest("hex").slice(0, 12);
882
+ workingDigests = /* @__PURE__ */ new Map();
883
+ GitRefNotFoundError = class extends Error {
884
+ };
885
+ filePatchLimit = 512 * 1024;
886
+ fullPatchLimit = 60 * 1024;
887
+ changedFilesCache = /* @__PURE__ */ new Map();
888
+ }
889
+ });
890
+
891
+ // server/store/configStore.ts
892
+ import { homedir } from "os";
893
+ import path4 from "path";
894
+ import { promises as fs3 } from "fs";
895
+ import { randomUUID } from "crypto";
896
+ var dataHome;
897
+ var init_configStore = __esm({
898
+ "server/store/configStore.ts"() {
899
+ "use strict";
900
+ init_capture();
901
+ init_sessionBinding();
902
+ init_input();
903
+ init_tree();
904
+ dataHome = () => process.env.BRANCH_LENS_HOME || path4.join(homedir(), ".branch-lens");
905
+ }
906
+ });
907
+
908
+ // server/http/errors.ts
909
+ var HttpError;
910
+ var init_errors = __esm({
911
+ "server/http/errors.ts"() {
912
+ "use strict";
913
+ HttpError = class extends Error {
914
+ status;
915
+ details;
916
+ constructor(status, message, details) {
917
+ super(message);
918
+ this.name = "HttpError";
919
+ this.status = status;
920
+ this.details = details;
921
+ }
922
+ };
923
+ }
924
+ });
925
+
926
+ // server/agent/prompts/loader.ts
927
+ import { promises as fs4 } from "fs";
928
+ import path5 from "path";
929
+ import { fileURLToPath } from "url";
930
+ async function resolvePromptsDir() {
931
+ const moduleDir = path5.dirname(fileURLToPath(import.meta.url));
932
+ const override = process.env.BRANCH_LENS_PROMPTS_DIR;
933
+ const { resourcesPath } = process;
934
+ const candidates = [
935
+ ...override ? [path5.resolve(override)] : [],
936
+ ...resourcesPath ? [path5.join(resourcesPath, "prompts")] : [],
937
+ moduleDir,
938
+ path5.resolve(moduleDir, "prompts"),
939
+ path5.resolve(moduleDir, "../server/agent/prompts"),
940
+ path5.resolve(process.cwd(), "server/agent/prompts")
941
+ ];
942
+ for (const dir of candidates) {
943
+ try {
944
+ await fs4.access(path5.join(dir, "context.md"));
945
+ return dir;
946
+ } catch {
947
+ }
948
+ }
949
+ throw new Error("\u627E\u4E0D\u5230\u63D0\u793A\u8BCD\u6A21\u677F\u76EE\u5F55 server/agent/prompts");
950
+ }
951
+ async function getPromptFilePath(filename) {
952
+ const dir = await resolvePromptsDir();
953
+ return path5.join(dir, filename);
954
+ }
955
+ async function loadPromptTemplate(filename) {
956
+ const filePath = await getPromptFilePath(filename);
957
+ return fs4.readFile(filePath, "utf8");
958
+ }
959
+ function lookupPath(scope, expr) {
960
+ if (expr in scope) {
961
+ return scope[expr];
962
+ }
963
+ const parts = expr.split(".");
964
+ let current = scope;
965
+ for (const part of parts) {
966
+ if (current === null || current === void 0 || typeof current !== "object") {
967
+ return void 0;
968
+ }
969
+ current = current[part];
970
+ }
971
+ return current;
972
+ }
973
+ function isTruthy(val) {
974
+ if (Array.isArray(val))
975
+ return val.length > 0;
976
+ return Boolean(val);
977
+ }
978
+ function findMatchingClose(template, startIndex, tag) {
979
+ const openToken = `{{#${tag} `;
980
+ const closeToken = `{{/${tag}}}`;
981
+ const elseToken = "{{else}}";
982
+ let depth = 1;
983
+ let cursor = startIndex;
984
+ let elseIndex = -1;
985
+ while (cursor < template.length) {
986
+ const nextOpen = template.indexOf(openToken, cursor);
987
+ const nextClose = template.indexOf(closeToken, cursor);
988
+ const nextElse = tag === "if" && depth === 1 ? template.indexOf(elseToken, cursor) : -1;
989
+ if (nextClose === -1) {
990
+ throw new Error(`\u6A21\u677F\u7F3A\u5C11\u95ED\u5408\u6807\u7B7E ${closeToken}`);
991
+ }
992
+ const earliest = Math.min(
993
+ nextOpen === -1 ? Infinity : nextOpen,
994
+ nextClose,
995
+ nextElse === -1 ? Infinity : nextElse
996
+ );
997
+ if (earliest === nextElse) {
998
+ if (elseIndex === -1)
999
+ elseIndex = nextElse;
1000
+ cursor = nextElse + elseToken.length;
1001
+ } else if (earliest === nextOpen) {
1002
+ depth++;
1003
+ cursor = nextOpen + openToken.length;
1004
+ } else {
1005
+ depth--;
1006
+ if (depth === 0) {
1007
+ return { closeStart: nextClose, closeEnd: nextClose + closeToken.length, elseIndex };
1008
+ }
1009
+ cursor = nextClose + closeToken.length;
1010
+ }
1011
+ }
1012
+ throw new Error(`\u6A21\u677F\u7F3A\u5C11\u95ED\u5408\u6807\u7B7E ${closeToken}`);
1013
+ }
1014
+ function renderTemplate(template, scope) {
1015
+ let out = "";
1016
+ let cursor = 0;
1017
+ while (cursor < template.length) {
1018
+ const openIdx = template.indexOf("{{", cursor);
1019
+ if (openIdx === -1) {
1020
+ out += template.slice(cursor);
1021
+ break;
1022
+ }
1023
+ out += template.slice(cursor, openIdx);
1024
+ const closeIdx = template.indexOf("}}", openIdx + 2);
1025
+ if (closeIdx === -1) {
1026
+ out += template.slice(openIdx);
1027
+ break;
1028
+ }
1029
+ const tagBody = template.slice(openIdx + 2, closeIdx).trim();
1030
+ if (tagBody.startsWith("#each ")) {
1031
+ const key = tagBody.slice("#each ".length).trim();
1032
+ const match = findMatchingClose(template, closeIdx + 2, "each");
1033
+ const body = template.slice(closeIdx + 2, match.closeStart);
1034
+ const items = lookupPath(scope, key);
1035
+ if (Array.isArray(items)) {
1036
+ items.forEach((item, idx) => {
1037
+ const childScope = {
1038
+ ...scope,
1039
+ ...item && typeof item === "object" ? item : { this: item },
1040
+ "@index": idx + 1
1041
+ };
1042
+ out += renderTemplate(body, childScope);
1043
+ });
1044
+ }
1045
+ cursor = match.closeEnd;
1046
+ } else if (tagBody.startsWith("#if ")) {
1047
+ const key = tagBody.slice("#if ".length).trim();
1048
+ const match = findMatchingClose(template, closeIdx + 2, "if");
1049
+ const truthy = isTruthy(lookupPath(scope, key));
1050
+ if (match.elseIndex !== -1) {
1051
+ const thenPart = template.slice(closeIdx + 2, match.elseIndex);
1052
+ const elsePart = template.slice(match.elseIndex + "{{else}}".length, match.closeStart);
1053
+ out += renderTemplate(truthy ? thenPart : elsePart, scope);
1054
+ } else if (truthy) {
1055
+ const thenPart = template.slice(closeIdx + 2, match.closeStart);
1056
+ out += renderTemplate(thenPart, scope);
1057
+ }
1058
+ cursor = match.closeEnd;
1059
+ } else {
1060
+ const val = lookupPath(scope, tagBody);
1061
+ if (val !== void 0 && val !== null) {
1062
+ out += String(val);
1063
+ }
1064
+ cursor = closeIdx + 2;
1065
+ }
1066
+ }
1067
+ return out;
1068
+ }
1069
+ var init_loader = __esm({
1070
+ "server/agent/prompts/loader.ts"() {
1071
+ "use strict";
1072
+ }
1073
+ });
1074
+
1075
+ // server/agent/pickedElement.ts
1076
+ import { promises as fs5 } from "fs";
1077
+ import path6 from "path";
1078
+ async function resolvePickedSources(elements, root) {
1079
+ if (!elements.some((el) => el.source)) return elements;
1080
+ const realRoot = root && await fs5.realpath(root).catch(() => void 0);
1081
+ return Promise.all(elements.map(async (element) => {
1082
+ if (!element.source) return element;
1083
+ if (realRoot) {
1084
+ const file = await fs5.realpath(path6.resolve(realRoot, element.source.file)).catch(() => void 0);
1085
+ if (file) {
1086
+ const rel = path6.relative(realRoot, file);
1087
+ if (rel && rel !== ".." && !rel.startsWith(".." + path6.sep) && !path6.isAbsolute(rel)) return element;
1088
+ }
1089
+ }
1090
+ const { source, ...rest } = element;
1091
+ return rest;
1092
+ }));
1093
+ }
1094
+ var PICKED_ELEMENT_STYLE_WHITELIST, STYLE_WHITELIST_SET;
1095
+ var init_pickedElement = __esm({
1096
+ "server/agent/pickedElement.ts"() {
1097
+ "use strict";
1098
+ PICKED_ELEMENT_STYLE_WHITELIST = [
1099
+ "display",
1100
+ "position",
1101
+ "width",
1102
+ "height",
1103
+ "margin",
1104
+ "padding",
1105
+ "font-size",
1106
+ "font-weight",
1107
+ "line-height",
1108
+ "color",
1109
+ "background-color",
1110
+ "background",
1111
+ "border-radius",
1112
+ "flex-direction",
1113
+ "justify-content",
1114
+ "align-items",
1115
+ "gap",
1116
+ "grid-template-columns",
1117
+ "grid-template-rows",
1118
+ "z-index"
1119
+ ];
1120
+ STYLE_WHITELIST_SET = new Set(PICKED_ELEMENT_STYLE_WHITELIST);
1121
+ }
1122
+ });
1123
+
1124
+ // server/agent/contextBundle.ts
1125
+ var contextBundle_exports = {};
1126
+ __export(contextBundle_exports, {
1127
+ computeCropRect: () => computeCropRect,
1128
+ cropRegionsPngSync: () => cropRegionsPngSync,
1129
+ generateContextBundle: () => generateContextBundle
1130
+ });
1131
+ import { promises as fs6 } from "fs";
1132
+ import path7 from "path";
1133
+ import { PNG as PNG2 } from "pngjs";
1134
+ function computeCropRect(box, imgWidth, imgHeight) {
1135
+ if (!Number.isFinite(box.x) || !Number.isFinite(box.y) || !Number.isFinite(box.width) || !Number.isFinite(box.height) || box.width <= 0 || box.height <= 0 || imgWidth <= 0 || imgHeight <= 0) {
1136
+ return null;
1137
+ }
1138
+ const left = Math.max(0, Math.floor(box.x));
1139
+ const top = Math.max(0, Math.floor(box.y));
1140
+ const right = Math.min(imgWidth, Math.ceil(box.x + box.width));
1141
+ const bottom = Math.min(imgHeight, Math.ceil(box.y + box.height));
1142
+ const width = right - left;
1143
+ const height = bottom - top;
1144
+ if (width <= 0 || height <= 0) {
1145
+ return null;
1146
+ }
1147
+ return { x: left, y: top, width, height };
1148
+ }
1149
+ function cropRegionsPngSync(imgBuf, regions) {
1150
+ const source = PNG2.sync.read(imgBuf);
1151
+ const cropped = [];
1152
+ const outOfBoundsIds = [];
1153
+ for (const { id, box } of regions) {
1154
+ const rect = computeCropRect(box, source.width, source.height);
1155
+ if (!rect) {
1156
+ outOfBoundsIds.push(id);
1157
+ continue;
1158
+ }
1159
+ const target = new PNG2({ width: rect.width, height: rect.height });
1160
+ PNG2.bitblt(source, target, rect.x, rect.y, rect.width, rect.height, 0, 0);
1161
+ cropped.push({ id, png: PNG2.sync.write(target) });
1162
+ }
1163
+ return { cropped, outOfBoundsIds };
1164
+ }
1165
+ function formatPickedElements(items) {
1166
+ return items.map((item) => ({
1167
+ ...item,
1168
+ elementRoute: item.route,
1169
+ stylesInline: Object.entries(item.styles).map(([k, v]) => `${k}: ${v}`).join("; ") || "\u65E0"
1170
+ }));
1171
+ }
1172
+ function formatRegions(regions, outOfBoundsIds) {
1173
+ return regions.map((r) => ({
1174
+ ...r,
1175
+ cropNote: outOfBoundsIds.has(r.id) ? "\u533A\u57DF\u8D85\u51FA\u622A\u56FE\u8303\u56F4" : "",
1176
+ relatedFiles: r.relatedFiles && r.relatedFiles.length > 0 ? r.relatedFiles.join("\u3001") : "\u5F85\u5B9A\u4F4D",
1177
+ domHints: r.domHints && r.domHints.length > 0 ? r.domHints.join("\uFF1B") : "\u65E0"
1178
+ }));
1179
+ }
1180
+ async function generateContextBundle(input) {
1181
+ const { task, taskDir } = input;
1182
+ await fs6.mkdir(taskDir, { recursive: true });
1183
+ let regions = task.context.regions ?? [];
1184
+ const screenshots = [];
1185
+ const outOfBoundsIds = /* @__PURE__ */ new Set();
1186
+ let route = task.context.route || "/";
1187
+ let viewport = task.context.viewport || { width: 1280, height: 800 };
1188
+ if (input.annotationCacheKey) {
1189
+ if (!/^[a-f0-9]{16}$/.test(input.annotationCacheKey)) {
1190
+ throw new HttpError(400, "\u65E0\u6548\u7684\u6279\u6CE8\u7F13\u5B58\u6807\u8BC6\uFF08annotationCacheKey\uFF09");
1191
+ }
1192
+ const cacheDir = path7.join(dataHome(), "cache", task.repoHash, input.annotationCacheKey);
1193
+ let annotation;
1194
+ try {
1195
+ annotation = JSON.parse(await fs6.readFile(path7.join(cacheDir, "result.json"), "utf8"));
1196
+ } catch (error) {
1197
+ if (error.code === "ENOENT") {
1198
+ throw new HttpError(404, `\u672A\u627E\u5230\u5BF9\u5E94\u7684\u6279\u6CE8\u7F13\u5B58\uFF08${input.annotationCacheKey}\uFF09`);
1199
+ }
1200
+ throw error;
1201
+ }
1202
+ if (!task.context.route && annotation.route) {
1203
+ route = annotation.route;
1204
+ }
1205
+ if (!task.context.viewport && annotation.viewport) {
1206
+ viewport = annotation.viewport;
1207
+ }
1208
+ if (regions.length === 0 && Array.isArray(annotation.regions)) {
1209
+ regions = annotation.regions;
1210
+ }
1211
+ const rawFilename = annotation.annotatedImageUrl ? path7.basename(annotation.annotatedImageUrl) : "annotated.png";
1212
+ const allowedImage = ["annotated.png", "target.png", "base.png", "diff.png"].includes(rawFilename) ? rawFilename : "annotated.png";
1213
+ const srcImagePath = path7.join(cacheDir, allowedImage);
1214
+ const beforePath = path7.join(taskDir, "before.png");
1215
+ const imgBuf = await fs6.readFile(srcImagePath);
1216
+ await fs6.writeFile(beforePath, imgBuf);
1217
+ screenshots.push(beforePath);
1218
+ if (regions.length > 0) {
1219
+ const boxes = regions.map(({ id, box }) => ({ id, box }));
1220
+ const { cropped, outOfBoundsIds: skipped } = await getCpuPool().run(
1221
+ { kind: "cropRegions", image: imgBuf, regions: boxes },
1222
+ () => cropRegionsPngSync(imgBuf, boxes)
1223
+ );
1224
+ for (const id of skipped) outOfBoundsIds.add(id);
1225
+ for (const { id, png } of cropped) {
1226
+ const regionFile = path7.join(taskDir, `region-${id}.png`);
1227
+ await fs6.writeFile(regionFile, asBuffer(png));
1228
+ screenshots.push(regionFile);
1229
+ }
1230
+ }
1231
+ }
1232
+ const changedFilesList = input.changedFiles.length > 0 ? input.changedFiles.slice(0, 40).map((f) => `- \`${f.path}\`\uFF08+${f.additions} / -${f.deletions}\uFF09`).join("\n") : "\uFF08\u5F53\u524D\u5206\u652F\u76F8\u5BF9\u4E3B\u5E72\u6682\u65E0\u6587\u4EF6\u5DEE\u5F02\uFF09";
1233
+ const pickedElements = await resolvePickedSources(
1234
+ input.pickedElements ?? task.context.pickedElements ?? [],
1235
+ task.worktreePath ?? input.repoPath
1236
+ );
1237
+ const template = await loadPromptTemplate("context.md");
1238
+ const rendered = renderTemplate(template, {
1239
+ taskId: task.id,
1240
+ title: task.title,
1241
+ sourceRef: task.sourceRef,
1242
+ sourceShortSha: input.sourceShortSha,
1243
+ framework: input.framework,
1244
+ packageManager: input.packageManager,
1245
+ devCommand: input.devCommand,
1246
+ instruction: task.instruction,
1247
+ route,
1248
+ viewportWidth: viewport.width,
1249
+ viewportHeight: viewport.height,
1250
+ hasImages: screenshots.length > 0,
1251
+ regions: formatRegions(regions, outOfBoundsIds),
1252
+ pickedElements: formatPickedElements(pickedElements),
1253
+ compareWith: task.context.compareWith || "",
1254
+ changedFilesList,
1255
+ typecheckCommand: input.typecheckCommand
1256
+ });
1257
+ const contextMdPath = path7.join(taskDir, "context.md");
1258
+ await fs6.writeFile(contextMdPath, rendered, "utf8");
1259
+ return {
1260
+ contextMdPath,
1261
+ screenshots,
1262
+ regions,
1263
+ pickedElements,
1264
+ outOfBoundsRegionIds: [...outOfBoundsIds]
1265
+ };
1266
+ }
1267
+ var init_contextBundle = __esm({
1268
+ "server/agent/contextBundle.ts"() {
1269
+ "use strict";
1270
+ init_cpuPool();
1271
+ init_configStore();
1272
+ init_errors();
1273
+ init_loader();
1274
+ init_pickedElement();
1275
+ }
1276
+ });
1277
+
1278
+ // server/core/optionalTs.ts
1279
+ import { createRequire } from "module";
1280
+ import path8 from "path";
1281
+ function findCompiler(requireFrom) {
1282
+ let resolved;
1283
+ try {
1284
+ resolved = requireFrom.resolve("typescript");
1285
+ } catch (error) {
1286
+ const { code } = error;
1287
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") return null;
1288
+ throw error;
1289
+ }
1290
+ const compiler = compilers.get(resolved) ?? requireFrom(resolved);
1291
+ compilers.set(resolved, compiler);
1292
+ return compiler;
1293
+ }
1294
+ function loadOptionalTypeScript(repoPath) {
1295
+ return findCompiler(runtimeRequire) ?? (repoPath ? findCompiler(createRequire(path8.resolve(repoPath, "package.json"))) : null);
1296
+ }
1297
+ var runtimeRequire, compilers;
1298
+ var init_optionalTs = __esm({
1299
+ "server/core/optionalTs.ts"() {
1300
+ "use strict";
1301
+ runtimeRequire = createRequire(import.meta.url);
1302
+ compilers = /* @__PURE__ */ new Map();
1303
+ }
1304
+ });
1305
+
1306
+ // server/git/importGraph.ts
1307
+ import { execFile as execFile4 } from "child_process";
1308
+ import { promises as fs7 } from "fs";
1309
+ import path9 from "path";
1310
+ function isImportSource(file) {
1311
+ return extensions.includes(path9.posix.extname(file)) && !testFile.test(file) && !ignoredDir.test(file);
1312
+ }
1313
+ function needsText(file) {
1314
+ return !ignoredDir.test(file) && (isImportSource(file) || /^(ts|js)config\.json$/.test(file) || /^(?:(?:web|client|frontend|(?:apps|packages)\/[^/]+)\/)?package\.json$/.test(file) || sampleFile.test(file) && /\.(json|[cm]?js|ts)$/.test(file) && !/\.(test|spec)\./.test(file));
1315
+ }
1316
+ async function workingFiles(repo, dir = "") {
1317
+ const result = [];
1318
+ for (const entry of await fs7.readdir(path9.join(repo, dir), { withFileTypes: true })) {
1319
+ const file = path9.posix.join(dir, entry.name);
1320
+ if (entry.isDirectory() && !ignoredDir.test(file)) result.push(...await workingFiles(repo, file));
1321
+ else if (entry.isFile()) result.push(file);
1322
+ }
1323
+ return result;
1324
+ }
1325
+ async function readBlobs(repo, blobs, texts) {
1326
+ const buffer = await new Promise((resolve, reject) => {
1327
+ const child = execFile4(
1328
+ "git",
1329
+ ["-C", repo, "cat-file", "--batch"],
1330
+ { encoding: "buffer", maxBuffer: 128 * 1024 * 1024 },
1331
+ (error, stdout) => error ? reject(error) : resolve(stdout)
1332
+ );
1333
+ child.stdin.end(blobs.map(([, oid]) => oid + "\n").join(""));
1334
+ });
1335
+ let offset = 0;
1336
+ for (const [file] of blobs) {
1337
+ const newline = buffer.indexOf(10, offset);
1338
+ const size = Number(buffer.toString("ascii", offset, newline).split(" ")[2]);
1339
+ const end = newline + 1 + size;
1340
+ texts.set(file, buffer.toString("utf8", newline + 1, end));
1341
+ offset = end + 1;
1342
+ }
1343
+ }
1344
+ async function readRepoSources(repo, ref = "__working__") {
1345
+ const text = /* @__PURE__ */ new Map();
1346
+ if (ref === "__working__") {
1347
+ const files3 = new Set(await workingFiles(repo));
1348
+ const wanted = [...files3].filter(needsText);
1349
+ for (let i = 0; i < wanted.length; i += 64) {
1350
+ await Promise.all(wanted.slice(i, i + 64).map(async (file) => {
1351
+ text.set(file, await fs7.readFile(path9.join(repo, file), "utf8"));
1352
+ }));
1353
+ }
1354
+ return { files: files3, text };
1355
+ }
1356
+ const sha = await resolveRefToSha(repo, ref);
1357
+ const tree = await git(repo, "ls-tree", "-rz", sha);
1358
+ const files2 = /* @__PURE__ */ new Set();
1359
+ const blobs = [];
1360
+ for (const record of tree.split("\0")) {
1361
+ if (!record.startsWith("100")) continue;
1362
+ const tab = record.indexOf(" ");
1363
+ const file = record.slice(tab + 1);
1364
+ files2.add(file);
1365
+ if (needsText(file)) blobs.push([file, record.slice(0, tab).split(" ")[2]]);
1366
+ }
1367
+ for (let i = 0; i < blobs.length; i += 128) await readBlobs(repo, blobs.slice(i, i + 128), text);
1368
+ return { files: files2, text };
1369
+ }
1370
+ function importResolver(repo, sources, compiler) {
1371
+ const config = ["tsconfig.json", "jsconfig.json"].find((file) => sources.text.has(file));
1372
+ const parsed = config && compiler?.parseConfigFileTextToJson(config, sources.text.get(config));
1373
+ if (parsed && parsed.error) throw new Error(`\u65E0\u6CD5\u89E3\u6790 ${config} \u4E2D\u7684\u7F16\u8BD1\u5668\u914D\u7F6E`);
1374
+ const options = parsed && parsed.config?.compilerOptions || {};
1375
+ const base = path9.relative(repo, path9.resolve(repo, options.baseUrl ?? ".")).split(path9.sep).join("/");
1376
+ const aliases = Object.entries(options.paths ?? {}).sort(([a], [b]) => b.split("*")[0].length - a.split("*")[0].length);
1377
+ function resolveFile(candidate) {
1378
+ const bare = candidate.replace(/\.m?jsx?$/, "");
1379
+ const partial = path9.posix.join(path9.posix.dirname(candidate), "_" + path9.posix.basename(candidate));
1380
+ return [
1381
+ candidate,
1382
+ ...extensions.map((ext) => bare + ext),
1383
+ ...extensions.map((ext) => path9.posix.join(candidate, "index" + ext)),
1384
+ partial,
1385
+ partial + ".scss"
1386
+ ].find((file) => sources.text.has(file));
1387
+ }
1388
+ return (importer, specifier, style = false) => {
1389
+ const name = specifier.split(/[?#]/, 1)[0];
1390
+ if (name.startsWith(".")) return resolveFile(path9.posix.join(path9.posix.dirname(importer), name));
1391
+ if (name.startsWith("/")) return resolveFile(name.slice(1));
1392
+ if (style) {
1393
+ const relative = resolveFile(path9.posix.join(path9.posix.dirname(importer), name));
1394
+ if (relative) return relative;
1395
+ }
1396
+ for (const [alias, targets] of aliases) {
1397
+ const [prefix, suffix] = alias.split("*");
1398
+ const exact = suffix === void 0;
1399
+ if (exact ? name !== alias : !name.startsWith(prefix) || !name.endsWith(suffix)) continue;
1400
+ const part = exact ? "" : name.slice(prefix.length, name.length - suffix.length);
1401
+ for (const target of targets) {
1402
+ const resolved = resolveFile(path9.posix.join(base, target.replace("*", part)));
1403
+ if (resolved) return resolved;
1404
+ }
1405
+ }
1406
+ if (options.baseUrl !== void 0) return resolveFile(path9.posix.join(base, name));
1407
+ };
1408
+ }
1409
+ function styleImports(source) {
1410
+ const refs = [];
1411
+ for (const [, clause] of source.replace(/\/\*[\s\S]*?\*\//g, "").matchAll(/@(?:import|use)\s+([^;{}]+)/gi)) {
1412
+ const paths = /(?:^|,)\s*(?:\([^)]*\)\s*)?(?:url\(\s*)?(?:"([^"]+)"|'([^']+)'|([^"'\s(),]+)(?=\s*\)))/gi;
1413
+ for (const [, double, single, bare] of clause.matchAll(paths)) refs.push({ name: double ?? single ?? bare, style: true });
1414
+ }
1415
+ return refs;
1416
+ }
1417
+ function moduleImports(source, compiler) {
1418
+ if (compiler) return compiler.preProcessFile(source, true, true).importedFiles.map((file) => ({ name: file.fileName, style: false }));
1419
+ const refs = [];
1420
+ const declarations = /(?<![\w$.])(?:import\s*(?:\(\s*|(?=["']))|(?:import|export)\b\s*(?:type\s+)?(?:(?:[\w$]+\s*,\s*)?(?:\{[^}]*\}|\*(?:\s+as\s+[\w$]+)?)\s*|[\w$]+\s+)from\s*)(["'])([^"'\r\n]+)\1|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*|(["'\x60])(?:\\[\s\S]|(?!\3)[^\\])*\3/g;
1421
+ for (const [, , name] of source.matchAll(declarations)) {
1422
+ if (name) refs.push({ name, style: false });
1423
+ }
1424
+ return refs;
1425
+ }
1426
+ function vueBlocks(source) {
1427
+ return [...source.matchAll(/<(script|style)\b([^>]*?)(?:\/\s*>|>([\s\S]*?)<\/\1\s*>)/gi)];
1428
+ }
1429
+ function imports(file, source, compiler) {
1430
+ if (styleFile.test(file)) return styleImports(source);
1431
+ if (!file.endsWith(".vue")) return moduleImports(source, compiler);
1432
+ return vueBlocks(source).flatMap(([, tag, attrs, body = ""]) => {
1433
+ const src = /\bsrc\s*=\s*["']([^"']+)["']/.exec(attrs)?.[1];
1434
+ return src ? [{ name: src, style: tag === "style" }] : tag === "script" ? moduleImports(body, compiler) : styleImports(body);
1435
+ });
1436
+ }
1437
+ async function buildImportGraph(repo, sources, compiler = loadOptionalTypeScript(repo)) {
1438
+ const tree = sources ?? await readRepoSources(repo);
1439
+ const resolveImport = importResolver(repo, tree, compiler);
1440
+ const reverse = /* @__PURE__ */ new Map();
1441
+ for (const [file, source] of tree.text) {
1442
+ if (!isImportSource(file)) continue;
1443
+ for (const { name, style } of imports(file, source, compiler)) {
1444
+ const dep = resolveImport(file, name, style);
1445
+ if (!dep) continue;
1446
+ if (!reverse.has(dep)) reverse.set(dep, /* @__PURE__ */ new Set());
1447
+ reverse.get(dep).add(file);
1448
+ }
1449
+ }
1450
+ return { reverse, resolveImport };
1451
+ }
1452
+ function traceAffectedEntries(graph, changedFiles, maxDepth = 8) {
1453
+ const impacts = /* @__PURE__ */ new Map();
1454
+ for (const changed of new Set(changedFiles)) {
1455
+ const queue = [{ file: changed, depth: 0 }];
1456
+ const seen = /* @__PURE__ */ new Set([changed]);
1457
+ for (let i = 0; i < queue.length; i++) {
1458
+ const { file, depth } = queue[i];
1459
+ const impact = impacts.get(file) ?? { depth, changedFiles: [] };
1460
+ impact.depth = Math.min(impact.depth, depth);
1461
+ impact.changedFiles.push(changed);
1462
+ impacts.set(file, impact);
1463
+ if (depth === maxDepth) continue;
1464
+ for (const upstream of graph.reverse.get(file) ?? []) {
1465
+ if (seen.has(upstream)) continue;
1466
+ seen.add(upstream);
1467
+ queue.push({ file: upstream, depth: depth + 1 });
1468
+ }
1469
+ }
1470
+ }
1471
+ return impacts;
1472
+ }
1473
+ async function inferSampleParams(repo, paramNames, sources) {
1474
+ const missing = new Set(paramNames);
1475
+ const params = Object.fromEntries([...missing].map((name) => [name, "1"]));
1476
+ if (!missing.size) return params;
1477
+ const files2 = sources ? [...sources.text.keys()] : (await workingFiles(repo)).filter(needsText);
1478
+ for (const file of files2.filter((file2) => sampleFile.test(file2)).sort()) {
1479
+ const source = sources ? sources.text.get(file) : await fs7.readFile(path9.join(repo, file), "utf8");
1480
+ const fields = source.matchAll(/(?:["']([\w-]+)["']|\b(\w+))\s*:\s*(?:["']([^"'\r\n]+)["']|(\d+)\b)/g);
1481
+ for (const [, quoted, bare, literal, number] of fields) {
1482
+ const name = quoted ?? bare;
1483
+ if (missing.delete(name)) params[name] = literal ?? number;
1484
+ }
1485
+ if (!missing.size) break;
1486
+ }
1487
+ return params;
1488
+ }
1489
+ var extensions, ignoredDir, testFile, styleFile, sampleFile;
1490
+ var init_importGraph = __esm({
1491
+ "server/git/importGraph.ts"() {
1492
+ "use strict";
1493
+ init_optionalTs();
1494
+ init_tree();
1495
+ extensions = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".vue", ".css", ".scss", ".less"];
1496
+ ignoredDir = /(?:^|\/)(?:\.[^/]+|node_modules|dist|build|out|output|outputs|coverage|target|vendor|test-results)(?:\/|$)/;
1497
+ testFile = /(?:^|\/)(?:__tests__|tests?|e2e)\/|\.(?:test|spec|d)\.[^/]+$/;
1498
+ styleFile = /\.(?:css|scss|less)$/i;
1499
+ sampleFile = /(?:^|[/.\-_])(?:__)?(?:mocks?|fixtures?|seeds?|samples?)(?:__|data)?(?:[/.\-_]|$)/i;
1500
+ }
1501
+ });
1502
+
1503
+ // server/git/routeFinder.ts
1504
+ var routeFinder_exports = {};
1505
+ __export(routeFinder_exports, {
1506
+ analyzeStaticRoutes: () => analyzeStaticRoutes,
1507
+ discoverCompareTargets: () => discoverCompareTargets
1508
+ });
1509
+ import path10 from "path";
1510
+ import { promises as fs8 } from "fs";
1511
+ function inferRouteLabel(route, componentName) {
1512
+ const hay = `${route} ${componentName}`;
1513
+ for (const [re, label] of ROUTE_LABEL_HINTS) {
1514
+ if (re.test(hay)) return label;
1515
+ }
1516
+ if (route === "/" || route === "/index.html") return "\u9ED8\u8BA4\u9996\u9875";
1517
+ return componentName || route;
1518
+ }
1519
+ function tokenize(str) {
1520
+ return str.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).map((t) => t.length > 4 && t.endsWith("s") ? t.slice(0, -1) : t).filter((t) => t.length >= 3 && !["src", "page", "component", "index", "tsx", "jsx", "vue", "css", "scss", "test", "mjs", "spec", "dist", "app", "web", "admin", "design", "review", "html", "asset"].includes(t));
1521
+ }
1522
+ function joinRoute(base, child) {
1523
+ return (child.startsWith("/") ? child : path10.posix.join(base, child)) || "/";
1524
+ }
1525
+ function parseRoutes(ts, file, source, resolve) {
1526
+ if (!/(?:<\s*(?:[\w$]+\.)*(?:Route|HashRouter)\b|\b(?:createBrowserRouter|createHashRouter|createMemoryRouter|createRouter|useRoutes|pathname)\b|\bvue-router\b|['"]?\bpath\b['"]?\s*(?:\/\*[\s\S]*?\*\/\s*)*:|\b\w*routes\s*[:=]|\bexport\s+default\s*\[)/i.test(source)) return [];
1527
+ function unwrap(node) {
1528
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isTypeAssertionExpression(node)) {
1529
+ node = node.expression;
1530
+ }
1531
+ return node;
1532
+ }
1533
+ function findNode(node, predicate) {
1534
+ return predicate(node) ? node : ts.forEachChild(node, (child) => findNode(child, predicate));
1535
+ }
1536
+ const isTag = (node) => ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node);
1537
+ const tagName = (tag) => tag.tagName.getText().split(".").pop();
1538
+ function attribute(tag, name) {
1539
+ const attr = tag.attributes.properties.find((p) => ts.isJsxAttribute(p) && p.name.getText() === name);
1540
+ const init = attr?.initializer;
1541
+ return init && ts.isJsxExpression(init) ? init.expression : init ?? attr;
1542
+ }
1543
+ function property(object, key) {
1544
+ const prop = object.properties.find((p) => p.name && (ts.isStringLiteral(p.name) ? p.name.text : p.name.getText()) === key);
1545
+ if (prop && ts.isPropertyAssignment(prop)) return prop.initializer;
1546
+ if (prop && ts.isShorthandPropertyAssignment(prop)) return prop.name;
1547
+ }
1548
+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, file.endsWith(".ts") ? ts.ScriptKind.TS : ts.ScriptKind.TSX);
1549
+ const modules = /* @__PURE__ */ new Map();
1550
+ const bindings = /* @__PURE__ */ new Map();
1551
+ const calls = [];
1552
+ const arrays = [];
1553
+ let vueRouter = false;
1554
+ function collect(node) {
1555
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
1556
+ const spec = node.moduleSpecifier.text;
1557
+ if (spec === "vue-router") vueRouter = true;
1558
+ const clause = node.importClause;
1559
+ if (clause?.name) modules.set(clause.name.text, spec);
1560
+ const named = clause?.namedBindings;
1561
+ if (named && ts.isNamedImports(named)) for (const item of named.elements) modules.set(item.name.text, spec);
1562
+ if (named && ts.isNamespaceImport(named)) modules.set(named.name.text, spec);
1563
+ }
1564
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
1565
+ bindings.set(node.name.text, node.initializer);
1566
+ if (/routes$/i.test(node.name.text)) arrays.push(node.initializer);
1567
+ }
1568
+ if (ts.isExportAssignment(node)) arrays.push(node.expression);
1569
+ if (ts.isCallExpression(node) && routerCall.test(node.expression.getText())) calls.push(node);
1570
+ ts.forEachChild(node, collect);
1571
+ }
1572
+ collect(ast);
1573
+ function component(node) {
1574
+ if (!node) return { sourceFile: file };
1575
+ const tag = findNode(node, (n) => isTag(n) && /^[A-Z]/.test(tagName(n)) && !guard.test(tagName(n)) && !/^(Suspense|Fragment|Route|Routes)$/.test(tagName(n)));
1576
+ const ident = tag?.tagName ?? (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? node : void 0);
1577
+ const name = ident?.getText();
1578
+ const binding = name && bindings.get(name);
1579
+ const dynamic = findNode(binding || node, (n) => ts.isCallExpression(n) && n.expression.kind === ts.SyntaxKind.ImportKeyword);
1580
+ const arg = dynamic?.arguments[0];
1581
+ const spec = name && modules.get(name.split(".")[0]) || (arg && ts.isStringLiteralLike(arg) ? arg.text : void 0);
1582
+ const sourceFile = spec && resolve(file, spec) || file;
1583
+ return { componentName: name || spec && path10.posix.parse(spec).name, sourceFile };
1584
+ }
1585
+ const hasGuard = (node) => !!node && !!findNode(node, (n) => isTag(n) && guard.test(tagName(n)) || ts.isIdentifier(n) && guard.test(n.text));
1586
+ const pages = /* @__PURE__ */ new Map();
1587
+ const indexRoutes = /* @__PURE__ */ new Set();
1588
+ function add(route, node, protectedRoute, framework, index = false, hashRouter = false) {
1589
+ if (indexRoutes.has(route)) return;
1590
+ const entry = component(node);
1591
+ if (route.endsWith("/*") && (!node || entry.componentName === "Navigate" || entry.componentName === "Redirect")) return;
1592
+ if (index) indexRoutes.add(route);
1593
+ pages.set(route, { route, framework, noLogin: !protectedRoute, declarationFile: file, hashRouter, ...entry });
1594
+ }
1595
+ function visit(node, base, protectedRoute, hashRouter) {
1596
+ const tag = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : void 0;
1597
+ if (tag) {
1598
+ hashRouter ||= tagName(tag) === "HashRouter";
1599
+ if (guard.test(tagName(tag))) protectedRoute = true;
1600
+ if (tagName(tag) === "Route") {
1601
+ const route = attribute(tag, "path");
1602
+ const element = attribute(tag, "element") ?? attribute(tag, "Component");
1603
+ protectedRoute ||= hasGuard(element);
1604
+ const index = !!attribute(tag, "index");
1605
+ if (route && ts.isStringLiteralLike(route)) base = joinRoute(base, route.text);
1606
+ if (route && ts.isStringLiteralLike(route) || index) add(base, element, protectedRoute, "react-router", index, hashRouter);
1607
+ }
1608
+ }
1609
+ if (ts.isBinaryExpression(node) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.EqualsEqualsToken].includes(node.operatorToken.kind)) {
1610
+ const [literal, other] = ts.isStringLiteralLike(node.right) ? [node.right, node.left] : [node.left, node.right];
1611
+ if (ts.isStringLiteralLike(literal) && literal.text.startsWith("/") && /\bpathname\b/.test(other.getText())) {
1612
+ let parent = node;
1613
+ while (parent.parent && ts.isExpression(parent.parent) && !ts.isConditionalExpression(parent.parent)) {
1614
+ if (ts.isBinaryExpression(parent.parent) && parent.parent.left === parent && parent.parent.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) break;
1615
+ parent = parent.parent;
1616
+ }
1617
+ const branch = parent.parent;
1618
+ const rendered = ts.isIfStatement(branch) ? branch.thenStatement : ts.isConditionalExpression(branch) ? branch.whenTrue : ts.isBinaryExpression(branch) ? branch.right : void 0;
1619
+ if (!pages.has(literal.text)) add(literal.text, rendered, protectedRoute, "custom");
1620
+ }
1621
+ }
1622
+ ts.forEachChild(node, (child) => visit(child, base, protectedRoute, hashRouter));
1623
+ }
1624
+ visit(ast, "/", false, false);
1625
+ const visitedArrays = /* @__PURE__ */ new Set();
1626
+ function parseArray(expr, base, protectedRoute, vue, hashRouter = false, ancestors = /* @__PURE__ */ new Set()) {
1627
+ if (!expr) return;
1628
+ const value = unwrap(expr);
1629
+ if (ancestors.has(value)) return;
1630
+ const next = new Set(ancestors).add(value);
1631
+ if (ts.isIdentifier(value)) return parseArray(bindings.get(value.text), base, protectedRoute, vue, hashRouter, next);
1632
+ if (!ts.isArrayLiteralExpression(value)) return;
1633
+ visitedArrays.add(value);
1634
+ for (const item of value.elements) {
1635
+ if (ts.isSpreadElement(item)) {
1636
+ parseArray(item.expression, base, protectedRoute, vue, hashRouter, next);
1637
+ continue;
1638
+ }
1639
+ if (!ts.isObjectLiteralExpression(item)) continue;
1640
+ const child = property(item, "path");
1641
+ const index = property(item, "index")?.kind === ts.SyntaxKind.TrueKeyword;
1642
+ const route = child && ts.isStringLiteralLike(child) ? joinRoute(base, child.text) : base;
1643
+ const vueComponent = property(item, "component");
1644
+ const element = vueComponent ?? property(item, "Component") ?? property(item, "element") ?? property(item, "lazy");
1645
+ const meta = property(item, "meta");
1646
+ const locked = protectedRoute || hasGuard(element) || !!(meta && ts.isObjectLiteralExpression(meta) && property(meta, "requiresAuth")?.kind === ts.SyntaxKind.TrueKeyword);
1647
+ if (child && ts.isStringLiteralLike(child) || index) add(route, element, locked, vue || vueComponent ? "vue-router" : "react-router", index, hashRouter);
1648
+ parseArray(property(item, "children"), route, locked, vue || !!vueComponent, hashRouter, next);
1649
+ }
1650
+ }
1651
+ for (const call of calls) {
1652
+ const arg = call.arguments[0];
1653
+ if (!arg) continue;
1654
+ if (call.expression.getText() === "createRouter" && ts.isObjectLiteralExpression(arg)) {
1655
+ const history = property(arg, "history");
1656
+ parseArray(property(arg, "routes"), "/", false, true, !!history && /\bcreateWebHashHistory\b/.test(history.getText()));
1657
+ } else parseArray(arg, "/", false, vueRouter, call.expression.getText() === "createHashRouter");
1658
+ }
1659
+ for (const expr of arrays) {
1660
+ const value = unwrap(expr);
1661
+ const bound = ts.isIdentifier(value) ? bindings.get(value.text) ?? value : value;
1662
+ if (!visitedArrays.has(unwrap(bound))) parseArray(bound, "/", false, vueRouter);
1663
+ }
1664
+ return [...pages.values()];
1665
+ }
1666
+ function discoverFilePages(sources, explicit, reverse, compiler) {
1667
+ const routes = [];
1668
+ const explicitRoots = new Set(explicit.map((page) => appRoot(page.declarationFile ?? page.sourceFile)));
1669
+ const explicitFiles = new Set(explicit.map((page) => page.sourceFile));
1670
+ const nextRoots = /* @__PURE__ */ new Set();
1671
+ const nuxtRoots = /* @__PURE__ */ new Set();
1672
+ for (const [file, text] of sources.text) {
1673
+ if (/(?:^|\/)next\.config\.|(?:^|\/)app\/(?:.*\/)?page\.[jt]sx?$/.test(file)) nextRoots.add(appRoot(file));
1674
+ if (/(?:^|\/)nuxt\.config\./.test(file)) nuxtRoots.add(appRoot(file));
1675
+ if (compiler && path10.posix.basename(file) === "package.json") {
1676
+ const pkg = compiler.parseConfigFileTextToJson(file, text).config;
1677
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
1678
+ if (deps.next) nextRoots.add(appRoot(file));
1679
+ if (deps.nuxt || deps["vite-plugin-pages"] || deps["unplugin-vue-router"]) nuxtRoots.add(appRoot(file));
1680
+ }
1681
+ }
1682
+ for (const file of sources.text.keys()) {
1683
+ const match = convention.exec(file);
1684
+ if (!match || !isImportSource(file)) continue;
1685
+ const [, root = "", kind, name, ext] = match;
1686
+ if (compiler && kind === "routes") continue;
1687
+ const parts = name.split("/");
1688
+ const leaf = parts.pop();
1689
+ if (kind === "app") {
1690
+ if (leaf !== "page" || ext === "vue" || parts.some((s) => s.startsWith("_") || s.startsWith("@"))) continue;
1691
+ const appDir = file.slice(0, -name.length - ext.length - 1);
1692
+ for (let i = 0; i <= parts.length; i++) {
1693
+ const stem = path10.posix.join(appDir, ...parts.slice(0, i), "layout");
1694
+ for (const ext2 of ["tsx", "jsx", "ts", "js", "mjs"]) {
1695
+ const layout = stem + "." + ext2;
1696
+ if (!sources.files.has(layout)) continue;
1697
+ if (!reverse.has(layout)) reverse.set(layout, /* @__PURE__ */ new Set());
1698
+ reverse.get(layout).add(file);
1699
+ }
1700
+ }
1701
+ } else {
1702
+ if (parts[0] === "api" || ["_app", "_document", "_error"].includes(leaf)) continue;
1703
+ if (ext === "vue" && explicitFiles.has(file) && !nuxtRoots.has(root)) continue;
1704
+ if (ext !== "vue" && explicitRoots.has(root) && !nextRoots.has(root)) continue;
1705
+ if (leaf !== "index") parts.push(leaf);
1706
+ }
1707
+ const segments = parts.filter((p) => !/^\(.*\)$/.test(p)).map((p) => ext === "vue" ? p.replace(/^_(\w+)$/, ":$1") : p);
1708
+ routes.push({
1709
+ route: "/" + segments.join("/"),
1710
+ componentName: segments.at(-1) || "\u9996\u9875",
1711
+ sourceFile: file,
1712
+ noLogin: true,
1713
+ framework: kind === "routes" ? "custom" : ext === "vue" ? "nuxt" : "nextjs"
1714
+ });
1715
+ }
1716
+ return routes;
1717
+ }
1718
+ function staticDirectory(devCommand) {
1719
+ const match = devCommand?.match(/--directory\s+(?:"([^"]+)"|'([^']+)'|(\S+))/);
1720
+ return match ? match.slice(1).find(Boolean) ?? "" : void 0;
1721
+ }
1722
+ async function discoverStaticHtmlRoutes(repo, directory, files2) {
1723
+ const serveRoot = path10.resolve(repo, directory || ".");
1724
+ const prefix = path10.relative(repo, serveRoot).split(path10.sep).join("/");
1725
+ const rooted = prefix ? prefix + "/" : "";
1726
+ let htmlFiles = [...files2].filter((f) => f.startsWith(rooted) && /\.html$/i.test(f)).map((f) => f.slice(rooted.length));
1727
+ const liveDirectory = directory !== void 0 && htmlFiles.length === 0;
1728
+ if (liveDirectory) {
1729
+ htmlFiles = [];
1730
+ async function walk(dir) {
1731
+ for (const entry of await fs8.readdir(path10.join(serveRoot, dir), { withFileTypes: true })) {
1732
+ const rel = path10.posix.join(dir, entry.name);
1733
+ if (staticSkip.test(rel)) continue;
1734
+ if (entry.isDirectory()) await walk(rel);
1735
+ else if (entry.isFile() && /\.html$/i.test(rel)) htmlFiles.push(rel);
1736
+ }
1737
+ }
1738
+ try {
1739
+ await walk("");
1740
+ } catch (error) {
1741
+ if (error.code !== "ENOENT") throw error;
1742
+ }
1743
+ }
1744
+ const pages = htmlFiles.filter((f) => !staticSkip.test(f)).map((rel) => ({
1745
+ route: "/" + rel.replace(/(^|\/)index\.html$/, "$1"),
1746
+ sourceFile: rooted + rel,
1747
+ componentName: path10.posix.basename(rel),
1748
+ framework: "static-html",
1749
+ noLogin: true
1750
+ }));
1751
+ return { pages, liveDirectory };
1752
+ }
1753
+ async function compareFiles(repo, base, target) {
1754
+ const files2 = await getBranchChangedFiles(repo, base, target);
1755
+ if (files2.length || base === "__working__" || target === "__working__") return files2;
1756
+ const parents = await git(repo, "log", "-1", "--format=%P", target, "--");
1757
+ const firstParent = parents.split(" ")[0];
1758
+ return firstParent ? getBranchChangedFiles(repo, firstParent, target) : files2;
1759
+ }
1760
+ function expandRoute(route, configured, inferred) {
1761
+ const paramNames = namesOf(route);
1762
+ if (!paramNames.length) return { resolvedRoute: route, isParameterized: false };
1763
+ const override = Object.hasOwn(configured, route) ? configured[route] : "";
1764
+ const fullPath = /^\/(?!\/)/.test(override) && !/[\\\x00-\x1f\x7f]/.test(override);
1765
+ const values = Object.fromEntries(paramNames.map((name) => [
1766
+ name,
1767
+ !fullPath && paramNames.length === 1 && override || Object.hasOwn(configured, name) && configured[name] || inferred[name] || "1"
1768
+ ]));
1769
+ if (fullPath) {
1770
+ const segments = override.split(/[?#]/, 1)[0].split("/");
1771
+ route.split("/").forEach((segment, i) => {
1772
+ const [name] = namesOf(segment);
1773
+ if (name && segments[i]) values[name] = repeatedParam(segment) ? segments.slice(i).join("/") : segments[i];
1774
+ });
1775
+ }
1776
+ const resolvedRoute = fullPath ? override : route.replace(parameters, (param, colon, bracket, splat) => {
1777
+ const value = values[colon ?? bracket ?? splat];
1778
+ return repeatedParam(param) ? value.split("/").map(encodeURIComponent).join("/") : encodeURIComponent(value);
1779
+ });
1780
+ return { resolvedRoute, isParameterized: true, paramNames, sampleParams: values };
1781
+ }
1782
+ async function analyzeRoutes(repo, targetRef, directory, compiler) {
1783
+ const targetKey = await resolveRefToSha(repo, targetRef).catch(() => null);
1784
+ const staticDirKey = directory === void 0 ? "" : path10.resolve(repo, directory);
1785
+ const compilerMode = compiler === void 0 ? "auto" : compiler === null ? "no-ts" : "ts";
1786
+ const key = targetKey ? `${repoHash(repo)}\0${targetKey}\0${compilerMode}\0${staticDirKey}` : null;
1787
+ if (key) {
1788
+ const hit = staticRouteCache.get(key);
1789
+ if (hit) {
1790
+ staticRouteCache.delete(key);
1791
+ staticRouteCache.set(key, hit);
1792
+ return hit;
1793
+ }
1794
+ }
1795
+ const ref = targetRef === "__working__" ? targetRef : targetKey ?? targetRef;
1796
+ const { pages, reverseEntries, allInferredParams, liveDirectory } = compiler ? await analyzeStaticRoutes(repo, ref, directory, compiler) : await getCpuPool().run(
1797
+ { kind: "analyzeRoutes", repo, ref, directory, useTypeScript: compiler === void 0 },
1798
+ () => analyzeStaticRoutes(repo, ref, directory, compiler)
1799
+ );
1800
+ const result = { pages, graph: { reverse: new Map(reverseEntries.map(([file, importers]) => [file, new Set(importers)])) }, allInferredParams };
1801
+ if (key && !liveDirectory) {
1802
+ staticRouteCache.set(key, result);
1803
+ if (staticRouteCache.size > 16) staticRouteCache.delete(staticRouteCache.keys().next().value);
1804
+ }
1805
+ return result;
1806
+ }
1807
+ async function analyzeStaticRoutes(repo, ref, directory, compiler = loadOptionalTypeScript(repo)) {
1808
+ const sources = await readRepoSources(repo, ref);
1809
+ const graph = await buildImportGraph(repo, sources, compiler);
1810
+ const explicit = [];
1811
+ if (compiler) {
1812
+ for (const [file, text] of sources.text) {
1813
+ if (!sourceRoot.test(file) || !isImportSource(file) || /\.(css|scss|less)$/.test(file)) continue;
1814
+ const code = file.endsWith(".vue") ? vueBlocks(text).filter((m) => m[1] === "script").map((m) => m[3]).join("\n") : text;
1815
+ explicit.push(...parseRoutes(compiler, file, code, graph.resolveImport));
1816
+ }
1817
+ }
1818
+ const filePages = discoverFilePages(sources, explicit, graph.reverse, compiler);
1819
+ const { pages: staticPages, liveDirectory } = await discoverStaticHtmlRoutes(repo, directory, sources.files);
1820
+ const pages = /* @__PURE__ */ new Map();
1821
+ for (const page of [...explicit, ...filePages, ...staticPages]) {
1822
+ const key = appRoot(page.declarationFile ?? page.sourceFile) + "\0" + page.route;
1823
+ if (!pages.has(key)) pages.set(key, page);
1824
+ }
1825
+ const uniquePages = [...pages.values()];
1826
+ const allInferredParams = await inferSampleParams(repo, uniquePages.flatMap((page) => namesOf(page.route)), sources);
1827
+ const reverseEntries = [...graph.reverse].map(([file, importers]) => [file, [...importers]]);
1828
+ return { pages: uniquePages, reverseEntries, allInferredParams, liveDirectory };
1829
+ }
1830
+ async function discoverCompareTargets(repo, baseRef, targetRef, devCommandOrConfig, compiler) {
1831
+ const config = typeof devCommandOrConfig === "string" ? { devCommand: devCommandOrConfig } : devCommandOrConfig ?? {};
1832
+ const [{ pages, graph, allInferredParams }, files2] = await Promise.all([
1833
+ analyzeRoutes(repo, targetRef, staticDirectory(config.devCommand), compiler),
1834
+ compareFiles(repo, baseRef, targetRef)
1835
+ ]);
1836
+ const changeSummary = summarizeFileChanges(files2);
1837
+ const changes = files2.filter((f) => f.category !== "test" && f.category !== "backend" && (isImportSource(f.path) || /\.(json|html|css|m?js|svg)$/i.test(f.path))).map((f) => f.path);
1838
+ const configured = config.routeParams ?? {};
1839
+ const impacts = traceAffectedEntries(graph, changes);
1840
+ const branchTokens = new Set(tokenize(targetRef));
1841
+ const fileTokens = changes.map((file) => ({ file, tokens: new Set(tokenize(file)) }));
1842
+ const allRoutes = pages.map(({ declarationFile, hashRouter, ...page }) => {
1843
+ const { route, sourceFile, componentName = "" } = page;
1844
+ const tokens = tokenize(`${route} ${componentName} ${page.framework === "static-html" ? "" : sourceFile}`);
1845
+ const unique = [...new Set(tokens)];
1846
+ const impact = sourceFile === declarationFile && !changes.includes(sourceFile) ? void 0 : impacts.get(sourceFile);
1847
+ const dir = path10.posix.dirname(sourceFile) + "/";
1848
+ const neighbors = page.framework === "static-html" && route !== "/" && route.endsWith("/") ? changes.filter((f) => f.startsWith(dir)) : [];
1849
+ const hints = fileTokens.filter((f) => unique.some((t) => f.tokens.has(t)));
1850
+ const changedFiles = impact || neighbors.length ? [.../* @__PURE__ */ new Set([...impact?.changedFiles ?? [], ...neighbors])] : hints.map((f) => f.file);
1851
+ const overlap = hints.reduce((max, f) => Math.max(max, unique.filter((t) => f.tokens.has(t)).length), 0);
1852
+ let score = Math.min(36, overlap * 12) + Math.min(24, unique.filter((t) => branchTokens.has(t)).length * 8);
1853
+ if (impact) score += impact.depth === 0 ? 1e3 : 840 - impact.depth * 60;
1854
+ if (neighbors.length) score += Math.min(60, neighbors.length * 6);
1855
+ const expanded = expandRoute(route, configured, allInferredParams);
1856
+ if (hashRouter && !expanded.resolvedRoute.startsWith("/#")) expanded.resolvedRoute = "/#" + expanded.resolvedRoute;
1857
+ if (score && page.noLogin && !expanded.isParameterized) score += /\/design-review\//.test(route) ? 30 : 6;
1858
+ const reason = impact ? impact.depth ? `\u7ECF ${impact.depth} \u5C42\u4F9D\u8D56\u5173\u8054\u6539\u52A8` : "\u9875\u9762\u6E90\u6587\u4EF6\u76F4\u63A5\u6539\u52A8" : neighbors.length ? "\u9875\u9762\u76EE\u5F55\u5185\u6709\u6539\u52A8" : hints.length ? "\u6587\u4EF6\u540D\u4E0E\u9875\u9762\u5339\u914D" : score ? "\u5206\u652F\u540D\u79F0\u4E0E\u9875\u9762\u5339\u914D" : route === "/" ? "\u5E94\u7528\u5165\u53E3\u8DEF\u7531" : "\u5168\u4ED3\u9875\u9762";
1859
+ return {
1860
+ ...page,
1861
+ ...expanded,
1862
+ label: inferRouteLabel(route, componentName),
1863
+ affected: !!impact || !!neighbors.length,
1864
+ changedFiles,
1865
+ dependencyDepth: impact?.depth,
1866
+ score,
1867
+ reason
1868
+ };
1869
+ });
1870
+ allRoutes.sort((a, b) => b.score - a.score || Number(a.isParameterized) - Number(b.isParameterized) || a.route.localeCompare(b.route));
1871
+ const best = allRoutes[0];
1872
+ let recommended = best?.score && changes.length ? best : void 0;
1873
+ if (recommended?.isParameterized && !recommended.noLogin && !configured[recommended.route]) {
1874
+ const sameChanges = new Set(recommended.changedFiles);
1875
+ const pageTokens = new Set(tokenize(recommended.route + " " + recommended.componentName));
1876
+ recommended = allRoutes.find((p) => p.noLogin && !p.isParameterized && p.route.startsWith("/design-review/") && tokenize(p.route).some((t) => pageTokens.has(t)) && p.changedFiles.some((f) => sameChanges.has(f))) ?? recommended;
1877
+ }
1878
+ const recommendedRoute = recommended?.resolvedRoute ?? "/";
1879
+ const targets = allRoutes.filter((p) => p.score || p.isParameterized || p.route === "/").map((p) => ({
1880
+ route: p.resolvedRoute,
1881
+ routeTemplate: p.route,
1882
+ label: p.label,
1883
+ reason: p.reason,
1884
+ noLogin: p.noLogin,
1885
+ isParameterized: p.isParameterized,
1886
+ dependencyDepth: p.dependencyDepth,
1887
+ changedFiles: p.changedFiles,
1888
+ score: p.score
1889
+ }));
1890
+ if (!targets.some((t) => t.route === "/")) targets.push({
1891
+ route: "/",
1892
+ label: "\u9ED8\u8BA4\u9996\u9875",
1893
+ noLogin: true,
1894
+ changedFiles: [],
1895
+ score: 0,
1896
+ reason: !changes.length ? "\u4E24\u7248\u672C\u6682\u65E0\u524D\u7AEF\u6587\u4EF6\u5DEE\u5F02" : "\u8FD4\u56DE\u5E94\u7528\u9ED8\u8BA4\u5165\u53E3"
1897
+ });
1898
+ return { recommendedRoute, targets, allRoutes, changeSummary };
1899
+ }
1900
+ var ROUTE_LABEL_HINTS, guard, routerCall, sourceRoot, convention, appRoot, staticSkip, parameters, namesOf, repeatedParam, staticRouteCache;
1901
+ var init_routeFinder = __esm({
1902
+ "server/git/routeFinder.ts"() {
1903
+ "use strict";
1904
+ init_cpuPool();
1905
+ init_optionalTs();
1906
+ init_tree();
1907
+ init_fileClassifier();
1908
+ init_importGraph();
1909
+ ROUTE_LABEL_HINTS = [
1910
+ [/room[-_]?workspace|room[-_]?detail|\/room/i, "\u623F\u95F4\u6548\u679C\u56FE\u5DE5\u4F5C\u53F0"],
1911
+ [/project[-_]?progress/i, "\u9879\u76EE\u8FDB\u5EA6\u89C6\u56FE"],
1912
+ [/client[-_]?progress[-_]?timeline/i, "\u5BA2\u6237\u8FDB\u5EA6\u65F6\u95F4\u7EBF"],
1913
+ [/client[-_]?progress/i, "\u5BA2\u6237\u8FDB\u5EA6\u9875"],
1914
+ [/client[-_]?project/i, "\u5BA2\u6237\u9879\u76EE\u8BE6\u60C5"],
1915
+ [/client[-_]?intent/i, "\u5BA2\u6237\u610F\u5411\u65B9\u6848"],
1916
+ [/client[-_]?dashboard/i, "\u5BA2\u6237\u9996\u9875"],
1917
+ [/supplier/i, "\u4F9B\u5E94\u5546\u7BA1\u7406"],
1918
+ [/today/i, "\u4ECA\u65E5\u5DE5\u4F5C\u53F0"],
1919
+ [/miniapp/i, "\u5C0F\u7A0B\u5E8F\u7AEF\u9884\u89C8"],
1920
+ [/admin\/users/i, "\u540E\u53F0\u7528\u6237\u7BA1\u7406"],
1921
+ [/admin\/projects/i, "\u540E\u53F0\u9879\u76EE\u7BA1\u7406"],
1922
+ [/admin\/audit/i, "\u540E\u53F0\u5BA1\u8BA1\u65E5\u5FD7"],
1923
+ [/admin/i, "\u7BA1\u7406\u540E\u53F0"],
1924
+ [/material/i, "\u6750\u6599\u5E93"],
1925
+ [/task/i, "\u4EFB\u52A1\u7BA1\u7406"],
1926
+ [/setting/i, "\u7CFB\u7EDF\u8BBE\u7F6E"],
1927
+ [/chat/i, "\u9879\u76EE\u6C9F\u901A"],
1928
+ [/buckle/i, "\u7BB1\u5305\u6263\u4EF6\u76EE\u5F55"],
1929
+ [/zipper/i, "\u62C9\u94FE\u5C55\u5385"],
1930
+ [/wardrobe/i, "\u8863\u67DC\u5C55\u5385"],
1931
+ [/en\.html/i, "\u82F1\u6587\u7248\u5C55\u5385"],
1932
+ [/dashboard/i, "\u603B\u89C8\u5DE5\u4F5C\u53F0"],
1933
+ [/login/i, "\u767B\u5F55\u9875"]
1934
+ ];
1935
+ guard = /^(ProtectedRoute|AdminProtected|RequireAuth|PrivateRoute|AuthGuard)$/;
1936
+ routerCall = /^(createBrowserRouter|createHashRouter|createMemoryRouter|useRoutes|createRouter)$/;
1937
+ sourceRoot = /^(?:src\/|(?:web|client|frontend)\/src\/|(?:apps|packages)\/[^/]+\/src\/|(?:app|pages|routers?)\/|(?:App\.|routes?\b|router))/i;
1938
+ convention = /^(?:(web|client|frontend|(?:apps|packages)\/[^/]+)\/)?(?:src\/)?(app|pages|routes)\/(.+)\.(tsx?|jsx?|mjs|vue)$/;
1939
+ appRoot = (file) => /^(web|client|frontend|(?:apps|packages)\/[^/]+)\//.exec(file)?.[1] ?? "";
1940
+ staticSkip = /(?:^|\/)(?:\.[^/]+|node_modules|assets|outputs?|docs|qa|exports|design-previews|deployments|tmp|tests?|dist|build|coverage)(?:\/|$)/;
1941
+ parameters = /:([\w-]+)(?:\([^)]*\))?[?*+]?|\[\[?(?:\.\.\.)?([\w-]+)\]\]?|(\*)(?=\/|$)/g;
1942
+ namesOf = (route) => [...new Set([...route.matchAll(parameters)].map((m) => m[1] ?? m[2] ?? m[3]))];
1943
+ repeatedParam = (segment) => segment.includes("...") || /[*+]$/.test(segment);
1944
+ staticRouteCache = /* @__PURE__ */ new Map();
1945
+ }
1946
+ });
1947
+
1948
+ // server/workers/cpuWorker.ts
1949
+ init_cpuPool();
1950
+ import { parentPort } from "worker_threads";
1951
+ async function execute(request, transfer) {
1952
+ const move = (bytes) => {
1953
+ const view = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && bytes.buffer instanceof ArrayBuffer ? bytes : new Uint8Array(bytes);
1954
+ transfer.add(view.buffer);
1955
+ return view;
1956
+ };
1957
+ switch (request.kind) {
1958
+ case "diffRegions": {
1959
+ const { diffRegions: diffRegions2 } = await Promise.resolve().then(() => (init_diffRegions(), diffRegions_exports));
1960
+ const base = asBuffer(request.base), target = asBuffer(request.target);
1961
+ const { diffData, diffPng, annotatedPng, basePng, targetPng, ...stats } = diffRegions2(base, target, request.baseDom, request.targetDom);
1962
+ const output = { ...stats, diffData: move(diffData), diffPng: move(diffPng), annotatedPng: move(annotatedPng) };
1963
+ return basePng === base ? { ...output, sameSize: true } : { ...output, sameSize: false, basePng: move(basePng), targetPng: move(targetPng) };
1964
+ }
1965
+ case "cropRegions": {
1966
+ const { cropRegionsPngSync: cropRegionsPngSync2 } = await Promise.resolve().then(() => (init_contextBundle(), contextBundle_exports));
1967
+ const { cropped, outOfBoundsIds } = cropRegionsPngSync2(asBuffer(request.image), request.regions);
1968
+ return { cropped: cropped.map(({ id, png }) => ({ id, png: move(png) })), outOfBoundsIds };
1969
+ }
1970
+ case "analyzeRoutes": {
1971
+ const { analyzeStaticRoutes: analyzeStaticRoutes2 } = await Promise.resolve().then(() => (init_routeFinder(), routeFinder_exports));
1972
+ return analyzeStaticRoutes2(request.repo, request.ref, request.directory, request.useTypeScript ? void 0 : null);
1973
+ }
1974
+ }
1975
+ }
1976
+ if (parentPort) {
1977
+ const port = parentPort;
1978
+ port.on("message", async (request) => {
1979
+ try {
1980
+ const transfer = /* @__PURE__ */ new Set();
1981
+ const result = await execute(request, transfer);
1982
+ port.postMessage({ result }, [...transfer]);
1983
+ } catch (error) {
1984
+ port.postMessage({ error });
1985
+ }
1986
+ });
1987
+ port.postMessage({ ready: true });
1988
+ }