{"record":{"id":"16932dc28b6c2c2c","repo":"linshenkx/prompt-optimizer","slug":"failed-to-serialize-object-for-ipc-details","errorCode":null,"errorMessage":"Failed to serialize object for IPC: ${details}","messagePattern":"Failed to serialize object for IPC: (.+?)","errorType":"exception","errorClass":"IpcSerializationError","httpStatus":null,"severity":"error","filePath":"packages/core/src/utils/ipc-serialization.ts","lineNumber":45,"sourceCode":" * @returns 纯净的JavaScript对象\n */\nexport function safeSerializeForIPC<T>(obj: T): T {\n  if (obj === null || obj === undefined) {\n    return obj;\n  }\n\n  // 对于基本类型，直接返回\n  if (typeof obj !== 'object') {\n    return obj;\n  }\n\n  // 使用JSON序列化确保100%的IPC兼容性\n  try {\n    return JSON.parse(JSON.stringify(obj));\n  } catch (error) {\n    console.error('[IPC Serialization] Failed to serialize object:', error);\n    const details = error instanceof Error ? error.message : String(error)\n    throw new IpcSerializationError(`Failed to serialize object for IPC: ${details}`);\n  }\n}\n\n/**\n * 检查对象是否可以安全地通过IPC传递\n * 主要用于开发时调试\n * \n * @param obj 要检查的对象\n * @param label 对象标签，用于日志输出\n */\nexport function debugIPCSerializability(obj: any, label: string = 'object'): void {\n  try {\n    JSON.stringify(obj);\n    console.log(`[IPC Debug] ${label} is serializable`);\n  } catch (error) {\n    console.error(`[IPC Debug] ${label} is NOT serializable:`, error);\n    console.error(`[IPC Debug] Object:`, obj);\n  }","sourceCodeStart":27,"sourceCodeEnd":63,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/core/src/utils/ipc-serialization.ts#L27-L63","documentation":"This error is thrown by safeSerializeForIPC when an object cannot be round-tripped through JSON (JSON.parse(JSON.stringify(obj))) before being sent over Electron IPC. Any value that JSON cannot represent — BigInt, functions, symbols, circular references, or objects with toJSON that throws — will trigger it. The wrapper exists to guarantee 100% IPC compatibility, since Electron's structured clone algorithm rejects some values that JSON accepts and vice versa.","triggerScenarios":"Calling save, update, importAll, validateData, or importAllData with a data payload containing BigInt values (e.g. Date.now() * 1000n, IDs parsed as BigInt), circular object graphs, or class instances carrying methods/symbols that break JSON.stringify. Also triggered by objects with a custom toJSON() that itself throws.","commonSituations":"Storing IDs as BigInt after switching a DB driver to bigint mode; embedding a document with parent/child back-references creating cycles; passing Mongoose documents or class instances with getters that throw; using Map/Set which silently become {} and later fail downstream but never throw here unless truly non-serializable.","solutions":["Convert BigInt fields to string before persisting: data.id = data.id.toString()","Break circular references by removing back-references or using a replacer: JSON.stringify(obj, (k, v) => typeof v === 'bigint' ? v.toString() : v)","Call JSON.parse(JSON.stringify(obj)) yourself in a try/catch before save/update to pinpoint which field fails","If the object is a class instance, map it to a plain DTO object before passing it to save/update"],"exampleFix":"// before\nawait repo.save({ id: BigInt(user.id), name: user.name });\n\n// after\nawait repo.save({ id: String(user.id), name: user.name });","handlingStrategy":"validation","validationCode":"const isJsonSafe = (v: unknown): boolean => {\n  try { JSON.parse(JSON.stringify(v)); return true; } catch { return false; }\n};\nif (!isJsonSafe(data)) {\n  data = JSON.parse(JSON.stringify(data, (k, val) =>\n    typeof val === 'bigint' ? val.toString() : val));\n}","typeGuard":"const isPlainSerializable = (o: unknown): o is Record<string, unknown> =>\n  o !== null && typeof o === 'object' && Object.getPrototypeOf(o) === Object.prototype;","tryCatchPattern":"try {\n  await repo.save(data);\n} catch (e) {\n  if (e instanceof IpcSerializationError) {\n    data = JSON.parse(JSON.stringify(data, (k, v) => typeof v === 'bigint' ? v.toString() : v));\n    await repo.save(data);\n  } else throw e;\n}","preventionTips":["Never store BigInt in persisted fields; normalize IDs to strings at the boundary","Avoid circular references; map entities to flat DTOs before save/update","Pre-flight test payloads with JSON.parse(JSON.stringify(x)) in development"],"tags":["ipc","serialization","json","bigint","electron"],"backgroundTag":"json-serialization-failed","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}