/** * JData encoding: JavaScript values (typed and N-D arrays, complex and sparse arrays, maps, byte * streams, NaN and infinities, 64-bit integers) as JData-annotated JSON or BJData values. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ import { Codec, getCodec, bytesToBase64, shuffle, isBuiltinBase64, ZLIB_CODEC, GZIP_CODEC } from './codecs'; import { zlibmtEncodeSync } from './zlibmt'; import { ZipJob } from './payloads'; import { NDArray, SparseArray, ELEM_BYTES, typeOfTypedArray, isTypedArray, arrayOf, product } from './ndarray'; import { floatToHalf } from './half'; export interface EncodeOptions { /** 'json' (default): the result is for JSON (base64 payloads, "_NaN_"/"_Inf_" strings, * numbers in arrays); 'bjdata': for a BJData writer such as bjd (raw payloads, IEEE numbers, * typed arrays left as they are) */ target?: 'json' | 'bjdata'; /** compress the arrays: 'zlib', 'gzip', 'lz4', 'base64', or a registered codec */ compression?: string; /** the fewest elements an array needs to be compressed (default 1) */ compressArraySize?: number; /** shuffle the bytes of the elements before compressing (true: by the element size) */ shuffle?: boolean | number; /** compression level */ level?: number; /** _ArrayZipData_ as base64 text (default: true for JSON, false for BJData) */ base64?: boolean; /** codecs for this call */ codecs?: { [name: string]: Codec }; /** zlib payloads in zlibmt blocks, which zmat, jdai and decodeAsync inflate on several threads * (a standard zlib stream still; default false, and true in encodeAsync) */ zlibmt?: boolean; } const HOST_LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; const MAX_SAFE = 9007199254740991; /** Little-endian bytes of the values of a typed array of JData type t. */ function bytesOf(data: any, t: string): Uint8Array { if (t === 'half' && !(typeOfTypedArray(data) === 'half')) { const b = new Uint8Array(2 * data.length); const v = new DataView(b.buffer); for (let k = 0; k < data.length; k++) { v.setUint16(2 * k, floatToHalf(Number(data[k])), true); } return b; } const b = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); const w = ELEM_BYTES[t]; if (HOST_LITTLE || w === 1) { return b; } const s = b.slice(); for (let k = 0; k < s.length; k += w) { s.subarray(k, k + w).reverse(); } return s; } export class JDataEncoder { private o: EncodeOptions; private json: boolean; private stack: any[] = []; private jobs?: ZipJob[]; /** jobs: zlib and gzip payloads are left there to compress later (encodeAsync) */ constructor(opts: EncodeOptions = {}, jobs?: ZipJob[]) { this.o = opts; this.jobs = jobs; this.json = opts.target !== 'bjdata'; } value(x: any): any { switch (typeof x) { case 'number': if (this.json && !isFinite(x)) { return x !== x ? '_NaN_' : x > 0 ? '_Inf_' : '-_Inf_'; } return x; case 'bigint': if (x >= BigInt(-MAX_SAFE) && x <= BigInt(MAX_SAFE)) { return Number(x); } if (!this.json) { return x; } return this.typed(x < BigInt(0) ? BigInt64Array.from([x]) : BigUint64Array.from([x]), [1]); case 'object': break; default: return x; } if (x === null) { return x; } if (x instanceof Date) { return isNaN(x.getTime()) ? null : x.toISOString(); } if (x instanceof SparseArray) { return this.sparse(x); } if (isTypedArray(x)) { if (!this.json && !this.zip(x.length)) { return x; } return this.typed(x, [x.length]); } if (x instanceof ArrayBuffer || x instanceof DataView) { const b = x instanceof DataView ? new Uint8Array(x.buffer, x.byteOffset, x.byteLength) : new Uint8Array(x); return { _ByteStream_: this.json ? bytesToBase64(b) : b }; } if (this.stack.indexOf(x) >= 0) { throw new Error('jdata: cannot encode a circular structure'); } this.stack.push(x); try { if (Array.isArray(x)) { return x.map((e) => this.value(e)); } if (x instanceof Set) { return Array.from(x, (e) => this.value(e)); } if (x instanceof Map) { return { _MapData_: Array.from(x.entries(), (e) => [this.value(e[0]), this.value(e[1])]) }; } if (x instanceof NDArray) { return this.typed(x.data, x.shape, x.dtype, x.imag); } if (x._ArrayType_ !== undefined && isTypedArray(x._ArrayData_) && x._ArraySize_ !== undefined && Object.keys(x).every((k) => ['_ArrayType_', '_ArraySize_', '_ArrayData_', '_ArrayOrder_'].indexOf(k) >= 0)) { // a packed N-D array read by bjd const shape = Array.from(x._ArraySize_ as ArrayLike, Number); let data = x._ArrayData_; if (x._ArrayOrder_ && String(x._ArrayOrder_)[0].toLowerCase() === 'c') { data = new NDArray(data, shape.slice().reverse()).transpose().data; } return this.typed(data, shape, String(x._ArrayType_)); } const nd = arrayOf(x); if (nd) { return this.typed(nd.data, nd.shape, nd.dtype || undefined); } if (typeof x.toJSON === 'function') { // (its JSON form, encoded too: a toJSON giving a typed array or a BigInt) const y = x.toJSON(); return y === x ? y : this.value(y); } const out: any = {}; for (const k of Object.keys(x)) { const v = x[k]; if (v === undefined || typeof v === 'function' || typeof v === 'symbol') { continue; } if (k === '__proto__') { Object.defineProperty(out, k, { value: this.value(v), writable: true, enumerable: true, configurable: true }); } else { out[k] = this.value(v); } } return out; } finally { this.stack.pop(); } } private zip(n: number): boolean { return !!this.o.compression && n >= (this.o.compressArraySize === undefined ? 1 : this.o.compressArraySize); } /** Adds the compressed payload of typed data of type t (and its annotations) to out. */ private zipInto(out: any, data: any, t: string, method: string, zipsize: number[]): any { out._ArrayZipType_ = method; out._ArrayZipSize_ = zipsize; const w = this.o.shuffle === true ? ELEM_BYTES[t] : Number(this.o.shuffle || 0); if (w > 1) { out._ArrayShuffle_ = w; } out._ArrayZipData_ = this.payload(data, t, method, w, out); return out; } /** The compressed payload of typed data of type t. */ private payload(data: any, t: string, method: string, w: number, out: any): any { let b = bytesOf(data, t); if (w > 1) { b = shuffle(b, w); } const asText = this.o.base64 !== undefined ? this.o.base64 : this.json; if (asText && method.toLowerCase() === 'base64' && isBuiltinBase64(method, this.o.codecs)) { // (the base64 codec: its output is already the text) return bytesToBase64(b); } const z = getCodec(method, this.o.codecs); if (!z.encode) { throw new Error('jdata: the codec ' + method + ' cannot compress'); } if (this.jobs && (z === ZLIB_CODEC || z === GZIP_CODEC)) { // (a copy: the data may change before the threads read it) this.jobs.push({ bytes: b === data || b.buffer === (data && data.buffer) ? b.slice() : b, gz: z === GZIP_CODEC, level: this.o.level === undefined ? 6 : this.o.level, put: (c) => { out._ArrayZipData_ = this.format(c, method, asText); } }); return null; } const c = z === ZLIB_CODEC && this.o.zlibmt ? zlibmtEncodeSync(b, this.o.level === undefined ? 6 : this.o.level) : z.encode(b, { level: this.o.level, type: t }); return this.format(c, method, asText); } /** A compressed payload as _ArrayZipData_. */ private format(c: Uint8Array, method: string, asText: boolean): any { if (asText && method.toLowerCase() === 'base64') { let s = ''; for (let k = 0; k < c.length; k += 8192) { s += String.fromCharCode.apply(null, c.subarray(k, k + 8192) as any); } return s; } // (raw bytes in JSON: a list of byte values) return asText ? bytesToBase64(c) : this.json ? Array.from(c) : c; } /** An annotated N-D array of typed (or plain) data. */ private typed(data: any, shape: number[], dtype?: string, imag?: any): any { const t = dtype || typeOfTypedArray(data) || 'double'; const jt = t === 'logical' ? 'uint8' : t; const out: any = { _ArrayType_: jt, _ArraySize_: shape.slice() }; if (imag !== undefined) { out._ArrayIsComplex_ = true; } const n = product(shape); const big = jt === 'int64' || jt === 'uint64'; // (64-bit integers do not survive as JSON numbers: compressed even when not asked) const method = this.zip(n) ? (this.o.compression as string) : this.json && big ? 'zlib' : null; if (method) { let flat = data; if (imag !== undefined) { const Ctor = data.constructor; flat = new Ctor(2 * n); flat.set(data, 0); flat.set(imag, n); } return this.zipInto(out, isTypedArray(flat) ? flat : Float64Array.from(flat), jt, method, imag !== undefined ? [2, n] : [1, n]); } if (this.json) { const list = (d: any) => { const n = d.length, out = new Array(n); for (let k = 0; k < n; k++) { const v = d[k]; out[k] = typeof v === 'number' ? (v - v === 0 ? v : this.value(v)) : typeof v === 'bigint' ? Number(v) : v; } return out; }; out._ArrayData_ = imag !== undefined ? [list(data), list(imag)] : list(data); } else if (imag !== undefined) { const Ctor = data.constructor; const both = new Ctor(2 * n); both.set(data, 0); both.set(imag, n); out._ArrayData_ = { _ArrayType_: jt, _ArraySize_: [2, n], _ArrayData_: both }; } else { out._ArrayData_ = data; } return out; } private sparse(s: SparseArray): any { const nnz = s.values.length; const rows = s.shape.length + (s.imag !== undefined ? 2 : 1); const Ctor = s.values.constructor === Array ? Float64Array : s.values.constructor; const all = new Ctor(rows * nnz); s.indices.forEach((idx, d) => { for (let k = 0; k < nnz; k++) { all[d * nnz + k] = typeof all[0] === 'bigint' ? BigInt(idx[k] + 1) : idx[k] + 1; } }); all.set(s.values, s.shape.length * nnz); if (s.imag !== undefined) { all.set(s.imag, (s.shape.length + 1) * nnz); } const out: any = { _ArrayType_: s.dtype, _ArraySize_: s.shape.slice(), _ArrayIsSparse_: true }; if (s.imag !== undefined) { out._ArrayIsComplex_ = true; } if (this.zip(rows * nnz)) { return this.zipInto(out, all, s.dtype, this.o.compression as string, [rows, nnz]); } const rowsOut: any[] = []; for (let r = 0; r < rows; r++) { rowsOut.push(Array.from(all.subarray(r * nnz, (r + 1) * nnz) as ArrayLike, Number)); } out._ArrayData_ = this.json ? rowsOut : { _ArrayType_: s.dtype, _ArraySize_: [rows, nnz], _ArrayData_: all }; return out; } } /** The JData-annotated form of a value (for JSON.stringify, or for a BJData writer with * target: 'bjdata'). */ export function encode(value: any, opts: EncodeOptions = {}): any { return new JDataEncoder(opts).value(value); }