@glw907/cairn-cms 0.17.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/components/DeleteDialog.svelte +81 -0
  2. package/dist/components/DeleteDialog.svelte.d.ts +21 -0
  3. package/dist/components/DeleteDialog.svelte.d.ts.map +1 -0
  4. package/dist/components/EditPage.svelte +136 -10
  5. package/dist/components/EditPage.svelte.d.ts +10 -0
  6. package/dist/components/EditPage.svelte.d.ts.map +1 -1
  7. package/dist/components/LinkPicker.svelte +109 -0
  8. package/dist/components/LinkPicker.svelte.d.ts +18 -0
  9. package/dist/components/LinkPicker.svelte.d.ts.map +1 -0
  10. package/dist/components/MarkdownEditor.svelte +33 -3
  11. package/dist/components/MarkdownEditor.svelte.d.ts +5 -0
  12. package/dist/components/MarkdownEditor.svelte.d.ts.map +1 -1
  13. package/dist/components/RenameDialog.svelte +72 -0
  14. package/dist/components/RenameDialog.svelte.d.ts +20 -0
  15. package/dist/components/RenameDialog.svelte.d.ts.map +1 -0
  16. package/dist/components/index.d.ts +3 -0
  17. package/dist/components/index.d.ts.map +1 -1
  18. package/dist/components/index.js +3 -0
  19. package/dist/components/link-completion.d.ts +16 -0
  20. package/dist/components/link-completion.d.ts.map +1 -0
  21. package/dist/components/link-completion.js +48 -0
  22. package/dist/components/markdown-format.d.ts +25 -5
  23. package/dist/components/markdown-format.d.ts.map +1 -1
  24. package/dist/components/markdown-format.js +85 -0
  25. package/dist/content/compose.d.ts.map +1 -1
  26. package/dist/content/compose.js +1 -0
  27. package/dist/content/ids.d.ts +7 -0
  28. package/dist/content/ids.d.ts.map +1 -1
  29. package/dist/content/ids.js +11 -0
  30. package/dist/content/links.d.ts +21 -0
  31. package/dist/content/links.d.ts.map +1 -0
  32. package/dist/content/links.js +52 -0
  33. package/dist/content/manifest.d.ts +69 -0
  34. package/dist/content/manifest.d.ts.map +1 -0
  35. package/dist/content/manifest.js +140 -0
  36. package/dist/content/types.d.ts +10 -1
  37. package/dist/content/types.d.ts.map +1 -1
  38. package/dist/delivery/index.d.ts +1 -0
  39. package/dist/delivery/index.d.ts.map +1 -1
  40. package/dist/delivery/index.js +1 -0
  41. package/dist/delivery/manifest.d.ts +13 -0
  42. package/dist/delivery/manifest.d.ts.map +1 -0
  43. package/dist/delivery/manifest.js +38 -0
  44. package/dist/github/repo.d.ts +21 -0
  45. package/dist/github/repo.d.ts.map +1 -1
  46. package/dist/github/repo.js +86 -0
  47. package/dist/index.d.ts +4 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +5 -0
  50. package/dist/render/pipeline.d.ts +4 -1
  51. package/dist/render/pipeline.d.ts.map +1 -1
  52. package/dist/render/pipeline.js +7 -2
  53. package/dist/render/resolve-links.d.ts +8 -0
  54. package/dist/render/resolve-links.d.ts.map +1 -0
  55. package/dist/render/resolve-links.js +36 -0
  56. package/dist/render/sanitize-schema.d.ts.map +1 -1
  57. package/dist/render/sanitize-schema.js +9 -0
  58. package/dist/sveltekit/content-routes.d.ts +13 -1
  59. package/dist/sveltekit/content-routes.d.ts.map +1 -1
  60. package/dist/sveltekit/content-routes.js +182 -7
  61. package/dist/sveltekit/public-routes.d.ts +2 -0
  62. package/dist/sveltekit/public-routes.d.ts.map +1 -1
  63. package/dist/sveltekit/public-routes.js +2 -1
  64. package/package.json +2 -1
  65. package/src/lib/components/DeleteDialog.svelte +81 -0
  66. package/src/lib/components/EditPage.svelte +136 -10
  67. package/src/lib/components/LinkPicker.svelte +109 -0
  68. package/src/lib/components/MarkdownEditor.svelte +33 -3
  69. package/src/lib/components/RenameDialog.svelte +72 -0
  70. package/src/lib/components/index.ts +3 -0
  71. package/src/lib/components/link-completion.ts +57 -0
  72. package/src/lib/components/markdown-format.ts +82 -0
  73. package/src/lib/content/compose.ts +1 -0
  74. package/src/lib/content/ids.ts +12 -0
  75. package/src/lib/content/links.ts +61 -0
  76. package/src/lib/content/manifest.ts +190 -0
  77. package/src/lib/content/types.ts +10 -3
  78. package/src/lib/delivery/index.ts +1 -0
  79. package/src/lib/delivery/manifest.ts +44 -0
  80. package/src/lib/github/repo.ts +110 -0
  81. package/src/lib/index.ts +17 -0
  82. package/src/lib/render/pipeline.ts +8 -2
  83. package/src/lib/render/resolve-links.ts +42 -0
  84. package/src/lib/render/sanitize-schema.ts +9 -0
  85. package/src/lib/sveltekit/content-routes.ts +209 -10
  86. package/src/lib/sveltekit/public-routes.ts +4 -2
