All files / third-parties/langchain/src encoding.ts

100% Statements 9/9
100% Branches 0/0
100% Functions 2/2
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32    3x                     137x 137x 137x 2093x   137x 137x                   13x    
// YDB tags every Float32 vector payload with this trailing byte so the engine
// can route opaque `String` columns to the Knn::* UDFs.
const YDB_VECTOR_MARKER = 0x01
 
/**
 * Pack a JS number array into the binary layout YDB's `Knn::*` UDFs expect:
 * `n × Float32 little-endian + 0x01 marker byte`. The result is stored in a
 * `String` column.
 *
 * `List<Float>` over gRPC is deliberately avoided — per-element protobuf
 * overhead bloats payloads by ~5× for typical embedding sizes.
 */
export function vectorToBytes(vector: number[]): Uint8Array {
	let result = new Uint8Array(vector.length * 4 + 1)
	let view = new DataView(result.buffer)
	for (let i = 0; i < vector.length; i++) {
		view.setFloat32(i * 4, vector[i]!, true)
	}
	result[vector.length * 4] = YDB_VECTOR_MARKER
	return result
}
 
/**
 * Escape a string for use inside a YQL JSON path literal (e.g. `'$.key'`).
 * JSON path keys cannot be passed as bound parameters in YQL, so escaping is
 * the only option. Not used for regular string values — those must be passed
 * as bound query parameters instead.
 */
export function escJsonPathKey(value: string): string {
	return value.replace(/'/g, "''")
}