starlight-annotations 0.9.0 โ†’ 0.10.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,11 @@
1
1
  # starlight-annotations
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ba3c36b: With `issues: true` in the GitHub options (or `{ repo }` for another repository), every open thread has **Open issue**: the server opens a GitHub issue with the quote, a link back and the whole conversation, labelled with the note's kind, then resolves the note and links the issue in the panel and on the overview page. The credential needs Issues read/write. `onChange` receives the new `issue` action, which Slack and Teams post.
8
+
3
9
  ## 0.9.0
4
10
 
5
11
  ### Minor Changes
package/index.d.ts CHANGED
@@ -77,6 +77,9 @@ export type AnnotationStrings = {
77
77
  kindDecision: string;
78
78
  wholePage: string;
79
79
  pageNote: string;
80
+ openIssue: string;
81
+ confirmIssue: string;
82
+ issue: string;
80
83
  };
81
84
 
82
85
  export interface StarlightAnnotationsOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.9.0",
3
+ "version": "0.10.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
@@ -20,6 +20,14 @@ export interface Storage {
20
20
  mutate: (doc: AnnotationDocument) => { annotation: Record<string, unknown>; message: string },
21
21
  user: User,
22
22
  ): Promise<{ annotation: Record<string, unknown>; annotations: Record<string, unknown>[] }>;
23
+ /** Opens an issue for a thread. When present, the panel offers "Open issue". Optional. */
24
+ createIssue?(input: {
25
+ page: string;
26
+ thread: Record<string, any>;
27
+ replies: Record<string, any>[];
28
+ url: string;
29
+ user: User;
30
+ }): Promise<{ number: number; url: string }>;
23
31
  }
24
32
 
