layerbase 2.0.1 → 2.2.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 (53) hide show
  1. package/README.md +7 -5
  2. package/dist/cli.js +22 -9
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/tui.js +40 -0
  5. package/dist/commands/tui.js.map +1 -0
  6. package/dist/lib/cloud-api.js +74 -17
  7. package/dist/lib/cloud-api.js.map +1 -1
  8. package/dist/lib/commands.js +5 -0
  9. package/dist/lib/commands.js.map +1 -1
  10. package/dist/tui/action-menu.js +74 -0
  11. package/dist/tui/action-menu.js.map +1 -0
  12. package/dist/tui/actions.js +328 -0
  13. package/dist/tui/actions.js.map +1 -0
  14. package/dist/tui/app.js +750 -0
  15. package/dist/tui/app.js.map +1 -0
  16. package/dist/tui/binary.js +16 -0
  17. package/dist/tui/binary.js.map +1 -0
  18. package/dist/tui/columns.js +126 -0
  19. package/dist/tui/columns.js.map +1 -0
  20. package/dist/tui/detail.js +77 -0
  21. package/dist/tui/detail.js.map +1 -0
  22. package/dist/tui/download-prompt.js +74 -0
  23. package/dist/tui/download-prompt.js.map +1 -0
  24. package/dist/tui/engines.js +57 -0
  25. package/dist/tui/engines.js.map +1 -0
  26. package/dist/tui/form.js +69 -0
  27. package/dist/tui/form.js.map +1 -0
  28. package/dist/tui/keys.js +57 -0
  29. package/dist/tui/keys.js.map +1 -0
  30. package/dist/tui/launch.js +190 -0
  31. package/dist/tui/launch.js.map +1 -0
  32. package/dist/tui/load.js +164 -0
  33. package/dist/tui/load.js.map +1 -0
  34. package/dist/tui/model.js +443 -0
  35. package/dist/tui/model.js.map +1 -0
  36. package/dist/tui/pending.js +26 -0
  37. package/dist/tui/pending.js.map +1 -0
  38. package/dist/tui/ports.js +82 -0
  39. package/dist/tui/ports.js.map +1 -0
  40. package/dist/tui/row-actions.js +101 -0
  41. package/dist/tui/row-actions.js.map +1 -0
  42. package/dist/tui/session.js +108 -0
  43. package/dist/tui/session.js.map +1 -0
  44. package/dist/tui/sidebar.js +77 -0
  45. package/dist/tui/sidebar.js.map +1 -0
  46. package/dist/tui/sign-in-panel.js +84 -0
  47. package/dist/tui/sign-in-panel.js.map +1 -0
  48. package/dist/tui/sign-in.js +144 -0
  49. package/dist/tui/sign-in.js.map +1 -0
  50. package/dist/tui/theme.js +51 -0
  51. package/dist/tui/theme.js.map +1 -0
  52. package/package.json +1 -1
  53. package/skills/layerbase/SKILL.md +5 -5
