starlight-annotations 0.0.0-stage โ†’ 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alessandro Rosa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # ๐Ÿ–๏ธ starlight-annotations
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/starlight-annotations?color=blue)](https://www.npmjs.com/package/starlight-annotations)
4
+ [![CI](https://github.com/alessandroros/starlight-annotations/actions/workflows/ci.yml/badge.svg)](https://github.com/alessandroros/starlight-annotations/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/alessandroros/starlight-annotations/blob/main/LICENSE)
6
+ [![Starlight plugin](https://img.shields.io/badge/Starlight-plugin-8a55f6)](https://starlight.astro.build/resources/plugins/)
7
+
8
+ Let readers highlight text and leave notes on your [Starlight](https://starlight.astro.build) docs. Notes are JSON files committed to your Git repository, not stored by a third-party service.
9
+
10
+ **๐Ÿ“– [Documentation](https://alessandroros.github.io/starlight-annotations/) ยท โœจ [Live demo](https://alessandroros.github.io/starlight-annotations/guides/demo/)**
11
+
12
+ ## Features
13
+
14
+ - ๐Ÿ’ฌ **Select, note, discuss.** Markdown notes with a formatting toolbar, replies, "in reply to" references, resolve and reopen.
15
+ - ๐Ÿ“Œ **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
+ - ๐Ÿ—‚๏ธ **Your repo, your data.** One file per page on a branch of its own; every note is a commit by its author.
17
+ - ๐ŸŒ **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.
18
+ - ๐Ÿชถ **Light and safe.** Highlights use the CSS Custom Highlight API, so the page markup is never rewritten. Notes cannot inject HTML, and the Markdown parser loads only when it is needed.
19
+ - ๐ŸŒ **Multilingual.** English, Italian, German, French and Spanish built in; the UI follows the page language.
20
+
21
+ ## ๐Ÿš€ Quick start
22
+
23
+ ```sh
24
+ npm install starlight-annotations
25
+ ```
26
+
27
+ ```js
28
+ // astro.config.mjs
29
+ import starlight from '@astrojs/starlight';
30
+ import { defineConfig } from 'astro/config';
31
+ import starlightAnnotations from 'starlight-annotations';
32
+
33
+ export default defineConfig({
34
+ integrations: [
35
+ starlight({
36
+ title: 'My docs',
37
+ plugins: [starlightAnnotations()],
38
+ }),
39
+ ],
40
+ });
41
+ ```
42
+
43
+ Run `npm run dev`, select text on any page and press **Annotate**. During development notes are written to `.annotations/` in your project.
44
+
45
+ ## โ˜๏ธ Publish
46
+
47
+ Mount the handler next to your pages, for example on a Cloudflare Worker:
48
+
49
+ ```js
50
+ import { createAnnotationsHandler, github } from 'starlight-annotations/server';
51
+
52
+ export default {
53
+ async fetch(request, env) {
54
+ const annotations = createAnnotationsHandler(
55
+ github({
56
+ repo: 'owner/docs',
57
+ token: env.GITHUB_TOKEN,
58
+ clientId: env.GITHUB_CLIENT_ID,
59
+ clientSecret: env.GITHUB_CLIENT_SECRET,
60
+ sessionSecret: env.ANNOTATIONS_SECRET,
61
+ }),
62
+ );
63
+ return (await annotations(request)) ?? env.ASSETS.fetch(request);
64
+ },
65
+ };
66
+ ```
67
+
68
+ See [Store notes on GitHub](https://alessandroros.github.io/starlight-annotations/guides/github/) for the OAuth app and the token, and [other hosts](https://alessandroros.github.io/starlight-annotations/guides/other-hosts/) for Netlify, Vercel, Node and Astro endpoints.
69
+
70
+ No server? `starlightAnnotations({ backend: 'browser' })` keeps notes in each reader's browser.
71
+
72
+ ## ๐Ÿ“„ License
73
+
74
+ MIT ยฉ Alessandro Rosa
package/index.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import type { StarlightPlugin } from '@astrojs/starlight/types';
2
+
3
+ export type AnnotationStrings = {
4
+ annotate: string;
5
+ notes: string;
6
+ newNote: string;
7
+ placeholder: string;
8
+ replyPlaceholder: string;
9
+ save: string;
10
+ cancel: string;
11
+ reply: string;
12
+ resolve: string;
13
+ reopen: string;
14
+ delete: string;
15
+ confirmDelete: string;
16
+ confirmDeleteReply: string;
17
+ inReplyTo: string;
18
+ replyingTo: string;
19
+ deletedMessage: string;
20
+ close: string;
21
+ showResolved: string;
22
+ empty: string;
23
+ orphans: string;
24
+ login: string;
25
+ logout: string;
26
+ local: string;
27
+ browserOnly: string;
28
+ you: string;
29
+ resolved: string;
30
+ write: string;
31
+ preview: string;
32
+ nothing: string;
33
+ markdown: string;
34
+ formatting: string;
35
+ bold: string;
36
+ italic: string;
37
+ strike: string;
38
+ code: string;
39
+ link: string;
40
+ quote: string;
41
+ bullets: string;
42
+ numbers: string;
43
+ tasks: string;
44
+ codeBlock: string;
45
+ };
46
+
47
+ export interface StarlightAnnotationsOptions {
48
+ /**
49
+ * Where notes are read and written.
50
+ * - `"api"` (default): the annotation handler on the same origin
51
+ * (see `starlight-annotations/server`). The UI stays hidden when it does not answer.
52
+ * - `"browser"`: localStorage only. No server and no sign-in; notes stay on the device.
53
+ */
54
+ backend?: 'api' | 'browser';
55
+ /** Path of the handler, relative to the site base. Default `"/_annotations"`. */
56
+ apiBase?: string;
57
+ /** The element whose text can be annotated. Default `".sl-markdown-content"`. */
58
+ content?: string;
59
+ /** More selectors whose text is ignored, on top of diagrams, buttons and heading anchors. */
60
+ exclude?: string[];
61
+ /** Selections longer than this (characters) are stored by their start and end. Default 400. */
62
+ longQuote?: number;
63
+ /** Override UI strings per language, e.g. `{ it: { annotate: 'Commenta' } }`. */
64
+ translations?: Record<string, Partial<AnnotationStrings>>;
65
+ /** localStorage key prefix for the `"browser"` backend. Default `"starlight-annotations"`. */
66
+ storageKey?: string;
67
+ /**
68
+ * The API served by `astro dev` for the `"api"` backend: notes on disk, author from
69
+ * `git config user.name`. `false` turns it off (for example to proxy a real API).
70
+ */
71
+ dev?: false | { dir?: string; user?: { login: string; name?: string } };
72
+ }
73
+
74
+ export default function starlightAnnotations(options?: StarlightAnnotationsOptions): StarlightPlugin;
package/index.js ADDED
@@ -0,0 +1,111 @@
1
+ // starlight-annotations: let readers highlight text and leave notes on a
2
+ // Starlight site. See README.md for the options and the server setup.
3
+
4
+ import { execFileSync } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const VIRTUAL_ID = 'virtual:starlight-annotations/config';
9
+ const RESOLVED_ID = `\0${VIRTUAL_ID}`;
10
+
11
+ /** @param {import('./index').StarlightAnnotationsOptions} [options] */
12
+ export default function starlightAnnotations(options = {}) {
13
+ const config = resolveOptions(options);
14
+ return {
15
+ name: 'starlight-annotations',
16
+ hooks: {
17
+ 'config:setup'({ addIntegration, config: starlightConfig, updateConfig }) {
18
+ // Starlight links customCss on every page, in dev and in the build.
19
+ // (CSS imported by an injected script is bundled but not linked.)
20
+ updateConfig({ customCss: [...(starlightConfig.customCss ?? []), 'starlight-annotations/styles.css'] });
21
+ addIntegration(annotationsIntegration(config));
22
+ },
23
+ },
24
+ };
25
+ }
26
+
27
+ function resolveOptions(options) {
28
+ const backend = options.backend ?? 'api';
29
+ if (backend !== 'api' && backend !== 'browser') {
30
+ throw new Error(`starlight-annotations: "backend" must be "api" or "browser", not ${JSON.stringify(backend)}.`);
31
+ }
32
+ const apiBase = (options.apiBase ?? '/_annotations').replace(/\/$/, '');
33
+ const longQuote = options.longQuote ?? 400;
34
+ if (!Number.isInteger(longQuote) || longQuote < 100) {
35
+ throw new Error('starlight-annotations: "longQuote" must be an integer of at least 100.');
36
+ }
37
+ return {
38
+ backend,
39
+ apiBase,
40
+ content: options.content ?? '.sl-markdown-content',
41
+ exclude: options.exclude ?? [],
42
+ longQuote,
43
+ translations: options.translations ?? {},
44
+ storageKey: options.storageKey ?? 'starlight-annotations',
45
+ dev: options.dev ?? {},
46
+ };
47
+ }
48
+
49
+ function annotationsIntegration(config) {
50
+ // Only what the browser needs goes into the bundle.
51
+ const { dev, ...clientConfig } = config;
52
+ let base = '';
53
+ let root = process.cwd();
54
+
55
+ return {
56
+ name: 'starlight-annotations',
57
+ hooks: {
58
+ 'astro:config:setup'({ config: astroConfig, injectScript, updateConfig }) {
59
+ base = astroConfig.base.replace(/\/$/, '');
60
+ root = fileURLToPath(astroConfig.root);
61
+ updateConfig({
62
+ vite: {
63
+ plugins: [
64
+ {
65
+ name: 'starlight-annotations-config',
66
+ resolveId: (id) => (id === VIRTUAL_ID ? RESOLVED_ID : undefined),
67
+ load: (id) => (id === RESOLVED_ID ? `export default ${JSON.stringify(clientConfig)};` : undefined),
68
+ },
69
+ ],
70
+ },
71
+ });
72
+ injectScript('page', `import 'starlight-annotations/client';`);
73
+ },
74
+
75
+ // `astro dev` serves the same API from disk, so the feature works
76
+ // without a server. The author is your `git config user.name`.
77
+ async 'astro:server:setup'({ server, logger }) {
78
+ if (config.backend !== 'api' || dev === false || !config.apiBase.startsWith('/')) return;
79
+ const { createAnnotationsHandler, staticAuth } = await import('./src/server/index.js');
80
+ const { fsStorage, toNodeMiddleware } = await import('./src/server/node.js');
81
+ const dir = path.resolve(root, dev.dir ?? '.annotations');
82
+ const middleware = toNodeMiddleware(
83
+ createAnnotationsHandler({
84
+ storage: fsStorage({ dir }),
85
+ auth: staticAuth(dev.user ?? gitUser(root)),
86
+ prefix: config.apiBase,
87
+ }),
88
+ );
89
+ // Vite may or may not have stripped the site base from req.url yet.
90
+ server.middlewares.use((req, res, next) => {
91
+ const url = base && req.url?.startsWith(`${base}${config.apiBase}/`) ? req.url.slice(base.length) : req.url;
92
+ if (!url?.startsWith(`${config.apiBase}/`)) return next();
93
+ req.url = url;
94
+ return middleware(req, res, next);
95
+ });
96
+ logger.info(`Notes are stored in ${path.relative(root, dir) || '.'} during development.`);
97
+ },
98
+ },
99
+ };
100
+ }
101
+
102
+ function gitUser(cwd) {
103
+ let name = '';
104
+ try {
105
+ name = execFileSync('git', ['config', 'user.name'], { cwd, encoding: 'utf8' }).trim();
106
+ } catch {
107
+ // Not a Git checkout, or no name set.
108
+ }
109
+ name ||= 'local';
110
+ return { login: name.toLowerCase().replace(/[^a-z0-9-]+/g, '-'), name };
111
+ }
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "๐Ÿ–๏ธ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository.",
5
+ "license": "MIT",
6
+ "author": "Alessandro Rosa",
7
+ "type": "module",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/alessandroros/starlight-annotations.git",
11
+ "directory": "packages/starlight-annotations"
12
+ },
13
+ "homepage": "https://alessandroros.github.io/starlight-annotations/",
14
+ "bugs": "https://github.com/alessandroros/starlight-annotations/issues",
15
+ "keywords": [
16
+ "withastro",
17
+ "starlight",
18
+ "starlight-plugin",
19
+ "astro",
20
+ "annotations",
21
+ "comments",
22
+ "documentation",
23
+ "web-annotation",
24
+ "highlight",
25
+ "notes",
26
+ "feedback",
27
+ "docs-review"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./index.d.ts",
32
+ "default": "./index.js"
33
+ },
34
+ "./server": {
35
+ "types": "./server.d.ts",
36
+ "default": "./src/server/index.js"
37
+ },
38
+ "./server/node": {
39
+ "types": "./server-node.d.ts",
40
+ "default": "./src/server/node.js"
41
+ },
42
+ "./client": "./src/client/annotations.js",
43
+ "./styles.css": "./src/client/styles.css",
44
+ "./package.json": "./package.json"
45
+ },
46
+ "files": [
47
+ "index.js",
48
+ "index.d.ts",
49
+ "server.d.ts",
50
+ "server-node.d.ts",
51
+ "src"
52
+ ],
53
+ "scripts": {
54
+ "test": "vitest run"
55
+ },
56
+ "peerDependencies": {
57
+ "@astrojs/starlight": ">=0.30.0"
58
+ },
59
+ "dependencies": {
60
+ "micromark": "^4.0.3",
61
+ "micromark-extension-gfm": "^3.0.0"
62
+ },
63
+ "devDependencies": {
64
+ "vitest": "~5.0.0"
65
+ },
66
+ "engines": {
67
+ "node": ">=20"
68
+ },
69
+ "publishConfig": {
70
+ "access": "public",
71
+ "provenance": true
72
+ }
73
+ }
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Storage } from './server';
3
+
4
+ /** Notes as JSON files under `dir`. */
5
+ export function fsStorage(options: { dir: string }): Storage;
6
+
7
+ /** Wraps a Web handler as Node/Connect/Express middleware. */
8
+ export function toNodeMiddleware(
9
+ handler: (request: Request) => Promise<Response | null>,
10
+ ): (req: IncomingMessage, res: ServerResponse, next?: (error?: unknown) => void) => Promise<void>;
package/server.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ export interface User {
2
+ login: string;
3
+ name?: string;
4
+ id?: number;
5
+ }
6
+
7
+ export interface AnnotationDocument {
8
+ version: number;
9
+ page: string;
10
+ annotations: Record<string, unknown>[];
11
+ }
12
+
13
+ export interface Storage {
14
+ mode?: string;
15
+ load(page: string): Promise<AnnotationDocument>;
16
+ update(
17
+ page: string,
18
+ mutate: (doc: AnnotationDocument) => { annotation: Record<string, unknown>; message: string },
19
+ user: User,
20
+ ): Promise<{ annotation: Record<string, unknown>; annotations: Record<string, unknown>[] }>;
21
+ }
22
+
23
+ export interface Auth {
24
+ mode?: string;
25
+ user(request: Request): Promise<User | null>;
26
+ route?(route: string, request: Request, url: URL, prefix: string): Promise<Response | null>;
27
+ }
28
+
29
+ export interface HandlerOptions {
30
+ storage: Storage;
31
+ auth?: Auth;
32
+ /** Path the handler answers on, including the site base. Default `"/_annotations"`. */
33
+ prefix?: string;
34
+ }
35
+
36
+ /** A Web-standard handler. Resolves to `null` when the path is not under `prefix`. */
37
+ export function createAnnotationsHandler(options: HandlerOptions): (request: Request) => Promise<Response | null>;
38
+
39
+ export interface GitHubStorageOptions {
40
+ /** `owner/name` of the repository that stores the notes. */
41
+ repo: string;
42
+ /** Token with Contents read/write (and Metadata read) on `repo`. */
43
+ token: string;
44
+ /** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
45
+ branch?: string;
46
+ /** Folder for the notes in the branch. Default `"annotations"`. */
47
+ dir?: string;
48
+ /** Rewrite the commit message, e.g. to fit your commit convention. */
49
+ commitMessage?: (message: string, page: string) => string;
50
+ }
51
+
52
+ export interface GitHubAuthOptions {
53
+ clientId: string;
54
+ clientSecret: string;
55
+ /** A long random string that signs the session cookie. */
56
+ sessionSecret: string;
57
+ /**
58
+ * Who may write. `"collaborators"` (default) checks the reader's permission on `repo`
59
+ * with `token`. `"anyone"` accepts every GitHub user.
60
+ */
61
+ writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
62
+ repo?: string;
63
+ token?: string;
64
+ /** Set to false only for plain-http local testing. Default true. */
65
+ cookieSecure?: boolean;
66
+ }
67
+
68
+ export function githubStorage(options: GitHubStorageOptions): Storage;
69
+ export function githubAuth(options: GitHubAuthOptions): Auth;
70
+ export function github(options: GitHubStorageOptions & GitHubAuthOptions): { storage: Storage; auth: Auth };
71
+
72
+ /** A fixed identity: for local development, or a site behind its own login. */
73
+ export function staticAuth(user: User): Auth;
74
+
75
+ export class AnnotationError extends Error {
76
+ status: number;
77
+ }