Open History to see the last commit
1import type { ServerConfig, ServerConfigStreamEvent } from "@t3tools/contracts";
2
3type ConfigDelta = Extract<ServerConfigStreamEvent, { readonly type: "configDelta" }>;
4
5function changedFields<T extends object>(previous: T, next: T) {
6 const changes: Partial<T> = {};
7 const removed: string[] = [];
8 for (const key of Object.keys(next) as Array<keyof T & string>) {
9 if (next[key] === undefined) continue;
10 if (JSON.stringify(previous[key]) !== JSON.stringify(next[key])) changes[key] = next[key];
11 }
12 // JSON drops a field set to undefined, as the config hash does, so it is a removal.
13 for (const key of Object.keys(previous) as Array<keyof T & string>) {
14 if (previous[key] !== undefined && next[key] === undefined) removed.push(key);
15 }
16 return { changes, removed };
17}
18
19/** Provider catalogs stay on the client when only health or quota changes. */
20export function diffServerConfig(
21 previous: ServerConfig,
22 next: ServerConfig,
23 configVersion: string,
24): ConfigDelta {
25 const { providers: _previous, ...previousFields } = previous;
26 const { providers: _next, ...nextFields } = next;
27 const fields = changedFields(previousFields, nextFields);
28 const previousProviders = new Map(
29 previous.providers.map((provider) => [provider.instanceId, provider]),
30 );
31 const providerChanges = next.providers.flatMap((provider) => {
32 const current = previousProviders.get(provider.instanceId);
33 const patch =
34 current === undefined ? { changes: provider, removed: [] } : changedFields(current, provider);
35 return Object.keys(patch.changes).length === 0 && patch.removed.length === 0
36 ? []
37 : [{ instanceId: provider.instanceId, ...patch }];
38 });
39 const providerOrder = next.providers.map((provider) => provider.instanceId);
40 return {
41 version: 1,
42 type: "configDelta",
43 configVersion,
44 ...fields,
45 providerChanges,
46 ...(JSON.stringify(previous.providers.map((provider) => provider.instanceId)) ===
47 JSON.stringify(providerOrder)
48 ? {}
49 : { providerOrder }),
50 };
51}