starlight-annotations 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # starlight-annotations
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 6ee673f: Adds a page listing every note on the site, at `/annotations/` (change it with the `overview` option, or set `overview: false` to leave it out). Notes are grouped by page and can be filtered by status, author and text; the filters are kept in the address. Each note links to its page with `#annotation-<id>`, which opens the panel on that note and scrolls to its passage, also for resolved notes. The notes panel links to the overview.
8
+
9
+ Storages gain an optional `list()`, implemented for GitHub, GitLab, Gitea/Forgejo, the disk and the browser, and the handler answers `GET {prefix}/api/all`.
10
+
11
+ ### Patch Changes
12
+
13
+ - b1bf95b: Makes the overview page easier to find: the notes panel links to it from its header, next to the title, and from the message shown on a page without notes, instead of at the end of the list.
14
+
15
+ ## 0.4.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 2a7a36c: Adds GitHub App support: `github({ app: { appId, privateKey } })` instead of `token`. The server mints installation tokens limited to the notes repository, valid for an hour and renewed before they expire, and the app's client ID and secret also handle sign-in, so one app replaces the OAuth app and the personal access token. It suits organizations: the app belongs to no one, needs no token approval and does not expire. Commits show the app as committer and the reader as author. `token` keeps working as before; `githubAppToken()` is exported for other uses of the same app.
20
+
3
21
  ## 0.3.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -12,6 +12,7 @@ Let readers highlight text and leave notes on your [Starlight](https://starlight
12
12
  ## Features
13
13
 
14
14
  - 💬 **Select, note, discuss.** Markdown notes with a formatting toolbar, replies, "in reply to" references, resolve and reopen.
15
+ - 🗒️ **All notes on one page.** An overview of every note on the site, filtered by status, author or text, each one a click away from its passage.
15
16
  - 📌 **Anchored to the text.** W3C Web Annotation selectors: notes find their place again after edits, and long passages are stored by their start and end.
16
17
  - 🗂️ **Your repo, your data.** One file per page on a branch of its own; every note is a commit by its author. Works with **GitHub**, **GitLab** (gitlab.com or self-managed) and **Gitea / Forgejo** (including Codeberg).
17
18
  - 🌍 **Runs anywhere.** The API is one Web-standard handler for Cloudflare Workers, Netlify, Vercel, Deno or Node. Or keep personal notes in the browser, with no server.
package/index.d.ts CHANGED
@@ -42,6 +42,23 @@ export type AnnotationStrings = {
42
42
  numbers: string;
43
43
  tasks: string;
44
44
  codeBlock: string;
45
+ allNotes: string;
46
+ overviewDescription: string;
47
+ statusOpen: string;
48
+ statusResolved: string;
49
+ statusAll: string;
50
+ everyone: string;
51
+ filter: string;
52
+ openOnPage: string;
53
+ oneReply: string;
54
+ replies: string;
55
+ noMatches: string;
56
+ overviewEmpty: string;
57
+ overviewUnavailable: string;
58
+ loading: string;
59
+ showing: string;
60
+ author: string;
61
+ seeAll: string;
45
62
  };
46
63
 
