alibai 0.0.0-stage → 0.2.0

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.
package/dist/git.js ADDED
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gitRoot = gitRoot;
4
+ exports.gitChanges = gitChanges;
5
+ exports.gitMetadata = gitMetadata;
6
+ const node_child_process_1 = require("node:child_process");
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const readLimit = 32 * 1024 * 1024;
11
+ function gitCommand(cwd, ...args) {
12
+ const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", LC_ALL: "C" };
13
+ // Git gives this environment variable precedence over --unified.
14
+ delete env.GIT_DIFF_OPTS;
15
+ return (0, node_child_process_1.spawnSync)("git", args, {
16
+ cwd,
17
+ env,
18
+ stdio: ["ignore", "pipe", "pipe"],
19
+ // shortcut: cap each Git read at 32 MiB, stream patches if larger snapshots are needed.
20
+ maxBuffer: readLimit,
21
+ });
22
+ }
23
+ function gitBytes(result) {
24
+ return !result.error && result.status === 0 ? result.stdout : null;
25
+ }
26
+ function gitText(result) {
27
+ return gitBytes(result)?.toString("utf8").replace(/\r?\n$/, "") ?? null;
28
+ }
29
+ function gitRoot() {
30
+ const result = gitCommand(process.cwd(), "rev-parse", "--show-toplevel");
31
+ if (result.error?.code === "ENOENT") {
32
+ throw new Error("Git must be installed to use alibai.");
33
+ }
34
+ if (result.error)
35
+ throw result.error;
36
+ const root = gitText(result);
37
+ if (!root)
38
+ throw new Error("Run alibai from a Git working tree.");
39
+ return root;
40
+ }
41
+ function untrackedDigest(file, rootPrefix) {
42
+ const entry = (0, node_fs_1.lstatSync)(file);
43
+ if (entry.isSymbolicLink()) {
44
+ return { kind: "l", digest: (0, node_crypto_1.createHash)("sha256").update((0, node_fs_1.readlinkSync)(file, { encoding: "buffer" })).digest() };
45
+ }
46
+ // Git lists paths below the root. Check that parent links haven't redirected a file outside it.
47
+ if (!entry.isFile())
48
+ return null;
49
+ const resolved = node_fs_1.realpathSync.native(file, { encoding: "buffer" });
50
+ if (!resolved.subarray(0, rootPrefix.length).equals(rootPrefix))
51
+ return null;
52
+ const fd = (0, node_fs_1.openSync)(resolved, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
53
+ try {
54
+ const stat = (0, node_fs_1.fstatSync)(fd);
55
+ if (!stat.isFile() || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size > readLimit)
56
+ return null;
57
+ const hash = (0, node_crypto_1.createHash)("sha256");
58
+ const buffer = Buffer.allocUnsafe(64 * 1024);
59
+ let total = 0;
60
+ for (;;) {
61
+ const size = (0, node_fs_1.readSync)(fd, buffer, 0, Math.min(buffer.length, readLimit - total + 1), null);
62
+ if (size === 0)
63
+ return { kind: "f", digest: hash.digest() };
64
+ total += size;
65
+ if (total > readLimit)
66
+ return null;
67
+ hash.update(buffer.subarray(0, size));
68
+ }
69
+ }
70
+ finally {
71
+ (0, node_fs_1.closeSync)(fd);
72
+ }
73
+ }
74
+ function snapshotDigest(root, headSha, untracked) {
75
+ const diff = (...revisions) => gitBytes(gitCommand(root, "--no-optional-locks", "-c", "core.quotePath=true", "-c", "core.bigFileThreshold=512m", "-c", "diff.suppressBlankEmpty=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.noprefix=false", "diff", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", "--no-relative", "--submodule=short", "--src-prefix=a/", "--dst-prefix=b/", "-O/dev/null", "--diff-algorithm=myers", "--unified=3", "--inter-hunk-context=0", "--indent-heuristic", ...revisions, "--", ":(top,exclude,literal).alibai"));
76
+ const staged = diff("--cached", headSha);
77
+ const unstaged = diff();
78
+ if (!staged || !unstaged || !(staged.length || unstaged.length || untracked.length))
79
+ return null;
80
+ // Lengths distinguish the two patches and each path. File digests are always 32 bytes.
81
+ const hash = (0, node_crypto_1.createHash)("sha256").update(`${staged.length}\n${unstaged.length}\n`).update(staged).update(unstaged);
82
+ try {
83
+ if (untracked.length) {
84
+ const realRoot = (0, node_fs_1.realpathSync)(root);
85
+ const rootPrefix = Buffer.from(realRoot.endsWith(node_path_1.sep) ? realRoot : realRoot + node_path_1.sep);
86
+ for (const path of untracked.sort(Buffer.compare)) {
87
+ const file = untrackedDigest(Buffer.concat([rootPrefix, path]), rootPrefix);
88
+ if (!file)
89
+ return null;
90
+ hash.update(`${file.kind}${path.length}\n`).update(path).update(file.digest);
91
+ }
92
+ }
93
+ return hash.digest("hex");
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ function gitChanges(root, headSha = gitText(gitCommand(root, "rev-parse", "--verify", "HEAD^{commit}"))) {
100
+ const status = gitBytes(gitCommand(root, "--no-optional-locks", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"));
101
+ if (!status)
102
+ return { changes: null };
103
+ const dirty = status.length > 0;
104
+ const paths = new Set();
105
+ const untracked = [];
106
+ for (let offset = 0; offset < status.length;) {
107
+ const end = status.indexOf(0, offset);
108
+ if (end < offset + 4)
109
+ return { changes: null };
110
+ const path = status.subarray(offset + 3, end);
111
+ const name = path.toString("utf8");
112
+ if (name !== ".alibai" && !name.startsWith(".alibai/")) {
113
+ paths.add(name);
114
+ if (status.toString("ascii", offset, offset + 2) === "??")
115
+ untracked.push(path);
116
+ }
117
+ offset = end + 1;
118
+ }
119
+ if (paths.size === 0)
120
+ return { dirty };
121
+ const diffSha256 = headSha ? snapshotDigest(root, headSha, untracked) : null;
122
+ return { dirty, changes: { paths: [...paths].sort(), diffSha256 } };
123
+ }
124
+ function gitMetadata(root, base) {
125
+ const git = (...args) => gitText(gitCommand(root, ...args));
126
+ const branch = git("symbolic-ref", "--quiet", "HEAD")?.replace(/^refs\/heads\//, "") ?? null;
127
+ const headSha = git("rev-parse", "--verify", "HEAD^{commit}");
128
+ const { dirty, changes: startChanges } = gitChanges(root, headSha);
129
+ const metadata = { branch, headSha, dirty, startChanges };
130
+ if (base !== undefined) {
131
+ const baseSha = git("rev-parse", "--verify", "--end-of-options", `${base}^{commit}`);
132
+ if (!baseSha)
133
+ throw new Error(`--base does not resolve to a local commit: ${base}`);
134
+ return { ...metadata, baseSha };
135
+ }
136
+ if (headSha) {
137
+ for (const ref of [
138
+ "refs/remotes/origin/HEAD", "refs/remotes/origin/main", "refs/heads/main",
139
+ "refs/remotes/origin/master", "refs/heads/master",
140
+ ]) {
141
+ const baseSha = git("merge-base", headSha, ref);
142
+ if (baseSha && baseSha !== headSha)
143
+ return { ...metadata, baseSha };
144
+ }
145
+ return { ...metadata, baseSha: git("rev-parse", "--verify", `${headSha}^1`) };
146
+ }
147
+ return { ...metadata, baseSha: null };
148
+ }
package/dist/report.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runId = void 0;
7
+ exports.assertRun = assertRun;
8
+ exports.parseJson = parseJson;
9
+ const _2020_1 = __importDefault(require("ajv/dist/2020"));
10
+ const run_schema_json_1 = __importDefault(require("./run.schema.json"));
11
+ exports.runId = new RegExp(run_schema_json_1.default.$defs.id.pattern);
12
+ let validate;
13
+ function assertRun(value, label) {
14
+ validate ??= new _2020_1.default({ strictRequired: false })
15
+ .addFormat("date-time", (value) => {
16
+ const time = Date.parse(value);
17
+ return Number.isFinite(time) && new Date(time).toISOString() === value;
18
+ })
19
+ .compile(run_schema_json_1.default);
20
+ if (!validate(value)) {
21
+ const error = validate.errors?.[0];
22
+ throw new Error(`${label}: invalid run format at ${error?.instancePath || "/"} (${error?.message}).`);
23
+ }
24
+ const { steps, checks } = value;
25
+ const ids = new Set();
26
+ for (const { id } of [...steps, ...checks]) {
27
+ if (ids.has(id))
28
+ throw new Error(`${label}: invalid run format (duplicate exhibit id ${id}).`);
29
+ ids.add(id);
30
+ }
31
+ }
32
+ function parseJson(value, label) {
33
+ try {
34
+ return JSON.parse(value, (_key, parsed) => {
35
+ if (typeof parsed === "number" && !Number.isFinite(parsed)) {
36
+ throw new Error("number is outside the supported range");
37
+ }
38
+ return parsed;
39
+ });
40
+ }
41
+ catch (error) {
42
+ throw new Error(`${label}: invalid JSON (${error.message}).`);
43
+ }
44
+ }
@@ -0,0 +1,100 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Alibi for AI run (version 1)",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": ["formatVersion", "id", "title", "createdAt", "git", "platform", "steps", "checks"],
7
+ "dependentRequired": {
8
+ "verdict": ["summary"],
9
+ "summary": ["verdict"],
10
+ "endedAt": ["verdict"]
11
+ },
12
+ "properties": {
13
+ "formatVersion": { "const": 1 },
14
+ "id": { "$ref": "#/$defs/id" },
15
+ "title": { "$ref": "#/$defs/text" },
16
+ "createdAt": { "$ref": "#/$defs/timestamp" },
17
+ "endedAt": { "$ref": "#/$defs/timestamp" },
18
+ "git": {
19
+ "type": "object",
20
+ "additionalProperties": false,
21
+ "required": ["branch", "baseSha", "headSha"],
22
+ "properties": {
23
+ "branch": { "type": ["string", "null"], "minLength": 1 },
24
+ "baseSha": { "$ref": "#/$defs/sha" },
25
+ "headSha": { "$ref": "#/$defs/sha" },
26
+ "dirty": { "type": "boolean" },
27
+ "startChanges": { "$ref": "#/$defs/gitChanges" },
28
+ "endChanges": { "$ref": "#/$defs/gitChanges" }
29
+ }
30
+ },
31
+ "agent": { "$ref": "#/$defs/text" },
32
+ "platform": { "enum": ["flutter", "ios", "android", "web"] },
33
+ "steps": {
34
+ "type": "array",
35
+ "items": { "$ref": "#/$defs/step" }
36
+ },
37
+ "checks": {
38
+ "type": "array",
39
+ "items": { "$ref": "#/$defs/check" }
40
+ },
41
+ "verdict": { "$ref": "#/$defs/result" },
42
+ "summary": {
43
+ "type": "string",
44
+ "pattern": "^[^\\r\\n\\u2028\\u2029]*\\S[^\\r\\n\\u2028\\u2029]*$"
45
+ }
46
+ },
47
+ "$defs": {
48
+ "id": { "type": "string", "pattern": "^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$" },
49
+ "text": { "type": "string", "pattern": "\\S" },
50
+ "timestamp": { "type": "string", "format": "date-time", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$" },
51
+ "sha": { "type": ["string", "null"], "pattern": "^(?:[a-f0-9]{40}|[a-f0-9]{64})$" },
52
+ "gitChanges": {
53
+ "type": ["object", "null"],
54
+ "additionalProperties": false,
55
+ "required": ["paths", "diffSha256"],
56
+ "properties": {
57
+ "paths": {
58
+ "type": "array", "minItems": 1, "uniqueItems": true,
59
+ "items": { "type": "string", "pattern": "^[^\\u0000]+$" }
60
+ },
61
+ "diffSha256": { "type": ["string", "null"], "pattern": "^[a-f0-9]{64}$" }
62
+ }
63
+ },
64
+ "result": { "enum": ["pass", "fail", "info"] },
65
+ "screenshot": { "type": "string", "pattern": "^screenshots/[a-zA-Z0-9_-]+(?:\\.[a-zA-Z0-9]+)?$" },
66
+ "step": {
67
+ "type": "object",
68
+ "additionalProperties": false,
69
+ "required": ["id", "order", "action", "note", "result"],
70
+ "anyOf": [{ "required": ["before"] }, { "required": ["after"] }],
71
+ "properties": {
72
+ "id": { "$ref": "#/$defs/id" },
73
+ "order": { "type": "integer", "minimum": 1 },
74
+ "action": { "$ref": "#/$defs/text" },
75
+ "createdAt": { "$ref": "#/$defs/timestamp" },
76
+ "before": { "$ref": "#/$defs/screenshot" },
77
+ "after": { "$ref": "#/$defs/screenshot" },
78
+ "note": { "type": "string" },
79
+ "result": { "$ref": "#/$defs/result" }
80
+ }
81
+ },
82
+ "check": {
83
+ "type": "object",
84
+ "additionalProperties": false,
85
+ "required": ["id", "target", "input", "before", "result"],
86
+ "anyOf": [{ "required": ["after"] }, { "required": ["error"] }],
87
+ "properties": {
88
+ "id": { "$ref": "#/$defs/id" },
89
+ "target": { "$ref": "#/$defs/text" },
90
+ "createdAt": { "$ref": "#/$defs/timestamp" },
91
+ "input": true,
92
+ "before": true,
93
+ "after": true,
94
+ "expected": true,
95
+ "error": { "$ref": "#/$defs/text" },
96
+ "result": { "$ref": "#/$defs/result" }
97
+ }
98
+ }
99
+ }
100
+ }
package/dist/store.js ADDED
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RunStore = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const promises_1 = require("node:fs/promises");
7
+ const node_path_1 = require("node:path");
8
+ const promises_2 = require("node:timers/promises");
9
+ const report_1 = require("./report");
10
+ function hasCode(error, code) {
11
+ return error.code === code;
12
+ }
13
+ async function requireDirectory(path) {
14
+ if (!(await (0, promises_1.lstat)(path)).isDirectory())
15
+ throw new Error(`Expected a directory at ${path}.`);
16
+ }
17
+ async function createDirectory(path) {
18
+ try {
19
+ await (0, promises_1.mkdir)(path, { mode: 0o700 });
20
+ }
21
+ catch (error) {
22
+ if (!hasCode(error, "EEXIST"))
23
+ throw error;
24
+ await requireDirectory(path);
25
+ }
26
+ }
27
+ async function save(directory, run) {
28
+ (0, report_1.assertRun)(run, (0, node_path_1.join)(directory, "run.json"));
29
+ await saveJson(directory, "run.json", run);
30
+ }
31
+ async function saveJson(directory, name, value) {
32
+ const temporary = (0, node_path_1.join)(directory, `.${name}-${(0, node_crypto_1.randomUUID)()}.tmp`);
33
+ try {
34
+ await (0, promises_1.writeFile)(temporary, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 0o600 });
35
+ await (0, promises_1.rename)(temporary, (0, node_path_1.join)(directory, name));
36
+ }
37
+ catch (error) {
38
+ await (0, promises_1.rm)(temporary, { force: true }).catch(() => { });
39
+ throw error;
40
+ }
41
+ }
42
+ function isComment(value) {
43
+ if (!value || typeof value !== "object")
44
+ return false;
45
+ const { id, text, createdAt, updatedAt } = value;
46
+ return typeof id === "string" && id.length === 36 && report_1.runId.test(id) &&
47
+ typeof text === "string" && typeof createdAt === "string" && Number.isFinite(Date.parse(createdAt)) &&
48
+ (updatedAt === undefined || (typeof updatedAt === "string" && Number.isFinite(Date.parse(updatedAt))));
49
+ }
50
+ async function readComments(directory) {
51
+ const path = (0, node_path_1.join)(directory, "comments.json");
52
+ try {
53
+ if (!(await (0, promises_1.lstat)(path)).isFile())
54
+ throw new Error(`Expected a regular file at ${path}.`);
55
+ const file = await (0, promises_1.open)(path, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
56
+ try {
57
+ if (!(await file.stat()).isFile())
58
+ throw new Error(`Expected a regular file at ${path}.`);
59
+ const comments = (0, report_1.parseJson)(await file.readFile("utf8"), path);
60
+ if (!comments || typeof comments !== "object" || Array.isArray(comments) ||
61
+ !Object.entries(comments).every(([id, thread]) => id.length === 36 && report_1.runId.test(id) &&
62
+ Array.isArray(thread) && thread.every(isComment))) {
63
+ throw new Error(`Invalid comments in ${path}.`);
64
+ }
65
+ return comments;
66
+ }
67
+ finally {
68
+ await file.close();
69
+ }
70
+ }
71
+ catch (error) {
72
+ if (hasCode(error, "ENOENT"))
73
+ return {};
74
+ throw error;
75
+ }
76
+ }
77
+ class RunStore {
78
+ home;
79
+ runs;
80
+ constructor(root) {
81
+ this.home = (0, node_path_1.join)(root, ".alibai");
82
+ this.runs = (0, node_path_1.join)(this.home, "runs");
83
+ }
84
+ async start(run) {
85
+ await createDirectory(this.home);
86
+ await (0, promises_1.writeFile)((0, node_path_1.join)(this.home, ".gitignore"), "*\n", { flag: "wx" }).catch((error) => {
87
+ if (!hasCode(error, "EEXIST"))
88
+ throw error;
89
+ });
90
+ await createDirectory(this.runs);
91
+ const staging = await (0, promises_1.mkdtemp)((0, node_path_1.join)(this.runs, ".start-"));
92
+ const directory = (0, node_path_1.join)(this.runs, run.id);
93
+ try {
94
+ await (0, promises_1.mkdir)((0, node_path_1.join)(staging, "screenshots"));
95
+ await save(staging, run);
96
+ await (0, promises_1.rename)(staging, directory);
97
+ }
98
+ catch (error) {
99
+ await (0, promises_1.rm)(staging, { recursive: true, force: true }).catch(() => { });
100
+ throw error;
101
+ }
102
+ return { path: (0, node_path_1.join)(directory, "run.json"), run };
103
+ }
104
+ async read(directory, id) {
105
+ const path = (0, node_path_1.join)(directory, "run.json");
106
+ if (!(await (0, promises_1.lstat)(path)).isFile())
107
+ throw new Error(`Expected a regular file at ${path}.`);
108
+ const run = (0, report_1.parseJson)(await (0, promises_1.readFile)(path, "utf8"), path);
109
+ (0, report_1.assertRun)(run, path);
110
+ if (run.id !== id)
111
+ throw new Error(`Run id in ${path} does not match its directory.`);
112
+ return { path, run };
113
+ }
114
+ async list() {
115
+ try {
116
+ await requireDirectory(this.home);
117
+ await requireDirectory(this.runs);
118
+ }
119
+ catch (error) {
120
+ if (hasCode(error, "ENOENT"))
121
+ return { runs: [], invalidRuns: [] };
122
+ throw error;
123
+ }
124
+ const entries = await (0, promises_1.readdir)(this.runs, { withFileTypes: true });
125
+ const discovered = await Promise.all(entries
126
+ .filter((entry) => entry.isDirectory() && report_1.runId.test(entry.name))
127
+ .map(async ({ name: id }) => {
128
+ const directory = (0, node_path_1.join)(this.runs, id);
129
+ try {
130
+ return await this.read(directory, id);
131
+ }
132
+ catch (error) {
133
+ return { id, path: (0, node_path_1.join)(directory, "run.json"), error: error.message };
134
+ }
135
+ }));
136
+ const runs = discovered.filter((entry) => "run" in entry);
137
+ const invalidRuns = discovered.filter((entry) => "error" in entry);
138
+ runs.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt) || b.run.id.localeCompare(a.run.id));
139
+ invalidRuns.sort((a, b) => a.id.localeCompare(b.id));
140
+ return { runs, invalidRuns };
141
+ }
142
+ async screenshot(id, name) {
143
+ if (!report_1.runId.test(id))
144
+ return;
145
+ const directory = (0, node_path_1.join)(this.runs, id);
146
+ const screenshots = (0, node_path_1.join)(directory, "screenshots");
147
+ try {
148
+ for (const path of [this.home, this.runs, directory, screenshots])
149
+ await requireDirectory(path);
150
+ const { run } = await this.read(directory, id);
151
+ const reference = `screenshots/${name}`;
152
+ if (!run.steps.some(({ before, after }) => before === reference || after === reference))
153
+ return;
154
+ const path = (0, node_path_1.join)(screenshots, name);
155
+ if (!(await (0, promises_1.lstat)(path)).isFile())
156
+ return;
157
+ const file = await (0, promises_1.open)(path, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
158
+ try {
159
+ if ((await file.stat()).isFile())
160
+ return await file.readFile();
161
+ }
162
+ finally {
163
+ await file.close();
164
+ }
165
+ }
166
+ catch {
167
+ // Unreadable reports or images are unavailable to the viewer.
168
+ return;
169
+ }
170
+ }
171
+ async existingDirectory(id) {
172
+ if (!report_1.runId.test(id))
173
+ return;
174
+ const directory = (0, node_path_1.join)(this.runs, id);
175
+ try {
176
+ await requireDirectory(this.home);
177
+ await requireDirectory(this.runs);
178
+ await requireDirectory(directory);
179
+ }
180
+ catch (error) {
181
+ if (hasCode(error, "ENOENT"))
182
+ return;
183
+ throw error;
184
+ }
185
+ return directory;
186
+ }
187
+ async comments(id) {
188
+ const directory = await this.existingDirectory(id);
189
+ if (!directory)
190
+ return;
191
+ await this.read(directory, id);
192
+ return readComments(directory);
193
+ }
194
+ async changeComment(id, exhibitId, change) {
195
+ if (!report_1.runId.test(exhibitId) || !report_1.runId.test(change.id))
196
+ return;
197
+ const directory = await this.existingDirectory(id);
198
+ if (!directory)
199
+ return;
200
+ return this.withRunLock(directory, id, async () => {
201
+ const { run } = await this.read(directory, id);
202
+ if (![...run.steps, ...run.checks].some((item) => item.id === exhibitId))
203
+ return;
204
+ const comments = await readComments(directory);
205
+ const thread = comments[exhibitId] ?? [];
206
+ const index = thread.findIndex((comment) => comment.id === change.id);
207
+ if (change.action === "delete") {
208
+ if (index === -1)
209
+ return thread;
210
+ thread.splice(index, 1);
211
+ }
212
+ else if (change.action === "add") {
213
+ if (index >= 0)
214
+ return thread[index].text === change.text ? thread : null;
215
+ thread.push({ id: change.id, text: change.text, createdAt: new Date().toISOString() });
216
+ }
217
+ else {
218
+ if (index === -1)
219
+ return null;
220
+ if (thread[index].text === change.text)
221
+ return thread;
222
+ thread[index] = { ...thread[index], text: change.text, updatedAt: new Date().toISOString() };
223
+ }
224
+ if (thread.length)
225
+ comments[exhibitId] = thread;
226
+ else
227
+ delete comments[exhibitId];
228
+ await saveJson(directory, "comments.json", comments);
229
+ return thread;
230
+ });
231
+ }
232
+ async withRunLock(directory, id, action) {
233
+ const lock = (0, node_path_1.join)(directory, ".lock");
234
+ const deadline = Date.now() + 5000;
235
+ // shortcut: recover interrupted writers manually as lock age cannot prove that a writer has exited.
236
+ for (;;) {
237
+ try {
238
+ await (0, promises_1.mkdir)(lock);
239
+ break;
240
+ }
241
+ catch (error) {
242
+ if (!hasCode(error, "EEXIST"))
243
+ throw error;
244
+ if (Date.now() >= deadline) {
245
+ const quotedLock = "'" + lock.replaceAll("'", "'\\''") + "'";
246
+ throw new Error(`Run ${id} is locked. Wait for active or pending writers to finish. ` +
247
+ `If all writers for this run have exited, remove the empty lock with rmdir -- ${quotedLock} and retry.`);
248
+ }
249
+ await (0, promises_2.setTimeout)(25);
250
+ }
251
+ }
252
+ try {
253
+ return await action();
254
+ }
255
+ finally {
256
+ await (0, promises_1.rmdir)(lock).catch(() => { });
257
+ }
258
+ }
259
+ async mutate(id, edit) {
260
+ if (!report_1.runId.test(id))
261
+ throw new Error("--run must be a run UUID.");
262
+ const directory = await this.existingDirectory(id);
263
+ if (!directory)
264
+ throw new Error(`Run ${id} was not found.`);
265
+ return this.withRunLock(directory, id, async () => {
266
+ const copied = [];
267
+ try {
268
+ const stored = await this.read(directory, id);
269
+ if (stored.run.verdict !== undefined)
270
+ throw new Error(`Run ${id} is already completed.`);
271
+ await edit(stored.run, async (source, name) => {
272
+ const sourceStat = await (0, promises_1.stat)(source).catch((error) => {
273
+ if (!hasCode(error, "ENOENT"))
274
+ throw error;
275
+ throw new Error(`Screenshot was not found: ${source}`);
276
+ });
277
+ if (!sourceStat.isFile())
278
+ throw new Error(`Screenshot must be a regular file: ${source}`);
279
+ await requireDirectory((0, node_path_1.join)(directory, "screenshots"));
280
+ const relative = `screenshots/${name}${(0, node_path_1.extname)(source).toLowerCase()}`;
281
+ const destination = (0, node_path_1.join)(directory, relative);
282
+ await (0, promises_1.copyFile)(source, destination, node_fs_1.constants.COPYFILE_EXCL);
283
+ copied.push(destination);
284
+ return relative;
285
+ });
286
+ await save(directory, stored.run);
287
+ return stored;
288
+ }
289
+ catch (error) {
290
+ await Promise.allSettled(copied.map((path) => (0, promises_1.rm)(path, { force: true })));
291
+ throw error;
292
+ }
293
+ });
294
+ }
295
+ }
296
+ exports.RunStore = RunStore;