@@ -0,0 +1,190 @@
1
+ // cairn-cms: the content manifest, a committed JSON projection of the corpus (content-graph
2
+ // design). The files in git stay the source of truth; the manifest exists so request-time admin
3
+ // code reads the content graph without an N+1 GitHub crawl. The build regenerates and verifies
4
+ // it; the save path patches one entry and commits it with the content in one commit. Each entry
5
+ // carries its identity and its outbound cairn: edges, so the manifest is the link graph.
6
+ import { idFromFilename, slugFromId } from './ids.js';
7
+ import { parseMarkdown } from './frontmatter.js';
8
+ import { permalink } from './permalink.js';
9
+ import { extractCairnLinks, type CairnRef, type LinkResolve } from './links.js';
10
+ import type { ConceptDescriptor } from './types.js';
11
+
12
+ /** One entry's projection: its identity, routing, draft flag, and outbound cairn: edges. */
13
+ export interface ManifestEntry {
14
+ id: string;
15
+ concept: string;
16
+ title: string;
17
+ date?: string;
18
+ permalink: string;
19
+ draft: boolean;
20
+ links: CairnRef[];
21
+ }
22
+
23
+ /** The whole corpus as one committed file. `version` guards a future shape migration. */
24
+ export interface Manifest {
25
+ version: 1;
26
+ entries: ManifestEntry[];
27
+ }
28
+
29
+ /** The minimal entry view the preview resolver and (later) the picker read. */
30
+ export interface LinkTarget {
31
+ concept: string;
32
+ id: string;
33
+ permalink: string;
34
+ title: string;
35
+ date?: string;
36
+ draft: boolean;
37
+ }
38
+
39
+ function basename(path: string): string {
40
+ const slash = path.lastIndexOf('/');
41
+ return slash >= 0 ? path.slice(slash + 1) : path;
42
+ }
43
+
44
+ /** Mirror content-index's frontmatter coercion: a present non-empty string, else undefined. */
45
+ function asString(value: unknown): string | undefined {
46
+ return typeof value === 'string' && value.trim() ? value : undefined;
47
+ }
48
+
49
+ /** Mirror content-index's date coercion: an unquoted YAML date is a JS Date, a string is sliced. */
50
+ function asDate(value: unknown): string | undefined {
51
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString().slice(0, 10);
52
+ if (typeof value === 'string') return value.match(/^\d{4}-\d{2}-\d{2}/)?.[0];
53
+ return undefined;
54
+ }
55
+
56
+ /** Build one manifest entry from a content file. Drafts are included and flagged. */
57
+ export function manifestEntryFromFile(descriptor: ConceptDescriptor, file: { path: string; raw: string }): ManifestEntry {
58
+ const id = idFromFilename(basename(file.path));
59
+ // Use the same slug rule content-index uses, so the manifest's permalink for an entry always
60
+ // equals content-index's permalink for it. A cairn link must resolve to one URL whether the
61
+ // admin preview reads the manifest or the public build reads the content index.
62
+ const slug = slugFromId(id, descriptor.routing.dated ? descriptor.datePrefix : null);
63
+ const { frontmatter, body } = parseMarkdown(file.raw);
64
+ const date = asDate(frontmatter.date);
65
+ return {
66
+ id,
67
+ concept: descriptor.id,
68
+ title: asString(frontmatter.title) ?? id,
69
+ date,
70
+ permalink: permalink(descriptor, { id, slug, date }),
71
+ draft: frontmatter.draft === true,
72
+ links: extractCairnLinks(body),
73
+ };
74
+ }
75
+
76
+ /** An empty manifest, the starting point when no committed file exists yet. */
77
+ export function emptyManifest(): Manifest {
78
+ return { version: 1, entries: [] };
79
+ }
80
+
81
+ function compareRef(a: CairnRef, b: CairnRef): number {
82
+ return a.concept.localeCompare(b.concept) || a.id.localeCompare(b.id);
83
+ }
84
+
85
+ /** Serialize canonically: entries sorted by concept then id, links sorted and deduped, a fixed key
86
+ * order, two-space pretty, and a trailing newline, so the committed file diffs cleanly in a PR. */
87
+ export function serializeManifest(manifest: Manifest): string {
88
+ const entries = [...manifest.entries].sort(compareRef).map((e) => ({
89
+ id: e.id,
90
+ concept: e.concept,
91
+ title: e.title,
92
+ ...(e.date ? { date: e.date } : {}),
93
+ permalink: e.permalink,
94
+ draft: e.draft,
95
+ links: [...e.links].sort(compareRef).map((r) => ({ concept: r.concept, id: r.id })),
96
+ }));
97
+ return `${JSON.stringify({ version: 1, entries }, null, 2)}\n`;
98
+ }
99
+
100
+ /** Parse a committed manifest. Throws on malformed JSON, a wrong version, or a malformed entry, so
101
+ * every reader (the save guard, the delete path, the preview) sees a well-formed graph or a clear
102
+ * error. The build regenerates the manifest, so a real file is always canonical; this guards a
103
+ * hand-edited or truncated one. */
104
+ export function parseManifest(raw: string): Manifest {
105
+ const data = JSON.parse(raw) as unknown;
106
+ if (!data || typeof data !== 'object') {
107
+ throw new Error('content manifest: malformed file, expected { version, entries: [] }');
108
+ }
109
+ const obj = data as { version?: unknown; entries?: unknown };
110
+ if (obj.version !== 1) {
111
+ throw new Error(`content manifest: unsupported version ${String(obj.version)}, expected 1`);
112
+ }
113
+ if (!Array.isArray(obj.entries)) {
114
+ throw new Error('content manifest: malformed file, expected { version, entries: [] }');
115
+ }
116
+ for (const entry of obj.entries) {
117
+ const e = entry as Record<string, unknown>;
118
+ const ok =
119
+ e &&
120
+ typeof e.id === 'string' &&
121
+ typeof e.concept === 'string' &&
122
+ typeof e.title === 'string' &&
123
+ typeof e.permalink === 'string' &&
124
+ typeof e.draft === 'boolean' &&
125
+ (e.date === undefined || typeof e.date === 'string') &&
126
+ Array.isArray(e.links);
127
+ if (!ok) {
128
+ throw new Error(`content manifest: malformed entry ${JSON.stringify(e)}`);
129
+ }
130
+ // Validate each link element's shape, not just that links is an array. inboundLinks and the
131
+ // delete guard read l.concept and l.id, so a string, null, or id-less element would read as
132
+ // undefined and silently drop a real inbound linker. Reject it here instead.
133
+ for (const link of e.links as unknown[]) {
134
+ const l = link as Record<string, unknown> | null;
135
+ if (!l || typeof l !== 'object' || typeof l.concept !== 'string' || typeof l.id !== 'string') {
136
+ throw new Error(`content manifest: malformed link ${JSON.stringify(link)} in entry ${JSON.stringify(e)}`);
137
+ }
138
+ }
139
+ }
140
+ return { version: 1, entries: obj.entries as ManifestEntry[] };
141
+ }
142
+
143
+ /** Throw if the committed manifest drifts from what the corpus says. Both sides are compared in the
144
+ * canonical serialized form, so semantic equality never spuriously fails. The build calls this so a
145
+ * raw-git content edit, which leaves the committed manifest stale, fails the build loudly. */
146
+ export function verifyManifest(built: Manifest, committedRaw: string): void {
147
+ if (committedRaw !== serializeManifest(built)) {
148
+ throw new Error(
149
+ 'content manifest is stale: the committed file does not match the corpus. Regenerate it (npm run cairn:manifest) and commit the result.',
150
+ );
151
+ }
152
+ }
153
+
154
+ /** Replace the entry with the same concept and id, or add it. Order does not matter, since
155
+ * serializeManifest sorts. This is the save path's incremental patch. */
156
+ export function upsertEntry(manifest: Manifest, entry: ManifestEntry): Manifest {
157
+ const entries = manifest.entries.filter((e) => !(e.concept === entry.concept && e.id === entry.id));
158
+ entries.push(entry);
159
+ return { version: 1, entries };
160
+ }
161
+
162
+ /** Drop the entry with the given concept and id, if present. The delete path's patch. */
163
+ export function removeEntry(manifest: Manifest, concept: string, id: string): Manifest {
164
+ return { version: 1, entries: manifest.entries.filter((e) => !(e.concept === concept && e.id === id)) };
165
+ }
166
+
167
+ /** One inbound linker: enough to name it and link to its edit page in the delete guard. */
168
+ export interface InboundLink {
169
+ concept: string;
170
+ id: string;
171
+ title: string;
172
+ permalink: string;
173
+ }
174
+
175
+ /** Every entry whose outbound edges point at the target, excluding the target itself. The delete
176
+ * guard reads this to name "what links here"; the backlinks panel will reuse it. Pure over the
177
+ * manifest, so the request-time delete path and a unit test call it the same way. */
178
+ export function inboundLinks(manifest: Manifest, concept: string, id: string): InboundLink[] {
179
+ return manifest.entries
180
+ .filter((e) => !(e.concept === concept && e.id === id))
181
+ .filter((e) => e.links.some((l) => l.concept === concept && l.id === id))
182
+ .map((e) => ({ concept: e.concept, id: e.id, title: e.title, permalink: e.permalink }));
183
+ }
184
+
185
+ /** A resolver backed by manifest targets, for the admin preview. A miss returns undefined, so the
186
+ * render step marks the link broken rather than throwing. The build resolver throws instead. */
187
+ export function manifestLinkResolver(targets: { concept: string; id: string; permalink: string }[]): LinkResolve {
188
+ const byKey = new Map(targets.map((t) => [`${t.concept}/${t.id}`, t.permalink]));
189
+ return (ref) => byKey.get(`${ref.concept}/${ref.id}`);
190
+ }
@@ -11,6 +11,7 @@ import type { ComponentRegistry } from '../render/registry.js';
11
11
  import type { IconSet } from '../render/glyph.js';
