From abd9ed4a08272625dd693c7082e4658d5ce79c3e Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Thu, 19 Nov 2026 15:01:44 -0500 Subject: [PATCH 1/5] feat: doc path rules, doc visibility, byte-exact text, frontmatter patching Shared round-trip fixtures in packages/core/fixtures/docs for every editor (decision 011). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHyaEvdoSPjkLy7T1aaz Signed-off-by: Erik Goins --- packages/core/fixtures/docs/README.md | 22 +++ packages/core/fixtures/docs/round-trip.json | 54 ++++++++ packages/core/package.json | 3 +- packages/core/src/docs/fixtures.ts | 40 ++++++ packages/core/src/docs/frontmatter.test.ts | 51 +++++++ packages/core/src/docs/frontmatter.ts | 146 ++++++++++++++++++++ packages/core/src/docs/index.ts | 4 + packages/core/src/docs/paths.test.ts | 76 ++++++++++ packages/core/src/docs/paths.ts | 97 +++++++++++++ packages/core/src/docs/round-trip.test.ts | 41 ++++++ packages/core/src/docs/text.ts | 78 +++++++++++ packages/core/src/index.ts | 1 + packages/core/src/visibility.ts | 25 ++++ 13 files changed, 637 insertions(+), 1 deletion(-) create mode 100644 packages/core/fixtures/docs/README.md create mode 100644 packages/core/fixtures/docs/round-trip.json create mode 100644 packages/core/src/docs/fixtures.ts create mode 100644 packages/core/src/docs/frontmatter.test.ts create mode 100644 packages/core/src/docs/frontmatter.ts create mode 100644 packages/core/src/docs/index.ts create mode 100644 packages/core/src/docs/paths.test.ts create mode 100644 packages/core/src/docs/paths.ts create mode 100644 packages/core/src/docs/round-trip.test.ts create mode 100644 packages/core/src/docs/text.ts diff --git a/packages/core/fixtures/docs/README.md b/packages/core/fixtures/docs/README.md new file mode 100644 index 0000000..da7a13c --- /dev/null +++ b/packages/core/fixtures/docs/README.md @@ -0,0 +1,22 @@ +# Doc round-trip fixtures + +Every Gitwork doc editor (web: CodeMirror 6; Mac: TextKit 2) must pass these cases (decision 011). +The rule they guard: a file's bytes survive load → edit → save, and lines nobody edited stay +byte-identical. + +`round-trip.json` holds `cases`. Each case has: + +- `input`: the file as a JSON string (exact, including `\r`, ``), or `inputBase64` for bytes + that are not valid UTF-8. +- `editable: false`: the editor must refuse to edit the file (invalid UTF-8). +- `separator`: the line separator the editor must use (`"\r\n"` only when every break is CRLF). +- `ops`, applied in order: + - `{ "find", "replace" }`: replace the first occurrence of `find`. + - `{ "frontmatter": "set" | "add" | "remove", "key", "value" }`: a frontmatter panel edit. + `expectNull: true` means the panel must refuse the edit (list, map, or missing key) and change nothing. +- `expected`: the file after the ops. + +Each editor also checks that loading `input` and saving with no edit gives the same bytes. + +Runners: `packages/core/src/docs/round-trip.test.ts` (string level) and +`apps/web/src/lib/doc-editor.test.ts` (through a CodeMirror `EditorState`). diff --git a/packages/core/fixtures/docs/round-trip.json b/packages/core/fixtures/docs/round-trip.json new file mode 100644 index 0000000..c25f4cf --- /dev/null +++ b/packages/core/fixtures/docs/round-trip.json @@ -0,0 +1,54 @@ +{ + "about": "Shared round-trip fixtures for every Gitwork doc editor (decision 011). Format: fixtures/docs/README.md.", + "cases": [ + { "name": "lf-basic", "input": "# Title\n\nHello *world*.\n", "separator": "\n", + "ops": [{ "find": "Hello", "replace": "Hi" }], "expected": "# Title\n\nHi *world*.\n" }, + { "name": "crlf", "input": "# Notes\r\n\r\nLine one\r\nLine two\r\n", "separator": "\r\n", + "ops": [{ "find": "two", "replace": "2" }], "expected": "# Notes\r\n\r\nLine one\r\nLine 2\r\n" }, + { "name": "crlf-new-line", "input": "a\r\nb\r\n", "separator": "\r\n", + "ops": [{ "find": "a\r\n", "replace": "a\r\nnew\r\n" }], "expected": "a\r\nnew\r\nb\r\n" }, + { "name": "mixed-endings", "input": "a\r\nb\nc\r\n", "separator": "\n", + "ops": [{ "find": "b", "replace": "B" }], "expected": "a\r\nB\nc\r\n" }, + { "name": "lone-cr", "input": "a\rb\nc\n", "separator": "\n", + "ops": [{ "find": "c", "replace": "d" }], "expected": "a\rb\nd\n" }, + { "name": "bom", "input": "# Title\nBody\n", "separator": "\n", + "ops": [{ "find": "Body", "replace": "Text" }], "expected": "# Title\nText\n" }, + { "name": "no-trailing-newline", "input": "first\nlast", "separator": "\n", + "ops": [{ "find": "last", "replace": "final" }], "expected": "first\nfinal" }, + { "name": "trailing-whitespace", "input": "keep \n\tedit me \t\nkeep\t\n", "separator": "\n", + "ops": [{ "find": "edit", "replace": "change" }], "expected": "keep \n\tchange me \t\nkeep\t\n" }, + { "name": "non-ascii", "input": "Café — naïve 😀\n日本語のテキスト\n", "separator": "\n", + "ops": [{ "find": "日本語", "replace": "中文" }], "expected": "Café — naïve 😀\n中文のテキスト\n" }, + { "name": "empty", "input": "", "separator": "\n", "ops": [], "expected": "" }, + { "name": "invalid-utf8", "inputBase64": "IyD/Cg==", "editable": false }, + { "name": "frontmatter-set", "input": "---\ntitle: Old title\ntags: [a, b]\nowner: \"Jane\"\n---\n\nBody\n", "separator": "\n", + "ops": [ + { "frontmatter": "set", "key": "title", "value": "New title" }, + { "frontmatter": "set", "key": "owner", "value": "Jane Doe" }, + { "frontmatter": "set", "key": "tags", "value": "c", "expectNull": true } + ], + "expected": "---\ntitle: New title\ntags: [a, b]\nowner: \"Jane Doe\"\n---\n\nBody\n" }, + { "name": "frontmatter-crlf-add", "input": "---\r\ntitle: A\r\n---\r\nBody\r\n", "separator": "\r\n", + "ops": [{ "frontmatter": "add", "key": "status", "value": "draft" }], "expected": "---\r\ntitle: A\r\nstatus: draft\r\n---\r\nBody\r\n" }, + { "name": "frontmatter-quotes-when-needed", "input": "---\ntitle: A\nflag: B\n---\n", "separator": "\n", + "ops": [ + { "frontmatter": "set", "key": "title", "value": "Note: important" }, + { "frontmatter": "set", "key": "flag", "value": "true" } + ], + "expected": "---\ntitle: \"Note: important\"\nflag: \"true\"\n---\n" }, + { "name": "frontmatter-single-quotes-kept", "input": "---\nowner: 'Ann'\n---\n", "separator": "\n", + "ops": [{ "frontmatter": "set", "key": "owner", "value": "Ann's team" }], "expected": "---\nowner: 'Ann''s team'\n---\n" }, + { "name": "frontmatter-list-read-only", "input": "---\ntags:\n - a\n - b\ntitle: X\n---\n", "separator": "\n", + "ops": [ + { "frontmatter": "set", "key": "tags", "value": "c", "expectNull": true }, + { "frontmatter": "set", "key": "title", "value": "Y" } + ], + "expected": "---\ntags:\n - a\n - b\ntitle: Y\n---\n" }, + { "name": "frontmatter-remove", "input": "---\na: 1\nb: 2\n---\n", "separator": "\n", + "ops": [{ "frontmatter": "remove", "key": "a" }], "expected": "---\nb: 2\n---\n" }, + { "name": "frontmatter-create", "input": "Body\n", "separator": "\n", + "ops": [{ "frontmatter": "add", "key": "title", "value": "Hello" }], "expected": "---\ntitle: Hello\n---\nBody\n" }, + { "name": "frontmatter-after-bom", "input": "---\ntitle: A\n---\n", "separator": "\n", + "ops": [{ "frontmatter": "set", "key": "title", "value": "B" }], "expected": "---\ntitle: B\n---\n" } + ] +} diff --git a/packages/core/package.json b/packages/core/package.json index f0847b0..8b2d340 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -5,7 +5,8 @@ "license": "AGPL-3.0-only", "type": "module", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./fixtures/docs/round-trip.json": "./fixtures/docs/round-trip.json" }, "scripts": { "lint": "eslint --config ../../eslint.config.mjs .", diff --git a/packages/core/src/docs/fixtures.ts b/packages/core/src/docs/fixtures.ts new file mode 100644 index 0000000..8186ac2 --- /dev/null +++ b/packages/core/src/docs/fixtures.ts @@ -0,0 +1,40 @@ +/** Loader and string-level runner for the shared round-trip fixtures (fixtures/docs/README.md). */ +import { addFrontmatterKey, removeFrontmatterKey, setFrontmatterValue } from "./frontmatter"; +import { type TextChange, applyChange, lineSeparatorOf } from "./text"; + +export type FixtureOp = + | { find: string; replace: string } + | { frontmatter: "set" | "add" | "remove"; key: string; value?: string; expectNull?: boolean }; + +export interface FixtureCase { + name: string; + input?: string; + inputBase64?: string; + editable?: boolean; + separator?: "\n" | "\r\n"; + ops?: FixtureOp[]; + expected?: string; +} + +/** The change one op makes to `text`, or null when the op must be refused. */ +export function opChange(text: string, op: FixtureOp): TextChange | null { + if ("find" in op) { + const from = text.indexOf(op.find); + if (from === -1) throw new Error(`fixture: "${op.find}" not found`); + return { from, to: from + op.find.length, insert: op.replace }; + } + if (op.frontmatter === "set") return setFrontmatterValue(text, op.key, op.value ?? ""); + if (op.frontmatter === "add") return addFrontmatterKey(text, op.key, op.value ?? "", lineSeparatorOf(text)); + return removeFrontmatterKey(text, op.key); +} + +export function runOps(text: string, ops: FixtureOp[]): string { + let out = text; + for (const op of ops) { + const change = opChange(out, op); + const refused = "frontmatter" in op && op.expectNull === true; + if (refused !== (change === null)) throw new Error(`fixture op ${JSON.stringify(op)}: ${refused ? "should be refused" : "was refused"}`); + if (change) out = applyChange(out, change); + } + return out; +} diff --git a/packages/core/src/docs/frontmatter.test.ts b/packages/core/src/docs/frontmatter.test.ts new file mode 100644 index 0000000..cb0e94d --- /dev/null +++ b/packages/core/src/docs/frontmatter.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import { formatValue, parseFrontmatter } from "./frontmatter"; +import { offsetToEditorPos } from "./text"; + +describe("parseFrontmatter", () => { + it("reads simple keys and marks complex ones read-only", () => { + const fm = parseFrontmatter('---\ntitle: Hello\nquoted: "a \\"b\\""\nlist: [1, 2]\nnested:\n a: 1\nnote: x # comment\nempty:\n---\nBody'); + expect(fm?.entries.map((e) => [e.key, e.value, e.editable])).toEqual([ + ["title", "Hello", true], + ["quoted", 'a "b"', true], + ["list", "[1, 2]", false], + ["nested", "", false], + ["note", "x # comment", false], + ["empty", "", true], + ]); + }); + + it("needs the opening line at the very top and a closing line", () => { + expect(parseFrontmatter("\n---\na: 1\n---\n")).toBeNull(); + expect(parseFrontmatter("---\na: 1\n")).toBeNull(); + expect(parseFrontmatter("---\na: 1\n...\n")?.entries).toHaveLength(1); + }); + + it("refuses escapes it cannot round-trip", () => { + expect(parseFrontmatter('---\na: "x\\ny"\n---\n')?.entries[0]?.editable).toBe(false); + }); +}); + +describe("formatValue", () => { + it.each([ + ["plain", "plain"], + ["two words", "two words"], + ["a: b", '"a: b"'], + ["#tag", '"#tag"'], + ["- item", '"- item"'], + ["null", '"null"'], + ["12", '"12"'], + [" padded", '" padded"'], + ["", '""'], + ['say "hi"', 'say "hi"'], + ['"start', '"\\"start"'], + ["line\nbreak", '"line\\nbreak"'], + ])("%j → %s", (value, out) => expect(formatValue(value)).toBe(out)); +}); + +describe("offsetToEditorPos", () => { + it("counts a CRLF as one editor position", () => { + expect(offsetToEditorPos("a\r\nb\r\nc", 6, "\r\n")).toBe(4); + expect(offsetToEditorPos("a\r\nb", 4, "\n")).toBe(4); + }); +}); diff --git a/packages/core/src/docs/frontmatter.ts b/packages/core/src/docs/frontmatter.ts new file mode 100644 index 0000000..e3aa594 --- /dev/null +++ b/packages/core/src/docs/frontmatter.ts @@ -0,0 +1,146 @@ +/** + * The frontmatter panel (decision 011). It never parses and re-dumps YAML: each edit replaces the + * value text on one line, so every other byte of the file stays as it was. Values the panel cannot + * edit safely (lists, maps, block scalars, comments) show as read-only. + */ +import type { TextChange } from "./text"; + +export interface FrontmatterEntry { + key: string; + /** The value as shown: quotes removed for simple strings, the raw text otherwise. */ + value: string; + /** False for lists, maps, multi-line, and commented values: edit those in the source. */ + editable: boolean; + /** String offsets of the raw value on its line (empty range when the line is "key:"). */ + valueFrom: number; + valueTo: number; + /** The whole line, including its line break. */ + lineFrom: number; + lineTo: number; + quote: '"' | "'" | null; +} + +export interface Frontmatter { + entries: FrontmatterEntry[]; + /** Offset of the closing "---" line's start: new keys go here. */ + insertAt: number; + /** The line break the block uses. */ + lineBreak: string; +} + +const KEY = /^([A-Za-z_][\w-]*(?: [\w-]+)*):(?:[ \t]+(.*?))?[ \t]*$/; + +function lines(text: string, from: number, to: number): { start: number; end: number; content: string; br: string }[] { + const out = []; + let pos = from; + while (pos < to) { + const nl = text.indexOf("\n", pos); + const end = nl === -1 || nl >= to ? to : nl + 1; + let content = text.slice(pos, end); + let br = ""; + if (content.endsWith("\r\n")) [content, br] = [content.slice(0, -2), "\r\n"]; + else if (content.endsWith("\n")) [content, br] = [content.slice(0, -1), "\n"]; + out.push({ start: pos, end, content, br }); + pos = end; + } + return out; +} + +function unquote(raw: string): { value: string; quote: '"' | "'" | null; simple: boolean } { + if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) { + const inner = raw.slice(1, -1); + // Escapes other than \" and \\ (\n, \t, \u…) are left to the source editor. + if (/\\[^"\\]/.test(inner) || /(^|[^\\])"/.test(inner.replace(/\\\\/g, ""))) return { value: raw, quote: null, simple: false }; + return { value: inner.replace(/\\(["\\])/g, "$1"), quote: '"', simple: true }; + } + if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) { + const inner = raw.slice(1, -1); + if (/(^|[^'])'(?!')/.test(inner)) return { value: raw, quote: null, simple: false }; + return { value: inner.replace(/''/g, "'"), quote: "'", simple: true }; + } + const simple = raw !== "" && !/^[[{|>&*!%@`]/.test(raw) && !/\s#/.test(raw); + return { value: raw, quote: null, simple }; +} + +/** The frontmatter block at the top of a doc (after an optional BOM), or null when there is none. */ +export function parseFrontmatter(text: string): Frontmatter | null { + const start = text.startsWith("\uFEFF") ? 1 : 0; + const all = lines(text, start, text.length); + if (all.length < 2 || all[0]!.content !== "---") return null; + const close = all.findIndex((l, i) => i > 0 && (l.content === "---" || l.content === "...")); + if (close === -1) return null; + const entries: FrontmatterEntry[] = []; + for (let i = 1; i < close; i++) { + const line = all[i]!; + const m = KEY.exec(line.content); + if (!m) { + // An indented or list line belongs to the key above it: that value is not simple. + const prev = entries[entries.length - 1]; + if (prev && /^[ \t-]/.test(line.content)) { + prev.editable = false; + prev.lineTo = line.end; + } + continue; + } + const raw = m[2] ?? ""; + // The key cannot contain ":", so the first one ends it. + const afterColon = line.start + line.content.indexOf(":") + 1; + const valueFrom = raw ? afterColon + text.slice(afterColon, line.start + line.content.length).search(/\S/) : afterColon; + const parsed = unquote(raw); + entries.push({ + key: m[1]!, + value: parsed.value, + editable: raw === "" ? true : parsed.simple, + valueFrom, + valueTo: valueFrom + raw.length, + lineFrom: line.start, + lineTo: line.end, + quote: parsed.quote, + }); + } + return { entries, insertAt: all[close]!.start, lineBreak: all[0]!.br || "\n" }; +} + +const RESERVED = /^(?:true|false|yes|no|on|off|null|~|[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?|0x[0-9a-f]+|\.inf|\.nan)$/i; + +/** YAML text for a string value. Keeps the old quote style; quotes when plain text would change. */ +export function formatValue(value: string, quote: '"' | "'" | null = null): string { + if (quote === "'") return `'${value.replace(/'/g, "''")}'`; + const plainOk = + value !== "" && + value.trim() === value && + !/[\r\n]/.test(value) && + !/^[-?:,[\]{}#&*!|>'"%@`]/.test(value) && + !/: |\s#|:$/.test(value) && + !RESERVED.test(value); + if (quote === null && plainOk) return value; + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n")}"`; +} + +/** The change that sets one editable key, or null when the key is missing or not editable. */ +export function setFrontmatterValue(text: string, key: string, value: string): TextChange | null { + const fm = parseFrontmatter(text); + const entry = fm?.entries.find((e) => e.key === key); + if (!entry || !entry.editable) return null; + const formatted = formatValue(value, entry.quote); + if (entry.valueFrom === entry.valueTo) return { from: entry.valueFrom, to: entry.valueTo, insert: ` ${formatted}` }; + return { from: entry.valueFrom, to: entry.valueTo, insert: formatted }; +} + +const NEW_KEY = /^[A-Za-z_][\w-]*$/; + +/** The change that adds a key at the end of the block, or creates the block at the top. */ +export function addFrontmatterKey(text: string, key: string, value: string, lineBreak = "\n"): TextChange | null { + if (!NEW_KEY.test(key)) return null; + const fm = parseFrontmatter(text); + if (fm?.entries.some((e) => e.key === key)) return null; + if (fm) return { from: fm.insertAt, to: fm.insertAt, insert: `${key}: ${formatValue(value)}${fm.lineBreak}` }; + const at = text.startsWith("\uFEFF") ? 1 : 0; + return { from: at, to: at, insert: `---${lineBreak}${key}: ${formatValue(value)}${lineBreak}---${lineBreak}` }; +} + +/** The change that removes one key and its value lines. */ +export function removeFrontmatterKey(text: string, key: string): TextChange | null { + const entry = parseFrontmatter(text)?.entries.find((e) => e.key === key); + return entry ? { from: entry.lineFrom, to: entry.lineTo, insert: "" } : null; +} diff --git a/packages/core/src/docs/index.ts b/packages/core/src/docs/index.ts new file mode 100644 index 0000000..ff93fb7 --- /dev/null +++ b/packages/core/src/docs/index.ts @@ -0,0 +1,4 @@ +export * from "./paths"; +export * from "./text"; +export * from "./frontmatter"; +export { type FixtureCase, type FixtureOp, opChange, runOps } from "./fixtures"; diff --git a/packages/core/src/docs/paths.test.ts b/packages/core/src/docs/paths.test.ts new file mode 100644 index 0000000..1f069e3 --- /dev/null +++ b/packages/core/src/docs/paths.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { imageType, isUnderRoot, normalizeDocPath, normalizeRoot, resolveRelative, safeFileName } from "./paths"; +import { docVisibilityContext, isDocVisible } from "../visibility"; + +describe("doc paths", () => { + it("accepts clean repo-relative paths", () => { + expect(normalizeDocPath("docs/a/b.md")).toBe("docs/a/b.md"); + expect(normalizeDocPath("docs/Ünïcode file.md")).toBe("docs/Ünïcode file.md"); + }); + + it.each(["", "/docs/a.md", "docs/a.md/", "docs//a.md", "docs/../x.md", "docs/./a.md", "docs\\a.md", "docs/a\u0000.md", ".git/config", "docs/ a.md", "x".repeat(401)])( + "rejects %j", + (p) => expect(normalizeDocPath(p)).toBeNull(), + ); + + it("normalizes a docs folder setting", () => { + expect(normalizeRoot("/docs/")).toBe("docs"); + expect(normalizeRoot(" handbook/guides ")).toBe("handbook/guides"); + expect(normalizeRoot("/")).toBeNull(); + expect(normalizeRoot("../x")).toBeNull(); + }); + + it("checks the root by whole segments", () => { + expect(isUnderRoot("docs/a.md", "docs")).toBe(true); + expect(isUnderRoot("docs-old/a.md", "docs")).toBe(false); + expect(isUnderRoot("docs", "docs")).toBe(false); + }); + + it("resolves links against the doc's folder and refuses escapes", () => { + expect(resolveRelative("docs/guide/a.md", "img/x.png")).toBe("docs/guide/img/x.png"); + expect(resolveRelative("docs/guide/a.md", "../assets/x%20y.png?raw=1#top")).toBe("docs/assets/x y.png"); + expect(resolveRelative("docs/a.md", "./b.md")).toBe("docs/b.md"); + expect(resolveRelative("docs/a.md", "../../../etc/passwd")).toBeNull(); + expect(resolveRelative("docs/a.md", "https://example.com/x.png")).toBeNull(); + expect(resolveRelative("docs/a.md", "/abs.png")).toBeNull(); + expect(resolveRelative("docs/a.md", "#heading")).toBeNull(); + expect(resolveRelative("docs/a.md", "javascript:alert(1)")).toBeNull(); + expect(resolveRelative("docs/a.md", "%E0%A4%A")).toBeNull(); + }); + + it("knows image types and makes safe upload names", () => { + expect(imageType("a/B.PNG")).toBe("image/png"); + expect(imageType("a/b.svg")).toBe("image/svg+xml"); + expect(imageType("a/b.pdf")).toBeNull(); + expect(safeFileName("Screen Shot 2026-11-19 at 10.00.png")).toBe("screen-shot-2026-11-19-at-10.00.png"); + expect(safeFileName("../../evil.PNG")).toBe("evil.png"); + expect(safeFileName("???.png")).toBe("image.png"); + }); +}); + +describe("isDocVisible", () => { + const reader = docVisibilityContext({ role: "read_only", hasGitHub: false }, { readOnlyCanComment: false, showDraftsToReadOnly: false }, "/Internal/"); + const member = docVisibilityContext({ role: "member", hasGitHub: false }, { readOnlyCanComment: false, showDraftsToReadOnly: false }, "internal"); + + it("hides the hide folder from Read Only, without case, and only whole segments", () => { + expect(isDocVisible("docs/internal/plan.md", "docs", reader)).toBe(false); + expect(isDocVisible("docs/INTERNAL/plan.md", "docs", reader)).toBe(false); + expect(isDocVisible("docs/internal", "docs", reader)).toBe(false); + expect(isDocVisible("docs/internal-notes.md", "docs", reader)).toBe(true); + expect(isDocVisible("docs/a/internal/x.md", "docs", reader)).toBe(true); + }); + + it("shows the hide folder to Members", () => { + expect(isDocVisible("docs/internal/plan.md", "docs", member)).toBe(true); + }); + + it("never shows files outside the docs folder", () => { + expect(isDocVisible("README.md", "docs", member)).toBe(false); + expect(isDocVisible("docs-old/a.md", "docs", member)).toBe(false); + }); + + it("hides nothing when no folder is set", () => { + const open = docVisibilityContext({ role: "read_only", hasGitHub: false }, { readOnlyCanComment: false, showDraftsToReadOnly: false }, " "); + expect(isDocVisible("docs/internal/plan.md", "docs", open)).toBe(true); + }); +}); diff --git a/packages/core/src/docs/paths.ts b/packages/core/src/docs/paths.ts new file mode 100644 index 0000000..eb747ac --- /dev/null +++ b/packages/core/src/docs/paths.ts @@ -0,0 +1,97 @@ +/** + * Doc paths (decision 011). A path is repo-relative, "/"-separated, with no leading or trailing + * slash. Every path from a client or a markdown link passes through these before any use. + */ + +export const MAX_PATH_LENGTH = 400; +export const DEFAULT_DOCS_ROOT = "docs"; + +// Control characters and backslashes never appear in a path we accept. +const BAD_CHARS = /[\u0000-\u001f\u007f\\]/; + +function cleanSegments(input: string): string[] | null { + if (input.length === 0 || input.length > MAX_PATH_LENGTH || BAD_CHARS.test(input)) return null; + const segments = input.split("/"); + for (const s of segments) { + if (s === "" || s === "." || s === ".." || s.trim() !== s || s.toLowerCase() === ".git") return null; + } + return segments; +} + +/** A repo-relative file path, or null when it is unsafe or malformed. */ +export function normalizeDocPath(input: string): string | null { + const segments = cleanSegments(input); + return segments ? segments.join("/") : null; +} + +/** A docs folder setting. Leading and trailing slashes are dropped; "" is not a folder. */ +export function normalizeRoot(input: string): string | null { + return normalizeDocPath(input.trim().replace(/^\/+|\/+$/g, "")); +} + +export function isUnderRoot(path: string, root: string): boolean { + return path.startsWith(`${root}/`); +} + +/** The part of `path` below `root` ("docs/a/b.md" → "a/b.md"). */ +export function relativeToRoot(path: string, root: string): string { + return isUnderRoot(path, root) ? path.slice(root.length + 1) : path; +} + +export function isMarkdownPath(path: string): boolean { + return /\.(md|markdown)$/i.test(path); +} + +const IMAGE_TYPES: Record = { + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + webp: "image/webp", + svg: "image/svg+xml", + avif: "image/avif", +}; + +/** The image media type for a path, or null when it is not an image we serve inline. */ +export function imageType(path: string): string | null { + const ext = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase(); + return ext ? (IMAGE_TYPES[ext] ?? null) : null; +} + +/** + * A link target in a doc, resolved against the doc's folder. Null for anything that is not a + * repo-relative file: URLs with a scheme, absolute paths, fragments, and paths that leave the repo. + */ +export function resolveRelative(fromDocPath: string, href: string): string | null { + const target = href.trim().split(/[?#]/)[0] ?? ""; + if (!target || target.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(target)) return null; + let decoded: string; + try { + decoded = decodeURIComponent(target); + } catch { + return null; + } + const parts = fromDocPath.split("/").slice(0, -1); + for (const seg of decoded.split("/")) { + if (seg === "" || seg === ".") continue; + if (seg === "..") { + if (parts.length === 0) return null; + parts.pop(); + } else parts.push(seg); + } + return normalizeDocPath(parts.join("/")); +} + +/** A file name for an uploaded image: lowercase, safe characters, the extension kept. */ +export function safeFileName(input: string): string { + const name = (input.split(/[\\/]/).pop() ?? "").replace(/^\.+/, ""); + const dot = name.lastIndexOf("."); + const base = (dot > 0 ? name.slice(0, dot) : name) + .normalize("NFKD") + .replace(/[^\w.-]+/g, "-") + .replace(/^-+|-+$/g, "") + .toLowerCase() + .slice(0, 60); + const ext = dot > 0 ? name.slice(dot + 1).toLowerCase().replace(/[^a-z0-9]/g, "") : ""; + return `${base || "image"}${ext ? `.${ext}` : ""}`; +} diff --git a/packages/core/src/docs/round-trip.test.ts b/packages/core/src/docs/round-trip.test.ts new file mode 100644 index 0000000..d2f5bc3 --- /dev/null +++ b/packages/core/src/docs/round-trip.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import fixtures from "../../fixtures/docs/round-trip.json"; +import { type FixtureCase, runOps } from "./fixtures"; +import { bytesEqual, bytesToText, decodeBase64, encodeBase64, lineSeparatorOf, textToBytes } from "./text"; + +const cases = fixtures.cases as FixtureCase[]; + +/** Lines with their own line break, so a changed ending counts as a changed line. */ +const linesOf = (s: string) => s.match(/[^\n]*\n|[^\n]+$/g) ?? []; + +describe.each(cases)("round-trip fixture $name", (c) => { + const bytes = c.inputBase64 ? decodeBase64(c.inputBase64) : textToBytes(c.input!); + + it("loads and saves with no edit to the same bytes (through base64, as GitHub sends them)", () => { + const text = bytesToText(decodeBase64(encodeBase64(bytes))); + if (c.editable === false) return expect(text).toBeNull(); + expect(text).toBe(c.input); + expect(bytesEqual(textToBytes(text!), bytes)).toBe(true); + }); + + if (c.editable === false) return; + + it("uses the expected line separator", () => { + expect(lineSeparatorOf(c.input!)).toBe(c.separator); + }); + + it("applies the ops and leaves untouched lines byte-identical", () => { + const out = runOps(c.input!, c.ops ?? []); + expect(out).toBe(c.expected); + const before = linesOf(c.input!); + const after = linesOf(out); + // Lines before the first difference and after the last one are the same strings. + let head = 0; + while (head < before.length && head < after.length && before[head] === after[head]) head++; + let tail = 0; + while (tail < before.length - head && tail < after.length - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++; + const changedBefore = before.length - head - tail; + // Every op touches at most a couple of lines; nothing else moved. + expect(changedBefore).toBeLessThanOrEqual(Math.max(1, (c.ops ?? []).length * 2)); + }); +}); diff --git a/packages/core/src/docs/text.ts b/packages/core/src/docs/text.ts new file mode 100644 index 0000000..42ddfdf --- /dev/null +++ b/packages/core/src/docs/text.ts @@ -0,0 +1,78 @@ +/** + * Byte-exact doc text (decision 011). A file's bytes become a string and back with no change: + * the BOM stays, line endings stay, and invalid UTF-8 is refused instead of repaired. + */ + +/** Docs larger than this open read-only. D1 caps a value at 2 MB; the cache stores the text. */ +export const MAX_EDITABLE_BYTES = 1_000_000; + +/** GitHub wraps base64 at 60 columns; whitespace is not part of the data. */ +export function decodeBase64(b64: string): Uint8Array { + const bin = atob(b64.replace(/\s+/g, "")); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +export function encodeBase64(bytes: Uint8Array): string { + let bin = ""; + const CHUNK = 0x8000; + for (let i = 0; i < bytes.length; i += CHUNK) { + bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); + } + return btoa(bin); +} + +/** The text of a UTF-8 file, or null when the bytes are not valid UTF-8 (open it read-only). */ +export function bytesToText(bytes: Uint8Array): string | null { + try { + // ignoreBOM: keep a leading U+FEFF in the string, so it is written back. + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); + } catch { + return null; + } +} + +export function textToBytes(text: string): Uint8Array { + return new TextEncoder().encode(text); +} + +export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + return true; +} + +export type LineSeparator = "\r\n" | "\n"; + +/** + * The separator an editor must split and join lines on. "\r\n" only when every line break is + * CRLF. Otherwise "\n": a CR before a LF (mixed files) or alone stays part of the line's text. + */ +export function lineSeparatorOf(text: string): LineSeparator { + const lf = text.split("\n").length - 1; + if (lf === 0) return "\n"; + const crlf = text.split("\r\n").length - 1; + const cr = text.split("\r").length - 1; + return crlf === lf && cr === crlf ? "\r\n" : "\n"; +} + +/** + * A string offset as an editor position. Editors count a line break as one position; with a CRLF + * separator the string has two characters for it. + */ +export function offsetToEditorPos(text: string, offset: number, separator: LineSeparator): number { + if (separator === "\n") return offset; + return offset - (text.slice(0, offset).split("\r\n").length - 1); +} + +/** One text change in string offsets. */ +export interface TextChange { + from: number; + to: number; + insert: string; +} + +export function applyChange(text: string, change: TextChange): string { + return text.slice(0, change.from) + change.insert + text.slice(change.to); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5ffe0ab..0c3470b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,3 +3,4 @@ export * from "./permissions"; export { safeRedirectPath } from "./redirect"; export * from "./visibility"; export * from "./keymap"; +export * from "./docs"; diff --git a/packages/core/src/visibility.ts b/packages/core/src/visibility.ts index e24befa..8236896 100644 --- a/packages/core/src/visibility.ts +++ b/packages/core/src/visibility.ts @@ -55,3 +55,28 @@ export function isTaskVisible(item: ItemFacts, ctx: VisibilityContext): boolean if (!ctx.canViewHidden && hasHideLabel(issue.labels, ctx.hideLabel)) return false; return true; } + +/** What the doc filter needs (decisions 011, 012). */ +export interface DocVisibilityContext { + /** `items.view_hidden`: may see files under the hide folder. */ + canViewHidden: boolean; + /** The workspace's hide folder, relative to each repo's docs folder, or null. */ + hideFolder: string | null; +} + +export function docVisibilityContext(actor: Actor, settings: PermissionSettings, hideFolder: string | null): DocVisibilityContext { + const folder = hideFolder?.trim().replace(/^\/+|\/+$/g, "") || null; + return { canViewHidden: can(actor, "items.view_hidden", settings), hideFolder: folder }; +} + +/** + * Whether a viewer may receive a file. Fail-closed: the path must sit under the docs folder, and + * a hidden folder is matched without case, so "Internal/" and "internal/" both hide. + */ +export function isDocVisible(path: string, root: string, ctx: DocVisibilityContext): boolean { + if (!path.startsWith(`${root}/`)) return false; + if (ctx.canViewHidden || !ctx.hideFolder) return true; + const rel = path.slice(root.length + 1).toLowerCase(); + const hidden = ctx.hideFolder.toLowerCase(); + return rel !== hidden && !rel.startsWith(`${hidden}/`); +} From 1d6d0e8f8efa239a1ce12740ca23d5e9b96f26aa Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Thu, 19 Nov 2026 15:01:44 -0500 Subject: [PATCH 2/5] feat: docs schema: per-repo docs folder and branch, hide folder, review mode, doc cache, pending PRs, presence Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHyaEvdoSPjkLy7T1aaz Signed-off-by: Erik Goins --- packages/db/migrations/0005_docs.sql | 57 + .../db/migrations/meta/0005_snapshot.json | 2499 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 88 + 4 files changed, 2651 insertions(+) create mode 100644 packages/db/migrations/0005_docs.sql create mode 100644 packages/db/migrations/meta/0005_snapshot.json diff --git a/packages/db/migrations/0005_docs.sql b/packages/db/migrations/0005_docs.sql new file mode 100644 index 0000000..739767c --- /dev/null +++ b/packages/db/migrations/0005_docs.sql @@ -0,0 +1,57 @@ +CREATE TABLE `doc_pending_prs` ( + `repo_node_id` text NOT NULL, + `base_branch` text NOT NULL, + `path` text NOT NULL, + `head_branch` text NOT NULL, + `pr_number` integer NOT NULL, + `pr_url` text NOT NULL, + `created_by` text, + `created_at` integer DEFAULT (unixepoch() * 1000) NOT NULL, + PRIMARY KEY(`repo_node_id`, `base_branch`, `path`), + FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE INDEX `doc_pending_prs_pr_idx` ON `doc_pending_prs` (`repo_node_id`,`pr_number`);--> statement-breakpoint +CREATE TABLE `doc_presence` ( + `workspace_id` text NOT NULL, + `repo_node_id` text NOT NULL, + `path` text NOT NULL, + `user_id` text NOT NULL, + `expires_at` integer NOT NULL, + PRIMARY KEY(`workspace_id`, `repo_node_id`, `path`, `user_id`), + FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `gh_doc_blobs` ( + `sha` text PRIMARY KEY NOT NULL, + `text` text NOT NULL, + `size` integer NOT NULL, + `fetched_at` integer NOT NULL +); +--> statement-breakpoint +CREATE TABLE `gh_doc_files` ( + `root_id` text NOT NULL, + `path` text NOT NULL, + `blob_sha` text NOT NULL, + `size` integer NOT NULL, + PRIMARY KEY(`root_id`, `path`) +); +--> statement-breakpoint +CREATE INDEX `gh_doc_files_blob_idx` ON `gh_doc_files` (`blob_sha`);--> statement-breakpoint +CREATE TABLE `gh_doc_roots` ( + `id` text PRIMARY KEY NOT NULL, + `repo_node_id` text NOT NULL, + `branch` text NOT NULL, + `path` text NOT NULL, + `head_oid` text, + `tree_oid` text, + `truncated` integer DEFAULT false NOT NULL, + `synced_at` integer +); +--> statement-breakpoint +CREATE INDEX `gh_doc_roots_repo_idx` ON `gh_doc_roots` (`repo_node_id`,`branch`);--> statement-breakpoint +ALTER TABLE `workspace_repos` ADD `docs_path` text DEFAULT 'docs' NOT NULL;--> statement-breakpoint +ALTER TABLE `workspace_repos` ADD `docs_branch` text;--> statement-breakpoint +ALTER TABLE `workspaces` ADD `hide_folder` text;--> statement-breakpoint +ALTER TABLE `workspaces` ADD `review_bot_doc_edits` integer DEFAULT false NOT NULL; \ No newline at end of file diff --git a/packages/db/migrations/meta/0005_snapshot.json b/packages/db/migrations/meta/0005_snapshot.json new file mode 100644 index 0000000..fd2f8f4 --- /dev/null +++ b/packages/db/migrations/meta/0005_snapshot.json @@ -0,0 +1,2499 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "f1dece56-5932-48c1-9fd5-c310a665f860", + "prevId": "d3c6cfe0-e141-47d7-855a-d10d0ff81651", + "tables": { + "account_owners": { + "name": "account_owners", + "columns": { + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "account_owners_user_id_idx": { + "name": "account_owners_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "account_owners_account_id_accounts_id_fk": { + "name": "account_owners_account_id_accounts_id_fk", + "tableFrom": "account_owners", + "tableTo": "accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "account_owners_user_id_users_id_fk": { + "name": "account_owners_user_id_users_id_fk", + "tableFrom": "account_owners", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "account_owners_account_id_user_id_pk": { + "columns": [ + "account_id", + "user_id" + ], + "name": "account_owners_account_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "accounts": { + "name": "accounts", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "audit_log_workspace_at_idx": { + "name": "audit_log_workspace_at_idx", + "columns": [ + "workspace_id", + "at" + ], + "isUnique": false + }, + "audit_log_user_at_idx": { + "name": "audit_log_user_at_idx", + "columns": [ + "user_id", + "at" + ], + "isUnique": false + }, + "audit_log_target_idx": { + "name": "audit_log_target_idx", + "columns": [ + "target" + ], + "isUnique": false + } + }, + "foreignKeys": { + "audit_log_user_id_users_id_fk": { + "name": "audit_log_user_id_users_id_fk", + "tableFrom": "audit_log", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_log_workspace_id_workspaces_id_fk": { + "name": "audit_log_workspace_id_workspaces_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "audit_log_via_ck": { + "name": "audit_log_via_ck", + "value": "\"audit_log\".\"via\" IN ('user', 'app', 'local')" + } + } + }, + "auth_identities": { + "name": "auth_identities", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "auth_identities_user_id_idx": { + "name": "auth_identities_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "auth_identities_provider_account_uq": { + "name": "auth_identities_provider_account_uq", + "columns": [ + "provider_id", + "account_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "auth_identities_user_id_users_id_fk": { + "name": "auth_identities_user_id_users_id_fk", + "tableFrom": "auth_identities", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "doc_pending_prs": { + "name": "doc_pending_prs", + "columns": { + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_branch": { + "name": "base_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "head_branch": { + "name": "head_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "doc_pending_prs_pr_idx": { + "name": "doc_pending_prs_pr_idx", + "columns": [ + "repo_node_id", + "pr_number" + ], + "isUnique": false + } + }, + "foreignKeys": { + "doc_pending_prs_created_by_users_id_fk": { + "name": "doc_pending_prs_created_by_users_id_fk", + "tableFrom": "doc_pending_prs", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "doc_pending_prs_repo_node_id_base_branch_path_pk": { + "columns": [ + "repo_node_id", + "base_branch", + "path" + ], + "name": "doc_pending_prs_repo_node_id_base_branch_path_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "doc_presence": { + "name": "doc_presence", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "doc_presence_workspace_id_workspaces_id_fk": { + "name": "doc_presence_workspace_id_workspaces_id_fk", + "tableFrom": "doc_presence", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "doc_presence_user_id_users_id_fk": { + "name": "doc_presence_user_id_users_id_fk", + "tableFrom": "doc_presence", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "doc_presence_workspace_id_repo_node_id_path_user_id_pk": { + "columns": [ + "workspace_id", + "repo_node_id", + "path", + "user_id" + ], + "name": "doc_presence_workspace_id_repo_node_id_path_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_doc_blobs": { + "name": "gh_doc_blobs", + "columns": { + "sha": { + "name": "sha", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fetched_at": { + "name": "fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_doc_files": { + "name": "gh_doc_files", + "columns": { + "root_id": { + "name": "root_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blob_sha": { + "name": "blob_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_doc_files_blob_idx": { + "name": "gh_doc_files_blob_idx", + "columns": [ + "blob_sha" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "gh_doc_files_root_id_path_pk": { + "columns": [ + "root_id", + "path" + ], + "name": "gh_doc_files_root_id_path_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_doc_roots": { + "name": "gh_doc_roots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "head_oid": { + "name": "head_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tree_oid": { + "name": "tree_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "truncated": { + "name": "truncated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "gh_doc_roots_repo_idx": { + "name": "gh_doc_roots_repo_idx", + "columns": [ + "repo_node_id", + "branch" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_issue_links": { + "name": "gh_issue_links", + "columns": { + "issue_node_id": { + "name": "issue_node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "parent_node_id": { + "name": "parent_node_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blocked_by": { + "name": "blocked_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_issue_links_parent_idx": { + "name": "gh_issue_links_parent_idx", + "columns": [ + "parent_node_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_issues": { + "name": "gh_issues", + "columns": { + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state_reason": { + "name": "state_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "labels": { + "name": "labels", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assignees": { + "name": "assignees", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "issue_type": { + "name": "issue_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "html_url": { + "name": "html_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_gh": { + "name": "created_at_gh", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "closed_at_gh": { + "name": "closed_at_gh", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "github_updated_at": { + "name": "github_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deleted": { + "name": "deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_issues_repo_number_uq": { + "name": "gh_issues_repo_number_uq", + "columns": [ + "repo_node_id", + "number" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_project_fields": { + "name": "gh_project_fields", + "columns": { + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_node_id": { + "name": "project_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "data_type": { + "name": "data_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_project_fields_project_idx": { + "name": "gh_project_fields_project_idx", + "columns": [ + "project_node_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_project_items": { + "name": "gh_project_items", + "columns": { + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_node_id": { + "name": "project_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_node_id": { + "name": "content_node_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "draft_title": { + "name": "draft_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "draft_body": { + "name": "draft_body", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "field_values": { + "name": "field_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "archived": { + "name": "archived", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "github_updated_at": { + "name": "github_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deleted": { + "name": "deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_project_items_project_idx": { + "name": "gh_project_items_project_idx", + "columns": [ + "project_node_id" + ], + "isUnique": false + }, + "gh_project_items_content_idx": { + "name": "gh_project_items_content_idx", + "columns": [ + "content_node_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_projects": { + "name": "gh_projects", + "columns": { + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_login": { + "name": "owner_login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "closed": { + "name": "closed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "available": { + "name": "available", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_repos": { + "name": "gh_repos", + "columns": { + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "github_id": { + "name": "github_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner": { + "name": "owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "full_name": { + "name": "full_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "private": { + "name": "private", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "archived": { + "name": "archived", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "html_url": { + "name": "html_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "available": { + "name": "available", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "synced_at": { + "name": "synced_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "gh_repos_github_id_unique": { + "name": "gh_repos_github_id_unique", + "columns": [ + "github_id" + ], + "isUnique": true + }, + "gh_repos_installation_idx": { + "name": "gh_repos_installation_idx", + "columns": [ + "installation_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "gh_sync_targets": { + "name": "gh_sync_targets", + "columns": { + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "locator": { + "name": "locator", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_full_sync_at": { + "name": "last_full_sync_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sweep_started_at": { + "name": "sweep_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sweep_cursor": { + "name": "sweep_cursor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "gh_sync_targets_kind_node_id_pk": { + "columns": [ + "kind", + "node_id" + ], + "name": "gh_sync_targets_kind_node_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "gh_sync_targets_kind_ck": { + "name": "gh_sync_targets_kind_ck", + "value": "\"gh_sync_targets\".\"kind\" IN ('repo', 'project')" + } + } + }, + "github_app": { + "name": "github_app", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "webhook_secret": { + "name": "webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "private_key": { + "name": "private_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "html_url": { + "name": "html_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_login": { + "name": "owner_login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "github_app_singleton_ck": { + "name": "github_app_singleton_ck", + "value": "\"github_app\".\"id\" = 1" + } + } + }, + "github_installation_tokens": { + "name": "github_installation_tokens", + "columns": { + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "github_installations": { + "name": "github_installations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_login": { + "name": "account_login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_type": { + "name": "account_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repository_selection": { + "name": "repository_selection", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "github_manifest_states": { + "name": "github_manifest_states", + "columns": { + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "github_manifest_states_user_id_users_id_fk": { + "name": "github_manifest_states_user_id_users_id_fk", + "tableFrom": "github_manifest_states", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "github_webhook_deliveries": { + "name": "github_webhook_deliveries", + "columns": { + "delivery_id": { + "name": "delivery_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "instance_settings": { + "name": "instance_settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "invites": { + "name": "invites", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "accepted_by": { + "name": "accepted_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "invites_token_hash_unique": { + "name": "invites_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + }, + "invites_workspace_id_idx": { + "name": "invites_workspace_id_idx", + "columns": [ + "workspace_id" + ], + "isUnique": false + }, + "invites_email_idx": { + "name": "invites_email_idx", + "columns": [ + "email" + ], + "isUnique": false + } + }, + "foreignKeys": { + "invites_workspace_id_workspaces_id_fk": { + "name": "invites_workspace_id_workspaces_id_fk", + "tableFrom": "invites", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invites_invited_by_users_id_fk": { + "name": "invites_invited_by_users_id_fk", + "tableFrom": "invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "invites_accepted_by_users_id_fk": { + "name": "invites_accepted_by_users_id_fk", + "tableFrom": "invites", + "tableTo": "users", + "columnsFrom": [ + "accepted_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "invites_role_ck": { + "name": "invites_role_ck", + "value": "\"invites\".\"role\" IN ('owner', 'admin', 'member', 'read_only')" + }, + "invites_email_lower_ck": { + "name": "invites_email_lower_ck", + "value": "\"invites\".\"email\" = lower(\"invites\".\"email\")" + } + } + }, + "rate_limits": { + "name": "rate_limits", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_request": { + "name": "last_request", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "rate_limits_key_unique": { + "name": "rate_limits_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "sessions_token_unique": { + "name": "sessions_token_unique", + "columns": [ + "token" + ], + "isUnique": true + }, + "sessions_user_id_idx": { + "name": "sessions_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sync_leases": { + "name": "sync_leases", + "columns": { + "name": { + "name": "name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "holder": { + "name": "holder", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified": { + "name": "email_verified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "verifications": { + "name": "verifications", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "verifications_identifier_idx": { + "name": "verifications_identifier_idx", + "columns": [ + "identifier" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_github": { + "name": "workspace_github", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_node_id": { + "name": "project_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kanban_field_id": { + "name": "kanban_field_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "start_field_id": { + "name": "start_field_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_field_id": { + "name": "target_field_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "iteration_field_id": { + "name": "iteration_field_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "linked_by": { + "name": "linked_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "linked_at": { + "name": "linked_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_github_workspace_id_workspaces_id_fk": { + "name": "workspace_github_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_github", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_github_linked_by_users_id_fk": { + "name": "workspace_github_linked_by_users_id_fk", + "tableFrom": "workspace_github", + "tableTo": "users", + "columnsFrom": [ + "linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_members": { + "name": "workspace_members", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "workspace_members_user_id_idx": { + "name": "workspace_members_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspace_members_workspace_id_workspaces_id_fk": { + "name": "workspace_members_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_members", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_members_user_id_users_id_fk": { + "name": "workspace_members_user_id_users_id_fk", + "tableFrom": "workspace_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_members_workspace_id_user_id_pk": { + "columns": [ + "workspace_id", + "user_id" + ], + "name": "workspace_members_workspace_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "workspace_members_role_ck": { + "name": "workspace_members_role_ck", + "value": "\"workspace_members\".\"role\" IN ('owner', 'admin', 'member', 'read_only')" + } + } + }, + "workspace_repos": { + "name": "workspace_repos", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_node_id": { + "name": "repo_node_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "docs_path": { + "name": "docs_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'docs'" + }, + "docs_branch": { + "name": "docs_branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "workspace_repos_repo_idx": { + "name": "workspace_repos_repo_idx", + "columns": [ + "repo_node_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspace_repos_workspace_id_workspaces_id_fk": { + "name": "workspace_repos_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_repos", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_repos_workspace_id_repo_node_id_pk": { + "columns": [ + "workspace_id", + "repo_node_id" + ], + "name": "workspace_repos_workspace_id_repo_node_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspaces": { + "name": "workspaces", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "read_only_can_comment": { + "name": "read_only_can_comment", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "show_drafts_to_read_only": { + "name": "show_drafts_to_read_only", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "hide_label": { + "name": "hide_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hide_folder": { + "name": "hide_folder", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "review_bot_doc_edits": { + "name": "review_bot_doc_edits", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch() * 1000)" + } + }, + "indexes": { + "workspaces_account_id_idx": { + "name": "workspaces_account_id_idx", + "columns": [ + "account_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspaces_account_id_accounts_id_fk": { + "name": "workspaces_account_id_accounts_id_fk", + "tableFrom": "workspaces", + "tableTo": "accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 5382e47..c294f53 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1792112885253, "tag": "0004_tasks", "breakpoints": true + }, + { + "idx": 5, + "version": "6", + "when": 1795117928777, + "tag": "0005_docs", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index da591a5..0bd1afb 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -138,6 +138,10 @@ export const workspaces = sqliteTable( showDraftsToReadOnly: integer("show_drafts_to_read_only", { mode: "boolean" }).notNull().default(false), /** Issues with this label are hidden from Read Only (decision 012). Compared without case. */ hideLabel: text("hide_label"), + /** Files under this folder (relative to each docs folder) are hidden from Read Only (012). */ + hideFolder: text("hide_folder"), + /** Decision 008 review mode: App doc writes open a pull request instead of a commit. */ + reviewBotDocEdits: integer("review_bot_doc_edits", { mode: "boolean" }).notNull().default(false), createdAt: createdAt(), }, (t) => [index("workspaces_account_id_idx").on(t.accountId)], @@ -405,6 +409,10 @@ export const workspaceRepos = sqliteTable( .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), repoNodeId: text("repo_node_id").notNull(), + /** The repo's docs folder for this workspace (decision 011). */ + docsPath: text("docs_path").notNull().default("docs"), + /** The branch docs are read from and committed to; null = the repo's default branch. */ + docsBranch: text("docs_branch"), }, (t) => [primaryKey({ columns: [t.workspaceId, t.repoNodeId] }), index("workspace_repos_repo_idx").on(t.repoNodeId)], ); @@ -447,3 +455,83 @@ export const auditLog = sqliteTable( check("audit_log_via_ck", sql`${t.via} IN ('user', 'app', 'local')`), ], ); + +// --------------------------------------------------------------------------------------------- +// Docs (Phase 4, decisions 011, 035, 036). The tree and text are a cache of GitHub, like gh_*. +// --------------------------------------------------------------------------------------------- + +/** + * One docs folder on one branch of one repo. Id: "::" (git branch names + * cannot contain ":"). `treeOid` is null when the folder does not exist on the branch. + */ +export const ghDocRoots = sqliteTable( + "gh_doc_roots", + { + id: text("id").primaryKey(), + repoNodeId: text("repo_node_id").notNull(), + branch: text("branch").notNull(), + path: text("path").notNull(), + headOid: text("head_oid"), + treeOid: text("tree_oid"), + /** GitHub cut the tree listing short, or it passed the file cap: the tree is incomplete. */ + truncated: integer("truncated", { mode: "boolean" }).notNull().default(false), + syncedAt: integer("synced_at", { mode: "timestamp_ms" }), + }, + (t) => [index("gh_doc_roots_repo_idx").on(t.repoNodeId, t.branch)], +); + +/** Files under a docs folder at the root's `headOid`. Paths are repo-relative. */ +export const ghDocFiles = sqliteTable( + "gh_doc_files", + { + rootId: text("root_id").notNull(), + path: text("path").notNull(), + blobSha: text("blob_sha").notNull(), + size: integer("size").notNull(), + }, + (t) => [primaryKey({ columns: [t.rootId, t.path] }), index("gh_doc_files_blob_idx").on(t.blobSha)], +); + +/** Doc text by git blob sha. Content-addressed: a row never changes, unused rows are pruned. */ +export const ghDocBlobs = sqliteTable("gh_doc_blobs", { + sha: text("sha").primaryKey(), + text: text("text").notNull(), + size: integer("size").notNull(), + fetchedAt: integer("fetched_at", { mode: "timestamp_ms" }).notNull(), +}); + +/** + * A doc save that became a pull request (branch protection or review mode). While it is open, + * saves of that doc go to the PR branch. The `pull_request` webhook removes the row on close. + */ +export const docPendingPrs = sqliteTable( + "doc_pending_prs", + { + repoNodeId: text("repo_node_id").notNull(), + baseBranch: text("base_branch").notNull(), + path: text("path").notNull(), + headBranch: text("head_branch").notNull(), + prNumber: integer("pr_number").notNull(), + prUrl: text("pr_url").notNull(), + createdBy: text("created_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.repoNodeId, t.baseBranch, t.path] }), index("doc_pending_prs_pr_idx").on(t.repoNodeId, t.prNumber)], +); + +/** "Jane is editing" (spec: presence is a heartbeat row). Rows past `expiresAt` are ignored. */ +export const docPresence = sqliteTable( + "doc_presence", + { + workspaceId: text("workspace_id") + .notNull() + .references(() => workspaces.id, { onDelete: "cascade" }), + repoNodeId: text("repo_node_id").notNull(), + path: text("path").notNull(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + }, + (t) => [primaryKey({ columns: [t.workspaceId, t.repoNodeId, t.path, t.userId] })], +); From ac50687bed251cf15ba8473b9c2dd5376bf569cb Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Thu, 19 Nov 2026 15:01:44 -0500 Subject: [PATCH 3/5] feat: docs sync, read, and write API Tree cache from push webhooks and reconcile; text cached by blob sha; one signed createCommitOnBranch per write; conflict vs. branch protection by re-reading the file; pull request fallback and review mode; image proxy with a sandbox policy; presence heartbeats. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHyaEvdoSPjkLy7T1aaz Signed-off-by: Erik Goins --- packages/server/src/api/router.ts | 5 +- packages/server/src/api/routes.ts | 172 +++- packages/server/src/errors.ts | 4 +- packages/server/src/github/cache.ts | 53 +- packages/server/src/github/docs.ts | 191 +++++ packages/server/src/github/reconcile.ts | 10 +- packages/server/src/github/webhooks.ts | 28 +- packages/server/src/services/access.ts | 18 +- packages/server/src/services/docs.ts | 758 ++++++++++++++++++ .../server/src/services/workspace-settings.ts | 13 +- packages/server/test/api-docs.test.ts | 117 +++ packages/server/test/docs.test.ts | 371 +++++++++ packages/server/test/fake-github.ts | 167 ++++ 13 files changed, 1894 insertions(+), 13 deletions(-) create mode 100644 packages/server/src/github/docs.ts create mode 100644 packages/server/src/services/docs.ts create mode 100644 packages/server/test/api-docs.test.ts create mode 100644 packages/server/test/docs.test.ts diff --git a/packages/server/src/api/router.ts b/packages/server/src/api/router.ts index ebd64b3..56bf6bb 100644 --- a/packages/server/src/api/router.ts +++ b/packages/server/src/api/router.ts @@ -71,7 +71,8 @@ function match(pattern: string, path: string): Record | null { } const json = (status: number, data: unknown) => Response.json(data, { status }); -const error = (status: number, code: string, message: string) => json(status, { error: { code, message } }); +const error = (status: number, code: string, message: string, data?: Record) => + json(status, { error: { ...data, code, message } }); /** * Cookie-authenticated writes must come from our own origin. Next.js route handlers get no CSRF @@ -116,7 +117,7 @@ export function createApiHandler(routes: Route[], prefix = "/api/v1") { if (result instanceof Response) return result; return result === undefined ? new Response(null, { status: 204 }) : json(200, result); } catch (e) { - if (e instanceof ServiceError) return error(e.status, e.code, e.message); + if (e instanceof ServiceError) return error(e.status, e.code, e.message, e.data); if (e instanceof GitHubRateLimitError) { const res = error(503, "github_rate_limited", "GitHub is rate limiting this instance. Try again shortly."); res.headers.set("retry-after", String(Math.max(1, Math.ceil((e.retryAt - Date.now()) / 1000)))); diff --git a/packages/server/src/api/routes.ts b/packages/server/src/api/routes.ts index 4878bd0..fc39a6e 100644 --- a/packages/server/src/api/routes.ts +++ b/packages/server/src/api/routes.ts @@ -15,11 +15,26 @@ import { import { changeMemberRole, listMembers, removeMember } from "../services/members"; import { getSignupPolicy, setSignupPolicy } from "../instance-settings"; import { installUrl, isInstanceAdmin, removeGitHubApp, startManifestFlow } from "../github/setup"; -import { conflict, forbidden } from "../errors"; +import { badRequest, conflict, forbidden } from "../errors"; import { getWorkspaceLink, linkWorkspace, listLinkCandidates, MAX_LINKED_REPOS, unlinkWorkspace } from "../services/link"; import { createTask, getTask, listTasks, resolveMapping, setFieldMapping, updateTask } from "../services/tasks"; import { serializedSnapshot } from "../services/board-sync"; import { updateWorkspaceSettings } from "../services/workspace-settings"; +import { + MAX_ATTACHMENTS, + createDoc, + deleteDoc, + getDoc, + heartbeat, + leave, + listDocs, + rawDocFile, + refreshDocs, + renameDoc, + saveDoc, + setDocsConfig, + workspaceDocRepos, +} from "../services/docs"; import { type RouteContext, createApiHandler, route } from "./router"; /** GitHub-backed services need the App; before /setup there is none. */ @@ -33,6 +48,20 @@ function taskDeps(ctx: RouteContext) { return { ...githubDeps(ctx), displayName: user.name?.trim() || user.email }; } +function docDeps(ctx: RouteContext) { + const user = ctx.session!.user; + return { ...githubDeps(ctx), author: { name: user.name?.trim() || user.email, email: user.email } }; +} + +/** `?repo=…&path=…` on doc reads, deletes, and presence. */ +function fileQuery(request: Request) { + const q = new URL(request.url).searchParams; + const repo = q.get("repo") ?? ""; + const path = q.get("path") ?? ""; + if (!repo || !path || repo.length > 200 || path.length > 400) throw badRequest("Name a repo and a path."); + return { repo, path, sha: q.get("sha") ?? "" }; +} + function requireInstanceAdmin(ctx: RouteContext) { if (!isInstanceAdmin(ctx.session!.user.email, ctx.deps.instanceAdminEmails ?? [])) throw forbidden(); } @@ -51,6 +80,11 @@ const fieldChanges = z.record(nodeId, fieldInput.nullable()).optional(); const taskTitle = z.string().trim().min(1, "Title is required.").max(256, "Title is too long."); // GitHub's issue body limit. const taskBody = z.string().max(65_536, "The description is too long."); +const docPath = z.string().min(1, "Name the doc.").max(400, "That path is too long."); +const blobSha = z.string().regex(/^[0-9a-f]{40}$/, "Unknown version of the doc."); +// The service checks the UTF-8 size (1 MB); this only stops absurd bodies early. +const docText = z.string().max(1_000_000, "This doc is too large to save here."); +const attachment = z.object({ path: docPath, data: z.string().max(14_000_000, "Images can be at most 10 MB.") }); export const routes = [ route({ @@ -164,6 +198,129 @@ export const routes = [ }, }), + route({ + method: "GET", + pattern: "/workspaces/:workspaceId/docs", + async handler({ deps, session, params }) { + const access = await requireWorkspaceAccess(deps.database.db, session!.user.id, params.workspaceId!); + return listDocs(deps.database.db, access); + }, + }), + + route({ + method: "POST", + pattern: "/workspaces/:workspaceId/docs/refresh", + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "docs.write"); + const out = await refreshDocs(githubDeps(ctx), access); + return { synced: out.synced.length, failed: out.failed.length }; + }, + }), + + route({ + method: "GET", + pattern: "/workspaces/:workspaceId/docs/file", + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + const q = fileQuery(ctx.request); + return { doc: await getDoc(githubDeps(ctx), access, q.repo, q.path) }; + }, + }), + + route({ + method: "GET", + pattern: "/workspaces/:workspaceId/docs/raw", + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + const q = fileQuery(ctx.request); + return rawDocFile(githubDeps(ctx), access, q.repo, q.path); + }, + }), + + route({ + method: "PUT", + pattern: "/workspaces/:workspaceId/docs/file", + body: z.object({ + repoNodeId: nodeId, + path: docPath, + baseSha: blobSha, + text: docText, + attachments: z.array(attachment).max(MAX_ATTACHMENTS).optional(), + message: z.string().max(200).optional(), + }), + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "docs.write"); + return saveDoc(docDeps(ctx), access, ctx.body); + }, + }), + + route({ + method: "POST", + pattern: "/workspaces/:workspaceId/docs/file", + body: z.object({ repoNodeId: nodeId, path: docPath, text: docText.optional() }), + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "docs.write"); + return createDoc(docDeps(ctx), access, ctx.body); + }, + }), + + route({ + method: "POST", + pattern: "/workspaces/:workspaceId/docs/rename", + body: z.object({ repoNodeId: nodeId, path: docPath, baseSha: blobSha, newPath: docPath }), + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "docs.write"); + return renameDoc(docDeps(ctx), access, ctx.body); + }, + }), + + route({ + method: "DELETE", + pattern: "/workspaces/:workspaceId/docs/file", + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "docs.delete"); + const q = fileQuery(ctx.request); + if (!/^[0-9a-f]{40}$/.test(q.sha)) throw badRequest("Unknown version of the doc."); + return deleteDoc(docDeps(ctx), access, { repoNodeId: q.repo, path: q.path, baseSha: q.sha }); + }, + }), + + route({ + method: "POST", + pattern: "/workspaces/:workspaceId/docs/presence", + body: z.object({ repoNodeId: nodeId, path: docPath }), + async handler({ deps, session, params, body }) { + const access = await requireWorkspaceAccess(deps.database.db, session!.user.id, params.workspaceId!); + return { editors: await heartbeat(deps.database.db, access, body.repoNodeId, body.path) }; + }, + }), + + route({ + method: "DELETE", + pattern: "/workspaces/:workspaceId/docs/presence", + async handler({ deps, session, params, request }) { + const access = await requireWorkspaceAccess(deps.database.db, session!.user.id, params.workspaceId!); + const q = fileQuery(request); + await leave(deps.database.db, access, q.repo, q.path); + }, + }), + + route({ + method: "PATCH", + pattern: "/workspaces/:workspaceId/github/repos/:repoNodeId/docs", + body: z.object({ docsPath: z.string().max(200).optional(), docsBranch: z.string().max(200).nullable().optional() }), + async handler(ctx) { + const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); + requireCapability(access, "workspace.github_settings"); + await setDocsConfig(githubDeps(ctx), access, { repoNodeId: ctx.params.repoNodeId!, ...ctx.body }); + }, + }), + route({ method: "GET", pattern: "/workspaces/:workspaceId/github", @@ -173,11 +330,20 @@ export const routes = [ const data = await getWorkspaceLink(db, params.workspaceId!); if (!data) return { linked: false }; const fields = data.fields.map((f) => ({ id: f.nodeId, name: f.name, dataType: f.dataType })); + const docRepos = await workspaceDocRepos(db, params.workspaceId!); return { linked: true, installationId: data.link.installationId, board: data.project ? { nodeId: data.project.nodeId, title: data.project.title, url: data.project.url, available: data.project.available } : null, - repos: data.repos.map((r) => ({ nodeId: r.nodeId, fullName: r.fullName, available: r.available })), + repos: data.repos.map((r) => { + const d = docRepos.find((x) => x.repoNodeId === r.nodeId); + return { + nodeId: r.nodeId, + fullName: r.fullName, + available: r.available, + docs: d ? { path: d.path, branch: d.branch, defaultBranch: d.defaultBranch } : null, + }; + }), fields, mapping: resolveMapping(fields, data.link), }; @@ -239,6 +405,8 @@ export const routes = [ pattern: "/workspaces/:workspaceId/settings", body: z.object({ hideLabel: z.string().max(50).nullable().optional(), + hideFolder: z.string().max(200).nullable().optional(), + reviewBotDocEdits: z.boolean().optional(), showDraftsToReadOnly: z.boolean().optional(), readOnlyCanComment: z.boolean().optional(), }), diff --git a/packages/server/src/errors.ts b/packages/server/src/errors.ts index e5d15e5..d65a311 100644 --- a/packages/server/src/errors.ts +++ b/packages/server/src/errors.ts @@ -4,6 +4,8 @@ export class ServiceError extends Error { readonly status: 400 | 401 | 403 | 404 | 409 | 410 | 429 | 502 | 503, readonly code: string, message: string, + /** Extra fields for the error body, e.g. the current text in a doc conflict. */ + readonly data?: Record, ) { super(message); this.name = "ServiceError"; @@ -14,5 +16,5 @@ export const notFound = (what = "Not found") => new ServiceError(404, "not_found export const forbidden = (code = "forbidden", message = "You do not have access to do that.") => new ServiceError(403, code, message); export const badRequest = (message: string) => new ServiceError(400, "invalid", message); -export const conflict = (code: string, message: string) => new ServiceError(409, code, message); +export const conflict = (code: string, message: string, data?: Record) => new ServiceError(409, code, message, data); export const unavailable = (code: string, message: string) => new ServiceError(503, code, message); diff --git a/packages/server/src/github/cache.ts b/packages/server/src/github/cache.ts index 00c6efc..292f13b 100644 --- a/packages/server/src/github/cache.ts +++ b/packages/server/src/github/cache.ts @@ -5,7 +5,19 @@ * - "fresh": data just fetched from GitHub also applies on an equal timestamp. * - Tombstoned (deleted) rows never come back. */ -import { type Db, type ProjectFieldValue, ghIssueLinks, ghIssues, ghProjectFields, ghProjectItems, ghProjects, ghRepos } from "@gitwork/db"; +import { + type Db, + type ProjectFieldValue, + ghDocBlobs, + ghDocFiles, + ghDocRoots, + ghIssueLinks, + ghIssues, + ghProjectFields, + ghProjectItems, + ghProjects, + ghRepos, +} from "@gitwork/db"; import { type SQL, and, eq, getTableColumns, lt, sql } from "drizzle-orm"; import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core"; import type { IssueLinksNode } from "./queries"; @@ -320,3 +332,42 @@ export function itemIssueLinks(db: Db, node: ProjectItemNode, now: Date) { if (node.type !== "ISSUE" || !content?.id || content.parent === undefined) return []; return [upsertIssueLinks(db, { id: content.id, parent: content.parent, blockedBy: content.blockedBy }, now)]; } + +// ---- Docs (decision 035) ---------------------------------------------------------------------- + +export type DocRootRow = typeof ghDocRoots.$inferInsert; + +/** A docs folder's head and tree. Last write wins: the next sync repairs a stale one. */ +export function upsertDocRoot(db: Db, row: DocRootRow) { + return db + .insert(ghDocRoots) + .values(row) + .onConflictDoUpdate({ target: ghDocRoots.id, set: { headOid: row.headOid, treeOid: row.treeOid, truncated: row.truncated, syncedAt: row.syncedAt } }); +} + +/** The head moved but the folder did not change. */ +export function touchDocRoot(db: Db, rootId: string, headOid: string | null, at: Date) { + return db.update(ghDocRoots).set({ headOid, syncedAt: at }).where(eq(ghDocRoots.id, rootId)); +} + +/** At most 20 rows: D1 binds at most 100 parameters per statement. */ +export function upsertDocFiles(db: Db, rootId: string, files: { path: string; blobSha: string; size: number }[]) { + return db + .insert(ghDocFiles) + .values(files.map((f) => ({ rootId, ...f }))) + .onConflictDoUpdate({ target: [ghDocFiles.rootId, ghDocFiles.path], set: excludedSet(ghDocFiles, ["rootId", "path"]) }); +} + +export function deleteDocFiles(db: Db, rootId: string, paths: string[]) { + return db.delete(ghDocFiles).where(and(eq(ghDocFiles.rootId, rootId), inJsonList(ghDocFiles.path, paths))); +} + +/** Text by blob sha never changes: an existing row is kept. */ +export function putDocBlob(db: Db, row: typeof ghDocBlobs.$inferInsert) { + return db.insert(ghDocBlobs).values(row).onConflictDoNothing(); +} + +/** Text rows no cached file points at any more. */ +export function pruneDocBlobs(db: Db) { + return db.delete(ghDocBlobs).where(sql`${ghDocBlobs.sha} NOT IN (SELECT ${ghDocFiles.blobSha} FROM ${ghDocFiles})`); +} diff --git a/packages/server/src/github/docs.ts b/packages/server/src/github/docs.ts new file mode 100644 index 0000000..d89ab78 --- /dev/null +++ b/packages/server/src/github/docs.ts @@ -0,0 +1,191 @@ +/** + * Docs on GitHub (decisions 011, 035, 036): read a docs folder's tree, read file bytes, and commit. + * + * - The tree: one GraphQL call gives the branch head and the folder's tree oid; when the oid + * changed, one REST call lists the folder recursively. The cache keeps paths and blob shas. + * - Text is cached by blob sha (content-addressed, so it never goes stale). + * - Every commit is `createCommitOnBranch`: GitHub signs it, it takes several files at once, and + * `expectedHeadOid` refuses to commit on top of a head we did not see. + */ +import { bytesToText, decodeBase64, MAX_EDITABLE_BYTES, normalizeDocPath } from "@gitwork/core"; +import { type Db, ghDocBlobs, ghDocFiles, ghDocRoots } from "@gitwork/db"; +import { eq } from "drizzle-orm"; +import { deleteDocFiles, putDocBlob, touchDocRoot, upsertDocFiles, upsertDocRoot } from "./cache"; +import type { GitHubAuth, GitHubClient } from "./client"; + +/** A docs folder with more files than this is listed in part (`truncated`). */ +export const MAX_DOC_FILES = 2000; +/** Files above this are not proxied; the tree links to GitHub instead. */ +export const MAX_RAW_BYTES = 25_000_000; + +export interface DocRootRef { + id: string; + repoNodeId: string; + /** "owner/name" */ + fullName: string; + branch: string; + path: string; + installationId: number; +} + +export function docRootId(repoNodeId: string, branch: string, path: string): string { + return `${repoNodeId}:${branch}:${path}`; +} + +type Write = Parameters[0][number]; + +const DOC_HEAD = ` + query DocHead($owner: String!, $name: String!, $ref: String!, $expr: String!) { + repository(owner: $owner, name: $name) { + ref(qualifiedName: $ref) { target { oid } } + object(expression: $expr) { __typename oid } + } + } +`; + +export interface DocHead { + /** The branch head commit, or null when the branch does not exist. */ + headOid: string | null; + /** The object at the path: a tree for a folder, a blob for a file, or null. */ + object: { type: "Tree" | "Blob" | string; oid: string } | null; +} + +/** The branch head and the object at `path` on it, in one call. */ +export async function readHead(client: GitHubClient, auth: GitHubAuth, fullName: string, branch: string, path: string): Promise { + const [owner, name] = fullName.split("/") as [string, string]; + const data = await client.graphql<{ + repository: { ref: { target: { oid: string } } | null; object: { __typename: string; oid: string } | null } | null; + }>(auth, DOC_HEAD, { owner, name, ref: `refs/heads/${branch}`, expr: `${branch}:${path}` }, { allowNotFound: true }); + const repo = data.repository; + return { + headOid: repo?.ref?.target.oid ?? null, + object: repo?.object ? { type: repo.object.__typename, oid: repo.object.oid } : null, + }; +} + +interface TreeJson { + sha: string; + truncated: boolean; + tree: { path: string; type: string; sha: string; size?: number }[]; +} + +/** + * The writes that bring one docs folder's cache up to date with GitHub, or [] when nothing + * changed. The root row comes last, so a batch cut short is retried on the next run. + */ +export async function planDocRootSync(db: Db, client: GitHubClient, root: DocRootRef, now: Date): Promise { + const auth = { installationId: root.installationId }; + const head = await readHead(client, auth, root.fullName, root.branch, root.path); + const treeOid = head.object?.type === "Tree" ? head.object.oid : null; + const [stored] = await db.select().from(ghDocRoots).where(eq(ghDocRoots.id, root.id)); + const rootRow = { id: root.id, repoNodeId: root.repoNodeId, branch: root.branch, path: root.path, headOid: head.headOid, treeOid, syncedAt: now }; + if (stored?.syncedAt && stored.treeOid === treeOid && !stored.truncated) { + return [touchDocRoot(db, root.id, head.headOid, now)]; + } + + let files: { path: string; blobSha: string; size: number }[] = []; + let truncated = false; + if (treeOid) { + const tree = await client.rest("GET", `/repos/${root.fullName}/git/trees/${treeOid}?recursive=1`, auth); + for (const entry of tree.tree) { + if (entry.type !== "blob") continue; + const path = normalizeDocPath(`${root.path}/${entry.path}`); + if (!path) continue; // a name we would refuse to write is not shown either + files.push({ path, blobSha: entry.sha, size: entry.size ?? 0 }); + } + truncated = tree.truncated || files.length > MAX_DOC_FILES; + files = files.slice(0, MAX_DOC_FILES); + } + + const existing = await db.select({ path: ghDocFiles.path, blobSha: ghDocFiles.blobSha }).from(ghDocFiles).where(eq(ghDocFiles.rootId, root.id)); + const before = new Map(existing.map((f) => [f.path, f.blobSha])); + const keep = new Set(files.map((f) => f.path)); + const removed = existing.filter((f) => !keep.has(f.path)).map((f) => f.path); + const changed = files.filter((f) => before.get(f.path) !== f.blobSha); + + const writes: Write[] = []; + if (removed.length > 0) writes.push(deleteDocFiles(db, root.id, removed)); + for (let i = 0; i < changed.length; i += 20) writes.push(upsertDocFiles(db, root.id, changed.slice(i, i + 20))); + writes.push(upsertDocRoot(db, { ...rootRow, truncated })); + return writes; +} + +interface BlobJson { + content: string; + encoding: string; + size: number; +} + +/** A file's bytes by blob sha. */ +export async function readBlobBytes(client: GitHubClient, auth: GitHubAuth, fullName: string, sha: string): Promise { + const blob = await client.rest("GET", `/repos/${fullName}/git/blobs/${sha}`, auth); + if (blob.encoding !== "base64") throw new Error(`unexpected blob encoding ${blob.encoding}`); + return decodeBase64(blob.content); +} + +export interface DocText { + /** Null when the file is not valid UTF-8 or is too large to edit. */ + text: string | null; + size: number; +} + +/** A doc's text, from the cache or GitHub. Cached only when it can be edited. */ +export async function readDocText(db: Db, client: GitHubClient, auth: GitHubAuth, fullName: string, sha: string, now: Date): Promise { + const [cached] = await db.select().from(ghDocBlobs).where(eq(ghDocBlobs.sha, sha)); + if (cached) return { text: cached.text, size: cached.size }; + const bytes = await readBlobBytes(client, auth, fullName, sha); + const text = bytes.length <= MAX_EDITABLE_BYTES ? bytesToText(bytes) : null; + if (text !== null) await putDocBlob(db, { sha, text, size: bytes.length, fetchedAt: now }); + return { text, size: bytes.length }; +} + +/** The git blob id of some bytes: sha1("blob \0" + bytes). Lets a save skip a no-op commit. */ +export async function gitBlobSha(bytes: Uint8Array): Promise { + const header = new TextEncoder().encode(`blob ${bytes.length}\0`); + const all = new Uint8Array(header.length + bytes.length); + all.set(header); + all.set(bytes, header.length); + const digest = await crypto.subtle.digest("SHA-1", all); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +const COMMIT_FILES = ` + mutation CommitFiles($input: CreateCommitOnBranchInput!) { + createCommitOnBranch(input: $input) { commit { oid url } } + } +`; + +export interface FileChanges { + additions: { path: string; contents: string /* base64 */ }[]; + deletions: { path: string }[]; +} + +/** One signed commit with several file changes, only on top of `expectedHeadOid`. */ +export async function commitFiles( + client: GitHubClient, + auth: GitHubAuth, + input: { fullName: string; branch: string; expectedHeadOid: string; headline: string; body?: string; changes: FileChanges }, +): Promise<{ oid: string; url: string }> { + const out = await client.graphql<{ createCommitOnBranch: { commit: { oid: string; url: string } } }>(auth, COMMIT_FILES, { + input: { + branch: { repositoryNameWithOwner: input.fullName, branchName: input.branch }, + message: { headline: input.headline, ...(input.body ? { body: input.body } : {}) }, + fileChanges: input.changes, + expectedHeadOid: input.expectedHeadOid, + }, + }); + return out.createCommitOnBranch.commit; +} + +/** A new branch at `sha`. */ +export async function createBranch(client: GitHubClient, auth: GitHubAuth, fullName: string, branch: string, sha: string) { + await client.rest("POST", `/repos/${fullName}/git/refs`, auth, { ref: `refs/heads/${branch}`, sha }); +} + +export async function openPullRequest( + client: GitHubClient, + auth: GitHubAuth, + input: { fullName: string; head: string; base: string; title: string; body: string }, +): Promise<{ number: number; html_url: string }> { + return client.rest("POST", `/repos/${input.fullName}/pulls`, auth, { title: input.title, head: input.head, base: input.base, body: input.body }); +} diff --git a/packages/server/src/github/reconcile.ts b/packages/server/src/github/reconcile.ts index 1d4a994..85fcd9d 100644 --- a/packages/server/src/github/reconcile.ts +++ b/packages/server/src/github/reconcile.ts @@ -12,6 +12,7 @@ */ import { type Db, ghRepos, ghSyncTargets } from "@gitwork/db"; import { acquireLease, releaseLease } from "../leases"; +import { allDocRoots, pruneDocCache, syncDocRoots } from "../services/docs"; import { and, asc, eq, sql } from "drizzle-orm"; import { type IssueJson, @@ -95,8 +96,12 @@ export async function reconcile(options: ReconcileOptions): Promise r.branch === branch); + const writes: Write[] = []; + for (const root of roots) writes.push(...(await planDocRootSync(db, deps.client, root, now))); + return writes; + } + + case "pull_request": { + // A closed doc pull request (merged or not) ends "pending review". A merge also pushes. + if (p.action !== "closed" || !p.repository?.node_id) return []; + return [ + db + .delete(docPendingPrs) + .where(and(eq(docPendingPrs.repoNodeId, p.repository.node_id), eq(docPendingPrs.prNumber, p.pull_request.number as number))), + ]; + } + default: - // ping, push (Phase 4), label (reconcile refreshes), … + // ping, label (reconcile refreshes), … return []; } } diff --git a/packages/server/src/services/access.ts b/packages/server/src/services/access.ts index 15c5b3d..472ee47 100644 --- a/packages/server/src/services/access.ts +++ b/packages/server/src/services/access.ts @@ -12,7 +12,14 @@ import { forbidden, notFound } from "../errors"; export interface WorkspaceAccess { userId: string; - workspace: { id: string; accountId: string; name: string; hideLabel: string | null }; + workspace: { + id: string; + accountId: string; + name: string; + hideLabel: string | null; + hideFolder: string | null; + reviewBotDocEdits: boolean; + }; role: Role; isAccountOwner: boolean; actor: Actor; @@ -49,7 +56,14 @@ export async function getWorkspaceAccess(db: Db, userId: string, workspaceId: st if (!role) return null; return { userId, - workspace: { id: workspace.id, accountId: workspace.accountId, name: workspace.name, hideLabel: workspace.hideLabel }, + workspace: { + id: workspace.id, + accountId: workspace.accountId, + name: workspace.name, + hideLabel: workspace.hideLabel, + hideFolder: workspace.hideFolder, + reviewBotDocEdits: workspace.reviewBotDocEdits, + }, role, isAccountOwner: owner !== undefined, actor: { role, hasGitHub }, diff --git a/packages/server/src/services/docs.ts b/packages/server/src/services/docs.ts new file mode 100644 index 0000000..8de6ed6 --- /dev/null +++ b/packages/server/src/services/docs.ts @@ -0,0 +1,758 @@ +/** + * Docs (decisions 008, 011, 012, 035, 036). Reads come from the cache and pass every path through + * `isDocVisible` in packages/core. Writes are one signed commit each: the user's own token first, + * the App on "access denied". A save checks the file's blob sha first: a changed file is a conflict. + * A commit GitHub refuses on an unchanged file is branch protection: the save becomes a pull request. + */ +import { + type DocVisibilityContext, + MAX_EDITABLE_BYTES, + docVisibilityContext, + encodeBase64, + imageType, + isDocVisible, + isMarkdownPath, + normalizeDocPath, + normalizeRoot, + relativeToRoot, + textToBytes, +} from "@gitwork/core"; +import { type Db, docPendingPrs, docPresence, ghDocFiles, ghDocRoots, ghRepos, users, workspaceGithub, workspaceRepos } from "@gitwork/db"; +import { and, eq, gt, sql } from "drizzle-orm"; +import { randomToken } from "../crypto"; +import { ServiceError, badRequest, conflict, notFound } from "../errors"; +import { putDocBlob, pruneDocBlobs } from "../github/cache"; +import { type GitHubAuth, GitHubError, GitHubRateLimitError, isAccessDenied } from "../github/client"; +import { + type DocRootRef, + type FileChanges, + MAX_RAW_BYTES, + commitFiles, + createBranch, + docRootId, + gitBlobSha, + openPullRequest, + planDocRootSync, + readBlobBytes, + readDocText, + readHead, +} from "../github/docs"; +import { userGitHubToken } from "../github/user-token"; +import { auditInsert } from "./audit"; +import { type WorkspaceAccess, requireCapability } from "./access"; +import type { GitHubServiceDeps } from "./link"; + +type Write = Parameters[0][number]; +type Via = "user" | "app"; + +/** Decision 011: images up to 10 MB, committed with the doc. */ +export const MAX_IMAGE_BYTES = 10_000_000; +export const MAX_ATTACHMENTS = 5; +const PRESENCE_TTL_MS = 45_000; + +// ---- Repos and roots -------------------------------------------------------------------------- + +export interface DocRepo extends DocRootRef { + /** False when the App can no longer reach the repo. */ + available: boolean; + archived: boolean; + /** Whether the branch is the repo's default (the setting is empty). */ + defaultBranch: boolean; +} + +/** The workspace's repos with their docs folder and branch. Cache only. */ +export async function workspaceDocRepos(db: Db, workspaceId: string): Promise { + const rows = await db + .select({ + repoNodeId: workspaceRepos.repoNodeId, + docsPath: workspaceRepos.docsPath, + docsBranch: workspaceRepos.docsBranch, + fullName: ghRepos.fullName, + repoDefault: ghRepos.defaultBranch, + available: ghRepos.available, + archived: ghRepos.archived, + installationId: ghRepos.installationId, + }) + .from(workspaceRepos) + .innerJoin(ghRepos, eq(ghRepos.nodeId, workspaceRepos.repoNodeId)) + .innerJoin(workspaceGithub, eq(workspaceGithub.workspaceId, workspaceRepos.workspaceId)) + .where(eq(workspaceRepos.workspaceId, workspaceId)); + return rows.map((r) => { + const branch = r.docsBranch ?? r.repoDefault ?? "main"; + const path = normalizeRoot(r.docsPath) ?? "docs"; + return { + id: docRootId(r.repoNodeId, branch, path), + repoNodeId: r.repoNodeId, + fullName: r.fullName, + branch, + path, + installationId: r.installationId, + available: r.available, + archived: r.archived, + defaultBranch: r.docsBranch === null, + }; + }); +} + +/** Every docs folder any workspace uses: what reconcile keeps current. */ +export async function allDocRoots(db: Db, repoNodeId?: string): Promise { + const rows = await db + .selectDistinct({ + repoNodeId: workspaceRepos.repoNodeId, + docsPath: workspaceRepos.docsPath, + docsBranch: workspaceRepos.docsBranch, + fullName: ghRepos.fullName, + repoDefault: ghRepos.defaultBranch, + installationId: ghRepos.installationId, + }) + .from(workspaceRepos) + .innerJoin(ghRepos, eq(ghRepos.nodeId, workspaceRepos.repoNodeId)) + .innerJoin(workspaceGithub, eq(workspaceGithub.workspaceId, workspaceRepos.workspaceId)) + .where(and(eq(ghRepos.available, true), repoNodeId ? eq(workspaceRepos.repoNodeId, repoNodeId) : undefined)); + const seen = new Map(); + for (const r of rows) { + const branch = r.docsBranch ?? r.repoDefault ?? "main"; + const path = normalizeRoot(r.docsPath) ?? "docs"; + const id = docRootId(r.repoNodeId, branch, path); + seen.set(id, { id, repoNodeId: r.repoNodeId, fullName: r.fullName, branch, path, installationId: r.installationId }); + } + return [...seen.values()]; +} + +async function batch(db: Db, writes: Write[]) { + for (let i = 0; i < writes.length; i += 100) { + const chunk = writes.slice(i, i + 100); + if (chunk.length) await db.batch(chunk as unknown as Parameters[0]); + } +} + +/** Syncs these docs folders now (bounded), then drops cache rows nothing uses. */ +export async function syncDocRoots(deps: Pick, roots: DocRootRef[], now = new Date()) { + const synced: string[] = []; + const failed: { root: string; error: string }[] = []; + for (const root of roots.slice(0, 20)) { + try { + await batch(deps.db, await planDocRootSync(deps.db, deps.client, root, now)); + synced.push(root.id); + } catch (error) { + if (error instanceof GitHubRateLimitError) throw error; + failed.push({ root: root.id, error: (error as Error).message }); + } + } + return { synced, failed }; +} + +/** Roots no workspace uses any more, their files, and text no file points at. */ +export async function pruneDocCache(db: Db) { + const used = new Set((await allDocRoots(db)).map((r) => r.id)); + const stored = await db.select({ id: ghDocRoots.id }).from(ghDocRoots); + const stale = stored.map((r) => r.id).filter((id) => !used.has(id)); + const writes: Write[] = []; + for (const id of stale) writes.push(db.delete(ghDocFiles).where(eq(ghDocFiles.rootId, id)), db.delete(ghDocRoots).where(eq(ghDocRoots.id, id))); + writes.push(pruneDocBlobs(db)); + await batch(db, writes); +} + +// ---- Reads ------------------------------------------------------------------------------------ + +export type FileKind = "doc" | "image" | "file"; + +export interface DocFileView { + path: string; + size: number; + kind: FileKind; + /** An open pull request holds edits to this doc. */ + pending: { number: number; url: string } | null; +} + +export interface DocRepoView { + repoNodeId: string; + fullName: string; + root: string; + branch: string; + /** "ok", "unsynced" (not read from GitHub yet), "missing" (no such folder), "unavailable". */ + status: "ok" | "unsynced" | "missing" | "unavailable"; + truncated: boolean; + files: DocFileView[]; +} + +export function fileKind(path: string): FileKind { + return isMarkdownPath(path) ? "doc" : imageType(path) ? "image" : "file"; +} + +function viewContext(access: WorkspaceAccess): DocVisibilityContext { + return docVisibilityContext(access.actor, access.settings, access.workspace.hideFolder); +} + +/** Every visible file in every linked repo's docs folder. Cache only. */ +export async function listDocs(db: Db, access: WorkspaceAccess): Promise<{ linked: boolean; repos: DocRepoView[] }> { + requireCapability(access, "workspace.view"); + const repos = await workspaceDocRepos(db, access.workspace.id); + const [link] = await db.select({ id: workspaceGithub.workspaceId }).from(workspaceGithub).where(eq(workspaceGithub.workspaceId, access.workspace.id)); + if (!link) return { linked: false, repos: [] }; + const ctx = viewContext(access); + const out: DocRepoView[] = []; + for (const repo of repos) { + const base = { repoNodeId: repo.repoNodeId, fullName: repo.fullName, root: repo.path, branch: repo.branch, truncated: false, files: [] }; + if (!repo.available) { + out.push({ ...base, status: "unavailable" }); + continue; + } + const [root] = await db.select().from(ghDocRoots).where(eq(ghDocRoots.id, repo.id)); + if (!root?.syncedAt) { + out.push({ ...base, status: "unsynced" }); + continue; + } + if (!root.treeOid) { + out.push({ ...base, status: "missing" }); + continue; + } + const [files, pending] = await Promise.all([ + db.select().from(ghDocFiles).where(eq(ghDocFiles.rootId, repo.id)), + db.select().from(docPendingPrs).where(and(eq(docPendingPrs.repoNodeId, repo.repoNodeId), eq(docPendingPrs.baseBranch, repo.branch))), + ]); + const pendingOf = new Map(pending.map((p) => [p.path, { number: p.prNumber, url: p.prUrl }])); + out.push({ + ...base, + status: "ok", + // Read Only must not learn that hidden files exist, so a truncated listing says nothing more. + truncated: root.truncated, + files: files + .filter((f) => isDocVisible(f.path, repo.path, ctx)) + .map((f) => ({ path: f.path, size: f.size, kind: fileKind(f.path), pending: pendingOf.get(f.path) ?? null })) + .concat( + // A new doc whose first save became a pull request exists only on the PR branch. + pending + .filter((p) => !files.some((f) => f.path === p.path) && isDocVisible(p.path, repo.path, ctx)) + .map((p) => ({ path: p.path, size: 0, kind: "doc" as const, pending: { number: p.prNumber, url: p.prUrl } })), + ) + .sort((a, b) => a.path.localeCompare(b.path)), + }); + } + return { linked: true, repos: out }; +} + +/** The repo and a checked path, or 404 for anything this viewer may not see. */ +async function resolveFile(db: Db, access: WorkspaceAccess, repoNodeId: string, rawPath: string) { + requireCapability(access, "workspace.view"); + const repo = (await workspaceDocRepos(db, access.workspace.id)).find((r) => r.repoNodeId === repoNodeId); + const path = normalizeDocPath(rawPath); + if (!repo || !repo.available || !path || !isDocVisible(path, repo.path, viewContext(access))) throw notFound("Doc not found."); + return { repo, path }; +} + +async function pendingFor(db: Db, repo: DocRepo, path: string) { + const [row] = await db + .select() + .from(docPendingPrs) + .where(and(eq(docPendingPrs.repoNodeId, repo.repoNodeId), eq(docPendingPrs.baseBranch, repo.branch), eq(docPendingPrs.path, path))); + return row ?? null; +} + +export interface Editor { + userId: string; + name: string; +} + +async function editorsOf(db: Db, access: WorkspaceAccess, repoNodeId: string, path: string, now: Date): Promise { + const rows = await db + .select({ userId: docPresence.userId, name: users.name, email: users.email }) + .from(docPresence) + .innerJoin(users, eq(users.id, docPresence.userId)) + .where( + and( + eq(docPresence.workspaceId, access.workspace.id), + eq(docPresence.repoNodeId, repoNodeId), + eq(docPresence.path, path), + gt(docPresence.expiresAt, now), + ), + ); + return rows.filter((r) => r.userId !== access.userId).map((r) => ({ userId: r.userId, name: r.name?.trim() || r.email })); +} + +export interface DocView { + repoNodeId: string; + fullName: string; + path: string; + /** Relative to the docs folder, for display. */ + name: string; + branch: string; + /** The blob sha the text came from: send it back with a save. */ + sha: string; + /** Null when the file is not valid UTF-8 or is over the editable size. */ + text: string | null; + size: number; + editable: boolean; + canDelete: boolean; + /** Saves go to this pull request's branch until it closes. */ + pending: { number: number; url: string; branch: string } | null; + editors: Editor[]; +} + +/** One doc's text. May call GitHub for text not cached yet: API routes only, never a page render. */ +export async function getDoc(deps: GitHubServiceDeps, access: WorkspaceAccess, repoNodeId: string, rawPath: string, now = new Date()): Promise { + const { db } = deps; + const { repo, path } = await resolveFile(db, access, repoNodeId, rawPath); + if (!isMarkdownPath(path)) throw notFound("Doc not found."); + let pending = await pendingFor(db, repo, path); + const auth = { installationId: repo.installationId }; + let sha: string | null = null; + if (pending) { + const head = await readHead(deps.client, auth, repo.fullName, pending.headBranch, path); + if (head.object?.type === "Blob") sha = head.object.oid; + if (!head.headOid) { + // The branch is gone (merged or closed, webhook missed): the doc is no longer pending. + await db.delete(docPendingPrs).where(and(eq(docPendingPrs.repoNodeId, repo.repoNodeId), eq(docPendingPrs.prNumber, pending.prNumber))); + pending = null; + } + } + if (!sha) { + const [file] = await db.select().from(ghDocFiles).where(and(eq(ghDocFiles.rootId, repo.id), eq(ghDocFiles.path, path))); + if (!file) throw notFound("Doc not found."); + sha = file.blobSha; + } + const { text, size } = await readDocText(db, deps.client, auth, repo.fullName, sha, now); + const canWrite = can(access, "docs.write"); + return { + repoNodeId: repo.repoNodeId, + fullName: repo.fullName, + path, + name: relativeToRoot(path, repo.path), + branch: pending?.headBranch ?? repo.branch, + sha, + text, + size, + editable: canWrite && text !== null && size <= MAX_EDITABLE_BYTES && !repo.archived, + canDelete: can(access, "docs.delete") && !repo.archived && !pending, + pending: pending ? { number: pending.prNumber, url: pending.prUrl, branch: pending.headBranch } : null, + editors: await editorsOf(db, access, repo.repoNodeId, path, now), + }; +} + +function can(access: WorkspaceAccess, capability: Parameters[1]): boolean { + try { + requireCapability(access, capability); + return true; + } catch { + return false; + } +} + +/** An image or other file in a docs folder, served after the same checks as a doc (decision 012). */ +export async function rawDocFile(deps: GitHubServiceDeps, access: WorkspaceAccess, repoNodeId: string, rawPath: string): Promise { + const { db } = deps; + const { repo, path } = await resolveFile(db, access, repoNodeId, rawPath); + const [file] = await db.select().from(ghDocFiles).where(and(eq(ghDocFiles.rootId, repo.id), eq(ghDocFiles.path, path))); + if (!file) throw notFound("File not found."); + if (file.size > MAX_RAW_BYTES) throw new ServiceError(409, "too_large", "This file is too large to open here. Open it on GitHub."); + const bytes = await readBlobBytes(deps.client, { installationId: repo.installationId }, repo.fullName, file.blobSha); + const type = imageType(path); + const name = path.split("/").pop()!.replace(/["\\\r\n]/g, "_"); + return new Response(bytes as BodyInit, { + headers: { + "content-type": type ?? "application/octet-stream", + // Inline only for images; SVG runs no script under this policy, even when opened directly. + "content-disposition": `${type ? "inline" : "attachment"}; filename="${name}"`, + "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", + "x-content-type-options": "nosniff", + "cache-control": "private, max-age=300", + etag: `"${file.blobSha}"`, + }, + }); +} + +// ---- Presence --------------------------------------------------------------------------------- + +/** "I have this doc open." Returns the other people who do. */ +export async function heartbeat(db: Db, access: WorkspaceAccess, repoNodeId: string, rawPath: string, now = new Date()): Promise { + const { repo, path } = await resolveFile(db, access, repoNodeId, rawPath); + requireCapability(access, "docs.write"); + const expiresAt = new Date(now.getTime() + PRESENCE_TTL_MS); + await db.batch([ + db + .insert(docPresence) + .values({ workspaceId: access.workspace.id, repoNodeId: repo.repoNodeId, path, userId: access.userId, expiresAt }) + .onConflictDoUpdate({ target: [docPresence.workspaceId, docPresence.repoNodeId, docPresence.path, docPresence.userId], set: { expiresAt } }), + // Old rows from anyone: presence is short-lived, nothing else reads them. + db.delete(docPresence).where(sql`${docPresence.expiresAt} < ${now.getTime() - PRESENCE_TTL_MS}`), + ]); + return editorsOf(db, access, repo.repoNodeId, path, now); +} + +export async function leave(db: Db, access: WorkspaceAccess, repoNodeId: string, rawPath: string) { + const { repo, path } = await resolveFile(db, access, repoNodeId, rawPath); + await db + .delete(docPresence) + .where( + and( + eq(docPresence.workspaceId, access.workspace.id), + eq(docPresence.repoNodeId, repo.repoNodeId), + eq(docPresence.path, path), + eq(docPresence.userId, access.userId), + ), + ); +} + +// ---- Writes ----------------------------------------------------------------------------------- + +export interface DocWriteDeps extends GitHubServiceDeps { + /** For the Co-authored-by trailer on App commits (decision 008). */ + author: { name: string; email: string }; +} + +export type WriteResult = + | { status: "committed"; commitSha: string; sha: string | null } + | { status: "pending_review"; pr: { number: number; url: string; branch: string }; sha: string | null } + | { status: "unchanged"; sha: string }; + +interface WritePlan { + action: "doc.save" | "doc.create" | "doc.rename" | "doc.delete"; + repo: DocRepo; + /** The doc the write is about (the new path for a rename). */ + path: string; + headline: string; + /** Files whose current blob sha must match before committing. null = must not exist. */ + expect: { path: string; sha: string | null }[]; + changes: FileChanges; + /** Blob shas of the new text, for the cache. */ + newText?: { sha: string; text: string; size: number }; + detail?: Record; +} + +async function writeContext(deps: DocWriteDeps, access: WorkspaceAccess, repoNodeId: string, rawPath: string, capability: "docs.write" | "docs.delete" = "docs.write") { + requireCapability(access, capability); + const { repo, path } = await resolveFile(deps.db, access, repoNodeId, rawPath); + if (repo.archived) throw conflict("repo_archived", "This repo is archived on GitHub."); + return { repo, path }; +} + +/** Throws a 409 with the file's current text when it is not what the client last saw. */ +async function checkExpectations(deps: DocWriteDeps, repo: DocRepo, branch: string, expect: WritePlan["expect"], auth: GitHubAuth, now: Date) { + let headOid: string | null = null; + for (const e of expect) { + const head = await readHead(deps.client, auth, repo.fullName, branch, e.path); + if (!head.headOid) throw conflict("branch_missing", `The branch "${branch}" does not exist on GitHub.`); + headOid ??= head.headOid; + const current = head.object?.type === "Blob" ? head.object.oid : null; + if (current === e.sha) continue; + if (e.sha === null) throw conflict("doc_exists", "A file with that name already exists."); + if (current === null) throw conflict("doc_gone", "Someone deleted or moved this doc on GitHub."); + const { text } = await readDocText(deps.db, deps.client, auth, repo.fullName, current, now); + throw conflict("doc_conflict", "Someone changed this doc on GitHub since you opened it.", { current: { sha: current, text } }); + } + return headOid!; +} + +function commitBody(deps: DocWriteDeps, via: Via): string | undefined { + // App commits name the person; GitHub keeps them verified (decision 008). + return via === "app" ? `Edited in Gitwork.\n\nCo-authored-by: ${deps.author.name} <${deps.author.email}>` : undefined; +} + +/** The user's token, then the App on "access denied" (decision 021). */ +async function asActor(token: string | null, installationId: number, call: (auth: GitHubAuth, via: Via) => Promise, appOnly = false) { + if (token && !appOnly) { + try { + return { result: await call({ userToken: token }, "user"), via: "user" as Via }; + } catch (error) { + if (!isAccessDenied(error)) throw error; + } + } + return { result: await call({ installationId }, "app"), via: "app" as Via }; +} + +/** GitHub refused the commit itself (not a rate limit or an outage). */ +function isRefusal(error: unknown): boolean { + if (!(error instanceof GitHubError) || error instanceof GitHubRateLimitError) return false; + return error.status < 500; +} + +function prBranchName(path: string): string { + const slug = (path.split("/").pop() ?? "doc").replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40); + return `gitwork/docs-${slug || "doc"}-${randomToken(4).toLowerCase().replace(/[^a-z0-9]/g, "x")}`; +} + +async function execute(deps: DocWriteDeps, access: WorkspaceAccess, plan: WritePlan, now: () => Date): Promise { + const { db } = deps; + const { repo } = plan; + const readAuth = { installationId: repo.installationId }; + const pending = plan.action === "doc.save" ? await pendingFor(db, repo, plan.path) : null; + const branch = pending?.headBranch ?? repo.branch; + const token = await userGitHubToken({ db, auth: deps.auth }, access.userId); + // Review mode: App writes become pull requests (decision 008). The user's own writes do not. + const reviewApp = access.workspace.reviewBotDocEdits && !token; + + const audit = async (via: Via, extra: { commitSha?: string; detail?: Record }, writes: Write[] = []) => { + const at = now(); + await batch(db, [ + ...writes, + ...(plan.newText ? [putDocBlob(db, { ...plan.newText, fetchedAt: at })] : []), + auditInsert( + db, + { + userId: access.userId, + workspaceId: access.workspace.id, + action: plan.action, + via, + repoNodeId: repo.repoNodeId, + target: plan.path, + commitSha: extra.commitSha ?? null, + detail: { ...plan.detail, ...extra.detail }, + }, + at, + ), + ]); + }; + + // Try a direct commit; a lost race with another commit retries once. + if (!reviewApp && !pending) { + let refused = false; + for (let attempt = 0; attempt < 2 && !refused; attempt++) { + const headOid = await checkExpectations(deps, repo, branch, plan.expect, readAuth, now()); + try { + const { result, via } = await asActor(token, repo.installationId, (auth, via) => + commitFiles(deps.client, auth, { fullName: repo.fullName, branch, expectedHeadOid: headOid, headline: plan.headline, body: commitBody(deps, via), changes: plan.changes }), + ); + // Refresh the tree from GitHub, so the cache holds exactly what was committed. + const writes = await planDocRootSync(db, deps.client, repo, now()); + await audit(via, { commitSha: result.oid }, writes); + return { status: "committed", commitSha: result.oid, sha: plan.newText?.sha ?? null }; + } catch (error) { + if (!isRefusal(error)) throw error; + const head = await readHead(deps.client, readAuth, repo.fullName, branch, plan.path); + if (head.headOid !== headOid) continue; // someone committed meanwhile: check again + // Same head, same files, still refused: branch protection or a ruleset. + refused = true; + } + } + if (!refused) throw conflict("doc_busy", "Others are committing to this branch right now. Try again."); + } + + // Saves to a doc that already has a pull request go to its branch. + if (pending) { + const headOid = await checkExpectations(deps, repo, branch, plan.expect, readAuth, now()); + const { result, via } = await asActor(token, repo.installationId, (auth, via) => + commitFiles(deps.client, auth, { fullName: repo.fullName, branch, expectedHeadOid: headOid, headline: plan.headline, body: commitBody(deps, via), changes: plan.changes }), + ); + await audit(via, { commitSha: result.oid, detail: { pr: pending.prNumber } }); + return { status: "pending_review", pr: { number: pending.prNumber, url: pending.prUrl, branch }, sha: plan.newText?.sha ?? null }; + } + + // A pull request from a new branch at the head we checked. + const headOid = await checkExpectations(deps, repo, repo.branch, plan.expect, readAuth, now()); + const prBranch = prBranchName(plan.path); + const reason = reviewApp + ? "This workspace requires review for edits from people without GitHub." + : `GitHub did not allow a direct commit to \`${repo.branch}\` (branch protection or a ruleset).`; + const { result, via } = await asActor( + token, + repo.installationId, + async (auth, via) => { + await createBranch(deps.client, auth, repo.fullName, prBranch, headOid); + const commit = await commitFiles(deps.client, auth, { + fullName: repo.fullName, + branch: prBranch, + expectedHeadOid: headOid, + headline: plan.headline, + body: commitBody(deps, via), + changes: plan.changes, + }); + const pr = await openPullRequest(deps.client, auth, { + fullName: repo.fullName, + head: prBranch, + base: repo.branch, + title: plan.headline, + body: `${reason}\n\nEdited by ${deps.author.name} in Gitwork.`, + }); + return { commit, pr }; + }, + reviewApp, + ); + const writes: Write[] = + plan.action === "doc.save" || plan.action === "doc.create" + ? [ + db + .insert(docPendingPrs) + .values({ repoNodeId: repo.repoNodeId, baseBranch: repo.branch, path: plan.path, headBranch: prBranch, prNumber: result.pr.number, prUrl: result.pr.html_url, createdBy: access.userId }) + .onConflictDoUpdate({ + target: [docPendingPrs.repoNodeId, docPendingPrs.baseBranch, docPendingPrs.path], + set: { headBranch: prBranch, prNumber: result.pr.number, prUrl: result.pr.html_url, createdBy: access.userId }, + }), + ] + : []; + await audit(via, { commitSha: result.commit.oid, detail: { pr: result.pr.number, reason: reviewApp ? "review_mode" : "protected" } }, writes); + return { status: "pending_review", pr: { number: result.pr.number, url: result.pr.html_url, branch: prBranch }, sha: plan.newText?.sha ?? null }; +} + +export interface Attachment { + /** Repo-relative path inside the docs folder. */ + path: string; + /** Base64 bytes. */ + data: string; +} + +async function attachmentChanges(repo: DocRepo, access: WorkspaceAccess, attachments: Attachment[] | undefined) { + const list = attachments ?? []; + if (list.length > MAX_ATTACHMENTS) throw badRequest(`Attach at most ${MAX_ATTACHMENTS} images per save.`); + const out: FileChanges["additions"] = []; + const expect: WritePlan["expect"] = []; + const ctx = docVisibilityContext(access.actor, access.settings, access.workspace.hideFolder); + for (const a of list) { + const path = normalizeDocPath(a.path); + if (!path || !imageType(path) || !isDocVisible(path, repo.path, ctx)) throw badRequest("Images must go inside the docs folder."); + // base64 length → bytes, without decoding twice. + const bytes = Math.floor((a.data.replace(/=+$/, "").length * 3) / 4); + if (bytes > MAX_IMAGE_BYTES) throw badRequest("Images can be at most 10 MB."); + out.push({ path, contents: a.data.replace(/\s+/g, "") }); + expect.push({ path, sha: null }); + } + return { additions: out, expect }; +} + +export interface SaveDocInput { + repoNodeId: string; + path: string; + /** The blob sha the client loaded (DocView.sha). */ + baseSha: string; + text: string; + attachments?: Attachment[]; + message?: string; +} + +export async function saveDoc(deps: DocWriteDeps, access: WorkspaceAccess, input: SaveDocInput, now = () => new Date()): Promise { + const { repo, path } = await writeContext(deps, access, input.repoNodeId, input.path); + if (!isMarkdownPath(path)) throw badRequest("Only markdown files can be edited."); + const bytes = textToBytes(input.text); + if (bytes.length > MAX_EDITABLE_BYTES) throw badRequest("This doc is too large to save here."); + const sha = await gitBlobSha(bytes); + const images = await attachmentChanges(repo, access, input.attachments); + if (sha === input.baseSha && images.additions.length === 0) return { status: "unchanged", sha }; + return execute( + deps, + access, + { + action: "doc.save", + repo, + path, + headline: input.message?.trim() || `Update ${relativeToRoot(path, repo.path)}`, + expect: [{ path, sha: input.baseSha }, ...images.expect], + changes: { additions: [{ path, contents: encodeBase64(bytes) }, ...images.additions], deletions: [] }, + newText: { sha, text: input.text, size: bytes.length }, + detail: images.additions.length ? { images: images.additions.map((a) => a.path) } : undefined, + }, + now, + ); +} + +export async function createDoc(deps: DocWriteDeps, access: WorkspaceAccess, input: { repoNodeId: string; path: string; text?: string }, now = () => new Date()) { + const { repo, path } = await writeContext(deps, access, input.repoNodeId, input.path); + if (!isMarkdownPath(path)) throw badRequest("Doc names end in .md."); + const text = input.text ?? `# ${relativeToRoot(path, repo.path).split("/").pop()!.replace(/\.(md|markdown)$/i, "")}\n`; + const bytes = textToBytes(text); + const sha = await gitBlobSha(bytes); + return execute( + deps, + access, + { + action: "doc.create", + repo, + path, + headline: `Add ${relativeToRoot(path, repo.path)}`, + expect: [{ path, sha: null }], + changes: { additions: [{ path, contents: encodeBase64(bytes) }], deletions: [] }, + newText: { sha, text, size: bytes.length }, + }, + now, + ); +} + +/** Rename or move: one commit, so git follows the file (decision 011). */ +export async function renameDoc( + deps: DocWriteDeps, + access: WorkspaceAccess, + input: { repoNodeId: string; path: string; baseSha: string; newPath: string }, + now = () => new Date(), +) { + const { repo, path } = await writeContext(deps, access, input.repoNodeId, input.path); + const target = normalizeDocPath(input.newPath); + const ctx = docVisibilityContext(access.actor, access.settings, access.workspace.hideFolder); + if (!target || !isMarkdownPath(target) || !isDocVisible(target, repo.path, ctx)) throw badRequest("Pick a .md name inside the docs folder."); + if (target === path) throw badRequest("That is the current name."); + if (await pendingFor(deps.db, repo, path)) throw conflict("doc_pending", "This doc has an open pull request. Rename it after the review."); + const bytes = await readBlobBytes(deps.client, { installationId: repo.installationId }, repo.fullName, input.baseSha); + return execute( + deps, + access, + { + action: "doc.rename", + repo, + path: target, + headline: `Rename ${relativeToRoot(path, repo.path)} to ${relativeToRoot(target, repo.path)}`, + expect: [ + { path, sha: input.baseSha }, + { path: target, sha: null }, + ], + changes: { additions: [{ path: target, contents: encodeBase64(bytes) }], deletions: [{ path }] }, + detail: { from: path }, + }, + now, + ); +} + +export async function deleteDoc(deps: DocWriteDeps, access: WorkspaceAccess, input: { repoNodeId: string; path: string; baseSha: string }, now = () => new Date()) { + const { repo, path } = await writeContext(deps, access, input.repoNodeId, input.path, "docs.delete"); + if (await pendingFor(deps.db, repo, path)) throw conflict("doc_pending", "This doc has an open pull request. Delete it after the review."); + return execute( + deps, + access, + { + action: "doc.delete", + repo, + path, + headline: `Delete ${relativeToRoot(path, repo.path)}`, + expect: [{ path, sha: input.baseSha }], + changes: { additions: [], deletions: [{ path }] }, + }, + now, + ); +} + +// ---- Settings --------------------------------------------------------------------------------- + +/** A repo's docs folder and branch for this workspace (decision 011). Admins only. */ +export async function setDocsConfig( + deps: Pick, + access: WorkspaceAccess, + input: { repoNodeId: string; docsPath?: string; docsBranch?: string | null }, + now = new Date(), +) { + requireCapability(access, "workspace.github_settings"); + const repo = (await workspaceDocRepos(deps.db, access.workspace.id)).find((r) => r.repoNodeId === input.repoNodeId); + if (!repo) throw notFound("Repo not found."); + const set: { docsPath?: string; docsBranch?: string | null } = {}; + if (input.docsPath !== undefined) { + const root = normalizeRoot(input.docsPath); + if (!root) throw badRequest("Enter a folder path such as docs or handbook/guides."); + set.docsPath = root; + } + if (input.docsBranch !== undefined) { + const branch = input.docsBranch?.trim() || null; + // git check-ref-format, the parts that matter here. + if (branch && (!/^[\w./-]+$/.test(branch) || /(^[./-])|\.\.|\/\/|[./]$|\.lock$|@\{/.test(branch))) throw badRequest("That is not a valid branch name."); + set.docsBranch = branch; + } + if (Object.keys(set).length === 0) return; + await deps.db.batch([ + deps.db.update(workspaceRepos).set(set).where(and(eq(workspaceRepos.workspaceId, access.workspace.id), eq(workspaceRepos.repoNodeId, input.repoNodeId))), + auditInsert(deps.db, { userId: access.userId, workspaceId: access.workspace.id, action: "workspace.docs_config", via: "local", repoNodeId: input.repoNodeId, target: access.workspace.id, detail: set }, now), + ]); + const updated = (await workspaceDocRepos(deps.db, access.workspace.id)).find((r) => r.repoNodeId === input.repoNodeId)!; + await syncDocRoots(deps, [updated], now); + await pruneDocCache(deps.db); +} + +/** Members may ask for a fresh read of the docs folders (the tree shows "not loaded yet"). */ +export async function refreshDocs(deps: Pick, access: WorkspaceAccess, now = new Date()) { + requireCapability(access, "docs.write"); + const repos = (await workspaceDocRepos(deps.db, access.workspace.id)).filter((r) => r.available); + return syncDocRoots(deps, repos, now); +} diff --git a/packages/server/src/services/workspace-settings.ts b/packages/server/src/services/workspace-settings.ts index 200d8a8..b083f47 100644 --- a/packages/server/src/services/workspace-settings.ts +++ b/packages/server/src/services/workspace-settings.ts @@ -1,4 +1,5 @@ -/** Per-workspace switches: hide label (012), Read Only drafts and comments (006, 007). */ +/** Per-workspace switches: hide label and folder (012), review mode (008), Read Only drafts and comments (006, 007). */ +import { normalizeRoot } from "@gitwork/core"; import { type Db, workspaces } from "@gitwork/db"; import { eq } from "drizzle-orm"; import { badRequest } from "../errors"; @@ -7,6 +8,8 @@ import { type WorkspaceAccess, requireCapability } from "./access"; export interface WorkspaceSettingsInput { hideLabel?: string | null; + hideFolder?: string | null; + reviewBotDocEdits?: boolean; showDraftsToReadOnly?: boolean; readOnlyCanComment?: boolean; } @@ -20,6 +23,14 @@ export async function updateWorkspaceSettings(db: Db, access: WorkspaceAccess, i if (label && label.length > 50) throw badRequest("Label names are at most 50 characters."); set.hideLabel = label; } + if (input.hideFolder !== undefined) { + const raw = input.hideFolder?.trim() ?? ""; + // Relative to each repo's docs folder (decision 012). + const folder = raw ? normalizeRoot(raw) : null; + if (raw && !folder) throw badRequest("Enter a folder inside the docs folder, such as internal."); + set.hideFolder = folder; + } + if (input.reviewBotDocEdits !== undefined) set.reviewBotDocEdits = input.reviewBotDocEdits; if (input.showDraftsToReadOnly !== undefined) set.showDraftsToReadOnly = input.showDraftsToReadOnly; if (input.readOnlyCanComment !== undefined) set.readOnlyCanComment = input.readOnlyCanComment; if (Object.keys(set).length === 0) return; diff --git a/packages/server/test/api-docs.test.ts b/packages/server/test/api-docs.test.ts new file mode 100644 index 0000000..69edb00 --- /dev/null +++ b/packages/server/test/api-docs.test.ts @@ -0,0 +1,117 @@ +import type { Database } from "@gitwork/db"; +import { type TestDriver, allTestDrivers } from "@gitwork/db/testing"; +import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import type { ApiDeps } from "../src/api/router"; +import { handleApiRequest } from "../src/api/routes"; +import { APP } from "./github-helpers"; +import { BASE_URL, signIn, testAuth } from "./helpers"; +import { IDS, setupWorkspace, tokenAuth } from "./tasks-fixture"; + +const drivers = await allTestDrivers(); +afterAll(() => Promise.all(drivers.map((d) => d.dispose()))); + +const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]); + +describe.each(drivers)("/api/v1 docs on $name", (driver: TestDriver) => { + let database: Database; + let w: Awaited>; + let deps: ApiDeps; + const cookies: Record = {}; + + function api(method: string, path: string, opts: { as?: string; body?: unknown } = {}) { + const headers = new Headers({ origin: BASE_URL }); + if (opts.as) headers.set("cookie", cookies[opts.as]!); + if (opts.body !== undefined) headers.set("content-type", "application/json"); + return handleApiRequest( + new Request(`${BASE_URL}/api/v1/workspaces/${w.ws.workspaceId}${path}`, { + method, + headers, + body: opts.body === undefined ? undefined : JSON.stringify(opts.body), + }), + deps, + ); + } + const q = (path: string, extra = "") => `?repo=${IDS.site}&path=${encodeURIComponent(path)}${extra}`; + const open = async (as: string, path: string) => ((await (await api("GET", `/docs/file${q(path)}`, { as })).json()) as { doc: { sha: string; text: string } }).doc; + + beforeEach(async () => { + database = await driver.fresh(); + w = await setupWorkspace(database); + w.fake.commit("acme/site", "main", { "docs/README.md": "# Docs\n", "docs/internal/plan.md": "# Plan\n", "docs/logo.png": new Uint8Array(PNG) }); + const auth = testAuth(database); + const api2 = { ...auth.auth.api, ...(tokenAuth as { api: object }).api }; + deps = { database, auth: { ...auth.auth, api: api2 } as never, email: auth.email, baseURL: BASE_URL, github: { app: APP, client: w.client } }; + for (const user of ["jane", "max", "rita"]) cookies[user] = await signIn(auth.auth, auth.email, `${user}@example.com`); + expect((await api("PUT", "/github", { as: "jane", body: { installationId: 99, projectNodeId: IDS.board, repoNodeIds: [IDS.site] } })).status).toBe(200); + expect((await api("PATCH", "/settings", { as: "jane", body: { hideFolder: "internal" } })).status).toBe(204); + }); + + it("returns 401 without a session", async () => { + expect((await api("GET", "/docs")).status).toBe(401); + expect((await api("GET", `/docs/file${q("docs/README.md")}`)).status).toBe(401); + expect((await api("PUT", "/docs/file", { body: {} })).status).toBe(401); + expect((await api("GET", `/docs/raw${q("docs/logo.png")}`)).status).toBe(401); + }); + + it("lists and opens docs, filtered for Read Only", async () => { + const list = (await (await api("GET", "/docs", { as: "rita" })).json()) as { repos: { files: { path: string }[] }[] }; + expect(list.repos[0]!.files.map((f) => f.path)).toEqual(["docs/logo.png", "docs/README.md"]); + expect((await open("rita", "docs/README.md")).text).toBe("# Docs\n"); + expect((await api("GET", `/docs/file${q("docs/internal/plan.md")}`, { as: "rita" })).status).toBe(404); + expect((await api("GET", `/docs/file${q("docs/internal/plan.md")}`, { as: "max" })).status).toBe(200); + const raw = await api("GET", `/docs/raw${q("docs/logo.png")}`, { as: "rita" }); + expect(raw.status).toBe(200); + expect(raw.headers.get("content-type")).toBe("image/png"); + }); + + it("saves, creates, renames, and deletes; Read Only gets 403", async () => { + const d = await open("max", "docs/README.md"); + const save = await api("PUT", "/docs/file", { as: "max", body: { repoNodeId: IDS.site, path: "docs/README.md", baseSha: d.sha, text: "# Docs\n\nMore.\n" } }); + expect(save.status).toBe(200); + expect(await save.json()).toMatchObject({ status: "committed" }); + expect((await api("PUT", "/docs/file", { as: "rita", body: { repoNodeId: IDS.site, path: "docs/README.md", baseSha: d.sha, text: "x" } })).status).toBe(403); + + expect((await api("POST", "/docs/file", { as: "max", body: { repoNodeId: IDS.site, path: "docs/new.md" } })).status).toBe(200); + expect((await api("POST", "/docs/file", { as: "rita", body: { repoNodeId: IDS.site, path: "docs/x.md" } })).status).toBe(403); + + const n = await open("max", "docs/new.md"); + expect((await api("POST", "/docs/rename", { as: "max", body: { repoNodeId: IDS.site, path: "docs/new.md", baseSha: n.sha, newPath: "docs/renamed.md" } })).status).toBe(200); + + const r = await open("max", "docs/renamed.md"); + expect((await api("DELETE", `/docs/file${q("docs/renamed.md", `&sha=${r.sha}`)}`, { as: "max" })).status).toBe(403); + expect((await api("DELETE", `/docs/file${q("docs/renamed.md", `&sha=${r.sha}`)}`, { as: "jane" })).status).toBe(200); + }); + + it("answers a conflict with 409 and the current text", async () => { + const d = await open("max", "docs/README.md"); + w.fake.commit("acme/site", "main", { "docs/README.md": "# Theirs\n" }); + const res = await api("PUT", "/docs/file", { as: "max", body: { repoNodeId: IDS.site, path: "docs/README.md", baseSha: d.sha, text: "# Mine\n" } }); + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ error: { code: "doc_conflict", current: { text: "# Theirs\n" } } }); + }); + + it("validates bodies and queries with 400", async () => { + const d = await open("max", "docs/README.md"); + expect((await api("PUT", "/docs/file", { as: "max", body: { repoNodeId: IDS.site, path: "docs/README.md", baseSha: "nope", text: "x" } })).status).toBe(400); + expect((await api("PUT", "/docs/file", { as: "max", body: { repoNodeId: IDS.site, path: "docs/README.md", baseSha: d.sha, text: "x".repeat(1_000_001) } })).status).toBe(400); + expect((await api("GET", "/docs/file?repo=", { as: "max" })).status).toBe(400); + expect((await api("DELETE", `/docs/file${q("docs/README.md", "&sha=zz")}`, { as: "jane" })).status).toBe(400); + expect((await api("PATCH", "/settings", { as: "jane", body: { hideFolder: "../up" } })).status).toBe(400); + expect((await api("PATCH", `/github/repos/${IDS.site}/docs`, { as: "jane", body: { docsPath: "" } })).status).toBe(400); + }); + + it("changes a repo's docs folder (Admins) and reports it in the GitHub summary", async () => { + expect((await api("PATCH", `/github/repos/${IDS.site}/docs`, { as: "max", body: { docsPath: "handbook" } })).status).toBe(403); + expect((await api("PATCH", `/github/repos/${IDS.site}/docs`, { as: "jane", body: { docsPath: "handbook", docsBranch: "main" } })).status).toBe(204); + const summary = await (await api("GET", "/github", { as: "max" })).json(); + expect(summary).toMatchObject({ repos: [{ fullName: "acme/site", docs: { path: "handbook", branch: "main", defaultBranch: false } }] }); + }); + + it("takes presence heartbeats from writers only", async () => { + expect((await api("POST", "/docs/presence", { as: "max", body: { repoNodeId: IDS.site, path: "docs/README.md" } })).status).toBe(200); + const res = await api("POST", "/docs/presence", { as: "jane", body: { repoNodeId: IDS.site, path: "docs/README.md" } }); + expect(await res.json()).toEqual({ editors: [{ userId: expect.any(String), name: "Max Member" }] }); + expect((await api("POST", "/docs/presence", { as: "rita", body: { repoNodeId: IDS.site, path: "docs/README.md" } })).status).toBe(403); + expect((await api("DELETE", `/docs/presence${q("docs/README.md")}`, { as: "max" })).status).toBe(204); + }); +}); diff --git a/packages/server/test/docs.test.ts b/packages/server/test/docs.test.ts new file mode 100644 index 0000000..bd052e7 --- /dev/null +++ b/packages/server/test/docs.test.ts @@ -0,0 +1,371 @@ +import { type Database, auditLog, docPendingPrs, ghDocBlobs, ghDocFiles, ghDocRoots } from "@gitwork/db"; +import { type TestDriver, allTestDrivers } from "@gitwork/db/testing"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { ServiceError } from "../src/errors"; +import { handleGitHubWebhook } from "../src/github/webhooks"; +import { reconcile } from "../src/github/reconcile"; +import { + createDoc, + deleteDoc, + getDoc, + heartbeat, + listDocs, + rawDocFile, + renameDoc, + saveDoc, + setDocsConfig, +} from "../src/services/docs"; +import { linkWorkspace } from "../src/services/link"; +import { updateWorkspaceSettings } from "../src/services/workspace-settings"; +import { blobSha } from "./fake-github"; +import { APP, webhookRequest } from "./github-helpers"; +import { IDS, setupWorkspace } from "./tasks-fixture"; + +const drivers = await allTestDrivers(); +afterAll(() => Promise.all(drivers.map((d) => d.dispose()))); + +async function rejects(promise: Promise, status: number, code?: string) { + const error = await promise.then( + () => null, + (e: unknown) => e, + ); + expect(error).toBeInstanceOf(ServiceError); + expect((error as ServiceError).status).toBe(status); + if (code) expect((error as ServiceError).code).toBe(code); + return error as ServiceError; +} + +const SITE = "acme/site"; +const CRLF = "# Setup\r\n\r\nStep one\r\nStep two\r\n"; +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]); +const SVG = ''; +const bytes = (s: string) => new TextEncoder().encode(s); + +describe.each(drivers)("docs on $name", (driver: TestDriver) => { + let database: Database; + let w: Awaited>; + const writer = (userId: string) => { + const people: Record = { + jane: { name: "Jane Admin", email: "jane@example.com" }, + max: { name: "Max Member", email: "max@example.com" }, + sam: { name: "Sam Member", email: "sam@example.com" }, + rita: { name: "Rita Reader", email: "rita@example.com" }, + }; + return { ...w.deps, author: people[userId]! }; + }; + const paths = async (userId: string) => (await listDocs(w.db, await w.access(userId))).repos.flatMap((r) => r.files.map((f) => f.path)); + const doc = async (userId: string, path: string) => getDoc(w.deps, await w.access(userId), IDS.site, path); + const webhook = (event: string, payload: unknown) => handleGitHubWebhook(webhookRequest(event, payload), { db: w.db, app: APP, client: w.client }); + + beforeEach(async () => { + database = await driver.fresh(); + w = await setupWorkspace(database); + w.fake.commit(SITE, "main", { + "README.md": "# Site\n", + "docs/README.md": "# Docs\n\nHello.\n", + "docs/guide/setup.md": CRLF, + "docs/internal/plan.md": "# Secret plan\n", + "docs/internal/chart.png": PNG, + "docs/assets/logo.png": PNG, + "docs/assets/x.svg": SVG, + "docs/bad.md": new Uint8Array([0x23, 0x20, 0xff, 0x0a]), + }); + await linkWorkspace(w.deps, await w.access("jane"), { installationId: 99, projectNodeId: IDS.board, repoNodeIds: [IDS.site] }); + await updateWorkspaceSettings(w.db, await w.access("owner"), { hideFolder: "Internal" }); + w.fake.writes = []; + }); + + describe("reads", () => { + it("syncs the docs folder when the workspace links the repo", async () => { + const [repo] = (await listDocs(w.db, await w.access("max"))).repos; + expect(repo).toMatchObject({ fullName: SITE, root: "docs", branch: "main", status: "ok" }); + expect(repo!.files.find((f) => f.path === "docs/assets/logo.png")?.kind).toBe("image"); + expect(repo!.files.find((f) => f.path === "docs/README.md")?.kind).toBe("doc"); + }); + + it("shows Members the hide folder and hides it from Read Only; never files outside the docs folder", async () => { + expect(await paths("max")).toContain("docs/internal/plan.md"); + const reader = await paths("rita"); + expect(reader.some((p) => p.includes("internal"))).toBe(false); + expect(reader).toContain("docs/README.md"); + for (const user of ["owner", "max", "rita"]) expect(await paths(user)).not.toContain("README.md"); + }); + + it("returns the exact text, CRLF and all", async () => { + const d = await doc("max", "docs/guide/setup.md"); + expect(d.text).toBe(CRLF); + expect(d.sha).toBe(blobSha(bytes(CRLF))); + expect(d).toMatchObject({ name: "guide/setup.md", editable: true, canDelete: false, pending: null }); + }); + + it("opens invalid UTF-8 read-only", async () => { + expect(await doc("max", "docs/bad.md")).toMatchObject({ text: null, editable: false }); + }); + + it("answers 404 for hidden, outside, traversal, and non-markdown paths", async () => { + await rejects(doc("rita", "docs/internal/plan.md"), 404); + await rejects(doc("rita", "docs/INTERNAL/plan.md"), 404); + await rejects(doc("max", "README.md"), 404); + await rejects(doc("max", "docs/../README.md"), 404); + await rejects(doc("max", "docs/assets/logo.png"), 404); + await rejects(getDoc(w.deps, await w.access("max"), IDS.internal, "docs/README.md"), 404); + }); + + it("shows Read Only a doc as not editable", async () => { + expect(await doc("rita", "docs/README.md")).toMatchObject({ editable: false, canDelete: false }); + }); + + it("serves images with a sandbox policy, and hides hidden files from Read Only", async () => { + const res = await rawDocFile(w.deps, await w.access("rita"), IDS.site, "docs/assets/logo.png"); + expect(res.headers.get("content-type")).toBe("image/png"); + expect(new Uint8Array(await res.arrayBuffer())).toEqual(PNG); + const svg = await rawDocFile(w.deps, await w.access("rita"), IDS.site, "docs/assets/x.svg"); + expect(svg.headers.get("content-security-policy")).toContain("sandbox"); + expect(svg.headers.get("x-content-type-options")).toBe("nosniff"); + await rejects(rawDocFile(w.deps, await w.access("rita"), IDS.site, "docs/internal/chart.png"), 404); + expect((await rawDocFile(w.deps, await w.access("max"), IDS.site, "docs/internal/chart.png")).status).toBe(200); + }); + }); + + describe("saves", () => { + it("commits as the user when their GitHub account can write, byte for byte", async () => { + const d = await doc("jane", "docs/guide/setup.md"); + const text = d.text!.replace("two", "2"); + const out = await saveDoc(writer("jane"), await w.access("jane"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text }); + expect(out.status).toBe("committed"); + expect(w.fake.fileText(SITE, "main", "docs/guide/setup.md")).toBe("# Setup\r\n\r\nStep one\r\nStep 2\r\n"); + expect(w.fake.writes).toEqual(["user:jane createCommitOnBranch main"]); + expect(w.fake.headMessage(SITE, "main")).toBe("Update guide/setup.md"); + // The cache holds the new version without waiting for a webhook. + expect((await doc("max", d.path)).text).toBe(text); + const [entry] = await w.db.select().from(auditLog).where(eq(auditLog.action, "doc.save")); + expect(entry).toMatchObject({ userId: "jane", via: "user", target: d.path, commitSha: out.status === "committed" ? out.commitSha : "" }); + }); + + it("commits through the App with a Co-authored-by trailer for people without GitHub", async () => { + const d = await doc("max", "docs/README.md"); + await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: `${d.text}More.\n` }); + expect(w.fake.writes).toEqual(["app createCommitOnBranch main"]); + expect(w.fake.headMessage(SITE, "main")).toContain("Co-authored-by: Max Member "); + }); + + it("falls back to the App when the user's own token is refused", async () => { + const d = await doc("sam", "docs/README.md"); + await saveDoc(writer("sam"), await w.access("sam"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "# Docs\n" }); + expect(w.fake.writes).toEqual(["app createCommitOnBranch main"]); + }); + + it("makes no commit when nothing changed", async () => { + const d = await doc("max", "docs/guide/setup.md"); + const out = await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: d.text! }); + expect(out).toEqual({ status: "unchanged", sha: d.sha }); + expect(w.fake.writes).toEqual([]); + }); + + it("refuses with the current text when GitHub changed since the doc was opened", async () => { + const d = await doc("max", "docs/README.md"); + w.fake.commit(SITE, "main", { "docs/README.md": "# Docs\n\nTheirs.\n" }); + const error = await rejects( + saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "# Docs\n\nMine.\n" }), + 409, + "doc_conflict", + ); + expect(error.data).toMatchObject({ current: { text: "# Docs\n\nTheirs.\n", sha: blobSha(bytes("# Docs\n\nTheirs.\n")) } }); + expect(w.fake.fileText(SITE, "main", "docs/README.md")).toBe("# Docs\n\nTheirs.\n"); + }); + + it("commits on top of an unrelated commit made meanwhile", async () => { + const d = await doc("max", "docs/README.md"); + w.fake.commit(SITE, "main", { "src/app.ts": "x" }); + const out = await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "# New\n" }); + expect(out.status).toBe("committed"); + expect(w.fake.fileText(SITE, "main", "src/app.ts")).toBe("x"); + }); + + it("refuses Read Only users", async () => { + const d = await doc("rita", "docs/README.md"); + await rejects(saveDoc(writer("rita"), await w.access("rita"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "x" }), 403); + }); + + it("commits images in the same commit as the doc, inside the docs folder only", async () => { + const d = await doc("max", "docs/README.md"); + const data = Buffer.from(PNG).toString("base64"); + const out = await saveDoc(writer("max"), await w.access("max"), { + repoNodeId: IDS.site, + path: d.path, + baseSha: d.sha, + text: `${d.text}![Shot](assets/shot.png)\n`, + attachments: [{ path: "docs/assets/shot.png", data }], + }); + expect(out.status).toBe("committed"); + expect(w.fake.writes).toEqual(["app createCommitOnBranch main"]); + expect(await paths("max")).toContain("docs/assets/shot.png"); + const d2 = await doc("max", "docs/README.md"); + await rejects( + saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d2.path, baseSha: d2.sha, text: "x", attachments: [{ path: "src/shot.png", data }] }), + 400, + ); + await rejects( + saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d2.path, baseSha: d2.sha, text: "x", attachments: [{ path: "docs/a.png", data: "A".repeat(14_000_000) }] }), + 400, + ); + await rejects( + saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d2.path, baseSha: d2.sha, text: "x", attachments: [{ path: "docs/assets/shot.png", data }] }), + 409, + "doc_exists", + ); + }); + }); + + describe("pull request fallback", () => { + it("opens a pull request when branch protection refuses the commit, then saves to its branch", async () => { + w.fake.protectedBranches.add(`${SITE}#main`); + const d = await doc("max", "docs/README.md"); + const out = await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "# Reviewed\n" }); + expect(out.status).toBe("pending_review"); + if (out.status !== "pending_review") return; + expect(w.fake.fileText(SITE, "main", "docs/README.md")).toBe("# Docs\n\nHello.\n"); + expect(w.fake.fileText(SITE, out.pr.branch, "docs/README.md")).toBe("# Reviewed\n"); + expect(w.fake.pulls).toHaveLength(1); + expect(w.fake.pulls[0]).toMatchObject({ base: "main", head: out.pr.branch }); + expect(w.fake.pulls[0]!.body).toContain("branch protection"); + + const files = (await listDocs(w.db, await w.access("max"))).repos[0]!.files; + expect(files.find((f) => f.path === "docs/README.md")?.pending).toEqual({ number: out.pr.number, url: out.pr.url }); + // The editor now opens the PR branch's version, and the next save goes there. + const pending = await doc("max", "docs/README.md"); + expect(pending).toMatchObject({ text: "# Reviewed\n", branch: out.pr.branch, canDelete: false }); + const again = await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: pending.sha, text: "# Reviewed twice\n" }); + expect(again.status).toBe("pending_review"); + expect(w.fake.fileText(SITE, out.pr.branch, "docs/README.md")).toBe("# Reviewed twice\n"); + expect(w.fake.pulls).toHaveLength(1); + + // Closing the pull request ends "pending review". + const res = await webhook("pull_request", { action: "closed", installation: { id: 99 }, repository: { node_id: IDS.site }, pull_request: { number: out.pr.number } }); + expect(res.status).toBe(200); + expect(await w.db.select().from(docPendingPrs)).toEqual([]); + }); + + it("review mode sends App writes to a pull request, but not the user's own", async () => { + await updateWorkspaceSettings(w.db, await w.access("owner"), { reviewBotDocEdits: true }); + const d = await doc("max", "docs/README.md"); + const out = await saveDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, text: "# Max\n" }); + expect(out.status).toBe("pending_review"); + expect(w.fake.writes.some((x) => x.endsWith("createCommitOnBranch main"))).toBe(false); + expect(w.fake.pulls[0]!.body).toContain("requires review"); + + const g = await doc("jane", "docs/guide/setup.md"); + expect((await saveDoc(writer("jane"), await w.access("jane"), { repoNodeId: IDS.site, path: g.path, baseSha: g.sha, text: "# Jane\n" })).status).toBe("committed"); + }); + + it("lists a new doc whose first save became a pull request", async () => { + w.fake.protectedBranches.add(`${SITE}#main`); + const out = await createDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "docs/new.md" }); + expect(out.status).toBe("pending_review"); + expect(await paths("max")).toContain("docs/new.md"); + expect((await doc("max", "docs/new.md")).text).toBe("# new\n"); + }); + }); + + describe("create, rename, delete", () => { + it("creates a doc and refuses an existing name or a path outside the folder", async () => { + const out = await createDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "docs/guide/faq.md" }); + expect(out.status).toBe("committed"); + expect(w.fake.fileText(SITE, "main", "docs/guide/faq.md")).toBe("# faq\n"); + await rejects(createDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "docs/README.md" }), 409, "doc_exists"); + await rejects(createDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "src/x.md" }), 404); + await rejects(createDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "docs/notes.txt" }), 400); + }); + + it("Read Only cannot write into the hide folder because it cannot see it", async () => { + await rejects(createDoc(writer("rita"), await w.access("rita"), { repoNodeId: IDS.site, path: "docs/internal/x.md" }), 403); + }); + + it("renames in one commit", async () => { + const d = await doc("max", "docs/guide/setup.md"); + const out = await renameDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha, newPath: "docs/guide/install.md" }); + expect(out.status).toBe("committed"); + expect(w.fake.writes).toEqual(["app createCommitOnBranch main"]); + expect(w.fake.fileText(SITE, "main", "docs/guide/setup.md")).toBeNull(); + expect(w.fake.fileText(SITE, "main", "docs/guide/install.md")).toBe(CRLF); + const list = await paths("max"); + expect(list).toContain("docs/guide/install.md"); + expect(list).not.toContain("docs/guide/setup.md"); + await rejects(renameDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: "docs/README.md", baseSha: d.sha, newPath: "README.md" }), 400); + }); + + it("deletes for Admins only", async () => { + const d = await doc("max", "docs/README.md"); + await rejects(deleteDoc(writer("max"), await w.access("max"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha }), 403); + expect((await deleteDoc(writer("jane"), await w.access("jane"), { repoNodeId: IDS.site, path: d.path, baseSha: d.sha })).status).toBe("committed"); + expect(await paths("max")).not.toContain("docs/README.md"); + expect(w.fake.fileText(SITE, "main", "docs/README.md")).toBeNull(); + }); + }); + + describe("sync", () => { + it("picks up a push to the docs branch from the webhook", async () => { + w.fake.commit(SITE, "main", { "docs/pushed.md": "# Pushed\n", "docs/README.md": null }); + const res = await webhook("push", { ref: "refs/heads/main", installation: { id: 99 }, repository: { node_id: IDS.site, full_name: SITE } }); + expect(res.status).toBe(200); + const list = await paths("max"); + expect(list).toContain("docs/pushed.md"); + expect(list).not.toContain("docs/README.md"); + }); + + it("ignores pushes to other branches, and skips the tree listing when the folder did not change", async () => { + w.fake.commit(SITE, "feature", { "docs/branch.md": "x" }); + await webhook("push", { ref: "refs/heads/feature", installation: { id: 99 }, repository: { node_id: IDS.site } }); + expect(await paths("max")).not.toContain("docs/branch.md"); + w.fake.commit(SITE, "main", { "src/app.ts": "x" }); + w.fake.requests = []; + await webhook("push", { ref: "refs/heads/main", installation: { id: 99 }, repository: { node_id: IDS.site } }); + expect(w.fake.requests.some((r) => r.includes("/git/trees/"))).toBe(false); + }); + + it("moves the docs folder and branch per repo, and prunes the old cache", async () => { + w.fake.commit(SITE, "main", { "handbook/intro.md": "# Intro\n" }); + await rejects(setDocsConfig(w.deps, await w.access("max"), { repoNodeId: IDS.site, docsPath: "handbook" }), 403); + await rejects(setDocsConfig(w.deps, await w.access("jane"), { repoNodeId: IDS.site, docsPath: "../x" }), 400); + await rejects(setDocsConfig(w.deps, await w.access("jane"), { repoNodeId: IDS.site, docsBranch: "bad..name" }), 400); + await setDocsConfig(w.deps, await w.access("jane"), { repoNodeId: IDS.site, docsPath: "/handbook/" }); + expect(await paths("max")).toEqual(["handbook/intro.md"]); + const roots = await w.db.select().from(ghDocRoots); + expect(roots.map((r) => r.path)).toEqual(["handbook"]); + expect((await w.db.select().from(ghDocFiles)).every((f) => f.path.startsWith("handbook/"))).toBe(true); + expect((await w.db.select().from(ghDocBlobs)).length).toBe(0); + }); + + it("reports a missing folder", async () => { + await setDocsConfig(w.deps, await w.access("jane"), { repoNodeId: IDS.site, docsPath: "nowhere" }); + expect((await listDocs(w.db, await w.access("max"))).repos[0]!.status).toBe("missing"); + }); + + it("reconcile repairs a missed push", async () => { + w.fake.commit(SITE, "main", { "docs/missed.md": "# Missed\n" }); + await reconcile({ db: w.db, client: w.client, holder: "test", onlyNodeIds: [IDS.site] }); + expect(await paths("max")).toContain("docs/missed.md"); + }); + }); + + describe("presence", () => { + it("shows who else has the doc open, until the heartbeat expires", async () => { + const t0 = new Date("2026-11-19T10:00:00Z"); + await heartbeat(w.db, await w.access("max"), IDS.site, "docs/README.md", t0); + expect(await heartbeat(w.db, await w.access("jane"), IDS.site, "docs/README.md", t0)).toEqual([{ userId: "max", name: "Max Member" }]); + expect(await heartbeat(w.db, await w.access("jane"), IDS.site, "docs/README.md", new Date(t0.getTime() + 60_000))).toEqual([]); + await rejects(heartbeat(w.db, await w.access("rita"), IDS.site, "docs/README.md", t0), 403); + await rejects(heartbeat(w.db, await w.access("max"), IDS.site, "README.md", t0), 404); + }); + }); + + describe("settings", () => { + it("validates the hide folder", async () => { + await rejects(updateWorkspaceSettings(w.db, await w.access("owner"), { hideFolder: "../x" }), 400); + await rejects(updateWorkspaceSettings(w.db, await w.access("max"), { hideFolder: "x" }), 403); + await updateWorkspaceSettings(w.db, await w.access("owner"), { hideFolder: " " }); + expect(await paths("rita")).toContain("docs/internal/plan.md"); + }); + }); +}); diff --git a/packages/server/test/fake-github.ts b/packages/server/test/fake-github.ts index 874594a..910edb4 100644 --- a/packages/server/test/fake-github.ts +++ b/packages/server/test/fake-github.ts @@ -1,6 +1,20 @@ /** An in-memory GitHub for tests: a fetch function that routes the calls the client makes. */ +import { createHash } from "node:crypto"; import type { IssueJson, ProjectItemNode, RepoJson } from "../src/github/cache"; +/** A repo's git data: branches → commit, commits → full file map (path → blob sha). */ +interface FakeGit { + branches: Map; + commits: Map; message: string }>; +} + +const sha1 = (data: Uint8Array | string) => createHash("sha1").update(data).digest("hex"); + +/** git's blob id. */ +export function blobSha(bytes: Uint8Array): string { + return sha1(Buffer.concat([Buffer.from(`blob ${bytes.length}\0`), Buffer.from(bytes)])); +} + /** A GitHub user behind an App user token (`ghu_…`): what their own account can see. */ export interface FakeUser { login: string; @@ -43,6 +57,13 @@ export class FakeGitHub { writes: string[] = []; /** Clock for created/updated timestamps. */ clock = Date.parse("2026-06-01T00:00:00Z"); + /** Git data per repo ("owner/name"). */ + git = new Map(); + blobs = new Map(); + /** "owner/name#branch": direct commits are refused, as branch protection does. */ + protectedBranches = new Set(); + pulls: { fullName: string; number: number; head: string; base: string; title: string; body: string; by: string }[] = []; + private trees = new Map(); private tokenInstallation = new Map(); private itemCounter = 0; @@ -180,6 +201,8 @@ export class FakeGitHub { this.writes.push(`${this.whoName(who)} PATCH /repos/${fullName}/issues/${existing.number}`); return Response.json(issue); } + const git = this.gitRoute(method, url, init, who); + if (git) return git; if (path !== "/graphql") return null; const { query, variables } = JSON.parse(String(init?.body)) as { query: string; variables: Record }; @@ -229,6 +252,150 @@ export class FakeGitHub { return null; } + private gitOf(fullName: string): FakeGit { + let g = this.git.get(fullName); + if (!g) { + g = { branches: new Map(), commits: new Map() }; + this.git.set(fullName, g); + } + return g; + } + + /** Commits file changes (null deletes) on a branch, creating it from `from` (default main). */ + commit(fullName: string, branch: string, changes: Record, message = "test commit", from = "main"): string { + const g = this.gitOf(fullName); + const parent = g.branches.get(branch) ?? g.branches.get(from); + const files = new Map(parent ? g.commits.get(parent)!.files : []); + for (const [path, content] of Object.entries(changes)) { + if (content === null) files.delete(path); + else { + const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content; + const sha = blobSha(bytes); + this.blobs.set(sha, bytes); + files.set(path, sha); + } + } + const oid = sha1(`${parent ?? ""}:${[...files].sort().join(",")}:${message}:${this.tick()}`); + g.commits.set(oid, { files, message }); + g.branches.set(branch, oid); + return oid; + } + + /** The text of a file at a branch head, or null. */ + fileText(fullName: string, branch: string, path: string): string | null { + const g = this.git.get(fullName); + const head = g?.branches.get(branch); + const sha = head ? g!.commits.get(head)!.files.get(path) : undefined; + return sha ? new TextDecoder().decode(this.blobs.get(sha)) : null; + } + + headMessage(fullName: string, branch: string): string | null { + const g = this.git.get(fullName); + const head = g?.branches.get(branch); + return head ? g!.commits.get(head)!.message : null; + } + + private treeOid(fullName: string, commit: string, path: string): string | null { + const files = this.git.get(fullName)!.commits.get(commit)!.files; + const under = [...files].filter(([p]) => p.startsWith(`${path}/`)).sort(); + if (under.length === 0) return null; + const oid = sha1(`tree:${under.join(",")}`); + this.trees.set(oid, { fullName, commit, path }); + return oid; + } + + private canReadRepo(who: Caller, fullName: string) { + if (who.kind === "user") return who.user.repos.has(fullName); + if (who.kind === "installation") return this.installationCanReach(who.id, fullName); + return false; + } + + /** Git REST routes and doc GraphQL. Null = not a git call. */ + private gitRoute(method: string, url: URL, init: RequestInit | undefined, who: Caller): Response | null { + const path = url.pathname; + const deny = () => new Response(JSON.stringify({ message: "Not Found" }), { status: 404 }); + let m: RegExpExecArray | null; + if ((m = /^\/repos\/([^/]+\/[^/]+)\/git\/trees\/([0-9a-f]+)$/.exec(path)) && method === "GET") { + const t = this.trees.get(m[2]!); + if (!t || t.fullName !== m[1] || !this.canReadRepo(who, m[1]!)) return deny(); + const files = this.git.get(t.fullName)!.commits.get(t.commit)!.files; + const tree = [...files] + .filter(([p]) => p.startsWith(`${t.path}/`)) + .map(([p, sha]) => ({ path: p.slice(t.path.length + 1), type: "blob", sha, size: this.blobs.get(sha)!.length })); + return Response.json({ sha: m[2], truncated: false, tree }); + } + if ((m = /^\/repos\/([^/]+\/[^/]+)\/git\/blobs\/([0-9a-f]+)$/.exec(path)) && method === "GET") { + const bytes = this.blobs.get(m[2]!); + if (!bytes || !this.canReadRepo(who, m[1]!)) return deny(); + // GitHub wraps base64 at 60 columns. + const b64 = Buffer.from(bytes).toString("base64").replace(/(.{60})/g, "$1\n"); + return Response.json({ sha: m[2], size: bytes.length, encoding: "base64", content: b64 }); + } + if ((m = /^\/repos\/([^/]+\/[^/]+)\/git\/refs$/.exec(path)) && method === "POST") { + if (!this.canWriteRepo(who, m[1]!)) return deny(); + const body = JSON.parse(String(init?.body)) as { ref: string; sha: string }; + const g = this.gitOf(m[1]!); + const branch = body.ref.replace(/^refs\/heads\//, ""); + if (g.branches.has(branch)) return Response.json({ message: "Reference already exists" }, { status: 422 }); + g.branches.set(branch, body.sha); + this.writes.push(`${this.whoName(who)} createRef ${branch}`); + return Response.json({ ref: body.ref, object: { sha: body.sha } }, { status: 201 }); + } + if ((m = /^\/repos\/([^/]+\/[^/]+)\/pulls$/.exec(path)) && method === "POST") { + if (!this.canWriteRepo(who, m[1]!)) return deny(); + const body = JSON.parse(String(init?.body)) as { title: string; head: string; base: string; body: string }; + const number = 100 + this.pulls.length + 1; + this.pulls.push({ fullName: m[1]!, number, ...body, by: this.whoName(who) }); + this.writes.push(`${this.whoName(who)} openPullRequest ${number}`); + return Response.json({ number, html_url: `https://github.com/${m[1]}/pull/${number}` }, { status: 201 }); + } + if (path !== "/graphql") return null; + const { query, variables } = JSON.parse(String(init?.body)) as { query: string; variables: Record }; // eslint-disable-line @typescript-eslint/no-explicit-any + if (query.includes("query DocHead")) { + const fullName = `${variables.owner}/${variables.name}`; + if (!this.repos.has(fullName) || !this.canReadRepo(who, fullName)) { + return Response.json({ data: { repository: null }, errors: [{ type: "NOT_FOUND", message: "Could not resolve to a Repository" }] }); + } + const g = this.gitOf(fullName); + const head = g.branches.get(String(variables.ref).replace(/^refs\/heads\//, "")) ?? null; + const expr = String(variables.expr); + const colon = expr.indexOf(":"); + const branchHead = g.branches.get(expr.slice(0, colon)); + const filePath = expr.slice(colon + 1); + let object: { __typename: string; oid: string } | null = null; + if (branchHead) { + const blob = g.commits.get(branchHead)!.files.get(filePath); + const tree = blob ? null : this.treeOid(fullName, branchHead, filePath); + object = blob ? { __typename: "Blob", oid: blob } : tree ? { __typename: "Tree", oid: tree } : null; + } + return Response.json({ data: { repository: { ref: head ? { target: { oid: head } } : null, object } } }); + } + if (query.includes("mutation CommitFiles")) { + const input = variables.input as { + branch: { repositoryNameWithOwner: string; branchName: string }; + message: { headline: string; body?: string }; + fileChanges: { additions: { path: string; contents: string }[]; deletions: { path: string }[] }; + expectedHeadOid: string; + }; + const fullName = input.branch.repositoryNameWithOwner; + const fail = (type: string, message: string) => Response.json({ data: { createCommitOnBranch: null }, errors: [{ type, message }] }); + if (!this.canWriteRepo(who, fullName)) return fail("FORBIDDEN", "Resource not accessible by integration"); + if (this.protectedBranches.has(`${fullName}#${input.branch.branchName}`)) return fail("UNPROCESSABLE", "Repository rule violations found"); + const g = this.gitOf(fullName); + const head = g.branches.get(input.branch.branchName); + if (!head) return fail("NOT_FOUND", "Branch not found"); + if (head !== input.expectedHeadOid) return fail("STALE_DATA", `Expected branch to point to "${input.expectedHeadOid}" but it did not`); + const changes: Record = {}; + for (const a of input.fileChanges.additions) changes[a.path] = new Uint8Array(Buffer.from(a.contents, "base64")); + for (const d of input.fileChanges.deletions) changes[d.path] = null; + const message = [input.message.headline, input.message.body].filter(Boolean).join("\n\n"); + const oid = this.commit(fullName, input.branch.branchName, changes, message); + this.writes.push(`${this.whoName(who)} createCommitOnBranch ${input.branch.branchName}`); + return Response.json({ data: { createCommitOnBranch: { commit: { oid, url: `https://github.com/${fullName}/commit/${oid}` } } } }); + } + return null; + } + addRepo(fullName: string, nodeId: string, id: number) { const [owner, name] = fullName.split("/") as [string, string]; this.repos.set(fullName, { node_id: nodeId, id, name, full_name: fullName, private: true, default_branch: "main", owner: { login: owner } }); From 33e3d3ae1e0d1112bc5be7ac2b4cecd905a9a1e3 Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Thu, 19 Nov 2026 15:16:06 -0500 Subject: [PATCH 4/5] feat: docs on web: tree, rich-text CodeMirror editor, frontmatter panel, conflict view Live preview hides markdown marks off the cursor's line; the text never changes, so the round-trip fixtures pass through a real EditorState. Images paste into /assets/ and commit with the doc. Settings: docs folder and branch per repo, hide folder, review mode. Cached docs open without the GitHub App. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHyaEvdoSPjkLy7T1aaz Signed-off-by: Erik Goins --- apps/web/e2e/docs.spec.ts | 149 +++++ apps/web/package.json | 9 + .../docs/[repoNodeId]/[...path]/page.tsx | 12 + .../w/[workspaceId]/docs/conflict-view.tsx | 59 ++ .../app/w/[workspaceId]/docs/doc-editor.tsx | 509 ++++++++++++++++++ .../src/app/w/[workspaceId]/docs/docs-api.ts | 42 ++ .../app/w/[workspaceId]/docs/docs-tree.tsx | 180 +++++++ .../[workspaceId]/docs/frontmatter-panel.tsx | 92 ++++ .../src/app/w/[workspaceId]/docs/layout.tsx | 17 + .../web/src/app/w/[workspaceId]/docs/links.ts | 17 + .../web/src/app/w/[workspaceId]/docs/page.tsx | 39 ++ .../src/app/w/[workspaceId]/settings/page.tsx | 21 +- .../settings/settings-panels.tsx | 84 ++- .../app/w/[workspaceId]/workspace-shell.tsx | 1 + apps/web/src/lib/doc-editor.test.ts | 51 ++ apps/web/src/lib/doc-editor.ts | 64 +++ apps/web/src/lib/live-preview.ts | 289 ++++++++++ apps/web/src/lib/markdown-commands.test.ts | 33 ++ apps/web/src/lib/markdown-commands.ts | 69 +++ packages/core/src/docs/paths.test.ts | 12 +- packages/core/src/docs/paths.ts | 15 + packages/server/src/api/routes.ts | 16 +- packages/server/src/index.ts | 9 + packages/server/src/services/docs.ts | 5 +- pnpm-lock.yaml | 237 ++++++++ 25 files changed, 2024 insertions(+), 7 deletions(-) create mode 100644 apps/web/e2e/docs.spec.ts create mode 100644 apps/web/src/app/w/[workspaceId]/docs/[repoNodeId]/[...path]/page.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/conflict-view.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/doc-editor.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/docs-api.ts create mode 100644 apps/web/src/app/w/[workspaceId]/docs/docs-tree.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/frontmatter-panel.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/layout.tsx create mode 100644 apps/web/src/app/w/[workspaceId]/docs/links.ts create mode 100644 apps/web/src/app/w/[workspaceId]/docs/page.tsx create mode 100644 apps/web/src/lib/doc-editor.test.ts create mode 100644 apps/web/src/lib/doc-editor.ts create mode 100644 apps/web/src/lib/live-preview.ts create mode 100644 apps/web/src/lib/markdown-commands.test.ts create mode 100644 apps/web/src/lib/markdown-commands.ts diff --git a/apps/web/e2e/docs.spec.ts b/apps/web/e2e/docs.spec.ts new file mode 100644 index 0000000..e725459 --- /dev/null +++ b/apps/web/e2e/docs.spec.ts @@ -0,0 +1,149 @@ +/** + * Phase 4 (docs/spec.md): the doc tree and the editor in a real browser. + * + * GitHub is not reachable in E2E, so the test writes the cache rows a synced docs folder would + * have, and checks what a page can do from the cache: the tree, the hide folder for Read Only, the + * rich-text view, formatting, the frontmatter panel, and that single-key shortcuts stay out of the + * editor. Commits are covered against a fake GitHub in packages/server/test/docs.test.ts. + */ +import { type BrowserContext, type Page, expect, test } from "@playwright/test"; +import { ghDocBlobs, ghDocFiles, ghDocRoots, ghProjects, ghRepos, workspaceGithub, workspaceRepos } from "@gitwork/db"; +import { openSqlite } from "@gitwork/db/node"; +import { lastEmail, signInCode } from "./outbox"; + +const README = "---\ntitle: Welcome\ntags: [a, b]\n---\n# Handbook\n\nSome **bold** words.\n\n- [ ] Write docs\n"; +const SECRET = "# Secret plan\n\nInternal only.\n"; + +async function signIn(page: Page, email: string) { + await page.goto("/sign-in"); + await page.getByLabel("Email").fill(email); + await page.getByRole("button", { name: "Email me a sign-in code" }).click(); + await page.getByLabel("Code").fill(await signInCode(email)); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); +} + +async function seedDocs(workspaceId: string) { + const { db } = openSqlite("file:.data/e2e.sqlite"); + const now = new Date(); + const root = "R_docs:main:docs"; + await db.batch([ + db + .insert(ghRepos) + .values({ nodeId: "R_docs", githubId: 50, installationId: 99, owner: "acme", name: "handbook", fullName: "acme/handbook", private: true, defaultBranch: "main", htmlUrl: "https://github.com/acme/handbook", syncedAt: now }) + .onConflictDoNothing(), + db.insert(ghProjects).values({ nodeId: "PVT_docs", installationId: 99, ownerLogin: "acme", number: 7, title: "Handbook", url: "https://github.com/orgs/acme/projects/7", syncedAt: now }).onConflictDoNothing(), + db.insert(workspaceGithub).values({ workspaceId, installationId: 99, projectNodeId: "PVT_docs", linkedAt: now }), + db.insert(workspaceRepos).values({ workspaceId, repoNodeId: "R_docs" }), + db.insert(ghDocRoots).values({ id: root, repoNodeId: "R_docs", branch: "main", path: "docs", headOid: "c0ffee", treeOid: "7ree", syncedAt: now }), + db.insert(ghDocFiles).values([ + { rootId: root, path: "docs/README.md", blobSha: "a".repeat(40), size: README.length }, + { rootId: root, path: "docs/internal/plan.md", blobSha: "b".repeat(40), size: SECRET.length }, + { rootId: root, path: "docs/guide/setup.md", blobSha: "c".repeat(40), size: 9 }, + ]), + db.insert(ghDocBlobs).values([ + { sha: "a".repeat(40), text: README, size: README.length, fetchedAt: now }, + { sha: "b".repeat(40), text: SECRET, size: SECRET.length, fetchedAt: now }, + { sha: "c".repeat(40), text: "# Setup\n", size: 9, fetchedAt: now }, + ]), + ]); +} + +test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ browser }) => { + const contexts: BrowserContext[] = []; + const page = async () => { + const ctx = await browser.newContext(); + contexts.push(ctx); + return ctx.newPage(); + }; + + const owner = await page(); + await signIn(owner, "docs-owner@example.com"); + await owner.getByLabel("Account name").fill("Docs Agency"); + await owner.getByLabel("First workspace").fill("Docs Website"); + await owner.getByRole("button", { name: "Create" }).click(); + await expect(owner.getByRole("heading", { name: "Docs Website" })).toBeVisible(); + const workspaceId = /\/w\/([^/?#]+)/.exec(owner.url())![1]!; + await seedDocs(workspaceId); + + // The hide folder, set through the settings form. + await owner.goto(`/w/${workspaceId}/settings`); + await owner.getByLabel("Hide docs in this folder").fill("internal"); + const saved = owner.waitForResponse((r) => r.url().endsWith(`/workspaces/${workspaceId}/settings`) && r.status() === 204); + await owner.getByRole("button", { name: "Save", exact: true }).click(); + await saved; + + // A Read Only client. + await owner.getByRole("link", { name: "Members" }).click(); + await owner.getByLabel("Email").fill("docs-reader@example.com"); + await owner.getByLabel("Role").selectOption("read_only"); + await owner.getByRole("button", { name: "Send invite" }).click(); + const [, invitePath] = await lastEmail("docs-reader@example.com", /http:\/\/localhost:\d+(\/invite\/[A-Za-z0-9_-]+)/); + const reader = await page(); + await signIn(reader, "docs-reader@example.com"); + await reader.goto(invitePath!); + await reader.getByRole("button", { name: "Accept invite" }).click(); + await expect(reader.getByText("Your role: Read Only")).toBeVisible(); + + // Owner: the whole tree, from the sidebar's Docs link. + await owner.goto(`/w/${workspaceId}`); + await owner.getByRole("link", { name: "Docs", exact: true }).click(); + const tree = owner.getByRole("complementary", { name: "Docs" }); + await expect(tree.getByRole("link", { name: "README" })).toBeVisible(); + await expect(tree.getByRole("button", { name: "internal" })).toBeVisible(); + + // Read Only: no hidden folder in the tree, the API, or by URL. + await reader.goto(`/w/${workspaceId}/docs`); + await expect(reader.getByRole("complementary", { name: "Docs" }).getByRole("link", { name: "README" })).toBeVisible(); + expect(await reader.content()).not.toContain("internal"); + const list = await (await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs`)).text(); + expect(list).not.toContain("internal"); + expect((await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs/file?repo=R_docs&path=docs/internal/plan.md`)).status()).toBe(404); + const r = await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs/file?repo=R_docs&path=docs/README.md`); + expect(await r.json()).toMatchObject({ doc: { text: README, editable: false } }); + + // Read Only sees the doc rendered, with no toolbar or save. + await reader.getByRole("link", { name: "README" }).click(); + await expect(reader.locator(".cm-lp-h1")).toHaveText("Handbook"); + await expect(reader.getByRole("toolbar", { name: "Formatting" })).toHaveCount(0); + await expect(reader.getByRole("button", { name: "Save" })).toHaveCount(0); + + // Owner: the rich-text view hides marks; the cursor's line shows the source. + await owner.getByRole("complementary", { name: "Docs" }).getByRole("link", { name: "README" }).click(); + const editor = owner.getByTestId("doc-editor"); + await expect(editor.locator(".cm-lp-h1")).toHaveText("Handbook"); + await expect(editor.locator(".cm-lp-strong")).toHaveText("bold"); + await expect(editor.locator("input.cm-lp-task")).toHaveCount(1); + await editor.locator(".cm-lp-h1").click(); + await expect(editor.locator(".cm-lp-h1")).toHaveText("# Handbook"); + + // Single-key shortcuts never fire inside the editor (roadmap C4): "c" types a "c". + await owner.keyboard.press("End"); + await owner.keyboard.type(" c"); + await expect(editor.locator(".cm-lp-h1")).toHaveText("# Handbook c"); + await expect(owner.getByRole("dialog")).toHaveCount(0); + await expect(owner.getByTestId("doc-status")).toHaveText("Unsaved changes"); + + // Formatting: select a word and make it italic. + await editor.locator(".cm-line", { hasText: "Some" }).click(); + await owner.keyboard.press("Home"); + for (let i = 0; i < 4; i++) await owner.keyboard.press("Shift+ArrowRight"); + await owner.getByRole("button", { name: "Italic (⌘I)" }).click(); + await owner.getByRole("group", { name: "View" }).getByRole("button", { name: "Markdown" }).click(); + await expect(editor.locator(".cm-line", { hasText: "bold" })).toHaveText("*Some* **bold** words."); + + // The frontmatter panel edits one line; the list stays read-only. + const panel = owner.getByRole("region", { name: "Properties" }); + await expect(panel.getByText("[a, b]")).toBeVisible(); + await panel.getByLabel("Property title").fill("Welcome aboard"); + await panel.getByLabel("Property title").press("Enter"); + await expect(editor.locator(".cm-line").nth(1)).toHaveText("title: Welcome aboard"); + await expect(editor.locator(".cm-line").nth(2)).toHaveText("tags: [a, b]"); + + // A save needs GitHub; without the App the editor says so and keeps the text. + await owner.getByRole("button", { name: "Save", exact: true }).click(); + await expect(owner.getByTestId("doc-status")).toContainText("GitHub App is not set up"); + await expect(editor.locator(".cm-line").nth(1)).toHaveText("title: Welcome aboard"); + + for (const ctx of contexts) await ctx.close(); +}); diff --git a/apps/web/package.json b/apps/web/package.json index d29d691..4a8ae43 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -18,9 +18,18 @@ "test:e2e": "playwright test" }, "dependencies": { + "@codemirror/commands": "6.11.1", + "@codemirror/lang-markdown": "6.5.2", + "@codemirror/language": "6.13.1", + "@codemirror/merge": "6.12.3", + "@codemirror/search": "6.7.2", + "@codemirror/state": "6.7.6", + "@codemirror/view": "6.43.15", "@gitwork/core": "workspace:*", "@gitwork/db": "workspace:*", "@gitwork/server": "workspace:*", + "@lezer/highlight": "1.2.5", + "@lezer/markdown": "1.8.1", "@opennextjs/cloudflare": "1.20.11", "better-auth": "1.7.8", "class-variance-authority": "0.7.1", diff --git a/apps/web/src/app/w/[workspaceId]/docs/[repoNodeId]/[...path]/page.tsx b/apps/web/src/app/w/[workspaceId]/docs/[repoNodeId]/[...path]/page.tsx new file mode 100644 index 0000000..114f309 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/[repoNodeId]/[...path]/page.tsx @@ -0,0 +1,12 @@ +import { requireWorkspacePage } from "@/server/pages"; +import { decodeSegment } from "../../links"; +import { DocEditor } from "../../doc-editor"; + +/** The editor loads the doc through /api/v1 in the browser: this render never calls GitHub. */ +export default async function DocPage({ params }: PageProps<"/w/[workspaceId]/docs/[repoNodeId]/[...path]">) { + const { workspaceId, repoNodeId, path } = await params; + await requireWorkspacePage(workspaceId, `/w/${workspaceId}/docs`); + const docPath = path.map(decodeSegment).join("/"); + const repo = decodeSegment(repoNodeId); + return ; +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/conflict-view.tsx b/apps/web/src/app/w/[workspaceId]/docs/conflict-view.tsx new file mode 100644 index 0000000..9b13daa --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/conflict-view.tsx @@ -0,0 +1,59 @@ +"use client"; +import { MergeView } from "@codemirror/merge"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { useEffect, useRef } from "react"; +import { Button } from "@/components/kit"; +import { docExtensions, docText } from "@/lib/doc-editor"; + +/** + * Someone changed the doc on GitHub since it was opened (decision 011). Left: GitHub's version. + * Right: this person's version, editable. They keep editing the right side, then save it on top + * of GitHub's version, or drop theirs. + */ +export function ConflictView(props: { + theirs: string; + mine: string; + busy: boolean; + onSave: (merged: string) => void; + onKeepEditing: (merged: string) => void; + onUseTheirs: () => void; +}) { + const host = useRef(null); + const view = useRef(null); + useEffect(() => { + const merge = new MergeView({ + a: { doc: props.theirs, extensions: [...docExtensions(props.theirs), EditorState.readOnly.of(true), EditorView.lineWrapping] }, + b: { doc: props.mine, extensions: [...docExtensions(props.mine), EditorView.lineWrapping] }, + parent: host.current!, + collapseUnchanged: { margin: 3, minSize: 6 }, + }); + view.current = merge; + return () => merge.destroy(); + }, [props.theirs, props.mine]); + const merged = () => (view.current ? docText(view.current.b.state) : props.mine); + + return ( +
+
+ Someone changed this doc on GitHub since you opened it. Left: the version on GitHub. Right: your version. Edit the right side, then save it. +
+
+ On GitHub + Yours +
+
+
+ + + +
+
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/doc-editor.tsx b/apps/web/src/app/w/[workspaceId]/docs/doc-editor.tsx new file mode 100644 index 0000000..20d9e12 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/doc-editor.tsx @@ -0,0 +1,509 @@ +"use client"; +import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands"; +import { markdown, markdownLanguage } from "@codemirror/lang-markdown"; +import { syntaxHighlighting } from "@codemirror/language"; +import { searchKeymap } from "@codemirror/search"; +import { Compartment, EditorState } from "@codemirror/state"; +import { EditorView, drawSelection, dropCursor, keymap, placeholder } from "@codemirror/view"; +import { MAX_EDITABLE_BYTES, type TextChange, lineSeparatorOf, relativeLink, resolveRelative, safeFileName } from "@gitwork/core"; +import type { DocView, Editor } from "@gitwork/server"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Button, Input } from "@/components/kit"; +import { changeSpec, docExtensions, docText } from "@/lib/doc-editor"; +import { livePreview, markdownHighlight } from "@/lib/live-preview"; +import { insertLink, run, setLinePrefix, toggleWrap } from "@/lib/markdown-commands"; +import { ConflictView } from "./conflict-view"; +import { DocsApiError, docsApi } from "./docs-api"; +import { FrontmatterPanel } from "./frontmatter-panel"; +import { docHref, rawHref } from "./links"; + +const MAX_IMAGE_BYTES = 10_000_000; +const MODE_KEY = "gitwork.docs.mode"; +type Mode = "preview" | "source"; +type Status = { kind: "idle" | "dirty" | "saving" | "saved" | "error"; text: string }; + +function storedMode(): Mode { + try { + return localStorage.getItem(MODE_KEY) === "source" ? "source" : "preview"; + } catch { + return "preview"; + } +} + +function toBase64(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result).replace(/^data:[^,]*,/, "")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(file); + }); +} + +export function DocEditor(props: { workspaceId: string; repoNodeId: string; path: string }) { + const { workspaceId, repoNodeId, path } = props; + const router = useRouter(); + const docs = useMemo(() => docsApi(workspaceId), [workspaceId]); + const [doc, setDoc] = useState(null); + const [loadError, setLoadError] = useState(""); + // What the editor shows: replaced on load and after a conflict is resolved. + const [source, setSource] = useState<{ text: string; sha: string; dirty: boolean; key: number } | null>(null); + const [status, setStatus] = useState({ kind: "idle", text: "" }); + const [mirror, setMirror] = useState(""); + const [conflict, setConflict] = useState<{ theirs: { sha: string; text: string | null }; mine: string } | null>(null); + const [mode, setMode] = useState("preview"); + const [editors, setEditors] = useState([]); + const [renaming, setRenaming] = useState(false); + const [newName, setNewName] = useState(""); + const [confirmDelete, setConfirmDelete] = useState(false); + const host = useRef(null); + const fileInput = useRef(null); + const viewRef = useRef(null); + const baseSha = useRef(""); + const images = useRef(new Map()); + const preview = useRef(new Compartment()); + const saveRef = useRef<() => void>(() => {}); + const saving = useRef(false); + + // ---- Load ---- + useEffect(() => { + let live = true; + docs + .get(repoNodeId, path) + .then((d) => { + if (!live) return; + setMode(storedMode()); + setDoc(d); + baseSha.current = d.sha; + setSource({ text: d.text ?? "", sha: d.sha, dirty: false, key: Date.now() }); + }) + .catch((e: Error) => live && setLoadError(e.message)); + return () => { + live = false; + }; + }, [docs, repoNodeId, path]); + + const resolveImage = useCallback( + (src: string) => { + if (/^https:\/\//i.test(src)) return src; + const abs = resolveRelative(path, src); + if (!abs) return null; + return images.current.get(abs)?.url ?? rawHref(workspaceId, repoNodeId, abs); + }, + [path, workspaceId, repoNodeId], + ); + + const addImages = useCallback( + async (files: File[]) => { + const view = viewRef.current; + if (!view || !doc?.editable) return false; + const list = files.filter((f) => f.type.startsWith("image/")); + if (list.length === 0) return false; + for (const file of list) { + if (file.size > MAX_IMAGE_BYTES) { + setStatus({ kind: "error", text: `${file.name} is larger than 10 MB.` }); + continue; + } + const base = safeFileName(file.name || "image.png"); + const dot = base.lastIndexOf("."); + const name = `${base.slice(0, dot > 0 ? dot : undefined)}-${Date.now().toString(36)}${dot > 0 ? base.slice(dot) : ".png"}`; + const abs = `${doc.root}/assets/${name}`; + const link = relativeLink(path, abs); + images.current.set(abs, { data: await toBase64(file), url: URL.createObjectURL(file), link }); + const alt = (file.name || "image").replace(/\.[^.]+$/, "").replace(/[[\]]/g, ""); + view.dispatch(view.state.replaceSelection(`![${alt}](${link})`), { userEvent: "input.paste" }); + } + return true; + }, + [doc, path], + ); + + // ---- Editor ---- + useEffect(() => { + if (!source || !doc || !host.current) return; + const editable = doc.editable; + let frame = 0; + const view = new EditorView({ + parent: host.current, + state: EditorState.create({ + doc: source.text, + extensions: [ + ...docExtensions(source.text), + history(), + drawSelection(), + dropCursor(), + keymap.of([ + { key: "Mod-s", preventDefault: true, run: () => (saveRef.current(), true) }, + { key: "Mod-b", run: (v) => run(v, (s) => toggleWrap(s, "**")) }, + { key: "Mod-i", run: (v) => run(v, (s) => toggleWrap(s, "*")) }, + ...defaultKeymap, + ...historyKeymap, + ...searchKeymap, + indentWithTab, + ]), + markdown({ base: markdownLanguage }), + syntaxHighlighting(markdownHighlight), + EditorView.lineWrapping, + EditorState.readOnly.of(!editable), + EditorView.editable.of(editable), + placeholder(editable ? "Start writing…" : ""), + preview.current.of(storedMode() === "preview" ? livePreview({ resolveImage }) : []), + EditorView.updateListener.of((u) => { + if (!u.docChanged) return; + setStatus({ kind: "dirty", text: "Unsaved changes" }); + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => setMirror(docText(u.state))); + }), + EditorView.domEventHandlers({ + paste: (e) => { + const files = [...(e.clipboardData?.files ?? [])]; + if (files.some((f) => f.type.startsWith("image/"))) { + e.preventDefault(); + void addImages(files); + return true; + } + return false; + }, + drop: (e) => { + const files = [...(e.dataTransfer?.files ?? [])]; + if (files.some((f) => f.type.startsWith("image/"))) { + e.preventDefault(); + void addImages(files); + return true; + } + return false; + }, + }), + EditorView.theme({ + "&": { fontSize: "15px" }, + "&.cm-focused": { outline: "none" }, + ".cm-content": { fontFamily: "inherit", padding: "12px 0 40vh", caretColor: "var(--foreground)" }, + ".cm-line": { padding: "0 2px", lineHeight: "1.65" }, + ".cm-scroller": { fontFamily: "inherit" }, + }), + ], + }), + }); + viewRef.current = view; + setMirror(source.text); + setStatus(source.dirty ? { kind: "dirty", text: "Unsaved changes" } : { kind: "idle", text: "" }); + return () => { + cancelAnimationFrame(frame); + view.destroy(); + viewRef.current = null; + }; + // The editor is rebuilt only when the content source changes, never on each render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [source?.key, doc?.editable]); + + function switchMode(next: Mode) { + setMode(next); + try { + localStorage.setItem(MODE_KEY, next); + } catch { + // Private windows: the choice lasts until the page closes. + } + viewRef.current?.dispatch({ effects: preview.current.reconfigure(next === "preview" ? livePreview({ resolveImage }) : []) }); + } + + // ---- Save ---- + async function save(textOverride?: string) { + const view = viewRef.current; + if (!doc?.editable || saving.current) return; + const text = textOverride ?? (view ? docText(view.state) : null); + if (text === null) return; + if (new TextEncoder().encode(text).length > MAX_EDITABLE_BYTES) { + setStatus({ kind: "error", text: "This doc is larger than 1 MB. Split it, or edit it on GitHub." }); + return; + } + const attachments = [...images.current].filter(([, img]) => text.includes(img.link)).map(([p, img]) => ({ path: p, data: img.data })); + saving.current = true; + setStatus({ kind: "saving", text: "Saving to GitHub…" }); + try { + const out = await docs.save({ repoNodeId, path, baseSha: baseSha.current, text, attachments: attachments.length ? attachments : undefined }); + baseSha.current = out.sha ?? baseSha.current; + for (const a of attachments) images.current.delete(a.path); + const changedSince = viewRef.current ? docText(viewRef.current.state) !== text : false; + if (out.status === "pending_review") { + setDoc((d) => (d ? { ...d, pending: out.pr, branch: out.pr.branch, canDelete: false } : d)); + setStatus({ kind: changedSince ? "dirty" : "saved", text: changedSince ? "Unsaved changes" : `Saved to pull request #${out.pr.number}` }); + } else if (out.status === "committed") { + setStatus({ kind: changedSince ? "dirty" : "saved", text: changedSince ? "Unsaved changes" : `Saved · ${out.commitSha.slice(0, 7)}` }); + } else { + setStatus({ kind: "saved", text: "No changes to save" }); + } + router.refresh(); + } catch (e) { + if (e instanceof DocsApiError && e.code === "doc_conflict") { + const current = e.data.current as { sha: string; text: string | null }; + setConflict({ theirs: current, mine: text }); + setStatus({ kind: "error", text: "Changed on GitHub — resolve below" }); + } else { + setStatus({ kind: "error", text: (e as Error).message }); + } + } finally { + saving.current = false; + } + } + useEffect(() => { + saveRef.current = () => void save(); + }); + + function remount(text: string, sha: string, dirty: boolean) { + baseSha.current = sha; + setConflict(null); + setSource({ text, sha, dirty, key: Date.now() }); + } + + // ---- Presence: "Jane is editing" (spec: a heartbeat row) ---- + useEffect(() => { + if (!doc?.editable) return; + let live = true; + const tick = () => + docs + .heartbeat(repoNodeId, path) + .then((e) => live && setEditors(e)) + .catch(() => {}); + void tick(); + const timer = setInterval(tick, 15_000); + return () => { + live = false; + clearInterval(timer); + void docs.leave(repoNodeId, path).catch(() => {}); + }; + }, [doc?.editable, docs, repoNodeId, path]); + + // ---- Unsaved changes ---- + const dirty = status.kind === "dirty" || status.kind === "error"; + useEffect(() => { + if (!dirty) return; + const warn = (e: BeforeUnloadEvent) => e.preventDefault(); + window.addEventListener("beforeunload", warn); + return () => window.removeEventListener("beforeunload", warn); + }, [dirty]); + + async function rename() { + if (!doc) return; + const clean = newName.trim().replace(/^\/+/, ""); + const target = `${doc.root}/${/\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`}`; + try { + const out = await docs.rename({ repoNodeId, path, baseSha: baseSha.current, newPath: target }); + setRenaming(false); + if (out.status === "pending_review") setStatus({ kind: "saved", text: `Rename is in pull request #${out.pr.number}` }); + else router.replace(docHref(workspaceId, repoNodeId, target)); + router.refresh(); + } catch (e) { + setStatus({ kind: "error", text: (e as Error).message }); + } + } + + async function remove() { + try { + const out = await docs.remove(repoNodeId, path, baseSha.current); + if (out.status === "pending_review") { + setStatus({ kind: "saved", text: `Delete is in pull request #${out.pr.number}` }); + setConfirmDelete(false); + return; + } + router.push(`/w/${workspaceId}/docs`); + router.refresh(); + } catch (e) { + setStatus({ kind: "error", text: (e as Error).message }); + } + } + + function applyChange(change: TextChange) { + const view = viewRef.current; + if (!view) return; + view.dispatch(view.state.update(changeSpec(view.state, change), { userEvent: "input.properties" })); + } + + if (loadError) return

