@x-tech-laboratories/x-app 0.117.0 → 0.119.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.
Files changed (63) hide show
  1. package/README.md +21 -8
  2. package/dist/agent/claude_stream.d.ts +22 -0
  3. package/dist/agent/claude_stream.js +85 -0
  4. package/dist/agent/git.d.ts +37 -0
  5. package/dist/agent/git.js +121 -0
  6. package/dist/agent/github.d.ts +81 -0
  7. package/dist/agent/github.js +185 -0
  8. package/dist/agent/programs.d.ts +17 -0
  9. package/dist/agent/programs.js +62 -0
  10. package/dist/agent/worktree_files.d.ts +20 -0
  11. package/dist/agent/worktree_files.js +69 -0
  12. package/dist/agent_transcript.d.ts +83 -0
  13. package/dist/agent_transcript.js +267 -0
  14. package/dist/app/daemon.js +2 -2
  15. package/dist/app/define.d.ts +7 -2
  16. package/dist/app/define.js +13 -0
  17. package/dist/app/desktop.js +2 -2
  18. package/dist/app/protocol.d.ts +3 -1
  19. package/dist/app/protocol.js +1 -0
  20. package/dist/app/server.d.ts +1 -0
  21. package/dist/app/server.js +13 -2
  22. package/dist/app/web/android.js +8 -1
  23. package/dist/app/web/hosts.d.ts +1 -1
  24. package/dist/app/web/hosts.js +5 -4
  25. package/dist/connection_protocol.d.ts +1 -0
  26. package/dist/connection_protocol.js +11 -0
  27. package/dist/daemon_router.d.ts +2 -2
  28. package/dist/daemon_router.js +3 -2
  29. package/dist/diff_rows.d.ts +78 -0
  30. package/dist/diff_rows.js +158 -0
  31. package/dist/frontmatter.d.ts +10 -0
  32. package/dist/frontmatter.js +57 -0
  33. package/dist/frontmatter_folder.d.ts +24 -0
  34. package/dist/frontmatter_folder.js +54 -0
  35. package/dist/history.js +14 -1
  36. package/dist/server/config.d.ts +2 -0
  37. package/dist/server/config.js +15 -1
  38. package/dist/server/events.d.ts +2 -0
  39. package/dist/server/events.js +3 -1
  40. package/dist/server/github_webhook.d.ts +30 -0
  41. package/dist/server/github_webhook.js +146 -0
  42. package/dist/sync_engine.d.ts +5 -0
  43. package/dist/sync_engine.js +63 -9
  44. package/dist/sync_protocol.d.ts +4 -0
  45. package/dist/sync_protocol.js +11 -0
  46. package/dist/test_helpers.d.ts +7 -0
  47. package/dist/test_helpers.js +44 -0
  48. package/dist/web/react/accounts.js +2 -1
  49. package/dist/web/react/controls.d.ts +3 -2
  50. package/dist/web/react/controls.js +6 -4
  51. package/dist/web/react/copy_button.d.ts +11 -0
  52. package/dist/web/react/copy_button.js +44 -0
  53. package/dist/web/react/dialog.js +2 -2
  54. package/dist/web/react/diff.d.ts +26 -0
  55. package/dist/web/react/diff.js +79 -0
  56. package/dist/web/react/file_tree.d.ts +26 -0
  57. package/dist/web/react/file_tree.js +46 -0
  58. package/dist/web/react/local_mcp_settings.js +2 -1
  59. package/dist/web/react/transcript.d.ts +24 -0
  60. package/dist/web/react/transcript.js +100 -0
  61. package/dist/web/tree.d.ts +3 -1
  62. package/dist/web/tree.js +38 -10
  63. package/package.json +5 -3