12
12
  import type { DatePrefix } from './ids.js';
13
13
  import type { ConceptSchema } from './schema.js';
14
+ import type { LinkResolve } from './links.js';
14
15
 
15
16
  /** Common to every frontmatter field: the frontmatter key, the form label, and whether it is required. */
16
17
  interface FieldBase {
@@ -171,8 +172,13 @@ export interface CairnAdapter {
171
172
  };
172
173
  backend: BackendConfig;
173
174
  sender: SenderConfig;
174
- /** The site's one renderer: the editor preview and every public page call it (design decision 4). */
175
- render(md: string, opts?: { stagger?: boolean }): string | Promise<string>;
175
+ /** The site's one renderer: the editor preview and every public page call it (design decision 4).
176
+ * `resolve` rewrites cairn: links to live permalinks; the build passes a site-index resolver, the
177
+ * preview a manifest one. */
178
+ render(md: string, opts?: { stagger?: boolean; resolve?: LinkResolve }): string | Promise<string>;
179
+ /** Repo-relative path to the committed content manifest. Defaults to src/content/.cairn/index.json
180
+ * in composeRuntime. It sits outside any concept directory, so content enumeration never globs it. */
181
+ manifestPath?: string;
176
182
  /** Directive component registry; the renderer and the future palette derive from it (seam 3). */
177
183
  registry?: ComponentRegistry;
178
184
  /** The site's glyph name to SVG path-data map, for the admin icon picker and the renderer. */
@@ -267,7 +273,8 @@ export interface CairnRuntime {
267
273
  backend: BackendConfig;
268
274
  sender: SenderConfig;
269
275
  /** The site's one renderer: the editor preview and every public page call it (design decision 4). */
270
- render(md: string, opts?: { stagger?: boolean }): string | Promise<string>;
276
+ render(md: string, opts?: { stagger?: boolean; resolve?: LinkResolve }): string | Promise<string>;
277
+ manifestPath: string;
271
278
  registry?: ComponentRegistry;
272
279
  /** The site's glyph name to SVG path-data map, for the admin icon picker and the renderer. */
273
280
  icons?: IconSet;
@@ -25,6 +25,7 @@ export type { Page } from './paginate.js';
25
25
  export { rssResponse, jsonFeedResponse, sitemapResponse, robotsResponse } from './responses.js';
26
26
  export { jsonLdScript } from './json-ld.js';
27
27
  export { permalink } from '../content/permalink.js';
28
+ export { buildSiteManifest, buildLinkResolver } from './manifest.js';
28
29
  export { createPublicRoutes } from '../sveltekit/public-routes.js';
29
30
  export type {
30
31
  PublicRoutesDeps,
@@ -0,0 +1,44 @@
1
+ // cairn-cms: the build-side manifest builder and the build link resolver (content-graph design).
2
+ // buildSiteManifest mirrors createSiteIndexes: it maps the site descriptors over the per-concept
3
+ // globs and projects each file to a manifest row. buildLinkResolver reads the site index, which is
4
+ // fresh from the files at build, and throws on a missing target so a dangling cairn: token fails
5
+ // the build (the backstop). The admin preview uses manifestLinkResolver instead.
6
+ import { siteDescriptors } from './site-descriptors.js';
7
+ import { fromGlob } from './content-index.js';
8
+ import { parseMarkdown } from '../content/frontmatter.js';
9
+ import { emptyManifest, manifestEntryFromFile } from '../content/manifest.js';
10
+ import type { Manifest } from '../content/manifest.js';
11
+ import type { LinkResolve } from '../content/links.js';
12
+ import type { SiteIndex } from './site-index.js';
13
+ import type { SiteConfig } from '../nav/site-config.js';
14
+ import type { CairnAdapter } from '../content/types.js';
15
+ import type { SiteGlobs } from './site-indexes.js';
16
+
17
+ /** Build the whole-corpus manifest from a site's adapter, config, and per-concept globs. Drafts are
18
+ * included and flagged, so the admin picker and the guards see the full graph. */
19
+ export function buildSiteManifest<A extends CairnAdapter>(adapter: A, config: SiteConfig, globs: SiteGlobs<A>): Manifest {
20
+ const globRecord = globs as Record<string, Record<string, string> | undefined>;
21
+ const manifest = emptyManifest();
22
+ for (const descriptor of siteDescriptors(adapter, config)) {
23
+ const record = globRecord[descriptor.id] ?? {};
24
+ for (const file of fromGlob(record)) {
25
+ // Validate the same way createContentIndex does, so the manifest and the site index agree on
26
+ // which entries exist. A validation failure is excluded from both; otherwise the preview would
27
+ // resolve a link the build then rejects as a missing target.
28
+ const { frontmatter, body } = parseMarkdown(file.raw);
29
+ if (!descriptor.validate(frontmatter, body).ok) continue;
30
+ manifest.entries.push(manifestEntryFromFile(descriptor, file));
31
+ }
32
+ }
33
+ return manifest;
34
+ }
35
+
36
+ /** A resolver backed by the site index, for the build. A miss throws, so a dangling cairn: token
37
+ * fails the prerender (the build backstop). The preview uses manifestLinkResolver, which marks. */
38
+ export function buildLinkResolver(site: SiteIndex): LinkResolve {
39
+ return (ref) => {
40
+ const url = site.concept(ref.concept)?.byId(ref.id)?.permalink;
41
+ if (!url) throw new Error(`cairn link target not found: cairn:${ref.concept}/${ref.id}`);
42
+ return url;
43
+ };
44
+ }
@@ -136,3 +136,113 @@ export async function commitFile(
136
136
  if (!res.ok) throw new Error(`GitHub commit ${path} failed: ${res.status} ${await res.text()}`);
137
137
  return ((await res.json()) as { commit: { sha: string } }).commit.sha;
138
138
  }
139
+
140
+ /** A path change for an atomic commit: write `content`, or delete the path when `content` is null. */
141
+ export interface FileChange {
142
+ path: string;
143
+ content: string | null;
144
+ }
145
+
146
+ /** A Git Trees API change entry: a blob written from raw content, or a `sha: null` delete. */
147
+ interface TreeChange {
148
+ path: string;
149
+ mode: '100644';
150
+ type: 'blob';
151
+ content?: string;
152
+ sha?: null;
153
+ }
154
+
155
+ /** A Git Data API URL under the repo's `git/` namespace. */
156
+ function gitUrl(repo: RepoRef, suffix: string): string {
157
+ return `${API}/repos/${repo.owner}/${repo.repo}/git/${suffix}`;
158
+ }
159
+
160
+ /** The branch head commit sha, through the Git Data API single-ref read. */
161
+ async function headCommitSha(repo: RepoRef, token: string): Promise<string> {
162
+ const res = await fetch(gitUrl(repo, `ref/heads/${encodeURIComponent(repo.branch)}`), {
163
+ headers: ghHeaders('application/vnd.github+json', token),
164
+ });
165
+ if (!res.ok) throw new Error(`GitHub ref ${repo.branch} failed: ${res.status}`);
166
+ return ((await res.json()) as { object: { sha: string } }).object.sha;
167
+ }
168
+
169
+ /** The base tree sha of a commit. */
170
+ async function commitTreeSha(repo: RepoRef, commitSha: string, token: string): Promise<string> {
171
+ const res = await fetch(gitUrl(repo, `commits/${commitSha}`), {
172
+ headers: ghHeaders('application/vnd.github+json', token),
173
+ });
174
+ if (!res.ok) throw new Error(`GitHub commit ${commitSha} failed: ${res.status}`);
175
+ return ((await res.json()) as { tree: { sha: string } }).tree.sha;
176
+ }
177
+
178
+ /** Map file changes to Git Trees API entries, encoding a null content as a delete. */
179
+ function treeChanges(changes: FileChange[]): TreeChange[] {
180
+ return changes.map((c) =>
181
+ c.content === null
182
+ ? { path: c.path, mode: '100644', type: 'blob', sha: null }
183
+ : { path: c.path, mode: '100644', type: 'blob', content: c.content },
184
+ );
185
+ }
186
+
187
+ /** Retries after the initial attempt when the branch moves under an atomic commit. */
188
+ const COMMIT_RETRIES = 3;
189
+
190
+ /**
191
+ * Commit several path changes in one commit over the Git Data API. The author is the editor; the
192
+ * committer is omitted, so GitHub attributes the commit to the App. Returns the new commit sha.
193
+ * Builds the new tree on the current head's tree, so paths not named here are preserved.
194
+ *
195
+ * Caller preconditions this layer cannot enforce (the save and lifecycle paths must): every
196
+ * `path` is confined to the site's content directories (the App token can write anywhere in the
197
+ * repo), and `author` is derived from the verified server-side session, never request input.
198
+ *
199
+ * An empty change set is rejected, since it would otherwise push an empty commit that triggers a
200
+ * site redeploy for no content change.
201
+ */
202
+ export async function commitFiles(
203
+ repo: RepoRef,
204
+ changes: FileChange[],
205
+ opts: { message: string; author: CommitAuthor },
206
+ token: string,
207
+ ): Promise<string> {
208
+ if (changes.length === 0) throw new Error('commitFiles: no changes to commit');
209
+ const tree = treeChanges(changes);
210
+ for (let attempt = 0; attempt <= COMMIT_RETRIES; attempt++) {
211
+ const parent = await headCommitSha(repo, token);
212
+ const baseTree = await commitTreeSha(repo, parent, token);
213
+
214
+ const treeRes = await fetch(gitUrl(repo, 'trees'), {
215
+ method: 'POST',
216
+ headers: { ...ghHeaders('application/vnd.github+json', token), 'Content-Type': 'application/json' },
217
+ body: JSON.stringify({ base_tree: baseTree, tree }),
218
+ });
219
+ if (!treeRes.ok) {
220
+ // A 422 means an entry is unprocessable against the base tree, which a delete of an
221
+ // already-removed path produces (a concurrent delete or rename got there first). Treat it as
222
+ // the same non-fast-forward conflict the ref PATCH surfaces, so the caller fails safe with the
223
+ // reload-and-retry path instead of a raw 500.
224
+ if (treeRes.status === 422) throw new CommitConflictError(`${repo.branch} (tree create)`);
225
+ throw new Error(`GitHub tree create failed: ${treeRes.status} ${await treeRes.text()}`);
226
+ }
227
+ const newTree = ((await treeRes.json()) as { sha: string }).sha;
228
+
229
+ const commitRes = await fetch(gitUrl(repo, 'commits'), {
230
+ method: 'POST',
231
+ headers: { ...ghHeaders('application/vnd.github+json', token), 'Content-Type': 'application/json' },
232
+ body: JSON.stringify({ message: opts.message, tree: newTree, parents: [parent], author: opts.author }),
233
+ });
234
+ if (!commitRes.ok) throw new Error(`GitHub commit create failed: ${commitRes.status} ${await commitRes.text()}`);
235
+ const newCommit = ((await commitRes.json()) as { sha: string }).sha;
236
+
237
+ const refRes = await fetch(gitUrl(repo, `refs/heads/${encodeURIComponent(repo.branch)}`), {
238
+ method: 'PATCH',
239
+ headers: { ...ghHeaders('application/vnd.github+json', token), 'Content-Type': 'application/json' },
240
+ body: JSON.stringify({ sha: newCommit, force: false }),
241
+ });
242
+ if (refRes.ok) return newCommit;
243
+ // A non-fast-forward means the branch moved; retry on the new head so a concurrent commit
244
+ // is preserved. Any other failure is not a race, so surface it.
245
+ if (refRes.status !== 422) throw new Error(`GitHub ref update failed: ${refRes.status} ${await refRes.text()}`);
246
+ }
247
+ throw new CommitConflictError(`${repo.branch} (atomic commit)`);
248
+ }
package/src/lib/index.ts CHANGED
@@ -49,6 +49,23 @@ export {
49
49
  composeDatedId,
50
50
  } from './content/ids.js';
51
51
  export type { DatePrefix } from './content/ids.js';
52
+ // Internal-link token and the committed content manifest (content-graph design). The corpus
53
+ // builder and the request-time resolver ship from the delivery entry; this surface is the
54
+ // grammar, the manifest operations, and their types a migrating site adopts.
55
+ export { parseCairnToken, extractCairnLinks, formatCairnToken, escapeLinkText } from './content/links.js';
56
+ export type { CairnRef, LinkResolve } from './content/links.js';
57
+ export {
58
+ serializeManifest,
59
+ parseManifest,
60
+ emptyManifest,
61
+ verifyManifest,
62
+ upsertEntry,
63
+ removeEntry,
64
+ manifestEntryFromFile,
65
+ manifestLinkResolver,
66
+ inboundLinks,
67
+ } from './content/manifest.js';
68
+ export type { Manifest, ManifestEntry, LinkTarget, InboundLink } from './content/manifest.js';
52
69
  // Render engine (Plan 04): generic directive pipeline; sites own the component registry.
53
70
  export { defineRegistry, emptyValues } from './render/registry.js';
54
71
  export type {
@@ -8,10 +8,13 @@ import rehypeSlug from 'rehype-slug';
8
8
  import rehypeStringify from 'rehype-stringify';
9
9
  import rehypeSanitize from 'rehype-sanitize';
10
10
  import type { Schema } from 'hast-util-sanitize';
11
+ import { VFile } from 'vfile';
11
12
  import { buildSanitizeSchema, rehypeAnchorRel } from './sanitize-schema.js';
12
13
  import { remarkDirectiveStamp } from './remark-directives.js';
14
+ import { remarkResolveCairnLinks, CAIRN_RESOLVE } from './resolve-links.js';
13
15
  import { rehypeDispatch } from './rehype-dispatch.js';
14
16
  import type { ComponentRegistry } from './registry.js';
17
+ import type { LinkResolve } from '../content/links.js';
15
18
 
16
19
  export interface RendererOptions {
17
20
  /** Stamp a `data-rise` ordinal (0, 1, 2, …) on each top-level component so a site's
@@ -33,7 +36,7 @@ export interface RendererOptions {
33
36
  * stamped markers to registry-built hast. Returns `renderMarkdown` plus the remark/
34
37
  * rehype plugin arrays (so the admin editor preview can reuse the exact same set). */
35
38
  export function createRenderer(registry: ComponentRegistry, options: RendererOptions = {}) {
36
- const remarkPlugins: PluggableList = [remarkDirective, [remarkDirectiveStamp, registry]];
39
+ const remarkPlugins: PluggableList = [remarkDirective, [remarkDirectiveStamp, registry], remarkResolveCairnLinks];
37
40
  // The sanitize floor runs after rehype-raw (so author raw HTML is parsed, then cleaned) and
38
41
  // before the dispatch (so the site's trusted build() output and its inline SVG icons are never
39
42
  // sanitized). The anchor-rel hardening runs last so it also covers component-built anchors.
@@ -57,6 +60,9 @@ export function createRenderer(registry: ComponentRegistry, options: RendererOpt
57
60
  return {
58
61
  remarkPlugins,
59
62
  rehypePlugins,
60
- renderMarkdown: async (content: string): Promise<string> => String(await processor.process(content)),
63
+ renderMarkdown: async (content: string, opts: { resolve?: LinkResolve } = {}): Promise<string> => {
64
+ const file = new VFile({ value: content, data: { [CAIRN_RESOLVE]: opts.resolve } });
65
+ return String(await processor.process(file));
66
+ },
61
67
  };
62
68
  }
@@ -0,0 +1,42 @@
1
+ // cairn-cms: the cairn: link resolver, an mdast step in the render pipeline (content-graph design).
2
+ // It runs before remark-rehype, so the rewritten href passes through the sanitize floor exactly as
3
+ // any other anchor. The per-call resolver is read off the VFile (set by renderMarkdown), so the
4
+ // processor is still built once. A miss either marks the link broken (preview) or throws (build),
5
+ // decided by the injected resolver.
6
+ import { visit } from 'unist-util-visit';
7
+ import type { VFile } from 'vfile';
8
+ import { parseCairnToken, type LinkResolve } from '../content/links.js';
9
+
10
+ /** The VFile data key the renderer sets the per-call resolver under. */
11
+ export const CAIRN_RESOLVE = 'cairnResolve';
12
+
13
+ interface LinkNode {
14
+ url: string;
15
+ data?: { hProperties?: Record<string, unknown> };
16
+ }
17
+
18
+ /** Resolve cairn: link nodes against the VFile's resolver. A non-cairn href and a malformed token
19
+ * pass through. A missing target is marked with the cairn-broken-link class (the resolver returns
20
+ * undefined) or, when the resolver throws, the error propagates and fails the build. */
21
+ export function remarkResolveCairnLinks() {
22
+ return (tree: unknown, file: VFile): void => {
23
+ const resolve = file.data[CAIRN_RESOLVE] as LinkResolve | undefined;
24
+ if (!resolve) return;
25
+ visit(tree as Parameters<typeof visit>[0], 'link', (node: LinkNode) => {
26
+ const ref = parseCairnToken(node.url);
27
+ if (!ref) return;
28
+ const url = resolve(ref); // may throw (build backstop); propagates out of render
29
+ if (url) {
30
+ node.url = url;
31
+ return;
32
+ }
33
+ // Missing target in the preview: mark it broken and neutralize the href, keeping the text.
34
+ node.url = '#';
35
+ node.data = node.data ?? {};
36
+ const props = (node.data.hProperties = node.data.hProperties ?? {});
37
+ const existing = Array.isArray(props.className) ? (props.className as string[]) : [];
38
+ props.className = [...existing, 'cairn-broken-link'];
39
+ props.title = 'Broken internal link';
40
+ });
41
+ };
42
+ }
@@ -29,6 +29,11 @@ export function buildSanitizeSchema(
29
29
  const anchorAttrs = (attributes.a ?? []).filter(
30
30
  (entry) => !(Array.isArray(entry) && entry[0] === 'className'),
31
31
  );
32
+ // Admit the inert `cairn:` href scheme on top of the default protocol allowlist. The render
33
+ // resolver rewrites a `cairn:` link to a live permalink before delivery; an unresolved one
34
+ // survives the floor in its inert token form (a visible unresolved-link signal), never as an
35
+ // executable vector. The dangerous-protocol strip (javascript:, data:) is preserved.
36
+ const protocols = defaultSchema.protocols ?? {};
32
37
  const schema: Schema = {
33
38
  ...defaultSchema,
34
39
  tagNames: [...(defaultSchema.tagNames ?? []), 'nav', 'details', 'summary'],
@@ -37,6 +42,10 @@ export function buildSanitizeSchema(
37
42
  '*': [...(attributes['*'] ?? []), 'className', ...markers],
38
43
  a: [...anchorAttrs, 'className', 'target', 'rel'],
39
44
  },
45
+ protocols: {
46
+ ...protocols,
47
+ href: [...(protocols.href ?? []), 'cairn'],
48
+ },
40
49
  };
41
50
  return extend ? extend(schema) : schema;
42
51
  }