@yuridulin/pointer 0.0.0-stage → 0.1.0

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 (71) hide show
  1. package/README.md +54 -2
  2. package/package.json +51 -4
  3. package/server/acp/catalog.ts +111 -0
  4. package/server/acp/connection.ts +233 -0
  5. package/server/acp/fake-agent.ts +408 -0
  6. package/server/acp/protocol.ts +167 -0
  7. package/server/acp/run.ts +139 -0
  8. package/server/acp/session.ts +1249 -0
  9. package/server/attachments.ts +115 -0
  10. package/server/changes.ts +239 -0
  11. package/server/cli.ts +362 -0
  12. package/server/compact.ts +361 -0
  13. package/server/config.ts +176 -0
  14. package/server/db.ts +462 -0
  15. package/server/dev.ts +8 -0
  16. package/server/diff.ts +190 -0
  17. package/server/engines.ts +63 -0
  18. package/server/files.ts +254 -0
  19. package/server/git.ts +319 -0
  20. package/server/history.ts +425 -0
  21. package/server/http/attachments.ts +63 -0
  22. package/server/http/browse.ts +108 -0
  23. package/server/http/chats.ts +627 -0
  24. package/server/http/closing.ts +14 -0
  25. package/server/http/files.ts +115 -0
  26. package/server/http/git.ts +84 -0
  27. package/server/http/preview.ts +21 -0
  28. package/server/http/providers.ts +200 -0
  29. package/server/http/reply.ts +38 -0
  30. package/server/hub.ts +521 -0
  31. package/server/install.ts +169 -0
  32. package/server/jobs.ts +664 -0
  33. package/server/linkPreview.ts +172 -0
  34. package/server/loop.ts +328 -0
  35. package/server/main.ts +353 -0
  36. package/server/probe.ts +34 -0
  37. package/server/process.ts +333 -0
  38. package/server/prompt.ts +196 -0
  39. package/server/providers/fake.ts +100 -0
  40. package/server/providers/opencode.ts +468 -0
  41. package/server/providers/registry.ts +149 -0
  42. package/server/providers/store.ts +210 -0
  43. package/server/segments.ts +248 -0
  44. package/server/sse.ts +93 -0
  45. package/server/tools/bash.ts +222 -0
  46. package/server/tools/edit.ts +254 -0
  47. package/server/tools/glob.ts +63 -0
  48. package/server/tools/grep.ts +122 -0
  49. package/server/tools/ignore.ts +54 -0
  50. package/server/tools/index.ts +129 -0
  51. package/server/tools/jail.ts +85 -0
  52. package/server/tools/jobs.ts +293 -0
  53. package/server/tools/read.ts +248 -0
  54. package/server/tools/write.ts +70 -0
  55. package/server/tray.ps1 +191 -0
  56. package/server/turn.ts +663 -0
  57. package/server/watch.ts +94 -0
  58. package/shared/acpConfig.ts +113 -0
  59. package/shared/links.ts +122 -0
  60. package/shared/types.ts +392 -0
  61. package/web/dist/app.css +1 -0
  62. package/web/dist/assets/codicon-mxdk0fnd.ttf +0 -0
  63. package/web/dist/index.html +28 -0
  64. package/web/dist/main.css +1 -0
  65. package/web/dist/main.js +1366 -0
  66. package/web/dist/tokens.css +1 -0
  67. package/web/dist/workers/css.worker.js +97 -0
  68. package/web/dist/workers/editor.worker.js +30 -0
  69. package/web/dist/workers/html.worker.js +300 -0
  70. package/web/dist/workers/json.worker.js +62 -0
  71. package/web/dist/workers/ts.worker.js +67733 -0