@@ -0,0 +1,158 @@
1
+ // A change to text files laid out for reading. A unified diff, as git diff prints it, is read into files, hunks and
2
+ // numbered lines through parse-diff; each file is laid out side by side, old on the left and new on the right, or as
3
+ // one column; removed and added lines are paired so the words that changed within them are marked, through jsdiff; and
4
+ // long unchanged stretches fold down to a few lines on each side of a change. `edit_lines` diffs a before and after
5
+ // text, such as one edit an agent made. parse-diff (MIT) and jsdiff (BSD-3-Clause) were chosen because they read git's
6
+ // format and mark words exactly as the hand-written readers did, and work alike in a page, a phone and Node.
7
+ // ── Imports ──────────────────────────────────────────────────────────────────
8
+ import { diffLines, diffWordsWithSpace } from "diff";
9
+ import parse_diff from "parse-diff";
10
+ // Lines kept on each side of a change when the rest of an unchanged stretch folds.
11
+ export const context_lines = 3;
12
+ // ── Reading ──────────────────────────────────────────────────────────────────
13
+ const no_file = "/dev/null";
14
+ function status_of(file, path, old_path) {
15
+ if (file.new || file.from === no_file)
16
+ return "added";
17
+ if (file.deleted || file.to === no_file)
18
+ return "removed";
19
+ return path === old_path ? "changed" : "renamed";
20
+ }
21
+ function line_of(change) {
22
+ // parse-diff keeps the leading +, - or space, which the view draws apart.
23
+ const text = change.content.slice(1);
24
+ if (change.type === "add")
25
+ return { kind: "added", text, old_number: null, new_number: change.ln };
26
+ if (change.type === "del")
27
+ return { kind: "removed", text, old_number: change.ln, new_number: null };
28
+ return { kind: "context", text, old_number: change.ln1, new_number: change.ln2 };
29
+ }
30
+ // The files a unified diff changes, in the order it lists them.
31
+ export function parse_unified_diff(text) {
32
+ return parse_diff(text).map((file) => {
33
+ const path = file.to && file.to !== no_file ? file.to : (file.from ?? "");
34
+ const old_path = file.from && file.from !== no_file ? file.from : path;
35
+ const hunks = file.chunks.map((chunk) => ({ header: chunk.content, lines: chunk.changes.filter((change) => !change.content.startsWith("\\")).map(line_of) }));
36
+ return { path, old_path, status: status_of(file, path, old_path), additions: file.additions, deletions: file.deletions, hunks };
37
+ });
38
+ }
39
+ // The whole change's added and removed line counts.
40
+ export function diff_totals(files) {
41
+ return files.reduce((total, file) => ({ additions: total.additions + file.additions, deletions: total.deletions + file.deletions }), { additions: 0, deletions: 0 });
42
+ }
43
+ // A diff cut at the last whole file within a size, and whether it was cut.
44
+ export function diff_within_limit(text, limit) {
45
+ if (text.length <= limit)
46
+ return { text, truncated: false };
47
+ const cut = text.lastIndexOf("\ndiff --git ", limit);
48
+ return { text: cut > 0 ? text.slice(0, cut + 1) : "", truncated: true };
49
+ }
50
+ // ── Words ────────────────────────────────────────────────────────────────────
51
+ const whole = (text) => [{ text, changed: false }];
52
+ // The words of an old and a new line, each side marking what it lost or gained; a line changed through is left whole.
53
+ export function word_parts(old_text, new_text) {
54
+ const parts = diffWordsWithSpace(old_text, new_text);
55
+ const kept = parts.filter((part) => !part.added && !part.removed).reduce((total, part) => total + part.value.trim().length, 0);
56
+ if (kept === 0)
57
+ return { old: whole(old_text), new: whole(new_text) };
58
+ return {
59
+ old: parts.filter((part) => !part.added).map((part) => ({ text: part.value, changed: Boolean(part.removed) })),
60
+ new: parts.filter((part) => !part.removed).map((part) => ({ text: part.value, changed: Boolean(part.added) })),
61
+ };
62
+ }
63
+ // Each hunk's lines walked as unchanged lines and blocks of removed lines followed by added ones.
64
+ function walk(file, on_header, on_same, on_block) {
65
+ for (const hunk of file.hunks) {
66
+ if (file.hunks.length > 1)
67
+ on_header(hunk.header);
68
+ let block = { removed: [], added: [] };
69
+ const flush = () => {
70
+ if (block.removed.length || block.added.length)
71
+ on_block(block);
72
+ block = { removed: [], added: [] };
73
+ };
74
+ for (const line of hunk.lines) {
75
+ if (line.kind === "context") {
76
+ flush();
77
+ on_same(line);
78
+ }
79
+ else if (line.kind === "removed") {
80
+ if (block.added.length)
81
+ flush();
82
+ block.removed.push(line);
83
+ }
84
+ else
85
+ block.added.push(line);
86
+ }
87
+ flush();
88
+ }
89
+ }
90
+ // The paired lines' words, a removed line matched with the added line at the same place in its block.
91
+ function paired(block) {
92
+ const old = block.removed.map((line) => whole(line.text));
93
+ const fresh = block.added.map((line) => whole(line.text));
94
+ for (let index = 0; index < Math.min(old.length, fresh.length); index += 1) {
95
+ const words = word_parts(block.removed[index].text, block.added[index].text);
96
+ old[index] = words.old;
97
+ fresh[index] = words.new;
98
+ }
99
+ return { old, new: fresh };
100
+ }
101
+ // The file as rows of old and new side by side.
102
+ export function split_rows(file) {
103
+ const rows = [];
104
+ walk(file, (header) => rows.push({ kind: "hunk", header }), (line) => rows.push({ kind: "same", left: { number: line.old_number, parts: whole(line.text) }, right: { number: line.new_number, parts: whole(line.text) } }), (block) => {
105
+ const words = paired(block);
106
+ for (let index = 0; index < Math.max(block.removed.length, block.added.length); index += 1) {
107
+ const old_line = block.removed[index];
108
+ const new_line = block.added[index];
109
+ rows.push({ kind: "change", left: old_line ? { number: old_line.old_number, parts: words.old[index] } : null, right: new_line ? { number: new_line.new_number, parts: words.new[index] } : null });
110
+ }
111
+ });
112
+ return rows;
113
+ }
114
+ // The file as one column, each block's removed lines before its added ones.
115
+ export function unified_rows(file) {
116
+ const rows = [];
117
+ walk(file, (header) => rows.push({ kind: "hunk", header }), (line) => rows.push({ kind: "same", old_number: line.old_number, new_number: line.new_number, parts: whole(line.text) }), (block) => {
118
+ const words = paired(block);
119
+ block.removed.forEach((line, index) => rows.push({ kind: "removed", old_number: line.old_number, new_number: null, parts: words.old[index] }));
120
+ block.added.forEach((line, index) => rows.push({ kind: "added", old_number: null, new_number: line.new_number, parts: words.new[index] }));
121
+ });
122
+ return rows;
123
+ }
124
+ // ── Folding ──────────────────────────────────────────────────────────────────
125
+ // The rows with each long unchanged stretch cut to a few lines beside its changes, the rest a fold, unless opened.
126
+ export function fold_rows(rows, opened, context = context_lines) {
127
+ const shown = [];
128
+ let index = 0;
129
+ while (index < rows.length) {
130
+ if (rows[index].kind !== "same") {
131
+ shown.push(rows[index]);
132
+ index += 1;
133
+ continue;
134
+ }
135
+ let end = index;
136
+ while (end < rows.length && rows[end].kind === "same")
137
+ end += 1;
138
+ const keep_before = index === 0 ? 0 : context;
139
+ const keep_after = end === rows.length ? 0 : context;
140
+ const hidden = end - index - keep_before - keep_after;
141
+ if (hidden > 1 && !opened.has(index)) {
142
+ shown.push(...rows.slice(index, index + keep_before), { kind: "fold", start: index, count: hidden }, ...rows.slice(end - keep_after, end));
143
+ }
144
+ else {
145
+ shown.push(...rows.slice(index, end));
146
+ }
147
+ index = end;
148
+ }
149
+ return shown;
150
+ }
151
+ // ── Before and after ─────────────────────────────────────────────────────────
152
+ // A before and after text as lines marked added, removed or kept.
153
+ export function edit_lines(before, after) {
154
+ return diffLines(before, after).flatMap((part) => {
155
+ const kind = part.added ? "added" : part.removed ? "removed" : "context";
156
+ return part.value.replace(/\n$/, "").split("\n").map((text) => ({ kind, text }));
157
+ });
158
+ }
@@ -0,0 +1,10 @@
1
+ import { Document } from "yaml";
2
+ export interface FrontmatterFile {
3
+ frontmatter: Document;
4
+ body: string;
5
+ }
6
+ export declare function parse_frontmatter(text: string): FrontmatterFile;
7
+ export declare function frontmatter_values(file: FrontmatterFile): Record<string, unknown>;
8
+ export declare function frontmatter_text(value: unknown): string;
9
+ export declare function frontmatter_list(value: unknown): string[];
10
+ export declare function write_frontmatter(values: Record<string, unknown>, body: string, previous?: Document | null): string;
@@ -0,0 +1,57 @@
1
+ // Markdown files that start with YAML frontmatter between --- lines, such as agent definitions or notes: read into the
2
+ // frontmatter document and the body, the values read as text or lists whatever shape they were written in, and written
3
+ // back with the app's keys set or dropped while every other key and comment stays as it was. It runs alike in a page
4
+ // and in Node, on the `yaml` package, an optional peer the app installs.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { Document, parseDocument } from "yaml";
7
+ const frontmatter_pattern = /^---\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)([\s\S]*)$/;
8
+ // ── Reading ──────────────────────────────────────────────────────────────────
9
+ // The file's frontmatter and body; throws in plain words when it has no frontmatter or it is not a set of keys.
10
+ export function parse_frontmatter(text) {
11
+ const match = frontmatter_pattern.exec(text);
12
+ if (!match)
13
+ throw new Error("it does not start with a frontmatter block between --- lines");
14
+ const frontmatter = parseDocument(match[1] ?? "");
15
+ if (frontmatter.errors.length)
16
+ throw new Error(`its frontmatter is not valid YAML: ${frontmatter.errors[0].message}`);
17
+ const values = frontmatter.toJS();
18
+ if (frontmatter.contents !== null && (typeof values !== "object" || values === null || Array.isArray(values)))
19
+ throw new Error("its frontmatter is not a set of keys");
20
+ return { frontmatter, body: match[2].trim() };
21
+ }
22
+ // The frontmatter's keys and values, an empty frontmatter as none.
23
+ export function frontmatter_values(file) {
24
+ return (file.frontmatter.toJS() ?? {});
25
+ }
26
+ // A value as text: a string, or a number written out; anything else as "".
27
+ export function frontmatter_text(value) {
28
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
29
+ }
30
+ // A value as a list of text, from a YAML list or a comma-separated line such as "Read, Grep, Bash".
31
+ export function frontmatter_list(value) {
32
+ if (Array.isArray(value))
33
+ return value.map(frontmatter_text).filter(Boolean);
34
+ return frontmatter_text(value)
35
+ .split(",")
36
+ .map((part) => part.trim())
37
+ .filter(Boolean);
38
+ }
39
+ // ── Writing ──────────────────────────────────────────────────────────────────
40
+ // Whether a value is left out of the frontmatter: undefined, null, "" or an empty list.
41
+ function is_empty(value) {
42
+ return value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
43
+ }
44
+ // The file's text with the values given set, or dropped when empty, every other key and comment kept from `previous`.
45
+ export function write_frontmatter(values, body, previous = null) {
46
+ const document = previous ? previous.clone() : new Document({});
47
+ if (document.contents === null)
48
+ document.contents = document.createNode({});
49
+ for (const [key, value] of Object.entries(values)) {
50
+ if (is_empty(value))
51
+ document.delete(key);
52
+ else
53
+ document.set(key, value);
54
+ }
55
+ const trimmed = body.trim();
56
+ return `---\n${String(document).trimEnd()}\n---\n${trimmed ? `\n${trimmed}\n` : ""}`;
57
+ }
@@ -0,0 +1,24 @@
1
+ import { type FrontmatterFile } from "./frontmatter.ts";
2
+ export interface FrontmatterFolderOptions {
3
+ folder: string;
4
+ id_of_file: (name: string) => string | null;
5
+ file_of_id: (id: string) => string;
6
+ on_change?: () => void;
7
+ settle_in_milliseconds?: number;
8
+ }
9
+ export interface FrontmatterProblem {
10
+ file: string;
11
+ problem: string;
12
+ }
13
+ export interface FrontmatterFolder {
14
+ read_all: () => {
15
+ files: Map<string, FrontmatterFile>;
16
+ problems: FrontmatterProblem[];
17
+ };
18
+ write: (id: string, text: string) => void;
19
+ remove: (id: string) => void;
20
+ has: (id: string) => boolean;
21
+ path_of: (id: string) => string;
22
+ watch: () => () => void;
23
+ }
24
+ export declare function create_frontmatter_folder({ folder, id_of_file, file_of_id, on_change, settle_in_milliseconds }: FrontmatterFolderOptions): FrontmatterFolder;
@@ -0,0 +1,54 @@
1
+ // A folder of frontmatter files named by id, such as `stage-<id>.md`: every file read with a problem for each that does
2
+ // not parse, one written beside its old self and moved over it so a reader never sees half a file, removed, and the
3
+ // folder followed for changes made by other programs.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { parse_frontmatter } from "./frontmatter.js";
8
+ // ── Folder ───────────────────────────────────────────────────────────────────
9
+ export function create_frontmatter_folder({ folder, id_of_file, file_of_id, on_change = () => undefined, settle_in_milliseconds = 300 }) {
10
+ const path_of = (id) => join(folder, file_of_id(id));
11
+ return {
12
+ path_of,
13
+ has: (id) => existsSync(path_of(id)),
14
+ read_all: () => {
15
+ const files = new Map();
16
+ const problems = [];
17
+ const names = existsSync(folder) ? readdirSync(folder).sort() : [];
18
+ for (const name of names) {
19
+ const id = id_of_file(name);
20
+ if (id === null)
21
+ continue;
22
+ try {
23
+ files.set(id, parse_frontmatter(readFileSync(join(folder, name), "utf8")));
24
+ }
25
+ catch (error) {
26
+ problems.push({ file: name, problem: error.message });
27
+ }
28
+ }
29
+ return { files, problems };
30
+ },
31
+ write: (id, text) => {
32
+ mkdirSync(folder, { recursive: true });
33
+ const target = path_of(id);
34
+ const temporary = `${target}.saving`;
35
+ writeFileSync(temporary, text);
36
+ renameSync(temporary, target);
37
+ },
38
+ remove: (id) => rmSync(path_of(id), { force: true }),
39
+ watch: () => {
40
+ mkdirSync(folder, { recursive: true });
41
+ let timer;
42
+ const watcher = watch(folder, (_event, name) => {
43
+ if (name !== null && id_of_file(String(name)) === null)
44
+ return;
45
+ clearTimeout(timer);
46
+ timer = setTimeout(on_change, settle_in_milliseconds);
47
+ });
48
+ return () => {
49
+ clearTimeout(timer);
50
+ watcher.close();
51
+ };
52
+ },
53
+ };
54
+ }
package/dist/history.js CHANGED
@@ -29,7 +29,8 @@ export function create_history(options) {
29
29
  CREATE INDEX IF NOT EXISTS ${versions}_by_time ON ${versions} (changed_at);
30
30
  CREATE TABLE IF NOT EXISTS ${pending} (${item_column} TEXT PRIMARY KEY) WITHOUT ROWID`;
31
31
  // For the sync engine's tables, so every device has every version.
32
- const synced_table = { name: versions, key_columns: ["uid"], local_columns: ["id"] };
32
+ // A version is never changed once saved, so it syncs as one value rather than one per column.
33
+ const synced_table = { name: versions, key_columns: ["uid"], local_columns: ["id"], rows_never_change: true };
33
34
  // ── Triggers ─────────────────────────────────────────────────────────────
34
35
  const triggers = options.watches.flatMap((watch) => ["insert", "update", "delete"].map((event) => {
35
36
  const row = event === "delete" ? "OLD" : "NEW";
@@ -46,6 +47,7 @@ export function create_history(options) {
46
47
  // a first version as it stands now, with an id every device gives it alike.
47
48
  function install(database) {
48
49
  database.exec(schema);
50
+ drop_duplicate_indexes(database);
49
51
  drop_triggers(database);
50
52
  for (const trigger of triggers)
51
53
  database.exec(`CREATE TRIGGER ${trigger.name} ${trigger.sql}`);
@@ -58,6 +60,17 @@ export function create_history(options) {
58
60
  insert(database, `first_seen:${id}`, String(id), options.created_at?.(snapshot) ?? new Date().toISOString(), "first_seen", site, null, snapshot);
59
61
  }
60
62
  }
63
+ // An index an app made itself on the same columns as the item index only slows every write, so it goes.
64
+ function drop_duplicate_indexes(database) {
65
+ const columns_of = (index) => database.prepare(`PRAGMA index_info("${index}")`).all().map((column) => column.name).join(",");
66
+ const indexes = database.prepare(`PRAGMA index_list("${versions}")`).all();
67
+ const item_index = `${versions}_by_item`;
68
+ const item_columns = columns_of(item_index);
69
+ for (const index of indexes) {
70
+ if (index.name !== item_index && index.origin === "c" && index.unique === 0 && columns_of(index.name) === item_columns)
71
+ database.exec(`DROP INDEX "${index.name}"`);
72
+ }
73
+ }
61
74
  // Writes that arrive by sync touch items too, but their versions come from the device that made them; pass it as the
62
75
  // sync engine's after_apply.
63
76
  function forget_touched(database) {
@@ -45,5 +45,7 @@ export declare function command_words(line: string, words_for?: SecretCommandWor
45
45
  export declare function secret_command_reader(words_for?: SecretCommandWords): SecretReader;
46
46
  export declare const read_secret_command: SecretReader;
47
47
  export declare function secret_from_command(command_line: string, read?: SecretReader, words_for?: SecretCommandWords): Promise<string>;
48
+ export declare function create_secret_file(path: string, bytes?: number): void;
49
+ export declare function has_secret_file(path: string): boolean;
48
50
  export declare function read_server_config<Name extends string = never>(spec: ServerConfigSpec<Name>): ServerConfig<Name>;
49
51
  export {};
@@ -4,7 +4,9 @@
4
4
  // the program and never holds the secret.
5
5
  // ── Imports ──────────────────────────────────────────────────────────────────
6
6
  import { execFile } from "node:child_process";
7
- import { readFileSync } from "node:fs";
7
+ import { randomBytes } from "node:crypto";
8
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { dirname } from "node:path";
8
10
  import { parseArgs } from "node:util";
9
11
  export class HelpRequested extends Error {
10
12
  usage;
@@ -104,6 +106,18 @@ export async function secret_from_command(command_line, read = read_secret_comma
104
106
  const words = command_words(command_line.trim(), words_for);
105
107
  return words.length === 0 ? "" : read(words);
106
108
  }
109
+ // A new random secret, such as a webhook's, written to a file only its owner may read, replacing any before it; the
110
+ // caller gives it out only when asked, through read_secret_file.
111
+ export function create_secret_file(path, bytes = 32) {
112
+ mkdirSync(dirname(path), { recursive: true });
113
+ writeFileSync(path, `${randomBytes(bytes).toString("hex")}\n`, { mode: 0o600 });
114
+ // A file that was there before keeps its old mode through writeFileSync, so it is tightened too.
115
+ chmodSync(path, 0o600);
116
+ }
117
+ // Whether the file holds a secret, without reading it out.
118
+ export function has_secret_file(path) {
119
+ return existsSync(path) && readFileSync(path, "utf8").trim() !== "";
120
+ }
107
121
  // ── Reading ──────────────────────────────────────────────────────────────────
108
122
  function capitals(name) {
109
123
  return name.replaceAll("-", "_").toUpperCase();
@@ -5,6 +5,7 @@ export interface EventStreamOptions {
5
5
  hello_event?: string | null;
6
6
  changed_event?: string;
7
7
  client_id_header?: string;
8
+ change_data?: () => string;
8
9
  }
9
10
  export interface StreamClient {
10
11
  id: string;
@@ -22,6 +23,7 @@ export declare class EventStream {
22
23
  readonly hello_event: string | null;
23
24
  readonly changed_event: string;
24
25
  readonly client_id_header: string;
26
+ private readonly change_data;
25
27
  private readonly streams;
26
28
  constructor(options?: EventStreamOptions);
27
29
  get client_count(): number;
@@ -11,6 +11,7 @@ export class EventStream {
11
11
  hello_event;
12
12
  changed_event;
13
13
  client_id_header;
14
+ change_data;
14
15
  streams = new Map();
15
16
  constructor(options = {}) {
16
17
  this.heartbeat_ms = options.heartbeat_ms ?? 25_000;
@@ -18,6 +19,7 @@ export class EventStream {
18
19
  this.hello_event = options.hello_event === undefined ? "hello" : options.hello_event;
19
20
  this.changed_event = options.changed_event ?? "changed";
20
21
  this.client_id_header = options.client_id_header ?? default_client_id_header;
22
+ this.change_data = options.change_data ?? (() => "");
21
23
  }
22
24
  get client_count() {
23
25
  return this.streams.size;
@@ -39,7 +41,7 @@ export class EventStream {
39
41
  }
40
42
  // The page that made a change already shows it, so only the others are told.
41
43
  announce_change(except_client_id = "") {
42
- this.send("", { event: this.changed_event, except_client_id });
44
+ this.send(this.change_data(), { event: this.changed_event, except_client_id });
43
45
  }
44
46
  // Serves the stream on the path, and ends every stream when the app closes, since one never ends by itself.
45
47
  register(app, path = "/events") {
@@ -0,0 +1,30 @@
1
+ import type { IncomingHttpHeaders } from "node:http";
2
+ import { AddressLockout, type WebhookAnswer } from "./forge_webhook.ts";
3
+ export declare const github_target_events: readonly ["pull_request", "check_suite", "check_run", "status", "workflow_run", "issues", "issue_comment"];
4
+ export interface WebhookTargets {
5
+ repository: string;
6
+ pull_requests: number[];
7
+ branches: string[];
8
+ issues: number[];
9
+ }
10
+ export interface GitHubDelivery {
11
+ delivery_id: string;
12
+ event: string;
13
+ targets: WebhookTargets;
14
+ }
15
+ export interface GitHubReceiverOptions {
16
+ secret: () => string;
17
+ events?: readonly string[];
18
+ on_delivery: (delivery: GitHubDelivery) => void;
19
+ lockout?: AddressLockout;
20
+ remembered?: number;
21
+ unsigned_text?: string;
22
+ }
23
+ export declare function is_repository_name(name: string): boolean;
24
+ export declare function repository_of(payload: unknown): string | null;
25
+ export declare function delivery_id_of(header: unknown): string;
26
+ export declare function targets_of(event: string, payload: unknown): WebhookTargets | null;
27
+ export declare function read_targets(repository: string, stored: string): WebhookTargets;
28
+ export declare function read_public_url(typed: string): string;
29
+ export declare function payload_url_of(public_url: string, path: string): string;
30
+ export declare function create_github_receiver({ secret, events, on_delivery, lockout, remembered, unsigned_text }: GitHubReceiverOptions): (address: string, headers: IncomingHttpHeaders, body: Buffer) => WebhookAnswer;
@@ -0,0 +1,146 @@
1
+ // GitHub's webhooks on top of `forge_webhook`: a delivery counts only when signed with X-Hub-Signature-256 under the
2
+ // app's secret, never by a bearer token or another forge's header; an address that keeps failing waits; a delivery id
3
+ // seen before is answered without being passed on again; and of each delivery only the repository and the pull
4
+ // requests, branches and issues it names are kept, each checked for shape, for the app to look up for itself.
5
+ import { AddressLockout, is_signed, parse_payload } from "./forge_webhook.js";
6
+ // ── Shapes ───────────────────────────────────────────────────────────────────
7
+ // The events that name pull requests, branches or issues, for the app to tick on GitHub.
8
+ export const github_target_events = ["pull_request", "check_suite", "check_run", "status", "workflow_run", "issues", "issue_comment"];
9
+ const repository_pattern = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
10
+ const branch_pattern = /^[A-Za-z0-9._/-]{1,255}$/;
11
+ const delivery_pattern = /^[A-Za-z0-9-]{1,100}$/;
12
+ const most_targets = 50;
13
+ function fields_of(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
15
+ }
16
+ function number_of(value) {
17
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value < 2 ** 31 ? value : null;
18
+ }
19
+ function branch_of(value) {
20
+ return typeof value === "string" && branch_pattern.test(value) && !value.includes("..") && !value.startsWith("-") ? value : null;
21
+ }
22
+ // The pull request numbers in a list such as check_suite.pull_requests, left out where they are not plain numbers.
23
+ function numbers_in(list) {
24
+ return (Array.isArray(list) ? list : []).map((entry) => number_of(fields_of(entry).number)).filter((number) => number !== null);
25
+ }
26
+ // Whether a name is a repository as owner/name.
27
+ export function is_repository_name(name) {
28
+ return repository_pattern.test(name);
29
+ }
30
+ // The repository a payload names as owner/name, or null when it names none that looks like one.
31
+ export function repository_of(payload) {
32
+ const name = fields_of(fields_of(payload).repository).full_name;
33
+ return typeof name === "string" && repository_pattern.test(name) ? name : null;
34
+ }
35
+ // The delivery id as GitHub sends it, or "" when it is missing or not an id.
36
+ export function delivery_id_of(header) {
37
+ return typeof header === "string" && delivery_pattern.test(header) ? header : "";
38
+ }
39
+ // The repository and the pull requests, branches and issues a delivery names, or null; nothing else in it is kept.
40
+ export function targets_of(event, payload) {
41
+ const repository = repository_of(payload);
42
+ if (repository === null)
43
+ return null;
44
+ const values = fields_of(payload);
45
+ const pull_requests = [];
46
+ const branches = [];
47
+ const issues = [];
48
+ if (event === "ping") {
49
+ // Only says the hook works.
50
+ }
51
+ else if (event === "pull_request") {
52
+ const pull = fields_of(values.pull_request);
53
+ const head = fields_of(pull.head);
54
+ pull_requests.push(number_of(pull.number) ?? number_of(values.number));
55
+ // A fork's branch is not one of the repository's own, so only a branch of the same repository counts.
56
+ if (fields_of(head.repo).full_name === repository)
57
+ branches.push(branch_of(head.ref));
58
+ }
59
+ else if (event === "check_suite" || event === "workflow_run") {
60
+ const suite = fields_of(values[event]);
61
+ branches.push(branch_of(suite.head_branch));
62
+ pull_requests.push(...numbers_in(suite.pull_requests));
63
+ }
64
+ else if (event === "check_run") {
65
+ const run = fields_of(values.check_run);
66
+ branches.push(branch_of(fields_of(run.check_suite).head_branch));
67
+ pull_requests.push(...numbers_in(run.pull_requests));
68
+ }
69
+ else if (event === "status") {
70
+ branches.push(...(Array.isArray(values.branches) ? values.branches : []).map((branch) => branch_of(fields_of(branch).name)));
71
+ }
72
+ else if (event === "issues" || event === "issue_comment") {
73
+ issues.push(number_of(fields_of(values.issue).number));
74
+ }
75
+ else
76
+ return null;
77
+ const kept = (list) => [...new Set(list.filter((value) => value !== null))].slice(0, most_targets);
78
+ return { repository, pull_requests: kept(pull_requests), branches: kept(branches), issues: kept(issues) };
79
+ }
80
+ // A delivery's targets as stored, each list left empty where the stored text is damaged.
81
+ export function read_targets(repository, stored) {
82
+ let fields = {};
83
+ try {
84
+ fields = fields_of(JSON.parse(stored));
85
+ }
86
+ catch {
87
+ fields = {};
88
+ }
89
+ const numbers = (value) => (Array.isArray(value) ? value.map(number_of).filter((number) => number !== null) : []);
90
+ const names = Array.isArray(fields.branches) ? fields.branches.map(branch_of).filter((branch) => branch !== null) : [];
91
+ return { repository, pull_requests: numbers(fields.pull_requests), branches: names, issues: numbers(fields.issues) };
92
+ }
93
+ // ── Addresses ────────────────────────────────────────────────────────────────
94
+ // A public address as saved: http or https with a host and maybe a path, no query, fragment or user; anything else throws.
95
+ export function read_public_url(typed) {
96
+ const trimmed = typed.trim().replace(/\/+$/, "");
97
+ if (trimmed === "")
98
+ return "";
99
+ let url;
100
+ try {
101
+ url = new URL(trimmed);
102
+ }
103
+ catch {
104
+ throw new Error("Give the address GitHub reaches this server at, such as https://example.org.");
105
+ }
106
+ if ((url.protocol !== "https:" && url.protocol !== "http:") || url.search || url.hash || url.username || url.password)
107
+ throw new Error("The address is http or https with a host and a path, and nothing more.");
108
+ return trimmed;
109
+ }
110
+ // The payload URL for a public address and the route's path, or "" when no address is given.
111
+ export function payload_url_of(public_url, path) {
112
+ const trimmed = public_url.trim().replace(/\/+$/, "");
113
+ return trimmed ? `${trimmed}${path}` : "";
114
+ }
115
+ // ── Receiving ────────────────────────────────────────────────────────────────
116
+ // Answers deliveries as `register_webhook_route`'s receive.
117
+ export function create_github_receiver({ secret, events = github_target_events, on_delivery, lockout = new AddressLockout(), remembered = 1000, unsigned_text = "The delivery is not signed with this server's webhook secret." }) {
118
+ // Delivery ids already taken, oldest first, so a replayed delivery is answered without being passed on again.
119
+ const seen = new Set();
120
+ return (address, headers, body) => {
121
+ if (lockout.is_locked(address))
122
+ return { status: 429, body: { message: "Too many deliveries were not signed; try again later." } };
123
+ const key = secret();
124
+ const signature = headers["x-hub-signature-256"];
125
+ if (key === "" || typeof signature !== "string" || !is_signed({ "x-hub-signature-256": signature }, body, key)) {
126
+ lockout.fail(address);
127
+ return { status: 401, body: { message: unsigned_text } };
128
+ }
129
+ lockout.succeed(address);
130
+ const header = headers["x-github-event"];
131
+ const event = typeof header === "string" ? header.toLowerCase() : "";
132
+ const targets = event === "ping" || events.includes(event) ? targets_of(event, parse_payload(body, headers["content-type"])) : null;
133
+ if (targets === null)
134
+ return { status: 204, body: { message: "" } };
135
+ const delivery_id = delivery_id_of(headers["x-github-delivery"]);
136
+ if (delivery_id && seen.has(delivery_id))
137
+ return { status: 200, body: { message: "Already received." } };
138
+ if (delivery_id) {
139
+ seen.add(delivery_id);
140
+ if (seen.size > remembered)
141
+ seen.delete(seen.values().next().value);
142
+ }
143
+ on_delivery({ delivery_id, event, targets });
144
+ return { status: 202, body: { message: event === "ping" ? "Pong." : "Received." } };
145
+ };
146
+ }
@@ -6,6 +6,7 @@ export interface SyncedTable {
6
6
  local_columns?: string[];
7
7
  local_keys?: readonly string[];
8
8
  map_columns?: string[];
9
+ rows_never_change?: boolean;
9
10
  }
10
11
  export interface SyncEngineOptions {
11
12
  tables: SyncedTable[];
@@ -47,6 +48,10 @@ export declare function create_sync_engine(options: SyncEngineOptions): {
47
48
  has_unsent_changes: (database: SqlDatabase, device: string) => boolean;
48
49
  count_unsent_rows: (database: SqlDatabase, devices: readonly string[]) => number;
49
50
  collect_changes_since: (database: SqlDatabase, cursor: number, except_site: string) => CollectedChanges;
51
+ changed_tables_since: (database: SqlDatabase, cursor: number) => {
52
+ tables: string[];
53
+ up_to_seq: number;
54
+ };
50
55
  collect_snapshot: (database: SqlDatabase) => CollectedChanges;
51
56
  apply_changes: (database: SqlDatabase, changes: SyncChange[]) => number;
52
57
  claim_everything: (database: SqlDatabase, theirs: SyncChange[]) => void;