Open History to see the last commit
1import {
2 type OrchestrationV2AppThread,
3 OrchestrationV2AppThreadJson,
4 ThreadPullRequestStack,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8
9/** Keep badge, search and settlement fields; PR views read canonical snapshots. */
10export const compactThreadPullRequests = (
11 thread: OrchestrationV2AppThread,
12): OrchestrationV2AppThread => {
13 const links = thread.pullRequests;
14 if (links === undefined) return thread;
15 return {
16 ...thread,
17 pullRequests: links.map((link) => ({
18 ...link,
19 snapshot:
20 link.snapshot === null
21 ? null
22 : {
23 state: link.snapshot.state,
24 title: link.snapshot.title,
25 headBranch: link.snapshot.headBranch,
26 baseBranch: link.snapshot.baseBranch,
27 isDraft: link.snapshot.isDraft,
28 updatedAt: link.snapshot.updatedAt,
29 syncedAt: link.snapshot.syncedAt,
30 ...(link.snapshot.mergedAt == null ? {} : { mergedAt: link.snapshot.mergedAt }),
31 ...(link.snapshot.closedAt == null ? {} : { closedAt: link.snapshot.closedAt }),
32 },
33 })),
34 };
35};
36
37// Store repeated stacks once without changing the public thread schema.
38const ReadPayload = Schema.fromJsonString(
39 Schema.Struct({
40 thread: OrchestrationV2AppThreadJson,
41 stacks: Schema.Array(ThreadPullRequestStack),
42 stackIndices: Schema.Array(Schema.NullOr(Schema.Number)),
43 }),
44);
45
46const encode = Schema.encodeEffect(ReadPayload);
47const decode = Schema.decodeUnknownEffect(ReadPayload);
48
49export const encodeThreadReadPayload = (thread: OrchestrationV2AppThread) => {
50 const stacks: Array<ThreadPullRequestStack> = [];
51 const indices = new Map<string, number>();
52 const stackIndices: Array<number | null> = [];
53 const pullRequests = thread.pullRequests?.map((link) => {
54 if (link.stack === null) {
55 stackIndices.push(null);
56 return link;
57 }
58 // Compare the whole stack, not its id: two links can have different sync vintages.
59 const key = JSON.stringify(link.stack);
60 let index = indices.get(key);
61 if (index === undefined) {
62 index = stacks.length;
63 stacks.push(link.stack);
64 indices.set(key, index);
65 }
66 stackIndices.push(index);
67 return { ...link, stack: null };
68 });
69 return encode({
70 thread: { ...thread, ...(pullRequests === undefined ? {} : { pullRequests }) },
71 stacks,
72 stackIndices,
73 });
74};
75
76export const decodeThreadReadPayload = (payload: string) =>
77 decode(payload).pipe(
78 Effect.map(({ thread, stacks, stackIndices }) => ({
79 ...thread,
80 ...(thread.pullRequests === undefined
81 ? {}
82 : {
83 pullRequests: thread.pullRequests.map((link, index) => ({
84 ...link,
85 stack: stackIndices[index] == null ? null : (stacks[stackIndices[index]!] ?? null),
86 })),
87 }),
88 })),
89 );