package/server/db.ts ADDED
@@ -0,0 +1,462 @@
1
+ import { mkdirSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { Database } from 'bun:sqlite'
4
+ import type { MessageRole, ReasoningLevel } from '../shared/types'
5
+
6
+ export type { MessageRole }
7
+
8
+ export type WorkspaceRow = {
9
+ id: string
10
+ name: string
11
+ root_path: string
12
+ created_at: number
13
+ last_opened_at: number
14
+ }
15
+
16
+ export type ChatRow = {
17
+ id: string
18
+ workspace_id: string
19
+ title: string
20
+ engine: string
21
+ model: string
22
+ acp_session_id: string | null
23
+ parent_chat_id: string | null
24
+ forked_from_seq: number | null
25
+ created_at: number
26
+ updated_at: number
27
+ archived_at: number | null
28
+ reasoning: ReasoningLevel | null
29
+ acp_config: string | null
30
+ }
31
+
32
+ export type MessageRow = {
33
+ id: string
34
+ chat_id: string
35
+ seq: number
36
+ role: MessageRole
37
+ content_json: string
38
+ details_json: string | null
39
+ created_at: number
40
+ }
41
+
42
+ // Next schema change is a new function. An applied step is not edited.
43
+ const steps: Array<(db: Database) => void> = [
44
+ (db) => {
45
+ db.run(`
46
+ CREATE TABLE workspaces (
47
+ id TEXT PRIMARY KEY,
48
+ name TEXT,
49
+ root_path TEXT UNIQUE,
50
+ created_at INTEGER,
51
+ last_opened_at INTEGER
52
+ )
53
+ `)
54
+ db.run(`
55
+ CREATE TABLE chats (
56
+ id TEXT PRIMARY KEY,
57
+ workspace_id TEXT REFERENCES workspaces(id),
58
+ title TEXT,
59
+ engine TEXT,
60
+ model TEXT,
61
+ acp_session_id TEXT,
62
+ parent_chat_id TEXT,
63
+ forked_from_seq INTEGER,
64
+ created_at INTEGER,
65
+ updated_at INTEGER,
66
+ archived_at INTEGER
67
+ )
68
+ `)
69
+ db.run(`
70
+ CREATE TABLE messages (
71
+ id TEXT PRIMARY KEY,
72
+ chat_id TEXT REFERENCES chats(id) ON DELETE CASCADE,
73
+ seq INTEGER,
74
+ role TEXT,
75
+ content_json TEXT,
76
+ details_json TEXT,
77
+ created_at INTEGER,
78
+ UNIQUE (chat_id, seq)
79
+ )
80
+ `)
81
+ db.run(`
82
+ CREATE TABLE file_revisions (
83
+ id TEXT PRIMARY KEY,
84
+ chat_id TEXT REFERENCES chats(id) ON DELETE CASCADE,
85
+ message_id TEXT REFERENCES messages(id) ON DELETE SET NULL,
86
+ path TEXT,
87
+ before_hash TEXT,
88
+ after_hash TEXT,
89
+ reviewed_at INTEGER,
90
+ created_at INTEGER
91
+ )
92
+ `)
93
+ db.run(`
94
+ CREATE TABLE blobs (
95
+ hash TEXT PRIMARY KEY,
96
+ size INTEGER,
97
+ content BLOB
98
+ )
99
+ `)
100
+ },
101
+ (db) => {
102
+ db.run('ALTER TABLE chats ADD COLUMN reasoning TEXT')
103
+ db.run(`
104
+ CREATE TABLE providers (
105
+ id TEXT PRIMARY KEY,
106
+ kind TEXT NOT NULL,
107
+ label TEXT NOT NULL,
108
+ base_url TEXT,
109
+ api_key TEXT,
110
+ command TEXT,
111
+ args_json TEXT,
112
+ cwd TEXT
113
+ )
114
+ `)
115
+ db.run(`
116
+ CREATE TABLE provider_models (
117
+ provider_id TEXT NOT NULL REFERENCES providers(id) ON DELETE CASCADE,
118
+ model_id TEXT NOT NULL,
119
+ PRIMARY KEY (provider_id, model_id)
120
+ )
121
+ `)
122
+ db.run(`
123
+ CREATE TABLE settings (
124
+ key TEXT PRIMARY KEY,
125
+ value TEXT NOT NULL
126
+ )
127
+ `)
128
+ db.run(`
129
+ INSERT INTO providers (id, kind, label) VALUES
130
+ ('opencode-go', 'opencode-go', 'OpenCode Go'),
131
+ ('openai', 'openai', 'OpenAI'),
132
+ ('acp:cursor', 'acp', 'Cursor')
133
+ `)
134
+ },
135
+ (db) => {
136
+ db.run(`UPDATE providers SET label = 'OpenAI-compatible' WHERE id = 'openai' AND label = 'OpenAI'`)
137
+ },
138
+ (db) => {
139
+ db.run('ALTER TABLE chats ADD COLUMN acp_config TEXT')
140
+ },
141
+ (db) => {
142
+ db.run('ALTER TABLE providers ADD COLUMN enabled INTEGER NOT NULL DEFAULT 1')
143
+ },
144
+ ]
145
+
146
+ export function openDatabase(file: string): Database {
147
+ if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true })
148
+ const db = new Database(file)
149
+ db.run('PRAGMA journal_mode = WAL')
150
+ db.run('PRAGMA foreign_keys = ON')
151
+ migrate(db)
152
+ return db
153
+ }
154
+
155
+ function migrate(db: Database): void {
156
+ const current = userVersion(db)
157
+ for (let index = current; index < steps.length; index++) {
158
+ const step = steps[index]
159
+ if (!step) continue
160
+ const version = index + 1
161
+ db.transaction(() => {
162
+ step(db)
163
+ db.run(`PRAGMA user_version = ${version}`)
164
+ })()
165
+ }
166
+ }
167
+
168
+ function userVersion(db: Database): number {
169
+ const row = db.query<{ user_version: number }, []>('PRAGMA user_version').get()
170
+ return row?.user_version ?? 0
171
+ }
172
+
173
+ /** Absolute, `/`, no trailing slash. On Windows the whole path is lowercased. */
174
+ export function normalizeRoot(input: string): string {
175
+ let posix = resolve(input).replaceAll('\\', '/')
176
+ if (process.platform === 'win32') posix = posix.toLowerCase()
177
+ if (posix.length > 3 && posix.endsWith('/')) posix = posix.replace(/\/+$/, '')
178
+ return posix
179
+ }
180
+
181
+ export function ensureWorkspace(db: Database, root: string, now = Date.now()): WorkspaceRow {
182
+ const rootPath = normalizeRoot(root)
183
+ const existing = db
184
+ .query<WorkspaceRow, [string]>(
185
+ 'SELECT id, name, root_path, created_at, last_opened_at FROM workspaces WHERE root_path = ?',
186
+ )
187
+ .get(rootPath)
188
+ if (existing) {
189
+ db.run('UPDATE workspaces SET last_opened_at = ? WHERE id = ?', [now, existing.id])
190
+ return { ...existing, last_opened_at: now }
191
+ }
192
+ const row: WorkspaceRow = {
193
+ id: crypto.randomUUID(),
194
+ name: folderName(rootPath),
195
+ root_path: rootPath,
196
+ created_at: now,
197
+ last_opened_at: now,
198
+ }
199
+ db.run(
200
+ `INSERT INTO workspaces (id, name, root_path, created_at, last_opened_at)
201
+ VALUES (?, ?, ?, ?, ?)`,
202
+ [row.id, row.name, row.root_path, row.created_at, row.last_opened_at],
203
+ )
204
+ return row
205
+ }
206
+
207
+ export type CreateChatInput = {
208
+ workspaceId: string
209
+ title: string
210
+ model: string
211
+ engine?: string
212
+ parentChatId?: string | null
213
+ forkedFromSeq?: number | null
214
+ reasoning?: ReasoningLevel | null
215
+ }
216
+
217
+ /** Always inserts a new chat; `ensureChat` is the one that reuses an existing row. */
218
+ export function createChat(db: Database, input: CreateChatInput, now = Date.now()): ChatRow {
219
+ const row: ChatRow = {
220
+ id: crypto.randomUUID(),
221
+ workspace_id: input.workspaceId,
222
+ title: input.title,
223
+ engine: input.engine ?? 'native',
224
+ model: input.model,
225
+ acp_session_id: null,
226
+ parent_chat_id: input.parentChatId ?? null,
227
+ forked_from_seq: input.forkedFromSeq ?? null,
228
+ created_at: now,
229
+ updated_at: now,
230
+ archived_at: null,
231
+ reasoning: input.reasoning ?? null,
232
+ acp_config: null,
233
+ }
234
+ insertChat(db, row)
235
+ return row
236
+ }
237
+
238
+ export function ensureChat(
239
+ db: Database,
240
+ workspaceId: string,
241
+ model: string,
242
+ title: string,
243
+ now = Date.now(),
244
+ ): ChatRow {
245
+ const existing = db
246
+ .query<ChatRow, [string]>(
247
+ `SELECT id, workspace_id, title, engine, model, acp_session_id, parent_chat_id,
248
+ forked_from_seq, created_at, updated_at, archived_at, reasoning, acp_config
249
+ FROM chats
250
+ WHERE workspace_id = ? AND archived_at IS NULL
251
+ ORDER BY created_at
252
+ LIMIT 1`,
253
+ )
254
+ .get(workspaceId)
255
+ if (existing) return existing
256
+ return createChat(db, { workspaceId, title, model }, now)
257
+ }
258
+
259
+ function insertChat(db: Database, row: ChatRow): void {
260
+ db.run(
261
+ `INSERT INTO chats (
262
+ id, workspace_id, title, engine, model, acp_session_id, parent_chat_id,
263
+ forked_from_seq, created_at, updated_at, archived_at, reasoning
264
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
265
+ [
266
+ row.id,
267
+ row.workspace_id,
268
+ row.title,
269
+ row.engine,
270
+ row.model,
271
+ row.acp_session_id,
272
+ row.parent_chat_id,
273
+ row.forked_from_seq,
274
+ row.created_at,
275
+ row.updated_at,
276
+ row.archived_at,
277
+ row.reasoning,
278
+ ],
279
+ )
280
+ }
281
+
282
+ export function appendMessage(
283
+ db: Database,
284
+ chatId: string,
285
+ role: MessageRole,
286
+ content: unknown,
287
+ details?: unknown,
288
+ ): MessageRow {
289
+ const contentJson = JSON.stringify(content)
290
+ const detailsJson = details === undefined ? null : JSON.stringify(details)
291
+ return db
292
+ .transaction((): MessageRow => {
293
+ const now = Date.now()
294
+ const current = db
295
+ .query<{ seq: number }, [string]>('SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM messages WHERE chat_id = ?')
296
+ .get(chatId)
297
+ const seq = current?.seq ?? 1
298
+ const id = crypto.randomUUID()
299
+ db.run(
300
+ `INSERT INTO messages (id, chat_id, seq, role, content_json, details_json, created_at)
301
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
302
+ [id, chatId, seq, role, contentJson, detailsJson, now],
303
+ )
304
+ db.run('UPDATE chats SET updated_at = ? WHERE id = ?', [now, chatId])
305
+ return {
306
+ id,
307
+ chat_id: chatId,
308
+ seq,
309
+ role,
310
+ content_json: contentJson,
311
+ details_json: detailsJson,
312
+ created_at: now,
313
+ }
314
+ })
315
+ .immediate()
316
+ }
317
+
318
+ export function listMessages(db: Database, chatId: string): MessageRow[] {
319
+ return db
320
+ .query<MessageRow, [string]>(
321
+ `SELECT id, chat_id, seq, role, content_json, details_json, created_at
322
+ FROM messages WHERE chat_id = ? ORDER BY seq`,
323
+ )
324
+ .all(chatId)
325
+ }
326
+
327
+ export function listWorkspaces(db: Database): WorkspaceRow[] {
328
+ return db
329
+ .query<WorkspaceRow, []>(
330
+ `SELECT id, name, root_path, created_at, last_opened_at
331
+ FROM workspaces ORDER BY last_opened_at DESC`,
332
+ )
333
+ .all()
334
+ }
335
+
336
+ export function getWorkspace(db: Database, id: string): WorkspaceRow | null {
337
+ return (
338
+ db
339
+ .query<WorkspaceRow, [string]>(
340
+ 'SELECT id, name, root_path, created_at, last_opened_at FROM workspaces WHERE id = ?',
341
+ )
342
+ .get(id) ?? null
343
+ )
344
+ }
345
+
346
+ const chatColumns = `id, workspace_id, title, engine, model, acp_session_id, parent_chat_id,
347
+ forked_from_seq, created_at, updated_at, archived_at, reasoning, acp_config`
348
+
349
+ export function getChat(db: Database, id: string): ChatRow | null {
350
+ return db.query<ChatRow, [string]>(`SELECT ${chatColumns} FROM chats WHERE id = ?`).get(id) ?? null
351
+ }
352
+
353
+ export function listChats(db: Database, workspaceId: string): ChatRow[] {
354
+ return db
355
+ .query<ChatRow, [string]>(
356
+ `SELECT ${chatColumns} FROM chats
357
+ WHERE workspace_id = ? AND archived_at IS NULL
358
+ ORDER BY created_at`,
359
+ )
360
+ .all(workspaceId)
361
+ }
362
+
363
+ export function listNativeChatIds(db: Database): string[] {
364
+ return db
365
+ .query<{ id: string }, []>(`SELECT id FROM chats WHERE engine = 'native'`)
366
+ .all()
367
+ .map((row) => row.id)
368
+ }
369
+
370
+ export function updateChatTitle(db: Database, chatId: string, title: string, now = Date.now()): void {
371
+ db.run('UPDATE chats SET title = ?, updated_at = ? WHERE id = ?', [title, now, chatId])
372
+ }
373
+
374
+ export function setAcpSessionId(db: Database, chatId: string, sessionId: string | null): void {
375
+ db.run('UPDATE chats SET acp_session_id = ?, updated_at = ? WHERE id = ?', [sessionId, Date.now(), chatId])
376
+ }
377
+
378
+ export function readAcpConfig(row: ChatRow | null): Record<string, string | boolean> {
379
+ if (!row?.acp_config) return {}
380
+ try {
381
+ const parsed = JSON.parse(row.acp_config) as unknown
382
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}
383
+ const saved: Record<string, string | boolean> = {}
384
+ for (const [key, value] of Object.entries(parsed)) {
385
+ if (typeof value === 'string' || typeof value === 'boolean') saved[key] = value
386
+ }
387
+ return saved
388
+ } catch {
389
+ return {}
390
+ }
391
+ }
392
+
393
+ export function writeAcpConfig(db: Database, chatId: string, saved: Record<string, string | boolean>): void {
394
+ db.run('UPDATE chats SET acp_config = ?, updated_at = ? WHERE id = ?', [JSON.stringify(saved), Date.now(), chatId])
395
+ }
396
+
397
+ export function updateChat(
398
+ db: Database,
399
+ chatId: string,
400
+ patch: {
401
+ title?: string
402
+ model?: string
403
+ archived?: boolean
404
+ reasoning?: ReasoningLevel | null
405
+ engine?: string
406
+ },
407
+ now = Date.now(),
408
+ ): ChatRow | null {
409
+ const sets: string[] = []
410
+ const values: Array<string | number | null> = []
411
+ if (patch.title !== undefined) {
412
+ sets.push('title = ?')
413
+ values.push(patch.title)
414
+ }
415
+ if (patch.model !== undefined) {
416
+ sets.push('model = ?')
417
+ values.push(patch.model)
418
+ }
419
+ if (patch.archived !== undefined) {
420
+ sets.push('archived_at = ?')
421
+ values.push(patch.archived ? now : null)
422
+ }
423
+ if ('reasoning' in patch) {
424
+ sets.push('reasoning = ?')
425
+ values.push(patch.reasoning ?? null)
426
+ }
427
+ if (patch.engine !== undefined) {
428
+ sets.push('engine = ?')
429
+ values.push(patch.engine)
430
+ }
431
+ if (sets.length === 0) return getChat(db, chatId)
432
+ sets.push('updated_at = ?')
433
+ values.push(now, chatId)
434
+ db.run(`UPDATE chats SET ${sets.join(', ')} WHERE id = ?`, values)
435
+ return getChat(db, chatId)
436
+ }
437
+
438
+ /** Удаляет чат; сообщения и ревизии уходят каскадом по внешним ключам. */
439
+ export function deleteChat(db: Database, chatId: string): boolean {
440
+ return db.run('DELETE FROM chats WHERE id = ?', [chatId]).changes > 0
441
+ }
442
+
443
+ export function listWorkspaceChatIds(db: Database, workspaceId: string): string[] {
444
+ return db
445
+ .query<{ id: string }, [string]>('SELECT id FROM chats WHERE workspace_id = ?')
446
+ .all(workspaceId)
447
+ .map((row) => row.id)
448
+ }
449
+
450
+ /** Удаляет строку папки и её чаты. Файлы на диске не трогает. */
451
+ export function deleteWorkspace(db: Database, id: string): boolean {
452
+ const remove = db.transaction(() => {
453
+ for (const chatId of listWorkspaceChatIds(db, id)) deleteChat(db, chatId)
454
+ return db.run('DELETE FROM workspaces WHERE id = ?', [id]).changes > 0
455
+ })
456
+ return remove()
457
+ }
458
+
459
+ function folderName(rootPath: string): string {
460
+ const parts = rootPath.split('/').filter(Boolean)
461
+ return parts.at(-1) ?? rootPath
462
+ }
package/server/dev.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { homedir } from 'node:os'
2
+ import { join } from 'node:path'
3
+ import { DEV_HOME_NAME } from './config'
4
+
5
+ const base = process.env.USERPROFILE || homedir()
6
+ if (!process.env.POINTER_HOME?.trim()) process.env.POINTER_HOME = join(base, DEV_HOME_NAME)
7
+ const { bootDaemon } = await import('./main')
8
+ bootDaemon()
package/server/diff.ts ADDED
@@ -0,0 +1,190 @@
1
+ export type DiffLine = { op: ' ' | '+' | '-'; text: string }
2
+ export type Hunk = {
3
+ oldStart: number
4
+ oldLines: number
5
+ newStart: number
6
+ newLines: number
7
+ lines: DiffLine[]
8
+ }
9
+ export type FileDiff = { hunks: Hunk[]; added: number; removed: number }
10
+
11
+ const MAX_D = 2000
12
+ const EMPTY = new Int32Array(0)
13
+ // A line that lacks its final newline carries this marker while lines are compared, so that
14
+ // `a\n` and `a` are different texts. It is stripped before the diff leaves this module.
15
+ // A lone surrogate cannot come out of UTF-8 decoding, so real line text never contains it.
16
+ const NO_EOL = '\uD800'
17
+
18
+ export function diffLines(before: string | null, after: string, context = 3): FileDiff {
19
+ const ops = diffOps(before === null ? [] : splitLines(before), splitLines(after))
20
+ let added = 0
21
+ let removed = 0
22
+ for (const line of ops) {
23
+ if (line.op === '+') added++
24
+ else if (line.op === '-') removed++
25
+ }
26
+ return { hunks: buildHunks(ops, Math.max(0, context)), added, removed }
27
+ }
28
+
29
+ function splitLines(text: string): string[] {
30
+ if (text === '') return []
31
+ const normalized = text.includes('\r') ? text.replace(/\r\n/g, '\n') : text
32
+ const lines = normalized.split('\n')
33
+ if (lines[lines.length - 1] === '') lines.pop()
34
+ else lines[lines.length - 1] += NO_EOL
35
+ return lines
36
+ }
37
+
38
+ function diffOps(a: string[], b: string[]): DiffLine[] {
39
+ let head = 0
40
+ const shortest = Math.min(a.length, b.length)
41
+ while (head < shortest && a[head] === b[head]) head++
42
+ let tailA = a.length
43
+ let tailB = b.length
44
+ while (tailA > head && tailB > head && a[tailA - 1] === b[tailB - 1]) {
45
+ tailA--
46
+ tailB--
47
+ }
48
+
49
+ const ops: DiffLine[] = []
50
+ for (let i = 0; i < head; i++) ops.push({ op: ' ', text: a[i] })
51
+ const middleA = a.slice(head, tailA)
52
+ const middleB = b.slice(head, tailB)
53
+ const middle = myers(middleA, middleB)
54
+ if (middle) for (const line of middle) ops.push(line)
55
+ else {
56
+ for (const text of middleA) ops.push({ op: '-', text })
57
+ for (const text of middleB) ops.push({ op: '+', text })
58
+ }
59
+ for (let i = tailA; i < a.length; i++) ops.push({ op: ' ', text: a[i] })
60
+ return ops.map((line) =>
61
+ line.text.endsWith(NO_EOL) ? { op: line.op, text: line.text.slice(0, -NO_EOL.length) } : line,
62
+ )
63
+ }
64
+
65
+ function myers(a: string[], b: string[]): DiffLine[] | null {
66
+ const n = a.length
67
+ const m = b.length
68
+ if (n === 0) return b.map((text) => ({ op: '+' as const, text }))
69
+ if (m === 0) return a.map((text) => ({ op: '-' as const, text }))
70
+
71
+ const limit = Math.min(n + m, MAX_D)
72
+ const offset = limit
73
+ const v = new Int32Array(2 * limit + 1)
74
+ const trace: Int32Array[] = []
75
+ let done = -1
76
+ for (let d = 0; d <= limit && done < 0; d++) {
77
+ trace.push(d === 0 ? EMPTY : v.slice(offset - d + 1, offset + d))
78
+ for (let k = -d; k <= d; k += 2) {
79
+ let x =
80
+ k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])
81
+ ? v[offset + k + 1]
82
+ : v[offset + k - 1] + 1
83
+ let y = x - k
84
+ while (x < n && y < m && a[x] === b[y]) {
85
+ x++
86
+ y++
87
+ }
88
+ v[offset + k] = x
89
+ if (x === n && y === m) {
90
+ done = d
91
+ break
92
+ }
93
+ }
94
+ }
95
+ if (done < 0) return null
96
+
97
+ const out: DiffLine[] = []
98
+ let x = n
99
+ let y = m
100
+ for (let d = done; d >= 1; d--) {
101
+ const state = trace[d]
102
+ const base = d - 1
103
+ const at = (k: number) => state[k + base]
104
+ const k = x - y
105
+ const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1
106
+ const prevX = at(prevK)
107
+ const prevY = prevX - prevK
108
+ while (x > prevX && y > prevY) {
109
+ out.push({ op: ' ', text: a[x - 1] })
110
+ x--
111
+ y--
112
+ }
113
+ if (x === prevX) {
114
+ out.push({ op: '+', text: b[y - 1] })
115
+ y--
116
+ } else {
117
+ out.push({ op: '-', text: a[x - 1] })
118
+ x--
119
+ }
120
+ }
121
+ while (x > 0 && y > 0) {
122
+ out.push({ op: ' ', text: a[x - 1] })
123
+ x--
124
+ y--
125
+ }
126
+ return out.reverse()
127
+ }
128
+
129
+ function buildHunks(ops: DiffLine[], context: number): Hunk[] {
130
+ const oldPos = new Int32Array(ops.length + 1)
131
+ const newPos = new Int32Array(ops.length + 1)
132
+ let oldNo = 1
133
+ let newNo = 1
134
+ for (let i = 0; i < ops.length; i++) {
135
+ oldPos[i] = oldNo
136
+ newPos[i] = newNo
137
+ if (ops[i].op !== '+') oldNo++
138
+ if (ops[i].op !== '-') newNo++
139
+ }
140
+ oldPos[ops.length] = oldNo
141
+ newPos[ops.length] = newNo
142
+
143
+ const hunks: Hunk[] = []
144
+ let start: number | null = null
145
+ let last = -1
146
+ let i = 0
147
+ while (i < ops.length) {
148
+ if (ops[i].op === ' ') {
149
+ i++
150
+ continue
151
+ }
152
+ let end = i
153
+ while (end < ops.length && ops[end].op !== ' ') end++
154
+ if (start !== null && i - last - 1 <= 2 * context) {
155
+ last = end - 1
156
+ } else {
157
+ if (start !== null) hunks.push(makeHunk(ops, oldPos, newPos, start, last + context + 1))
158
+ start = i - context
159
+ last = end - 1
160
+ }
161
+ i = end
162
+ }
163
+ if (start !== null) hunks.push(makeHunk(ops, oldPos, newPos, start, last + context + 1))
164
+ return hunks
165
+ }
166
+
167
+ function makeHunk(
168
+ ops: DiffLine[],
169
+ oldPos: Int32Array,
170
+ newPos: Int32Array,
171
+ from: number,
172
+ to: number,
173
+ ): Hunk {
174
+ const start = Math.max(0, from)
175
+ const end = Math.min(ops.length, to)
176
+ const lines = ops.slice(start, end)
177
+ let oldLines = 0
178
+ let newLines = 0
179
+ for (const line of lines) {
180
+ if (line.op !== '+') oldLines++
181
+ if (line.op !== '-') newLines++
182
+ }
183
+ return {
184
+ oldStart: oldLines === 0 ? oldPos[start] - 1 : oldPos[start],
185
+ oldLines,
186
+ newStart: newLines === 0 ? newPos[start] - 1 : newPos[start],
187
+ newLines,
188
+ lines,
189
+ }
190
+ }