refactor(desktop): organize lib modules by domain

This commit is contained in:
t8y2 committed 2026-07-04 13:53:52 +08:00
1 parent 90f0594e93
commit 7e7c4944e9
700 files changed
+1292 -1264

No files matched your search

@@ -0,0 +1,68 @@
export type RedisCommandSafety = "allowed" | "confirm" | "blocked";
const BLOCKED_COMMANDS = new Set(["KEYS", "FLUSHALL", "SHUTDOWN", "CONFIG", "SAVE", "BGSAVE", "SLAVEOF", "REPLICAOF", "MIGRATE", "MODULE", "SCRIPT", "EVAL", "EVALSHA"]);
const CONFIRM_COMMANDS = new Set([
"DEL",
"UNLINK",
"EXPIRE",
"EXPIREAT",
"PEXPIRE",
"PEXPIREAT",
"PERSIST",
"RENAME",
"RENAMENX",
"SET",
"SETEX",
"PSETEX",
"SETNX",
"MSET",
"MSETNX",
"HSET",
"HDEL",
"LPUSH",
"RPUSH",
"LPOP",
"RPOP",
"LSET",
"LREM",
"SADD",
"SREM",
"ZADD",
"ZREM",
"XADD",
"XDEL",
"FLUSHDB",
]);
export function firstRedisCommandToken(command: string): string {
const trimmed = command.trimStart();
if (!trimmed) return "";
const quote = trimmed[0] === '"' || trimmed[0] === "'" ? trimmed[0] : "";
let token = "";
let escaping = false;
for (let i = quote ? 1 : 0; i < trimmed.length; i++) {
const ch = trimmed[i];
if (escaping) {
token += ch;
escaping = false;
continue;
}
if (ch === "\\") {
escaping = true;
continue;
}
if (quote && ch === quote) break;
if (!quote && /\s/.test(ch)) break;
token += ch;
}
return token.toUpperCase();
}
export function classifyRedisCommandSafety(command: string): RedisCommandSafety {
const token = firstRedisCommandToken(command);
if (BLOCKED_COMMANDS.has(token)) return "blocked";
if (CONFIRM_COMMANDS.has(token)) return "confirm";
return "allowed";
}
@@ -0,0 +1,22 @@
export function nextRedisCommandDb(currentDb: number, command: string, result: unknown): number {
if (result !== "OK") return currentDb;
const match = command.trim().match(/^SELECT\s+(\d+)\s*;?$/i);
if (!match) return currentDb;
const nextDb = Number.parseInt(match[1], 10);
return Number.isFinite(nextDb) ? nextDb : currentDb;
}
export function isRedisClearScreenCommand(command: string): boolean {
return /^(clear|cls)\s*;?$/i.test(command.trim());
}
export function redisKeyTextToRaw(key: string): string {
const bytes = new TextEncoder().encode(key);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
@@ -0,0 +1,463 @@
/**
* Static Redis command metadata, distilled from the official Redis command table
* (redis-doc `commands.json` / the `COMMAND` output). Kept offline and lightweight:
* we only retain what the editor syntax diagnostics need — `arity` and `group` —
* plus a `safety` hint for danger/write-command highlighting.
*
* Arity semantics (matches the Redis `COMMAND` reply, command name INCLUDED in the count):
* arity > 0 → the command takes exactly `arity` tokens (e.g. GET key → arity 2).
* arity < 0 → the command takes AT LEAST `-arity` tokens (e.g. MSET k v [k v ...] → arity -3).
*
* `safety` is aligned with the token-level sets in `redisCommandSafety.ts` (used to gate
* execution). Here it is recorded per-command (including subcommands) so diagnostics can
* be more precise than the first-token classification.
*
* Subcommands are keyed as `"MAIN SUB"` in UPPER CASE (e.g. `"CONFIG GET"`, `"XGROUP CREATE"`).
*/
import type { RedisCommandSafety } from "@/lib/redis/redisCommandSafety";
export interface RedisCommandSpec {
/** Token count including the command name. Positive = exact, negative = minimum (-N). */
arity: number;
/** Redis command group: string/list/hash/.../server. */
group: string;
/** Danger level for diagnostic highlighting. */
safety: RedisCommandSafety;
}
type Spec = [arity: number, group: string, safety?: RedisCommandSafety];
// Compact tuple form → expanded into the record below.
const RAW_COMMANDS: Record<string, Spec> = {
// ---- String ----
APPEND: [3, "string", "confirm"],
DECR: [2, "string", "confirm"],
DECRBY: [3, "string", "confirm"],
GET: [2, "string"],
GETDEL: [2, "string", "confirm"],
GETEX: [-2, "string"],
GETRANGE: [4, "string"],
GETSET: [3, "string", "confirm"],
INCR: [2, "string", "confirm"],
INCRBY: [3, "string", "confirm"],
INCRBYFLOAT: [3, "string", "confirm"],
LCS: [-3, "string"],
MGET: [-2, "string"],
MSET: [-3, "string", "confirm"],
MSETNX: [-3, "string", "confirm"],
PSETEX: [4, "string", "confirm"],
SET: [-3, "string", "confirm"],
SETEX: [4, "string", "confirm"],
SETNX: [3, "string", "confirm"],
SETRANGE: [4, "string", "confirm"],
STRLEN: [2, "string"],
// ---- Generic key ----
COPY: [-3, "generic", "confirm"],
DEL: [-2, "generic", "confirm"],
DUMP: [2, "generic"],
EXISTS: [-2, "generic"],
EXPIRE: [-3, "generic", "confirm"],
EXPIREAT: [-3, "generic", "confirm"],
KEYS: [2, "generic", "blocked"],
MIGRATE: [-6, "generic", "blocked"],
MOVE: [3, "generic", "confirm"],
OBJECT_ENCODING: [3, "generic"],
OBJECT_FREQ: [3, "generic"],
OBJECT_IDLETIME: [3, "generic"],
OBJECT_REFCOUNT: [3, "generic"],
OBJECT_HELP: [2, "generic"],
PERSIST: [2, "generic", "confirm"],
PEXPIRE: [-3, "generic", "confirm"],
PEXPIREAT: [-3, "generic", "confirm"],
PTTL: [2, "generic"],
RANDOMKEY: [1, "generic"],
RENAME: [3, "generic", "confirm"],
RENAMENX: [3, "generic", "confirm"],
RESTORE: [-4, "generic", "confirm"],
SCAN: [-2, "generic"],
SORT: [-2, "generic", "confirm"],
SORT_RO: [-2, "generic"],
TOUCH: [-2, "generic"],
TTL: [2, "generic"],
TYPE: [2, "generic"],
UNLINK: [-2, "generic", "confirm"],
WAIT: [3, "generic"],
WAITAOF: [4, "generic"],
// ---- List ----
BLMOVE: [6, "list"],
BLMPOP: [-4, "list"],
BLPOP: [-3, "list"],
BRPOP: [-3, "list"],
BRPOPLPUSH: [4, "list"],
LINDEX: [3, "list"],
LINSERT: [5, "list", "confirm"],
LLEN: [2, "list"],
LMOVE: [5, "list", "confirm"],
LMPOP: [-4, "list", "confirm"],
LPOP: [-2, "list", "confirm"],
LPOS: [-2, "list"],
LPUSH: [-3, "list", "confirm"],
LPUSHX: [-3, "list", "confirm"],
LRANGE: [4, "list"],
LREM: [4, "list", "confirm"],
LSET: [4, "list", "confirm"],
LTRIM: [4, "list", "confirm"],
RPOP: [-2, "list", "confirm"],
RPOPLPUSH: [4, "list", "confirm"],
RPUSH: [-3, "list", "confirm"],
RPUSHX: [-3, "list", "confirm"],
// ---- Hash ----
HDEL: [-3, "hash", "confirm"],
HEXISTS: [3, "hash"],
HGET: [3, "hash"],
HGETALL: [2, "hash"],
HINCRBY: [4, "hash", "confirm"],
HINCRBYFLOAT: [4, "hash", "confirm"],
HKEYS: [2, "hash"],
HLEN: [2, "hash"],
HMGET: [-3, "hash"],
HMSET: [-4, "hash", "confirm"],
HRANDFIELD: [-2, "hash"],
HSCAN: [-3, "hash"],
HSET: [-4, "hash", "confirm"],
HSETNX: [4, "hash", "confirm"],
HSTRLEN: [3, "hash"],
HVALS: [2, "hash"],
// ---- Set ----
SADD: [-3, "set", "confirm"],
SCARD: [2, "set"],
SDIFF: [-2, "set"],
SDIFFSTORE: [-3, "set", "confirm"],
SINTER: [-2, "set"],
SINTERCARD: [-3, "set"],
SINTERSTORE: [-3, "set", "confirm"],
SISMEMBER: [3, "set"],
SMEMBERS: [2, "set"],
SMISMEMBER: [-3, "set"],
SMOVE: [4, "set", "confirm"],
SPOP: [-2, "set", "confirm"],
SRANDMEMBER: [-2, "set"],
SREM: [-3, "set", "confirm"],
SSCAN: [-3, "set"],
SUNION: [-2, "set"],
SUNIONSTORE: [-3, "set", "confirm"],
// ---- Sorted set ----
BZMPOP: [-3, "zset"],
BZPOPMAX: [-3, "zset"],
BZPOPMIN: [-3, "zset"],
ZADD: [-4, "zset", "confirm"],
ZCARD: [2, "zset"],
ZCOUNT: [4, "zset"],
ZDIFF: [-3, "zset"],
ZDIFFSTORE: [-4, "zset", "confirm"],
ZINCRBY: [4, "zset", "confirm"],
ZINTER: [-3, "zset"],
ZINTERCARD: [-3, "zset"],
ZINTERSTORE: [-4, "zset", "confirm"],
ZLEXCOUNT: [4, "zset"],
ZMPOP: [-3, "zset", "confirm"],
ZMSCORE: [-3, "zset"],
ZPOPMAX: [-2, "zset", "confirm"],
ZPOPMIN: [-2, "zset", "confirm"],
ZRANGE: [-4, "zset"],
ZRANGEBYLEX: [-4, "zset"],
ZRANGEBYSCORE: [-4, "zset"],
ZRANGESTORE: [-5, "zset", "confirm"],
ZRANK: [-3, "zset"],
ZREM: [-3, "zset", "confirm"],
ZREMRANGEBYLEX: [4, "zset", "confirm"],
ZREMRANGEBYRANK: [4, "zset", "confirm"],
ZREMRANGEBYSCORE: [4, "zset", "confirm"],
ZREVRANGE: [-4, "zset"],
ZREVRANGEBYLEX: [-4, "zset"],
ZREVRANGEBYSCORE: [-4, "zset"],
ZREVRANK: [-3, "zset"],
ZSCAN: [-3, "zset"],
ZSCORE: [3, "zset"],
ZUNION: [-3, "zset"],
ZUNIONSTORE: [-4, "zset", "confirm"],
// ---- Bitmap ----
BITCOUNT: [-2, "bitmap"],
BITFIELD: [-2, "bitmap", "confirm"],
BITFIELD_RO: [-2, "bitmap"],
BITOP: [-4, "bitmap", "confirm"],
BITPOS: [-3, "bitmap"],
GETBIT: [3, "bitmap"],
SETBIT: [4, "bitmap", "confirm"],
// ---- Hyperloglog ----
PFADD: [-2, "hyperloglog", "confirm"],
PFCOUNT: [-2, "hyperloglog"],
PFMERGE: [-2, "hyperloglog", "confirm"],
// ---- Geo ----
GEOADD: [-5, "geo", "confirm"],
GEODIST: [-4, "geo"],
GEOHASH: [-3, "geo"],
GEOPOS: [-3, "geo"],
GEORADIUS: [-6, "geo", "confirm"],
GEORADIUS_RO: [-6, "geo"],
GEORADIUSBYMEMBER: [-5, "geo", "confirm"],
GEORADIUSBYMEMBER_RO: [-5, "geo"],
GEOSEARCH: [-7, "geo"],
GEOSEARCHSTORE: [-8, "geo", "confirm"],
// ---- Stream ----
XACK: [-4, "stream", "confirm"],
XADD: [-5, "stream", "confirm"],
XAUTOCLAIM: [-7, "stream", "confirm"],
XCLAIM: [-6, "stream", "confirm"],
XDEL: [-3, "stream", "confirm"],
"XGROUP CREATE": [-6, "stream", "confirm"],
"XGROUP CREATECONSUMER": [5, "stream", "confirm"],
"XGROUP DELCONSUMER": [4, "stream", "confirm"],
"XGROUP DESTROY": [4, "stream", "confirm"],
"XGROUP HELP": [2, "stream"],
"XGROUP SETID": [-5, "stream", "confirm"],
"XINFO CONSUMERS": [4, "stream"],
"XINFO GROUPS": [3, "stream"],
"XINFO HELP": [2, "stream"],
"XINFO STREAM": [-3, "stream"],
XLEN: [2, "stream"],
XPENDING: [-3, "stream"],
XRANGE: [-4, "stream"],
XREAD: [-4, "stream"],
XREADGROUP: [-7, "stream"],
XREVRANGE: [-4, "stream"],
XSETID: [-3, "stream", "confirm"],
XTRIM: [-4, "stream", "confirm"],
// ---- Pub/Sub ----
PSUBSCRIBE: [-2, "pubsub"],
PUBLISH: [3, "pubsub"],
"PUBSUB CHANNELS": [-2, "pubsub"],
"PUBSUB NUMPAT": [1, "pubsub"],
"PUBSUB NUMSUB": [-2, "pubsub"],
"PUBSUB SHARDCHANNELS": [-2, "pubsub"],
"PUBSUB SHARDNUMSUB": [-2, "pubsub"],
PUNSUBSCRIBE: [-1, "pubsub"],
SPUBLISH: [3, "pubsub"],
SSUBSCRIBE: [2, "pubsub"],
SUBSCRIBE: [-2, "pubsub"],
SUNSUBSCRIBE: [-1, "pubsub"],
UNSUBSCRIBE: [-1, "pubsub"],
// ---- Transactions ----
DISCARD: [1, "transactions"],
EXEC: [1, "transactions"],
MULTI: [1, "transactions"],
UNWATCH: [1, "transactions"],
WATCH: [-2, "transactions"],
// ---- Scripting ----
EVAL: [-3, "scripting", "blocked"],
EVALSHA: [-3, "scripting", "blocked"],
EVAL_RO: [-3, "scripting", "blocked"],
EVALSHA_RO: [-3, "scripting", "blocked"],
FCALL: [-3, "scripting"],
FCALL_RO: [-3, "scripting"],
"FUNCTION DELETE": [3, "scripting", "confirm"],
"FUNCTION DUMP": [2, "scripting"],
"FUNCTION FLUSH": [-2, "scripting", "confirm"],
"FUNCTION LIST": [-2, "scripting"],
"FUNCTION LOAD": [-3, "scripting", "confirm"],
"FUNCTION RESTORE": [-4, "scripting", "confirm"],
"FUNCTION STATS": [1, "scripting"],
"SCRIPT EXISTS": [-2, "scripting", "blocked"],
"SCRIPT FLUSH": [-2, "scripting", "blocked"],
"SCRIPT KILL": [1, "scripting", "blocked"],
"SCRIPT LOAD": [2, "scripting", "blocked"],
// ---- Connection ----
AUTH: [-2, "connection"],
ECHO: [2, "connection"],
HELLO: [-1, "connection"],
PING: [-1, "connection"],
QUIT: [1, "connection"],
RESET: [1, "connection"],
SELECT: [2, "connection"],
"CLIENT CACHING": [3, "connection"],
"CLIENT GETNAME": [1, "connection"],
"CLIENT GETREDIR": [1, "connection"],
"CLIENT ID": [1, "connection"],
"CLIENT INFO": [1, "connection"],
"CLIENT KILL": [-3, "connection", "confirm"],
"CLIENT LIST": [-2, "connection"],
"CLIENT NO-EVICT": [2, "connection"],
"CLIENT NO-TOUCH": [2, "connection"],
"CLIENT PAUSE": [-2, "connection"],
"CLIENT REPLY": [2, "connection"],
"CLIENT SETINFO": [-3, "connection"],
"CLIENT SETNAME": [3, "connection"],
"CLIENT TRACKING": [-3, "connection"],
"CLIENT TRACKINGINFO": [1, "connection"],
"CLIENT UNPAUSE": [1, "connection"],
// ---- Server ----
BGREWRITEAOF: [1, "server"],
BGSAVE: [-1, "server", "blocked"],
"COMMAND COUNT": [1, "server"],
"COMMAND DOCS": [-2, "server"],
"COMMAND GETKEYS": [-3, "server"],
"COMMAND INFO": [-2, "server"],
"COMMAND LIST": [-2, "server"],
"CONFIG GET": [-2, "server", "blocked"],
"CONFIG RESETSTAT": [1, "server", "blocked"],
"CONFIG REWRITE": [1, "server", "blocked"],
"CONFIG SET": [-3, "server", "blocked"],
DBSIZE: [1, "server"],
FAILOVER: [-1, "server", "confirm"],
FLUSHALL: [-1, "server", "blocked"],
FLUSHDB: [-1, "server", "confirm"],
INFO: [-1, "server"],
LASTSAVE: [1, "server"],
"MEMORY USAGE": [-3, "server"],
"MEMORY STATS": [1, "server"],
"MEMORY PURGE": [1, "server"],
"MEMORY DOCS": [1, "server"],
"MODULE LIST": [1, "server", "blocked"],
"MODULE LOAD": [-3, "server", "blocked"],
"MODULE LOADEX": [-3, "server", "blocked"],
"MODULE UNLOAD": [3, "server", "blocked"],
MONITOR: [1, "server"],
REPLICAOF: [3, "server", "blocked"],
ROLE: [1, "server"],
SAVE: [1, "server", "blocked"],
SHUTDOWN: [-1, "server", "blocked"],
SLAVEOF: [3, "server", "blocked"],
"SLOWLOG GET": [-2, "server"],
"SLOWLOG LEN": [1, "server"],
"SLOWLOG RESET": [1, "server"],
"SLOWLOG HELP": [1, "server"],
SWAPDB: [3, "server", "confirm"],
SYNC: [1, "server"],
TIME: [1, "server"],
// ---- Cluster ----
"CLUSTER ADDSLOTS": [-3, "cluster", "confirm"],
"CLUSTER COUNT-FAILURE-REPORTS": [2, "cluster"],
"CLUSTER COUNTKEYSINSLOT": [3, "cluster"],
"CLUSTER DELSLOTS": [-3, "cluster", "confirm"],
"CLUSTER FAILOVER": [-2, "cluster", "confirm"],
"CLUSTER FLUSHSLOTS": [1, "cluster", "confirm"],
"CLUSTER FORGET": [2, "cluster", "confirm"],
"CLUSTER GETKEYSINSLOT": [4, "cluster"],
"CLUSTER INFO": [1, "cluster"],
"CLUSTER KEYSLOT": [2, "cluster"],
"CLUSTER LINKS": [1, "cluster"],
"CLUSTER MEET": [-4, "cluster", "confirm"],
"CLUSTER MYID": [1, "cluster"],
"CLUSTER NODES": [1, "cluster"],
"CLUSTER REPLICAS": [2, "cluster"],
"CLUSTER REPLICATE": [2, "cluster", "confirm"],
"CLUSTER RESET": [-2, "cluster", "confirm"],
"CLUSTER SAVECONFIG": [1, "cluster", "confirm"],
"CLUSTER SET-CONFIG-EPOCH": [2, "cluster", "confirm"],
"CLUSTER SETSLOT": [-4, "cluster", "confirm"],
"CLUSTER SHARDS": [1, "cluster"],
"CLUSTER SLAVES": [2, "cluster"],
"CLUSTER SLOTS": [1, "cluster"],
READONLY: [1, "cluster"],
READWRITE: [1, "cluster"],
};
export const REDIS_COMMAND_TABLE: Record<string, RedisCommandSpec> = Object.fromEntries(Object.entries(RAW_COMMANDS).map(([name, [arity, group, safety]]) => [name.toUpperCase(), { arity, group, safety: safety ?? "allowed" }]));
/**
* Resolve a command spec. Handles two-token subcommands (e.g. `XGROUP CREATE`,
* `CONFIG GET`) by trying `MAIN SUB` first, then falling back to the main token.
*/
export function resolveRedisCommandSpec(argvUpper: readonly string[]): RedisCommandSpec | undefined {
if (argvUpper.length === 0) return undefined;
const main = argvUpper[0];
if (argvUpper.length >= 2) {
const sub = `${main} ${argvUpper[1]}`;
const subSpec = REDIS_COMMAND_TABLE[sub];
if (subSpec) return subSpec;
}
return REDIS_COMMAND_TABLE[main];
}
/**
* Minimal argv tokenizer for the first two tokens of a Redis command line —
* enough to resolve a spec (which only needs the command head, optionally a
* subcommand). Single-quoted, double-quoted and unquoted tokens are supported
* with backslash escapes; quoting errors are tolerated (the token still resolves).
* Kept local so this module stays self-contained (no dependency on the syntax
* diagnostics tokenizer).
*/
function firstRedisArgvUpper(line: string): string[] {
const tokens: string[] = [];
let i = 0;
const n = line.length;
while (i < n && tokens.length < 2) {
while (i < n && /\s/.test(line[i])) i++;
if (i >= n) break;
const quote = line[i] === '"' || line[i] === "'" ? line[i] : "";
let token = "";
let escaping = false;
if (quote) i++;
while (i < n) {
const ch = line[i];
if (escaping) {
token += ch;
escaping = false;
i++;
continue;
}
if (ch === "\\") {
escaping = true;
i++;
continue;
}
if (quote && ch === quote) {
i++;
break;
}
if (!quote && /\s/.test(ch)) break;
token += ch;
i++;
}
tokens.push(token.toUpperCase());
}
return tokens;
}
// Commands marked `safety: "blocked"` because they are dangerous/administrative,
// but which do NOT actually change the key set of the current db — so they should
// NOT trigger key-name completion cache invalidation. (e.g. KEYS is read-only;
// SAVE/BGSAVE/SHUTDOWN/REPLICAOF/SLAVEOF are server admin.) Everything else in the
// `blocked` set (FLUSHALL, MIGRATE, EVAL[ESHA]) may mutate keys and is left in.
const NON_MUTATING_BLOCKED = new Set(["KEYS", "BGSAVE", "SAVE", "SHUTDOWN", "REPLICAOF", "SLAVEOF"]);
/**
* True when a command may change the key set of the db it ran on (adds/edits/
* removes/renames keys, or wipes the db), and therefore the cached key-name
* completion for that db is potentially stale and should be dropped.
*
* Mapping from the diagnostic `safety` field:
* - `confirm` → every write command mutates keys (SET/DEL/INCR/HSET/...).
* - `blocked` → mostly destructive/admin; we keep the ones that may touch keys
* (FLUSHALL, MIGRATE, EVAL[ESHA]) and exclude the read-only/admin
* ones in `NON_MUTATING_BLOCKED`.
* - `allowed` → read-only (GET/LRANGE/SCAN/...), never invalidates.
*
* Commands absent from the table (unknown or read-only extensions) are treated as
* non-mutating so we never thrash the cache on lookups.
*/
export function isRedisMutatingCommand(command: string): boolean {
const argv = firstRedisArgvUpper(command);
const spec = resolveRedisCommandSpec(argv);
if (!spec) return false;
if (spec.safety === "confirm") return true;
if (spec.safety === "blocked") {
return !NON_MUTATING_BLOCKED.has(argv[0]);
}
return false;
}
@@ -0,0 +1,243 @@
/**
* Redis command autocompletion for the query editor. Mirrors the shape of
* `elasticsearchCompletion.ts` so the editor's completion pipeline (the single
* `autocompletion({ override })` in QueryEditor.vue) can dispatch to it.
*
* Data source: the static `REDIS_COMMAND_TABLE` (built for diagnostics). Keys
* are UPPER CASE command names; two-token subcommands are keyed as `"MAIN SUB"`
* (e.g. `"XGROUP CREATE"`). We split those into a main-name index + subcommand
* index here.
*/
import { REDIS_COMMAND_TABLE } from "@/lib/redis/redisCommandTable";
import type { RedisCommandSpec } from "@/lib/redis/redisCommandTable";
export interface RedisCompletionItem {
label: string;
type: "keyword" | "text"; // command/subcommand=keyword, key name=text
detail?: string; // single-line, e.g. "string · confirm"
info?: string; // multi-line: Group / Arity / Safety
apply?: string;
boost: number;
}
export interface RedisCompletionContext {
mode: "command" | "subcommand" | "argument";
prefix: string;
/** Absolute document offset where the completion starts. */
from: number;
/** Upper-cased main command already typed, when known. */
mainCommand?: string;
/** In argument mode: 0-based index of the argument position (after the command head). */
argumentIndex?: number;
}
export interface RedisCompletionInput {
keys?: string[];
}
// ---- Static indexes derived from the command table ----
interface MainCommandEntry {
name: string;
spec: RedisCommandSpec;
}
interface SubcommandEntry {
main: string;
sub: string;
spec: RedisCommandSpec;
}
const MAIN_COMMANDS: MainCommandEntry[] = [];
const SUBCOMMANDS: SubcommandEntry[] = [];
const SUBCOMMAND_MAINS = new Set<string>();
for (const [key, spec] of Object.entries(REDIS_COMMAND_TABLE)) {
const space = key.indexOf(" ");
if (space < 0) {
MAIN_COMMANDS.push({ name: key, spec });
} else {
const main = key.slice(0, space);
const sub = key.slice(space + 1);
SUBCOMMANDS.push({ main, sub, spec });
SUBCOMMAND_MAINS.add(main);
// A main command that only has subcommand forms still needs a main-name
// entry so the user can complete the main token first.
if (!REDIS_COMMAND_TABLE[main]) MAIN_COMMANDS.push({ name: main, spec });
}
}
// Groups whose first argument is a key name (enable key completion there).
const KEY_ARGUMENT_GROUPS = new Set(["string", "generic", "list", "hash", "set", "zset", "bitmap", "hyperloglog", "geo", "stream"]);
// Commands that accept a variadic list of keys (keep suggesting keys beyond the
// first argument slot). Most key commands take exactly one key; these keep going.
const MULTI_KEY_COMMANDS = new Set(["DEL", "UNLINK", "EXISTS", "TOUCH", "MGET"]);
// Boost tuning: common groups surface higher.
const GROUP_BOOST: Record<string, number> = {
string: 110,
generic: 108,
connection: 100,
server: 96,
};
function describeArity(arity: number): string {
if (arity > 0) {
const n = arity - 1;
return `exactly ${n} argument${n === 1 ? "" : "s"}`;
}
if (arity < 0) {
const n = -arity - 1;
return `at least ${n} argument${n === 1 ? "" : "s"}`;
}
return "variable arguments";
}
function matchesPrefix(value: string, prefix: string): boolean {
return value.toLowerCase().startsWith(prefix.toLowerCase());
}
function buildSpecDetail(spec: RedisCommandSpec): string {
return spec.safety === "allowed" ? spec.group : `${spec.group} · ${spec.safety}`;
}
function buildSpecInfo(spec: RedisCommandSpec, label: string): string {
return [`Command: ${label}`, `Group: ${spec.group}`, `Arity: ${describeArity(spec.arity)}`, `Safety: ${spec.safety}`].join("\n");
}
function boostFor(spec: RedisCommandSpec): number {
return GROUP_BOOST[spec.group] ?? 90;
}
// ---- Context parsing ----
export function getRedisCompletionContext(text: string, cursor: number): RedisCompletionContext {
const safeCursor = Math.max(0, Math.min(cursor, text.length));
const lineStart = text.lastIndexOf("\n", safeCursor - 1) + 1;
const beforeCursor = text.slice(lineStart, safeCursor);
// Tokenize the part before the cursor by whitespace.
const tokens = beforeCursor.trimStart().length === 0 ? [] : beforeCursor.trim().split(/\s+/);
const endsWithSpace = beforeCursor.length > 0 && /\s$/.test(beforeCursor);
// Current word being typed (no trailing space yet).
const currentWord = endsWithSpace ? "" : (tokens[tokens.length - 1] ?? "");
const wordStartFromEnd = currentWord.length;
const from = safeCursor - wordStartFromEnd;
const typedTokens = endsWithSpace ? tokens : tokens.slice(0, -1);
// No command yet (or typing the very first token).
if (typedTokens.length === 0) {
return { mode: "command", prefix: currentWord, from };
}
const main = typedTokens[0]!.toUpperCase();
// First token done + space → maybe a subcommand of a command that has them.
if (typedTokens.length === 1 && SUBCOMMAND_MAINS.has(main)) {
return { mode: "subcommand", prefix: currentWord, from, mainCommand: main };
}
// Past the command (and any subcommand slot) → an argument. Track which
// argument position the cursor is at so we only suggest key names for the
// first key argument (e.g. GET <key>, not after the key is filled in).
const commandHeadTokens = typedTokens.length >= 2 && REDIS_COMMAND_TABLE[`${main} ${typedTokens[1]!.toUpperCase()}`] ? 2 : 1;
const argumentIndex = Math.max(typedTokens.length - commandHeadTokens, 0);
return { mode: "argument", prefix: currentWord, from, mainCommand: main, argumentIndex };
}
// ---- Item builders ----
function commandItems(prefix: string): RedisCompletionItem[] {
const items = MAIN_COMMANDS.filter((entry) => matchesPrefix(entry.name, prefix)).map((entry) => ({
label: entry.name,
type: "keyword" as const,
detail: buildSpecDetail(entry.spec),
info: buildSpecInfo(entry.spec, entry.name),
boost: boostFor(entry.spec),
}));
return items.sort((a, b) => b.boost - a.boost);
}
function subcommandItems(main: string, prefix: string): RedisCompletionItem[] {
const items = SUBCOMMANDS.filter((entry) => entry.main === main && matchesPrefix(entry.sub, prefix)).map((entry) => ({
label: entry.sub,
type: "keyword" as const,
detail: buildSpecDetail(entry.spec),
info: buildSpecInfo(entry.spec, `${main} ${entry.sub}`),
boost: boostFor(entry.spec),
}));
return items.sort((a, b) => b.boost - a.boost);
}
function keyItems(prefix: string, keys: string[]): RedisCompletionItem[] {
if (!prefix) {
// No partial key typed yet: offer a bounded sample (sorted) so the menu isn't empty.
return keys.slice(0, 100).map((key) => ({
label: key,
type: "text" as const,
detail: "key",
boost: 60,
}));
}
return keys
.filter((key) => key.toLowerCase().includes(prefix.toLowerCase()))
.slice(0, 100)
.map((key) => ({
label: key,
type: "text" as const,
detail: "key",
boost: key.toLowerCase().startsWith(prefix.toLowerCase()) ? 70 : 55,
}));
}
export function buildRedisCompletionItemsFromContext(context: RedisCompletionContext, input: RedisCompletionInput = {}): RedisCompletionItem[] {
if (context.mode === "command") return commandItems(context.prefix);
if (context.mode === "subcommand" && context.mainCommand) {
return subcommandItems(context.mainCommand, context.prefix);
}
// argument mode: offer key names at the key-argument slot only. Most key
// commands take a single key (first slot); variadic key-list commands
// (DEL/UNLINK/EXISTS/...) keep suggesting at every slot.
if (context.mode === "argument" && takesKeyArgument(context.mainCommand) && shouldSuggestKeyAt(context.mainCommand, context.argumentIndex)) {
return keyItems(context.prefix, input.keys ?? []);
}
return [];
}
function shouldSuggestKeyAt(mainCommand: string | undefined, argumentIndex: number | undefined): boolean {
if (argumentIndex == null) return false;
if (mainCommand && MULTI_KEY_COMMANDS.has(mainCommand)) return true;
return argumentIndex === 0;
}
export function buildRedisCompletionItems(text: string, cursor: number, input: RedisCompletionInput = {}): RedisCompletionItem[] {
return buildRedisCompletionItemsFromContext(getRedisCompletionContext(text, cursor), input);
}
/** True when the main command's first argument is a key (by group heuristic). */
export function takesKeyArgument(mainCommand?: string): boolean {
if (!mainCommand) return false;
const spec = REDIS_COMMAND_TABLE[mainCommand];
if (spec) return KEY_ARGUMENT_GROUPS.has(spec.group);
// A main that only exists via subcommands (e.g. XGROUP, CONFIG): treat stream/cluster
// subcommand roots as key-taking only for the stream group, conservatively.
return false;
}
export function shouldAutoOpenRedisCompletion(text: string, cursor: number): boolean {
const previousChar = text[cursor - 1];
if (!previousChar) return false;
if (/[\n\r]/.test(previousChar)) return false;
// Open while typing command names or key names (letters/digits/_/:/./-).
if (/[\w:*.-]/.test(previousChar)) return true;
// Just typed a space after a command → open to suggest subcommands / keys.
if (/\s/.test(previousChar)) return true;
return false;
}
export function getRedisCompletionResultValidFor(): RegExp {
return /[\w:*.-]*$/;
}
@@ -0,0 +1,41 @@
import type { AppThemeAppearance } from "@/lib/app/appTheme";
export type RedisJsonHighlighter = (content: string, appearance?: AppThemeAppearance) => string;
interface RedisShikiJsonHighlighterOptions {
appearance: () => AppThemeAppearance;
}
const SHIKI_THEMES = {
dark: "github-dark",
light: "github-light",
} as const;
type ShikiHighlighter = Awaited<ReturnType<typeof import("shiki/core").createHighlighterCore>>;
let highlighterPromise: Promise<ShikiHighlighter> | undefined;
export async function createRedisShikiJsonHighlighter(options: RedisShikiJsonHighlighterOptions): Promise<RedisJsonHighlighter> {
const highlighter = await getRedisShikiHighlighter();
return (content, appearance = options.appearance()) =>
highlighter.codeToHtml(content, {
lang: "json",
structure: "inline",
theme: SHIKI_THEMES[appearance],
});
}
function getRedisShikiHighlighter(): Promise<ShikiHighlighter> {
highlighterPromise ??= loadRedisShikiHighlighter();
return highlighterPromise;
}
async function loadRedisShikiHighlighter(): Promise<ShikiHighlighter> {
const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, json] = await Promise.all([import("shiki/core"), import("shiki/engine/javascript"), import("shiki/themes/github-dark.mjs"), import("shiki/themes/github-light.mjs"), import("shiki/langs/json.mjs")]);
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
langs: [json.default],
themes: [githubDark.default, githubLight.default],
});
}
@@ -0,0 +1,19 @@
const REDIS_GLOB_SPECIAL_CHARS = /[\\*?[\]]/g;
const REDIS_GLOB_SPECIAL_CHARS_FUZZY = /[\\*?[\]]/g;
export function escapeRedisGlobText(value: string, fuzzy = false): string {
return value.replace(fuzzy ? REDIS_GLOB_SPECIAL_CHARS_FUZZY : REDIS_GLOB_SPECIAL_CHARS, "\\$&");
}
export function redisKeySearchPattern(value: string, fuzzy: boolean): string {
const pattern = value.trim();
if (!pattern) return "*";
return fuzzy ? `*${escapeRedisGlobText(pattern, fuzzy)}*` : pattern;
}
// Redis scan page size (COUNT parameter per SCAN round-trip) — shared defaults
// and validation bounds used by the connection form and key browser.
export const REDIS_SCAN_PAGE_SIZE_DEFAULT = 1000;
export const REDIS_SCAN_PAGE_SIZE_MIN = 200;
export const REDIS_SCAN_PAGE_SIZE_MAX = 10_000;
export const REDIS_SCAN_PAGE_SIZE_OPTIONS = [200, 1000, 5000, 10_000] as const;
+239
View File
@@ -0,0 +1,239 @@
import type { RedisKeyInfo } from "@/lib/backend/api";
export interface RedisKeyTreeLeafNode {
kind: "leaf";
id: string;
label: string;
fullKeyDisplay: string;
keyRaw: string;
db: number;
keyType: string;
ttl: number;
size: number;
valuePreview: string;
pathSegments: string[];
}
export interface RedisKeyTreeGroupNode {
kind: "group";
id: string;
label: string;
pathSegments: string[];
children: RedisKeyTreeNode[];
}
export type RedisKeyTreeNode = RedisKeyTreeLeafNode | RedisKeyTreeGroupNode;
export interface RedisKeyTreeRow {
node: RedisKeyTreeNode;
depth: number;
}
export function redisKeyNameCopyText(node: RedisKeyTreeNode): string | null {
// keyRaw is base64-encoded for backend roundtrips; copy the user-visible
// Redis key name instead of the internal transport value.
return node.kind === "leaf" ? node.fullKeyDisplay : null;
}
function buildGroupId(db: number, pathSegments: string[]): string {
return `group:${db}:${pathSegments.join("\u0000")}`;
}
function buildLeafId(db: number, keyRaw: string): string {
return `leaf:${db}:${keyRaw}`;
}
export function redisKeyToFlatTreeRow(key: RedisKeyInfo, db: number): RedisKeyTreeRow {
return {
node: {
kind: "leaf",
id: buildLeafId(db, key.key_raw),
label: key.key_display,
fullKeyDisplay: key.key_display,
keyRaw: key.key_raw,
db,
keyType: key.key_type ?? "",
ttl: key.ttl ?? -2,
size: key.size ?? 0,
valuePreview: key.value_preview ?? "",
pathSegments: [key.key_display],
},
depth: 0,
};
}
function compareRedisTreeNodes(a: RedisKeyTreeNode, b: RedisKeyTreeNode): number {
if (a.kind !== b.kind) return a.kind === "group" ? -1 : 1;
return a.label.localeCompare(b.label);
}
function sortRedisTreeNodes(nodes: RedisKeyTreeNode[]): RedisKeyTreeNode[] {
return [...nodes].sort(compareRedisTreeNodes).map((node) =>
node.kind === "group"
? {
...node,
children: sortRedisTreeNodes(node.children),
}
: node,
);
}
export function buildRedisKeyTree(keys: RedisKeyInfo[], db: number, separator = ":"): RedisKeyTreeNode[] {
const root: RedisKeyTreeNode[] = [];
const groupMap = new Map<string, RedisKeyTreeGroupNode>();
for (const key of keys) {
insertKeyIntoTree(root, groupMap, key, db, separator);
}
return sortRedisTreeNodes(root);
}
function insertKeyIntoTree(root: RedisKeyTreeNode[], groupMap: Map<string, RedisKeyTreeGroupNode>, key: RedisKeyInfo, db: number, separator: string): void {
const pathSegments = separator ? key.key_display.split(separator) : [key.key_display];
if (pathSegments.length === 1) {
root.push({
kind: "leaf",
id: buildLeafId(db, key.key_raw),
label: pathSegments[0],
fullKeyDisplay: key.key_display,
keyRaw: key.key_raw,
db,
keyType: key.key_type ?? "",
ttl: key.ttl ?? -2,
size: key.size ?? 0,
valuePreview: key.value_preview ?? "",
pathSegments,
});
return;
}
let currentLevel = root;
const groupSegments: string[] = [];
for (const segment of pathSegments.slice(0, -1)) {
groupSegments.push(segment);
const groupId = buildGroupId(db, groupSegments);
let group = groupMap.get(groupId);
if (!group) {
group = {
kind: "group",
id: groupId,
label: segment,
pathSegments: [...groupSegments],
children: [],
};
groupMap.set(groupId, group);
currentLevel.push(group);
}
currentLevel = group.children;
}
currentLevel.push({
kind: "leaf",
id: buildLeafId(db, key.key_raw),
label: pathSegments[pathSegments.length - 1],
fullKeyDisplay: key.key_display,
keyRaw: key.key_raw,
db,
keyType: key.key_type ?? "",
ttl: key.ttl ?? -2,
size: key.size ?? 0,
valuePreview: key.value_preview ?? "",
pathSegments,
});
}
function rebuildGroupMap(tree: RedisKeyTreeNode[]): Map<string, RedisKeyTreeGroupNode> {
const groupMap = new Map<string, RedisKeyTreeGroupNode>();
const walk = (nodes: RedisKeyTreeNode[]) => {
for (const node of nodes) {
if (node.kind === "group") {
groupMap.set(node.id, node);
walk(node.children);
}
}
};
walk(tree);
return groupMap;
}
export function mergeKeysIntoRedisKeyTree(existingTree: RedisKeyTreeNode[], newKeys: RedisKeyInfo[], db: number, separator = ":"): RedisKeyTreeNode[] {
if (existingTree.length === 0) return buildRedisKeyTree(newKeys, db, separator);
const groupMap = rebuildGroupMap(existingTree);
const existingKeyIds = new Set<string>();
const collectKeys = (nodes: RedisKeyTreeNode[]) => {
for (const node of nodes) {
if (node.kind === "leaf") {
existingKeyIds.add(node.keyRaw);
} else {
collectKeys(node.children);
}
}
};
collectKeys(existingTree);
for (const key of newKeys) {
if (existingKeyIds.has(key.key_raw)) continue;
insertKeyIntoTree(existingTree, groupMap, key, db, separator);
}
return sortRedisTreeNodes(existingTree);
}
export function collectExpandedGroupIds(nodes: RedisKeyTreeNode[]): Set<string> {
const ids = new Set<string>();
const visit = (entries: RedisKeyTreeNode[]) => {
for (const node of entries) {
if (node.kind !== "group") continue;
ids.add(node.id);
visit(node.children);
}
};
visit(nodes);
return ids;
}
export function collectRedisGroupKeyRaws(group: RedisKeyTreeGroupNode): string[] {
const keyRaws: string[] = [];
const visit = (nodes: RedisKeyTreeNode[]) => {
for (const node of nodes) {
if (node.kind === "leaf") {
keyRaws.push(node.keyRaw);
} else {
visit(node.children);
}
}
};
visit(group.children);
return keyRaws;
}
export function flattenVisibleRedisKeyTree(nodes: RedisKeyTreeNode[], expandedGroupIds: ReadonlySet<string>, depth = 0): RedisKeyTreeRow[] {
const rows: RedisKeyTreeRow[] = [];
const stack: RedisKeyTreeRow[] = [];
for (let index = nodes.length - 1; index >= 0; index--) {
stack.push({ node: nodes[index], depth });
}
while (stack.length > 0) {
const row = stack.pop()!;
rows.push(row);
if (row.node.kind !== "group" || !expandedGroupIds.has(row.node.id)) continue;
const childDepth = row.depth + 1;
for (let index = row.node.children.length - 1; index >= 0; index--) {
stack.push({ node: row.node.children[index], depth: childDepth });
}
}
return rows;
}
@@ -0,0 +1,49 @@
import type { QueryResult } from "@/types/database";
import { formatRedisCommandResult } from "@/lib/redis/redisValuePresentation";
const KEY_VALUE_COMMANDS = new Set(["HGETALL"]);
function isKeyValueCommand(command: string): boolean {
return KEY_VALUE_COMMANDS.has(command.toUpperCase().trim());
}
export function redisCommandResultToQueryResult(value: unknown, elapsedMs: number, command?: string): QueryResult {
if (Array.isArray(value) && command && isKeyValueCommand(command)) {
const rows: (string | number | boolean | null)[][] = [];
for (let i = 0; i + 1 < value.length; i += 2) {
rows.push([formatRedisCommandResult(value[i]), formatRedisCommandResult(value[i + 1])]);
}
return {
columns: ["field", "value"],
rows,
affected_rows: value.length / 2,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
};
}
// INFO commands in cluster mode → [[node_addr, info_text], ...] pairs.
// Render as a two-column table with the addr as the index and info text as the value.
if (Array.isArray(value) && value.length > 0 && value.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string" && typeof item[1] === "string")) {
const rows: (string | number | boolean | null)[][] = value.map((item: [string, string]) => [item[0], item[1]]);
return {
columns: ["(index)", "value"],
rows,
affected_rows: value.length,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
};
}
if (Array.isArray(value)) {
const rows: (string | number | boolean | null)[][] = value.map((item, i) => [i + 1, formatRedisCommandResult(item)]);
return {
columns: ["(index)", "value"],
rows,
affected_rows: value.length,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
};
}
return {
columns: ["result"],
rows: [[formatRedisCommandResult(value)]],
affected_rows: 0,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
};
}
@@ -0,0 +1,224 @@
/**
* Redis command syntax diagnostics for the query editor.
*
* Mirrors the shape of `sqlSemantic/diagnostics.ts` so the editor's diagnostic
* pipeline (StateField + Decoration.mark) can render them with no extra wiring.
* Diagnostics are produced per-line (one Redis command per line — matching the
* execution contract in `queryStore.executeTabSql`).
*/
import type { SqlTextSpan } from "@/types/database";
import type { SqlSemanticDiagnostic } from "@/lib/sql/semantic/diagnostics";
import { resolveRedisCommandSpec } from "@/lib/redis/redisCommandTable";
export interface RedisArgvToken {
/** Token text (raw, case preserved). */
value: string;
/** 1-based start/end character columns within the source line. */
startColumn: number;
endColumn: number;
}
export interface RedisArgvResult {
argv: RedisArgvToken[];
/** True when a quoted string was not closed before end-of-line. */
unclosedQuote: boolean;
/** Column where an unclosed quote started (1-based), if any. */
unclosedQuoteStart?: number;
}
/**
* Tokenize a single Redis command line into argv, mirroring the server-side
* `parse_command_argv` rules (whitespace separation, single/double quotes,
* backslash escapes). Trailing `;` is stripped. Each token records its column
* span so diagnostics can underline the offending token.
*/
export function tokenizeRedisLine(line: string): RedisArgvResult {
const argv: RedisArgvToken[] = [];
let i = 0;
const n = line.length;
let unclosedQuote = false;
let unclosedQuoteStart: number | undefined;
while (i < n) {
// Skip whitespace.
while (i < n && (line[i] === " " || line[i] === "\t")) i++;
if (i >= n) break;
const startColumn = i + 1; // 1-based
let value = "";
let closed = false;
const ch = line[i];
if (ch === '"' || ch === "'") {
if (unclosedQuoteStart === undefined) unclosedQuoteStart = startColumn;
const quote = ch;
i++; // consume opening quote
let escaping = false;
while (i < n) {
const c = line[i];
if (escaping) {
value += c;
escaping = false;
i++;
continue;
}
if (c === "\\") {
escaping = true;
i++;
continue;
}
if (c === quote) {
i++; // consume closing quote
closed = true;
break;
}
value += c;
i++;
}
if (!closed && i >= n) {
unclosedQuote = true;
} else {
// If the quote was closed, allow trailing chars until whitespace as part
// of the same token (e.g. `"a"b` → `ab`) to match common tokenizers.
while (i < n && line[i] !== " " && line[i] !== "\t") {
value += line[i];
i++;
}
}
} else {
closed = true; // unquoted tokens are always complete
while (i < n && line[i] !== " " && line[i] !== "\t") {
if (line[i] === "\\") {
i++;
if (i < n) {
value += line[i];
i++;
}
continue;
}
value += line[i];
i++;
}
}
// Strip a single trailing semicolon (line-level `;` terminator).
if (value.endsWith(";")) value = value.slice(0, -1);
if (value.length > 0 || !closed) {
argv.push({ value, startColumn, endColumn: i + 1 });
}
}
return { argv, unclosedQuote, unclosedQuoteStart };
}
function aritySatisfied(arity: number, tokenCount: number): boolean {
if (arity > 0) return tokenCount === arity;
if (arity < 0) return tokenCount >= -arity;
return true; // arity 0 — unspecified, accept anything
}
function describeArity(arity: number): string {
if (arity > 0) return `exactly ${arity - 1} argument${arity - 1 === 1 ? "" : "s"}`;
if (arity < 0) return `at least ${-arity - 1} argument${-arity - 1 === 1 ? "" : "s"}`;
return "any number of arguments";
}
function lineSpan(lineIndex: number, startColumn: number, endColumn: number): SqlTextSpan {
// SqlTextSpan columns are 1-based and inclusive; map onto the physical line.
return {
start_line: lineIndex,
start_column: startColumn,
end_line: lineIndex,
end_column: endColumn,
};
}
/**
* Build diagnostics for the whole editor source (multi-line). Each non-empty,
* non-comment line is parsed as one Redis command.
*/
export function buildRedisSyntaxDiagnostics(source: string): SqlSemanticDiagnostic[] {
const diagnostics: SqlSemanticDiagnostic[] = [];
const lines = source.split(/\r?\n/);
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const rawLine = lines[lineIndex];
const lineNo = lineIndex + 1; // 1-based line number for SqlTextSpan
if (!rawLine || !rawLine.trim()) continue;
// Skip comment-ish lines (Redis has no official comments, but `#`/`--` are
// commonly used by users as notes).
if (/^\s*(#|--)/.test(rawLine)) continue;
const { argv, unclosedQuote, unclosedQuoteStart } = tokenizeRedisLine(rawLine);
if (unclosedQuote) {
const startCol = unclosedQuoteStart ?? 1;
diagnostics.push({
span: lineSpan(lineNo, startCol, Math.max(rawLine.length, startCol)),
message: "Unclosed quote",
severity: "error",
});
continue; // further checks are unreliable without a clean parse
}
if (argv.length === 0) continue;
const upper = argv.map((token) => token.value.toUpperCase());
const spec = resolveRedisCommandSpec(upper);
const commandToken = argv[0];
if (!spec) {
diagnostics.push({
span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
message: `Unknown command '${argv[0].value}'`,
severity: "error",
});
continue;
}
if (!aritySatisfied(spec.arity, argv.length)) {
diagnostics.push({
span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
message: `Wrong number of arguments for '${argv[0].value}': expected ${describeArity(spec.arity)}, got ${argv.length - 1}`,
severity: "error",
});
// Don't also emit a safety marker on the same token — arity error is clearer.
continue;
}
if (spec.safety === "blocked") {
diagnostics.push({
span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
message: `Blocked command '${argv[0].value}'`,
severity: "error",
});
} else if (spec.safety === "confirm") {
diagnostics.push({
span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
message: `Write command '${argv[0].value}' — will modify data`,
severity: "warning",
});
}
}
return diagnostics;
}
/**
* Gate diagnostics while the user is actively typing the command name on the
* current line, to avoid transient "Unknown command" noise. Mirrors the intent
* of `shouldRunSqlSemanticDiagnostics`.
*/
export function shouldRunRedisDiagnostics(source: string, cursor: number): boolean {
if (!source.trim()) return false;
// Find the line the cursor is on.
const upto = source.slice(0, cursor);
const lineStart = upto.lastIndexOf("\n") + 1;
const lineText = source.slice(lineStart, cursor);
const trimmed = lineText.trimStart();
// If the cursor line only has whitespace and a partial first token with no
// separating whitespace yet, we're still typing the command name → wait.
if (trimmed.length > 0 && !/\s/.test(trimmed)) return false;
return true;
}
@@ -0,0 +1,133 @@
export type RedisMemberDetailFormat = "json" | "text";
export interface RedisMemberDetail {
text: string;
rawText: string;
format: RedisMemberDetailFormat;
json?: RedisJsonDetail;
}
export interface RedisJsonDetail {
rawText: string;
formattedText: string;
value: unknown;
}
export type RedisMemberDetailKind = "list" | "set" | "hash" | "zset" | "stream";
export const REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH = 360;
export const REDIS_MEMBER_DETAIL_SHEET_MAX_WIDTH = 900;
export function canEditRedisMemberDetail(kind: RedisMemberDetailKind): boolean {
return kind !== "stream";
}
export function clampRedisMemberDetailSheetWidth(width: number, viewportWidth: number): number {
const viewportMax = Math.max(REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH, viewportWidth - 32);
return Math.min(Math.min(REDIS_MEMBER_DETAIL_SHEET_MAX_WIDTH, viewportMax), Math.max(REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH, width));
}
export function formatRedisMemberDetail(value: unknown): RedisMemberDetail {
if (typeof value === "string") {
const json = parseRedisJsonDetail(value);
return json ? { text: json.formattedText, rawText: value, format: "json", json } : { text: value, rawText: value, format: "text" };
}
try {
const formattedText = JSON.stringify(value, null, 2);
return {
text: formattedText,
rawText: formattedText,
format: "json",
json: { rawText: formattedText, formattedText, value },
};
} catch {
const text = String(value);
return { text, rawText: text, format: "text" };
}
}
export function formatRedisStringValue(value: unknown): string {
if (typeof value !== "string") return String(value ?? "");
return formatRedisJsonString(value) ?? value;
}
export function formatRedisCommandResult(value: unknown): string {
if (typeof value === "string") return formatRedisStringValue(value);
return JSON.stringify(value, null, 2);
}
/**
* Detect if a value is a cluster-aggregated INFO response:
* `[[addr, infoText], ...]` where each `infoText` starts with `"# "`
* (the INFO section marker). This is the format produced by the backend
* in `redis_driver.rs::execute_command` for cluster-mode INFO.
*/
function isRedisClusterInfoValue(value: unknown): value is [string, string][] {
return Array.isArray(value) && value.length > 0 && (value as unknown[]).every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string" && typeof item[1] === "string" && item[1].startsWith("# "));
}
/**
* Format a Redis command result for the **command console terminal** (RedisKeyBrowser.vue).
* Unlike `formatRedisCommandResult` (used by the query result table UI), this function
* renders cluster-aggregated INFO output as plain text (not JSON), matching the native
* redis-cli display style.
*
* - Cluster INFO `[[addr, infoText], ...]` → `"{addr}\n{infoText}"` per node, joined by newlines.
* - Plain string → passthrough (handles single-node INFO text correctly).
* - Everything else → JSON.stringify (arrays, objects, etc.).
*/
export function formatRedisConsoleValue(value: unknown): string {
if (isRedisClusterInfoValue(value)) {
return value.map(([addr, info]) => `${addr}\n${info}`).join("\n");
}
if (typeof value === "string") return formatRedisStringValue(value);
return JSON.stringify(value, null, 2);
}
function formatRedisJsonString(value: string): string | null {
return parseRedisJsonDetail(value)?.formattedText ?? null;
}
export function parseRedisJsonDetail(value: unknown): RedisJsonDetail | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
if (!looksLikeJsonContainer(trimmed)) return null;
try {
const parsed = JSON.parse(trimmed);
if (!isJsonContainer(parsed)) return null;
return {
rawText: value,
formattedText: JSON.stringify(parsed, null, 2),
value: parsed,
};
} catch {
return null;
}
}
function looksLikeJsonContainer(value: string): boolean {
return (value.startsWith("{") && value.endsWith("}")) || (value.startsWith("[") && value.endsWith("]"));
}
function isJsonContainer(value: unknown): boolean {
return value !== null && typeof value === "object";
}
export function getRedisMemberSelectionKey(title: string, value: unknown): string {
return `${title}\n${formatRedisMemberDetail(value).text}`;
}
export function highlightRedisJsonDetail(json: string): string {
const escaped = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
return escaped.replace(/("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g, (match) => {
let cls = "json-number";
if (match.startsWith('"')) cls = match.endsWith(":") ? "json-key" : "json-string";
else if (match === "true" || match === "false") cls = "json-boolean";
else if (match === "null") cls = "json-null";
return `<span class="${cls}">${match}</span>`;
});
}