47
64
  export interface StarlightAnnotationsOptions {
@@ -62,6 +79,11 @@ export interface StarlightAnnotationsOptions {
62
79
  longQuote?: number;
63
80
  /** Override UI strings per language, e.g. `{ it: { annotate: 'Commenta' } }`. */
64
81
  translations?: Record<string, Partial<AnnotationStrings>>;
82
+ /**
83
+ * Path of the page listing every note on the site, relative to the site base.
84
+ * Default `"annotations"` (so `/annotations/`). `false` leaves it out.
85
+ */
86
+ overview?: string | false;
65
87
  /** localStorage key prefix for the `"browser"` backend. Default `"starlight-annotations"`. */
66
88
  storageKey?: string;
67
89
  /**
package/index.js CHANGED
@@ -18,7 +18,10 @@ export default function starlightAnnotations(options = {}) {
18
18
  // Starlight links customCss on every page, in dev and in the build.
19
19
  // (CSS imported by an injected script is bundled but not linked.)
20
20
  updateConfig({ customCss: [...(starlightConfig.customCss ?? []), 'starlight-annotations/styles.css'] });
21
- addIntegration(annotationsIntegration(config));
21
+ // The overview page is not localized: it speaks the default language.
22
+ const locales = starlightConfig.locales ?? {};
23
+ const lang = locales[starlightConfig.defaultLocale ?? 'root']?.lang ?? locales.root?.lang ?? starlightConfig.defaultLocale ?? 'en';
24
+ addIntegration(annotationsIntegration({ ...config, lang }));
22
25
  },
23
26
  },
24
27
  };
@@ -34,9 +37,14 @@ function resolveOptions(options) {
34
37
  if (!Number.isInteger(longQuote) || longQuote < 100) {
35
38
  throw new Error('starlight-annotations: "longQuote" must be an integer of at least 100.');
36
39
  }
40
+ const overview = options.overview ?? 'annotations';
41
+ if (overview !== false && (typeof overview !== 'string' || !/^[a-z0-9][a-z0-9/_-]*$/i.test(overview.replace(/^\/+|\/+$/g, '')))) {
42
+ throw new Error('starlight-annotations: "overview" must be a path such as "annotations", or false.');
43
+ }
37
44
  return {
38
45
  backend,
39
46
  apiBase,
47
+ overview: overview === false ? false : overview.replace(/^\/+|\/+$/g, ''),
40
48
  content: options.content ?? '.sl-markdown-content',
41
49
  exclude: options.exclude ?? [],
42
50
  longQuote,
@@ -55,7 +63,7 @@ function annotationsIntegration(config) {
55
63
  return {
56
64
  name: 'starlight-annotations',
57
65
  hooks: {
58
- 'astro:config:setup'({ config: astroConfig, injectScript, updateConfig }) {
66
+ 'astro:config:setup'({ config: astroConfig, injectRoute, injectScript, updateConfig }) {
59
67
  base = astroConfig.base.replace(/\/$/, '');
60
68
  root = fileURLToPath(astroConfig.root);
61
69
  updateConfig({
@@ -70,6 +78,9 @@ function annotationsIntegration(config) {
70
78
  },
71
79
  });
72
80
  injectScript('page', `import 'starlight-annotations/client';`);
81
+ if (config.overview) {
82
+ injectRoute({ pattern: `/${config.overview}`, entrypoint: fileURLToPath(new URL('./src/overview.astro', import.meta.url)), prerender: true });
83
+ }
73
84
  },
74
85
 
75
86
  // `astro dev` serves the same API from disk, so the feature works
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "🖍️ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository on GitHub, GitLab, Gitea or Forgejo.",
5
5
  "license": "MIT",
6
6
  "author": "Alessandro Rosa",
package/server.d.ts CHANGED
@@ -13,6 +13,8 @@ export interface AnnotationDocument {
13
13
  export interface Storage {
14
14
  mode?: string;
15
15
  load(page: string): Promise<AnnotationDocument>;
16
+ /** Every page that has a notes file, for the overview page. Optional. */
17
+ list?(): Promise<{ page: string; annotations: AnnotationDocument['annotations'] }[]>;
16
18
  update(
17
19
  page: string,
18
20
  mutate: (doc: AnnotationDocument) => { annotation: Record<string, unknown>; message: string },
@@ -45,8 +47,10 @@ export function createAnnotationsHandler(options: HandlerOptions): (request: Req
45
47
  export interface GitHubStorageOptions {
46
48
  /** `owner/name` of the repository that stores the notes. */
47
49
  repo: string;
48
- /** Token with Contents read/write (and Metadata read) on `repo`. */
49
- token: string;
50
+ /** Token with Contents read/write (and Metadata read) on `repo`. Or use `app`. */
51
+ token?: string | (() => Promise<string>);
52
+ /** A GitHub App installed on `repo`, instead of `token`. */
53
+ app?: GitHubAppOptions;
50
54
  /** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
51
55
  branch?: string;
52
56
  /** Folder for the notes in the branch. Default `"annotations"`. */
@@ -55,7 +59,20 @@ export interface GitHubStorageOptions {
55
59
  commitMessage?: (message: string, page: string) => string;
56
60
  }
57
61
 
62
+ export interface GitHubAppOptions {
63
+ /** The App ID, on the app's General page. */
64
+ appId: string | number;
65
+ /** The app's private key: the `.pem` file, PKCS#1 or PKCS#8. Line breaks may be written as `\n`. */
66
+ privateKey: string;
67
+ /** The installation on `repo`. Looked up when omitted. */
68
+ installationId?: string | number;
69
+ }
70
+
71
+ /** Installation tokens of a GitHub App, limited to `repo` and renewed before they expire. */
72
+ export function githubAppToken(options: GitHubAppOptions & { repo: string }): () => Promise<string>;
73
+
58
74
  export interface GitHubAuthOptions {
75
+ /** The OAuth app's client ID, or the GitHub App's. */
59
76
  clientId: string;
60
77
  clientSecret: string;
61
78
  /** A long random string that signs the session cookie. */
@@ -66,7 +83,8 @@ export interface GitHubAuthOptions {
66
83
  */
67
84
  writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
68
85
  repo?: string;
69
- token?: string;
86
+ token?: string | (() => Promise<string>);
87
+ app?: GitHubAppOptions;
70
88
  /**
71
89
  * Seconds between checks that a signed-in user may still write, on saves and page loads.
72
90
  * `false` checks only at sign-in. Default 60.
@@ -9,6 +9,7 @@
9
9
  import config from 'virtual:starlight-annotations/config';
10
10
  import { createBackend } from './backend.js';
11
11
  import { strings } from './i18n.js';
12
+ import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
12
13
 
13
14
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
14
15
  // Text the reader does not see as content: diagrams (rendered late), heading
@@ -21,49 +22,6 @@ const backend = createBackend(config, BASE, T);
21
22
  const mac = /Mac|iPhone|iPad/.test(navigator.platform);
22
23
  const mod = mac ? '⌘' : 'Ctrl+';
23
24
 
24
- // ---- Markdown ----
25
-
26
- // The Markdown parser is most of the client's weight, so it loads on demand:
27
- // when the page has notes, or when the reader starts to write one. Until it
28
- // arrives a note shows as plain text, then it is filled in.
29
- let markdown = null;
30
- let markdownLoading = null;
31
- const waitingForMarkdown = new Map(); // element -> source
32
-
33
- function loadMarkdown() {
34
- markdownLoading ??= Promise.all([import('micromark'), import('micromark-extension-gfm')]).then(([{ micromark }, { gfm, gfmHtml }]) => {
35
- markdown = (source) => micromark(source, { extensions: [gfm()], htmlExtensions: [gfmHtml()] });
36
- for (const [target, source] of waitingForMarkdown) if (target.isConnected) renderMarkdown(target, source);
37
- waitingForMarkdown.clear();
38
- }).catch(() => {
39
- // Offline or blocked: notes stay as plain text, and the next note retries.
40
- markdownLoading = null;
41
- });
42
- return markdownLoading;
43
- }
44
-
45
- function renderMarkdown(target, source) {
46
- if (!markdown) {
47
- target.textContent = source;
48
- target.classList.add('annot-md-pending');
49
- waitingForMarkdown.set(target, source);
50
- loadMarkdown();
51
- return target;
52
- }
53
- target.classList.remove('annot-md-pending');
54
- target.innerHTML = markdown(source);
55
- for (const link of target.querySelectorAll('a[href]')) {
56
- // micromark empties unsafe URLs (javascript: and the like): show plain text.
57
- if (!link.getAttribute('href')) {
58
- link.replaceWith(...link.childNodes);
59
- continue;
60
- }
61
- link.target = '_blank';
62
- link.rel = 'noopener noreferrer nofollow';
63
- }
64
- return target;
65
- }
66
-
67
25
  // Edits go through execCommand when it works, so Cmd+Z still undoes them.
68
26
  function insert(area, text) {
69
27
  area.focus();
@@ -140,7 +98,8 @@ const TOOLS = [
140
98
  ];
141
99
 
142
100
  const root = document.querySelector(config.content);
143
- if (root instanceof HTMLElement) start(root);
101
+ // The overview page lists notes; it is not annotated itself.
102
+ if (root instanceof HTMLElement && !document.querySelector('.annot-overview')) start(root);
144
103
 
145
104
  function pageKey() {
146
105
  let path = decodeURIComponent(location.pathname);
@@ -149,18 +108,6 @@ function pageKey() {
149
108
  return path || 'index';
150
109
  }
151
110
 
152
- function h(tag, attrs = {}, ...children) {
153
- const el = document.createElement(tag);
154
- for (const [key, value] of Object.entries(attrs)) {
155
- if (value === undefined || value === false) continue;
156
- if (key.startsWith('on')) el.addEventListener(key.slice(2), value);
157
- else if (key === 'class') el.className = value;
158
- else el.setAttribute(key, value === true ? '' : value);
159
- }
160
- for (const child of children.flat()) if (child != null && child !== false) el.append(child);
161
- return el;
162
- }
163
-
164
111
  // ---- Text index: the page text as one string, mapped back to DOM nodes ----
165
112
 
166
113
  function buildIndex(root) {
@@ -264,19 +211,6 @@ function selectorFor(text, start, end) {
264
211
  };
265
212
  }
266
213
 
267
- // What the panel shows: a long quote is cut in the middle.
268
- function quoteText(selector) {
269
- const squash = (value) => value.replace(/\s+/g, ' ').trim();
270
- if (selector.type === 'RangeSelector') {
271
- // The stored edges are cut by length: drop the half words at the cut.
272
- const head = squash(selector.startSelector.exact).replace(/\s+\S*$/, '');
273
- const tail = squash(selector.endSelector.exact).replace(/^\S*\s+/, '');
274
- return `${head} … ${tail}`;
275
- }
276
- const exact = squash(selector.exact);
277
- return exact.length > 220 ? `${exact.slice(0, 130).trimEnd()} … ${exact.slice(-70).trimStart()}` : exact;
278
- }
279
-
280
214
  // ---- The feature ----
281
215
 
282
216
  async function start(root) {
@@ -312,6 +246,16 @@ async function start(root) {
312
246
  const count = h('span', { class: 'annot-count' });
313
247
  const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count);
314
248
  const body = h('div', { class: 'annot-body' });
249
+ // The page with every note on the site, when the plugin adds it.
250
+ const overviewUrl = config.overview ? `${BASE}/${config.overview}/` : null;
251
+ const resolvedBox = h('input', {
252
+ type: 'checkbox',
253
+ onchange: (event) => {
254
+ state.showResolved = event.target.checked;
255
+ paint();
256
+ render();
257
+ },
258
+ });
315
259
  const drawer = h(
316
260
  'aside',
317
261
  { class: 'annot-drawer', 'aria-label': T.notes },
@@ -319,17 +263,11 @@ async function start(root) {
319
263
  'header',
320
264
  {},
321
265
  h('strong', {}, T.notes),
266
+ overviewUrl ? h('a', { class: 'annot-all', href: overviewUrl }, T.allNotes) : null,
322
267
  h(
323
268
  'label',
324
269
  { class: 'annot-resolved-toggle' },
325
- h('input', {
326
- type: 'checkbox',
327
- onchange: (event) => {
328
- state.showResolved = event.target.checked;
329
- paint();
330
- render();
331
- },
332
- }),
270
+ resolvedBox,
333
271
  T.showResolved,
334
272
  ),
335
273
  h('button', { type: 'button', class: 'annot-close', 'aria-label': T.close, onclick: () => setOpen(false) }, '×'),
@@ -627,7 +565,8 @@ async function start(root) {
627
565
  .filter((thread) => visible(thread) && state.anchors.has(thread.id))
628
566
  .sort((a, b) => state.anchors.get(a.id).start - state.anchors.get(b.id).start);
629
567
  const orphans = all.filter((thread) => visible(thread) && !state.anchors.has(thread.id));
630
- if (all.length === 0 && !state.pending) parts.push(h('p', { class: 'annot-empty' }, T.empty));
568
+ if (all.length === 0 && !state.pending)
569
+ parts.push(h('p', { class: 'annot-empty' }, T.empty, overviewUrl ? [' ', h('a', { href: overviewUrl }, T.seeAll)] : null));
631
570
  parts.push(...anchored.map((thread) => threadCard(thread, true)));
632
571
  if (orphans.length) parts.push(h('h3', { class: 'annot-orphans' }, T.orphans), ...orphans.map((thread) => threadCard(thread, false)));
633
572
  body.replaceChildren(...parts.filter(Boolean));
@@ -720,9 +659,26 @@ async function start(root) {
720
659
  }
721
660
  });
722
661
 
662
+ // "#annotation-<id>", from the overview page or a shared link: open that
663
+ // note, showing resolved notes if it is one, and scroll to its text.
664
+ function openFromHash() {
665
+ const id = decodeURIComponent(location.hash.match(/^#annotation-(.+)$/)?.[1] ?? '');
666
+ const item = id && state.annotations.find((annotation) => annotation.id === id);
667
+ if (!item) return;
668
+ const thread = (item.replyTo && state.annotations.find((annotation) => annotation.id === item.replyTo)) || item;
669
+ if (thread.resolved && !state.showResolved) {
670
+ state.showResolved = true;
671
+ resolvedBox.checked = true;
672
+ }
673
+ focusThread(thread.id, true);
674
+ if (item !== thread) flash(item.id);
675
+ }
676
+ window.addEventListener('hashchange', openFromHash);
677
+
723
678
  reanchor();
724
679
  paint();
725
680
  render();
681
+ openFromHash();
726
682
  // Fonts and late layout do not move text nodes, but a late script might.
727
683
  window.addEventListener('load', () => {
728
684
  reanchor();
@@ -35,6 +35,15 @@ function apiBackend(config, base) {
35
35
  return { ok: false, status: response.status, signedOut: Boolean(data.signedOut), error: data.error || `Error ${response.status}` };
36
36
  return { ok: true, ...data };
37
37
  },
38
+ // Every page with notes, or null when the API cannot list them.
39
+ async list() {
40
+ try {
41
+ const response = await fetch(`${api}/api/all`, { credentials: 'same-origin' });
42
+ return response.ok ? (await response.json()).pages : null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ },
38
47
  loginUrl: () => `${api}/login?return=${here()}`,
39
48
  logoutUrl: () => `${api}/logout?return=${here()}`,
40
49
  };
@@ -54,6 +63,22 @@ function browserBackend(config, T) {
54
63
  async load(page) {
55
64
  return { annotations: read(page).annotations, user, mode: 'browser' };
56
65
  },
66
+ async list() {
67
+ const prefix = `${config.storageKey}:`;
68
+ const pages = [];
69
+ try {
70
+ for (let i = 0; i < localStorage.length; i++) {
71
+ const name = localStorage.key(i);
72
+ if (!name?.startsWith(prefix)) continue;
73
+ const page = name.slice(prefix.length);
74
+ const { annotations } = read(page);
75
+ if (annotations.length) pages.push({ page, annotations });
76
+ }
77
+ } catch {
78
+ return null;
79
+ }
80
+ return pages.sort((a, b) => a.page.localeCompare(b.page));
81
+ },
57
82
  async send(page, change) {
58
83
  try {
59
84
  const doc = read(page);
@@ -43,6 +43,23 @@ const en = {
43
43
  numbers: 'Numbered list',
44
44
  tasks: 'Task list',
45
45
  codeBlock: 'Code block',
46
+ allNotes: 'All notes',
47
+ overviewDescription: 'Every note left on these docs, page by page.',
48
+ statusOpen: 'Open',
49
+ statusResolved: 'Resolved',
50
+ statusAll: 'All',
51
+ everyone: 'Everyone',
52
+ filter: 'Filter notes…',
53
+ openOnPage: 'Open on the page',
54
+ oneReply: '1 reply',
55
+ replies: '{n} replies',
56
+ noMatches: 'No notes match these filters.',
57
+ overviewEmpty: 'No notes yet.',
58
+ overviewUnavailable: 'Notes are not available on this site.',
59
+ loading: 'Loading notes…',
60
+ showing: 'Status',
61
+ author: 'Author',
62
+ seeAll: 'See the notes on other pages.',
46
63
  };
47
64
 
48
65
  const it = {
@@ -87,6 +104,23 @@ const it = {
87
104
  numbers: 'Elenco numerato',
88
105
  tasks: 'Lista di attività',
89
106
  codeBlock: 'Blocco di codice',
107
+ allNotes: 'Tutte le note',
108
+ overviewDescription: 'Tutte le note lasciate su questa documentazione, pagina per pagina.',
109
+ statusOpen: 'Aperte',
110
+ statusResolved: 'Risolte',
111
+ statusAll: 'Tutte',
112
+ everyone: 'Tutti',
113
+ filter: 'Filtra le note…',
114
+ openOnPage: 'Apri nella pagina',
115
+ oneReply: '1 risposta',
116
+ replies: '{n} risposte',
117
+ noMatches: 'Nessuna nota corrisponde ai filtri.',
118
+ overviewEmpty: 'Ancora nessuna nota.',
119
+ overviewUnavailable: 'Le note non sono disponibili su questo sito.',
120
+ loading: 'Caricamento delle note…',
121
+ showing: 'Stato',
122
+ author: 'Autore',
123
+ seeAll: 'Guarda le note delle altre pagine.',
90
124
  };
91
125
 
92
126
  const de = {
@@ -131,6 +165,23 @@ const de = {
131
165
  numbers: 'Nummerierte Liste',
132
166
  tasks: 'Aufgabenliste',
133
167
  codeBlock: 'Codeblock',
168
+ allNotes: 'Alle Notizen',
169
+ overviewDescription: 'Alle Notizen zu dieser Dokumentation, Seite für Seite.',
170
+ statusOpen: 'Offen',
171
+ statusResolved: 'Erledigt',
172
+ statusAll: 'Alle',
173
+ everyone: 'Alle Personen',
174
+ filter: 'Notizen filtern…',
175
+ openOnPage: 'Auf der Seite öffnen',
176
+ oneReply: '1 Antwort',
177
+ replies: '{n} Antworten',
178
+ noMatches: 'Keine Notizen passen zu diesen Filtern.',
179
+ overviewEmpty: 'Noch keine Notizen.',
180
+ overviewUnavailable: 'Notizen sind auf dieser Website nicht verfügbar.',
181
+ loading: 'Notizen werden geladen…',
182
+ showing: 'Status',
183
+ author: 'Autor',
184
+ seeAll: 'Notizen auf anderen Seiten ansehen.',
134
185
  };
135
186
 
136
187
  const fr = {
@@ -175,6 +226,23 @@ const fr = {
175
226
  numbers: 'Liste numérotée',
176
227
  tasks: 'Liste de tâches',
177
228
  codeBlock: 'Bloc de code',
229
+ allNotes: 'Toutes les notes',
230
+ overviewDescription: 'Toutes les notes laissées sur cette documentation, page par page.',
231
+ statusOpen: 'Ouvertes',
232
+ statusResolved: 'Résolues',
233
+ statusAll: 'Toutes',
234
+ everyone: 'Tout le monde',
235
+ filter: 'Filtrer les notes…',
236
+ openOnPage: 'Ouvrir dans la page',
237
+ oneReply: '1 réponse',
238
+ replies: '{n} réponses',
239
+ noMatches: 'Aucune note ne correspond à ces filtres.',
240
+ overviewEmpty: 'Aucune note pour le moment.',
241
+ overviewUnavailable: 'Les notes ne sont pas disponibles sur ce site.',
242
+ loading: 'Chargement des notes…',
243
+ showing: 'Statut',
244
+ author: 'Auteur',
245
+ seeAll: 'Voir les notes des autres pages.',
178
246
  };
179
247
 
180
248
  const es = {
@@ -219,6 +287,23 @@ const es = {
219
287
  numbers: 'Lista numerada',
220
288
  tasks: 'Lista de tareas',
221
289
  codeBlock: 'Bloque de código',
290
+ allNotes: 'Todas las notas',
291
+ overviewDescription: 'Todas las notas dejadas en esta documentación, página por página.',
292
+ statusOpen: 'Abiertas',
293
+ statusResolved: 'Resueltas',
294
+ statusAll: 'Todas',
295
+ everyone: 'Todos',
296
+ filter: 'Filtrar notas…',
297
+ openOnPage: 'Abrir en la página',
298
+ oneReply: '1 respuesta',
299
+ replies: '{n} respuestas',
300
+ noMatches: 'Ninguna nota coincide con estos filtros.',
301
+ overviewEmpty: 'Aún no hay notas.',
302
+ overviewUnavailable: 'Las notas no están disponibles en este sitio.',
303
+ loading: 'Cargando notas…',
304
+ showing: 'Estado',
305
+ author: 'Autor',
306
+ seeAll: 'Ver las notas de otras páginas.',
222
307
  };
223
308
 
224
309
  export const builtIn = { en, it, de, fr, es };
@@ -0,0 +1,172 @@
1
+ // The overview page: every note on the site, grouped by page, with filters.
2
+ // Read-only: a note opens on its page, where it can be answered or resolved.
3
+ import config from 'virtual:starlight-annotations/config';
4
+ import { createBackend } from './backend.js';
5
+ import { strings } from './i18n.js';
6
+ import { h, quoteText, renderMarkdown } from './shared.js';
7
+
8
+ const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
9
+ const T = strings(document.documentElement.lang, config.translations);
10
+ const container = document.querySelector('.annot-overview');
11
+ if (container instanceof HTMLElement) start(container);
12
+
13
+ // "guides/demo" -> "/base/guides/demo/", "index" -> "/base/", "it/index" -> "/base/it/".
14
+ function pageUrl(page) {
15
+ const path = page === 'index' ? '' : page.replace(/\/index$/, '');
16
+ return `${BASE}/${path ? `${path}/` : ''}`;
17
+ }
18
+
19
+ async function start(container) {
20
+ const titles = JSON.parse(container.dataset.titles || '{}');
21
+ const pages = await createBackend(config, BASE, T).list();
22
+ if (!pages) {
23
+ container.replaceChildren(h('p', {}, T.overviewUnavailable));
24
+ return;
25
+ }
26
+
27
+ // One entry per thread, with what the filters and the cards need.
28
+ const threads = pages.flatMap(({ page, annotations }) =>
29
+ annotations
30
+ .filter((item) => !item.replyTo)
31
+ .map((thread) => ({
32
+ page,
33
+ title: titles[page] ?? titles[page.replace(/\/index$/, '')] ?? page,
34
+ thread,
35
+ replies: annotations.filter((item) => item.replyTo === thread.id),
36
+ })),
37
+ );
38
+ if (threads.length === 0) {
39
+ container.replaceChildren(h('p', {}, T.overviewEmpty));
40
+ return;
41
+ }
42
+
43
+ // Filters live in the address, so a filtered view can be shared.
44
+ const params = new URLSearchParams(location.search);
45
+ const state = {
46
+ status: ['open', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
47
+ author: params.get('author') ?? '',
48
+ text: params.get('q') ?? '',
49
+ };
50
+
51
+ const counts = {
52
+ open: threads.filter((entry) => !entry.thread.resolved).length,
53
+ resolved: threads.filter((entry) => entry.thread.resolved).length,
54
+ all: threads.length,
55
+ };
56
+ const authors = new Map();
57
+ for (const { thread, replies } of threads)
58
+ for (const item of [thread, ...replies]) authors.set(item.author.login, item.author.name || item.author.login);
59
+
60
+ const status = h(
61
+ 'select',
62
+ { onchange: (event) => update({ status: event.target.value }) },
63
+ ['open', 'resolved', 'all'].map((value) =>
64
+ h(
65
+ 'option',
66
+ { value, selected: state.status === value },
67
+ `${{ open: T.statusOpen, resolved: T.statusResolved, all: T.statusAll }[value]} (${counts[value]})`,
68
+ ),
69
+ ),
70
+ );
71
+ const author = h(
72
+ 'select',
73
+ { onchange: (event) => update({ author: event.target.value }) },
74
+ h('option', { value: '' }, T.everyone),
75
+ [...authors]
76
+ .sort((a, b) => a[1].localeCompare(b[1]))
77
+ .map(([login, name]) => h('option', { value: login, selected: state.author === login }, name)),
78
+ );
79
+ const search = h('input', {
80
+ type: 'search',
81
+ value: state.text,
82
+ placeholder: T.filter,
83
+ 'aria-label': T.filter,
84
+ oninput: (event) => update({ text: event.target.value }),
85
+ });
86
+ const list = h('div', { class: 'annot-overview-list' });
87
+ container.replaceChildren(
88
+ h(
89
+ 'div',
90
+ { class: 'annot-overview-filters not-content' },
91
+ h('label', {}, T.showing, status),
92
+ h('label', {}, T.author, author),
93
+ search,
94
+ ),
95
+ list,
96
+ );
97
+
98
+ function update(change) {
99
+ Object.assign(state, change);
100
+ const query = new URLSearchParams();
101
+ if (state.status !== 'open') query.set('status', state.status);
102
+ if (state.author) query.set('author', state.author);
103
+ if (state.text) query.set('q', state.text);
104
+ const qs = String(query);
105
+ history.replaceState(null, '', `${location.pathname}${qs ? `?${qs}` : ''}`);
106
+ render();
107
+ }
108
+
109
+ function matches({ thread, replies }) {
110
+ if (state.status === 'open' && thread.resolved) return false;
111
+ if (state.status === 'resolved' && !thread.resolved) return false;
112
+ const messages = [thread, ...replies];
113
+ if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
114
+ const text = state.text.trim().toLowerCase();
115
+ if (!text) return true;
116
+ return [quoteText(thread.target.selector), ...messages.map((item) => item.body)].some((value) => value.toLowerCase().includes(text));
117
+ }
118
+
119
+ function card({ page, thread, replies }) {
120
+ const when = new Date(thread.created).toLocaleString(document.documentElement.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
121
+ const last = replies.at(-1);
122
+ return h(
123
+ 'article',
124
+ { class: `annot-thread annot-overview-card${thread.resolved ? ' resolved' : ''}` },
125
+ h('blockquote', { class: 'annot-quote' }, quoteText(thread.target.selector)),
126
+ h(
127
+ 'div',
128
+ { class: 'annot-meta' },
129
+ h('span', { class: 'annot-author', title: thread.author.login }, thread.author.name),
130
+ ' · ',
131
+ when,
132
+ thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
133
+ ),
134
+ renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
135
+ h(
136
+ 'div',
137
+ { class: 'annot-overview-footer' },
138
+ replies.length
139
+ ? h('span', {}, replies.length === 1 ? T.oneReply : T.replies.replace('{n}', String(replies.length)), last ? ` · ${last.author.name}` : '')
140
+ : h('span'),
141
+ h('a', { href: `${pageUrl(page)}#annotation-${encodeURIComponent(thread.id)}` }, `${T.openOnPage} →`),
142
+ ),
143
+ );
144
+ }
145
+
146
+ function render() {
147
+ const shown = threads.filter(matches);
148
+ if (shown.length === 0) {
149
+ list.replaceChildren(h('p', { class: 'annot-empty' }, T.noMatches));
150
+ return;
151
+ }
152
+ const byPage = new Map();
153
+ for (const entry of shown) byPage.set(entry.page, [...(byPage.get(entry.page) ?? []), entry]);
154
+ const groups = [...byPage].sort((a, b) => a[1][0].title.localeCompare(b[1][0].title));
155
+ list.replaceChildren(
156
+ ...groups.map(([page, entries]) =>
157
+ h(
158
+ 'section',
159
+ { class: 'annot-overview-page' },
160
+ h('h2', {}, h('a', { href: pageUrl(page) }, entries[0].title), h('span', { class: 'annot-count' }, String(entries.length))),
161
+ h(
162
+ 'div',
163
+ { class: 'not-content annot-overview-cards' },
164
+ entries.sort((a, b) => b.thread.created.localeCompare(a.thread.created)).map(card),
165
+ ),
166
+ ),
167
+ ),
168
+ );
169
+ }
170
+
171
+ render();
172
+ }
@@ -0,0 +1,73 @@
1
+ // Pieces shared by the notes panel and the overview page.
2
+ //
3
+ // Notes are written in Markdown (GitHub flavour) and stored as typed.
4
+ // micromark escapes raw HTML and drops javascript: links by default, so a
5
+ // note cannot inject markup into the page.
6
+
7
+ // ---- Markdown ----
8
+
9
+ // The Markdown parser is most of the client's weight, so it loads on demand:
10
+ // when the page has notes, or when the reader starts to write one. Until it
11
+ // arrives a note shows as plain text, then it is filled in.
12
+ let markdown = null;
13
+ let markdownLoading = null;
14
+ const waitingForMarkdown = new Map(); // element -> source
15
+
16
+ export function loadMarkdown() {
17
+ markdownLoading ??= Promise.all([import('micromark'), import('micromark-extension-gfm')]).then(([{ micromark }, { gfm, gfmHtml }]) => {
18
+ markdown = (source) => micromark(source, { extensions: [gfm()], htmlExtensions: [gfmHtml()] });
19
+ for (const [target, source] of waitingForMarkdown) if (target.isConnected) renderMarkdown(target, source);
20
+ waitingForMarkdown.clear();
21
+ }).catch(() => {
22
+ // Offline or blocked: notes stay as plain text, and the next note retries.
23
+ markdownLoading = null;
24
+ });
25
+ return markdownLoading;
26
+ }
27
+
28
+ export function renderMarkdown(target, source) {
29
+ if (!markdown) {
30
+ target.textContent = source;
31
+ target.classList.add('annot-md-pending');
32
+ waitingForMarkdown.set(target, source);
33
+ loadMarkdown();
34
+ return target;
35
+ }
36
+ target.classList.remove('annot-md-pending');
37
+ target.innerHTML = markdown(source);
38
+ for (const link of target.querySelectorAll('a[href]')) {
39
+ // micromark empties unsafe URLs (javascript: and the like): show plain text.
40
+ if (!link.getAttribute('href')) {
41
+ link.replaceWith(...link.childNodes);
42
+ continue;
43
+ }
44
+ link.target = '_blank';
45
+ link.rel = 'noopener noreferrer nofollow';
46
+ }
47
+ return target;
48
+ }
49
+
50
+ export function h(tag, attrs = {}, ...children) {
51
+ const el = document.createElement(tag);
52
+ for (const [key, value] of Object.entries(attrs)) {
53
+ if (value === undefined || value === false) continue;
54
+ if (key.startsWith('on')) el.addEventListener(key.slice(2), value);
55
+ else if (key === 'class') el.className = value;
56
+ else el.setAttribute(key, value === true ? '' : value);
57
+ }
58
+ for (const child of children.flat()) if (child != null && child !== false) el.append(child);
59
+ return el;
60
+ }
61
+
62
+ // What the panel shows: a long quote is cut in the middle.
63
+ export function quoteText(selector) {
64
+ const squash = (value) => value.replace(/\s+/g, ' ').trim();
65
+ if (selector.type === 'RangeSelector') {
66
+ // The stored edges are cut by length: drop the half words at the cut.
67
+ const head = squash(selector.startSelector.exact).replace(/\s+\S*$/, '');
68
+ const tail = squash(selector.endSelector.exact).replace(/^\S*\s+/, '');
69
+ return `${head} … ${tail}`;
70
+ }
71
+ const exact = squash(selector.exact);
72
+ return exact.length > 220 ? `${exact.slice(0, 130).trimEnd()} … ${exact.slice(-70).trimStart()}` : exact;
73
+ }
@@ -385,3 +385,61 @@ button.annot-ref:hover {
385
385
  display: none;
386
386
  }
387
387
  }
388
+
389
+ /* Link from the panel header to the overview page. */
390
+ .annot-all {
391
+ font-size: var(--sl-text-xs);
392
+ white-space: nowrap;
393
+ }
394
+
395
+ /* The overview page. */
396
+ .annot-overview-filters {
397
+ display: flex;
398
+ flex-wrap: wrap;
399
+ gap: 0.75rem 1.25rem;
400
+ align-items: center;
401
+ margin-bottom: 1.5rem;
402
+ font-size: var(--sl-text-sm);
403
+ }
404
+ .annot-overview-filters label {
405
+ display: flex;
406
+ gap: 0.4rem;
407
+ align-items: center;
408
+ color: var(--sl-color-gray-2);
409
+ }
410
+ .annot-overview-filters :is(select, input) {
411
+ padding: 0.3rem 0.5rem;
412
+ border: 1px solid var(--sl-color-gray-5);
413
+ border-radius: 0.4rem;
414
+ background: var(--sl-color-bg);
415
+ color: var(--sl-color-white);
416
+ font: inherit;
417
+ }
418
+ .annot-overview-filters input {
419
+ flex: 1 1 12rem;
420
+ }
421
+ .annot-overview-page h2 {
422
+ display: flex;
423
+ gap: 0.6rem;
424
+ align-items: center;
425
+ }
426
+ .annot-overview-page h2 .annot-count {
427
+ font-size: var(--sl-text-xs);
428
+ }
429
+ .annot-overview-cards {
430
+ display: grid;
431
+ gap: 0.75rem;
432
+ margin-top: 0.75rem;
433
+ }
434
+ .annot-overview-card {
435
+ font-size: var(--sl-text-sm);
436
+ }
437
+ .annot-overview-footer {
438
+ display: flex;
439
+ flex-wrap: wrap;
440
+ gap: 0.5rem;
441
+ justify-content: space-between;
442
+ margin-top: 0.6rem;
443
+ color: var(--sl-color-gray-3);
444
+ font-size: var(--sl-text-xs);
445
+ }
package/src/core.js CHANGED
@@ -36,6 +36,18 @@ export function filePath(page, dir = 'annotations') {
36
36
  return folder ? `${folder}/${checkPage(page)}.json` : `${checkPage(page)}.json`;
37
37
  }
38
38
 
39
+ // The page of a stored file, or null for anything else in the folder.
40
+ export function pageFromPath(file, dir = 'annotations') {
41
+ const folder = String(dir).replace(/^\/+|\/+$/g, '');
42
+ const prefix = folder ? `${folder}/` : '';
43
+ if (!file.startsWith(prefix) || !file.endsWith('.json')) return null;
44
+ try {
45
+ return checkPage(file.slice(prefix.length, -'.json'.length));
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
39
51
  export function emptyDocument(page) {
40
52
  return { version: FORMAT_VERSION, page, annotations: [] };
41
53
  }
@@ -0,0 +1,22 @@
1
+ ---
2
+ // The overview page, added by the plugin at `/<overview>/`. The list itself
3
+ // is drawn in the browser (client/overview.js), from the same API as the
4
+ // notes panel; here only the page titles are known, from the content.
5
+ import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
6
+ import { getCollection } from 'astro:content';
7
+ import config from 'virtual:starlight-annotations/config';
8
+ import { strings } from './client/i18n.js';
9
+
10
+ const T = strings(config.lang, config.translations);
11
+ const docs = await getCollection('docs');
12
+ const titles = Object.fromEntries(docs.map((entry) => [entry.id, entry.data.title]));
13
+ ---
14
+
15
+ <StarlightPage frontmatter={{ title: T.allNotes, description: T.overviewDescription, tableOfContents: false, pagefind: false, editUrl: false }}>
16
+ <div class="annot-overview" data-titles={JSON.stringify(titles)}>
17
+ <p>{T.loading}</p>
18
+ </div>
19
+ <script>
20
+ import './client/overview.js';
21
+ </script>
22
+ </StarlightPage>
@@ -12,6 +12,7 @@ import { AnnotationError, parseDocument, serializeDocument } from '../core.js';
12
12
  * write: (page: string, text: string, version: string | undefined, message: string, user: object) =>
13
13
  * Promise<'ok' | 'conflict' | 'missing-branch'>,
14
14
  * createBranch: () => Promise<void>,
15
+ * pages?: () => Promise<string[]>,
15
16
  * }} host
16
17
  */
17
18
  export function gitStorage(host) {
@@ -25,6 +26,14 @@ export function gitStorage(host) {
25
26
  async load(page) {
26
27
  return (await read(page)).doc;
27
28
  },
29
+ // Every page with a notes file, for the overview. One request to list the
30
+ // files, then one per page, a few at a time.
31
+ ...(host.pages && {
32
+ async list() {
33
+ const pages = await host.pages();
34
+ return mapLimit(pages, 6, async (page) => ({ page, annotations: (await read(page)).doc.annotations }));
35
+ },
36
+ }),
28
37
  async update(page, mutate, user) {
29
38
  let branchCreated = false;
30
39
  for (let attempt = 0; attempt < 4; attempt++) {
@@ -49,3 +58,16 @@ export function gitStorage(host) {
49
58
  },
50
59
  };
51
60
  }
61
+
62
+ async function mapLimit(items, limit, run) {
63
+ const results = new Array(items.length);
64
+ let next = 0;
65
+ const worker = async () => {
66
+ while (next < items.length) {
67
+ const i = next++;
68
+ results[i] = await run(items[i]);
69
+ }
70
+ };
71
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
72
+ return results;
73
+ }
@@ -8,7 +8,7 @@
8
8
  // Sign-in: an OAuth2 application on the server. Only people with write
9
9
  // access to the repository may annotate, unless `writers` says otherwise.
10
10
 
11
- import { filePath } from '../core.js';
11
+ import { filePath, pageFromPath } from '../core.js';
12
12
  import { gitStorage } from './git-storage.js';
13
13
  import { oauthAuth } from './oauth.js';
14
14
  import { decodeText, encodeText, required, restClient } from './util.js';
@@ -60,6 +60,20 @@ export function giteaStorage({ host, repo, token, branch = 'annotations', dir =
60
60
  throw new Error(`Gitea ${sha ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
61
61
  },
62
62
 
63
+ async pages() {
64
+ const pages = [];
65
+ // The tree comes in pages; `truncated` says there is more.
66
+ for (let page = 1; page <= 50; page++) {
67
+ const tree = await api.get(`/repos/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=true&per_page=1000&page=${page}`, {
68
+ allow404: true,
69
+ });
70
+ if (!tree) break; // No notes branch yet.
71
+ for (const entry of tree.tree ?? []) if (entry.type === 'blob') pages.push(pageFromPath(entry.path, dir));
72
+ if (!tree.truncated) break;
73
+ }
74
+ return pages.filter(Boolean);
75
+ },
76
+
63
77
  async createBranch() {
64
78
  const info = await api.get(`/repos/${repo}`);
65
79
  const response = await api.raw(`/repos/${repo}/branches`, {
@@ -0,0 +1,100 @@
1
+ // Server credentials from a GitHub App instead of a personal access token.
2
+ //
3
+ // The server signs a short JWT with the app's private key, finds the app's
4
+ // installation on `repo`, and exchanges the JWT for an installation token
5
+ // limited to that one repository. The token lasts an hour; it is kept in
6
+ // memory and renewed five minutes before it expires.
7
+ //
8
+ // Unlike a personal token, an app belongs to no one: it survives people
9
+ // leaving, needs no approval as a personal token in an organization, and
10
+ // its commits show the app as committer (the reader stays the author).
11
+
12
+ import { base64url, fromBase64, required, restClient } from './util.js';
13
+
14
+ const API = 'https://api.github.com';
15
+ const HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
16
+ const RENEW_BEFORE = 5 * 60 * 1000;
17
+
18
+ /**
19
+ * A function that returns a valid installation token for `repo`.
20
+ * @param {{ appId: string | number, privateKey: string, installationId?: string | number, repo: string }} options
21
+ * @returns {() => Promise<string>}
22
+ */
23
+ export function githubAppToken({ appId, privateKey, installationId, repo }) {
24
+ required({ appId, privateKey, repo }, 'githubAppToken');
25
+ const name = repo.split('/')[1];
26
+ let key;
27
+ let installation = installationId;
28
+ let current;
29
+ let pending;
30
+
31
+ async function appJwt() {
32
+ key ??= await crypto.subtle.importKey('pkcs8', pkcs8(privateKey), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']);
33
+ const now = Math.floor(Date.now() / 1000);
34
+ // 60 s in the past for clock drift; GitHub accepts at most 10 minutes.
35
+ const part = (value) => base64url(new TextEncoder().encode(JSON.stringify(value)));
36
+ const unsigned = `${part({ alg: 'RS256', typ: 'JWT' })}.${part({ iat: now - 60, exp: now + 540, iss: String(appId) })}`;
37
+ const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(unsigned));
38
+ return `${unsigned}.${base64url(new Uint8Array(signature))}`;
39
+ }
40
+
41
+ async function mint() {
42
+ const api = restClient({ base: API, headers: { ...HEADERS, Authorization: `Bearer ${await appJwt()}` }, label: 'GitHub App' });
43
+ if (!installation) {
44
+ const found = await api.get(`/repos/${repo}/installation`, { allow404: true });
45
+ if (!found) throw new Error(`starlight-annotations: the GitHub App ${appId} is not installed on ${repo}.`);
46
+ installation = found.id;
47
+ }
48
+ const response = await api.raw(`/app/installations/${installation}/access_tokens`, {
49
+ method: 'POST',
50
+ body: JSON.stringify({ repositories: [name] }),
51
+ });
52
+ if (!response.ok) throw new Error(`GitHub App token ${response.status}: ${await response.text()}`);
53
+ const { token, expires_at: expiresAt } = await response.json();
54
+ return { token, expires: Date.parse(expiresAt) };
55
+ }
56
+
57
+ return async function installationToken() {
58
+ if (current && current.expires - Date.now() > RENEW_BEFORE) return current.token;
59
+ // Requests that arrive together share one renewal.
60
+ const renewal = (pending ??= mint()
61
+ .then((fresh) => (current = fresh))
62
+ .finally(() => (pending = undefined)));
63
+ return (await renewal).token;
64
+ };
65
+ }
66
+
67
+ // GitHub downloads keys as PKCS#1 ("BEGIN RSA PRIVATE KEY"); Web Crypto
68
+ // imports PKCS#8 ("BEGIN PRIVATE KEY"). Both are accepted, also with the
69
+ // line breaks written as "\n", as they often are in environment variables.
70
+ export function pkcs8(pem) {
71
+ const text = String(pem).replace(/\\n/g, '\n').trim();
72
+ const der = fromBase64(text.replace(/-----(BEGIN|END)[^-]*-----/g, '').replace(/\s/g, ''));
73
+ if (text.includes('BEGIN PRIVATE KEY')) return der;
74
+ if (text.includes('BEGIN RSA PRIVATE KEY')) {
75
+ // PrivateKeyInfo { version 0, AlgorithmIdentifier { rsaEncryption, NULL }, OCTET STRING { the PKCS#1 key } }
76
+ const rsaEncryption = Uint8Array.of(0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00);
77
+ return node(0x30, concat(Uint8Array.of(0x02, 0x01, 0x00), rsaEncryption, node(0x04, der)));
78
+ }
79
+ throw new Error('starlight-annotations: the GitHub App private key must be a PEM ("BEGIN RSA PRIVATE KEY" or "BEGIN PRIVATE KEY").');
80
+ }
81
+
82
+ function node(tag, content) {
83
+ const length = [];
84
+ if (content.length < 0x80) length.push(content.length);
85
+ else {
86
+ for (let n = content.length; n > 0; n >>= 8) length.unshift(n & 0xff);
87
+ length.unshift(0x80 | length.length);
88
+ }
89
+ return concat(Uint8Array.of(tag, ...length), content);
90
+ }
91
+
92
+ function concat(...parts) {
93
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
94
+ let offset = 0;
95
+ for (const part of parts) {
96
+ out.set(part, offset);
97
+ offset += part.length;
98
+ }
99
+ return out;
100
+ }
@@ -6,33 +6,53 @@
6
6
  // branch on the first save. Each commit has the reader as author (their
7
7
  // noreply address), so `git log` and `git blame` show who wrote what.
8
8
  //
9
- // Sign-in: a GitHub OAuth app. Only people with write access to `repo` may
10
- // annotate, unless `writers` says otherwise.
9
+ // Sign-in: a GitHub OAuth app, or the client id and secret of a GitHub App.
10
+ // Only people with write access to `repo` may annotate, unless `writers`
11
+ // says otherwise.
12
+ //
13
+ // Server credentials: a token, or `app` ({ appId, privateKey }) for a GitHub
14
+ // App installed on `repo` (see github-app.js).
11
15
 
12
- import { filePath } from '../core.js';
16
+ import { filePath, pageFromPath } from '../core.js';
17
+ import { githubAppToken } from './github-app.js';
13
18
  import { gitStorage } from './git-storage.js';
14
19
  import { oauthAuth } from './oauth.js';
15
20
  import { decodeText, encodeText, required, restClient } from './util.js';
16
21
 
22
+ // `token` is a string, or a function that returns one (a GitHub App).
17
23
  const client = (token) =>
18
24
  restClient({
19
25
  base: 'https://api.github.com',
20
- headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
26
+ headers: async () => ({
27
+ Authorization: `Bearer ${typeof token === 'function' ? await token() : token}`,
28
+ Accept: 'application/vnd.github+json',
29
+ 'X-GitHub-Api-Version': '2022-11-28',
30
+ }),
21
31
  label: 'GitHub',
22
32
  });
23
33
 
34
+ // The server credential: `token` as given, or installation tokens of `app`.
35
+ function serverToken({ repo, token, app }, where) {
36
+ if (token) return token;
37
+ if (app) return githubAppToken({ ...app, repo });
38
+ throw new Error(`starlight-annotations: ${where} needs token or app.`);
39
+ }
40
+
24
41
  /**
25
- * Storage and sign-in together, which is what most sites want.
42
+ * Storage and sign-in together, which is what most sites want. With `app`,
43
+ * both share one installation token.
26
44
  * @param {import('../../server').GitHubOptions} options
27
45
  */
28
46
  export function github(options) {
29
- return { storage: githubStorage(options), auth: githubAuth(options) };
47
+ const token = options.token || options.app ? serverToken(options, 'github') : undefined;
48
+ const shared = { ...options, token, app: undefined };
49
+ return { storage: githubStorage(shared), auth: githubAuth(shared) };
30
50
  }
31
51
 
32
52
  /** @param {import('../../server').GitHubStorageOptions} options */
33
- export function githubStorage({ repo, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
34
- required({ repo, token }, 'githubStorage');
35
- const api = client(token);
53
+ export function githubStorage({ repo, token, app, branch = 'annotations', dir = 'annotations', commitMessage }) {
54
+ required({ repo }, 'githubStorage');
55
+ const api = client(serverToken({ repo, token, app }, 'githubStorage'));
36
56
  const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
37
57
 
38
58
  return gitStorage({
@@ -64,6 +84,13 @@ export function githubStorage({ repo, token, branch = 'annotations', dir = 'anno
64
84
  throw new Error(`GitHub PUT ${response.status}: ${detail}`);
65
85
  },
66
86
 
87
+ async pages() {
88
+ const tree = await api.get(`/repos/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=1`, { allow404: true });
89
+ if (!tree) return []; // No notes branch yet.
90
+ if (tree.truncated) console.warn('starlight-annotations: the notes branch is too large to list in one request; some pages are missing.');
91
+ return tree.tree.filter((entry) => entry.type === 'blob').map((entry) => pageFromPath(entry.path, dir)).filter(Boolean);
92
+ },
93
+
67
94
  async createBranch() {
68
95
  const info = await api.get(`/repos/${repo}`);
69
96
  const head = await api.get(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
@@ -78,8 +105,12 @@ export function githubStorage({ repo, token, branch = 'annotations', dir = 'anno
78
105
  }
79
106
 
80
107
  /** @param {import('../../server').GitHubAuthOptions} options */
81
- export function githubAuth({ repo, token, writers = 'collaborators', ...options }) {
82
- if (writers === 'collaborators') required({ repo, token }, 'githubAuth with writers "collaborators"');
108
+ export function githubAuth({ repo, token, app, writers = 'collaborators', ...options }) {
109
+ let server;
110
+ if (writers === 'collaborators') {
111
+ required({ repo }, 'githubAuth with writers "collaborators"');
112
+ server = serverToken({ repo, token, app }, 'githubAuth with writers "collaborators"');
113
+ }
83
114
  return oauthAuth({
84
115
  ...options,
85
116
  writers,
@@ -96,7 +127,7 @@ export function githubAuth({ repo, token, writers = 'collaborators', ...options
96
127
  // counts as write, triage as read. On a public repository GitHub answers
97
128
  // "read" for anyone, so read access is not enough.
98
129
  async canWrite(profile) {
99
- const permission = await client(token).get(`/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, {
130
+ const permission = await client(server).get(`/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, {
100
131
  allow404: true,
101
132
  });
102
133
  return permission?.permission === 'admin' || permission?.permission === 'write';
@@ -9,7 +9,7 @@
9
9
  // project members with the Developer role or higher may annotate, unless
10
10
  // `writers` says otherwise.
11
11
 
12
- import { filePath } from '../core.js';
12
+ import { filePath, pageFromPath } from '../core.js';
13
13
  import { gitStorage } from './git-storage.js';
14
14
  import { oauthAuth } from './oauth.js';
15
15
  import { decodeText, encodeText, required, restClient } from './util.js';
@@ -69,6 +69,20 @@ export function gitlabStorage({ host, project, token, branch = 'annotations', di
69
69
  throw new Error(`GitLab ${lastCommitId ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
70
70
  },
71
71
 
72
+ async pages() {
73
+ const folder = String(dir).replace(/^\/+|\/+$/g, '');
74
+ const pages = [];
75
+ for (let page = 1; page <= 50; page++) {
76
+ const query = new URLSearchParams({ ref: branch, recursive: 'true', per_page: '100', page: String(page) });
77
+ if (folder) query.set('path', folder);
78
+ const entries = await api.get(`/projects/${id}/repository/tree?${query}`, { allow404: true });
79
+ if (!entries) break; // No notes branch, or no folder yet.
80
+ for (const entry of entries) if (entry.type === 'blob') pages.push(pageFromPath(entry.path, dir));
81
+ if (entries.length < 100) break;
82
+ }
83
+ return pages.filter(Boolean);
84
+ },
85
+
72
86
  async createBranch() {
73
87
  const info = await api.get(`/projects/${id}`);
74
88
  const response = await api.raw(
@@ -8,12 +8,14 @@
8
8
  //
9
9
  // Routes, under `prefix` (default "/_annotations"):
10
10
  // GET /api?page=<page> notes of a page, and who is signed in
11
+ // GET /api/all notes of every page, for the overview
11
12
  // POST /api { page, change } applies one change
12
13
  // GET /login /callback /logout handled by the auth, when it has them
13
14
 
14
15
  import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json } from '../core.js';
15
16
 
16
17
  export { github, githubAuth, githubStorage } from './github.js';
18
+ export { githubAppToken } from './github-app.js';
17
19
  export { gitlab, gitlabAuth, gitlabStorage } from './gitlab.js';
18
20
  export { forgejo, gitea, giteaAuth, giteaStorage } from './gitea.js';
19
21
  export { AnnotationError } from '../core.js';
@@ -57,6 +59,13 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
57
59
  );
58
60
  }
59
61
 
62
+ if (route === '/api/all' && request.method === 'GET') {
63
+ if (!storage.list) return json({ error: 'This storage cannot list pages.' }, 501);
64
+ const pages = (await storage.list()).filter((entry) => entry.annotations.length > 0);
65
+ pages.sort((a, b) => a.page.localeCompare(b.page));
66
+ return json({ pages, mode: auth?.mode ?? storage.mode ?? 'api' });
67
+ }
68
+
60
69
  if (route === '/api' && request.method === 'POST') {
61
70
  const origin = request.headers.get('Origin');
62
71
  if (origin && origin !== url.origin) return json({ error: 'Cross-site request refused.' }, 403);
@@ -94,6 +103,7 @@ export function staticAuth(user) {
94
103
  * @typedef {{
95
104
  * mode?: string,
96
105
  * load(page: string): Promise<AnnotationDocument>,
106
+ * list?(): Promise<{ page: string, annotations: object[] }[]>,
97
107
  * update(page: string, mutate: (doc: AnnotationDocument) => { annotation: object, message: string }, user: User):
98
108
  * Promise<{ annotation: object, annotations: object[] }>,
99
109
  * }} Storage
@@ -2,9 +2,9 @@
2
2
  // IncomingMessage/ServerResponse to the Web-standard handler (used by the dev
3
3
  // server, and usable with Express, Fastify or plain node:http).
4
4
 
5
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { filePath, parseDocument, serializeDocument } from '../core.js';
7
+ import { filePath, pageFromPath, parseDocument, serializeDocument } from '../core.js';
8
8
 
9
9
  /**
10
10
  * Notes as JSON files in a folder. Good for development, or for a Node
@@ -29,6 +29,17 @@ export function fsStorage({ dir }) {
29
29
  return {
30
30
  mode: 'local',
31
31
  load,
32
+ async list() {
33
+ let files;
34
+ try {
35
+ files = await readdir(dir, { recursive: true });
36
+ } catch (error) {
37
+ if (error.code === 'ENOENT') return [];
38
+ throw error;
39
+ }
40
+ const pages = files.map((file) => pageFromPath(file.split(path.sep).join('/'), '')).filter(Boolean);
41
+ return Promise.all(pages.map(async (page) => ({ page, annotations: (await load(page)).annotations })));
42
+ },
32
43
  update(page, mutate) {
33
44
  const run = async () => {
34
45
  const doc = await load(page);
@@ -63,14 +63,15 @@ export function timingSafeEqual(left, right) {
63
63
  }
64
64
 
65
65
  // A small REST client: JSON in and out, `null` for an allowed 404.
66
+ // `headers` may be a function, for credentials that change (GitHub App).
66
67
  export function restClient({ base, headers, label }) {
67
- const raw = (path, init = {}) =>
68
+ const raw = async (path, init = {}) =>
68
69
  fetch(`${base}${path}`, {
69
70
  ...init,
70
71
  headers: {
71
72
  Accept: 'application/json',
72
73
  'User-Agent': 'starlight-annotations',
73
- ...headers,
74
+ ...(typeof headers === 'function' ? await headers() : headers),
74
75
  ...(init.body ? { 'Content-Type': 'application/json' } : {}),
75
76
  },
76
77
  });