/** * JSON 序列化与反序列化,支持更多 JS 原生类型,支持全部 ITablePrimitive 类型 * 还支持 :Error, URL */ export const TableJSON = { /** * 解析 Table JSON 字符串,还原特殊类型 * 通过检查字符串开头快速判断是否需要解包 */ parse(text: string, reviver?: (this: any, key: string, value: any) => any): any { // 快速路径:检查字符串开头是否有 TABLE_WRAP_KEY 标记 // TABLE_WRAP_KEY 总是放在对象最前面,所以只需检查开头 const hasTableMark = text.startsWith(TABLE_WRAP_PREFIX) if (!hasTableMark) { // 普通 JSON,直接使用原生 JSON.parse return JSON.parse(text, reviver) } // 有标记,需要解包特殊类型 const parsed = JSON.parse(text) return unwrapValue(parsed, reviver) }, /** * 将 JS 数据序列化为 JSON 字符串 * 支持更多 JS 原生类型: * - `Date`, `RegExp`, `Map`, `Set`, `bigint`, `ArrayBuffer`, `DataView`, 所有 TypedArray 类型 * - `Error`, `URL` */ stringify( value: any, replacer?: ((this: any, key: string, value: any) => any) | null, space?: string | number ): string { // 有 space 或 replacer 时使用原来的方式(保证格式化输出正确) if (space !== undefined || replacer) { const wrapped = wrapValue(value, replacer as any) return JSON.stringify(wrapped, null, space) } // 无格式化时使用直接序列化(更快) return stringifyDirect(value) }, /** * 注册自定义类型处理器 */ registerType(handler: TypeHandler): void { registerTypeHandler(handler) }, } // ---------------------------------------------------------- // 包装类型的标识符 const TYPE_KEY = "ஐ" const VALUE_KEY = "𐆗" const TABLE_WRAP_KEY = "⧃▤" // 预计算的常量字符串 const WRAP_PREFIX = '{"ஐ":"' const WRAP_MID = '","𐆗":' const WRAP_SUFFIX = "}" // Error cause 支持(最多 3 层) const MAX_ERROR_CAUSE_DEPTH = 3 const ERROR_CAUSE_MARK = "__error__" // TABLE_WRAP_KEY 前缀,用于快速检测字符串开头 const TABLE_WRAP_PREFIX = '{"⧃▤":""' // 类型处理器接口 interface TypeHandler { // 类型名称 name: string // 检查是否是该类型 check: (value: any) => boolean // 将值序列化为可 JSON 化的格式 serialize: (value: T) => any // 从序列化格式还原值 deserialize: (data: any) => T // 直接序列化为字符串(可选,用于优化) stringifyDirect?: (value: T) => string } // 类型处理器注册表 - 使用 Map 快速按名称查找 const typeHandlersByName = new Map() // 按 constructor.name 索引的处理器 - 用于快速类型匹配 const typeHandlersByConstructor = new Map() // 需要特殊检查的处理器(如 bigint, undefined) const specialTypeHandlers: TypeHandler[] = [] // 注册类型处理器 function registerTypeHandler(handler: TypeHandler): void { typeHandlersByName.set(handler.name, handler) // 对于有对应 constructor 的类型,添加快速索引 if (handler.name !== "undefined" && handler.name !== "bigint") { typeHandlersByConstructor.set(handler.name, handler) } else { specialTypeHandlers.push(handler) } } // 根据类型名称获取处理器(O(1) 查找) function getHandlerByName(name: string): TypeHandler | undefined { return typeHandlersByName.get(name) } // ===================== 注册内置类型处理器 ===================== // undefined registerTypeHandler({ name: "undefined", check: (value) => value === undefined, serialize: () => null, deserialize: () => undefined, stringifyDirect: () => WRAP_PREFIX + "undefined" + WRAP_MID + "null" + WRAP_SUFFIX, }) // Date registerTypeHandler({ name: "Date", check: (value) => value instanceof Date, serialize: (value) => value.toISOString(), deserialize: (data) => new Date(data), stringifyDirect: (value) => WRAP_PREFIX + "Date" + WRAP_MID + '"' + value.toISOString() + '"' + WRAP_SUFFIX, }) // RegExp registerTypeHandler({ name: "RegExp", check: (value) => value instanceof RegExp, serialize: (value) => ({ source: value.source, flags: value.flags }), deserialize: (data) => new RegExp(data.source, data.flags), stringifyDirect: (value) => WRAP_PREFIX + "RegExp" + WRAP_MID + '{"source":' + JSON.stringify(value.source) + ',"flags":"' + value.flags + '"}' + WRAP_SUFFIX, }) // Map registerTypeHandler>({ name: "Map", check: (value) => value instanceof Map, serialize: (value) => Array.from(value.entries()), deserialize: (data) => { // data 已经被 unwrapValue 处理过,entries 中的特殊类型已被解包 return new Map(data) }, // Map 的 value 可能包含特殊类型,需要递归处理 }) // Set registerTypeHandler>({ name: "Set", check: (value) => value instanceof Set, serialize: (value) => Array.from(value), deserialize: (data) => { // data 已经被 unwrapValue 处理过,元素中的特殊类型已被解包 return new Set(data) }, // Set 的 value 可能包含特殊类型,需要递归处理 }) // bigint registerTypeHandler({ name: "bigint", check: (value) => typeof value === "bigint", serialize: (value) => value.toString(), deserialize: (data) => BigInt(data), stringifyDirect: (value) => WRAP_PREFIX + "bigint" + WRAP_MID + '"' + value.toString() + '"' + WRAP_SUFFIX, }) // ArrayBuffer registerTypeHandler({ name: "ArrayBuffer", check: (value) => value instanceof ArrayBuffer, serialize: (value) => Array.from(new Uint8Array(value)), deserialize: (data) => new Uint8Array(data).buffer, stringifyDirect: (value) => WRAP_PREFIX + "ArrayBuffer" + WRAP_MID + "[" + Array.from(new Uint8Array(value)).join(",") + "]" + WRAP_SUFFIX, }) // DataView registerTypeHandler({ name: "DataView", check: (value) => value instanceof DataView, serialize: (value) => Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)), deserialize: (data) => new DataView(new Uint8Array(data).buffer), stringifyDirect: (value) => WRAP_PREFIX + "DataView" + WRAP_MID + "[" + Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)).join(",") + "]" + WRAP_SUFFIX, }) // TypedArray 处理器工厂 function createTypedArrayHandler( name: string, TypedArrayClass: { new (arr: any[]): T; new (buffer: ArrayBuffer): T }, isBigInt = false ): TypeHandler { return { name, check: (value) => value instanceof TypedArrayClass, serialize: isBigInt ? (value) => Array.from(value as any, (v: bigint) => v.toString()) : (value) => Array.from(value as any), deserialize: isBigInt ? (data) => new TypedArrayClass(data.map((v: string) => BigInt(v))) : (data) => new TypedArrayClass(data), stringifyDirect: isBigInt ? (value) => WRAP_PREFIX + name + WRAP_MID + "[" + Array.from(value as any, (v: bigint) => '"' + v.toString() + '"').join(",") + "]" + WRAP_SUFFIX : (value) => WRAP_PREFIX + name + WRAP_MID + "[" + Array.from(value as any).join(",") + "]" + WRAP_SUFFIX, } } // 注册所有 TypedArray 类型 registerTypeHandler(createTypedArrayHandler("Int8Array", Int8Array)) registerTypeHandler(createTypedArrayHandler("Int16Array", Int16Array)) registerTypeHandler(createTypedArrayHandler("Int32Array", Int32Array)) registerTypeHandler(createTypedArrayHandler("Uint8Array", Uint8Array)) registerTypeHandler(createTypedArrayHandler("Uint8ClampedArray", Uint8ClampedArray)) registerTypeHandler(createTypedArrayHandler("Uint16Array", Uint16Array)) registerTypeHandler(createTypedArrayHandler("Uint32Array", Uint32Array)) registerTypeHandler(createTypedArrayHandler("Float32Array", Float32Array)) registerTypeHandler(createTypedArrayHandler("Float64Array", Float64Array)) registerTypeHandler(createTypedArrayHandler("BigInt64Array", BigInt64Array, true)) registerTypeHandler(createTypedArrayHandler("BigUint64Array", BigUint64Array, true)) // Error registerTypeHandler({ name: "Error", check: (value) => value instanceof Error, serialize: (value) => serializeErrorData(value, MAX_ERROR_CAUSE_DEPTH), deserialize: (data) => deserializeErrorData(data, MAX_ERROR_CAUSE_DEPTH), stringifyDirect: (value) => WRAP_PREFIX + "Error" + WRAP_MID + stringifyValue(serializeErrorData(value, MAX_ERROR_CAUSE_DEPTH)) + WRAP_SUFFIX, }) // Error 序列化(最多 3 层 cause) function serializeErrorData(error: Error, depth: number): any { const data: any = { [ERROR_CAUSE_MARK]: 1, name: error.name, message: error.message, stack: error.stack, } if (depth > 0 && "cause" in (error as any)) { const cause = (error as any).cause if (cause instanceof Error) { data.cause = serializeErrorData(cause, depth - 1) } else { data.cause = cause } } return data } // Error 反序列化(最多 3 层 cause) function deserializeErrorData(data: any, depth: number): Error { const error = new Error(data?.message) error.name = data?.name ?? "Error" if (data?.stack) error.stack = data.stack if (depth > 0 && data && "cause" in data) { const cause = data.cause if (cause && cause[ERROR_CAUSE_MARK] === 1) { ;(error as any).cause = deserializeErrorData(cause, depth - 1) } else { ;(error as any).cause = cause } } return error } // URL registerTypeHandler({ name: "URL", check: (value) => value instanceof URL, serialize: (value) => value.href, deserialize: (data) => new URL(data), stringifyDirect: (value) => WRAP_PREFIX + "URL" + WRAP_MID + '"' + value.href + '"' + WRAP_SUFFIX, }) // ===================== 直接序列化实现(核心优化) ===================== /** * 快速检测对象是否包含需要特殊处理的类型 * 使用栈避免递归 */ function hasSpecialTypes(rootValue: any): boolean { if (rootValue === null) return false const type = typeof rootValue if (type === "bigint" || type === "undefined") return true if (type !== "object") return false // 检查是否是特殊对象类型 const constructorName = rootValue.constructor?.name if (constructorName && typeHandlersByConstructor.has(constructorName)) { return true } if (rootValue instanceof Error) return true // 对于普通对象和数组,检查子元素 const stack: any[] = [rootValue] while (stack.length > 0) { const obj = stack.pop() if (Array.isArray(obj)) { for (let i = 0; i < obj.length; i++) { const val = obj[i] if (val === null) continue const valType = typeof val if (valType === "bigint" || valType === "undefined") return true if (valType !== "object") continue const valConstructor = val.constructor?.name if (valConstructor && typeHandlersByConstructor.has(valConstructor)) { return true } if (val instanceof Error) return true stack.push(val) } } else { const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { const val = obj[keys[i]] if (val === null) continue const valType = typeof val if (valType === "bigint" || valType === "undefined") return true if (valType !== "object") continue const valConstructor = val.constructor?.name if (valConstructor && typeHandlersByConstructor.has(valConstructor)) { return true } if (val instanceof Error) return true stack.push(val) } } } return false } /** * 直接生成 JSON 字符串,不创建中间对象 * 使用栈模拟递归,避免栈溢出 */ /** * 直接序列化值(内部递归使用,不添加 TABLE_WRAP_KEY) */ function stringifyValue(value: any): string { const type = typeof value // 快速路径:基本类型 if (value === null) return "null" if (type === "string") return JSON.stringify(value) if (type === "number") return Number.isFinite(value) ? String(value) : "null" if (type === "boolean") return value ? "true" : "false" // 特殊基本类型 if (type === "undefined") return WRAP_PREFIX + "undefined" + WRAP_MID + "null" + WRAP_SUFFIX if (type === "bigint") return WRAP_PREFIX + "bigint" + WRAP_MID + '"' + value.toString() + '"' + WRAP_SUFFIX // 对象类型 const constructorName = value.constructor?.name if (constructorName) { const handler = typeHandlersByConstructor.get(constructorName) if (handler) { if (handler.stringifyDirect) { return handler.stringifyDirect(value) } const serialized = handler.serialize(value) return WRAP_PREFIX + handler.name + WRAP_MID + stringifyValue(serialized) + WRAP_SUFFIX } } // Error 子类特殊处理 if (value instanceof Error) { const handler = typeHandlersByName.get("Error")! return handler.stringifyDirect!(value) } // 普通对象/数组:先快速检测是否有特殊类型 if (!hasSpecialTypes(value)) { return JSON.stringify(value) } // 有特殊类型,递归序列化 if (Array.isArray(value)) { return stringifyArrayWithSpecialTypes(value) } // 对象类型 return stringifyObjectWithSpecialTypes(value) } /** * 序列化包含特殊类型的对象 */ function stringifyObjectWithSpecialTypes(obj: Record): string { const parts: string[] = ["{"] const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { if (i > 0) parts.push(",") const key = keys[i] parts.push('"' + key + '":') parts.push(stringifyValue(obj[key])) } parts.push("}") return parts.join("") } /** * 根级别序列化 - 添加 TABLE_WRAP_KEY 标记 */ function stringifyDirect(rootValue: any): string { const type = typeof rootValue // 快速路径:基本类型(不需要 TABLE_WRAP_KEY) if (rootValue === null) return "null" if (type === "string") return JSON.stringify(rootValue) if (type === "number") return Number.isFinite(rootValue) ? String(rootValue) : "null" if (type === "boolean") return rootValue ? "true" : "false" // 特殊基本类型:需要 TABLE_WRAP_KEY if (type === "undefined") return TABLE_WRAP_PREFIX + ',"\u0b90":"undefined","\ud800\udd97":null}' if (type === "bigint") return TABLE_WRAP_PREFIX + ',"\u0b90":"bigint","\ud800\udd97":"' + rootValue.toString() + '"}' // 对象类型 const constructorName = rootValue.constructor?.name if (constructorName) { const handler = typeHandlersByConstructor.get(constructorName) if (handler) { // 单个特殊类型作为根值,需要添加 TABLE_WRAP_KEY if (handler.stringifyDirect) { const inner = handler.stringifyDirect(rootValue) // inner 是 {"\u0b90":"Type",...},需要插入 TABLE_WRAP_KEY return TABLE_WRAP_PREFIX + ',' + inner.slice(1) } // 没有 stringifyDirect 的类型(如 Map, Set) const serialized = handler.serialize(rootValue) return TABLE_WRAP_PREFIX + ',"\u0b90":"' + handler.name + '","\ud800\udd97":' + stringifyValue(serialized) + '}' } } // Error 子类特殊处理 if (rootValue instanceof Error) { const handler = typeHandlersByName.get("Error")! const inner = handler.stringifyDirect!(rootValue) return TABLE_WRAP_PREFIX + ',' + inner.slice(1) } // 普通对象/数组:先快速检测是否有特殊类型 // 如果没有,直接用 JSON.stringify(更快) if (!hasSpecialTypes(rootValue)) { return JSON.stringify(rootValue) } // 有特殊类型,需要添加 TABLE_WRAP_KEY 标记 const isRootArray = Array.isArray(rootValue) // 对于数组,使用包装对象: {"⧃▤":"", "𐆗": [...]} if (isRootArray) { return TABLE_WRAP_PREFIX + ',"' + VALUE_KEY + '":' + stringifyArrayWithSpecialTypes(rootValue) + '}' } // 对象类型,在开头添加 TABLE_WRAP_KEY 标记 const parts: string[] = [TABLE_WRAP_PREFIX] // 栈元素类型 type StackItem = { value: any keys: string[] | null // null 表示数组 index: number isFirst: boolean } const stack: StackItem[] = [ { value: rootValue, keys: Object.keys(rootValue), index: 0, isFirst: false, // 已经有 TABLE_WRAP_KEY 了,不是第一个 }, ] while (stack.length > 0) { const current = stack[stack.length - 1] const obj = current.value const isArray = current.keys === null const length = isArray ? obj.length : current.keys!.length if (current.index >= length) { // 结束当前对象/数组 parts.push(isArray ? "]" : "}") stack.pop() continue } const key = isArray ? current.index : current.keys![current.index] const val = obj[key] current.index++ // 添加逗号 if (!current.isFirst) { parts.push(",") } current.isFirst = false // 添加 key(对象需要) if (!isArray) { parts.push('"') parts.push(key as string) parts.push('":') } // 处理值 const valType = typeof val if (val === null) { parts.push("null") continue } if (valType === "string") { parts.push(JSON.stringify(val)) continue } if (valType === "number") { parts.push(Number.isFinite(val) ? String(val) : "null") continue } if (valType === "boolean") { parts.push(val ? "true" : "false") continue } if (valType === "undefined") { parts.push(WRAP_PREFIX + "undefined" + WRAP_MID + "null" + WRAP_SUFFIX) continue } if (valType === "bigint") { parts.push(WRAP_PREFIX + "bigint" + WRAP_MID + '"' + val.toString() + '"' + WRAP_SUFFIX) continue } // 对象类型 const valConstructor = val.constructor?.name if (valConstructor) { const handler = typeHandlersByConstructor.get(valConstructor) if (handler) { if (handler.stringifyDirect) { parts.push(handler.stringifyDirect(val)) } else { const serialized = handler.serialize(val) parts.push(WRAP_PREFIX + handler.name + WRAP_MID + stringifyValue(serialized) + WRAP_SUFFIX) } continue } } // Error 子类 if (val instanceof Error) { const handler = typeHandlersByName.get("Error")! parts.push(handler.stringifyDirect!(val)) continue } // 普通对象或数组 - 推入栈 const isChildArray = Array.isArray(val) parts.push(isChildArray ? "[" : "{") stack.push({ value: val, keys: isChildArray ? null : Object.keys(val), index: 0, isFirst: true, }) } return parts.join("") } /** * 序列化包含特殊类型的数组(不带外层括号,用于 stringifyDirect 的数组包装) */ function stringifyArrayWithSpecialTypes(arr: any[]): string { const parts: string[] = ["["] for (let i = 0; i < arr.length; i++) { if (i > 0) parts.push(",") const val = arr[i] const valType = typeof val if (val === null) { parts.push("null") continue } if (valType === "string") { parts.push(JSON.stringify(val)) continue } if (valType === "number") { parts.push(Number.isFinite(val) ? String(val) : "null") continue } if (valType === "boolean") { parts.push(val ? "true" : "false") continue } if (valType === "undefined") { parts.push(WRAP_PREFIX + "undefined" + WRAP_MID + "null" + WRAP_SUFFIX) continue } if (valType === "bigint") { parts.push(WRAP_PREFIX + "bigint" + WRAP_MID + '"' + val.toString() + '"' + WRAP_SUFFIX) continue } // 对象类型 const valConstructor = val.constructor?.name if (valConstructor) { const handler = typeHandlersByConstructor.get(valConstructor) if (handler) { if (handler.stringifyDirect) { parts.push(handler.stringifyDirect(val)) } else { const serialized = handler.serialize(val) parts.push(WRAP_PREFIX + handler.name + WRAP_MID + stringifyValue(serialized) + WRAP_SUFFIX) } continue } } // Error 子类 if (val instanceof Error) { const handler = typeHandlersByName.get("Error")! parts.push(handler.stringifyDirect!(val)) continue } // 普通对象或嵌套数组 if (hasSpecialTypes(val)) { parts.push(stringifyValue(val)) } else { parts.push(JSON.stringify(val)) } } parts.push("]") return parts.join("") } // ===================== 原有的 wrapValue 实现(用于格式化输出) ===================== // 栈元素类型 interface WrapStackItem { source: any target: any keys: string[] index: number } // 预分配的包装对象池(减少 GC 压力) function createWrapped(typeName: string, value: any): any { return { [TYPE_KEY]: typeName, [VALUE_KEY]: value } } /** * 使用循环方式包装对象中的特殊类型 * 返回一个新的对象,其中特殊类型被包装为 {ஐ: type, 𐆗: value} 格式 * 如果包含特殊类型,会在根对象添加 TABLE_WRAP_KEY 标记 */ function wrapValue(rootValue: any, replacer?: (this: any, key: string, value: any) => any): any { // 快速路径:基本类型 const rootType = typeof rootValue // 处理 bigint - 需要包装并添加标记在前面 if (rootType === "bigint") { return { [TABLE_WRAP_KEY]: "", [TYPE_KEY]: "bigint", [VALUE_KEY]: rootValue.toString() } } // 处理 undefined - 需要包装并添加标记在前面 if (rootType === "undefined") { return { [TABLE_WRAP_KEY]: "", [TYPE_KEY]: "undefined", [VALUE_KEY]: null } } // 其他基本类型直接返回(不需要标记) if (rootValue === null || rootType !== "object") { return rootValue } // 检查是否是特殊对象类型 const rootConstructor = rootValue.constructor?.name if (rootConstructor) { const handler = typeHandlersByConstructor.get(rootConstructor) if (handler) { const serialized = handler.serialize(rootValue) const wrappedSerialized = wrapValue(serialized, undefined) // 标记在前面 return { [TABLE_WRAP_KEY]: "", [TYPE_KEY]: handler.name, [VALUE_KEY]: wrappedSerialized } } } // Error 特殊处理 if (rootValue instanceof Error) { const handler = typeHandlersByName.get("Error")! return { [TABLE_WRAP_KEY]: "", [TYPE_KEY]: "Error", [VALUE_KEY]: handler.serialize(rootValue) } } // 复杂类型使用栈进行迭代处理 const isRootArray = Array.isArray(rootValue) const result: any = isRootArray ? new Array(rootValue.length) : {} const stack: WrapStackItem[] = [ { source: rootValue, target: result, keys: isRootArray ? null! : Object.keys(rootValue), index: 0, }, ] while (stack.length > 0) { const current = stack[stack.length - 1] const source = current.source const target = current.target const isArray = Array.isArray(source) const length = isArray ? source.length : current.keys.length if (current.index >= length) { stack.pop() continue } const key = isArray ? current.index : current.keys[current.index] current.index++ let value = source[key] const originalUndefined = value === undefined // 应用 replacer if (replacer) { value = replacer.call(source, String(key), value) // 如果 replacer 返回 undefined(且原始值不是 undefined),跳过此属性(与 JSON.stringify 行为一致) if (value === undefined && !originalUndefined) { continue } } // 快速路径:检查值类型 const valueType = typeof value // 处理 undefined if (valueType === "undefined") { target[key] = createWrapped("undefined", null) continue } // 处理 bigint if (valueType === "bigint") { target[key] = createWrapped("bigint", value.toString()) continue } // 基本类型直接赋值 if (value === null || valueType !== "object") { target[key] = value continue } // 检查是否是特殊对象类型 const constructorName = value.constructor?.name if (constructorName) { const handler = typeHandlersByConstructor.get(constructorName) if (handler) { const serialized = handler.serialize(value) const wrappedSerialized = wrapValue(serialized, undefined) target[key] = createWrapped(handler.name, wrappedSerialized) continue } } // Error 特殊处理 if (value instanceof Error) { const handler = typeHandlersByName.get("Error")! target[key] = createWrapped("Error", handler.serialize(value)) continue } // 处理普通对象和数组 const isChildArray = Array.isArray(value) const childTarget = isChildArray ? new Array(value.length) : {} target[key] = childTarget stack.push({ source: value, target: childTarget, keys: isChildArray ? null! : Object.keys(value), index: 0, }) } // 检查是否有特殊类型需要标记 if (hasSpecialTypes(rootValue)) { if (isRootArray) { // 数组需要用包装对象: {"⧃▤":"", "𐆗": [...]} return { [TABLE_WRAP_KEY]: "", [VALUE_KEY]: result } } else { // 对象:在开头添加标记,通过创建新对象确保顺序 return { [TABLE_WRAP_KEY]: "", ...result } } } return result } // ===================== unwrapValue 实现 ===================== // 解包栈元素类型 interface UnwrapStackItem { source: any target: any keys: string[] index: number nodesToProcess: UnwrapNode[] } interface UnwrapNode { source: any parent: any key: string | number } /** * 使用循环方式解包对象中的包装类型 * TABLE_WRAP_KEY 只在根对象存在,内部不需要检查 */ function unwrapValue(rootValue: any, reviver?: (this: any, key: string, value: any) => any): any { // 基本类型直接返回 if (rootValue === null || typeof rootValue !== "object") { if (reviver) { return reviver.call({ "": rootValue }, "", rootValue) } return rootValue } // 检查根值是否是包装类型(单个特殊值,如 Date, bigint 等) if (TYPE_KEY in rootValue && VALUE_KEY in rootValue) { const handler = typeHandlersByName.get(rootValue[TYPE_KEY]) if (handler) { const unwrappedInner = unwrapValue(rootValue[VALUE_KEY], undefined) const result = handler.deserialize(unwrappedInner) if (reviver) { return reviver.call({ "": result }, "", result) } return result } } // 检查是否是数组包装 {"⧃▤":"", "𐆗": [...]} // 这种情况发生在根值是数组且包含特殊类型时 if (TABLE_WRAP_KEY in rootValue && VALUE_KEY in rootValue && !(TYPE_KEY in rootValue)) { const arrayValue = rootValue[VALUE_KEY] const result = unwrapValue(arrayValue, undefined) if (reviver) { return applyReviver(result, reviver) } return result } // 根对象可能有 TABLE_WRAP_KEY 标记,需要跳过 const hasRootMarker = TABLE_WRAP_KEY in rootValue // 复杂类型使用栈进行迭代处理 const isRootArray = Array.isArray(rootValue) const result: any = isRootArray ? new Array(rootValue.length) : {} // 收集需要解包的节点 const allNodesToProcess: UnwrapNode[] = [] // 根对象的 keys 需要过滤掉 TABLE_WRAP_KEY const rootKeys = isRootArray ? null : Object.keys(rootValue).filter(k => k !== TABLE_WRAP_KEY) const stack: { source: any; target: any; keys: string[] | null; index: number }[] = [ { source: rootValue, target: result, keys: rootKeys, index: 0, }, ] while (stack.length > 0) { const current = stack[stack.length - 1] const source = current.source const target = current.target const isArray = Array.isArray(source) const length = isArray ? source.length : current.keys!.length if (current.index >= length) { stack.pop() continue } const key = isArray ? current.index : current.keys![current.index] current.index++ const value = source[key] // 基本类型直接复制 if (value === null || typeof value !== "object") { target[key] = value continue } // 检查是否是包装类型(特殊值) if (TYPE_KEY in value && VALUE_KEY in value) { allNodesToProcess.push({ source: value, parent: target, key: key, }) target[key] = value // 占位符 continue } // 普通对象或数组 const isChildArray = Array.isArray(value) const childTarget = isChildArray ? new Array(value.length) : {} target[key] = childTarget stack.push({ source: value, target: childTarget, keys: isChildArray ? null : Object.keys(value), index: 0, }) } // 从后向前处理包装类型(确保嵌套的先处理) for (let i = allNodesToProcess.length - 1; i >= 0; i--) { const node = allNodesToProcess[i] const wrapped = node.source const handler = typeHandlersByName.get(wrapped[TYPE_KEY]) if (handler) { const innerValue = unwrapValue(wrapped[VALUE_KEY], undefined) node.parent[node.key] = handler.deserialize(innerValue) } } // 应用 reviver if (reviver) { return applyReviver(result, reviver) } return result } /** * 使用循环方式应用 reviver */ function applyReviver(root: any, reviver: (this: any, key: string, value: any) => any): any { if (root === null || typeof root !== "object") { return reviver.call({ "": root }, "", root) } // 收集所有节点,按深度排序 type NodeInfo = { parent: any; key: string; depth: number } const nodes: NodeInfo[] = [] const collectStack: { obj: any; parent: any; key: string; depth: number }[] = [ { obj: root, parent: { "": root }, key: "", depth: 0 }, ] while (collectStack.length > 0) { const current = collectStack.pop()! const obj = current.obj if (obj !== null && typeof obj === "object") { nodes.push({ parent: current.parent, key: current.key, depth: current.depth }) const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { const key = keys[i] const value = obj[key] if (value !== null && typeof value === "object") { collectStack.push({ obj: value, parent: obj, key, depth: current.depth + 1 }) } else { nodes.push({ parent: obj, key, depth: current.depth + 1 }) } } } else { nodes.push({ parent: current.parent, key: current.key, depth: current.depth }) } } // 按深度从大到小排序,先处理叶子节点 nodes.sort((a, b) => b.depth - a.depth) // 应用 reviver const rootHolder = { "": root } for (let i = 0; i < nodes.length; i++) { const node = nodes[i] if (node.key === "" && node.parent[""] === root) { continue } const value = node.parent[node.key] const newValue = reviver.call(node.parent, node.key, value) if (newValue !== undefined) { node.parent[node.key] = newValue } } // 最后处理根节点 return reviver.call(rootHolder, "", root) }