32 lines
1.1 KiB
TypeScript
32 lines
1.1 KiB
TypeScript
import { stream } from "../utils/utils.ts";
|
|
|
|
const undefinedBuff = new Blob([new TextEncoder().encode('undefined')]);
|
|
const nullBuff = new Blob([new TextEncoder().encode('null')]);
|
|
|
|
export default async function serialize(val: unknown, depth = 16): Promise<ReadableStream<Uint8Array>> {
|
|
while (true) {
|
|
if (depth <= 0) throw new Error("Call depth exceeded limit.");
|
|
|
|
if (val instanceof Promise) val = await val;
|
|
else if (val instanceof Function) {
|
|
if (val.length !== 0) throw new Error('Can\'t serialize an argument-accepting function');
|
|
val = val();
|
|
}
|
|
else break;
|
|
|
|
depth--;
|
|
}
|
|
|
|
if (val === undefined) return undefinedBuff.stream();
|
|
if (val === null) return nullBuff.stream();
|
|
if (val instanceof Blob) return val.stream();
|
|
if (val instanceof ReadableStream) return val;
|
|
if (val instanceof Uint8Array) return new Blob([val]).stream();
|
|
|
|
if (!(val instanceof Array) && val.toString !== Object.prototype.toString && val.toString instanceof Function) {
|
|
val = val.toString();
|
|
}
|
|
|
|
return stream(JSON.stringify(val));
|
|
}
|