project-brain 0.47.0 → 0.48.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.
@@ -0,0 +1,573 @@
1
+ export const TEXT_PREVIEW_MAX_BYTES = 2 * 1024 * 1024
2
+ export const READ_CAP_BYTES = 192 * 1024
3
+ export const DEBOUNCE_MS = 120
4
+ export const NVIM_TIMEOUT_MS = 700
5
+ export const READ_TIMEOUT_MS = 2000
6
+ export const LAUNCH_TIMEOUT_MS = 5000
7
+ export const THUMB_TIMEOUT_MS = 8000
8
+ export const THUMB_MAX_PX = 800
9
+ export const FAILED_SERVER_TTL_MS = 30_000
10
+ export const PANE_LINES = 200
11
+ export const PANE_COLUMNS = 400
12
+ export const MAX_PATHS_PER_ROW = 6
13
+ export const RENDER_CACHE_LIMIT = 200
14
+
15
+ export const PATH_TOOLS: readonly string[] = ['Read', 'Edit', 'Write']
16
+
17
+ /**
18
+ * Names never previewed or opened: the owner records demos, so a key or a
19
+ * token must never reach the screen by a click. Globs matched,
20
+ * case-insensitively, against the file's name and against every directory
21
+ * between the project root and it.
22
+ */
23
+ export const SECRET_NAMES: readonly string[] = [
24
+ '.env*',
25
+ 'env.production*',
26
+ '*.pem',
27
+ '*.key',
28
+ 'id_rsa*',
29
+ 'id_dsa*',
30
+ 'id_ecdsa*',
31
+ 'id_ed25519*',
32
+ 'credentials*',
33
+ '*.p12',
34
+ '*.pfx',
35
+ '.npmrc',
36
+ '.netrc',
37
+ '.pgpass',
38
+ '.git-credentials',
39
+ '.pypirc',
40
+ 'kubeconfig*',
41
+ 'secrets.*',
42
+ '*.tfvars',
43
+ '*.tfvars.json',
44
+ 'terraform.tfstate*',
45
+ '.dev.vars',
46
+ '*.kdbx',
47
+ '*.token',
48
+ '.vault-token',
49
+ '*.asc',
50
+ '*.ppk',
51
+ '.htpasswd',
52
+ '.mcp.json',
53
+ '*.keystore',
54
+ '*.jks',
55
+ 'service-account*.json',
56
+ '.zsh_history',
57
+ '.bash_history',
58
+ '.claude.json',
59
+ ]
60
+
61
+ /** Directories whose whole content counts as secret, at any depth. */
62
+ export const SECRET_DIRS: readonly string[] = ['.ssh', '.gnupg', '.aws', '.kube']
63
+
64
+ /** Globs over the last components of the path: a file secret only in its directory. */
65
+ export const SECRET_PATHS: readonly string[] = ['.docker/config.json', '.git/config', '.claude/settings*.json', '.config/gh/hosts.yml']
66
+
67
+ /**
68
+ * Content that refuses a whole preview, by label; the label is what the
69
+ * person is told, never the text that matched.
70
+ */
71
+ export const SECRET_CONTENT: ReadonlyArray<{ label: string; pattern: RegExp }> = [
72
+ { label: 'a private key', pattern: /-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----/ },
73
+ { label: 'a PuTTY key', pattern: /PuTTY-User-Key-File-\d/ },
74
+ { label: 'an AWS access key id', pattern: /\bAKIA[0-9A-Z]{16}\b/ },
75
+ { label: 'a GitHub token', pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,})/ },
76
+ { label: 'an API key (sk-)', pattern: /\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}/ },
77
+ { label: 'a Slack token', pattern: /\bxox[abpor]-[A-Za-z0-9-]{10,}/ },
78
+ { label: 'a Google API key', pattern: /\bAIza[0-9A-Za-z_-]{35}/ },
79
+ { label: 'a JWT', pattern: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
80
+ ]
81
+
82
+ const ASSIGNMENT = /(?:password|passwd|secret|token|api[_-]?key)[\w.-]{0,40}["']?[ \t]{0,8}[:=][ \t]{0,8}["']?([A-Za-z0-9+/=_-]{16,512})/gi
83
+
84
+ export const IMAGE_EXTS: readonly string[] = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'heic']
85
+ export const VIDEO_EXTS: readonly string[] = ['mp4', 'mov', 'webm', 'mkv']
86
+
87
+ const UNSAFE_CHARS = /[\u0000-\u001f\u007f]/
88
+
89
+ export type Kind = 'text' | 'image' | 'video'
90
+ export type Target = { path: string; line: number }
91
+
92
+ const globToRegExp = (glob: string): RegExp =>
93
+ new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`, 'i')
94
+
95
+ const NAME_PATTERNS = SECRET_NAMES.map(globToRegExp)
96
+ const PATH_PATTERNS = SECRET_PATHS.map(glob => glob.split('/').map(globToRegExp))
97
+
98
+ export const baseName = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
99
+
100
+ export const extensionOf = (path: string): string => {
101
+ const name = baseName(path)
102
+ const dot = name.lastIndexOf('.')
103
+ return dot <= 0 ? '' : name.slice(dot + 1).toLowerCase()
104
+ }
105
+
106
+ export const kindOf = (path: string): Kind => {
107
+ const ext = extensionOf(path)
108
+ if (IMAGE_EXTS.includes(ext)) return 'image'
109
+ if (VIDEO_EXTS.includes(ext)) return 'video'
110
+ return 'text'
111
+ }
112
+
113
+ export const isInside = (real: string, root: string): boolean => {
114
+ const base = root.replace(/\/+$/, '')
115
+ if (base === '') return real.startsWith('/')
116
+ return real === base || real.startsWith(`${base}/`)
117
+ }
118
+
119
+ /** The components under the root that holds the path, or all of them when none does. */
120
+ const componentsUnder = (path: string, roots: readonly string[]): string[] => {
121
+ const root = roots.find(candidate => isInside(path, candidate))
122
+ const rest = root === undefined ? path : path.slice(root.replace(/\/+$/, '').length)
123
+ return rest.split('/').filter(part => part !== '')
124
+ }
125
+
126
+ export const isSecretName = (path: string, roots: readonly string[] = []): boolean => {
127
+ const parts = componentsUnder(path, roots)
128
+ if (parts.some(part => NAME_PATTERNS.some(pattern => pattern.test(part)))) return true
129
+ if (parts.slice(0, -1).some(part => SECRET_DIRS.includes(part.toLowerCase()))) return true
130
+ return PATH_PATTERNS.some(globs => globs.length <= parts.length && globs.every((glob, i) => glob.test(parts[parts.length - globs.length + i]!)))
131
+ }
132
+
133
+ /** The label of the first secret the text holds, or undefined. */
134
+ export const secretInContent = (text: string): string | undefined => {
135
+ for (const { label, pattern } of SECRET_CONTENT) if (pattern.test(text)) return label
136
+ for (const match of text.matchAll(ASSIGNMENT)) {
137
+ const value = match[1] ?? ''
138
+ if (/[0-9]/.test(value) && /[A-Za-z]/.test(value)) return 'a password or token assignment'
139
+ }
140
+ return undefined
141
+ }
142
+
143
+ export const isUnsafeSpelling = (path: string): boolean => path === '' || UNSAFE_CHARS.test(path)
144
+
145
+ export const looksBinary = (bytes: Uint8Array): boolean => bytes.includes(0)
146
+
147
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
148
+
149
+ export const decodeBase64 = (text: string): Uint8Array => {
150
+ const clean = text.replace(/[^A-Za-z0-9+/]/g, '')
151
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4))
152
+ let bits = 0
153
+ let value = 0
154
+ let at = 0
155
+ for (const char of clean) {
156
+ value = ((value << 6) | B64.indexOf(char)) & 0xffffff
157
+ bits += 6
158
+ if (bits >= 8) {
159
+ bits -= 8
160
+ out[at++] = (value >> bits) & 0xff
161
+ }
162
+ }
163
+ return out.subarray(0, at)
164
+ }
165
+
166
+ /** Joins and folds `.`/`..` by spelling only; the guard still trusts `realPath` alone. */
167
+ export const absoluteOf = (spelled: string, cwd: string): string => {
168
+ const joined = spelled.startsWith('/') ? spelled : `${cwd.replace(/\/+$/, '')}/${spelled}`
169
+ const parts: string[] = []
170
+ for (const part of joined.split('/')) {
171
+ if (part === '' || part === '.') continue
172
+ if (part === '..') parts.pop()
173
+ else parts.push(part)
174
+ }
175
+ return `/${parts.join('/')}`
176
+ }
177
+
178
+ export const splitRoots = (value: string | undefined): string[] =>
179
+ (value ?? '').split(':').map(part => part.trim()).filter(part => part.startsWith('/'))
180
+
181
+ /** A root that is the home folder or `/` would put every dotfile in reach: never a preview root. */
182
+ export const isForbiddenRoot = (real: string, home: string | undefined): boolean => {
183
+ const trimmed = real.replace(/\/+$/, '')
184
+ return trimmed === '' || (home !== undefined && home !== '' && trimmed === home.replace(/\/+$/, ''))
185
+ }
186
+
187
+ export type PathFacts = {
188
+ spelled: string
189
+ real: string | undefined
190
+ kind: 'file' | 'dir' | 'other' | undefined
191
+ roots: readonly string[]
192
+ }
193
+
194
+ export type Verdict = { ok: true; real: string } | { ok: false; reason: string }
195
+
196
+ /** The gate by name and place, in front of every preview and open; the bytes are checked again when read. */
197
+ export const checkTarget = (facts: PathFacts): Verdict => {
198
+ if (isUnsafeSpelling(facts.spelled)) return { ok: false, reason: 'the path holds a control character' }
199
+ if (facts.roots.length === 0) return { ok: false, reason: 'no project root to preview from (home and / are never one)' }
200
+ if (facts.real === undefined || facts.kind === undefined) return { ok: false, reason: 'the file does not exist' }
201
+ if (isUnsafeSpelling(facts.real)) return { ok: false, reason: 'the path holds a control character' }
202
+ if (facts.kind !== 'file') return { ok: false, reason: 'not a regular file' }
203
+ if (!facts.roots.some(root => isInside(facts.real!, root))) return { ok: false, reason: 'outside the project roots' }
204
+ if (isSecretName(baseName(facts.spelled)) || isSecretName(facts.real, facts.roots)) return { ok: false, reason: 'a secret-like file is never shown' }
205
+ return { ok: true, real: facts.real }
206
+ }
207
+
208
+ /**
209
+ * Reads a file once, by argv: opened with O_NOFOLLOW (a symlink swapped in
210
+ * fails) and O_NONBLOCK (a FIFO cannot hang it), then fstat on that handle:
211
+ * a regular file with one link, still reachable at the same absolute path
212
+ * with no symlink on the way. Prints `OK <size> <truncated>` and the base64
213
+ * of at most `cap` bytes, or `ERR <code>`.
214
+ */
215
+ export const READ_ONCE_PERL = [
216
+ 'use strict;',
217
+ 'use Fcntl qw(O_RDONLY O_NOFOLLOW O_NONBLOCK S_ISREG);',
218
+ 'use Cwd qw(abs_path);',
219
+ 'use MIME::Base64 qw(encode_base64);',
220
+ 'my ($path, $cap) = @ARGV;',
221
+ 'sub out { print "ERR $_[0]\\n"; exit 0 }',
222
+ 'sysopen(my $fh, $path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) or out("open");',
223
+ 'my @st = stat($fh) or out("open");',
224
+ 'S_ISREG($st[2]) or out("notfile");',
225
+ '$st[3] == 1 or out("links");',
226
+ 'my $now = abs_path($path);',
227
+ 'my @again = lstat($path);',
228
+ '(defined $now && $now eq $path && @again && $again[0] == $st[0] && $again[1] == $st[1]) or out("moved");',
229
+ 'my $want = $st[7] < $cap ? $st[7] : $cap;',
230
+ 'my $buf = "";',
231
+ 'while (length($buf) < $want) { my $n = sysread($fh, $buf, $want - length($buf), length($buf)); last unless $n; }',
232
+ 'print "OK $st[7] ", ($st[7] > length($buf) ? 1 : 0), "\\n", encode_base64($buf, ""), "\\n";',
233
+ ].join(' ')
234
+
235
+ export const readOnceArgv = (real: string, cap = READ_CAP_BYTES): string[] => ['perl', '-e', READ_ONCE_PERL, '--', real, String(cap)]
236
+
237
+ const READ_ERRORS: Record<string, string> = {
238
+ open: 'the file could not be opened without following a link',
239
+ notfile: 'not a regular file',
240
+ links: 'a file with more than one hard link is never shown',
241
+ moved: 'the file moved while it was being read',
242
+ }
243
+
244
+ export type ReadOnce = { ok: true; size: number; truncated: boolean; base64: string; bytes: Uint8Array } | { ok: false; reason: string }
245
+
246
+ export const parseReadOnce = (stdout: string): ReadOnce => {
247
+ const [head = '', body = ''] = stdout.split('\n')
248
+ const error = /^ERR (\w+)$/.exec(head)
249
+ if (error) return { ok: false, reason: READ_ERRORS[error[1]!] ?? 'the file could not be read' }
250
+ const ok = /^OK (\d+) ([01])$/.exec(head)
251
+ if (!ok || !/^[A-Za-z0-9+/=]*$/.test(body)) return { ok: false, reason: 'the file could not be read' }
252
+ return { ok: true, size: Number(ok[1]), truncated: ok[2] === '1', base64: body, bytes: decodeBase64(body) }
253
+ }
254
+
255
+ export type Shown = { ok: true; text: string } | { ok: false; reason: string }
256
+
257
+ /** Every byte that will be shown, checked: not binary, no secret by content. */
258
+ export const checkContent = (bytes: Uint8Array, decode: (bytes: Uint8Array) => string): Shown => {
259
+ if (looksBinary(bytes)) return { ok: false, reason: 'a binary file is not previewed' }
260
+ const text = decode(bytes)
261
+ const secret = secretInContent(text)
262
+ return secret === undefined ? { ok: true, text } : { ok: false, reason: `it holds what looks like ${secret}` }
263
+ }
264
+
265
+ export const toolTarget = (tool: string, input: unknown): Target | undefined => {
266
+ if (!PATH_TOOLS.includes(tool) || typeof input !== 'object' || input === null) return undefined
267
+ const record = input as Record<string, unknown>
268
+ const path = record.file_path
269
+ if (typeof path !== 'string' || isUnsafeSpelling(path)) return undefined
270
+ const offset = typeof record.offset === 'number' && record.offset > 0 ? Math.floor(record.offset) : 0
271
+ return { path, line: tool === 'Read' ? offset : 0 }
272
+ }
273
+
274
+ const PATH_TOKEN = /(^|[\s(\[`'"])((?:\.{1,2}\/|\/)?(?:[\w.@+-]+\/)*[\w@+-][\w.@+-]*\.[A-Za-z0-9]{1,10})(?::(\d{1,7}))?(?=$|[\s)\]`'",;!?]|[.:](?:\s|$))/gm
275
+
276
+ /**
277
+ * Path-like tokens of a markdown text, first seen first, by shape alone (no
278
+ * file system at render): anything with a slash, or a bare `name.ext` inside
279
+ * a code span, so prose such as "Node.js" grows no button.
280
+ */
281
+ export const detectPaths = (text: string, limit = MAX_PATHS_PER_ROW): Target[] => {
282
+ const found: Target[] = []
283
+ const seen = new Set<string>()
284
+ for (const match of text.matchAll(PATH_TOKEN)) {
285
+ const path = match[2] ?? ''
286
+ const start = (match.index ?? 0) + (match[1]?.length ?? 0)
287
+ if (text.slice(Math.max(0, start - 3), start).includes('://')) continue
288
+ const isBare = !path.includes('/')
289
+ if (isBare && (match[1] !== '`' || !/^[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]{0,9}$/.test(path))) continue
290
+ if (/^\d+(\.\d+)+$/.test(path) || isUnsafeSpelling(path) || isSecretName(path)) continue
291
+ if (seen.has(path)) continue
292
+ seen.add(path)
293
+ found.push({ path, line: match[3] === undefined ? 0 : Number(match[3]) })
294
+ if (found.length >= limit) break
295
+ }
296
+ return found
297
+ }
298
+
299
+ /** A command line as argv, no shell: single and double quotes, backslash escapes; undefined when a quote is left open. */
300
+ export const parseCommand = (line: string): string[] | undefined => {
301
+ const words: string[] = []
302
+ let word = ''
303
+ let hasWord = false
304
+ let quote: '"' | "'" | undefined
305
+ for (let i = 0; i < line.length; i++) {
306
+ const char = line[i]!
307
+ if (quote === "'") {
308
+ if (char === "'") quote = undefined
309
+ else word += char
310
+ continue
311
+ }
312
+ if (char === '\\' && i + 1 < line.length && (quote === undefined || '"\\$`'.includes(line[i + 1]!))) {
313
+ word += line[++i]
314
+ hasWord = true
315
+ continue
316
+ }
317
+ if (quote === '"') {
318
+ if (char === '"') quote = undefined
319
+ else word += char
320
+ continue
321
+ }
322
+ if (char === '"' || char === "'") {
323
+ quote = char
324
+ hasWord = true
325
+ continue
326
+ }
327
+ if (/\s/.test(char)) {
328
+ if (hasWord) words.push(word)
329
+ word = ''
330
+ hasWord = false
331
+ continue
332
+ }
333
+ word += char
334
+ hasWord = true
335
+ }
336
+ if (quote !== undefined) return undefined
337
+ if (hasWord) words.push(word)
338
+ return words
339
+ }
340
+
341
+ export type EditorEnv = { PB_EDITOR?: string; VISUAL?: string; EDITOR?: string }
342
+
343
+ export const editorCommand = (env: EditorEnv): string[] => {
344
+ for (const value of [env.PB_EDITOR, env.VISUAL, env.EDITOR]) {
345
+ if (value === undefined || value.trim() === '') continue
346
+ const argv = parseCommand(value)
347
+ if (argv !== undefined && argv.length > 0 && !argv.some(isUnsafeSpelling)) return argv
348
+ }
349
+ return ['nvim']
350
+ }
351
+
352
+ const TERMINAL_EDITORS = new Set(['nvim', 'vim', 'vi', 'nano', 'emacs', 'hx', 'helix', 'micro', 'kak', 'joe'])
353
+ const GOTO_EDITORS = new Set(['code', 'code-insiders', 'cursor', 'codium', 'windsurf'])
354
+ const COLON_EDITORS = new Set(['zed', 'subl'])
355
+
356
+ export const isNvim = (editor: readonly string[]): boolean => baseName(editor[0] ?? '') === 'nvim'
357
+
358
+ /** Editors that need a terminal of their own; anything else is a launcher that hands off and exits. */
359
+ export const isTerminalEditor = (editor: readonly string[]): boolean => TERMINAL_EDITORS.has(baseName(editor[0] ?? ''))
360
+
361
+ export const editorArgv = (editor: readonly string[], file: string, line: number): string[] => {
362
+ const name = baseName(editor[0] ?? '')
363
+ if (line > 0 && TERMINAL_EDITORS.has(name)) return [...editor, `+${line}`, '--', file]
364
+ if (line > 0 && GOTO_EDITORS.has(name)) return [...editor, '-g', `${file}:${line}`]
365
+ if (line > 0 && COLON_EDITORS.has(name)) return [...editor, `${file}:${line}`]
366
+ return [...editor, file]
367
+ }
368
+
369
+ /**
370
+ * POSIX single quoting, for the one string a shell reads: the command a new
371
+ * Supacode tab runs. Checked against `sh`; fish reads `\'` inside single
372
+ * quotes differently and is not covered.
373
+ */
374
+ export const shQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
375
+
376
+ export const supacodeTabArgv = (title: string, command: readonly string[], background: boolean): string[] => [
377
+ 'supacode',
378
+ 'tab',
379
+ 'new',
380
+ ...(background ? ['--background'] : []),
381
+ '--title',
382
+ title.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, 80),
383
+ '--input',
384
+ command.map(shQuote).join(' '),
385
+ ]
386
+
387
+ export const readOnlyNvimArgv = (file: string, line: number): string[] => ['nvim', '-R', ...(line > 0 ? [`+${line}`] : []), '--', file]
388
+
389
+ /** A Vim single-quoted literal: no escapes inside, a quote doubled. */
390
+ export const vimString = (value: string): string => `'${value.replace(/'/g, "''")}'`
391
+
392
+ /**
393
+ * Lua run inside the owner's Neovim through `luaeval(code, _A)`. It never
394
+ * opens the path: the lines arrive as base64 of the bytes the mod read and
395
+ * checked, the path is only the title. A scratch buffer in a floating window
396
+ * opened with `enter = false` and `focusable = false`, so focus, cursor and
397
+ * the current window stay put. A non-focusable float cannot take `q`, so it
398
+ * closes on the next cursor move, insert or buffer change in the owner's
399
+ * window, or when the next preview replaces it.
400
+ */
401
+ export const FLOAT_LUA = [
402
+ '(function(a)',
403
+ 'local title, data, line = a[1], a[2], a[3]',
404
+ 'local api = vim.api',
405
+ 'local prev = vim.g.pb_file_preview_win',
406
+ 'if prev and api.nvim_win_is_valid(prev) then pcall(api.nvim_win_close, prev, true) end',
407
+ 'local lines = vim.split(vim.base64.decode(data), "\\n", { plain = true })',
408
+ 'for i, l in ipairs(lines) do lines[i] = l:gsub("\\r$", "") end',
409
+ 'if #lines > 1 and lines[#lines] == "" then table.remove(lines) end',
410
+ 'local buf = api.nvim_create_buf(false, true)',
411
+ 'api.nvim_buf_set_lines(buf, 0, -1, false, lines)',
412
+ 'vim.bo[buf].bufhidden = "wipe"',
413
+ 'vim.bo[buf].modifiable = false',
414
+ 'local ft = vim.filetype.match({ filename = title, buf = buf })',
415
+ 'local lang = ft and vim.treesitter.language.get_lang(ft)',
416
+ 'if lang then pcall(vim.treesitter.start, buf, lang) end',
417
+ 'local cols, rows = vim.o.columns, vim.o.lines',
418
+ 'local width = math.max(20, math.floor(cols * 0.8))',
419
+ 'local height = math.max(3, math.min(math.max(#lines, 1), math.floor(rows * 0.7)))',
420
+ 'local win = api.nvim_open_win(buf, false, { relative = "editor", row = math.floor((rows - height) / 2) - 1, col = math.floor((cols - width) / 2), width = width, height = height, style = "minimal", border = "rounded", title = " " .. vim.fn.fnamemodify(title, ":~:.") .. " ", title_pos = "center", focusable = false, zindex = 200 })',
421
+ 'if line > 0 and #lines > 0 then local target = math.min(line, #lines) api.nvim_win_call(win, function() vim.fn.winrestview({ lnum = target, topline = math.max(1, target - 3) }) end) end',
422
+ 'vim.g.pb_file_preview_win = win',
423
+ 'local group = api.nvim_create_augroup("pb_file_preview", { clear = true })',
424
+ 'api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI", "InsertEnter", "BufLeave" }, { group = group, once = true, callback = function() if api.nvim_win_is_valid(win) then pcall(api.nvim_win_close, win, true) end end })',
425
+ 'return win',
426
+ 'end)(_A)',
427
+ ].join(' ')
428
+
429
+ /** `tab drop` at the line, only while the path is still a regular file: a FIFO swapped in would hang the editor. */
430
+ export const OPEN_LUA = [
431
+ '(function(a)',
432
+ 'local st = vim.uv.fs_lstat(a[1])',
433
+ 'if not st or st.type ~= "file" then return 0 end',
434
+ 'vim.cmd.drop({ args = { vim.fn.fnameescape(a[1]) }, mods = { tab = 1 } })',
435
+ 'if a[2] > 0 then pcall(vim.api.nvim_win_set_cursor, 0, { a[2], 0 }) vim.cmd("normal! zz") end',
436
+ 'return 1',
437
+ 'end)(_A)',
438
+ ].join(' ')
439
+
440
+ const whole = (n: number) => String(Math.max(0, Math.floor(n)))
441
+
442
+ export const floatExpr = (title: string, base64: string, line: number): string =>
443
+ `luaeval(${vimString(FLOAT_LUA)}, [${vimString(title)}, ${vimString(base64.replace(/[^A-Za-z0-9+/=]/g, ''))}, ${whole(line)}])`
444
+
445
+ export const openExpr = (path: string, line: number): string => `luaeval(${vimString(OPEN_LUA)}, [${vimString(path)}, ${whole(line)}])`
446
+
447
+ export const nvimExprArgv = (server: string, expr: string): string[] => ['nvim', '--server', server, '--remote-expr', expr]
448
+
449
+ /** Sockets Neovim makes by default: `nvim.<pid>.0`. */
450
+ export const isDefaultSocketName = (name: string): boolean => /^nvim\.\d+\.0$/.test(name)
451
+
452
+ export type SocketEnv = { TMPDIR?: string; XDG_RUNTIME_DIR?: string; USER?: string }
453
+
454
+ /**
455
+ * Where Neovim's `stdpath("run")` puts default sockets: `<TMPDIR or /tmp>/nvim.$USER/<random>/`
456
+ * (macOS, and Linux without a runtime dir), or `$XDG_RUNTIME_DIR` itself (Linux).
457
+ */
458
+ export const socketDirs = (env: SocketEnv): Array<{ dir: string; nested: boolean }> => {
459
+ const trim = (dir: string) => dir.replace(/\/+$/, '')
460
+ const dirs: Array<{ dir: string; nested: boolean }> = []
461
+ if (env.USER !== undefined && env.USER !== '' && !env.USER.includes('/')) {
462
+ for (const base of [env.TMPDIR, '/tmp']) if (base !== undefined && base !== '') dirs.push({ dir: `${trim(base)}/nvim.${env.USER}`, nested: true })
463
+ }
464
+ if (env.XDG_RUNTIME_DIR !== undefined && env.XDG_RUNTIME_DIR !== '') dirs.push({ dir: trim(env.XDG_RUNTIME_DIR), nested: false })
465
+ return dirs.filter((entry, index) => dirs.findIndex(other => other.dir === entry.dir) === index)
466
+ }
467
+
468
+ export type ServerSearch = {
469
+ explicit?: string
470
+ inherited?: string
471
+ sockets: readonly string[]
472
+ projectDirs: readonly string[]
473
+ cwdOf: (server: string) => Promise<string | undefined>
474
+ }
475
+
476
+ /**
477
+ * Every candidate is asked at once, so the search costs one timeout, not one
478
+ * per socket. Then by rank: `PB_NVIM_SERVER`, `$NVIM`, each used when it
479
+ * answers; then the first default socket whose Neovim's cwd is the project's.
480
+ * A Neovim open on another project never gets a float.
481
+ */
482
+ export const pickServer = async (search: ServerSearch): Promise<string | undefined> => {
483
+ const ranked = [search.explicit, search.inherited].filter((s): s is string => s !== undefined && s !== '' && !isUnsafeSpelling(s))
484
+ const candidates = [...new Set([...ranked, ...search.sockets])]
485
+ const answers = await Promise.all(candidates.map(server => search.cwdOf(server).catch(() => undefined)))
486
+ const cwdOf = new Map(candidates.map((server, i) => [server, answers[i]]))
487
+ for (const server of ranked) if (cwdOf.get(server) !== undefined) return server
488
+ const wanted = new Set(search.projectDirs.map(dir => dir.replace(/\/+$/, '')))
489
+ for (const socket of search.sockets) {
490
+ const cwd = cwdOf.get(socket)
491
+ if (cwd !== undefined && wanted.has(cwd.trim().replace(/\/+$/, ''))) return socket
492
+ }
493
+ return undefined
494
+ }
495
+
496
+ /** Servers that failed recently: skipped until `ttlMs` has passed, so a dead socket costs one timeout, not one per click. */
497
+ export const createFailureMemo = (ttlMs = FAILED_SERVER_TTL_MS) => {
498
+ const failed = new Map<string, number>()
499
+ return {
500
+ isSkipped: (server: string, now: number) => {
501
+ const at = failed.get(server)
502
+ if (at === undefined) return false
503
+ if (now - at < ttlMs) return true
504
+ failed.delete(server)
505
+ return false
506
+ },
507
+ fail: (server: string, now: number) => void failed.set(server, now),
508
+ ok: (server: string) => void failed.delete(server),
509
+ }
510
+ }
511
+
512
+ /** A Map that keeps at most `limit` entries, the oldest written leaving first. */
513
+ export const createBoundedCache = <V>(limit = RENDER_CACHE_LIMIT) => {
514
+ const entries = new Map<string, V>()
515
+ return {
516
+ get: (key: string) => entries.get(key),
517
+ set: (key: string, value: V) => {
518
+ entries.delete(key)
519
+ entries.set(key, value)
520
+ while (entries.size > limit) entries.delete(entries.keys().next().value as string)
521
+ },
522
+ get size() {
523
+ return entries.size
524
+ },
525
+ }
526
+ }
527
+
528
+ /** Plain lines for the pane: tabs as two spaces, control characters dropped, each line cut. */
529
+ export const headLines = (text: string, maxLines = PANE_LINES, maxColumns = PANE_COLUMNS): string[] =>
530
+ text
531
+ .split(/\r?\n/)
532
+ .slice(0, maxLines)
533
+ .map(line => line.replace(/\t/g, ' ').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, maxColumns))
534
+
535
+ export const cacheKey = (real: string, size: number, mtimeMs: number): string => {
536
+ let hash = 0x811c9dc5
537
+ for (const char of `${real}\u0000${size}\u0000${mtimeMs}\u0000${THUMB_MAX_PX}`) {
538
+ hash ^= char.charCodeAt(0)
539
+ hash = Math.imul(hash, 0x01000193)
540
+ }
541
+ return (hash >>> 0).toString(16).padStart(8, '0')
542
+ }
543
+
544
+ /** A private (0700) directory of its own for thumbnails, never a predictable shared name. */
545
+ export const privateDirArgv = (tmp: string | undefined): string[] => ['mktemp', '-d', `${(tmp || '/tmp').replace(/\/+$/, '')}/pb-file-preview.XXXXXX`]
546
+
547
+ export const thumbnailArgv = (kind: 'image' | 'video', real: string, out: string): string[] =>
548
+ kind === 'video'
549
+ ? ['ffmpeg', '-v', 'error', '-ss', '1', '-i', real, '-frames:v', '1', '-vf', `scale='min(${THUMB_MAX_PX},iw)':-2`, '-y', out]
550
+ : ['sips', '-s', 'format', 'png', '-Z', String(THUMB_MAX_PX), real, '--out', out]
551
+
552
+ export type Latest = {
553
+ /**
554
+ * Waits the debounce, then runs `work` only if no newer call came in; the
555
+ * result comes back only while this call is still the newest. `isCurrent`
556
+ * lets work stop between steps.
557
+ */
558
+ run<T>(work: (isCurrent: () => boolean) => Promise<T>): Promise<T | undefined>
559
+ }
560
+
561
+ export const createLatest = (sleep: (ms: number) => Promise<void>, delayMs = DEBOUNCE_MS): Latest => {
562
+ let newest = 0
563
+ return {
564
+ async run(work) {
565
+ const id = ++newest
566
+ await sleep(delayMs)
567
+ if (id !== newest) return undefined
568
+ const isCurrent = () => id === newest
569
+ const result = await work(isCurrent)
570
+ return isCurrent() ? result : undefined
571
+ },
572
+ }
573
+ }
@@ -0,0 +1 @@
1
+ { "modules": ["./register.tsx"] }