neonctl 2.37.0 → 2.38.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 (160) hide show
  1. package/{LICENSE.md → LICENSE} +27 -3
  2. package/README.md +15 -700
  3. package/bin/cli.js +3 -0
  4. package/package.json +8 -75
  5. package/dist/analytics.js +0 -168
  6. package/dist/api.js +0 -720
  7. package/dist/auth.js +0 -125
  8. package/dist/callback.html +0 -51
  9. package/dist/cli.js +0 -9
  10. package/dist/commands/api.js +0 -278
  11. package/dist/commands/auth.js +0 -214
  12. package/dist/commands/bootstrap.js +0 -481
  13. package/dist/commands/branches.js +0 -488
  14. package/dist/commands/bucket.js +0 -549
  15. package/dist/commands/checkout.js +0 -321
  16. package/dist/commands/config.js +0 -626
  17. package/dist/commands/connection_string.js +0 -172
  18. package/dist/commands/data_api.js +0 -284
  19. package/dist/commands/databases.js +0 -82
  20. package/dist/commands/deploy.js +0 -26
  21. package/dist/commands/dev.js +0 -698
  22. package/dist/commands/diff.js +0 -222
  23. package/dist/commands/env.js +0 -189
  24. package/dist/commands/functions.js +0 -373
  25. package/dist/commands/index.js +0 -62
  26. package/dist/commands/init.js +0 -73
  27. package/dist/commands/inspect.js +0 -65
  28. package/dist/commands/ip_allow.js +0 -137
  29. package/dist/commands/link.js +0 -1121
  30. package/dist/commands/neon_auth.js +0 -1028
  31. package/dist/commands/operations.js +0 -28
  32. package/dist/commands/orgs.js +0 -24
  33. package/dist/commands/projects.js +0 -413
  34. package/dist/commands/psql.js +0 -62
  35. package/dist/commands/roles.js +0 -65
  36. package/dist/commands/schema_diff.js +0 -151
  37. package/dist/commands/set_context.js +0 -29
  38. package/dist/commands/snapshots.js +0 -455
  39. package/dist/commands/status.js +0 -40
  40. package/dist/commands/user.js +0 -15
  41. package/dist/commands/vpc_endpoints.js +0 -134
  42. package/dist/config.js +0 -11
  43. package/dist/config_format.js +0 -72
  44. package/dist/context.js +0 -231
  45. package/dist/current_branch_fast_path.js +0 -55
  46. package/dist/dev/env.js +0 -244
  47. package/dist/dev/functions.js +0 -70
  48. package/dist/dev/inputs.js +0 -63
  49. package/dist/dev/runtime.js +0 -146
  50. package/dist/env.js +0 -36
  51. package/dist/env_file.js +0 -159
  52. package/dist/errors.js +0 -80
  53. package/dist/functions_api.js +0 -48
  54. package/dist/help.js +0 -146
  55. package/dist/index.js +0 -240
  56. package/dist/log.js +0 -18
  57. package/dist/parameters.gen.js +0 -480
  58. package/dist/pkg.js +0 -25
  59. package/dist/psql/cli.js +0 -53
  60. package/dist/psql/command/cmd_cond.js +0 -437
  61. package/dist/psql/command/cmd_connect.js +0 -820
  62. package/dist/psql/command/cmd_copy.js +0 -1035
  63. package/dist/psql/command/cmd_describe.js +0 -1815
  64. package/dist/psql/command/cmd_format.js +0 -948
  65. package/dist/psql/command/cmd_io.js +0 -2193
  66. package/dist/psql/command/cmd_lo.js +0 -393
  67. package/dist/psql/command/cmd_meta.js +0 -969
  68. package/dist/psql/command/cmd_misc.js +0 -187
  69. package/dist/psql/command/cmd_pipeline.js +0 -1148
  70. package/dist/psql/command/cmd_restrict.js +0 -171
  71. package/dist/psql/command/cmd_show.js +0 -766
  72. package/dist/psql/command/dispatch.js +0 -343
  73. package/dist/psql/command/inputQueue.js +0 -42
  74. package/dist/psql/command/shared.js +0 -71
  75. package/dist/psql/complete/filenames.js +0 -139
  76. package/dist/psql/complete/index.js +0 -104
  77. package/dist/psql/complete/matcher.js +0 -315
  78. package/dist/psql/complete/psqlVars.js +0 -249
  79. package/dist/psql/complete/queries.js +0 -493
  80. package/dist/psql/complete/rules.js +0 -2424
  81. package/dist/psql/core/common.js +0 -1253
  82. package/dist/psql/core/help.js +0 -576
  83. package/dist/psql/core/mainloop.js +0 -1360
  84. package/dist/psql/core/prompt.js +0 -439
  85. package/dist/psql/core/settings.js +0 -686
  86. package/dist/psql/core/sqlHelp.js +0 -1066
  87. package/dist/psql/core/startup.js +0 -846
  88. package/dist/psql/core/syncVars.js +0 -116
  89. package/dist/psql/core/variables.js +0 -287
  90. package/dist/psql/describe/formatters.js +0 -1330
  91. package/dist/psql/describe/processNamePattern.js +0 -270
  92. package/dist/psql/describe/queries.js +0 -2452
  93. package/dist/psql/describe/versionGate.js +0 -44
  94. package/dist/psql/index.js +0 -2030
  95. package/dist/psql/io/history.js +0 -299
  96. package/dist/psql/io/input.js +0 -120
  97. package/dist/psql/io/lineEditor/buffer.js +0 -325
  98. package/dist/psql/io/lineEditor/complete.js +0 -227
  99. package/dist/psql/io/lineEditor/filename.js +0 -159
  100. package/dist/psql/io/lineEditor/index.js +0 -893
  101. package/dist/psql/io/lineEditor/keymap.js +0 -745
  102. package/dist/psql/io/lineEditor/vt100.js +0 -363
  103. package/dist/psql/io/pgpass.js +0 -202
  104. package/dist/psql/io/pgservice.js +0 -194
  105. package/dist/psql/io/psqlrc.js +0 -422
  106. package/dist/psql/print/aligned.js +0 -1748
  107. package/dist/psql/print/asciidoc.js +0 -230
  108. package/dist/psql/print/crosstab.js +0 -463
  109. package/dist/psql/print/csv.js +0 -76
  110. package/dist/psql/print/html.js +0 -240
  111. package/dist/psql/print/json.js +0 -96
  112. package/dist/psql/print/latex.js +0 -379
  113. package/dist/psql/print/pager.js +0 -267
  114. package/dist/psql/print/troff.js +0 -240
  115. package/dist/psql/print/unaligned.js +0 -99
  116. package/dist/psql/print/units.js +0 -188
  117. package/dist/psql/scanner/slash.js +0 -515
  118. package/dist/psql/scanner/sql.js +0 -914
  119. package/dist/psql/scanner/stringutils.js +0 -394
  120. package/dist/psql/types/backslash.js +0 -1
  121. package/dist/psql/types/connection.js +0 -1
  122. package/dist/psql/types/index.js +0 -7
  123. package/dist/psql/types/printer.js +0 -1
  124. package/dist/psql/types/repl.js +0 -1
  125. package/dist/psql/types/scanner.js +0 -24
  126. package/dist/psql/types/settings.js +0 -1
  127. package/dist/psql/types/variables.js +0 -1
  128. package/dist/psql/wire/connection.js +0 -2857
  129. package/dist/psql/wire/copy.js +0 -108
  130. package/dist/psql/wire/notify.js +0 -59
  131. package/dist/psql/wire/pipeline.js +0 -521
  132. package/dist/psql/wire/protocol.js +0 -466
  133. package/dist/psql/wire/sasl.js +0 -294
  134. package/dist/psql/wire/tls.js +0 -602
  135. package/dist/storage_api.js +0 -147
  136. package/dist/test_utils/fixtures.js +0 -121
  137. package/dist/test_utils/oauth_server.js +0 -9
  138. package/dist/types.js +0 -1
  139. package/dist/utils/ai_gateway_notice.js +0 -180
  140. package/dist/utils/api_enums.js +0 -33
  141. package/dist/utils/auth.js +0 -5
  142. package/dist/utils/branch_notice.js +0 -22
  143. package/dist/utils/branch_picker.js +0 -103
  144. package/dist/utils/compute_units.js +0 -28
  145. package/dist/utils/config_diff.js +0 -185
  146. package/dist/utils/enrichers.js +0 -161
  147. package/dist/utils/esbuild.js +0 -158
  148. package/dist/utils/formats.js +0 -18
  149. package/dist/utils/git_diff.js +0 -90
  150. package/dist/utils/inspect_db.js +0 -153
  151. package/dist/utils/inspect_queries.js +0 -372
  152. package/dist/utils/middlewares.js +0 -20
  153. package/dist/utils/openapi.js +0 -114
  154. package/dist/utils/package_manager.js +0 -68
  155. package/dist/utils/point_in_time.js +0 -56
  156. package/dist/utils/psql.js +0 -120
  157. package/dist/utils/string.js +0 -5
  158. package/dist/utils/ui.js +0 -59
  159. package/dist/utils/zip.js +0 -4
  160. package/dist/writer.js +0 -97