@@ -0,0 +1,750 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
3
+ import { Box, Text, useInput, useWindowSize } from 'ink';
4
+ import { ACCENT } from '../ui/brand.js';
5
+ import { getVersion } from '../lib/version.js';
6
+ import { copyCloudConnection, copyLocalConnection, createCloudBranch, createCloudDatabase, createLocalBranch, createLocalDatabase, downloadEngine, openCloudPage, openLayerbaseDesktop, setCloudPower, setLocalPower, } from '../tui/actions.js';
7
+ import { findLayerbaseDesktop } from '../tui/launch.js';
8
+ import { engineLabel, LOCAL_ENGINES } from '../tui/engines.js';
9
+ import { FormView } from '../tui/form.js';
10
+ import { loadCloud, loadLocal, loadSession } from '../tui/load.js';
11
+ import { signInWithApiKey, signInWithBrowser } from '../tui/sign-in.js';
12
+ import { ageLabel, childrenOf, connectBlockReason, countGroup, findRow, flattenNodes, frameHeight, groupTitle, keepSelection, moveSelection, rowKey, shortProblem, sidebarLines, sliceLines, statusLabel, } from '../tui/model.js';
13
+ import { ActionMenu } from '../tui/action-menu.js';
14
+ import { DownloadPrompt } from '../tui/download-prompt.js';
15
+ import { Detail } from '../tui/detail.js';
16
+ import { escapeChord, SHORTCUT_GROUPS } from '../tui/keys.js';
17
+ import { pendingColumn, pendingLabel, pendingPhrase, spinFrame, } from '../tui/pending.js';
18
+ import { actionMenu, powerToggle } from '../tui/row-actions.js';
19
+ import { KeyForm, SignInPanel } from '../tui/sign-in-panel.js';
20
+ import { Sidebar } from '../tui/sidebar.js';
21
+ import { anonymousSession, authMethodLabel, canCreateCloud, canWake, sessionBadge, statusBarText, } from '../tui/session.js';
22
+ import { BAD, PANEL, statusColor } from '../tui/theme.js';
23
+ function clip(text, width) {
24
+ if (width <= 0)
25
+ return '';
26
+ if (text.length <= width)
27
+ return text;
28
+ if (width === 1)
29
+ return text.slice(0, 1);
30
+ return `${text.slice(0, width - 1)}~`;
31
+ }
32
+ function ShortcutModal(props) {
33
+ useInput((input, key) => {
34
+ if (input === 'q') {
35
+ props.onQuit();
36
+ return;
37
+ }
38
+ if (key.escape) {
39
+ props.onEscape();
40
+ return;
41
+ }
42
+ if (input === '?')
43
+ props.onClose();
44
+ }, { isActive: true });
45
+ const innerWidth = Math.max(1, props.width - 4);
46
+ const innerHeight = Math.max(1, props.height - 2);
47
+ const lines = [{ key: 'title', kind: 'page', text: 'Shortcuts' }];
48
+ for (const group of SHORTCUT_GROUPS) {
49
+ lines.push({ key: group.title, kind: 'section', text: group.title });
50
+ for (const row of group.rows) {
51
+ lines.push({
52
+ key: `${group.title}:${row.keys}`,
53
+ kind: 'row',
54
+ keys: row.keys.padEnd(12).slice(0, 12),
55
+ text: row.action,
56
+ });
57
+ }
58
+ }
59
+ lines.push({ key: 'close', kind: 'hint', text: 'esc or ? closes' });
60
+ return (_jsx(Box, { flexDirection: "column", height: props.height, width: props.width, borderStyle: "round", borderColor: PANEL, paddingX: 1, children: lines.slice(0, innerHeight).map((line) => (_jsx(Box, { height: 1, width: innerWidth, children: line.kind === 'row' ? (_jsxs(Text, { wrap: "truncate", children: [_jsx(Text, { dimColor: true, children: ` ${line.keys} ` }), _jsx(Text, { children: clip(line.text, Math.max(1, innerWidth - 16)) })] })) : (_jsx(Text, { wrap: "truncate", bold: line.kind === 'page' || line.kind === 'section', color: line.kind === 'page' ? ACCENT : undefined, dimColor: line.kind === 'hint', children: clip(line.text, innerWidth) })) }, line.key))) }));
61
+ }
62
+ function TabStrip(props) {
63
+ const localOn = props.tab === 'local';
64
+ return (_jsx(Box, { width: props.width, height: 1, children: _jsxs(Text, { wrap: "truncate", children: [_jsx(Text, { bold: localOn, color: localOn ? ACCENT : undefined, dimColor: !localOn, children: localOn ? '[Local]' : 'Local' }), _jsx(Text, { dimColor: true, children: ` ${props.localMeta} ` }), _jsx(Text, { bold: !localOn, color: !localOn ? ACCENT : props.cloudAttention ? BAD : undefined, dimColor: localOn && !props.cloudAttention, children: localOn ? 'Cloud' : '[Cloud]' }), _jsx(Text, { color: props.cloudAttention ? BAD : undefined, dimColor: !props.cloudAttention, children: ` ${props.cloudMeta}` })] }) }));
65
+ }
66
+ function HeaderBar(props) {
67
+ const brand = 'layerbase';
68
+ const versionText = ` ${props.version} `;
69
+ const fit = (status, badge) => brand.length +
70
+ versionText.length +
71
+ (status ? status.length + 1 : 0) +
72
+ (badge ? badge.length + 2 : 0);
73
+ let badge = props.badge;
74
+ let status = props.status;
75
+ if (fit(status, badge) > props.width - 8)
76
+ badge = '';
77
+ if (fit(status, badge) > props.width - 4)
78
+ status = '';
79
+ if (fit(status, badge) > props.width) {
80
+ return (_jsx(Box, { height: 1, width: props.width, children: _jsx(Text, { wrap: "truncate", children: clip(`${brand} ${props.version}`, props.width) }) }));
81
+ }
82
+ const name = clip(props.name, props.width - fit(status, badge));
83
+ return (_jsx(Box, { height: 1, width: props.width, children: _jsxs(Text, { wrap: "truncate", children: [_jsx(Text, { bold: true, color: ACCENT, children: brand }), _jsx(Text, { dimColor: true, children: versionText }), _jsx(Text, { bold: true, children: name }), status ? (_jsx(Text, { color: statusColor(status), children: ` ${status}` })) : null, badge ? _jsx(Text, { dimColor: true, children: ` ${badge}` }) : null] }) }));
84
+ }
85
+ export function TuiApp(props) {
86
+ const { columns, rows } = useWindowSize();
87
+ const width = Math.max(columns, 1);
88
+ const height = frameHeight(rows);
89
+ const wide = width >= 100;
90
+ const [session, setSession] = useState(anonymousSession());
91
+ const [local, setLocal] = useState({
92
+ nodes: [],
93
+ error: null,
94
+ });
95
+ const [cloud, setCloud] = useState({
96
+ nodes: [],
97
+ error: null,
98
+ });
99
+ const [loadedAt, setLoadedAt] = useState(null);
100
+ const [now, setNow] = useState(() => Date.now());
101
+ const [tab, setTab] = useState(props.initialSelection?.startsWith('cloud:') ? 'cloud' : 'local');
102
+ const [selected, setSelected] = useState(props.initialSelection);
103
+ const [screen, setScreen] = useState({ kind: 'list' });
104
+ const [signIn, setSignIn] = useState(null);
105
+ const [banner, setBanner] = useState(props.notice);
106
+ const [formError, setFormError] = useState(null);
107
+ const [busy, setBusy] = useState(false);
108
+ const [pending, setPending] = useState(null);
109
+ const [escHint, setEscHint] = useState(false);
110
+ const [desktop, setDesktop] = useState(null);
111
+ const loading = useRef(false);
112
+ const escAt = useRef(0);
113
+ const escTimer = useRef(null);
114
+ const loginLock = useRef(false);
115
+ const downloadJob = useRef(0);
116
+ const sessionRef = useRef(session);
117
+ const indexRef = useRef(0);
118
+ const selectionRef = useRef({
119
+ local: props.initialSelection?.startsWith('cloud:')
120
+ ? null
121
+ : props.initialSelection,
122
+ cloud: props.initialSelection?.startsWith('cloud:')
123
+ ? props.initialSelection
124
+ : null,
125
+ });
126
+ sessionRef.current = session;
127
+ const flat = useMemo(() => flattenNodes(tab === 'local' ? local.nodes : cloud.nodes), [local, cloud, tab]);
128
+ const foundIndex = flat.findIndex((row) => rowKey(row) === selected);
129
+ if (foundIndex >= 0)
130
+ indexRef.current = foundIndex;
131
+ const refreshDatabases = useCallback(async () => {
132
+ if (loading.current)
133
+ return null;
134
+ loading.current = true;
135
+ try {
136
+ const [nextLocal, nextCloud] = await Promise.all([
137
+ loadLocal(),
138
+ loadCloud(sessionRef.current),
139
+ ]);
140
+ setLocal(nextLocal);
141
+ setCloud(nextCloud);
142
+ setLoadedAt(Date.now());
143
+ return { local: nextLocal, cloud: nextCloud };
144
+ }
145
+ finally {
146
+ loading.current = false;
147
+ }
148
+ }, []);
149
+ const refreshAll = useCallback(async () => {
150
+ const next = await loadSession();
151
+ sessionRef.current = next;
152
+ setSession(next);
153
+ await refreshDatabases();
154
+ }, [refreshDatabases]);
155
+ useEffect(() => {
156
+ void refreshAll();
157
+ }, [refreshAll]);
158
+ useEffect(() => {
159
+ let alive = true;
160
+ void findLayerbaseDesktop().then((found) => {
161
+ if (alive)
162
+ setDesktop(found);
163
+ });
164
+ return () => {
165
+ alive = false;
166
+ };
167
+ }, []);
168
+ useEffect(() => {
169
+ if (screen.kind !== 'list' || busy || signIn)
170
+ return;
171
+ const timer = setInterval(() => {
172
+ void refreshDatabases();
173
+ }, 4000);
174
+ return () => clearInterval(timer);
175
+ }, [screen.kind, busy, signIn, refreshDatabases]);
176
+ useEffect(() => {
177
+ const timer = setInterval(() => setNow(Date.now()), pending ? 120 : 1000);
178
+ return () => clearInterval(timer);
179
+ }, [pending]);
180
+ useEffect(() => {
181
+ setSelected((current) => {
182
+ const remembered = selectionRef.current[tab];
183
+ const preferred = current && flat.some((row) => rowKey(row) === current)
184
+ ? current
185
+ : remembered;
186
+ const next = keepSelection(flat, preferred, indexRef.current);
187
+ selectionRef.current[tab] = next;
188
+ return next;
189
+ });
190
+ }, [flat, tab]);
191
+ const selectedRow = findRow(flat, selected);
192
+ const signedOut = session.mode === 'anonymous';
193
+ const cloudLocked = signedOut || Boolean(session.keyRejected);
194
+ const authPanel = tab === 'cloud' && (cloudLocked || signIn !== null);
195
+ async function submitForm(value) {
196
+ if (screen.kind !== 'form')
197
+ return;
198
+ if (!value.name) {
199
+ setFormError('Name is required.');
200
+ return;
201
+ }
202
+ if (screen.engines && !value.engine) {
203
+ setFormError('Pick an engine.');
204
+ return;
205
+ }
206
+ setBusy(true);
207
+ setFormError(null);
208
+ const result = screen.mode === 'local'
209
+ ? await createLocalDatabase({
210
+ name: value.name,
211
+ engine: value.engine ?? 'sqlite',
212
+ })
213
+ : screen.mode === 'cloud'
214
+ ? await createCloudDatabase({
215
+ name: value.name,
216
+ engine: value.engine ?? '',
217
+ })
218
+ : selectedRow?.source === 'cloud'
219
+ ? await createCloudBranch({
220
+ parentId: selectedRow.id,
221
+ name: value.name,
222
+ })
223
+ : await createLocalBranch({
224
+ source: selectedRow?.name ?? '',
225
+ name: value.name,
226
+ });
227
+ setBusy(false);
228
+ if (!result.ok) {
229
+ setFormError(result.message);
230
+ return;
231
+ }
232
+ const createdSource = screen.mode === 'cloud' ||
233
+ (screen.mode === 'branch' && selectedRow?.source === 'cloud')
234
+ ? 'cloud'
235
+ : 'local';
236
+ setScreen({ kind: 'list' });
237
+ setFormError(null);
238
+ const snapshot = await refreshDatabases();
239
+ const created = snapshot
240
+ ? [
241
+ ...flattenNodes(snapshot.local.nodes),
242
+ ...flattenNodes(snapshot.cloud.nodes),
243
+ ].find((row) => row.source === createdSource && row.name === result.name)
244
+ : null;
245
+ if (created)
246
+ setSelected(rowKey(created));
247
+ setBanner(`Created ${result.name}.`);
248
+ setTab(createdSource);
249
+ }
250
+ function showTab(next) {
251
+ selectionRef.current[tab] = selected;
252
+ setTab(next);
253
+ setSelected(selectionRef.current[next]);
254
+ }
255
+ function onEscape() {
256
+ const now = Date.now();
257
+ if (escapeChord({ now, lastAt: escAt.current }) === 'quit') {
258
+ if (escTimer.current)
259
+ clearTimeout(escTimer.current);
260
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
261
+ return;
262
+ }
263
+ escAt.current = now;
264
+ setEscHint(true);
265
+ if (escTimer.current)
266
+ clearTimeout(escTimer.current);
267
+ escTimer.current = setTimeout(() => {
268
+ escAt.current = 0;
269
+ setEscHint(false);
270
+ }, 1000);
271
+ if (screen.kind === 'list' && tab === 'local')
272
+ return;
273
+ setScreen({ kind: 'list' });
274
+ setFormError(null);
275
+ setSignIn((current) => current?.step === 'waiting' || current?.step === 'saving'
276
+ ? current
277
+ : null);
278
+ showTab('local');
279
+ }
280
+ function accessOptions() {
281
+ return {
282
+ paid: canWake(session),
283
+ cloudKey: canCreateCloud(session),
284
+ desktop: desktop !== null,
285
+ };
286
+ }
287
+ function openActions() {
288
+ if (!selectedRow) {
289
+ setBanner('Select a database.');
290
+ return;
291
+ }
292
+ setScreen({ kind: 'actions', index: 0 });
293
+ }
294
+ function connectSelected() {
295
+ if (!selectedRow)
296
+ return;
297
+ const blocked = connectBlockReason(selectedRow);
298
+ if (blocked) {
299
+ setBanner(blocked);
300
+ return;
301
+ }
302
+ const selectKey = rowKey(selectedRow);
303
+ if (selectedRow.source === 'cloud') {
304
+ setTimeout(() => props.onAction({
305
+ type: 'connect-cloud',
306
+ ref: selectedRow.id,
307
+ selectKey,
308
+ }), 0);
309
+ return;
310
+ }
311
+ setTimeout(() => props.onAction({
312
+ type: 'connect-local',
313
+ name: selectedRow.name,
314
+ selectKey,
315
+ }), 0);
316
+ }
317
+ function openBranch() {
318
+ if (!selectedRow)
319
+ return;
320
+ if (selectedRow.parentName) {
321
+ setBanner('Select the parent to branch it.');
322
+ return;
323
+ }
324
+ if (selectedRow.linked) {
325
+ setBanner('Linked databases cannot be branched here.');
326
+ return;
327
+ }
328
+ if (selectedRow.source === 'cloud' && !canCreateCloud(session)) {
329
+ setBanner('Cloud branch needs an API key.');
330
+ return;
331
+ }
332
+ setFormError(null);
333
+ setScreen({ kind: 'form', mode: 'branch', engines: null });
334
+ }
335
+ function localPorts() {
336
+ return flattenNodes(local.nodes)
337
+ .map((item) => Number(item.detail))
338
+ .filter((port) => Number.isInteger(port) && port > 0);
339
+ }
340
+ function localPort(row) {
341
+ const port = Number(row.detail);
342
+ if (!Number.isInteger(port) || port <= 0)
343
+ return null;
344
+ return port;
345
+ }
346
+ function portHolder(row) {
347
+ const port = localPort(row);
348
+ if (!port)
349
+ return null;
350
+ const holder = flattenNodes(local.nodes).find((item) => item.name !== row.name &&
351
+ item.status === 'running' &&
352
+ Number(item.detail) === port);
353
+ return holder?.name ?? null;
354
+ }
355
+ async function runPower(id, options) {
356
+ if (!selectedRow)
357
+ return;
358
+ const row = selectedRow;
359
+ if (row.source === 'local' && id !== 'start' && id !== 'stop') {
360
+ setBanner('Wake and hibernate are cloud actions.');
361
+ return;
362
+ }
363
+ setPending({ key: rowKey(row), verb: id });
364
+ setBanner(pendingPhrase(id, row.name));
365
+ setBusy(true);
366
+ try {
367
+ const result = row.source === 'local'
368
+ ? await setLocalPower({
369
+ name: row.name,
370
+ verb: id === 'stop' ? 'stop' : 'start',
371
+ engine: row.engine,
372
+ port: localPort(row),
373
+ reservedPorts: localPorts(),
374
+ holder: portHolder(row),
375
+ })
376
+ : await setCloudPower({ id: row.id, name: row.name, verb: id });
377
+ setScreen({ kind: 'list' });
378
+ if (!result.ok) {
379
+ if (result.needsBinary &&
380
+ options?.offerDownload !== false &&
381
+ row.version) {
382
+ setFormError(null);
383
+ setScreen({
384
+ kind: 'download',
385
+ name: row.name,
386
+ engine: row.engine,
387
+ version: row.version,
388
+ index: 0,
389
+ });
390
+ setBanner(null);
391
+ return;
392
+ }
393
+ setBanner(result.message);
394
+ return;
395
+ }
396
+ setBanner(result.message ?? `${id} ${result.name}`);
397
+ await refreshDatabases();
398
+ }
399
+ finally {
400
+ setBusy(false);
401
+ setPending(null);
402
+ }
403
+ }
404
+ async function acceptDownload() {
405
+ if (screen.kind !== 'download' || busy)
406
+ return;
407
+ const request = screen;
408
+ const token = downloadJob.current + 1;
409
+ downloadJob.current = token;
410
+ const label = engineLabel(request.engine);
411
+ setBusy(true);
412
+ setFormError(null);
413
+ setBanner(`Downloading ${label} ${request.version}...`);
414
+ const downloaded = await downloadEngine({
415
+ engine: request.engine,
416
+ version: request.version,
417
+ });
418
+ if (downloadJob.current !== token)
419
+ return;
420
+ if (!downloaded.ok) {
421
+ setBusy(false);
422
+ setFormError(downloaded.message);
423
+ setBanner(downloaded.message);
424
+ return;
425
+ }
426
+ setScreen({ kind: 'list' });
427
+ setBusy(false);
428
+ await runPower('start', { offerDownload: false });
429
+ }
430
+ function leaveDownload() {
431
+ downloadJob.current += 1;
432
+ const waiting = busy;
433
+ setBusy(false);
434
+ setBanner(waiting ? 'Stopped waiting. The download may still finish.' : null);
435
+ onEscape();
436
+ }
437
+ async function finishQuiet(result) {
438
+ setBusy(false);
439
+ setScreen({ kind: 'list' });
440
+ if (result.message)
441
+ setBanner(result.message);
442
+ }
443
+ async function copySelected() {
444
+ if (!selectedRow)
445
+ return;
446
+ const row = selectedRow;
447
+ setBusy(true);
448
+ const result = row.source === 'local'
449
+ ? await copyLocalConnection(row.name)
450
+ : await copyCloudConnection({ id: row.id, name: row.name });
451
+ await finishQuiet(result);
452
+ }
453
+ async function openSelectedPage(page) {
454
+ if (!selectedRow)
455
+ return;
456
+ const row = selectedRow;
457
+ setBusy(true);
458
+ const result = await openCloudPage({ id: row.id, name: row.name, page });
459
+ await finishQuiet(result);
460
+ }
461
+ async function openSelectedDesktop() {
462
+ if (!desktop) {
463
+ setBanner('Layerbase Desktop is not installed.');
464
+ setScreen({ kind: 'list' });
465
+ return;
466
+ }
467
+ setBusy(true);
468
+ const result = await openLayerbaseDesktop(desktop);
469
+ await finishQuiet(result);
470
+ }
471
+ function runRowAction(id) {
472
+ if (id === 'connect') {
473
+ connectSelected();
474
+ return;
475
+ }
476
+ if (id === 'branch') {
477
+ openBranch();
478
+ return;
479
+ }
480
+ if (id === 'copy') {
481
+ void copySelected();
482
+ return;
483
+ }
484
+ if (id === 'web') {
485
+ void openSelectedPage('dashboard');
486
+ return;
487
+ }
488
+ if (id === 'query') {
489
+ void openSelectedPage('query');
490
+ return;
491
+ }
492
+ if (id === 'desktop') {
493
+ void openSelectedDesktop();
494
+ return;
495
+ }
496
+ void runPower(id);
497
+ }
498
+ function togglePower() {
499
+ if (!selectedRow) {
500
+ setBanner('Select a database.');
501
+ return;
502
+ }
503
+ const next = powerToggle(selectedRow, accessOptions());
504
+ if ('message' in next) {
505
+ setBanner(next.message);
506
+ return;
507
+ }
508
+ void runPower(next.id);
509
+ }
510
+ function startBrowserSignIn() {
511
+ if (loginLock.current)
512
+ return;
513
+ loginLock.current = true;
514
+ setSignIn({ step: 'waiting', authUrl: '' });
515
+ void signInWithBrowser({
516
+ onWaiting: (authUrl) => setSignIn({ step: 'waiting', authUrl }),
517
+ })
518
+ .then(async (result) => {
519
+ setSignIn({ step: 'saving' });
520
+ await refreshAll();
521
+ setSignIn(null);
522
+ setBanner(result.banner);
523
+ setTab('cloud');
524
+ })
525
+ .catch((error) => {
526
+ const message = error instanceof Error ? error.message : 'Sign-in failed.';
527
+ setSignIn({ step: 'error', message });
528
+ })
529
+ .finally(() => {
530
+ loginLock.current = false;
531
+ });
532
+ }
533
+ function submitApiKey(apiKey) {
534
+ if (!apiKey.trim()) {
535
+ setFormError('Paste the key, then press enter.');
536
+ return;
537
+ }
538
+ setBusy(true);
539
+ setFormError(null);
540
+ void signInWithApiKey(apiKey)
541
+ .then(async (result) => {
542
+ setScreen({ kind: 'list' });
543
+ await refreshAll();
544
+ setBanner(result.banner);
545
+ setTab('cloud');
546
+ })
547
+ .catch((error) => {
548
+ setFormError(error instanceof Error ? error.message : 'The API key was rejected.');
549
+ })
550
+ .finally(() => {
551
+ setBusy(false);
552
+ });
553
+ }
554
+ useInput((input, key) => {
555
+ if (screen.kind !== 'list')
556
+ return;
557
+ if (key.escape) {
558
+ onEscape();
559
+ return;
560
+ }
561
+ if (busy)
562
+ return;
563
+ if (input === 'q') {
564
+ // Unmounting Ink from inside its own key dispatch deadlocks the
565
+ // reconciler, so the handoff waits until this turn finishes.
566
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
567
+ return;
568
+ }
569
+ if (input === '?') {
570
+ setScreen({ kind: 'help' });
571
+ return;
572
+ }
573
+ if (input === 'r') {
574
+ void refreshAll();
575
+ return;
576
+ }
577
+ if (key.tab && key.shift) {
578
+ togglePower();
579
+ return;
580
+ }
581
+ if (key.tab || key.leftArrow || key.rightArrow) {
582
+ showTab(tab === 'local' ? 'cloud' : 'local');
583
+ return;
584
+ }
585
+ if (input === '1') {
586
+ showTab('local');
587
+ return;
588
+ }
589
+ if (input === '2') {
590
+ showTab('cloud');
591
+ return;
592
+ }
593
+ if (key.downArrow || input === 'j') {
594
+ setSelected((current) => moveSelection(flat, current, 1));
595
+ return;
596
+ }
597
+ if (key.upArrow || input === 'k') {
598
+ setSelected((current) => moveSelection(flat, current, -1));
599
+ return;
600
+ }
601
+ if (input === 'g' && !key.shift) {
602
+ const first = flat[0];
603
+ if (first)
604
+ setSelected(rowKey(first));
605
+ return;
606
+ }
607
+ if (input === 'G' || (input === 'g' && key.shift)) {
608
+ const last = flat.at(-1);
609
+ if (last)
610
+ setSelected(rowKey(last));
611
+ return;
612
+ }
613
+ if (input === 'n') {
614
+ setFormError(null);
615
+ setScreen({ kind: 'form', mode: 'local', engines: [...LOCAL_ENGINES] });
616
+ return;
617
+ }
618
+ if (input === 'b') {
619
+ openBranch();
620
+ return;
621
+ }
622
+ if (input === ' ' || key.return) {
623
+ openActions();
624
+ }
625
+ }, { isActive: screen.kind === 'list' && !authPanel });
626
+ const sidebarWidth = wide
627
+ ? Math.min(104, Math.max(64, Math.floor(width * 0.64)))
628
+ : width;
629
+ const sidebarInner = wide ? sidebarWidth - 4 : sidebarWidth;
630
+ const detailWidth = wide ? Math.max(1, width - sidebarWidth - 1) : width;
631
+ const detailInner = wide ? Math.max(1, detailWidth - 4) : detailWidth;
632
+ const boxWidth = authPanel ? width : sidebarWidth;
633
+ const boxInner = authPanel
634
+ ? wide
635
+ ? Math.max(1, width - 4)
636
+ : width
637
+ : sidebarInner;
638
+ const activeNodes = tab === 'local' ? local.nodes : cloud.nodes;
639
+ const lines = sidebarLines({
640
+ nodes: activeNodes,
641
+ empty: tab === 'local'
642
+ ? 'No local databases. n to create one.'
643
+ : 'No cloud databases yet.',
644
+ error: tab === 'local'
645
+ ? shortProblem(local.error)
646
+ : cloudLocked
647
+ ? null
648
+ : shortProblem(cloud.error),
649
+ width: boxInner,
650
+ });
651
+ const maxBody = Math.max(1, height - 2);
652
+ const detailBudget = wide
653
+ ? Math.max(1, maxBody - 2)
654
+ : Math.min(8, Math.max(1, Math.floor(maxBody / 2)));
655
+ const listBudget = wide
656
+ ? Math.max(1, maxBody - 4)
657
+ : Math.max(1, maxBody - detailBudget - 3);
658
+ const visibleLines = sliceLines(lines, selected, listBudget);
659
+ const localMeta = groupTitle('Local', countGroup(local.nodes)).replace(/^Local\s*/, '');
660
+ const cloudMeta = cloudLocked
661
+ ? 'sign in'
662
+ : groupTitle('Cloud', countGroup(cloud.nodes)).replace(/^Cloud\s*/, '');
663
+ const childNodes = selectedRow?.parentName
664
+ ? []
665
+ : childrenOf(selectedRow?.source === 'cloud' ? cloud.nodes : local.nodes, selected);
666
+ const index = flat.findIndex((row) => rowKey(row) === selected);
667
+ const badge = sessionBadge(session);
668
+ const headerName = authPanel ? 'cloud' : (selectedRow?.name ?? 'databases');
669
+ const onPendingRow = pending !== null &&
670
+ selectedRow !== null &&
671
+ rowKey(selectedRow) === pending.key;
672
+ const pendingView = pending
673
+ ? {
674
+ key: pending.key,
675
+ status: pendingLabel(pending.verb),
676
+ column: pendingColumn(pending.verb),
677
+ mark: spinFrame(now),
678
+ }
679
+ : null;
680
+ const headerStatus = authPanel || !selectedRow
681
+ ? ''
682
+ : onPendingRow && pendingView
683
+ ? pendingView.status
684
+ : statusLabel(selectedRow);
685
+ const neighbor = !authPanel && selectedRow ? `${index + 1}/${flat.length}` : null;
686
+ const footer = statusBarText({
687
+ auth: authMethodLabel(session),
688
+ escHint,
689
+ banner,
690
+ age: ageLabel(loadedAt, now),
691
+ width,
692
+ });
693
+ let main = (_jsxs(Box, { flexDirection: wide ? 'row' : 'column', alignItems: "flex-start", width: width, height: maxBody, children: [_jsxs(Box, { width: boxWidth, height: wide ? maxBody : undefined, flexDirection: "column", borderStyle: wide ? 'round' : undefined, borderColor: wide ? PANEL : undefined, paddingX: wide ? 1 : 0, children: [_jsx(TabStrip, { tab: tab, localMeta: localMeta, cloudMeta: cloudMeta, cloudAttention: cloudLocked, width: boxInner }), authPanel ? (_jsx(SignInPanel, { width: boxInner, maxLines: listBudget, reason: signedOut ? 'signed-out' : 'rejected', keyFromEnv: session.keyFromEnv, step: signIn?.step ?? 'choose', authUrl: signIn?.step === 'waiting' ? signIn.authUrl : null, error: signIn?.step === 'error' ? signIn.message : null, onBrowser: startBrowserSignIn, onPaste: () => {
694
+ setFormError(null);
695
+ setScreen({ kind: 'key' });
696
+ }, onBack: () => {
697
+ if (signIn?.step === 'error')
698
+ setSignIn(null);
699
+ showTab('local');
700
+ }, onEscape: onEscape, onQuit: () => {
701
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
702
+ } })) : (_jsx(Sidebar, { lines: visibleLines, selectedKey: selected, width: boxInner, pending: pendingView
703
+ ? {
704
+ key: pendingView.key,
705
+ status: pendingView.column,
706
+ mark: pendingView.mark,
707
+ }
708
+ : null }))] }), wide && !authPanel ? _jsx(Text, { children: " " }) : null, authPanel ? null : (_jsx(Box, { width: detailWidth, height: wide ? maxBody : undefined, flexDirection: "column", borderStyle: wide ? 'round' : undefined, borderColor: wide ? PANEL : undefined, paddingX: wide ? 1 : 0, children: _jsx(Detail, { row: selectedRow, children: childNodes, width: detailInner, maxLines: detailBudget, pending: onPendingRow && pendingView
709
+ ? { status: pendingView.status, mark: pendingView.mark }
710
+ : null }) }))] }));
711
+ if (screen.kind === 'actions' && selectedRow) {
712
+ const menu = actionMenu(selectedRow, accessOptions());
713
+ const index = Math.min(screen.index, Math.max(menu.actions.length - 1, 0));
714
+ const menuLines = 2 + menu.actions.length + (menu.note ? 1 : 0) + (busy ? 1 : 0);
715
+ main = (_jsx(Box, { width: width, height: maxBody, flexDirection: "column", children: _jsx(ActionMenu, { title: selectedRow.name, actions: menu.actions, note: menu.note, index: index, width: width, height: Math.min(maxBody, menuLines + 2), busy: busy, busyLabel: pending ? pendingPhrase(pending.verb, selectedRow.name) : null, onMove: (next) => setScreen({ kind: 'actions', index: next }), onRun: () => {
716
+ const action = menu.actions[index];
717
+ if (action)
718
+ runRowAction(action.id);
719
+ }, onEscape: onEscape, onQuit: () => {
720
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
721
+ } }) }));
722
+ }
723
+ else if (screen.kind === 'help') {
724
+ main = (_jsx(ShortcutModal, { height: maxBody, width: width, onClose: () => setScreen({ kind: 'list' }), onEscape: onEscape, onQuit: () => {
725
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
726
+ } }));
727
+ }
728
+ else if (screen.kind === 'download') {
729
+ main = (_jsx(Box, { width: width, height: maxBody, flexDirection: "column", children: _jsx(DownloadPrompt, { engine: screen.engine, version: screen.version, name: screen.name, index: screen.index, width: width, busy: busy, busyLabel: banner, error: formError, onMove: (index) => setScreen({ ...screen, index }), onAccept: () => {
730
+ void acceptDownload();
731
+ }, onDecline: leaveDownload, onEscape: leaveDownload, onQuit: () => {
732
+ setTimeout(() => props.onAction({ type: 'quit' }), 0);
733
+ } }) }));
734
+ }
735
+ else if (screen.kind === 'key') {
736
+ main = (_jsx(KeyForm, { width: width, height: Math.min(8, maxBody), error: formError, busy: busy, onCancel: onEscape, onSubmit: submitApiKey }));
737
+ }
738
+ else if (screen.kind === 'form') {
739
+ const title = screen.mode === 'local'
740
+ ? 'New local database'
741
+ : screen.mode === 'cloud'
742
+ ? 'New cloud database'
743
+ : `Branch ${selectedRow?.name ?? ''}`;
744
+ main = (_jsx(FormView, { title: title, engines: screen.engines, error: formError, busy: busy, height: Math.min(6, maxBody), width: width, onCancel: onEscape, onSubmit: (value) => {
745
+ void submitForm(value);
746
+ } }));
747
+ }
748
+ return (_jsxs(Box, { flexDirection: "column", width: width, height: height, children: [_jsx(HeaderBar, { width: width, version: getVersion(), name: headerName, status: headerStatus, badge: [badge, neighbor].filter(Boolean).join(' ') }), main, _jsx(Box, { height: 1, width: width, children: _jsx(Text, { dimColor: true, children: footer || ' ' }) })] }));
749
+ }
750
+ //# sourceMappingURL=app.js.map