in lib/AssistantStream.ts [723:803]
static accumulateDelta(
acc: Record<string, any>,
delta: Record<string, any>,
): Record<string, any> {
for (const [key, deltaValue] of Object.entries(delta)) {
if (!acc.hasOwnProperty(key)) {
acc[key] = deltaValue;
continue;
}
let accValue = acc[key];
if (accValue === null || accValue === undefined) {
acc[key] = deltaValue;
continue;
}
// We don't accumulate these special properties
if (key === "index" || key === "type") {
acc[key] = deltaValue;
continue;
}
// Type-specific accumulation logic
if (typeof accValue === "string" && typeof deltaValue === "string") {
accValue += deltaValue;
} else if (
typeof accValue === "number" && typeof deltaValue === "number"
) {
accValue += deltaValue;
} else if (Core.isObj(accValue) && Core.isObj(deltaValue)) {
accValue = this.accumulateDelta(
accValue as Record<string, any>,
deltaValue as Record<string, any>,
);
} else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {
if (
accValue.every((x) => typeof x === "string" || typeof x === "number")
) {
accValue.push(...deltaValue); // Use spread syntax for efficient addition
continue;
}
for (const deltaEntry of deltaValue) {
if (!Core.isObj(deltaEntry)) {
throw new Error(
`Expected array delta entry to be an object but got: ${deltaEntry}`,
);
}
const index = deltaEntry["index"];
if (index == null) {
console.error(deltaEntry);
throw new Error(
"Expected array delta entry to have an `index` property",
);
}
if (typeof index !== "number") {
throw new Error(
`Expected array delta entry \`index\` property to be a number but got ${index}`,
);
}
const accEntry = accValue[index];
if (accEntry == null) {
accValue.push(deltaEntry);
} else {
accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
}
}
continue;
} else {
throw Error(
`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`,
);
}
acc[key] = accValue;
}
return acc;
}