{loadError}

; + if (!doc || !source) return

Loading…

; + + const githubUrl = `https://github.com/${doc.fullName}/blob/${encodeURIComponent(doc.branch)}/${doc.path.split("/").map(encodeURIComponent).join("/")}`; + const lineBreak = lineSeparatorOf(source.text); + + return ( +
+
+
+ {renaming ? ( +
{ + e.preventDefault(); + void rename(); + }} + > + setNewName(e.target.value)} autoFocus className="h-8 w-72" /> + + +
+ ) : ( +

+ {doc.name} +

+ )} +

+ {doc.fullName} · {doc.branch} ·{" "} + + Open on GitHub + +

+
+
+
+ {(["preview", "source"] as const).map((m) => ( + + ))} +
+ {doc.editable && !renaming && ( + + )} + {doc.canDelete && + (confirmDelete ? ( + + ) : ( + + ))} + {doc.editable && ( + + )} +
+
+ +

+ {status.text} +

+ + {doc.pending && ( +

+ Pending review: saves go to{" "} + + pull request #{doc.pending.number} + {" "} + until it is merged or closed. +

+ )} + {editors.length > 0 && ( +

+ {editors.map((e) => e.name).join(", ")} {editors.length === 1 ? "is" : "are"} editing this doc. Saves by others show up as a conflict you can resolve. +

+ )} + {!doc.editable && ( +

+ {doc.text === null + ? "This file is not plain UTF-8 text, or it is larger than 1 MB. Open it on GitHub to edit it." + : "You can read this doc. Your role cannot edit it."} +

+ )} + + {conflict && ( + { + remount(merged, conflict.theirs.sha, true); + // The rebuilt editor holds `merged`; save it on top of GitHub's version. + setTimeout(() => void save(merged), 0); + }} + onKeepEditing={(merged) => remount(merged, conflict.theirs.sha, true)} + onUseTheirs={() => remount(conflict.theirs.text ?? "", conflict.theirs.sha, false)} + /> + )} + +
+ ); +} + +type Spec = Parameters[1]; + +function Toolbar({ onRun, onImage }: { onRun: (spec: Spec) => void; onImage: () => void }) { + const items: { label: string; title: string; spec: Spec }[] = [ + { label: "B", title: "Bold (⌘B)", spec: (s) => toggleWrap(s, "**") }, + { label: "I", title: "Italic (⌘I)", spec: (s) => toggleWrap(s, "*") }, + { label: "S", title: "Strikethrough", spec: (s) => toggleWrap(s, "~~") }, + { label: "H1", title: "Heading 1", spec: (s) => setLinePrefix(s, "# ") }, + { label: "H2", title: "Heading 2", spec: (s) => setLinePrefix(s, "## ") }, + { label: "H3", title: "Heading 3", spec: (s) => setLinePrefix(s, "### ") }, + { label: "•", title: "Bulleted list", spec: (s) => setLinePrefix(s, "- ") }, + { label: "1.", title: "Numbered list", spec: (s) => setLinePrefix(s, "1. ") }, + { label: "☐", title: "Checklist", spec: (s) => setLinePrefix(s, "- [ ] ") }, + { label: "❝", title: "Quote", spec: (s) => setLinePrefix(s, "> ") }, + { label: "", title: "Inline code", spec: (s) => toggleWrap(s, "`") }, + { label: "Link", title: "Link", spec: insertLink }, + ]; + return ( +
+ {items.map((i) => ( + + ))} + +
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/docs-api.ts b/apps/web/src/app/w/[workspaceId]/docs/docs-api.ts new file mode 100644 index 0000000..af0cd41 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/docs-api.ts @@ -0,0 +1,42 @@ +"use client"; +import type { DocView, WriteResult } from "@gitwork/server"; + +/** A failed docs call, with the API's code and extra fields (e.g. the current text on a conflict). */ +export class DocsApiError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + readonly data: Record, + ) { + super(message); + } +} + +async function call(method: string, url: string, body?: unknown, init?: RequestInit): Promise { + const res = await fetch(url, { + method, + headers: body === undefined ? undefined : { "content-type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + ...init, + }); + if (res.status === 204) return undefined as T; + const data = (await res.json().catch(() => ({}))) as { error?: { code?: string; message?: string } & Record }; + if (!res.ok) throw new DocsApiError(res.status, data.error?.code ?? "error", data.error?.message ?? `Request failed (${res.status}).`, data.error ?? {}); + return data as T; +} + +export function docsApi(workspaceId: string) { + const base = `/api/v1/workspaces/${workspaceId}/docs`; + const q = (repo: string, path: string, extra = "") => `?repo=${encodeURIComponent(repo)}&path=${encodeURIComponent(path)}${extra}`; + return { + get: (repo: string, path: string) => call<{ doc: DocView }>("GET", `${base}/file${q(repo, path)}`).then((r) => r.doc), + save: (body: { repoNodeId: string; path: string; baseSha: string; text: string; attachments?: { path: string; data: string }[] }) => + call("PUT", `${base}/file`, body), + rename: (body: { repoNodeId: string; path: string; baseSha: string; newPath: string }) => call("POST", `${base}/rename`, body), + remove: (repo: string, path: string, sha: string) => call("DELETE", `${base}/file${q(repo, path, `&sha=${sha}`)}`), + heartbeat: (repoNodeId: string, path: string) => + call<{ editors: { userId: string; name: string }[] }>("POST", `${base}/presence`, { repoNodeId, path }).then((r) => r.editors), + leave: (repo: string, path: string) => call("DELETE", `${base}/presence${q(repo, path)}`, undefined, { keepalive: true }), + }; +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/docs-tree.tsx b/apps/web/src/app/w/[workspaceId]/docs/docs-tree.tsx new file mode 100644 index 0000000..21f5d87 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/docs-tree.tsx @@ -0,0 +1,180 @@ +"use client"; +import type { DocFileView, DocRepoView } from "@gitwork/server"; +import Link from "next/link"; +import { useParams, useRouter } from "next/navigation"; +import { useMemo, useState } from "react"; +import { Button, ErrorText, Input } from "@/components/kit"; +import { api } from "@/lib/api"; +import { decodeSegment, docHref, rawHref } from "./links"; + +interface Folder { + name: string; + path: string; + folders: Map; + files: DocFileView[]; +} + +function buildTree(repo: DocRepoView): Folder { + const root: Folder = { name: repo.root, path: repo.root, folders: new Map(), files: [] }; + for (const file of repo.files) { + const parts = file.path.slice(repo.root.length + 1).split("/"); + let folder = root; + for (const part of parts.slice(0, -1)) { + let next = folder.folders.get(part); + if (!next) { + next = { name: part, path: `${folder.path}/${part}`, folders: new Map(), files: [] }; + folder.folders.set(part, next); + } + folder = next; + } + folder.files.push(file); + } + return root; +} + +const STATUS_TEXT: Record = { + ok: "", + unsynced: "Not loaded from GitHub yet.", + missing: "This folder does not exist on the branch yet. Create a doc to start it.", + unavailable: "The GitHub App cannot reach this repo right now.", +}; + +export function DocsTree(props: { workspaceId: string; linked: boolean; repos: DocRepoView[]; canWrite: boolean }) { + const router = useRouter(); + const params = useParams<{ repoNodeId?: string; path?: string[] }>(); + const current = params.repoNodeId && params.path ? `${decodeSegment(params.repoNodeId)}:${params.path.map(decodeSegment).join("/")}` : null; + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [creating, setCreating] = useState(null); + const [name, setName] = useState(""); + + async function refresh() { + setBusy(true); + setError(""); + try { + await api("POST", `/workspaces/${props.workspaceId}/docs/refresh`); + router.refresh(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + } + + async function create(repo: DocRepoView) { + const clean = name.trim().replace(/^\/+/, ""); + if (!clean) return; + const path = `${repo.root}/${/\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`}`; + setBusy(true); + setError(""); + try { + await api("POST", `/workspaces/${props.workspaceId}/docs/file`, { repoNodeId: repo.repoNodeId, path }); + setCreating(null); + setName(""); + router.push(docHref(props.workspaceId, repo.repoNodeId, path)); + router.refresh(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + } + + if (!props.linked) return null; + return ( + + ); +} + +function FolderView(props: { workspaceId: string; repo: DocRepoView; folder: Folder; current: string | null; depth: number }) { + const { folder, repo, depth } = props; + const folders = useMemo(() => [...folder.folders.values()].sort((a, b) => a.name.localeCompare(b.name)), [folder]); + const [open, setOpen] = useState(true); + const body = ( +
    + {folders.map((f) => ( +
  • + +
  • + ))} + {folder.files.map((file) => { + const name = file.path.split("/").pop()!; + const active = props.current === `${repo.repoNodeId}:${file.path}`; + const cls = `flex items-center justify-between gap-2 rounded-md px-2 py-1 ${active ? "bg-muted font-medium" : "text-muted-foreground hover:bg-muted hover:text-foreground"}`; + return ( +
  • + {file.kind === "doc" ? ( + + {name.replace(/\.(md|markdown)$/i, "")} + {file.pending && ( + + PR + + )} + + ) : ( + + {name} + + )} +
  • + ); + })} +
+ ); + if (depth === 0) return body; + return ( +
+ + {open &&
{body}
} +
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/frontmatter-panel.tsx b/apps/web/src/app/w/[workspaceId]/docs/frontmatter-panel.tsx new file mode 100644 index 0000000..166149e --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/frontmatter-panel.tsx @@ -0,0 +1,92 @@ +"use client"; +import { type Frontmatter, type TextChange, addFrontmatterKey, parseFrontmatter, removeFrontmatterKey, setFrontmatterValue } from "@gitwork/core"; +import { useState } from "react"; +import { Input } from "@/components/kit"; + +/** + * Properties from the doc's frontmatter. Each edit is one text change on one line, applied + * through the editor (so undo works and nothing else in the file moves). + */ +export function FrontmatterPanel(props: { text: string; readOnly: boolean; lineBreak: string; onChange: (change: TextChange) => void }) { + const fm: Frontmatter | null = parseFrontmatter(props.text); + const [adding, setAdding] = useState(false); + const [key, setKey] = useState(""); + const [value, setValue] = useState(""); + const [error, setError] = useState(""); + if (!fm && props.readOnly) return null; + + const apply = (change: TextChange | null, message: string) => { + if (!change) return setError(message); + setError(""); + props.onChange(change); + }; + + return ( +
+ {fm && fm.entries.length > 0 && ( +
+ {fm.entries.map((e) => ( +
+
{e.key}
+
+ {e.editable && !props.readOnly ? ( + { + if (ev.key === "Enter") (ev.target as HTMLInputElement).blur(); + }} + onBlur={(ev) => { + if (ev.target.value !== e.value) apply(setFrontmatterValue(props.text, e.key, ev.target.value), "This value cannot change here."); + }} + /> + ) : ( + + {e.value || "—"} + + )} +
+
+ {!props.readOnly && ( + + )} +
+
+ ))} +
+ )} + {!props.readOnly && + (adding ? ( +
{ + ev.preventDefault(); + apply(addFrontmatterKey(props.text, key.trim(), value, props.lineBreak), "Use letters, digits, - and _ for a new property name, and no duplicates."); + setKey(""); + setValue(""); + setAdding(false); + }} + > + setKey(e.target.value)} className="h-7 w-32" autoFocus /> + setValue(e.target.value)} className="h-7" /> + +
+ ) : ( + + ))} + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/layout.tsx b/apps/web/src/app/w/[workspaceId]/docs/layout.tsx new file mode 100644 index 0000000..980964b --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/layout.tsx @@ -0,0 +1,17 @@ +import { can } from "@gitwork/core"; +import { listDocs } from "@gitwork/server"; +import { requireWorkspacePage } from "@/server/pages"; +import { DocsTree } from "./docs-tree"; + +/** The doc tree beside every doc. Reads the cache only; GitHub is never called from a render. */ +export default async function DocsLayout({ children, params }: LayoutProps<"/w/[workspaceId]/docs">) { + const { workspaceId } = await params; + const { access, db } = await requireWorkspacePage(workspaceId, `/w/${workspaceId}/docs`); + const docs = await listDocs(db, access); + return ( +
+ +
{children}
+
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/links.ts b/apps/web/src/app/w/[workspaceId]/docs/links.ts new file mode 100644 index 0000000..ef08fca --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/links.ts @@ -0,0 +1,17 @@ +/** URLs of the docs pages. Each path segment is encoded on its own. */ +export function docHref(workspaceId: string, repoNodeId: string, path: string): string { + return `/w/${workspaceId}/docs/${encodeURIComponent(repoNodeId)}/${path.split("/").map(encodeURIComponent).join("/")}`; +} + +export function rawHref(workspaceId: string, repoNodeId: string, path: string): string { + return `/api/v1/workspaces/${workspaceId}/docs/raw?repo=${encodeURIComponent(repoNodeId)}&path=${encodeURIComponent(path)}`; +} + +/** Route params arrive encoded on some runtimes and decoded on others. */ +export function decodeSegment(segment: string): string { + try { + return decodeURIComponent(segment); + } catch { + return segment; + } +} diff --git a/apps/web/src/app/w/[workspaceId]/docs/page.tsx b/apps/web/src/app/w/[workspaceId]/docs/page.tsx new file mode 100644 index 0000000..27aaf09 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/docs/page.tsx @@ -0,0 +1,39 @@ +import Link from "next/link"; +import { listDocs } from "@gitwork/server"; +import { Card } from "@/components/kit"; +import { requireWorkspacePage } from "@/server/pages"; +import { docHref } from "./links"; + +export default async function DocsIndexPage({ params }: PageProps<"/w/[workspaceId]/docs">) { + const { workspaceId } = await params; + const { access, db } = await requireWorkspacePage(workspaceId, `/w/${workspaceId}/docs`); + const docs = await listDocs(db, access); + if (!docs.linked) { + return ( + +

+ Docs come from the docs/ folder of each linked repo. Link this workspace to GitHub repos in{" "} + + Settings + {" "} + first. +

+
+ ); + } + // The first doc of the first repo, so the page is never empty when docs exist. + const first = docs.repos.flatMap((r) => r.files.filter((f) => f.kind === "doc").map((f) => ({ repo: r.repoNodeId, path: f.path })))[0]; + return ( + +

Docs

+

Pick a doc on the left. Every save is a commit to the repo on GitHub.

+ {first && ( +

+ + Open {first.path} + +

+ )} +
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/settings/page.tsx b/apps/web/src/app/w/[workspaceId]/settings/page.tsx index 4e60cdd..ea25086 100644 --- a/apps/web/src/app/w/[workspaceId]/settings/page.tsx +++ b/apps/web/src/app/w/[workspaceId]/settings/page.tsx @@ -1,11 +1,11 @@ import { authorize, can } from "@gitwork/core"; -import { getWorkspaceLink, resolveMapping } from "@gitwork/server"; +import { getWorkspaceLink, resolveMapping, workspaceDocRepos } from "@gitwork/server"; import Link from "next/link"; import { notFound } from "next/navigation"; import { Card } from "@/components/kit"; import { getDeps } from "@/server/context"; import { requireWorkspacePage } from "@/server/pages"; -import { FieldMappingPanel, GitHubLinkPanel, VisibilityPanel } from "./settings-panels"; +import { DocFoldersPanel, DocReviewPanel, FieldMappingPanel, GitHubLinkPanel, VisibilityPanel } from "./settings-panels"; export default async function WorkspaceSettingsPage({ params }: PageProps<"/w/[workspaceId]/settings">) { const { workspaceId } = await params; @@ -16,6 +16,7 @@ export default async function WorkspaceSettingsPage({ params }: PageProps<"/w/[w const { github: app } = await getDeps(); const data = await getWorkspaceLink(db, workspaceId); const fields = data?.fields.map((f) => ({ id: f.nodeId, name: f.name, dataType: f.dataType })) ?? []; + const docRepos = data ? await workspaceDocRepos(db, workspaceId) : []; return ( <> @@ -56,16 +57,32 @@ export default async function WorkspaceSettingsPage({ params }: PageProps<"/w/[w )} + {data && github.ok && docRepos.length > 0 && ( + +

Docs folders

+ ({ nodeId: r.repoNodeId, fullName: r.fullName, path: r.path, branch: r.branch, defaultBranch: r.defaultBranch }))} + /> +
+ )} {canSettings && (

What Read Only members see

)} + {canSettings && ( + +

Doc edits

+ +
+ )} ); diff --git a/apps/web/src/app/w/[workspaceId]/settings/settings-panels.tsx b/apps/web/src/app/w/[workspaceId]/settings/settings-panels.tsx index 626c5b0..c45c4d7 100644 --- a/apps/web/src/app/w/[workspaceId]/settings/settings-panels.tsx +++ b/apps/web/src/app/w/[workspaceId]/settings/settings-panels.tsx @@ -210,16 +210,19 @@ export function FieldMappingPanel(props: { workspaceId: string; fields: { id: st ); } -export function VisibilityPanel(props: { workspaceId: string; hideLabel: string; showDraftsToReadOnly: boolean }) { +export function VisibilityPanel(props: { workspaceId: string; hideLabel: string; hideFolder: string; showDraftsToReadOnly: boolean }) { const { error, busy, run } = useRun(); const [hideLabel, setHideLabel] = useState(props.hideLabel); + const [hideFolder, setHideFolder] = useState(props.hideFolder); const [drafts, setDrafts] = useState(props.showDraftsToReadOnly); return (
{ e.preventDefault(); - void run(() => api("PATCH", `/workspaces/${props.workspaceId}/settings`, { hideLabel: hideLabel || null, showDraftsToReadOnly: drafts })); + void run(() => + api("PATCH", `/workspaces/${props.workspaceId}/settings`, { hideLabel: hideLabel || null, hideFolder: hideFolder || null, showDraftsToReadOnly: drafts }), + ); }} >
@@ -227,6 +230,13 @@ export function VisibilityPanel(props: { workspaceId: string; hideLabel: string; setHideLabel(e.target.value)} />

Read Only members never see these issues. Empty hides nothing.

+
+ + setHideFolder(e.target.value)} /> +

+ Inside each repo's docs folder: “internal” hides docs/internal/. Read Only members never see these files. Empty hides nothing. +

+
setDrafts(on === true)} /> @@ -238,3 +248,73 @@ export function VisibilityPanel(props: { workspaceId: string; hideLabel: string; ); } + +/** Review mode (decision 008): App doc writes open a pull request instead of a commit. */ +export function DocReviewPanel(props: { workspaceId: string; reviewBotDocEdits: boolean }) { + const { error, busy, run } = useRun(); + const [on, setOn] = useState(props.reviewBotDocEdits); + return ( +
{ + e.preventDefault(); + void run(() => api("PATCH", `/workspaces/${props.workspaceId}/settings`, { reviewBotDocEdits: on })); + }} + > +
+ setOn(v === true)} /> + +
+

Their saves open a pull request instead of committing. People who linked GitHub still commit as themselves.

+ {error} + +
+ ); +} + +/** Each repo's docs folder and branch (decision 011). */ +export function DocFoldersPanel(props: { workspaceId: string; repos: { nodeId: string; fullName: string; path: string; branch: string; defaultBranch: boolean }[] }) { + return ( +
+ {props.repos.map((r) => ( + + ))} +
+ ); +} + +function DocFolderRow(props: { workspaceId: string; repo: { nodeId: string; fullName: string; path: string; branch: string; defaultBranch: boolean } }) { + const { error, busy, run } = useRun(); + const [path, setPath] = useState(props.repo.path); + const [branch, setBranch] = useState(props.repo.defaultBranch ? "" : props.repo.branch); + const id = props.repo.nodeId.replace(/[^\w-]/g, "_"); + return ( +
{ + e.preventDefault(); + void run(() => + api("PATCH", `/workspaces/${props.workspaceId}/github/repos/${encodeURIComponent(props.repo.nodeId)}/docs`, { docsPath: path, docsBranch: branch || null }), + ); + }} + > +

{props.repo.fullName}

+
+ + setPath(e.target.value)} placeholder="docs" /> +
+
+ + setBranch(e.target.value)} placeholder={props.repo.defaultBranch ? `${props.repo.branch} (default)` : "default branch"} /> +
+ +
+ {error} +
+
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/workspace-shell.tsx b/apps/web/src/app/w/[workspaceId]/workspace-shell.tsx index 641dc5b..222d39f 100644 --- a/apps/web/src/app/w/[workspaceId]/workspace-shell.tsx +++ b/apps/web/src/app/w/[workspaceId]/workspace-shell.tsx @@ -54,6 +54,7 @@ function Sidebar({ workspaceId, name, role, email }: { workspaceId: string; name const base = `/w/${workspaceId}`; const links = [ { href: base, label: "Tasks", active: pathname === base || pathname.startsWith(`${base}/tasks`) }, + { href: `${base}/docs`, label: "Docs", active: pathname.startsWith(`${base}/docs`) }, { href: `${base}/members`, label: "Members", active: pathname === `${base}/members` }, ...(role === "owner" || role === "admin" ? [{ href: `${base}/settings`, label: "Settings", active: pathname === `${base}/settings` }] : []), ]; diff --git a/apps/web/src/lib/doc-editor.test.ts b/apps/web/src/lib/doc-editor.test.ts new file mode 100644 index 0000000..659b617 --- /dev/null +++ b/apps/web/src/lib/doc-editor.test.ts @@ -0,0 +1,51 @@ +import { type FixtureCase, bytesEqual, bytesToText, decodeBase64, opChange, textToBytes } from "@gitwork/core"; +import fixtures from "@gitwork/core/fixtures/docs/round-trip.json"; +import { describe, expect, it } from "vitest"; +import { changeSpec, createDocState, docText } from "./doc-editor"; + +const cases = (fixtures.cases as FixtureCase[]).filter((c) => c.editable !== false); + +describe.each(cases)("CodeMirror round trip: $name", (c) => { + it("keeps the file's bytes with no edit", () => { + const state = createDocState(c.input!); + expect(docText(state)).toBe(c.input); + expect(state.lineBreak).toBe(c.separator); + expect(bytesEqual(textToBytes(docText(state)), textToBytes(c.input!))).toBe(true); + }); + + it("applies the fixture ops as editor transactions", () => { + let state = createDocState(c.input!); + for (const op of c.ops ?? []) { + const change = opChange(docText(state), op); + if (!change) continue; + state = state.update(changeSpec(state, change)).state; + } + expect(docText(state)).toBe(c.expected); + }); +}); + +describe("typed and pasted line breaks", () => { + it("become CRLF in a CRLF file", () => { + const state = createDocState("a\r\nb\r\n"); + const next = state.update({ changes: { from: 1, insert: "\nx\ny" }, userEvent: "input.paste" }).state; + expect(docText(next)).toBe("a\r\nx\r\ny\r\nb\r\n"); + }); + + it("become LF in an LF file, even when pasted as CRLF", () => { + const state = createDocState("a\nb\n"); + const next = state.update({ changes: { from: 1, insert: "\r\nx" }, userEvent: "input.paste" }).state; + expect(docText(next)).toBe("a\nx\nb\n"); + }); + + it("leave untouched mixed lines as they were", () => { + const state = createDocState("a\r\nb\nc\r\n"); + const next = state.update({ changes: { from: state.doc.line(2).to, insert: "\nnew" }, userEvent: "input.type" }).state; + expect(docText(next)).toBe("a\r\nb\nnew\nc\r\n"); + }); +}); + +describe("invalid UTF-8", () => { + it("is refused before it reaches the editor", () => { + expect(bytesToText(decodeBase64("IyD/Cg=="))).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/doc-editor.ts b/apps/web/src/lib/doc-editor.ts new file mode 100644 index 0000000..f5354b9 --- /dev/null +++ b/apps/web/src/lib/doc-editor.ts @@ -0,0 +1,64 @@ +/** + * CodeMirror state for byte-exact docs (decision 011). Framework-free, so the shared round-trip + * fixtures run against it in Vitest without a browser. + * + * CodeMirror splits lines on \r\n, \r, and \n and joins them with \n unless told otherwise, which + * would rewrite every CRLF file on the first save. So the separator is always set explicitly: + * "\r\n" when every break is CRLF, else "\n" (a stray \r stays part of its line's text). Typed and + * pasted text gets the file's separator, so a new line never mixes styles into an old file. + */ +import { type Extension, EditorState, Transaction, type TransactionSpec } from "@codemirror/state"; +import { type LineSeparator, type TextChange, lineSeparatorOf, offsetToEditorPos } from "@gitwork/core"; + +/** Rewrites line breaks in inserted text to the file's separator. */ +export function separatorFilter(separator: LineSeparator): Extension { + return EditorState.transactionFilter.of((tr) => { + if (!tr.docChanged || !(tr.isUserEvent("input") || tr.isUserEvent("paste") || tr.isUserEvent("drop"))) return tr; + let needs = false; + tr.changes.iterChanges((_a, _b, _c, _d, inserted) => { + for (let i = 1; i <= inserted.lines && !needs; i++) { + const line = inserted.line(i).text; + if (separator === "\r\n" ? /[\r\n]/.test(line) : /\r$/.test(line) && i < inserted.lines) needs = true; + } + }); + if (!needs) return tr; + const changes: { from: number; to: number; insert: string }[] = []; + tr.changes.iterChanges((fromA, toA, _fb, _tb, inserted) => { + const raw = inserted.sliceString(0, inserted.length, "\n"); + changes.push({ from: fromA, to: toA, insert: raw.replace(/\r\n|\r|\n/g, separator) }); + }); + // The state splits inserted text on its own separator only, so insert exactly that. + return [{ changes, selection: tr.selection, scrollIntoView: tr.scrollIntoView, userEvent: tr.annotation(Transaction.userEvent) } as TransactionSpec]; + }); +} + +export function docExtensions(text: string): Extension[] { + const separator = lineSeparatorOf(text); + return [EditorState.lineSeparator.of(separator), separatorFilter(separator)]; +} + +/** + * The file text. Never `state.doc.toString()`: that always joins lines with "\n". + * `sliceDoc` joins them with the state's separator. + */ +export function docText(state: EditorState): string { + return state.sliceDoc(); +} + +/** A state whose `docText` is exactly `text`. */ +export function createDocState(text: string, extensions: Extension[] = []): EditorState { + return EditorState.create({ doc: text, extensions: [...docExtensions(text), ...extensions] }); +} + +/** A change in string offsets (core helpers) as a transaction on the editor's positions. */ +export function changeSpec(state: EditorState, change: TextChange): TransactionSpec { + const text = docText(state); + const separator = state.lineBreak === "\r\n" ? "\r\n" : "\n"; + return { + changes: { + from: offsetToEditorPos(text, change.from, separator), + to: offsetToEditorPos(text, change.to, separator), + insert: change.insert, + }, + }; +} diff --git a/apps/web/src/lib/live-preview.ts b/apps/web/src/lib/live-preview.ts new file mode 100644 index 0000000..6e30026 --- /dev/null +++ b/apps/web/src/lib/live-preview.ts @@ -0,0 +1,289 @@ +/** + * Live preview (decision 011, decision 037): the editor shows formatted text and hides markdown + * marks on every line the cursor is not on. Only decorations change; the text itself never does, + * so the round-trip guarantee holds. On the cursor's lines the source shows for editing. + */ +import { HighlightStyle, syntaxTree } from "@codemirror/language"; +import { offsetToEditorPos, parseFrontmatter } from "@gitwork/core"; +import { tags } from "@lezer/highlight"; +import { type EditorState, type Extension, type Range, StateEffect, StateField } from "@codemirror/state"; +import { Decoration, type DecorationSet, EditorView, WidgetType } from "@codemirror/view"; + +export interface LivePreviewOptions { + /** A URL for an image link in the doc, or null to leave the source showing. */ + resolveImage: (src: string) => string | null; +} + +class BulletWidget extends WidgetType { + eq() { + return true; + } + toDOM() { + const span = document.createElement("span"); + span.className = "cm-lp-bullet"; + span.textContent = "•"; + return span; + } +} + +class CheckboxWidget extends WidgetType { + constructor( + readonly checked: boolean, + readonly from: number, + ) { + super(); + } + eq(other: CheckboxWidget) { + return other.checked === this.checked && other.from === this.from; + } + toDOM(view: EditorView) { + const box = document.createElement("input"); + box.type = "checkbox"; + box.className = "cm-lp-task"; + box.checked = this.checked; + box.setAttribute("aria-label", this.checked ? "Done" : "Not done"); + box.addEventListener("mousedown", (e) => { + e.preventDefault(); + if (view.state.readOnly) return; + // "[ ]" ↔ "[x]": one character, the rest of the line stays as it was. + view.dispatch({ changes: { from: this.from + 1, to: this.from + 2, insert: this.checked ? " " : "x" }, userEvent: "input.toggle" }); + }); + return box; + } + ignoreEvent() { + return false; + } +} + +class RuleWidget extends WidgetType { + eq() { + return true; + } + toDOM() { + const hr = document.createElement("hr"); + hr.className = "cm-lp-hr"; + return hr; + } +} + +class ImageWidget extends WidgetType { + constructor( + readonly url: string, + readonly alt: string, + ) { + super(); + } + eq(other: ImageWidget) { + return other.url === this.url && other.alt === this.alt; + } + toDOM() { + const img = document.createElement("img"); + img.className = "cm-lp-image"; + img.src = this.url; + img.alt = this.alt; + img.loading = "lazy"; + return img; + } +} + +const hide = Decoration.replace({}); +const mark = (cls: string) => Decoration.mark({ class: cls }); +const line = (cls: string) => Decoration.line({ class: cls }); + +/** Line numbers any selection range touches. */ +function activeLines(state: EditorState): Set { + const lines = new Set(); + for (const r of state.selection.ranges) { + const first = state.doc.lineAt(r.from).number; + const last = state.doc.lineAt(r.to).number; + for (let n = first; n <= last; n++) lines.add(n); + } + return lines; +} + +function build(state: EditorState, options: LivePreviewOptions, focused: boolean): DecorationSet { + const out: Range[] = []; + // Without focus there is no line being edited: everything renders. + const active = focused ? activeLines(state) : new Set(); + const isActive = (from: number, to: number) => { + const a = state.doc.lineAt(from).number; + const b = state.doc.lineAt(to).number; + for (let n = a; n <= b; n++) if (active.has(n)) return true; + return false; + }; + const text = (from: number, to: number) => state.sliceDoc(from, to); + + // Frontmatter: the properties panel shows it, so rich text hides the block. The parser would + // read it as a rule and a setext heading. On the cursor's lines it shows as plain source. + let fmEnd = -1; + const head = state.sliceDoc(0, Math.min(state.doc.length, 64_000)); + const fm = parseFrontmatter(head); + if (fm) { + const separator = state.lineBreak === "\r\n" ? "\r\n" : "\n"; + const start = head.startsWith("\uFEFF") ? 1 : 0; + const closing = state.doc.lineAt(offsetToEditorPos(head, fm.insertAt, separator)); + fmEnd = closing.to; + if (isActive(start, fmEnd)) { + for (let pos = start; pos <= fmEnd; ) { + const l = state.doc.lineAt(pos); + out.push(line("cm-lp-frontmatter").range(l.from)); + pos = l.to + 1; + } + } else { + out.push(Decoration.replace({ block: true }).range(state.doc.lineAt(start).from, fmEnd)); + } + } + + syntaxTree(state).iterate({ + from: fmEnd + 1, + enter(node) { + const { from, to, name } = node; + if (from <= fmEnd) return; + const heading = /^ATXHeading(\d)$/.exec(name); + if (heading) { + out.push(line(`cm-lp-h cm-lp-h${heading[1]}`).range(state.doc.lineAt(from).from)); + return; + } + switch (name) { + case "HeaderMark": { + if (isActive(from, to) || node.node.parent?.name.startsWith("SetextHeading")) return; + // The marks and the space after them. + const end = text(to, to + 1) === " " ? to + 1 : to; + out.push(hide.range(from, end)); + return; + } + case "Emphasis": + out.push(mark("cm-lp-em").range(from, to)); + return; + case "StrongEmphasis": + out.push(mark("cm-lp-strong").range(from, to)); + return; + case "Strikethrough": + out.push(mark("cm-lp-strike").range(from, to)); + return; + case "InlineCode": + out.push(mark("cm-lp-code").range(from, to)); + return; + case "Link": + out.push(mark("cm-lp-link").range(from, to)); + return; + case "EmphasisMark": + case "StrikethroughMark": + if (!isActive(from, to)) out.push(hide.range(from, to)); + return; + case "CodeMark": + // Inline code only; a fenced block keeps its fences. + if (node.node.parent?.name === "InlineCode" && !isActive(from, to)) out.push(hide.range(from, to)); + return; + case "LinkMark": + case "URL": + case "LinkTitle": + if (node.node.parent?.name === "Link" && !isActive(from, to)) out.push(hide.range(from, to)); + return; + case "Image": { + if (isActive(from, to)) return false; + const source = text(from, to); + const m = /^!\[([^\]]*)\]\(\s*)]+)>?/.exec(source); + const url = m ? options.resolveImage(m[2]!) : null; + if (url) out.push(Decoration.replace({ widget: new ImageWidget(url, m![1]!) }).range(from, to)); + return false; + } + case "Blockquote": { + for (let pos = from; pos <= to; ) { + const l = state.doc.lineAt(pos); + out.push(line("cm-lp-quote").range(l.from)); + pos = l.to + 1; + } + return; + } + case "QuoteMark": { + if (isActive(from, to)) return; + const end = text(to, to + 1) === " " ? to + 1 : to; + out.push(hide.range(from, end)); + return; + } + case "ListMark": { + if (isActive(from, to) || node.node.parent?.parent?.name !== "BulletList") return; + // A task item shows only its checkbox. + const task = /^\s\[[ xX]\]/.test(text(to, to + 4)); + out.push((task ? hide : Decoration.replace({ widget: new BulletWidget() })).range(from, task ? to + 1 : to)); + return; + } + case "TaskMarker": { + if (isActive(from, to)) return; + const checked = /x/i.test(text(from, to)); + out.push(Decoration.replace({ widget: new CheckboxWidget(checked, from) }).range(from, to)); + return; + } + case "HorizontalRule": + if (!isActive(from, to)) out.push(Decoration.replace({ widget: new RuleWidget() }).range(from, to)); + return; + case "FencedCode": { + for (let pos = from; pos <= to; ) { + const l = state.doc.lineAt(pos); + out.push(line("cm-lp-codeblock").range(l.from)); + pos = l.to + 1; + } + return; + } + } + }, + }); + return Decoration.set(out, true); +} + +/** Live preview as one extension. Pass it inside a Compartment to switch to plain source. */ +export function livePreview(options: LivePreviewOptions): Extension { + const field = StateField.define({ + create: (state) => build(state, options, false), + update(value, tr) { + if (tr.docChanged || tr.selection || tr.effects.length > 0 || syntaxTree(tr.startState) !== syntaxTree(tr.state)) { + return build(tr.state, options, focusedOf(tr.state)); + } + return value; + }, + provide: (f) => [EditorView.decorations.from(f), EditorView.atomicRanges.of((view) => view.state.field(f))], + }); + return [focusState, field, focusTracker, previewTheme]; +} + +// Focus lives in state so the field can read it: blur renders every line. +const setFocus = StateEffect.define(); +const focusState = StateField.define({ + create: () => false, + update: (value, tr) => tr.effects.reduce((v, e) => (e.is(setFocus) ? e.value : v), value), +}); +const focusedOf = (state: EditorState) => state.field(focusState, false) ?? false; +const focusTracker = EditorView.focusChangeEffect.of((_state, focusing) => setFocus.of(focusing)); + +/** Source highlighting for both views. No underlined headings (CodeMirror's default style). */ +export const markdownHighlight = HighlightStyle.define([ + { tag: tags.heading, fontWeight: "650" }, + { tag: tags.emphasis, fontStyle: "italic" }, + { tag: tags.strong, fontWeight: "650" }, + { tag: tags.strikethrough, textDecoration: "line-through" }, + { tag: tags.link, textDecoration: "underline", textUnderlineOffset: "2px" }, + { tag: [tags.url, tags.processingInstruction, tags.meta, tags.contentSeparator, tags.labelName], color: "var(--muted-foreground)" }, + { tag: tags.monospace, fontFamily: "var(--font-mono, ui-monospace, monospace)", fontSize: "0.92em" }, + { tag: tags.quote, color: "var(--muted-foreground)" }, +]); + +const previewTheme = EditorView.baseTheme({ + ".cm-lp-frontmatter": { fontFamily: "var(--font-mono, ui-monospace, monospace)", fontSize: "0.85em", color: "var(--muted-foreground)" }, + ".cm-lp-h": { fontWeight: "650", lineHeight: "1.3" }, + ".cm-lp-h1": { fontSize: "1.75em", paddingTop: "0.4em" }, + ".cm-lp-h2": { fontSize: "1.4em", paddingTop: "0.35em" }, + ".cm-lp-h3": { fontSize: "1.2em", paddingTop: "0.3em" }, + ".cm-lp-h4, .cm-lp-h5, .cm-lp-h6": { fontSize: "1.05em" }, + ".cm-lp-em": { fontStyle: "italic" }, + ".cm-lp-strong": { fontWeight: "650" }, + ".cm-lp-strike": { textDecoration: "line-through" }, + ".cm-lp-code": { fontFamily: "var(--font-mono, ui-monospace, monospace)", fontSize: "0.9em", background: "var(--muted)", borderRadius: "4px", padding: "0 3px" }, + ".cm-lp-link": { color: "var(--primary)", textDecoration: "underline", textUnderlineOffset: "2px" }, + ".cm-lp-quote": { borderLeft: "3px solid var(--border)", paddingLeft: "12px !important", color: "var(--muted-foreground)" }, + ".cm-lp-codeblock": { fontFamily: "var(--font-mono, ui-monospace, monospace)", fontSize: "0.9em", background: "var(--muted)" }, + ".cm-lp-bullet": { display: "inline-block", width: "1ch", color: "var(--muted-foreground)" }, + ".cm-lp-task": { verticalAlign: "middle", margin: "0 4px 0 0", cursor: "pointer" }, + ".cm-lp-hr": { border: "none", borderTop: "1px solid var(--border)", margin: "0.6em 0" }, + ".cm-lp-image": { display: "block", maxWidth: "100%", maxHeight: "480px", margin: "6px 0", borderRadius: "6px" }, +}); diff --git a/apps/web/src/lib/markdown-commands.test.ts b/apps/web/src/lib/markdown-commands.test.ts new file mode 100644 index 0000000..9df421a --- /dev/null +++ b/apps/web/src/lib/markdown-commands.test.ts @@ -0,0 +1,33 @@ +import { EditorSelection, EditorState } from "@codemirror/state"; +import { describe, expect, it } from "vitest"; +import { insertLink, setLinePrefix, toggleWrap } from "./markdown-commands"; + +const at = (doc: string, from: number, to = from) => EditorState.create({ doc, selection: EditorSelection.single(from, to), extensions: EditorState.allowMultipleSelections.of(true) }); +const apply = (state: EditorState, spec: ReturnType) => state.update(spec).state.sliceDoc(); + +describe("markdown commands", () => { + it("wraps and unwraps bold", () => { + expect(apply(at("say hi", 4, 6), toggleWrap(at("say hi", 4, 6), "**"))).toBe("say **hi**"); + const s = at("say **hi**", 6, 8); + expect(apply(s, toggleWrap(s, "**"))).toBe("say hi"); + }); + + it("sets, swaps, and removes a line prefix on every selected line only", () => { + const doc = "one\r\ntwo\r\nthree"; + const s = EditorState.create({ doc, selection: EditorSelection.single(0, 7), extensions: EditorState.lineSeparator.of("\r\n") }); + expect(apply(s, setLinePrefix(s, "- "))).toBe("- one\r\n- two\r\nthree"); + const h = at("- item", 2); + expect(apply(h, setLinePrefix(h, "## "))).toBe("## item"); + const again = at("## item", 3); + expect(apply(again, setLinePrefix(again, "## "))).toBe("item"); + const indented = at(" - nested", 5); + expect(apply(indented, setLinePrefix(indented, "- [ ] "))).toBe(" - [ ] nested"); + }); + + it("inserts a link around the selection", () => { + const s = at("see docs", 4, 8); + const next = s.update(insertLink(s)).state; + expect(next.sliceDoc()).toBe("see [docs](url)"); + expect(next.sliceDoc(next.selection.main.from, next.selection.main.to)).toBe("url"); + }); +}); diff --git a/apps/web/src/lib/markdown-commands.ts b/apps/web/src/lib/markdown-commands.ts new file mode 100644 index 0000000..d181fce --- /dev/null +++ b/apps/web/src/lib/markdown-commands.ts @@ -0,0 +1,69 @@ +/** + * Toolbar and shortcut commands. Each one is a small text edit on the source, so the file stays + * plain markdown and only the touched lines change. + */ +import { EditorSelection, type EditorState, type TransactionSpec } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; + +/** Wraps each selection in `mark` (e.g. "**"), or unwraps it when it is already wrapped. */ +export function toggleWrap(state: EditorState, mark: string): TransactionSpec { + return state.changeByRange((range) => { + const before = state.sliceDoc(range.from - mark.length, range.from); + const after = state.sliceDoc(range.to, range.to + mark.length); + if (before === mark && after === mark) { + return { + changes: [ + { from: range.from - mark.length, to: range.from }, + { from: range.to, to: range.to + mark.length }, + ], + range: EditorSelection.range(range.from - mark.length, range.to - mark.length), + }; + } + return { + changes: [ + { from: range.from, insert: mark }, + { from: range.to, insert: mark }, + ], + range: EditorSelection.range(range.from + mark.length, range.to + mark.length), + }; + }); +} + +const LINE_PREFIX = /^(\s*)(#{1,6} |> |- \[[ xX]\] |[-*+] |\d+[.)] )?/; + +/** Sets each selected line's block prefix ("# ", "- ", "> " …). The same prefix again removes it. */ +export function setLinePrefix(state: EditorState, prefix: string): TransactionSpec { + const changes: { from: number; to: number; insert: string }[] = []; + const seen = new Set(); + for (const range of state.selection.ranges) { + for (let pos = range.from; pos <= range.to; ) { + const line = state.doc.lineAt(pos); + if (!seen.has(line.number)) { + seen.add(line.number); + const m = LINE_PREFIX.exec(line.text)!; + const indent = m[1]!.length; + const current = m[2] ?? ""; + changes.push({ from: line.from + indent, to: line.from + indent + current.length, insert: current === prefix ? "" : prefix }); + } + pos = line.to + 1; + } + } + return { changes }; +} + +/** "[text](url)" around the selection, with the cursor in the url. */ +export function insertLink(state: EditorState): TransactionSpec { + return state.changeByRange((range) => { + const label = state.sliceDoc(range.from, range.to) || "link"; + const insert = `[${label}](url)`; + const urlFrom = range.from + label.length + 3; + return { changes: { from: range.from, to: range.to, insert }, range: EditorSelection.range(urlFrom, urlFrom + 3) }; + }); +} + +export function run(view: EditorView, spec: (state: EditorState) => TransactionSpec) { + if (view.state.readOnly) return false; + view.dispatch(view.state.update(spec(view.state), { userEvent: "input.format", scrollIntoView: true })); + view.focus(); + return true; +} diff --git a/packages/core/src/docs/paths.test.ts b/packages/core/src/docs/paths.test.ts index 1f069e3..017f516 100644 --- a/packages/core/src/docs/paths.test.ts +++ b/packages/core/src/docs/paths.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { imageType, isUnderRoot, normalizeDocPath, normalizeRoot, resolveRelative, safeFileName } from "./paths"; +import { imageType, isUnderRoot, normalizeDocPath, normalizeRoot, relativeLink, resolveRelative, safeFileName } from "./paths"; import { docVisibilityContext, isDocVisible } from "../visibility"; describe("doc paths", () => { @@ -38,6 +38,16 @@ describe("doc paths", () => { expect(resolveRelative("docs/a.md", "%E0%A4%A")).toBeNull(); }); + it("makes relative links that resolve back to the same file", () => { + expect(relativeLink("docs/guide/a.md", "docs/assets/x.png")).toBe("../assets/x.png"); + expect(relativeLink("docs/a.md", "docs/assets/my shot.png")).toBe("assets/my%20shot.png"); + expect(relativeLink("docs/a.md", "docs/x (1).png")).toBe("x%20%281%29.png"); + expect(relativeLink("docs/a/b/c.md", "docs/a/b/d.png")).toBe("d.png"); + for (const [from, to] of [["docs/guide/a.md", "docs/assets/x (1).png"], ["docs/a.md", "docs/a/b.png"], ["docs/x/y/z.md", "docs/q.png"]] as const) { + expect(resolveRelative(from, relativeLink(from, to))).toBe(to); + } + }); + it("knows image types and makes safe upload names", () => { expect(imageType("a/B.PNG")).toBe("image/png"); expect(imageType("a/b.svg")).toBe("image/svg+xml"); diff --git a/packages/core/src/docs/paths.ts b/packages/core/src/docs/paths.ts index eb747ac..303bbff 100644 --- a/packages/core/src/docs/paths.ts +++ b/packages/core/src/docs/paths.ts @@ -95,3 +95,18 @@ export function safeFileName(input: string): string { const ext = dot > 0 ? name.slice(dot + 1).toLowerCase().replace(/[^a-z0-9]/g, "") : ""; return `${base || "image"}${ext ? `.${ext}` : ""}`; } + +/** A relative link from one doc to another file ("docs/guide/a.md" → "docs/assets/x.png" = "../assets/x.png"). */ +export function relativeLink(fromDocPath: string, toPath: string): string { + const from = fromDocPath.split("/").slice(0, -1); + const to = toPath.split("/"); + let common = 0; + while (common < from.length && common < to.length - 1 && from[common] === to[common]) common++; + const up = from.length - common; + const rel = [...Array(up).fill(".."), ...to.slice(common)].join("/"); + // Spaces and parentheses would end a markdown link early. + return rel + .split("/") + .map((s) => (s === ".." ? s : encodeURIComponent(s).replace(/[()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`))) + .join("/"); +} diff --git a/packages/server/src/api/routes.ts b/packages/server/src/api/routes.ts index fc39a6e..aa972dd 100644 --- a/packages/server/src/api/routes.ts +++ b/packages/server/src/api/routes.ts @@ -36,6 +36,7 @@ import { workspaceDocRepos, } from "../services/docs"; import { type RouteContext, createApiHandler, route } from "./router"; +import type { GitHubClient } from "../github/client"; /** GitHub-backed services need the App; before /setup there is none. */ function githubDeps(ctx: RouteContext) { @@ -48,6 +49,19 @@ function taskDeps(ctx: RouteContext) { return { ...githubDeps(ctx), displayName: user.name?.trim() || user.email }; } +/** Calls GitHub only when it must: without the App, cached docs still open. */ +const NO_GITHUB = new Proxy({} as GitHubClient, { + get() { + return () => { + throw conflict("github_not_setup", "The GitHub App is not set up on this instance yet."); + }; + }, +}); + +function readDeps(ctx: RouteContext) { + return { db: ctx.deps.database.db, client: ctx.deps.github?.client ?? NO_GITHUB, auth: ctx.deps.auth }; +} + function docDeps(ctx: RouteContext) { const user = ctx.session!.user; return { ...githubDeps(ctx), author: { name: user.name?.trim() || user.email, email: user.email } }; @@ -224,7 +238,7 @@ export const routes = [ async handler(ctx) { const access = await requireWorkspaceAccess(ctx.deps.database.db, ctx.session!.user.id, ctx.params.workspaceId!); const q = fileQuery(ctx.request); - return { doc: await getDoc(githubDeps(ctx), access, q.repo, q.path) }; + return { doc: await getDoc(readDeps(ctx), access, q.repo, q.path) }; }, }), diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index fa9dbdf..5942013 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -63,3 +63,12 @@ export { } from "./github/setup"; export { handleGitHubWebhook } from "./github/webhooks"; export { type RequestDepsInput, createRequestDeps } from "./deps"; +export { + type DocFileView, + type DocRepoView, + type DocView, + type Editor, + type WriteResult, + listDocs, + workspaceDocRepos, +} from "./services/docs"; diff --git a/packages/server/src/services/docs.ts b/packages/server/src/services/docs.ts index 8de6ed6..90bd5ff 100644 --- a/packages/server/src/services/docs.ts +++ b/packages/server/src/services/docs.ts @@ -241,7 +241,7 @@ async function resolveFile(db: Db, access: WorkspaceAccess, repoNodeId: string, return { repo, path }; } -async function pendingFor(db: Db, repo: DocRepo, path: string) { +async function pendingFor(db: Db, repo: DocRepo, path: string): Promise { const [row] = await db .select() .from(docPendingPrs) @@ -276,6 +276,8 @@ export interface DocView { path: string; /** Relative to the docs folder, for display. */ name: string; + /** The docs folder: uploaded images go to `/assets/`. */ + root: string; branch: string; /** The blob sha the text came from: send it back with a save. */ sha: string; @@ -318,6 +320,7 @@ export async function getDoc(deps: GitHubServiceDeps, access: WorkspaceAccess, r fullName: repo.fullName, path, name: relativeToRoot(path, repo.path), + root: repo.path, branch: pending?.headBranch ?? repo.branch, sha, text, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2b6dbcb..7adb32c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -181,6 +181,27 @@ importers: apps/web: dependencies: + '@codemirror/commands': + specifier: 6.11.1 + version: 6.11.1 + '@codemirror/lang-markdown': + specifier: 6.5.2 + version: 6.5.2 + '@codemirror/language': + specifier: 6.13.1 + version: 6.13.1 + '@codemirror/merge': + specifier: 6.12.3 + version: 6.12.3 + '@codemirror/search': + specifier: 6.7.2 + version: 6.7.2 + '@codemirror/state': + specifier: 6.7.6 + version: 6.7.6 + '@codemirror/view': + specifier: 6.43.15 + version: 6.43.15 '@gitwork/core': specifier: workspace:* version: link:../../packages/core @@ -190,6 +211,12 @@ importers: '@gitwork/server': specifier: workspace:* version: link:../../packages/server + '@lezer/highlight': + specifier: 1.2.5 + version: 1.2.5 + '@lezer/markdown': + specifier: 1.8.1 + version: 1.8.1 '@opennextjs/cloudflare': specifier: 1.20.11 version: 1.20.11(next@16.3.8(@babel/core@7.29.7(supports-color@10.2.2))(@playwright/test@1.64.1)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(supports-color@10.2.2)(wrangler@4.151.0(@cloudflare/workers-types@5.20261013.1)(@types/node@20.19.43)) @@ -838,6 +865,45 @@ packages: '@cloudflare/workers-types@5.20261013.1': resolution: {integrity: sha512-0SfkM/MA+oSIAzFFmjr0wZLH54oeCtugaOn8GpJDBnerQiML+rOPq2W6j6bBGE51o+N4DOd0tvMruLmkAQzlpw==} + '@codemirror/autocomplete@6.20.4': + resolution: {integrity: sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==} + + '@codemirror/commands@6.11.1': + resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==} + + '@codemirror/lang-css@6.3.1': + resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==} + + '@codemirror/lang-html@6.4.12': + resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==} + + '@codemirror/lang-javascript@6.2.5': + resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==} + + '@codemirror/lang-markdown@6.5.2': + resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==} + + '@codemirror/language@6.13.1': + resolution: {integrity: sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==} + + '@codemirror/lint@6.9.8': + resolution: {integrity: sha512-qNvtcE73xUto/D1RvtgSRI4A1Hg8ekxlvtZpjHpdpisLBnhyu82EUEJMEgaxkjuQCA8vqnrylENWKOsEDCOHcw==} + + '@codemirror/merge@6.12.3': + resolution: {integrity: sha512-Wq9wXrp41cW/nIpi1CQPyNwD+36kg8KIX676ym0Hyfn3Dpr+XQHNAIsZYVNlaivuVB4SAASbreG3V0VXinbqZA==} + + '@codemirror/search@6.7.2': + resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==} + + '@codemirror/state@6.7.6': + resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==} + + '@codemirror/streamparser@6.0.0': + resolution: {integrity: sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==} + + '@codemirror/view@6.43.15': + resolution: {integrity: sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==} + '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} @@ -1602,6 +1668,27 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + '@lezer/common@1.5.5': + resolution: {integrity: sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==} + + '@lezer/css@1.3.9': + resolution: {integrity: sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==} + + '@lezer/highlight@1.2.5': + resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==} + + '@lezer/html@1.3.13': + resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==} + + '@lezer/javascript@1.5.6': + resolution: {integrity: sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==} + + '@lezer/lr@1.4.12': + resolution: {integrity: sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ==} + + '@lezer/markdown@1.8.1': + resolution: {integrity: sha512-M5YmEcKWO4mJ45Y1hECwqyu8cLv25EiXOK554PVOvDOWOP0olwelHHQUWr9sjF+d1bENVhy0nfJ8E57XZUTiXg==} + '@libsql/client@0.18.0': resolution: {integrity: sha512-zMCCo58vv7w27j7+cnt/GW+X6/Rih6cHZ86PKi0AxCMOqMfrVgG9OZ5lW2bDMJhSeOjsv2szH2nJF3A9l36UmA==} @@ -1659,6 +1746,9 @@ packages: cpu: [x64] os: [win32] + '@marijn/find-cluster-break@1.0.4': + resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==} + '@modelcontextprotocol/sdk@1.32.1': resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==} engines: {node: '>=18'} @@ -3523,6 +3613,9 @@ packages: resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} engines: {node: '>= 0.10'} + crelt@1.0.7: + resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -5501,6 +5594,9 @@ packages: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} + style-mod@4.1.5: + resolution: {integrity: sha512-WQ2llCZa9sZSkJA+aOwpg5DkfbAXFKGh//t3MRTBeruFiSBC+GXUmbBzrw3bXyboCWAbtCW9InDfBsXrRD/rAg==} + styled-jsx@5.1.6: resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==} engines: {node: '>= 12.0.0'} @@ -5803,6 +5899,9 @@ packages: jsdom: optional: true + w3c-keyname@2.2.8: + resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + web-streams-polyfill@4.0.0-beta.3: resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==} engines: {node: '>= 14'} @@ -6804,6 +6903,103 @@ snapshots: '@cloudflare/workers-types@5.20261013.1': {} + '@codemirror/autocomplete@6.20.4': + dependencies: + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + + '@codemirror/commands@6.11.1': + dependencies: + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + + '@codemirror/lang-css@6.3.1': + dependencies: + '@codemirror/autocomplete': 6.20.4 + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@lezer/common': 1.5.5 + '@lezer/css': 1.3.9 + + '@codemirror/lang-html@6.4.12': + dependencies: + '@codemirror/autocomplete': 6.20.4 + '@codemirror/lang-css': 6.3.1 + '@codemirror/lang-javascript': 6.2.5 + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + '@lezer/css': 1.3.9 + '@lezer/html': 1.3.13 + + '@codemirror/lang-javascript@6.2.5': + dependencies: + '@codemirror/autocomplete': 6.20.4 + '@codemirror/language': 6.13.1 + '@codemirror/lint': 6.9.8 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + '@lezer/javascript': 1.5.6 + + '@codemirror/lang-markdown@6.5.2': + dependencies: + '@codemirror/autocomplete': 6.20.4 + '@codemirror/lang-html': 6.4.12 + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + '@lezer/markdown': 1.8.1 + + '@codemirror/language@6.13.1': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/streamparser': 6.0.0 + '@codemirror/view': 6.43.15 + '@lezer/common': 1.5.5 + '@lezer/highlight': 1.2.5 + '@lezer/lr': 1.4.12 + style-mod: 4.1.5 + + '@codemirror/lint@6.9.8': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + crelt: 1.0.7 + + '@codemirror/merge@6.12.3': + dependencies: + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + '@lezer/highlight': 1.2.5 + style-mod: 4.1.5 + + '@codemirror/search@6.7.2': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.15 + crelt: 1.0.7 + + '@codemirror/state@6.7.6': + dependencies: + '@marijn/find-cluster-break': 1.0.4 + + '@codemirror/streamparser@6.0.0': {} + + '@codemirror/view@6.43.15': + dependencies: + '@codemirror/state': 6.7.6 + crelt: 1.0.7 + style-mod: 4.1.5 + w3c-keyname: 2.2.8 + '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 @@ -7334,6 +7530,39 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 + '@lezer/common@1.5.5': {} + + '@lezer/css@1.3.9': + dependencies: + '@lezer/common': 1.5.5 + '@lezer/highlight': 1.2.5 + '@lezer/lr': 1.4.12 + + '@lezer/highlight@1.2.5': + dependencies: + '@lezer/common': 1.5.5 + + '@lezer/html@1.3.13': + dependencies: + '@lezer/common': 1.5.5 + '@lezer/highlight': 1.2.5 + '@lezer/lr': 1.4.12 + + '@lezer/javascript@1.5.6': + dependencies: + '@lezer/common': 1.5.5 + '@lezer/highlight': 1.2.5 + '@lezer/lr': 1.4.12 + + '@lezer/lr@1.4.12': + dependencies: + '@lezer/common': 1.5.5 + + '@lezer/markdown@1.8.1': + dependencies: + '@lezer/common': 1.5.5 + '@lezer/highlight': 1.2.5 + '@libsql/client@0.18.0': dependencies: '@libsql/core': 0.18.0 @@ -7392,6 +7621,8 @@ snapshots: '@libsql/win32-x64-msvc@0.5.29': optional: true + '@marijn/find-cluster-break@1.0.4': {} + '@modelcontextprotocol/sdk@1.32.1(supports-color@10.2.2)(zod@3.25.76)': dependencies: '@hono/node-server': 2.1.5(hono@4.13.13) @@ -9309,6 +9540,8 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 + crelt@1.0.7: {} + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -11590,6 +11823,8 @@ snapshots: strip-json-comments@3.1.1: {} + style-mod@4.1.5: {} + styled-jsx@5.1.6(@babel/core@7.29.7(supports-color@10.2.2))(react@19.3.0): dependencies: client-only: 0.0.1 @@ -11850,6 +12085,8 @@ snapshots: transitivePeerDependencies: - msw + w3c-keyname@2.2.8: {} + web-streams-polyfill@4.0.0-beta.3: {} webidl-conversions@3.0.1: {} From 619d7f89416cc17c687cd6d102ce3052222bf27e Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Thu, 19 Nov 2026 15:18:26 -0500 Subject: [PATCH 5/5] docs: Phase 4 feature doc, decisions 035-037, STATE, INDEX, roadmap order change Also tests for D1's 100-parameter limit on doc sync and for hidden frontmatter in the rich-text view. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHyaEvdoSPjkLy7T1aaz Signed-off-by: Erik Goins --- CLAUDE.md | 6 +- apps/web/e2e/docs.spec.ts | 3 + docs/INDEX.md | 4 ++ docs/STATE.md | 13 ++-- docs/decisions/035-docs-cache.md | 38 ++++++++++++ docs/decisions/036-doc-writes.md | 43 +++++++++++++ docs/decisions/037-rich-text-view.md | 31 ++++++++++ docs/features/docs.md | 92 ++++++++++++++++++++++++++++ docs/roadmap.md | 3 + packages/server/test/docs.test.ts | 13 ++++ 10 files changed, 240 insertions(+), 6 deletions(-) create mode 100644 docs/decisions/035-docs-cache.md create mode 100644 docs/decisions/036-doc-writes.md create mode 100644 docs/decisions/037-rich-text-view.md create mode 100644 docs/features/docs.md diff --git a/CLAUDE.md b/CLAUDE.md index fef7994..ca9bab8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,8 +52,10 @@ docs/ INDEX.md → STATE.md → spec.md, decisions/ - UI: shadcn/ui files in `apps/web/src/components/ui/` stay as the CLI writes them; app wrappers live in `components/kit.tsx`. - New `/api/v1` routes go in `packages/server/src/api/routes.ts`, with tests in - `packages/server/test/api.test.ts` or, for task and link routes, `api-tasks.test.ts` - (success, 401, 403, 400). + `packages/server/test/api.test.ts` or, for task and link routes, `api-tasks.test.ts`, or, for + doc routes, `api-docs.test.ts` (success, 401, 403, 400). +- Docs: every path passes `normalizeDocPath()` and `isDocVisible()` (packages/core). Read the + editor's text with `docText()` (`sliceDoc`), never `doc.toString()`. - DB tests run on both drivers: `describe.each(await allTestDrivers())` from `@gitwork/db/testing`. - Pages read the request (`getSession()`/`connection()`) before any config, or `next build` fails. - Webhook handlers verify the signature and are idempotent on the delivery ID. diff --git a/apps/web/e2e/docs.spec.ts b/apps/web/e2e/docs.spec.ts index e725459..7210e79 100644 --- a/apps/web/e2e/docs.spec.ts +++ b/apps/web/e2e/docs.spec.ts @@ -114,6 +114,9 @@ test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ br await expect(editor.locator(".cm-lp-h1")).toHaveText("Handbook"); await expect(editor.locator(".cm-lp-strong")).toHaveText("bold"); await expect(editor.locator("input.cm-lp-task")).toHaveCount(1); + // Frontmatter lives in the properties panel; the parser would draw it as a rule and a heading. + await expect(editor.getByText("title: Welcome")).toHaveCount(0); + await expect(editor.locator("hr")).toHaveCount(0); await editor.locator(".cm-lp-h1").click(); await expect(editor.locator(".cm-lp-h1")).toHaveText("# Handbook"); diff --git a/docs/INDEX.md b/docs/INDEX.md index 517c392..c5fff3f 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -43,6 +43,9 @@ | 031 | [Linear features out of scope for v1](decisions/031-v1-scope.md) | | 032 | [Triage is linked-repo issues not on the board](decisions/032-triage.md) | | 033 | [Sync by snapshot ETag, not a change table; no IndexedDB yet](decisions/033-snapshot-etag-sync.md) | +| 035 | [Docs cache: tree by folder oid, text by blob sha](decisions/035-docs-cache.md) | +| 036 | [Doc writes: one signed commit, conflict check, pull request fallback](decisions/036-doc-writes.md) | +| 037 | ["Rich text" is a live preview over the source, not WYSIWYG](decisions/037-rich-text-view.md) | ## Features @@ -57,3 +60,4 @@ | [features/speed.md](features/speed.md) | Client store, /sync with ETag, optimistic edits, side panel, measured budgets. | | [features/keyboard.md](features/keyboard.md) | Shared keymap, command menu, pickers, bulk edit with undo, shortcut sheet. | | [features/shell.md](features/shell.md) | Workspace layout and sidebar, grouped virtualized list, dense cards, write-path line, dark mode. | +| [features/docs.md](features/docs.md) | Doc tree, rich-text editor, frontmatter panel, images, commits, PR fallback, conflicts, presence. | diff --git a/docs/STATE.md b/docs/STATE.md index cffed48..0676724 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -1,6 +1,6 @@ # State -Last updated: 2026-11-10 +Last updated: 2026-11-19 ## Resume here @@ -20,6 +20,9 @@ Last updated: 2026-11-10 ## In Progress +Phase 4 — Docs on web: built on `feature/docs-web`, PR open, waiting for the owner's merge. The owner +said "start phase 4" on 2026-11-19, ahead of the live GitHub check and Track E. + First Cloudflare deploy (blocked on the owner's account steps, above). ## Completed @@ -36,6 +39,7 @@ First Cloudflare deploy (blocked on the owner's account steps, above). | Track C — Keyboard and command menu (PR #9) | 2026-11-10 | [features/keyboard.md](features/keyboard.md) | | Track D — App shell and clear UI (PR #10) | 2026-11-10 | [features/shell.md](features/shell.md) | | Timeline virtualization, roadmap B6 (PR #11) | 2026-11-10 | [features/shell.md](features/shell.md) | +| Phase 4 — Docs on web (decisions 035–037; PR awaiting merge) | 2026-11-19 | [features/docs.md](features/docs.md) | ## Backlog @@ -44,11 +48,12 @@ Order: `docs/roadmap.md` (decisions 023–033). 0. Live GitHub check on the deployed instance (gate for Track E and Phase 4). 1. Track E tier 1 — Triage, My tasks, priority/estimate/labels/assignees edits, comments, saved views, inbox (merges Phase 5). -2. Phase 4 — Docs on web (editor, round-trip fidelity, images, PR fallback, conflicts) -3. Phase 6 — Mac app v1 -4. Deploy to Cloudflare button (needs the app isolated in one folder; see features/self-host.md) +2. Phase 6 — Mac app v1 (reuse `packages/core/fixtures/docs/`) +3. Deploy to Cloudflare button (needs the app isolated in one folder; see features/self-host.md) Chores: +- **Docs, after the live GitHub check:** confirm the protected-branch refusal of + `createCommitOnBranch` triggers the PR fallback, and that a 10 MB image commits (decision 036). - **Server job queue for bulk edits (decision 027).** Bulk edits run in the browser, one by one, for now (features/keyboard.md). Build the queue (decision 004 adapter) before bulk edits grow. - Before a hosted launch: `/github/installed` should show org names only to users whose GitHub diff --git a/docs/decisions/035-docs-cache.md b/docs/decisions/035-docs-cache.md new file mode 100644 index 0000000..fbbddd4 --- /dev/null +++ b/docs/decisions/035-docs-cache.md @@ -0,0 +1,38 @@ +# 035 — Docs cache: tree by folder oid, text by blob sha + +Date: 2026-11-19 · Status: Accepted (default; the owner may override) · Builds on 010, 011, 012 + +## Context +Pages never call GitHub (CLAUDE.md), so the doc tree must be in the database. A docs folder can +hold many files, D1 caps each statement at 100 bound parameters and each value at 2 MB, and push +payloads list at most 20 commits with file lists that can be stale. + +## Decision +- **One docs folder per workspace repo.** `workspace_repos.docs_path` (default `docs`) and + `docs_branch` (null = the repo's default branch). A cached folder is a "root": repo + branch + + path. Two workspaces with the same settings share one root. +- **Tree.** One GraphQL call reads the branch head and the folder's tree oid + (`object(expression: ":")`). Only when the oid changed, one REST call lists the + folder (`git/trees/?recursive=1`). The cache keeps path, blob sha, and size + (`gh_doc_files`), diffed against the stored rows, at most 2,000 files per folder. +- **Text by blob sha** (`gh_doc_blobs`): content-addressed, so a row never goes stale. Fetched on + first open (an API route, never a page render) and stored only when it is editable (valid UTF-8, + at most 1 MB). Rows no file points at are pruned on every reconcile. +- **Updates.** The `push` webhook re-reads every root on the pushed branch; it ignores the + payload's file lists. Reconcile re-reads the roots of each repo it syncs. A write re-reads its + root right after the commit, so the editor and the tree never wait for the webhook. +- **Hide folder (012).** `workspaces.hide_folder`, relative to each docs folder, matched by whole + path segments and without case. `isDocVisible()` in packages/core filters every list, read, + image, presence call, and write path. + +## Alternatives considered +- **Cache the whole repo tree:** simpler paths, but large repos would fill the database with files + nobody can open. +- **Trust the push payload's added/modified/removed lists:** no extra call, but the lists are capped + and miss force-pushes. + +## Consequences +- A push to the docs branch costs one GraphQL call per root, plus a tree listing when the folder + changed. +- A folder with more than 2,000 files shows a "more files than Gitwork lists" note. +- Files over 1 MB or not UTF-8 open read-only with a link to GitHub. diff --git a/docs/decisions/036-doc-writes.md b/docs/decisions/036-doc-writes.md new file mode 100644 index 0000000..73ed559 --- /dev/null +++ b/docs/decisions/036-doc-writes.md @@ -0,0 +1,43 @@ +# 036 — Doc writes: one signed commit, conflict check, pull request fallback + +Date: 2026-11-19 · Status: Accepted (default; the owner may override) · Builds on 008, 011, 021 + +## Context +Decision 011 asks for one writer at a time with conflict detection, a pull request when branch +protection blocks a commit, renames in one commit, and images in the same commit as the doc. +Decision 008 asks for verified commits and a Co-authored-by trailer on App writes. + +## Decision +- **Every write is one `createCommitOnBranch` call** (GraphQL). GitHub signs it, it takes several + files at once (doc + images, rename = add + delete), and `expectedHeadOid` refuses to commit on + top of a head we did not check. +- **User token first, App on refusal** (021). App commits end with + `Co-authored-by: `. +- **Conflict check before the commit.** The client sends the blob sha it loaded. The server reads + the file's current sha at the branch head; a different sha is a 409 `doc_conflict` with GitHub's + current text, and the editor shows a side-by-side merge view. +- **Conflict vs. protection without trusting status codes.** When GitHub refuses the commit, the + server reads the head again. A moved head is a race: check and try once more. The same head and + the same file, still refused, means branch protection or a ruleset: the save becomes a pull + request. +- **Pull request fallback.** A new branch `gitwork/docs--` at the checked head, the + same commit there, and a pull request to the docs branch. The doc is "pending review" + (`doc_pending_prs`): it opens from the PR branch, and later saves commit there. The + `pull_request` webhook (closed) ends it; a deleted branch found on open also ends it. +- **Review mode (008).** `workspaces.review_bot_doc_edits`: App writes go straight to a pull request. + A user who linked GitHub still commits as themselves. +- **No empty commits.** The server computes the git blob sha of the new text; equal to the base sha + with no images means "unchanged", and nothing is sent. +- **Rename and delete** refuse while the doc has an open pull request. Delete needs `docs.delete`. + +## Alternatives considered +- **Contents API (`PUT /contents`)** for single files: built-in sha check, but one file per commit, + so no doc + image commit and no one-commit rename. +- **Treat any 409/422 as a conflict:** GitHub uses those codes for protection, rulesets, and + stale data alike. Re-reading the file is the only reliable signal. + +## Consequences +- The exact error GitHub returns for a protected branch on `createCommitOnBranch` is not verified + against real GitHub yet (fake GitHub only). The re-read rule does not depend on it. The live + GitHub check must confirm the PR fallback. +- `createCommitOnBranch` with a 10 MB image is also unverified against real GitHub's request limits. diff --git a/docs/decisions/037-rich-text-view.md b/docs/decisions/037-rich-text-view.md new file mode 100644 index 0000000..bedf6f0 --- /dev/null +++ b/docs/decisions/037-rich-text-view.md @@ -0,0 +1,31 @@ +# 037 — "Rich text" is a live preview over the source, not WYSIWYG + +Date: 2026-11-19 · Status: Accepted (default; the owner may override) · Builds on 011 + +## Context +The owner asked for the docs folder in "the rich text doc editor". Decision 011 rejects WYSIWYG +editors (ProseMirror, Tiptap) because they re-serialize markdown and change lines nobody edited. + +## Decision +- **The default view is "Rich text":** a CodeMirror 6 live preview. Headings, bold, italics, links, + inline code, quotes, bullets, checkboxes (clickable), rules, and images render; markdown marks + hide on every line the cursor is not on. The cursor's lines show the source. Frontmatter shows in + a properties panel above the text. +- **"Markdown" view** shows the plain source with light highlighting. The choice is remembered per + browser. +- **A toolbar and keys** (⌘B, ⌘I, headings, lists, checklist, quote, code, link, image) make small + text edits on the selected lines only. +- **Bytes.** The editor always sets its line separator: CRLF when every break is CRLF, else LF, with + a stray CR kept as text. Typed and pasted breaks take the file's separator. File text is read with + `state.sliceDoc()`, never `doc.toString()` (which always joins with LF). The shared round-trip + fixtures run through a real `EditorState`. + +## Alternatives considered +- **Tiptap / ProseMirror WYSIWYG:** the most familiar feel, but it breaks the byte-exact guarantee + (011) and the Mac app could not share the fixtures. +- **Source only:** safe, but not what the owner asked for. + +## Consequences +- Tables and footnotes render as source for now. +- Navigating away inside the app with unsaved changes is not blocked; closing or reloading the tab + asks first. Saves are explicit (each one is a commit), so there is no autosave. diff --git a/docs/features/docs.md b/docs/features/docs.md new file mode 100644 index 0000000..695d00f --- /dev/null +++ b/docs/features/docs.md @@ -0,0 +1,92 @@ +# Docs on web — tree, rich-text editor, commits + +Shipped 2026-11-19 (Phase 4). Branch `feature/docs-web`. Decisions 008, 011, 012, 035, 036, 037. + +## What it does +- **Docs** in the workspace sidebar lists every file under each linked repo's docs folder (default + `docs/`, set per repo with its branch in Settings → Docs folders). Markdown files open in the + editor; images and other files open through an access-checked proxy. +- The editor opens in **Rich text**: formatted text with markdown marks hidden off the cursor's + line (decision 037). **Markdown** shows the plain source. A toolbar and ⌘B / ⌘I / ⌘S format and + save. Frontmatter edits in a **properties panel**; lists and maps stay read-only there. +- **Save** is one signed commit on GitHub. The user's own token is used when they linked GitHub; + otherwise the App commits with `Co-authored-by: ` (decision 008). +- **Paste or drop an image**: it goes to `/assets/` and commits with the doc, linked by a + relative path. Up to 10 MB each, 5 per save. +- **Conflicts**: if the doc changed on GitHub since it was opened, a side-by-side view shows + GitHub's version and yours; save yours on top, keep editing, or take GitHub's. +- **Branch protection or review mode** turns a save into a pull request. The doc shows "Pending + review"; later saves go to that pull request until it closes. +- **Presence**: "Max is editing this doc" while someone else has it open. +- **Create, rename, delete** from the tree and the doc header. Delete needs Admin. +- **Read Only** reads docs; files under the workspace's **hide folder** (Settings → What Read Only + members see) never reach them: not in the tree, the API, images, or by URL. + +## How it works + +**Code.** +| File | Role | +|---|---| +| `packages/core/src/docs/paths.ts` | Path rules (`normalizeDocPath`, `normalizeRoot`, `resolveRelative`, `relativeLink`, `safeFileName`, `imageType`). | +| `packages/core/src/docs/text.ts` | Byte-exact text: base64, `bytesToText` (fatal UTF-8, BOM kept), `lineSeparatorOf`, `offsetToEditorPos`. | +| `packages/core/src/docs/frontmatter.ts` | `parseFrontmatter`, and set/add/remove as one-line text changes. | +| `packages/core/src/visibility.ts` | `isDocVisible()` and `docVisibilityContext()`: the hide-folder filter. | +| `packages/core/fixtures/docs/` | The shared round-trip fixtures (web and Mac). | +| `packages/server/src/github/docs.ts` | `readHead`, `planDocRootSync`, `readDocText`, `gitBlobSha`, `commitFiles`, PR helpers. | +| `packages/server/src/github/cache.ts` | Doc cache writers (`upsertDocRoot`, `upsertDocFiles`, `deleteDocFiles`, `putDocBlob`, `pruneDocBlobs`). | +| `packages/server/src/services/docs.ts` | List, read, raw files, presence, save/create/rename/delete, docs config, sync and prune. | +| `apps/web/src/lib/doc-editor.ts` | CodeMirror state with the file's line separator; `docText()` = `sliceDoc()`. | +| `apps/web/src/lib/live-preview.ts` | The rich-text view (decorations only) and the highlight style. | +| `apps/web/src/lib/markdown-commands.ts` | Toolbar edits: wrap, line prefix, link. | +| `apps/web/src/app/w/[workspaceId]/docs/` | Layout + tree (cache only), editor, properties panel, conflict view. | + +**API (`/api/v1/workspaces/:id/…`).** `GET docs`, `POST docs/refresh`, `GET docs/file?repo&path`, +`PUT docs/file` (save), `POST docs/file` (create), `POST docs/rename`, `DELETE docs/file?repo&path&sha`, +`GET docs/raw?repo&path`, `POST|DELETE docs/presence`, `PATCH github/repos/:repoNodeId/docs`, +`PATCH settings` (`hideFolder`, `reviewBotDocEdits`). Write routes check the role first. +`GET docs/file` works without the GitHub App while the text is cached. + +**Write path (decision 036).** Read the file's current blob sha at the branch head → 409 with the +current text if it differs → `createCommitOnBranch` with `expectedHeadOid` (user token, App on +refusal) → re-read the root so the cache matches → audit row with the commit sha. A refusal with an +unchanged head and file means protection: branch + commit + pull request, and a +`doc_pending_prs` row. + +**Sync (decision 035).** Roots are `::`. `push` webhook and reconcile run +`planDocRootSync`: one GraphQL call; a tree listing only when the folder's oid changed; a diff +against `gh_doc_files`. Text is fetched on first open and cached by blob sha. + +## Data model +`workspace_repos.docs_path`, `.docs_branch`; `workspaces.hide_folder`, `.review_bot_doc_edits`; +`gh_doc_roots`, `gh_doc_files`, `gh_doc_blobs` (cache, rebuilt from GitHub); `doc_pending_prs`; +`doc_presence` (45-second heartbeat rows). Migration `0005_docs.sql`, additive only. + +## External services +GitHub App permissions already in the manifest: Contents (rw), Pull requests (rw). Webhooks +`push` and `pull_request` (already subscribed) now do work. No new GitHub settings. + +## Testing +- `packages/core/src/docs/*.test.ts`: paths, visibility, frontmatter, and the fixture suite. +- `apps/web/src/lib/doc-editor.test.ts`: every fixture through a CodeMirror `EditorState`, and + line breaks in typed and pasted text. `markdown-commands.test.ts`: toolbar edits. +- `packages/server/test/docs.test.ts` (both drivers, fake GitHub with a git model): sync, filters, + every write, attribution, conflicts, races, protection and review mode, presence, settings. +- `packages/server/test/api-docs.test.ts`: routes (success, 401, 403, 400, 409). +- `apps/web/e2e/docs.spec.ts`: tree, hide folder for Read Only, rich-text view, formatting, + properties panel, single-key shortcuts inside the editor, save without the App. + +## Gotchas +- **`doc.toString()` joins lines with LF** even in a CRLF file. Use `docText()` (`sliceDoc`). + Test: `doc-editor.test.ts`. +- **With an explicit separator, CodeMirror does not split inserted text on other breaks.** The + separator filter rewrites typed and pasted breaks. Test: `doc-editor.test.ts`. +- **`TextDecoder` drops a BOM by default.** `ignoreBOM: true` keeps it. Test: fixture `bom`. +- **The markdown parser reads frontmatter as a rule plus a setext heading.** Rich text hides the + block; the panel edits it. Test: `docs.spec.ts`. +- **D1 allows 100 bound parameters per statement**; libsql allows more. Doc rows go in at 20 per + statement. Test: "larger than one statement's bound parameters" (fails on D1 at 60). +- **SVG can carry script.** Raw files are served with `CSP: default-src 'none'; sandbox` and + `nosniff`. Test: `docs.test.ts` reads. +- **The hide folder matches whole segments and ignores case.** Test: `paths.test.ts`, `docs.test.ts`. +- **Unverified against real GitHub:** the protected-branch refusal of `createCommitOnBranch`, and + 10 MB images in one GraphQL request. Confirm in the live GitHub check. diff --git a/docs/roadmap.md b/docs/roadmap.md index 49aa1eb..c3f5403 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -27,6 +27,9 @@ cannot hold gets a question for the owner, not a quiet local table. Phase 5 (Activity, inbox) merges into Track E, tier 1. +**Change, 2026-11-19:** the owner started Phase 4 before the live GitHub check and Track E, tier 1. +Phase 4 is built against the fake GitHub; the live check must also cover the docs write path. + ## Step 0 — iCloud copies in PR #5 (blocker) Commit `0943411` on `feature/live-check` (PR #5) adds 24 files named ` 2.`: diff --git a/packages/server/test/docs.test.ts b/packages/server/test/docs.test.ts index bd052e7..d8fdb30 100644 --- a/packages/server/test/docs.test.ts +++ b/packages/server/test/docs.test.ts @@ -314,6 +314,19 @@ describe.each(drivers)("docs on $name", (driver: TestDriver) => { expect(list).not.toContain("docs/README.md"); }); + it("syncs a folder larger than one statement's bound parameters (D1 allows 100)", async () => { + const many: Record = {}; + for (let i = 0; i < 45; i++) many[`docs/bulk/note-${String(i).padStart(2, "0")}.md`] = `# Note ${i}\n`; + w.fake.commit(SITE, "main", many); + await webhook("push", { ref: "refs/heads/main", installation: { id: 99 }, repository: { node_id: IDS.site } }); + expect((await paths("max")).filter((p) => p.startsWith("docs/bulk/"))).toHaveLength(45); + const removeAll: Record = {}; + for (const p of Object.keys(many)) removeAll[p] = null; + w.fake.commit(SITE, "main", removeAll); + await webhook("push", { ref: "refs/heads/main", installation: { id: 99 }, repository: { node_id: IDS.site } }); + expect((await paths("max")).filter((p) => p.startsWith("docs/bulk/"))).toHaveLength(0); + }); + it("ignores pushes to other branches, and skips the tree listing when the folder did not change", async () => { w.fake.commit(SITE, "feature", { "docs/branch.md": "x" }); await webhook("push", { ref: "refs/heads/feature", installation: { id: 99 }, repository: { node_id: IDS.site } });