@@ -1,893 +0,0 @@
1
- /**
2
- * Public-facing line editor.
3
- *
4
- * Glues the streaming VT100 decoder, the keymap, the line buffer, and
5
- * the completion engine into a `readLine(prompt)` Promise-returning API.
6
- *
7
- * Architecture
8
- * ------------
9
- *
10
- * stdin (raw mode)
11
- * │ bytes
12
- * ▼
13
- * Vt100Decoder ─── KeyEvent[]
14
- * │
15
- * ▼
16
- * dispatch(state, ev) ─── EditorAction
17
- * │
18
- * ▼
19
- * render(prompt, state, stdout) (CSI writes)
20
- * │
21
- * └── on submit: resolve readLine() with state.buffer.text
22
- * └── on ^C: reject with SignalError
23
- * └── on ^D: resolve with EOF symbol
24
- *
25
- * Rendering strategy
26
- * ------------------
27
- *
28
- * Naive but robust: track the number of rows last drawn, on every
29
- * redraw move the cursor up to the prompt's anchor row and rewrite the
30
- * whole `prompt + buffer.text` block. This avoids per-keystroke diffing
31
- * bugs at the cost of a few extra bytes per keystroke. For the
32
- * ~80-char lines users actually type interactively this is invisible.
33
- *
34
- * Wrapping uses the inlined `displayWidth` (port of WP-09's table) so
35
- * East-Asian wide characters and zero-width combining marks render
36
- * correctly. We never call `stdout.write` with embedded `\n`; line
37
- * breaks come from explicit `\r\n` only on submit or when we need to
38
- * display multi-row output (paste-mode newlines, candidate listings).
39
- */
40
- import { LineBuffer } from "./buffer.js";
41
- import { CompletionState, formatCandidates, } from "./complete.js";
42
- import { dispatch, makeState, } from "./keymap.js";
43
- import { BEL, CR, csiClearScreen, csiDown, csiEraseToEol, csiLeft, csiRight, csiUp, disableBracketedPaste, enableBracketedPaste, LF, Vt100Decoder, } from "./vt100.js";
44
- /** Thrown when ^C cancels the current line. */
45
- export class SignalError extends Error {
46
- constructor() {
47
- super("SIGINT");
48
- this.name = "SignalError";
49
- this.signal = "SIGINT";
50
- }
51
- }
52
- /**
53
- * Sentinel for "Ctrl-D on an empty line". Compared with `===` by callers
54
- * so we don't accidentally match a literal string.
55
- */
56
- const EOF_SYMBOL = Symbol("LineEditor.EOF");
57
- export class LineEditor {
58
- constructor(opts = {}) {
59
- this.EOF = EOF_SYMBOL;
60
- /**
61
- * Pending mode change requested via `setMode()`. Applied at the next
62
- * `readLine()` boundary so an in-flight line keeps its current dispatch
63
- * (mirrors upstream readline's "next prompt" semantics for `set
64
- * editing-mode`).
65
- */
66
- this.pendingMode = null;
67
- this.completion = new CompletionState();
68
- /** Event queue; processed serially so async completion blocks subsequent keys. */
69
- this.eventQueue = [];
70
- this.processing = false;
71
- /** Active readLine, if any. */
72
- this.active = null;
73
- /** Listeners attached to stdin while readLine is active. */
74
- this.dataListener = null;
75
- this.wasRaw = false;
76
- /** TTY state restoration handlers. */
77
- this.exitListener = null;
78
- this.stdin = opts.stdin ?? process.stdin;
79
- this.stdout = opts.stdout ?? process.stdout;
80
- this.bracketedPaste = opts.bracketedPaste ?? true;
81
- this.completer = opts.completer;
82
- this.mode = opts.mode ?? "emacs";
83
- this.state = makeState(opts.history ?? [], this.mode === "vi" ? "insert" : "emacs");
84
- this.decoder = new Vt100Decoder({
85
- // LineEditor default: 50ms matches GNU readline's `keyseq-timeout`
86
- // default — enough to disambiguate Alt-X across all modern terminals
87
- // without making bare Esc noticeably laggy. Callers can override (or
88
- // set 0 to restore the legacy "emit Esc immediately" behaviour).
89
- escTimeoutMs: opts.escTimeoutMs ?? 50,
90
- onTimeoutEvent: (ev) => {
91
- this.handleDecoderTimeout(ev);
92
- },
93
- });
94
- }
95
- /** Read one line. Resolves on Enter; rejects on Ctrl-C. */
96
- readLine(prompt) {
97
- if (this.active !== null) {
98
- return Promise.reject(new Error("LineEditor.readLine called re-entrantly"));
99
- }
100
- // Apply any pending setMode() request at this readLine boundary so an
101
- // in-flight line keeps its prior dispatch.
102
- if (this.pendingMode !== null) {
103
- this.mode = this.pendingMode;
104
- this.pendingMode = null;
105
- }
106
- return new Promise((resolve, reject) => {
107
- // Fresh buffer for the new prompt.
108
- this.state.buffer = new LineBuffer();
109
- this.state.historyIndex = -1;
110
- this.state.liveSnapshot = null;
111
- // Switch state.mode to match the editor mode: vi → start in 'insert',
112
- // emacs → 'emacs'. This must happen on every readLine so a mid-session
113
- // VI_MODE flip is observed (the state machine has its own per-line
114
- // mode field that needs to be reset).
115
- if (this.mode === "vi") {
116
- this.state.mode = "insert";
117
- this.state.viPending = null;
118
- }
119
- else {
120
- this.state.mode = "emacs";
121
- this.state.viPending = null;
122
- this.state.exBuffer = "";
123
- }
124
- this.completion.reset();
125
- this.active = {
126
- prompt,
127
- resolve,
128
- reject,
129
- rowsDrawn: 0,
130
- cursorRow: 0,
131
- cursorCol: 0,
132
- search: null,
133
- listingRowsDrawn: 0,
134
- };
135
- try {
136
- this.enterRaw();
137
- }
138
- catch (err) {
139
- this.active = null;
140
- reject(err);
141
- return;
142
- }
143
- this.render();
144
- // If a previous readLine submitted mid-chunk and left residual key
145
- // events queued (e.g. the user pasted `analyze (\n\t\t` — after the
146
- // `\n` triggered submit, the `\t\t` was already decoded but sat in
147
- // `eventQueue` because `active` had been nulled), drain them now
148
- // against the new line buffer. Mirrors readline's natural behaviour
149
- // of carrying buffered input across the line boundary.
150
- if (this.eventQueue.length > 0)
151
- void this.drainQueue();
152
- });
153
- }
154
- /** Force redraw (call from SIGWINCH handler). */
155
- redraw() {
156
- if (this.active !== null)
157
- this.render(true);
158
- }
159
- /**
160
- * Inject an out-of-band line into the terminal while a prompt is being
161
- * edited. Used by callers that produce async output (NOTIFY messages,
162
- * notices, etc.) that would otherwise clobber the prompt rendering.
163
- *
164
- * Behaviour:
165
- * - No active readLine: pass-through to stdout.
166
- * - Active readLine: move cursor to end-of-block, write a fresh newline
167
- * so the injected text starts on its own row, write the text, then
168
- * redraw the prompt + buffer below it (re-attaching the cursor).
169
- *
170
- * The injected text should NOT have a trailing newline — we add one as
171
- * part of the move-to-end + LF dance. If the caller's payload already
172
- * ends with `\n`, we strip it once.
173
- */
174
- interject(text) {
175
- if (this.active === null) {
176
- this.stdout.write(text);
177
- return;
178
- }
179
- const a = this.active;
180
- this.moveCursorToEnd();
181
- this.stdout.write(LF);
182
- const body = text.endsWith("\n") ? text.slice(0, -1) : text;
183
- this.stdout.write(body);
184
- this.stdout.write(LF);
185
- // Reset drawn-state so render() lays out a fresh block under the
186
- // injected text instead of trying to overwrite the area we just used.
187
- a.rowsDrawn = 0;
188
- a.cursorRow = 0;
189
- a.cursorCol = 0;
190
- // Interjected text overwrites any candidate listing that was on screen.
191
- a.listingRowsDrawn = 0;
192
- this.render(true);
193
- }
194
- /** Cleanup raw mode and restore TTY. Idempotent. */
195
- close() {
196
- this.exitRaw();
197
- }
198
- /**
199
- * Request a switch between vi and emacs editing modes. The change takes
200
- * effect at the NEXT `readLine()` boundary, not retroactively on the line
201
- * currently being edited — matching upstream readline's `set editing-mode`
202
- * semantics. Calling this with the currently-active mode is a no-op.
203
- */
204
- setMode(mode) {
205
- this.pendingMode = mode;
206
- }
207
- /** Read the editor's currently effective mode. Exposed for tests. */
208
- getMode() {
209
- return this.mode;
210
- }
211
- /** Push a line into the in-memory history. */
212
- pushHistory(line) {
213
- if (line.length === 0)
214
- return;
215
- const last = this.state.history[this.state.history.length - 1];
216
- if (last === line)
217
- return;
218
- this.state.history.push(line);
219
- }
220
- /** Replace the in-memory history list. */
221
- setHistory(lines) {
222
- this.state.history = lines.slice();
223
- this.state.historyIndex = -1;
224
- this.state.liveSnapshot = null;
225
- }
226
- // -------------------------------------------------------------------------
227
- // I/O wiring
228
- // -------------------------------------------------------------------------
229
- enterRaw() {
230
- const s = this.stdin;
231
- if (isTtyReadStream(s)) {
232
- this.wasRaw = Boolean(s.isRaw);
233
- s.setRawMode(true);
234
- }
235
- s.resume();
236
- this.decoder.reset();
237
- if (this.bracketedPaste)
238
- this.stdout.write(enableBracketedPaste());
239
- this.dataListener = (chunk) => {
240
- this.handleChunk(chunk);
241
- };
242
- s.on("data", this.dataListener);
243
- if (!this.exitListener) {
244
- this.exitListener = () => {
245
- this.exitRaw();
246
- };
247
- process.once("exit", this.exitListener);
248
- process.once("SIGTERM", this.exitListener);
249
- }
250
- }
251
- exitRaw() {
252
- const s = this.stdin;
253
- if (this.dataListener !== null) {
254
- s.off("data", this.dataListener);
255
- this.dataListener = null;
256
- }
257
- if (isTtyReadStream(s) && !this.wasRaw) {
258
- try {
259
- s.setRawMode(false);
260
- }
261
- catch {
262
- /* ignore */
263
- }
264
- }
265
- if (this.bracketedPaste) {
266
- try {
267
- this.stdout.write(disableBracketedPaste());
268
- }
269
- catch {
270
- /* ignore */
271
- }
272
- }
273
- if (this.exitListener !== null) {
274
- process.off("exit", this.exitListener);
275
- process.off("SIGTERM", this.exitListener);
276
- this.exitListener = null;
277
- }
278
- }
279
- // -------------------------------------------------------------------------
280
- // Chunk processing
281
- // -------------------------------------------------------------------------
282
- handleChunk(chunk) {
283
- if (this.active === null)
284
- return;
285
- const events = this.decoder.push(new Uint8Array(chunk));
286
- for (const ev of events)
287
- this.eventQueue.push(ev);
288
- void this.drainQueue();
289
- }
290
- /** Called when the decoder's bare-Esc timer fires with a buffered event. */
291
- handleDecoderTimeout(ev) {
292
- if (this.active === null)
293
- return;
294
- this.eventQueue.push(ev);
295
- void this.drainQueue();
296
- }
297
- /**
298
- * Serially drain the event queue. Each event may kick off async work
299
- * (notably Tab completion); we await it before processing the next
300
- * event so keystrokes don't race ahead of pending completion results.
301
- */
302
- async drainQueue() {
303
- if (this.processing)
304
- return;
305
- this.processing = true;
306
- try {
307
- while (this.eventQueue.length > 0 && this.active !== null) {
308
- const ev = this.eventQueue.shift();
309
- if (ev === undefined)
310
- break;
311
- await this.handleEvent(ev);
312
- }
313
- }
314
- finally {
315
- this.processing = false;
316
- }
317
- }
318
- async handleEvent(ev) {
319
- if (this.active === null)
320
- return;
321
- const a = this.active;
322
- // Search mode handling is local: events go into the search state machine
323
- // instead of the keymap.
324
- if (a.search !== null) {
325
- await this.handleSearchKey(ev);
326
- return;
327
- }
328
- const action = dispatch(this.state, ev);
329
- await this.applyAction(action, ev);
330
- }
331
- /**
332
- * Reset the completion engine and forget any listing geometry: the next Tab
333
- * will request a fresh result, and the next `list` / `cycled` will emit a
334
- * new block on a fresh row instead of trying to overwrite a stale listing
335
- * whose coordinates are no longer valid.
336
- */
337
- resetCompletion() {
338
- this.completion.reset();
339
- if (this.active !== null)
340
- this.active.listingRowsDrawn = 0;
341
- }
342
- async applyAction(action, ev) {
343
- if (this.active === null)
344
- return;
345
- const a = this.active;
346
- switch (action.kind) {
347
- case "noop":
348
- return;
349
- case "redraw":
350
- this.resetCompletion();
351
- this.render();
352
- return;
353
- case "bell":
354
- this.stdout.write(BEL);
355
- return;
356
- case "submit": {
357
- this.resetCompletion();
358
- const text = this.state.buffer.text;
359
- // Move cursor past the end of the rendered block and emit a newline.
360
- this.moveCursorToEnd();
361
- this.stdout.write(LF);
362
- const resolve = a.resolve;
363
- this.active = null;
364
- this.exitRaw();
365
- resolve(text);
366
- return;
367
- }
368
- case "cancel": {
369
- // Upstream psql doesn't echo `^C` to the screen on Ctrl-C — it just
370
- // breaks to the next prompt line silently. Match that behaviour.
371
- this.resetCompletion();
372
- this.moveCursorToEnd();
373
- this.stdout.write(LF);
374
- const reject = a.reject;
375
- this.active = null;
376
- this.exitRaw();
377
- reject(new SignalError());
378
- return;
379
- }
380
- case "eof": {
381
- this.resetCompletion();
382
- this.moveCursorToEnd();
383
- this.stdout.write(LF);
384
- const resolve = a.resolve;
385
- this.active = null;
386
- this.exitRaw();
387
- resolve(EOF_SYMBOL);
388
- return;
389
- }
390
- case "complete": {
391
- if (!this.completer) {
392
- this.stdout.write(BEL);
393
- return;
394
- }
395
- await this.runCompletion();
396
- return;
397
- }
398
- case "clear-screen":
399
- this.resetCompletion();
400
- this.stdout.write(csiClearScreen());
401
- a.rowsDrawn = 0;
402
- a.cursorRow = 0;
403
- a.cursorCol = 0;
404
- this.render(true);
405
- return;
406
- case "search-start":
407
- this.resetCompletion();
408
- a.search = {
409
- pattern: "",
410
- matchIndex: null,
411
- savedBuffer: this.state.buffer.text,
412
- };
413
- this.render();
414
- return;
415
- case "paste-start":
416
- case "paste-end":
417
- // Bracketed paste markers are otherwise transparent.
418
- void ev;
419
- return;
420
- case "ex-update":
421
- // Vi `:`-ex prompt text changed (entered/typed/backspaced). The
422
- // renderer reads `state.mode === 'ex'` and swaps in a `: <buf>` line.
423
- this.resetCompletion();
424
- this.render();
425
- return;
426
- }
427
- }
428
- // -------------------------------------------------------------------------
429
- // Completion
430
- // -------------------------------------------------------------------------
431
- async runCompletion() {
432
- if (this.completer === undefined || this.active === null)
433
- return;
434
- const step = await this.completion.apply(this.state.buffer, this.completer);
435
- if (this.active === null)
436
- return;
437
- switch (step.kind) {
438
- case "bell":
439
- this.stdout.write(BEL);
440
- return;
441
- case "inserted":
442
- this.render();
443
- return;
444
- case "cycled": {
445
- // In-place rewrite of the candidate listing with the new highlight.
446
- // If we already have a listing on screen (placed above the current
447
- // prompt block by an earlier `list` or `cycled`), navigate up to its
448
- // first row, erase each row, and reprint with the cycled highlight.
449
- // Otherwise fall back to the "print listing below" path, matching
450
- // first-time `list` behaviour.
451
- const cands = this.completion.getCandidates();
452
- const cycleIndex = this.completion.getCycleIndex();
453
- if (cands.length > 0) {
454
- const w = this.termWidth();
455
- const block = formatCandidates(cands, w, cycleIndex);
456
- const blockRows = block.split("\n").length;
457
- if (this.active.listingRowsDrawn > 0) {
458
- this.rewriteListingInPlace(block, blockRows);
459
- }
460
- else {
461
- this.emitListingBelow(block, blockRows);
462
- }
463
- }
464
- else {
465
- this.render();
466
- }
467
- return;
468
- }
469
- case "list": {
470
- // Print listing on a new row, then redraw the prompt+line below it.
471
- const w = this.termWidth();
472
- const block = formatCandidates(step.candidates, w);
473
- const blockRows = block.split("\n").length;
474
- this.emitListingBelow(block, blockRows);
475
- return;
476
- }
477
- }
478
- }
479
- /**
480
- * Print `block` on fresh rows below the prompt block, then redraw the
481
- * prompt + buffer below it. Remembers how many rows the listing occupies
482
- * in `listingRowsDrawn` so a subsequent cycle can rewrite it in place.
483
- */
484
- emitListingBelow(block, blockRows) {
485
- if (this.active === null)
486
- return;
487
- this.moveCursorToEnd();
488
- this.stdout.write(LF);
489
- this.stdout.write(block + LF);
490
- this.active.rowsDrawn = 0;
491
- this.active.cursorRow = 0;
492
- this.active.cursorCol = 0;
493
- this.active.listingRowsDrawn = blockRows;
494
- this.render(true);
495
- }
496
- /**
497
- * Rewrite the candidate listing in place. Pre-condition: a listing of
498
- * `this.active.listingRowsDrawn` rows is currently drawn just above the
499
- * prompt block.
500
- *
501
- * 1) Step up to the FIRST row of the listing (past the prompt block).
502
- * 2) Erase + reprint each listing row.
503
- * 3) Move back down past any trailing erase, then redraw prompt + buffer.
504
- *
505
- * If `block` has a different row count from the old listing the difference
506
- * is absorbed by clearing extra rows (shrinking) or by accepting some
507
- * scroll (growing — rare in practice because the candidate list is fixed
508
- * for the duration of a cycle).
509
- */
510
- rewriteListingInPlace(block, blockRows) {
511
- if (this.active === null)
512
- return;
513
- const a = this.active;
514
- const oldRows = a.listingRowsDrawn;
515
- // 1. Cursor is somewhere inside the prompt block. Anchor to row 0 of the
516
- // prompt block first.
517
- this.stdout.write(CR);
518
- if (a.cursorRow > 0)
519
- this.stdout.write(csiUp(a.cursorRow));
520
- // 2. Step up `oldRows` more rows so the cursor sits on the first row of
521
- // the listing.
522
- this.stdout.write(csiUp(oldRows));
523
- // 3. Erase each listing row and write the new block. We treat the listing
524
- // as `blockRows` lines separated by LF; on the last line we DON'T emit
525
- // a trailing LF (otherwise we'd push the prompt down by one row).
526
- const newLines = block.split("\n");
527
- for (let i = 0; i < newLines.length; i++) {
528
- this.stdout.write(csiEraseToEol());
529
- this.stdout.write(newLines[i]);
530
- if (i < newLines.length - 1)
531
- this.stdout.write(LF + CR);
532
- }
533
- // 4. If the new block is shorter than the old one, clear the leftover
534
- // rows below.
535
- if (blockRows < oldRows) {
536
- const extra = oldRows - blockRows;
537
- for (let i = 0; i < extra; i++) {
538
- this.stdout.write(LF + CR + csiEraseToEol());
539
- }
540
- // Step back up so the cursor sits right under the last listing line.
541
- this.stdout.write(csiUp(extra));
542
- }
543
- // 5. Move past the listing onto the row where the prompt should start.
544
- this.stdout.write(LF + CR);
545
- // 6. The prompt's geometry needs to be redrawn fresh below the listing.
546
- a.rowsDrawn = 0;
547
- a.cursorRow = 0;
548
- a.cursorCol = 0;
549
- a.listingRowsDrawn = blockRows;
550
- this.render(true);
551
- }
552
- // -------------------------------------------------------------------------
553
- // Reverse-incremental-search
554
- // -------------------------------------------------------------------------
555
- async handleSearchKey(ev) {
556
- if (this.active?.search == null)
557
- return;
558
- const s = this.active.search;
559
- // ^G or Escape cancels and restores the saved line.
560
- if ((ev.key === "char" && ev.ctrl && ev.char === "g") ||
561
- ev.key === "escape") {
562
- this.state.buffer.setText(s.savedBuffer);
563
- this.active.search = null;
564
- this.render();
565
- return;
566
- }
567
- // Enter accepts the current match (whatever's in the buffer).
568
- if (ev.key === "enter") {
569
- this.active.search = null;
570
- await this.applyAction({ kind: "submit" }, ev);
571
- return;
572
- }
573
- // ^C bubbles to cancel.
574
- if (ev.key === "char" && ev.ctrl && ev.char === "c") {
575
- await this.applyAction({ kind: "cancel" }, ev);
576
- return;
577
- }
578
- // ^R again: search further back.
579
- if (ev.key === "char" && ev.ctrl && ev.char === "r") {
580
- this.searchStep(-1);
581
- return;
582
- }
583
- // Backspace: shrink the pattern.
584
- if (ev.key === "backspace") {
585
- s.pattern = s.pattern.slice(0, -1);
586
- s.matchIndex = null;
587
- this.searchStep(0);
588
- return;
589
- }
590
- // Printable char: extend the pattern.
591
- if (ev.key === "char" &&
592
- !ev.ctrl &&
593
- !ev.meta &&
594
- ev.char !== undefined) {
595
- s.pattern += ev.char;
596
- s.matchIndex = null;
597
- this.searchStep(0);
598
- return;
599
- }
600
- // Anything else (arrows, etc) accepts the match and processes the key.
601
- this.active.search = null;
602
- await this.handleEvent(ev);
603
- }
604
- /** Walk history backward looking for the current pattern. */
605
- searchStep(delta) {
606
- if (this.active?.search == null)
607
- return;
608
- const s = this.active.search;
609
- const hist = this.state.history;
610
- const startFrom = s.matchIndex === null ? hist.length - 1 : s.matchIndex + delta;
611
- for (let i = startFrom; i >= 0 && i < hist.length; i--) {
612
- if (s.pattern === "" || hist[i].includes(s.pattern)) {
613
- s.matchIndex = i;
614
- this.state.buffer.setText(hist[i]);
615
- this.render();
616
- return;
617
- }
618
- }
619
- // No match: ring bell, keep current buffer.
620
- this.stdout.write(BEL);
621
- this.render();
622
- }
623
- // -------------------------------------------------------------------------
624
- // Rendering
625
- // -------------------------------------------------------------------------
626
- /**
627
- * Repaint the prompt + buffer. If `full` is true, skip the cursor-up
628
- * optimisation (we don't know the previous geometry).
629
- */
630
- render(full = false) {
631
- if (this.active === null)
632
- return;
633
- const a = this.active;
634
- // Move the cursor back to row 0 of the previously drawn block.
635
- if (!full && a.rowsDrawn > 0) {
636
- // Move up to the anchor row.
637
- const up = a.cursorRow;
638
- this.stdout.write(CR + (up > 0 ? csiUp(up) : ""));
639
- }
640
- else {
641
- this.stdout.write(CR);
642
- }
643
- // Compose the output: prompt + buffer text, with line wrapping computed
644
- // virtually so we know where the cursor ends up.
645
- const width = Math.max(1, this.termWidth());
646
- // Pick the prompt + rendered text for the three render flavours:
647
- // - vi ex-mode (`:`-prompt): `: <exBuffer>`, cursor at the end.
648
- // - reverse-i-search: the `(reverse-i-search)\`pat':` preamble,
649
- // with the matched pattern highlighted.
650
- // - default editing: the caller-supplied prompt + buffer text.
651
- const inExMode = this.state.mode === "ex";
652
- const promptStr = inExMode
653
- ? ":"
654
- : a.search === null
655
- ? a.prompt
656
- : `(reverse-i-search)\`${a.search.pattern}': `;
657
- const rawText = inExMode
658
- ? this.state.exBuffer
659
- : this.state.buffer.text.replace(/\n/g, "⏎"); // newline glyph
660
- // For search rendering we highlight the matched pattern (case-insensitive)
661
- // inside the matched entry; otherwise the rendered text equals the raw text.
662
- const renderText = !inExMode && a.search !== null && a.search.pattern.length > 0
663
- ? highlightMatch(rawText, a.search.pattern)
664
- : rawText;
665
- const promptWidth = displayWidth(promptStr);
666
- // Cursor positioning uses the raw text length, NOT the rendered text
667
- // length, because ANSI escapes have zero display width but non-zero
668
- // string length. In ex mode the cursor always sits at the end of the
669
- // ex buffer.
670
- const beforeText = inExMode
671
- ? rawText
672
- : rawText.slice(0, this.codePointsBeforeCursor().length);
673
- const allText = renderText;
674
- // Compute physical row/col for cursor.
675
- const { row: cursorRow, col: cursorCol } = positionAfter(promptWidth, beforeText, width);
676
- // Compute final row/col for the full block (so we know how many rows).
677
- // Strip ANSI escape sequences from the geometry calculation since they
678
- // have zero display width but non-zero string length.
679
- const { row: lastRow } = positionAfter(promptWidth, stripAnsi(allText), width);
680
- const rowsDrawn = lastRow + 1;
681
- // Write the line. We erase each row first so leftover chars from a longer
682
- // previous render are scrubbed.
683
- this.stdout.write(csiEraseToEol());
684
- this.stdout.write(promptStr);
685
- this.stdout.write(allText);
686
- // After writing, if the previous render had more rows than this one,
687
- // erase the leftover rows.
688
- if (a.rowsDrawn > rowsDrawn) {
689
- const extra = a.rowsDrawn - rowsDrawn;
690
- for (let i = 0; i < extra; i++) {
691
- this.stdout.write(LF + csiEraseToEol());
692
- }
693
- // Move back up to where we are.
694
- this.stdout.write(csiUp(extra));
695
- }
696
- // Reposition cursor.
697
- // After writing `allText`, cursor is at (lastRow, lastCol). We want
698
- // (cursorRow, cursorCol).
699
- const rowDelta = cursorRow - lastRow;
700
- if (rowDelta < 0)
701
- this.stdout.write(csiUp(-rowDelta));
702
- if (rowDelta > 0)
703
- this.stdout.write(csiDown(rowDelta));
704
- this.stdout.write(CR);
705
- if (cursorCol > 0)
706
- this.stdout.write(csiRight(cursorCol));
707
- a.rowsDrawn = rowsDrawn;
708
- a.cursorRow = cursorRow;
709
- a.cursorCol = cursorCol;
710
- // Silence unused.
711
- void csiLeft;
712
- }
713
- moveCursorToEnd() {
714
- if (this.active === null)
715
- return;
716
- const a = this.active;
717
- // Step down to the final row of the current render.
718
- const down = a.rowsDrawn - 1 - a.cursorRow;
719
- if (down > 0)
720
- this.stdout.write(csiDown(down));
721
- this.stdout.write(CR);
722
- a.cursorRow = a.rowsDrawn - 1;
723
- a.cursorCol = 0;
724
- }
725
- codePointsBeforeCursor() {
726
- return { length: this.state.buffer.cursor };
727
- }
728
- termWidth() {
729
- const s = this.stdout;
730
- if (typeof s.columns === "number" && s.columns > 0)
731
- return s.columns;
732
- return 80;
733
- }
734
- }
735
- const isTtyReadStream = (s) => typeof s.setRawMode === "function";
736
- // ---------------------------------------------------------------------------
737
- // Search-line rendering / highlighting
738
- // ---------------------------------------------------------------------------
739
- const SGR_REVERSE = "\x1b[7m";
740
- const SGR_NO_REVERSE = "\x1b[27m";
741
- /**
742
- * Wrap the first case-insensitive occurrence of `pattern` inside `text`
743
- * with the reverse-video SGR pair. Returns `text` unchanged when the
744
- * pattern is empty or not found.
745
- *
746
- * Kept as a pure helper for unit-testing (the renderer calls it during
747
- * search mode, but `renderSearchLine` is the unit-testable surface).
748
- */
749
- export const highlightMatch = (text, pattern) => {
750
- if (pattern.length === 0)
751
- return text;
752
- const lcText = text.toLowerCase();
753
- const lcPat = pattern.toLowerCase();
754
- const idx = lcText.indexOf(lcPat);
755
- if (idx < 0)
756
- return text;
757
- return (text.slice(0, idx) +
758
- SGR_REVERSE +
759
- text.slice(idx, idx + pattern.length) +
760
- SGR_NO_REVERSE +
761
- text.slice(idx + pattern.length));
762
- };
763
- /**
764
- * Render the search prompt + matched entry as a single string, with the
765
- * matched pattern highlighted via reverse video. Exposed for unit tests.
766
- * The real interactive renderer applies the same logic inline.
767
- */
768
- export const renderSearchLine = (pattern, entry) => {
769
- const prefix = `(reverse-i-search)\`${pattern}': `;
770
- return prefix + highlightMatch(entry, pattern);
771
- };
772
- /** Strip ANSI CSI escape sequences from `text` for display-width math. */
773
- const stripAnsi = (text) =>
774
- // Targets the SGR forms we emit (e.g. \x1b[7m, \x1b[27m). Kept narrow on
775
- // purpose so it doesn't accidentally eat legitimate `[` characters.
776
- text.replace(/\x1b\[[0-9;]*m/g, "");
777
- // ---------------------------------------------------------------------------
778
- // Display-width helpers (inlined copy of WP-09's tables; kept minimal).
779
- // ---------------------------------------------------------------------------
780
- const WIDE_RANGES = [
781
- [0x1100, 0x115f],
782
- [0x2329, 0x232a],
783
- [0x2e80, 0x303e],
784
- [0x3041, 0x33ff],
785
- [0x3400, 0x4dbf],
786
- [0x4e00, 0x9fff],
787
- [0xa000, 0xa4cf],
788
- [0xac00, 0xd7a3],
789
- [0xf900, 0xfaff],
790
- [0xfe10, 0xfe19],
791
- [0xfe30, 0xfe6f],
792
- [0xff00, 0xff60],
793
- [0xffe0, 0xffe6],
794
- [0x1f300, 0x1f64f],
795
- [0x1f900, 0x1f9ff],
796
- [0x20000, 0x2fffd],
797
- [0x30000, 0x3fffd],
798
- ];
799
- const ZERO_RANGES = [
800
- [0x0300, 0x036f],
801
- [0x0483, 0x0489],
802
- [0x0591, 0x05bd],
803
- [0x05bf, 0x05bf],
804
- [0x05c1, 0x05c2],
805
- [0x05c4, 0x05c5],
806
- [0x05c7, 0x05c7],
807
- [0x0610, 0x061a],
808
- [0x064b, 0x065f],
809
- [0x0670, 0x0670],
810
- [0x06d6, 0x06dc],
811
- [0x06df, 0x06e4],
812
- [0x06e7, 0x06e8],
813
- [0x06ea, 0x06ed],
814
- [0x0711, 0x0711],
815
- [0x0730, 0x074a],
816
- [0x200b, 0x200f],
817
- [0x202a, 0x202e],
818
- [0x2060, 0x206f],
819
- [0x20d0, 0x20f0],
820
- [0xfe00, 0xfe0f],
821
- [0xfe20, 0xfe2f],
822
- [0xfeff, 0xfeff],
823
- [0xe0100, 0xe01ef],
824
- ];
825
- const inRange = (cp, ranges) => {
826
- let lo = 0;
827
- let hi = ranges.length - 1;
828
- while (lo <= hi) {
829
- const mid = (lo + hi) >> 1;
830
- const entry = ranges[mid];
831
- if (cp < entry[0])
832
- hi = mid - 1;
833
- else if (cp > entry[1])
834
- lo = mid + 1;
835
- else
836
- return true;
837
- }
838
- return false;
839
- };
840
- const codePointWidth = (cp) => {
841
- if (cp === 0)
842
- return 0;
843
- if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0))
844
- return 0;
845
- if (inRange(cp, ZERO_RANGES))
846
- return 0;
847
- if (inRange(cp, WIDE_RANGES))
848
- return 2;
849
- return 1;
850
- };
851
- const displayWidth = (text) => {
852
- let w = 0;
853
- for (const ch of text)
854
- w += codePointWidth(ch.codePointAt(0) ?? 0);
855
- return w;
856
- };
857
- /**
858
- * Compute the final (row, col) position after writing `text` to a
859
- * terminal whose cursor starts at column `startCol` and is `width`
860
- * columns wide. Wrapping happens by display column count, not code points.
861
- */
862
- const positionAfter = (startCol, text, width) => {
863
- let row = 0;
864
- let col = startCol % width;
865
- // Initial wrap if startCol exactly hit the width boundary.
866
- if (col === 0 && startCol > 0) {
867
- row += Math.floor(startCol / width);
868
- }
869
- else {
870
- row += Math.floor(startCol / width);
871
- }
872
- for (const ch of text) {
873
- if (ch === "\n") {
874
- row += 1;
875
- col = 0;
876
- continue;
877
- }
878
- const w = codePointWidth(ch.codePointAt(0) ?? 0);
879
- if (col + w > width) {
880
- row += 1;
881
- col = w;
882
- }
883
- else {
884
- col += w;
885
- if (col === width) {
886
- // Stay on this row; next char triggers the wrap.
887
- // (Real terminals differ here; the conservative choice that matches
888
- // most xterm derivatives is to NOT advance row until the next glyph.)
889
- }
890
- }
891
- }
892
- return { row, col };
893
- };