sailfork / t3code-github / .repos/ alchemy-effect/ packages/ redis/ src/ Resp.ts

/**
 * RESP2 + RESP3 codec. Commands are encoded as arrays of bulk strings.
 * Replies are parsed with a length-prefixed recursive reader so values
 * may contain CR/LF/`

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/redis/src/Resp.ts at main · sailfork/t3code-github · Sailfork
	
		
/`*` and may arrive split across TCP frames. * * Spec: https://github.com/redis/redis-specifications/blob/master/protocol/RESP2.md * Algorithm: the same as NodeRedis/node-redis-parser, reimplemented here * so alchemy does not take a Redis client dependency. */ import { ProtocolError, ReplyError } from "./Errors.ts"; export type Arg = string | number | Uint8Array; /** * A decoded RESP value. Nested errors stay as {@link ReplyError} values * (arrays may contain them). Top-level errors fail the command. */ export type Reply = | string | number | boolean | bigint | null | ReplyError | readonly Reply[] | { readonly [key: string]: Reply }; export type ParseResult = | { readonly _tag: "Incomplete" } | { readonly _tag: "Reply"; readonly value: Reply } | { readonly _tag: "Error"; readonly error: ReplyError } | { readonly _tag: "Push"; readonly value: readonly Reply[] } | { readonly _tag: "Protocol"; readonly error: ProtocolError }; const encoder = new TextEncoder(); const decoder = new TextDecoder("utf-8"); const CR = 13; const LF = 10; const CRLF = new Uint8Array([CR, LF]); const PLUS = 43; const MINUS = 45; const COLON = 58; const DOLLAR = 36; const STAR = 42; const UNDERSCORE = 95; const HASH = 35; const COMMA = 44; const LPAREN = 40; const EQUALS = 61; const PERCENT = 37; const TILDE = 126; const PIPE = 124; const GT = 62; const BANG = 33; const DOT = 46; const SEMICOLON = 59; const QUESTION = 63; /** Redis bulk strings are capped at 512 MB. */ const MAX_BULK = 512 * 1024 * 1024; const MAX_AGGREGATE = 1_000_000; export const Incomplete: Extract<ParseResult, { _tag: "Incomplete" }> = { _tag: "Incomplete", }; const concat = (parts: readonly Uint8Array[]): Uint8Array => { let total = 0; for (const part of parts) total += part.length; const out = new Uint8Array(total); let offset = 0; for (const part of parts) { out.set(part, offset); offset += part.length; } return out; }; const bytesOf = (value: string): Uint8Array => encoder.encode(value); const argBytes = (arg: Arg): Uint8Array => { if (typeof arg === "string") return bytesOf(arg); if (typeof arg === "number") return bytesOf(String(arg)); return arg; }; export const encodeSimpleString = (value: string): Uint8Array => concat([bytesOf(`+${value}`), CRLF]); export const encodeError = (value: string): Uint8Array => concat([bytesOf(`-${value}`), CRLF]); export const encodeInteger = (value: number | bigint): Uint8Array => concat([bytesOf(`:${value}`), CRLF]); export const encodeBoolean = (value: boolean): Uint8Array => bytesOf(value ? "#t\r\n" : "#f\r\n"); export const encodeDouble = (value: number): Uint8Array => { if (Number.isNaN(value)) return bytesOf(",nan\r\n"); if (value === Infinity) return bytesOf(",inf\r\n"); if (value === -Infinity) return bytesOf(",-inf\r\n"); return concat([bytesOf(`,${value}`), CRLF]); }; export const encodeBigNumber = (value: bigint): Uint8Array => concat([bytesOf(`(${value}`), CRLF]); export const encodeNull = (): Uint8Array => bytesOf("$-1\r\n"); export const encodeNullArray = (): Uint8Array => bytesOf("*-1\r\n"); export const encodeBulk = (value: string | Uint8Array): Uint8Array => { const payload = typeof value === "string" ? bytesOf(value) : value; return concat([bytesOf(`${payload.length}\r\n`), payload, CRLF]); }; export const encodeArray = (items: readonly Uint8Array[]): Uint8Array => concat([bytesOf(`*${items.length}\r\n`), ...items]); /** Encode a client command as a RESP array of bulk strings. */ export const encodeCommand = (command: string, args: readonly Arg[] = []): Uint8Array => { const parts = [bytesOf(command), ...args.map(argBytes)]; const chunks: Uint8Array[] = [bytesOf(`*${parts.length}\r\n`)]; for (const part of parts) { chunks.push(bytesOf(`${part.length}\r\n`), part, CRLF); } return concat(chunks); }; export const encodeReply = (value: Reply): Uint8Array => { if (value === null) return encodeNull(); if (typeof value === "string") return encodeBulk(value); if (typeof value === "boolean") return encodeBoolean(value); if (typeof value === "bigint") { if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) { return encodeInteger(Number(value)); } return encodeBigNumber(value); } if (typeof value === "number") { return Number.isInteger(value) ? encodeInteger(value) : encodeDouble(value); } if (value instanceof ReplyError) return encodeError(value.message); if (Array.isArray(value)) { return encodeArray(value.map(encodeReply)); } const entries = Object.entries(value); const encoded: Uint8Array[] = [bytesOf(`%${entries.length}\r\n`)]; for (const [key, item] of entries) { encoded.push(encodeSimpleString(key), encodeReply(item)); } return concat(encoded); }; type Line = { readonly text: string; readonly bytes: Uint8Array; readonly next: number; }; type Outcome = | { readonly ok: true; readonly frame: Exclude<ParseResult, { _tag: "Incomplete" | "Protocol" }>; readonly offset: number; } | { readonly ok: false; readonly incomplete: true } | { readonly ok: false; readonly error: ProtocolError }; const INCOMPLETE: Outcome = { ok: false, incomplete: true }; const fail = (message: string): Outcome => ({ ok: false, error: new ProtocolError({ message }), }); const ok = ( frame: Exclude<ParseResult, { _tag: "Incomplete" | "Protocol" }>, offset: number, ): Outcome => ({ ok: true, frame, offset }); const parseLine = (buf: Uint8Array, offset: number): Line | undefined | ProtocolError => { for (let i = offset; i < buf.length; i++) { if (buf[i] === LF) { if (i === offset || buf[i - 1] !== CR) { return new ProtocolError({ message: "expected CRLF line terminator" }); } const bytes = buf.subarray(offset, i - 1); return { text: decoder.decode(bytes), bytes, next: i + 1 }; } } return undefined; }; const parseCount = ( buf: Uint8Array, offset: number, ): | { readonly kind: "null"; readonly next: number } | { readonly kind: "stream"; readonly next: number } | { readonly kind: "n"; readonly n: number; readonly next: number } | { readonly kind: "incomplete" } | { readonly kind: "error"; readonly error: ProtocolError } => { const line = parseLine(buf, offset); if (line === undefined) return { kind: "incomplete" }; if (line instanceof ProtocolError) return { kind: "error", error: line }; if (line.text === "?") return { kind: "stream", next: line.next }; if (line.text === "-1") return { kind: "null", next: line.next }; if (line.text.length === 0 || !/^-?\d+$/.test(line.text)) { return { kind: "error", error: new ProtocolError({ message: `invalid length ${JSON.stringify(line.text)}`, }), }; } const n = Number(line.text); if (!Number.isSafeInteger(n) || n < 0) { return { kind: "error", error: new ProtocolError({ message: `invalid length ${line.text}` }), }; } if (n > MAX_BULK) { return { kind: "error", error: new ProtocolError({ message: `length ${n} exceeds ${MAX_BULK}` }), }; } return { kind: "n", n, next: line.next }; }; const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER); const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER); const parseIntegerValue = (text: string): number | bigint => { if (text.length === 0 || !/^-?\d+$/.test(text)) { throw new ProtocolError({ message: `invalid integer ${JSON.stringify(text)}`, }); } const value = BigInt(text); if (value >= MIN_SAFE && value <= MAX_SAFE) return Number(value); return value; }; const parseErrorLine = (text: string): ReplyError => { const space = text.indexOf(" "); const code = space === -1 ? text : text.slice(0, space); return new ReplyError({ code, message: text }); }; const asElement = (frame: Exclude<ParseResult, { _tag: "Incomplete" | "Protocol" }>): Reply => { if (frame._tag === "Error") return frame.error; if (frame._tag === "Push") return frame.value; return frame.value; }; const parseBulkBody = (buf: Uint8Array, offset: number, n: number): Outcome => { const end = offset + n + 2; if (end > buf.length) return INCOMPLETE; if (buf[offset + n] !== CR || buf[offset + n + 1] !== LF) { return fail("missing CRLF after bulk string"); } return ok({ _tag: "Reply", value: decoder.decode(buf.subarray(offset, offset + n)) }, end); }; const parseStreamedString = (buf: Uint8Array, offset: number): Outcome => { const chunks: Uint8Array[] = []; let cursor = offset; while (true) { if (cursor >= buf.length) return INCOMPLETE; if (buf[cursor] !== SEMICOLON) { return fail("expected streamed string chunk"); } const count = parseCount(buf, cursor + 1); if (count.kind === "incomplete") return INCOMPLETE; if (count.kind === "error") return { ok: false, error: count.error }; if (count.kind !== "n") return fail("invalid streamed string chunk length"); if (count.n === 0) { return ok({ _tag: "Reply", value: decoder.decode(concat(chunks)) }, count.next); } const body = parseBulkBody(buf, count.next, count.n); if (!body.ok) return body; if (body.frame._tag !== "Reply" || typeof body.frame.value !== "string") { return fail("invalid streamed string chunk"); } chunks.push(buf.subarray(count.next, count.next + count.n)); cursor = body.offset; } }; const parseVerbatim = (buf: Uint8Array, offset: number): Outcome => { const count = parseCount(buf, offset); if (count.kind === "incomplete") return INCOMPLETE; if (count.kind === "error") return { ok: false, error: count.error }; if (count.kind !== "n") return fail("invalid verbatim string length"); const body = parseBulkBody(buf, count.next, count.n); if (!body.ok) return body; if (body.frame._tag !== "Reply" || typeof body.frame.value !== "string") { return fail("invalid verbatim string"); } const raw = body.frame.value; const value = raw.length >= 4 && raw[3] === ":" ? raw.slice(4) : raw; return ok({ _tag: "Reply", value }, body.offset); }; const parseBlobError = (buf: Uint8Array, offset: number): Outcome => { const count = parseCount(buf, offset); if (count.kind === "incomplete") return INCOMPLETE; if (count.kind === "error") return { ok: false, error: count.error }; if (count.kind !== "n") return fail("invalid blob error length"); const body = parseBulkBody(buf, count.next, count.n); if (!body.ok) return body; if (body.frame._tag !== "Reply" || typeof body.frame.value !== "string") { return fail("invalid blob error"); } return ok({ _tag: "Error", error: parseErrorLine(body.frame.value) }, body.offset); }; const parseElements = ( buf: Uint8Array, offset: number, n: number, ): { readonly ok: true; readonly values: Reply[]; readonly offset: number } | Outcome => { if (n > MAX_AGGREGATE) { return fail(`aggregate length ${n} exceeds ${MAX_AGGREGATE}`); } const values: Reply[] = []; let cursor = offset; for (let i = 0; i < n; i++) { const next = parseFrame(buf, cursor); if (!next.ok) return next; values.push(asElement(next.frame)); cursor = next.offset; } return { ok: true, values, offset: cursor }; }; const parseStreamedAggregate = ( buf: Uint8Array, offset: number, ): { readonly ok: true; readonly values: Reply[]; readonly offset: number } | Outcome => { const values: Reply[] = []; let cursor = offset; while (true) { if (cursor >= buf.length) return INCOMPLETE; if (buf[cursor] === DOT) { const line = parseLine(buf, cursor + 1); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; if (line.text.length !== 0) return fail("invalid aggregate terminator"); return { ok: true, values, offset: line.next }; } const next = parseFrame(buf, cursor); if (!next.ok) return next; values.push(asElement(next.frame)); cursor = next.offset; if (values.length > MAX_AGGREGATE) { return fail(`aggregate length exceeds ${MAX_AGGREGATE}`); } } }; const pairsToReply = (values: readonly Reply[]): Reply => { if (values.length % 2 !== 0) { return values; } const entries: Array<[Reply, Reply]> = []; for (let i = 0; i < values.length; i += 2) { entries.push([values[i]!, values[i + 1]!]); } const out: Record<string, Reply> = {}; for (const [key, value] of entries) { if (typeof key !== "string") return values; out[key] = value; } return out; }; const parseAggregate = ( buf: Uint8Array, offset: number, kind: "array" | "map" | "set" | "push", ): Outcome => { const count = parseCount(buf, offset); if (count.kind === "incomplete") return INCOMPLETE; if (count.kind === "error") return { ok: false, error: count.error }; if (count.kind === "null") { return ok({ _tag: "Reply", value: null }, count.next); } const parsed = count.kind === "stream" ? parseStreamedAggregate(buf, count.next) : parseElements(buf, count.next, kind === "map" ? count.n * 2 : count.n); if (!("values" in parsed)) return parsed; if (kind === "push") { return ok({ _tag: "Push", value: parsed.values }, parsed.offset); } if (kind === "map") { return ok({ _tag: "Reply", value: pairsToReply(parsed.values) }, parsed.offset); } return ok({ _tag: "Reply", value: parsed.values }, parsed.offset); }; const parseBulk = (buf: Uint8Array, offset: number): Outcome => { const count = parseCount(buf, offset); if (count.kind === "incomplete") return INCOMPLETE; if (count.kind === "error") return { ok: false, error: count.error }; if (count.kind === "null") { return ok({ _tag: "Reply", value: null }, count.next); } if (count.kind === "stream") return parseStreamedString(buf, count.next); return parseBulkBody(buf, count.next, count.n); }; function parseFrame(buf: Uint8Array, offset: number): Outcome { let cursor = offset; while (cursor < buf.length && buf[cursor] === PIPE) { const attrs = parseAggregate(buf, cursor + 1, "map"); if (!attrs.ok) return attrs; cursor = attrs.offset; } if (cursor >= buf.length) return INCOMPLETE; const type = buf[cursor]!; const next = cursor + 1; switch (type) { case PLUS: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; return ok({ _tag: "Reply", value: line.text }, line.next); } case MINUS: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; return ok({ _tag: "Error", error: parseErrorLine(line.text) }, line.next); } case COLON: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; try { return ok({ _tag: "Reply", value: parseIntegerValue(line.text) }, line.next); } catch (error) { return error instanceof ProtocolError ? { ok: false, error } : fail(String(error)); } } case DOLLAR: return parseBulk(buf, next); case STAR: return parseAggregate(buf, next, "array"); case UNDERSCORE: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; if (line.text.length !== 0) return fail("invalid null"); return ok({ _tag: "Reply", value: null }, line.next); } case HASH: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; if (line.text === "t") return ok({ _tag: "Reply", value: true }, line.next); if (line.text === "f") return ok({ _tag: "Reply", value: false }, line.next); return fail(`invalid boolean ${JSON.stringify(line.text)}`); } case COMMA: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; const text = line.text.toLowerCase(); if (text === "nan" || text === "-nan") { return ok({ _tag: "Reply", value: Number.NaN }, line.next); } if (text === "inf") return ok({ _tag: "Reply", value: Infinity }, line.next); if (text === "-inf") { return ok({ _tag: "Reply", value: -Infinity }, line.next); } if (!/^-?(?:\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(line.text)) { return fail(`invalid double ${JSON.stringify(line.text)}`); } return ok({ _tag: "Reply", value: Number(line.text) }, line.next); } case LPAREN: { const line = parseLine(buf, next); if (line === undefined) return INCOMPLETE; if (line instanceof ProtocolError) return { ok: false, error: line }; if (line.text.length === 0 || !/^-?\d+$/.test(line.text)) { return fail(`invalid big number ${JSON.stringify(line.text)}`); } return ok({ _tag: "Reply", value: BigInt(line.text) }, line.next); } case EQUALS: return parseVerbatim(buf, next); case PERCENT: return parseAggregate(buf, next, "map"); case TILDE: return parseAggregate(buf, next, "set"); case GT: return parseAggregate(buf, next, "push"); case BANG: return parseBlobError(buf, next); case QUESTION: return fail("unexpected '?' type byte"); default: return fail( `unexpected type byte ${JSON.stringify(String.fromCharCode(type))} (0x${type.toString(16)})`, ); } } /** * Incremental RESP parser. Feed TCP chunks with {@link Parser.push} and * pull complete frames with {@link Parser.next}. */ export class Parser { #buffer: Uint8Array<ArrayBufferLike> = new Uint8Array(0); #offset = 0; push(chunk: Uint8Array): void { if (chunk.length === 0) return; if (this.#offset >= this.#buffer.length) { this.#buffer = chunk; this.#offset = 0; return; } const remaining = this.#buffer.subarray(this.#offset); const next = new Uint8Array(remaining.length + chunk.length); next.set(remaining, 0); next.set(chunk, remaining.length); this.#buffer = next; this.#offset = 0; } #compact(): void { if (this.#offset === 0) return; if (this.#offset >= this.#buffer.length) { this.#buffer = new Uint8Array(0); this.#offset = 0; return; } this.#buffer = this.#buffer.slice(this.#offset); this.#offset = 0; } /** Unparsed bytes still buffered. */ get pending(): number { return this.#buffer.length - this.#offset; } next(): ParseResult { const result = parseFrame(this.#buffer, this.#offset); if (!result.ok) { if ("incomplete" in result) { this.#compact(); return Incomplete; } return { _tag: "Protocol", error: result.error }; } this.#offset = result.offset; this.#compact(); return result.frame; } } /** Parse one complete frame. Incomplete or leftover bytes are protocol errors. */ export const decode = (bytes: Uint8Array | string): ParseResult => { const buf = typeof bytes === "string" ? bytesOf(bytes) : bytes; const parser = new Parser(); parser.push(buf); const result = parser.next(); if (result._tag === "Incomplete") { return { _tag: "Protocol", error: new ProtocolError({ message: "incomplete RESP value" }), }; } if (parser.pending > 0 && result._tag !== "Protocol") { return { _tag: "Protocol", error: new ProtocolError({ message: "unexpected trailing RESP bytes" }), }; } return result; }; /** Parse every complete frame in `bytes`. Trailing incomplete data errors. */ export const decodeAll = (bytes: Uint8Array | string): ParseResult[] => { const buf = typeof bytes === "string" ? bytesOf(bytes) : bytes; const parser = new Parser(); parser.push(buf); const frames: ParseResult[] = []; while (true) { const result = parser.next(); if (result._tag === "Incomplete") { if (parser.pending > 0 || frames.length === 0) { frames.push({ _tag: "Protocol", error: new ProtocolError({ message: "incomplete RESP value" }), }); } return frames; } frames.push(result); if (result._tag === "Protocol") return frames; } };
.repos/alchemy-effect/packages/redis/src/Resp.ts at main · sailfork/t3code-github · Sailfork
/`*` and may arrive split across TCP frames.\n *\n * Spec: https://github.com/redis/redis-specifications/blob/master/protocol/RESP2.md\n * Algorithm: the same as NodeRedis/node-redis-parser, reimplemented here\n * so alchemy does not take a Redis client dependency.\n */\nimport { ProtocolError, ReplyError } from \"./Errors.ts\";\n\nexport type Arg = string | number | Uint8Array;\n\n/**\n * A decoded RESP value. Nested errors stay as {@link ReplyError} values\n * (arrays may contain them). Top-level errors fail the command.\n */\nexport type Reply =\n | string\n | number\n | boolean\n | bigint\n | null\n | ReplyError\n | readonly Reply[]\n | { readonly [key: string]: Reply };\n\nexport type ParseResult =\n | { readonly _tag: \"Incomplete\" }\n | { readonly _tag: \"Reply\"; readonly value: Reply }\n | { readonly _tag: \"Error\"; readonly error: ReplyError }\n | { readonly _tag: \"Push\"; readonly value: readonly Reply[] }\n | { readonly _tag: \"Protocol\"; readonly error: ProtocolError };\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\");\n\nconst CR = 13;\nconst LF = 10;\nconst CRLF = new Uint8Array([CR, LF]);\n\nconst PLUS = 43;\nconst MINUS = 45;\nconst COLON = 58;\nconst DOLLAR = 36;\nconst STAR = 42;\nconst UNDERSCORE = 95;\nconst HASH = 35;\nconst COMMA = 44;\nconst LPAREN = 40;\nconst EQUALS = 61;\nconst PERCENT = 37;\nconst TILDE = 126;\nconst PIPE = 124;\nconst GT = 62;\nconst BANG = 33;\nconst DOT = 46;\nconst SEMICOLON = 59;\nconst QUESTION = 63;\n\n/** Redis bulk strings are capped at 512 MB. */\nconst MAX_BULK = 512 * 1024 * 1024;\nconst MAX_AGGREGATE = 1_000_000;\n\nexport const Incomplete: Extract\u003cParseResult, { _tag: \"Incomplete\" }> = {\n _tag: \"Incomplete\",\n};\n\nconst concat = (parts: readonly Uint8Array[]): Uint8Array => {\n let total = 0;\n for (const part of parts) total += part.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n};\n\nconst bytesOf = (value: string): Uint8Array => encoder.encode(value);\n\nconst argBytes = (arg: Arg): Uint8Array => {\n if (typeof arg === \"string\") return bytesOf(arg);\n if (typeof arg === \"number\") return bytesOf(String(arg));\n return arg;\n};\n\nexport const encodeSimpleString = (value: string): Uint8Array =>\n concat([bytesOf(`+${value}`), CRLF]);\n\nexport const encodeError = (value: string): Uint8Array => concat([bytesOf(`-${value}`), CRLF]);\n\nexport const encodeInteger = (value: number | bigint): Uint8Array =>\n concat([bytesOf(`:${value}`), CRLF]);\n\nexport const encodeBoolean = (value: boolean): Uint8Array => bytesOf(value ? \"#t\\r\\n\" : \"#f\\r\\n\");\n\nexport const encodeDouble = (value: number): Uint8Array => {\n if (Number.isNaN(value)) return bytesOf(\",nan\\r\\n\");\n if (value === Infinity) return bytesOf(\",inf\\r\\n\");\n if (value === -Infinity) return bytesOf(\",-inf\\r\\n\");\n return concat([bytesOf(`,${value}`), CRLF]);\n};\n\nexport const encodeBigNumber = (value: bigint): Uint8Array => concat([bytesOf(`(${value}`), CRLF]);\n\nexport const encodeNull = (): Uint8Array => bytesOf(\"$-1\\r\\n\");\n\nexport const encodeNullArray = (): Uint8Array => bytesOf(\"*-1\\r\\n\");\n\nexport const encodeBulk = (value: string | Uint8Array): Uint8Array => {\n const payload = typeof value === \"string\" ? bytesOf(value) : value;\n return concat([bytesOf(`${payload.length}\\r\\n`), payload, CRLF]);\n};\n\nexport const encodeArray = (items: readonly Uint8Array[]): Uint8Array =>\n concat([bytesOf(`*${items.length}\\r\\n`), ...items]);\n\n/** Encode a client command as a RESP array of bulk strings. */\nexport const encodeCommand = (command: string, args: readonly Arg[] = []): Uint8Array => {\n const parts = [bytesOf(command), ...args.map(argBytes)];\n const chunks: Uint8Array[] = [bytesOf(`*${parts.length}\\r\\n`)];\n for (const part of parts) {\n chunks.push(bytesOf(`${part.length}\\r\\n`), part, CRLF);\n }\n return concat(chunks);\n};\n\nexport const encodeReply = (value: Reply): Uint8Array => {\n if (value === null) return encodeNull();\n if (typeof value === \"string\") return encodeBulk(value);\n if (typeof value === \"boolean\") return encodeBoolean(value);\n if (typeof value === \"bigint\") {\n if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value \u003c= BigInt(Number.MAX_SAFE_INTEGER)) {\n return encodeInteger(Number(value));\n }\n return encodeBigNumber(value);\n }\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? encodeInteger(value) : encodeDouble(value);\n }\n if (value instanceof ReplyError) return encodeError(value.message);\n if (Array.isArray(value)) {\n return encodeArray(value.map(encodeReply));\n }\n const entries = Object.entries(value);\n const encoded: Uint8Array[] = [bytesOf(`%${entries.length}\\r\\n`)];\n for (const [key, item] of entries) {\n encoded.push(encodeSimpleString(key), encodeReply(item));\n }\n return concat(encoded);\n};\n\ntype Line = {\n readonly text: string;\n readonly bytes: Uint8Array;\n readonly next: number;\n};\n\ntype Outcome =\n | {\n readonly ok: true;\n readonly frame: Exclude\u003cParseResult, { _tag: \"Incomplete\" | \"Protocol\" }>;\n readonly offset: number;\n }\n | { readonly ok: false; readonly incomplete: true }\n | { readonly ok: false; readonly error: ProtocolError };\n\nconst INCOMPLETE: Outcome = { ok: false, incomplete: true };\n\nconst fail = (message: string): Outcome => ({\n ok: false,\n error: new ProtocolError({ message }),\n});\n\nconst ok = (\n frame: Exclude\u003cParseResult, { _tag: \"Incomplete\" | \"Protocol\" }>,\n offset: number,\n): Outcome => ({ ok: true, frame, offset });\n\nconst parseLine = (buf: Uint8Array, offset: number): Line | undefined | ProtocolError => {\n for (let i = offset; i \u003c buf.length; i++) {\n if (buf[i] === LF) {\n if (i === offset || buf[i - 1] !== CR) {\n return new ProtocolError({ message: \"expected CRLF line terminator\" });\n }\n const bytes = buf.subarray(offset, i - 1);\n return { text: decoder.decode(bytes), bytes, next: i + 1 };\n }\n }\n return undefined;\n};\n\nconst parseCount = (\n buf: Uint8Array,\n offset: number,\n):\n | { readonly kind: \"null\"; readonly next: number }\n | { readonly kind: \"stream\"; readonly next: number }\n | { readonly kind: \"n\"; readonly n: number; readonly next: number }\n | { readonly kind: \"incomplete\" }\n | { readonly kind: \"error\"; readonly error: ProtocolError } => {\n const line = parseLine(buf, offset);\n if (line === undefined) return { kind: \"incomplete\" };\n if (line instanceof ProtocolError) return { kind: \"error\", error: line };\n if (line.text === \"?\") return { kind: \"stream\", next: line.next };\n if (line.text === \"-1\") return { kind: \"null\", next: line.next };\n if (line.text.length === 0 || !/^-?\\d+$/.test(line.text)) {\n return {\n kind: \"error\",\n error: new ProtocolError({\n message: `invalid length ${JSON.stringify(line.text)}`,\n }),\n };\n }\n const n = Number(line.text);\n if (!Number.isSafeInteger(n) || n \u003c 0) {\n return {\n kind: \"error\",\n error: new ProtocolError({ message: `invalid length ${line.text}` }),\n };\n }\n if (n > MAX_BULK) {\n return {\n kind: \"error\",\n error: new ProtocolError({ message: `length ${n} exceeds ${MAX_BULK}` }),\n };\n }\n return { kind: \"n\", n, next: line.next };\n};\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\nconst parseIntegerValue = (text: string): number | bigint => {\n if (text.length === 0 || !/^-?\\d+$/.test(text)) {\n throw new ProtocolError({\n message: `invalid integer ${JSON.stringify(text)}`,\n });\n }\n const value = BigInt(text);\n if (value >= MIN_SAFE && value \u003c= MAX_SAFE) return Number(value);\n return value;\n};\n\nconst parseErrorLine = (text: string): ReplyError => {\n const space = text.indexOf(\" \");\n const code = space === -1 ? text : text.slice(0, space);\n return new ReplyError({ code, message: text });\n};\n\nconst asElement = (frame: Exclude\u003cParseResult, { _tag: \"Incomplete\" | \"Protocol\" }>): Reply => {\n if (frame._tag === \"Error\") return frame.error;\n if (frame._tag === \"Push\") return frame.value;\n return frame.value;\n};\n\nconst parseBulkBody = (buf: Uint8Array, offset: number, n: number): Outcome => {\n const end = offset + n + 2;\n if (end > buf.length) return INCOMPLETE;\n if (buf[offset + n] !== CR || buf[offset + n + 1] !== LF) {\n return fail(\"missing CRLF after bulk string\");\n }\n return ok({ _tag: \"Reply\", value: decoder.decode(buf.subarray(offset, offset + n)) }, end);\n};\n\nconst parseStreamedString = (buf: Uint8Array, offset: number): Outcome => {\n const chunks: Uint8Array[] = [];\n let cursor = offset;\n while (true) {\n if (cursor >= buf.length) return INCOMPLETE;\n if (buf[cursor] !== SEMICOLON) {\n return fail(\"expected streamed string chunk\");\n }\n const count = parseCount(buf, cursor + 1);\n if (count.kind === \"incomplete\") return INCOMPLETE;\n if (count.kind === \"error\") return { ok: false, error: count.error };\n if (count.kind !== \"n\") return fail(\"invalid streamed string chunk length\");\n if (count.n === 0) {\n return ok({ _tag: \"Reply\", value: decoder.decode(concat(chunks)) }, count.next);\n }\n const body = parseBulkBody(buf, count.next, count.n);\n if (!body.ok) return body;\n if (body.frame._tag !== \"Reply\" || typeof body.frame.value !== \"string\") {\n return fail(\"invalid streamed string chunk\");\n }\n chunks.push(buf.subarray(count.next, count.next + count.n));\n cursor = body.offset;\n }\n};\n\nconst parseVerbatim = (buf: Uint8Array, offset: number): Outcome => {\n const count = parseCount(buf, offset);\n if (count.kind === \"incomplete\") return INCOMPLETE;\n if (count.kind === \"error\") return { ok: false, error: count.error };\n if (count.kind !== \"n\") return fail(\"invalid verbatim string length\");\n const body = parseBulkBody(buf, count.next, count.n);\n if (!body.ok) return body;\n if (body.frame._tag !== \"Reply\" || typeof body.frame.value !== \"string\") {\n return fail(\"invalid verbatim string\");\n }\n const raw = body.frame.value;\n const value = raw.length >= 4 && raw[3] === \":\" ? raw.slice(4) : raw;\n return ok({ _tag: \"Reply\", value }, body.offset);\n};\n\nconst parseBlobError = (buf: Uint8Array, offset: number): Outcome => {\n const count = parseCount(buf, offset);\n if (count.kind === \"incomplete\") return INCOMPLETE;\n if (count.kind === \"error\") return { ok: false, error: count.error };\n if (count.kind !== \"n\") return fail(\"invalid blob error length\");\n const body = parseBulkBody(buf, count.next, count.n);\n if (!body.ok) return body;\n if (body.frame._tag !== \"Reply\" || typeof body.frame.value !== \"string\") {\n return fail(\"invalid blob error\");\n }\n return ok({ _tag: \"Error\", error: parseErrorLine(body.frame.value) }, body.offset);\n};\n\nconst parseElements = (\n buf: Uint8Array,\n offset: number,\n n: number,\n): { readonly ok: true; readonly values: Reply[]; readonly offset: number } | Outcome => {\n if (n > MAX_AGGREGATE) {\n return fail(`aggregate length ${n} exceeds ${MAX_AGGREGATE}`);\n }\n const values: Reply[] = [];\n let cursor = offset;\n for (let i = 0; i \u003c n; i++) {\n const next = parseFrame(buf, cursor);\n if (!next.ok) return next;\n values.push(asElement(next.frame));\n cursor = next.offset;\n }\n return { ok: true, values, offset: cursor };\n};\n\nconst parseStreamedAggregate = (\n buf: Uint8Array,\n offset: number,\n): { readonly ok: true; readonly values: Reply[]; readonly offset: number } | Outcome => {\n const values: Reply[] = [];\n let cursor = offset;\n while (true) {\n if (cursor >= buf.length) return INCOMPLETE;\n if (buf[cursor] === DOT) {\n const line = parseLine(buf, cursor + 1);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n if (line.text.length !== 0) return fail(\"invalid aggregate terminator\");\n return { ok: true, values, offset: line.next };\n }\n const next = parseFrame(buf, cursor);\n if (!next.ok) return next;\n values.push(asElement(next.frame));\n cursor = next.offset;\n if (values.length > MAX_AGGREGATE) {\n return fail(`aggregate length exceeds ${MAX_AGGREGATE}`);\n }\n }\n};\n\nconst pairsToReply = (values: readonly Reply[]): Reply => {\n if (values.length % 2 !== 0) {\n return values;\n }\n const entries: Array\u003c[Reply, Reply]> = [];\n for (let i = 0; i \u003c values.length; i += 2) {\n entries.push([values[i]!, values[i + 1]!]);\n }\n const out: Record\u003cstring, Reply> = {};\n for (const [key, value] of entries) {\n if (typeof key !== \"string\") return values;\n out[key] = value;\n }\n return out;\n};\n\nconst parseAggregate = (\n buf: Uint8Array,\n offset: number,\n kind: \"array\" | \"map\" | \"set\" | \"push\",\n): Outcome => {\n const count = parseCount(buf, offset);\n if (count.kind === \"incomplete\") return INCOMPLETE;\n if (count.kind === \"error\") return { ok: false, error: count.error };\n if (count.kind === \"null\") {\n return ok({ _tag: \"Reply\", value: null }, count.next);\n }\n\n const parsed =\n count.kind === \"stream\"\n ? parseStreamedAggregate(buf, count.next)\n : parseElements(buf, count.next, kind === \"map\" ? count.n * 2 : count.n);\n if (!(\"values\" in parsed)) return parsed;\n\n if (kind === \"push\") {\n return ok({ _tag: \"Push\", value: parsed.values }, parsed.offset);\n }\n if (kind === \"map\") {\n return ok({ _tag: \"Reply\", value: pairsToReply(parsed.values) }, parsed.offset);\n }\n return ok({ _tag: \"Reply\", value: parsed.values }, parsed.offset);\n};\n\nconst parseBulk = (buf: Uint8Array, offset: number): Outcome => {\n const count = parseCount(buf, offset);\n if (count.kind === \"incomplete\") return INCOMPLETE;\n if (count.kind === \"error\") return { ok: false, error: count.error };\n if (count.kind === \"null\") {\n return ok({ _tag: \"Reply\", value: null }, count.next);\n }\n if (count.kind === \"stream\") return parseStreamedString(buf, count.next);\n return parseBulkBody(buf, count.next, count.n);\n};\n\nfunction parseFrame(buf: Uint8Array, offset: number): Outcome {\n let cursor = offset;\n while (cursor \u003c buf.length && buf[cursor] === PIPE) {\n const attrs = parseAggregate(buf, cursor + 1, \"map\");\n if (!attrs.ok) return attrs;\n cursor = attrs.offset;\n }\n if (cursor >= buf.length) return INCOMPLETE;\n\n const type = buf[cursor]!;\n const next = cursor + 1;\n switch (type) {\n case PLUS: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n return ok({ _tag: \"Reply\", value: line.text }, line.next);\n }\n case MINUS: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n return ok({ _tag: \"Error\", error: parseErrorLine(line.text) }, line.next);\n }\n case COLON: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n try {\n return ok({ _tag: \"Reply\", value: parseIntegerValue(line.text) }, line.next);\n } catch (error) {\n return error instanceof ProtocolError ? { ok: false, error } : fail(String(error));\n }\n }\n case DOLLAR:\n return parseBulk(buf, next);\n case STAR:\n return parseAggregate(buf, next, \"array\");\n case UNDERSCORE: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n if (line.text.length !== 0) return fail(\"invalid null\");\n return ok({ _tag: \"Reply\", value: null }, line.next);\n }\n case HASH: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n if (line.text === \"t\") return ok({ _tag: \"Reply\", value: true }, line.next);\n if (line.text === \"f\") return ok({ _tag: \"Reply\", value: false }, line.next);\n return fail(`invalid boolean ${JSON.stringify(line.text)}`);\n }\n case COMMA: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n const text = line.text.toLowerCase();\n if (text === \"nan\" || text === \"-nan\") {\n return ok({ _tag: \"Reply\", value: Number.NaN }, line.next);\n }\n if (text === \"inf\") return ok({ _tag: \"Reply\", value: Infinity }, line.next);\n if (text === \"-inf\") {\n return ok({ _tag: \"Reply\", value: -Infinity }, line.next);\n }\n if (!/^-?(?:\\d+)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(line.text)) {\n return fail(`invalid double ${JSON.stringify(line.text)}`);\n }\n return ok({ _tag: \"Reply\", value: Number(line.text) }, line.next);\n }\n case LPAREN: {\n const line = parseLine(buf, next);\n if (line === undefined) return INCOMPLETE;\n if (line instanceof ProtocolError) return { ok: false, error: line };\n if (line.text.length === 0 || !/^-?\\d+$/.test(line.text)) {\n return fail(`invalid big number ${JSON.stringify(line.text)}`);\n }\n return ok({ _tag: \"Reply\", value: BigInt(line.text) }, line.next);\n }\n case EQUALS:\n return parseVerbatim(buf, next);\n case PERCENT:\n return parseAggregate(buf, next, \"map\");\n case TILDE:\n return parseAggregate(buf, next, \"set\");\n case GT:\n return parseAggregate(buf, next, \"push\");\n case BANG:\n return parseBlobError(buf, next);\n case QUESTION:\n return fail(\"unexpected '?' type byte\");\n default:\n return fail(\n `unexpected type byte ${JSON.stringify(String.fromCharCode(type))} (0x${type.toString(16)})`,\n );\n }\n}\n\n/**\n * Incremental RESP parser. Feed TCP chunks with {@link Parser.push} and\n * pull complete frames with {@link Parser.next}.\n */\nexport class Parser {\n #buffer: Uint8Array\u003cArrayBufferLike> = new Uint8Array(0);\n #offset = 0;\n\n push(chunk: Uint8Array): void {\n if (chunk.length === 0) return;\n if (this.#offset >= this.#buffer.length) {\n this.#buffer = chunk;\n this.#offset = 0;\n return;\n }\n const remaining = this.#buffer.subarray(this.#offset);\n const next = new Uint8Array(remaining.length + chunk.length);\n next.set(remaining, 0);\n next.set(chunk, remaining.length);\n this.#buffer = next;\n this.#offset = 0;\n }\n\n #compact(): void {\n if (this.#offset === 0) return;\n if (this.#offset >= this.#buffer.length) {\n this.#buffer = new Uint8Array(0);\n this.#offset = 0;\n return;\n }\n this.#buffer = this.#buffer.slice(this.#offset);\n this.#offset = 0;\n }\n\n /** Unparsed bytes still buffered. */\n get pending(): number {\n return this.#buffer.length - this.#offset;\n }\n\n next(): ParseResult {\n const result = parseFrame(this.#buffer, this.#offset);\n if (!result.ok) {\n if (\"incomplete\" in result) {\n this.#compact();\n return Incomplete;\n }\n return { _tag: \"Protocol\", error: result.error };\n }\n this.#offset = result.offset;\n this.#compact();\n return result.frame;\n }\n}\n\n/** Parse one complete frame. Incomplete or leftover bytes are protocol errors. */\nexport const decode = (bytes: Uint8Array | string): ParseResult => {\n const buf = typeof bytes === \"string\" ? bytesOf(bytes) : bytes;\n const parser = new Parser();\n parser.push(buf);\n const result = parser.next();\n if (result._tag === \"Incomplete\") {\n return {\n _tag: \"Protocol\",\n error: new ProtocolError({ message: \"incomplete RESP value\" }),\n };\n }\n if (parser.pending > 0 && result._tag !== \"Protocol\") {\n return {\n _tag: \"Protocol\",\n error: new ProtocolError({ message: \"unexpected trailing RESP bytes\" }),\n };\n }\n return result;\n};\n\n/** Parse every complete frame in `bytes`. Trailing incomplete data errors. */\nexport const decodeAll = (bytes: Uint8Array | string): ParseResult[] => {\n const buf = typeof bytes === \"string\" ? bytesOf(bytes) : bytes;\n const parser = new Parser();\n parser.push(buf);\n const frames: ParseResult[] = [];\n while (true) {\n const result = parser.next();\n if (result._tag === \"Incomplete\") {\n if (parser.pending > 0 || frames.length === 0) {\n frames.push({\n _tag: \"Protocol\",\n error: new ProtocolError({ message: \"incomplete RESP value\" }),\n });\n }\n return frames;\n }\n frames.push(result);\n if (result._tag === \"Protocol\") return frames;\n }\n};\n","preview":null,"history":null,"version":"91f748ce284f9a7ca4c29fd84208cb24ba3eef1f"},"/_session?shell=1":null}