@leitwerk-dev/gitlab 0.0.0-bootstrap.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ import {
2
+ type CoreServerSetupDeps,
3
+ createExternalSourcePollReporter,
4
+ type ExternalActionSource,
5
+ } from "@leitwerk-dev/process-sdk";
6
+ import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
7
+ import type { GitLabIntegration } from "./capability.js";
8
+ import { type GitLabFeedback, type GitLabObservation, observeMergeRequest } from "./client.js";
9
+ /** @internal */
10
+ export const GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
11
+ /** @public */
12
+ export interface GitLabSourceConfig {
13
+ /** @public */
14
+ profile: string;
15
+ /** @public */
16
+ projectId: number;
17
+ /** @public */
18
+ iid: number;
19
+ /** @public */
20
+ pollInterval?: string;
21
+ /** @public */
22
+ afterKey?: string;
23
+ /** Optional timer also wakes retry work when GitLab facts have not changed. @public */
24
+ wakeAt?: number;
25
+ /** @public */
26
+ feedback?: {
27
+ /** @public */
28
+ afterId: number;
29
+ /** @public */
30
+ since?: string;
31
+ /** @public */
32
+ quietPeriodMs: number;
33
+ };
34
+ }
35
+ /** A trailing quiet period survives restarts because it uses the newest unseen note's timestamp. @public */
36
+ export function pendingGitLabFeedback(
37
+ items: GitLabFeedback[],
38
+ afterId: number,
39
+ since?: string,
40
+ ): GitLabFeedback[] {
41
+ const start = since ? Date.parse(since) : 0;
42
+ return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
43
+ }
44
+ /** @public */
45
+ export function gitLabFeedbackReadyAt(
46
+ items: GitLabFeedback[],
47
+ quietPeriodMs: number,
48
+ ): number | null {
49
+ return items.length
50
+ ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs
51
+ : null;
52
+ }
53
+ /** @public */
54
+ export const observationKey = ({ mr, pipeline, targetHead }: GitLabObservation): string =>
55
+ JSON.stringify([
56
+ mr.state,
57
+ mr.sha,
58
+ [...mr.labels].sort(),
59
+ pipeline?.project_id,
60
+ pipeline?.id,
61
+ pipeline?.status,
62
+ mr.source_project_id,
63
+ mr.source_branch,
64
+ mr.target_project_id,
65
+ mr.target_branch,
66
+ targetHead,
67
+ mr.has_conflicts,
68
+ mr.merge_status,
69
+ mr.detailed_merge_status,
70
+ ]);
71
+ /** @public */
72
+ export const gitlabExternal = {
73
+ /** @public */
74
+ mergeRequest<P, S>(
75
+ resolve: (ctx: {
76
+ /** @public */
77
+ params: P;
78
+ /** @public */
79
+ state: S;
80
+ }) => GitLabSourceConfig,
81
+ ): ExternalActionSource<P, S, GitLabObservation> {
82
+ return {
83
+ kind: GITLAB_MR_KIND,
84
+ label: "GitLab merge request",
85
+ description: "Observe MR state, source/target heads, mergeability and revision-correlated CI",
86
+ config: {},
87
+ inputMode: "none",
88
+ resolve,
89
+ };
90
+ },
91
+ };
92
+ /** @internal */
93
+ export function createGitLabProvider(
94
+ deps: CoreServerSetupDeps,
95
+ integration: GitLabIntegration,
96
+ options: {
97
+ /** @internal */
98
+ now?: () => number;
99
+ } = {},
100
+ ) {
101
+ const schedule = new Map<string, { at: number; failures: number }>();
102
+ const now = options.now ?? Date.now;
103
+ return deps.polling.create({
104
+ id: "gitlab",
105
+ pollInterval: () => "5s",
106
+ isEnabled: () => true,
107
+ defaultIntervalMs: 5000,
108
+ async pollOnce() {
109
+ const result = emptyPollResult();
110
+ const report = createExternalSourcePollReporter(deps.externalSources, result);
111
+ await report.poll(GITLAB_MR_KIND, async (armed) => {
112
+ const c = armed.resolved as unknown as GitLabSourceConfig;
113
+ if (
114
+ !c ||
115
+ typeof c.profile !== "string" ||
116
+ !Number.isInteger(c.projectId) ||
117
+ !Number.isInteger(c.iid)
118
+ )
119
+ throw new Error("Invalid GitLab external source");
120
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
121
+ const previous = schedule.get(key);
122
+ if (previous && previous.at > now()) return;
123
+ try {
124
+ const observation = await observeMergeRequest(
125
+ integration.client(c.profile),
126
+ c.projectId,
127
+ c.iid,
128
+ );
129
+ const observedKey = observationKey(observation);
130
+ const feedback =
131
+ c.feedback && observation.mr.state === "opened"
132
+ ? pendingGitLabFeedback(
133
+ await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
134
+ c.feedback.afterId,
135
+ c.feedback.since,
136
+ )
137
+ : [];
138
+ const feedbackReadyAt = gitLabFeedbackReadyAt(
139
+ feedback,
140
+ c.feedback?.quietPeriodMs ?? 120_000,
141
+ );
142
+ const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
143
+ await report.observe(armed, {
144
+ observation: {
145
+ summary: `${observation.mr.state} · ${observation.pipeline?.status ?? "no current pipeline"}`,
146
+ observedAt: new Date(now()).toISOString(),
147
+ subject: observation.mr.web_url,
148
+ revision: observation.mr.sha,
149
+ },
150
+ });
151
+ if (
152
+ observedKey !== c.afterKey ||
153
+ feedbackReady ||
154
+ (c.wakeAt !== undefined && c.wakeAt <= now())
155
+ )
156
+ await report.fire(
157
+ armed,
158
+ { ...observation },
159
+ `${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`,
160
+ );
161
+ schedule.set(key, {
162
+ at: now() + parseDurationMs(c.pollInterval ?? "30s", 30000),
163
+ failures: 0,
164
+ });
165
+ } catch (error) {
166
+ const failures = (previous?.failures ?? 0) + 1;
167
+ schedule.set(key, {
168
+ at: now() + Math.min(300000, 30000 * 2 ** Math.min(failures - 1, 4)),
169
+ failures,
170
+ });
171
+ await report.observe(armed, {
172
+ refreshError: error instanceof Error ? error.message : "GitLab observation unavailable",
173
+ });
174
+ throw error;
175
+ }
176
+ });
177
+ return result;
178
+ },
179
+ });
180
+ }
package/src/index.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type { LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
+ import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
3
+ import { GitLabClient, parseGitLabProfiles } from "./client.js";
4
+ import { setupGitLabIntegration } from "./setup.js";
5
+
6
+ /** @internal */
7
+ const manifest = {
8
+ /** @internal */
9
+ id: "gitlab",
10
+ /** @internal */
11
+ version: "0.1.9",
12
+ } as const;
13
+ /** @public */
14
+ const extension: LeitwerkExtensionModule = {
15
+ manifest,
16
+ setupServer(api, config) {
17
+ const profiles = parseGitLabProfiles(config);
18
+ const clients = new Map([...profiles].map(([id, profile]) => [id, new GitLabClient(profile)]));
19
+ setupGitLabIntegration(api, {
20
+ profiles: () => [...profiles.keys()],
21
+ client: (profile) => {
22
+ const client = clients.get(profile);
23
+ if (!client) throw new Error(`Unknown GitLab profile '${profile}'`);
24
+ return client;
25
+ },
26
+ });
27
+ const deps = api.get(coreHostCapabilities.serverSetup);
28
+ if (!deps || Array.isArray(deps)) return;
29
+ deps.repositoryCredentials.register({
30
+ kind: "git_https",
31
+ resolve(ref) {
32
+ const profile = ref.startsWith("gitlab:") ? profiles.get(ref.slice(7)) : undefined;
33
+ return profile
34
+ ? { origin: profile.baseUrl, username: "oauth2", password: profile.token }
35
+ : null;
36
+ },
37
+ });
38
+ },
39
+ };
40
+ export default extension;
41
+ export type { GitLabIntegration } from "./capability.js";
42
+ export {
43
+ gitlabIntegration,
44
+ gitlabRepositoryCredentials,
45
+ } from "./capability.js";
46
+ export type {
47
+ GitLabDiff,
48
+ GitLabFeedback,
49
+ GitLabIdentity,
50
+ GitLabJob,
51
+ GitLabMergeRequest,
52
+ GitLabObservation,
53
+ GitLabProject,
54
+ } from "./client.js";
55
+ export { observeMergeRequest } from "./client.js";
56
+ export {
57
+ gitLabFeedbackReadyAt,
58
+ gitlabExternal,
59
+ observationKey,
60
+ pendingGitLabFeedback,
61
+ } from "./external.js";
62
+ export type { GitLabSelection } from "./selection.js";
63
+ export {
64
+ parseGitLabSelection,
65
+ selectGitLabProjects,
66
+ } from "./selection.js";
67
+ export { ensureGitLabSeenReaction, resolveGitLabBinding } from "./tools.js";
@@ -0,0 +1,16 @@
1
+ import type { GitLabMergeRequest } from "./client.js";
2
+
3
+ export const mr: GitLabMergeRequest = {
4
+ iid: 1,
5
+ project_id: 7,
6
+ source_project_id: 7,
7
+ target_project_id: 7,
8
+ title: "Upgrade",
9
+ description: null,
10
+ state: "opened",
11
+ labels: ["renovate"],
12
+ sha: "head",
13
+ source_branch: "renovate/dependency",
14
+ target_branch: "main",
15
+ web_url: "https://forge.test/a/-/merge_requests/1",
16
+ };
@@ -0,0 +1,77 @@
1
+ import type { GitLabClientLike, GitLabProject } from "./client.js";
2
+ /** @public */
3
+ export interface GitLabSelection {
4
+ /** @public */
5
+ projects: {
6
+ /** @public */
7
+ include: readonly string[];
8
+ /** @internal */
9
+ exclude: readonly string[];
10
+ };
11
+ /** @public */
12
+ groups: {
13
+ /** @public */
14
+ include: readonly string[];
15
+ /** @internal */
16
+ exclude: readonly string[];
17
+ };
18
+ /** @internal */
19
+ allAccessible: boolean;
20
+ }
21
+ /** @public */
22
+ export function parseGitLabSelection(raw: Record<string, unknown>): GitLabSelection {
23
+ const list = (value: unknown): string[] => {
24
+ if (value === undefined) return [];
25
+ if (
26
+ !Array.isArray(value) ||
27
+ value.some(
28
+ (v) =>
29
+ typeof v !== "string" ||
30
+ !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) ||
31
+ v.split("/").some((p: string) => p === "." || p === ".."),
32
+ )
33
+ )
34
+ throw new Error("GitLab selectors require exact namespace paths");
35
+ return [...new Set(value as string[])];
36
+ };
37
+ const pair = (value: unknown) => {
38
+ if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value)))
39
+ throw new Error("GitLab selectors must be objects");
40
+ const item = value as Record<string, unknown> | undefined;
41
+ return { include: list(item?.include), exclude: list(item?.exclude) };
42
+ };
43
+ if (raw.all_accessible !== undefined && typeof raw.all_accessible !== "boolean")
44
+ throw new Error("all_accessible must be a boolean");
45
+ const parsed = {
46
+ projects: pair(raw.projects),
47
+ groups: pair(raw.groups),
48
+ allAccessible: raw.all_accessible === true,
49
+ };
50
+ if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
51
+ throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
52
+ return parsed;
53
+ }
54
+ /** @internal */
55
+ export function projectExcluded(selection: GitLabSelection, name: string): boolean {
56
+ return (
57
+ selection.projects.exclude.includes(name) ||
58
+ selection.groups.exclude.some((group) => name.startsWith(`${group}/`))
59
+ );
60
+ }
61
+ /** Include union, subgroup expansion, exclusion precedence, stable-ID deduplication. @public */
62
+ export async function selectGitLabProjects(
63
+ client: GitLabClientLike,
64
+ selection: GitLabSelection,
65
+ ): Promise<GitLabProject[]> {
66
+ const candidates: GitLabProject[] = selection.allAccessible ? await client.listProjects() : [];
67
+ for (const name of selection.projects.include) candidates.push(await client.getProject(name));
68
+ for (const group of selection.groups.include)
69
+ candidates.push(...(await client.listGroupProjects(group)));
70
+ return [
71
+ ...new Map(
72
+ candidates
73
+ .filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace))
74
+ .map((p) => [p.id, p]),
75
+ ).values(),
76
+ ];
77
+ }
package/src/setup.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { coreHostCapabilities, type ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
2
+ import { type GitLabIntegration, gitlabIntegration } from "./capability.js";
3
+ import { createGitLabProvider } from "./external.js";
4
+ import { registerGitLabTools } from "./tools.js";
5
+
6
+ /** Register shared tools and polling with an explicit integration. @public */
7
+ export function setupGitLabIntegration(
8
+ api: ServerExtensionAPI,
9
+ integration: GitLabIntegration,
10
+ options: {
11
+ /** @public */
12
+ now?: () => number;
13
+ } = {},
14
+ ) {
15
+ api.provide(gitlabIntegration, integration);
16
+ const deps = api.get(coreHostCapabilities.serverSetup);
17
+ if (!deps || Array.isArray(deps)) return;
18
+ registerGitLabTools(api, integration);
19
+ return createGitLabProvider(deps, integration, options);
20
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,254 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import type {
5
+ GitLabClientLike,
6
+ GitLabDiff,
7
+ GitLabFeedback,
8
+ GitLabMergeRequest,
9
+ GitLabNote,
10
+ GitLabNoteReaction,
11
+ GitLabPipeline,
12
+ GitLabProject,
13
+ } from "./client.js";
14
+
15
+ export { setupGitLabIntegration } from "./setup.js";
16
+
17
+ /** @public */
18
+ interface LocalState {
19
+ /** @internal */
20
+ projects: GitLabProject[];
21
+ /** @internal */
22
+ mrs: GitLabMergeRequest[];
23
+ /** @internal */
24
+ pipelines: GitLabPipeline[];
25
+ /** @public */
26
+ notes: Record<string, GitLabNote[]>;
27
+ /** @internal */
28
+ diffs: Record<string, GitLabDiff[]>;
29
+ /** @public */
30
+ feedback?: Record<string, GitLabFeedback[]>;
31
+ /** @public */
32
+ discussionNotes?: Record<string, GitLabNote[]>;
33
+ /** @public */
34
+ reactions?: Record<string, GitLabNoteReaction[]>;
35
+ }
36
+ /** Persistent GitLab test boundary. Repository URLs use local Git's file transport. @public */
37
+ export class LocalGitLabAdapter {
38
+ /** @public */
39
+ state: LocalState;
40
+ /** @public */
41
+ loseNextCommentResponse = false;
42
+ /** @public */
43
+ loseNextReplyResponse = false;
44
+ /** @public */
45
+ loseNextReactionResponse = false;
46
+ /** @public */
47
+ constructor(
48
+ /** @internal */
49
+ readonly root: string,
50
+ /** @internal */
51
+ readonly baseUrl = "https://gitlab.test",
52
+ ) {
53
+ mkdirSync(root, { recursive: true });
54
+ const file = path.join(root, "gitlab.json");
55
+ this.state = existsSync(file)
56
+ ? JSON.parse(readFileSync(file, "utf8"))
57
+ : { projects: [], mrs: [], pipelines: [], notes: {}, diffs: {} };
58
+ }
59
+ /** @public */
60
+ save() {
61
+ writeFileSync(path.join(this.root, "gitlab.json"), JSON.stringify(this.state), { mode: 0o600 });
62
+ }
63
+ private append<T>(items: T[], item: T, kind: "Comment" | "Reply" | "Reaction"): T {
64
+ items.push(item);
65
+ this.save();
66
+ const flag = `loseNext${kind}Response` as const;
67
+ if (this[flag]) {
68
+ this[flag] = false;
69
+ const action = {
70
+ Comment: "comment write",
71
+ Reply: "discussion reply",
72
+ Reaction: "reaction write",
73
+ };
74
+ throw new Error(`Response lost after ${action[kind]}`);
75
+ }
76
+ return item;
77
+ }
78
+ private project(id: number | string) {
79
+ const p = this.state.projects.find((p) => p.id === id || p.path_with_namespace === id);
80
+ if (!p) throw new Error("Unknown test project");
81
+ return p;
82
+ }
83
+ private git(id: number, args: string[]) {
84
+ return execFileSync(
85
+ "git",
86
+ ["-c", "core.hooksPath=/dev/null", "--git-dir", this.project(id).http_url_to_repo, ...args],
87
+ { encoding: "utf8" },
88
+ ).trim();
89
+ }
90
+ /** @public */
91
+ addProject(name: string, bare: string): GitLabProject {
92
+ const project: GitLabProject = {
93
+ id: this.state.projects.length + 1,
94
+ path_with_namespace: name,
95
+ http_url_to_repo: bare,
96
+ web_url: `${this.baseUrl}/${name}`,
97
+ default_branch: "main",
98
+ };
99
+ this.state.projects.push(project);
100
+ this.save();
101
+ return project;
102
+ }
103
+ /** @public */
104
+ openMr(project: GitLabProject, branch: string): GitLabMergeRequest {
105
+ const mr: GitLabMergeRequest = {
106
+ iid: this.state.mrs.length + 1,
107
+ project_id: project.id,
108
+ target_project_id: project.id,
109
+ source_project_id: project.id,
110
+ title: "Update dependency",
111
+ description: "Renovate upgrade",
112
+ state: "opened",
113
+ labels: ["renovate"],
114
+ sha: this.git(project.id, ["rev-parse", branch]),
115
+ source_branch: branch,
116
+ target_branch: "main",
117
+ web_url: `${project.web_url}/-/merge_requests/${this.state.mrs.length + 1}`,
118
+ };
119
+ this.state.mrs.push(mr);
120
+ this.save();
121
+ return mr;
122
+ }
123
+ /** @public */
124
+ pipeline(mr: GitLabMergeRequest, status: string): GitLabPipeline {
125
+ const value: GitLabPipeline = {
126
+ id: this.state.pipelines.length + 1,
127
+ project_id: mr.source_project_id,
128
+ sha: this.git(mr.source_project_id, ["rev-parse", mr.source_branch]),
129
+ ref: mr.source_branch,
130
+ status,
131
+ source: "merge_request_event",
132
+ web_url: `${this.project(mr.source_project_id).web_url}/-/pipelines/${this.state.pipelines.length + 1}`,
133
+ };
134
+ this.state.pipelines.push(value);
135
+ this.save();
136
+ return value;
137
+ }
138
+ /** @public */
139
+ client(): GitLabClientLike {
140
+ const mr = (id: number, iid: number) => {
141
+ const m = this.state.mrs.find((m) => m.project_id === id && m.iid === iid);
142
+ if (!m) throw new Error("Unknown test MR");
143
+ return m;
144
+ };
145
+ const commit = (id: number, ref: string) => ({
146
+ id: this.git(id, ["rev-parse", ref]),
147
+ parent_ids: this.git(id, ["show", "-s", "--format=%P", ref]).split(" ").filter(Boolean),
148
+ message: this.git(id, ["show", "-s", "--format=%B", ref]),
149
+ });
150
+ return {
151
+ baseUrl: this.baseUrl,
152
+ getProject: async (id) => structuredClone(this.project(id)),
153
+ listProjects: async () => structuredClone(this.state.projects),
154
+ getGroup: async (id) => ({ id: 1, full_path: String(id) }),
155
+ listGroupProjects: async (group) =>
156
+ structuredClone(
157
+ this.state.projects.filter((p) => p.path_with_namespace.startsWith(`${group}/`)),
158
+ ),
159
+ getMergeRequest: async (id, iid) => ({
160
+ ...structuredClone(mr(id, iid)),
161
+ sha: commit(mr(id, iid).source_project_id, mr(id, iid).source_branch).id,
162
+ }),
163
+ listMergeRequests: async (id, label) =>
164
+ structuredClone(
165
+ this.state.mrs.filter(
166
+ (m) => m.project_id === id && m.state === "opened" && m.labels.includes(label),
167
+ ),
168
+ ),
169
+ getBranch: async (id, branch) => ({
170
+ name: branch,
171
+ can_push: true,
172
+ protected: false,
173
+ commit: commit(id, branch),
174
+ }),
175
+ getCommit: async (id, ref) => commit(id, ref),
176
+ getChanges: async (id, iid) => structuredClone(this.state.diffs[`${id}:${iid}`] ?? []),
177
+ listMergeRequestPipelines: async (id, iid) =>
178
+ structuredClone(
179
+ this.state.pipelines.filter(
180
+ (p) =>
181
+ p.project_id === mr(id, iid).source_project_id && p.ref === mr(id, iid).source_branch,
182
+ ),
183
+ ),
184
+ listBranchPipelines: async (id, branch, sha) =>
185
+ structuredClone(
186
+ this.state.pipelines.filter(
187
+ (p) => p.project_id === id && p.ref === branch && p.sha === sha && p.source === "push",
188
+ ),
189
+ ),
190
+ getPipeline: async (id, pipeline) => {
191
+ const p = this.state.pipelines.find((p) => p.project_id === id && p.id === pipeline);
192
+ if (!p) throw new Error("Unknown test pipeline");
193
+ return structuredClone(p);
194
+ },
195
+ listFailedJobs: async (id, pipeline) => [
196
+ {
197
+ id: pipeline * 100,
198
+ name: "test",
199
+ status: "failed",
200
+ web_url: `${this.project(id).web_url}/-/jobs/${pipeline * 100}`,
201
+ failure_reason: "script_failure",
202
+ },
203
+ ],
204
+ getJobTrace: async () => ({
205
+ text: "Expected new dependency API; test failed",
206
+ truncated: false,
207
+ }),
208
+ resolveGitIdentity: async () => ({
209
+ name: "Leitwerk Bot",
210
+ email: "bot@gitlab.test",
211
+ username: "bot",
212
+ }),
213
+ listNotes: async (id, iid) => structuredClone(this.state.notes[`${id}:${iid}`] ?? []),
214
+ listMergeRequestFeedback: async (id, iid) =>
215
+ structuredClone(this.state.feedback?.[`${id}:${iid}`] ?? []),
216
+ getDiscussion: async (id, iid, discussionId) => ({
217
+ id: discussionId,
218
+ notes: (this.state.discussionNotes?.[`${id}:${iid}:${discussionId}`] ?? []).map((note) => ({
219
+ ...structuredClone(note),
220
+ system: false,
221
+ created_at: new Date().toISOString(),
222
+ author: { username: "bot" },
223
+ })),
224
+ }),
225
+ replyToDiscussion: async (id, iid, discussionId, body) => {
226
+ const key = `${id}:${iid}:${discussionId}`;
227
+ this.state.discussionNotes ??= {};
228
+ this.state.discussionNotes[key] ??= [];
229
+ const notes = this.state.discussionNotes[key];
230
+ return this.append(notes, { id: notes.length + 1, body }, "Reply");
231
+ },
232
+ listNoteReactions: async (id, iid, noteId) =>
233
+ structuredClone(this.state.reactions?.[`${id}:${iid}:${noteId}`] ?? []),
234
+ addNoteReaction: async (id, iid, noteId, name) => {
235
+ const key = `${id}:${iid}:${noteId}`;
236
+ this.state.reactions ??= {};
237
+ this.state.reactions[key] ??= [];
238
+ const reactions = this.state.reactions[key];
239
+ if (
240
+ reactions.some((reaction) => reaction.name === name && reaction.user.username === "bot")
241
+ )
242
+ throw new Error("Reaction already exists");
243
+ const reaction = { id: reactions.length + 1, name, user: { username: "bot" } };
244
+ return this.append(reactions, reaction, "Reaction");
245
+ },
246
+ addNote: async (id, iid, body) => {
247
+ const key = `${id}:${iid}`;
248
+ this.state.notes[key] ??= [];
249
+ const notes = this.state.notes[key];
250
+ return this.append(notes, { id: notes.length + 1, body }, "Comment");
251
+ },
252
+ };
253
+ }
254
+ }