25
33
  export interface Auth {
@@ -38,7 +46,7 @@ export interface Auth {
38
46
  openContact?(sealed: string): Promise<string | null>;
39
47
  }
40
48
 
41
- export type AnnotationAction = 'create' | 'reply' | 'resolve' | 'reopen' | 'edit' | 'anchor' | 'delete';
49
+ export type AnnotationAction = 'create' | 'reply' | 'resolve' | 'reopen' | 'edit' | 'anchor' | 'issue' | 'delete';
42
50
 
43
51
  /** What `onChange` receives after every saved change. */
44
52
  export interface AnnotationEvent {
@@ -110,6 +118,12 @@ export interface GitHubStorageOptions {
110
118
  dir?: string;
111
119
  /** Rewrite the commit message, e.g. to fit your commit convention. */
112
120
  commitMessage?: (message: string, page: string) => string;
121
+ /**
122
+ * Let readers turn a thread into a GitHub issue, which resolves the note.
123
+ * `true` opens issues in `repo`; `{ repo }` in another repository. The token
124
+ * or GitHub App needs Issues read/write there.
125
+ */
126
+ issues?: boolean | { repo?: string };
113
127
  }
114
128
 
115
129
  export interface GitHubAppOptions {
@@ -169,6 +169,7 @@ async function start(root) {
169
169
  annotations: initial.annotations,
170
170
  user: initial.user,
171
171
  mode: initial.mode,
172
+ issues: Boolean(initial.issues), // the server can turn a thread into an issue
172
173
  index: null,
173
174
  anchors: new Map(), // id -> { start, end, range }
174
175
  pending: null, // the selector of the selection being annotated
@@ -425,6 +426,10 @@ async function start(root) {
425
426
  }
426
427
 
427
428
  // The quoted passage, or "Whole page" for a note about the page.
429
+ function issueLink(issue) {
430
+ return h('a', { class: 'annot-issue', href: issue.url, target: '_blank', rel: 'noopener noreferrer' }, `${T.issue} #${issue.number} โ†—`);
431
+ }
432
+
428
433
  function quote(selector) {
429
434
  if (!selector) return h('div', { class: 'annot-quote annot-whole-page' }, T.wholePage);
430
435
  return h('blockquote', { class: 'annot-quote' }, quoteText(selector));
@@ -540,6 +545,7 @@ async function start(root) {
540
545
  ),
541
546
  ...(thread.kind ? [h('span', { class: `annot-kind annot-kind-${thread.kind}` }, kindLabel(thread.kind, T))] : []),
542
547
  ...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
548
+ ...(thread.issue ? [issueLink(thread.issue)] : []),
543
549
  ...moveBox(),
544
550
  h('div', { class: `annot-message${fresh(thread) ? ' annot-fresh' : ''}`, 'data-msg': thread.id }, meta(thread), text(thread)),
545
551
  ...repliesOf(thread.id).map((reply) =>
@@ -568,6 +574,24 @@ async function start(root) {
568
574
  { class: 'annot-actions' },
569
575
  h('button', { type: 'button', onclick: () => openReply(null) }, T.reply),
570
576
  h('button', { type: 'button', onclick: () => send({ action: 'resolve', id: thread.id, resolved: !thread.resolved }) }, thread.resolved ? T.reopen : T.resolve),
577
+ state.issues && !thread.issue && !thread.resolved
578
+ ? h(
579
+ 'button',
580
+ {
581
+ type: 'button',
582
+ onclick: async (event) => {
583
+ if (!confirm(T.confirmIssue)) return;
584
+ event.currentTarget.disabled = true;
585
+ if (!(await send({ action: 'issue', id: thread.id }))) return;
586
+ // The note is now resolved: keep it in view, with its link.
587
+ state.showResolved = true;
588
+ resolvedBox.checked = true;
589
+ focusThread(thread.id, false);
590
+ },
591
+ },
592
+ T.openIssue,
593
+ )
594
+ : null,
571
595
  ...ownActions(thread, T.confirmDelete),
572
596
  ),
573
597
  );
@@ -78,6 +78,9 @@ const en = {
78
78
  kindDecision: 'Decision',
79
79
  wholePage: 'Whole page',
80
80
  pageNote: 'Note on this page',
81
+ openIssue: 'Open issue',
82
+ confirmIssue: 'Open a GitHub issue with this conversation? The note will be resolved.',
83
+ issue: 'Issue',
81
84
  };
82
85
 
83
86
  const it = {
@@ -157,6 +160,9 @@ const it = {
157
160
  kindDecision: 'Decisione',
158
161
  wholePage: 'Tutta la pagina',
159
162
  pageNote: 'Nota sulla pagina',
163
+ openIssue: 'Apri issue',
164
+ confirmIssue: 'Aprire una issue su GitHub con questa conversazione? La nota verrร  risolta.',
165
+ issue: 'Issue',
160
166
  };
161
167
 
162
168
  const de = {
@@ -236,6 +242,9 @@ const de = {
236
242
  kindDecision: 'Entscheidung',
237
243
  wholePage: 'Ganze Seite',
238
244
  pageNote: 'Notiz zur Seite',
245
+ openIssue: 'Issue รถffnen',
246
+ confirmIssue: 'Ein GitHub-Issue mit dieser Unterhaltung รถffnen? Die Notiz wird als erledigt markiert.',
247
+ issue: 'Issue',
239
248
  };
240
249
 
241
250
  const fr = {
@@ -315,6 +324,9 @@ const fr = {
315
324
  kindDecision: 'Dรฉcision',
316
325
  wholePage: 'Toute la page',
317
326
  pageNote: 'Note sur la page',
327
+ openIssue: 'Ouvrir une issue',
328
+ confirmIssue: 'Ouvrir une issue GitHub avec cette conversation ? La note sera rรฉsolue.',
329
+ issue: 'Issue',
318
330
  };
319
331
 
320
332
  const es = {
@@ -394,6 +406,9 @@ const es = {
394
406
  kindDecision: 'Decisiรณn',
395
407
  wholePage: 'Toda la pรกgina',
396
408
  pageNote: 'Nota sobre la pรกgina',
409
+ openIssue: 'Abrir issue',
410
+ confirmIssue: 'ยฟAbrir una issue de GitHub con esta conversaciรณn? La nota se resolverรก.',
411
+ issue: 'Issue',
397
412
  };
398
413
 
399
414
  export const builtIn = { en, it, de, fr, es };
@@ -158,6 +158,9 @@ async function start(container) {
158
158
  ' ยท ',
159
159
  when,
160
160
  thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
161
+ thread.issue
162
+ ? h('a', { class: 'annot-issue', href: thread.issue.url, target: '_blank', rel: 'noopener noreferrer' }, `${T.issue} #${thread.issue.number} โ†—`)
163
+ : null,
161
164
  fresh ? h('span', { class: 'annot-badge annot-fresh-label' }, T.fresh) : null,
162
165
  !thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
163
166
  ),
@@ -234,6 +234,12 @@
234
234
  .annot-kind-select {
235
235
  margin-left: auto;
236
236
  }
237
+ .annot-issue {
238
+ align-self: flex-start;
239
+ margin-left: 0.4rem;
240
+ font-size: var(--sl-text-xs);
241
+ font-weight: 600;
242
+ }
237
243
  .annot-badge.annot-changed {
238
244
  margin-left: 0.4rem;
239
245
  background: var(--sl-color-orange-low);
package/src/core.js CHANGED
@@ -124,6 +124,8 @@ function kindOf(value) {
124
124
  // { action: 'resolve', id, resolved }
125
125
  // { action: 'edit', id, body, kind? } the author changes their message
126
126
  // { action: 'anchor', id, target } a thread moves to another passage
127
+ // { action: 'issue', id, issue: { number, url } } the thread became an issue
128
+ // (the handler fills `issue` after creating it)
127
129
  // { action: 'delete', id }
128
130
  // It returns the annotation it touched, and a commit message.
129
131
  export function applyChange(doc, change, user, now = new Date()) {
@@ -198,6 +200,19 @@ export function applyChange(doc, change, user, now = new Date()) {
198
200
  annotation.movedAt = created;
199
201
  return { annotation, message: `docs(annotations): move note on ${doc.page}` };
200
202
  }
203
+ case 'issue': {
204
+ const annotation = find(change.id);
205
+ if (annotation.replyTo) throw new AnnotationError(400, 'Only a thread can become an issue.');
206
+ if (annotation.issue) throw new AnnotationError(409, 'This note already has an issue.');
207
+ const { number, url } = change.issue ?? {};
208
+ if (!Number.isInteger(number) || number < 1 || !/^https:\/\//.test(String(url))) throw new AnnotationError(400, 'Invalid issue.');
209
+ annotation.issue = { number, url };
210
+ // The conversation goes on in the issue: the note is done.
211
+ annotation.resolved = true;
212
+ annotation.resolvedBy = author;
213
+ annotation.resolvedAt = created;
214
+ return { annotation, message: `docs(annotations): open issue #${number} for a note on ${doc.page}` };
215
+ }
201
216
  case 'delete': {
202
217
  const annotation = find(change.id);
203
218
  if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can delete a note.');
@@ -13,9 +13,10 @@
13
13
  // Server credentials: a token, or `app` ({ appId, privateKey }) for a GitHub
14
14
  // App installed on `repo` (see github-app.js).
15
15
 
16
- import { filePath, pageFromPath } from '../core.js';
16
+ import { AnnotationError, filePath, pageFromPath } from '../core.js';
17
17
  import { githubAppToken } from './github-app.js';
18
18
  import { gitStorage } from './git-storage.js';
19
+ import { issueContent } from './issue.js';
19
20
  import { oauthAuth } from './oauth.js';
20
21
  import { decodeText, encodeText, required, restClient } from './util.js';
21
22
 
@@ -45,17 +46,20 @@ function serverToken({ repo, token, app }, where) {
45
46
  */
46
47
  export function github(options) {
47
48
  const token = options.token || options.app ? serverToken(options, 'github') : undefined;
48
- const shared = { ...options, token, app: undefined };
49
+ // Issues in another repository need an installation token for that one.
50
+ const elsewhere = options.app && options.issues?.repo && options.issues.repo !== options.repo;
51
+ const issues = elsewhere ? { ...options.issues, token: githubAppToken({ ...options.app, repo: options.issues.repo }) } : options.issues;
52
+ const shared = { ...options, token, app: undefined, issues };
49
53
  return { storage: githubStorage(shared), auth: githubAuth(shared) };
50
54
  }
51
55
 
52
56
  /** @param {import('../../server').GitHubStorageOptions} options */
53
- export function githubStorage({ repo, token, app, branch = 'annotations', dir = 'annotations', commitMessage }) {
57
+ export function githubStorage({ repo, token, app, branch = 'annotations', dir = 'annotations', commitMessage, issues }) {
54
58
  required({ repo }, 'githubStorage');
55
59
  const api = client(serverToken({ repo, token, app }, 'githubStorage'));
56
60
  const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
57
61
 
58
- return gitStorage({
62
+ const storage = gitStorage({
59
63
  mode: 'github',
60
64
  commitMessage,
61
65
 
@@ -102,6 +106,31 @@ export function githubStorage({ repo, token, app, branch = 'annotations', dir =
102
106
  if (!response.ok && response.status !== 422) throw new Error(`GitHub create branch ${response.status}: ${await response.text()}`);
103
107
  },
104
108
  });
109
+
110
+ // With `issues`, a thread can become a GitHub issue, in `repo` or in
111
+ // `issues.repo`. The server credential opens it: a GitHub App needs the
112
+ // repository permission "Issues: Read and write".
113
+ if (issues) {
114
+ const issueRepo = issues === true ? repo : issues.repo || repo;
115
+ const issueApi = issueRepo === repo ? api : client(issues.token ?? serverToken({ repo: issueRepo, token, app }, 'githubStorage issues'));
116
+ storage.createIssue = async (input) => {
117
+ const { title, body, labels } = issueContent({ ...input, profile: (login) => `https://github.com/${encodeURIComponent(login)}` });
118
+ const open = (withLabels) =>
119
+ issueApi.raw(`/repos/${issueRepo}/issues`, { method: 'POST', body: JSON.stringify({ title, body, ...(withLabels.length ? { labels: withLabels } : {}) }) });
120
+ let response = await open(labels);
121
+ // Labels the token may not create: open the issue without them.
122
+ if (response.status === 422 && labels.length) response = await open([]);
123
+ if (!response.ok) {
124
+ const detail = await response.text();
125
+ if (response.status === 403 || response.status === 404 || response.status === 410)
126
+ throw new AnnotationError(502, `Could not open an issue on ${issueRepo}: issues may be turned off there, or the server credential cannot write issues.`);
127
+ throw new Error(`GitHub create issue ${response.status}: ${detail}`);
128
+ }
129
+ const issue = await response.json();
130
+ return { number: issue.number, url: issue.html_url };
131
+ };
132
+ }
133
+ return storage;
105
134
  }
106
135
 
107
136
  /** @param {import('../../server').GitHubAuthOptions} options */
@@ -107,6 +107,7 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX,
107
107
  user: user && { login: user.login, name: user.name },
108
108
  mode: auth?.mode ?? storage.mode ?? 'api',
109
109
  canSignIn: Boolean(auth?.route),
110
+ issues: Boolean(storage.createIssue),
110
111
  },
111
112
  200,
112
113
  revoked && auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {},
@@ -131,10 +132,24 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX,
131
132
  const error = auth.noAccess ? auth.noAccess(user.login) : 'You may no longer annotate these docs.';
132
133
  return json({ error, signedOut: true }, 403, auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {});
133
134
  }
134
- const { page, change } = await request.json();
135
+ const body = await request.json();
136
+ const page = checkPage(body.page);
137
+ let change = body.change;
138
+ // A thread becomes an issue: open it first, then record it on the note.
139
+ if (change?.action === 'issue') {
140
+ if (!storage.createIssue) return json({ error: 'Issues are not turned on for these notes.' }, 400);
141
+ const doc = await storage.load(page);
142
+ const thread = doc.annotations.find((item) => item.id === change.id);
143
+ if (!thread) return json({ error: 'Annotation not found.' }, 404);
144
+ if (thread.replyTo) return json({ error: 'Only a thread can become an issue.' }, 400);
145
+ if (thread.issue) return json({ error: 'This note already has an issue.' }, 409);
146
+ const replies = doc.annotations.filter((item) => item.replyTo === thread.id);
147
+ const issue = await storage.createIssue({ page, thread, replies, url: linkTo(page, request, url, thread.id), user });
148
+ change = { action: 'issue', id: thread.id, issue };
149
+ }
135
150
  // With `emails`, new notes carry the writer's email, sealed.
136
151
  const writer = auth?.sealContact && user.email ? { ...user, contact: await auth.sealContact(user.email) } : user;
137
- const saved = await storage.update(checkPage(page), (doc) => applyChange(doc, change, writer), writer);
152
+ const saved = await storage.update(page, (doc) => applyChange(doc, change, writer), writer);
138
153
  const result = { ...saved, annotation: withoutContact(saved.annotation), annotations: saved.annotations.map(withoutContact) };
139
154
  if (listeners.length) {
140
155
  const deleted = change.action === 'delete';
@@ -173,6 +188,7 @@ export function staticAuth(user) {
173
188
  * list?(): Promise<{ page: string, annotations: object[] }[]>,
174
189
  * update(page: string, mutate: (doc: AnnotationDocument) => { annotation: object, message: string }, user: User):
175
190
  * Promise<{ annotation: object, annotations: object[] }>,
191
+ * createIssue?(input: { page: string, thread: object, replies: object[], url: string, user: User }): Promise<{ number: number, url: string }>,
176
192
  * }} Storage
177
193
  * @typedef {{
178
194
  * mode?: string,
@@ -0,0 +1,59 @@
1
+ // The issue a thread becomes: a title from its first words, the quoted
2
+ // passage, a link back to the note, and the whole conversation.
3
+ import { quoteOf } from './notify.js';
4
+
5
+ // GitHub labels for the kinds of note.
6
+ const LABELS = { question: 'question', issue: 'problem', proposal: 'proposal', decision: 'decision' };
7
+
8
+ /**
9
+ * @param {{
10
+ * page: string,
11
+ * thread: Record<string, any>,
12
+ * replies: Record<string, any>[],
13
+ * url: string,
14
+ * user: { login: string, name?: string },
15
+ * profile: (login: string) => string,
16
+ * }} input
17
+ * @returns {{ title: string, body: string, labels: string[] }}
18
+ */
19
+ export function issueContent({ page, thread, replies, url, user, profile }) {
20
+ // People are links to their profile, not "@login": opening an issue should
21
+ // not notify everyone in the thread. Mentions they wrote themselves stay.
22
+ const person = (who) => `[${who.name || who.login}](${profile(who.login)})`;
23
+ const quote = quoteOf(thread);
24
+ const message = (item) => `**${person(item.author)}** ยท ${when(item.created)}${item.edited ? ' (edited)' : ''}\n\n${item.body}`;
25
+ const body = [
26
+ quote ? quote.split('\n').map((line) => `> ${line}`).join('\n') : '**Whole page**',
27
+ `[Open the note on ${page}](${url})`,
28
+ ...[thread, ...replies].map(message),
29
+ `<sub>Opened by ${person(user)} from the review notes.</sub>`,
30
+ ].join('\n\n---\n\n');
31
+ return {
32
+ title: titleOf(thread.body) || `Note on ${page}`,
33
+ body,
34
+ labels: thread.kind && LABELS[thread.kind] ? [LABELS[thread.kind]] : [],
35
+ };
36
+ }
37
+
38
+ // The first line of a Markdown message, as plain text, cut at a word.
39
+ function titleOf(markdown) {
40
+ const line =
41
+ String(markdown ?? '')
42
+ .replace(/```[\s\S]*?```/g, ' ')
43
+ .split('\n')
44
+ .map((value) => value.trim())
45
+ .find(Boolean) ?? '';
46
+ const plain = line
47
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
48
+ .replace(/^[>#\-*+\s]+|^\d+\.\s+/g, '')
49
+ .replace(/[*_~`]/g, '')
50
+ .trim();
51
+ if (plain.length <= 80) return plain;
52
+ const cut = plain.slice(0, 80);
53
+ return `${cut.slice(0, cut.lastIndexOf(' ') > 40 ? cut.lastIndexOf(' ') : 80).trimEnd()}โ€ฆ`;
54
+ }
55
+
56
+ // "2026-11-24T10:05:00Z" -> "2026-11-24 10:05 UTC"
57
+ function when(iso) {
58
+ return `${String(iso).slice(0, 10)} ${String(iso).slice(11, 16)} UTC`;
59
+ }
@@ -8,7 +8,7 @@
8
8
  // let you reach people too, with your own login -> address map.
9
9
 
10
10
  // What the Slack and Teams senders post by default: not edits and moves.
11
- const ACTIONS = ['create', 'reply', 'resolve', 'reopen', 'delete'];
11
+ const ACTIONS = ['create', 'reply', 'resolve', 'reopen', 'issue', 'delete'];
12
12
 
13
13
  // "@ada" and "@ada-l" in a message, not inside an email address or code span.
14
14
  const MENTION = /(?<![\w`.@/])@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})(?![\w-])/gi;
@@ -66,6 +66,7 @@ export function describeChange(event) {
66
66
  reopen: `${who} reopened a note on ${event.page}`,
67
67
  edit: `${who} edited a note on ${event.page}`,
68
68
  anchor: `${who} moved a note on ${event.page}`,
69
+ issue: `${who} opened issue #${event.annotation?.issue?.number} for a note on ${event.page}`,
69
70
  delete: `${who} deleted a note on ${event.page}`,
70
71
  }[event.action];
71
72
  const quote = quoteOf(event.thread);