@anthusai/papyrus 1.0.0-next.5 → 1.0.0-next.7

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.
@@ -493,6 +493,12 @@ const schema = a.schema({
493
493
  .returns(a.json())
494
494
  .authorization((allow) => [allow.groups(contentWriteGroups)])
495
495
  .handler(a.handler.function(contentActions)),
496
+ requestStagingBuild: a
497
+ .mutation()
498
+ .arguments({ input: a.json().required() })
499
+ .returns(a.json())
500
+ .authorization((allow) => [allow.groups(contentWriteGroups)])
501
+ .handler(a.handler.function(contentActions)),
496
502
  knowledgeQuery: a
497
503
  .query()
498
504
  .arguments({
@@ -537,6 +537,13 @@ const schema = a.schema({
537
537
  .authorization((allow) => [allow.groups(contentWriteGroups)])
538
538
  .handler(a.handler.function(contentActions)),
539
539
 
540
+ requestStagingBuild: a
541
+ .mutation()
542
+ .arguments({ input: a.json().required() })
543
+ .returns(a.json())
544
+ .authorization((allow) => [allow.groups(contentWriteGroups)])
545
+ .handler(a.handler.function(contentActions)),
546
+
540
547
  knowledgeQuery: a
541
548
  .query()
542
549
  .arguments({
@@ -393,6 +393,12 @@ export const schema = a.schema({
393
393
  .returns(a.json())
394
394
  .authorization((allow) => [allow.groups(contentWriteGroups)])
395
395
  .handler(a.handler.function(contentActions)),
396
+ requestStagingBuild: a
397
+ .mutation()
398
+ .arguments({ input: a.json().required() })
399
+ .returns(a.json())
400
+ .authorization((allow) => [allow.groups(contentWriteGroups)])
401
+ .handler(a.handler.function(contentActions)),
396
402
  knowledgeQuery: a
397
403
  .query()
398
404
  .arguments({
@@ -431,6 +431,13 @@ export const schema = a.schema({
431
431
  .authorization((allow) => [allow.groups(contentWriteGroups)])
432
432
  .handler(a.handler.function(contentActions)),
433
433
 
434
+ requestStagingBuild: a
435
+ .mutation()
436
+ .arguments({ input: a.json().required() })
437
+ .returns(a.json())
438
+ .authorization((allow) => [allow.groups(contentWriteGroups)])
439
+ .handler(a.handler.function(contentActions)),
440
+
434
441
  knowledgeQuery: a
435
442
  .query()
436
443
  .arguments({
@@ -1,10 +1,18 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import json
4
+ import os
4
5
  from typing import Any
5
6
 
6
7
  from papyrus_content.graphql_authoring import create_authoring_client
7
8
  from papyrus_content.markus_renderer.derive import derive_body
9
+ from papyrus_content.rebuild_trigger import (
10
+ DEFAULT_STAGING_BRANCH,
11
+ reader_target_from_environment,
12
+ trigger_pretext_revalidation,
13
+ trigger_rebuild,
14
+ trigger_staging_build,
15
+ )
8
16
  from papyrus_content.publishing import (
9
17
  ItemFields,
10
18
  PublishError,
@@ -72,21 +80,53 @@ def save_item_draft_action(arguments: dict, actor: str) -> dict:
72
80
  }
73
81
 
74
82
 
83
+ def site_triggers_for(client, item_id: str) -> dict:
84
+ triggers: dict = {}
85
+ reader_app_id, reader_branch = reader_target_from_environment()
86
+ revalidate_base_url = (os.environ.get("PAPYRUS_REVALIDATE_BASE_URL") or "").strip()
87
+ if revalidate_base_url:
88
+ try:
89
+ item = client.get_record("Item", item_id) or {}
90
+ slugs = [item["slug"]] if item.get("slug") else []
91
+ revalidated = trigger_pretext_revalidation(slugs, None, base_url=revalidate_base_url)
92
+ triggers["revalidated"] = revalidated if revalidated is not None else {"ok": False, "reason": "not-configured"}
93
+ except Exception as error: # noqa: BLE001 - a trigger failure never fails the publish
94
+ triggers["revalidated"] = {"ok": False, "error": f"{type(error).__name__}: {error}"}
95
+ if reader_app_id:
96
+ triggers["rebuild"] = trigger_rebuild(reader_app_id=reader_app_id, reader_branch=reader_branch)
97
+ return triggers
98
+
99
+
75
100
  def publish_item_action(arguments: dict, actor: str) -> dict:
76
101
  client, _claims = create_authoring_client()
77
102
  result = publish_item(client, arguments["id"], actor=actor)
78
- return {
103
+ response = {
79
104
  "ok": True,
80
105
  "changed": result.changed,
81
106
  "publishedId": result.published_item_id,
82
107
  "versionNumber": result.version_number,
83
108
  }
109
+ if result.changed:
110
+ response.update(site_triggers_for(client, arguments["id"]))
111
+ return response
84
112
 
85
113
 
86
114
  def unpublish_item_action(arguments: dict, actor: str) -> dict:
87
115
  client, _claims = create_authoring_client()
88
116
  result = unpublish_item(client, arguments["id"], actor=actor)
89
- return {"ok": True, "changed": result.changed}
117
+ response = {"ok": True, "changed": result.changed}
118
+ if result.changed:
119
+ response.update(site_triggers_for(client, arguments["id"]))
120
+ return response
121
+
122
+
123
+ def request_staging_build_action() -> dict:
124
+ cms_app_id = (os.environ.get("PAPYRUS_CMS_AMPLIFY_APP_ID") or "").strip()
125
+ if not cms_app_id:
126
+ return {"ok": False, "errors": [{"code": "staging-build-not-configured", "message": "This site has no staging build configured.", "line": None}]}
127
+ staging_branch = (os.environ.get("PAPYRUS_STAGING_BRANCH") or "").strip() or DEFAULT_STAGING_BRANCH
128
+ build = trigger_staging_build(cms_app_id=cms_app_id, staging_branch=staging_branch)
129
+ return {"ok": True, "build": build}
90
130
 
91
131
 
92
132
  def handler(event, context):
@@ -102,6 +142,8 @@ def handler(event, context):
102
142
  return publish_item_action(arguments, actor)
103
143
  if field == "unpublishItem":
104
144
  return unpublish_item_action(arguments, actor)
145
+ if field == "requestStagingBuild":
146
+ return request_staging_build_action()
105
147
  except PublishError as error:
106
148
  return failure_response(error)
107
149
  raise ValueError(f"Unsupported field {field}")
@@ -0,0 +1,22 @@
1
+ export const REBUILD_TRIGGER_ACTIONS = ["amplify:StartJob", "amplify:ListJobs"];
2
+ function branchJobsArn(input, appId, branch) {
3
+ return `arn:aws:amplify:${input.region}:${input.account}:apps/${appId}/branches/${branch}/jobs/*`;
4
+ }
5
+ export function rebuildTriggerSettings(input) {
6
+ const environment = {};
7
+ const resources = [];
8
+ const readerAppId = (input.reader?.amplifyAppId ?? "").trim();
9
+ if (readerAppId !== "") {
10
+ const readerBranch = (input.reader?.branchName ?? "").trim() || "main";
11
+ environment.PAPYRUS_READER_AMPLIFY_APP_ID = readerAppId;
12
+ environment.PAPYRUS_READER_BRANCH = readerBranch;
13
+ resources.push(branchJobsArn(input, readerAppId, readerBranch));
14
+ }
15
+ const cmsAppId = input.cmsAppId.trim();
16
+ if (input.stagingBuildEnabled && cmsAppId !== "") {
17
+ environment.PAPYRUS_CMS_AMPLIFY_APP_ID = cmsAppId;
18
+ environment.PAPYRUS_STAGING_BRANCH = "staging";
19
+ resources.push(branchJobsArn(input, cmsAppId, "staging"));
20
+ }
21
+ return { environment, actions: REBUILD_TRIGGER_ACTIONS, resources };
22
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Environment and IAM policy for the content-actions Lambda's site triggers.
3
+ * Pure (no CDK imports) so the policy can be tested without synthesizing.
4
+ */
5
+ export type RebuildTriggerInput = {
6
+ reader?: { amplifyAppId: string; branchName?: string };
7
+ stagingBuildEnabled: boolean;
8
+ cmsAppId: string;
9
+ region: string;
10
+ account: string;
11
+ };
12
+
13
+ export type RebuildTriggerSettings = {
14
+ environment: Record<string, string>;
15
+ actions: string[];
16
+ resources: string[];
17
+ };
18
+
19
+ export const REBUILD_TRIGGER_ACTIONS = ["amplify:StartJob", "amplify:ListJobs"];
20
+
21
+ function branchJobsArn(input: RebuildTriggerInput, appId: string, branch: string): string {
22
+ return `arn:aws:amplify:${input.region}:${input.account}:apps/${appId}/branches/${branch}/jobs/*`;
23
+ }
24
+
25
+ export function rebuildTriggerSettings(input: RebuildTriggerInput): RebuildTriggerSettings {
26
+ const environment: Record<string, string> = {};
27
+ const resources: string[] = [];
28
+ const readerAppId = (input.reader?.amplifyAppId ?? "").trim();
29
+ if (readerAppId !== "") {
30
+ const readerBranch = (input.reader?.branchName ?? "").trim() || "main";
31
+ environment.PAPYRUS_READER_AMPLIFY_APP_ID = readerAppId;
32
+ environment.PAPYRUS_READER_BRANCH = readerBranch;
33
+ resources.push(branchJobsArn(input, readerAppId, readerBranch));
34
+ }
35
+ const cmsAppId = input.cmsAppId.trim();
36
+ if (input.stagingBuildEnabled && cmsAppId !== "") {
37
+ environment.PAPYRUS_CMS_AMPLIFY_APP_ID = cmsAppId;
38
+ environment.PAPYRUS_STAGING_BRANCH = "staging";
39
+ resources.push(branchJobsArn(input, cmsAppId, "staging"));
40
+ }
41
+ return { environment, actions: REBUILD_TRIGGER_ACTIONS, resources };
42
+ }
@@ -21,6 +21,12 @@ export type PapyrusSiteBackendConfig = {
21
21
  */
22
22
  productionAppId?: string;
23
23
  auth?: PapyrusAuthConfig;
24
+ /** Static reader app (Markus-static sites) that a publish rebuilds through IAM `amplify:StartJob`. */
25
+ reader?: { amplifyAppId: string; branchName?: string };
26
+ /** Lets the newsroom start the `staging` branch build of this CMS app. */
27
+ stagingBuild?: { enabled: boolean };
28
+ /** Base URL of a Pretext reader whose `/api/revalidate` a publish calls (secret `PAPYRUS_REVALIDATE_SECRET`). */
29
+ revalidateBaseUrl?: string;
24
30
  features?: {
25
31
  consoleResponder?: boolean;
26
32
  inboundEmail?: boolean;
@@ -12,6 +12,7 @@ import { CfnEventSourceMapping, FunctionUrlAuthType } from "aws-cdk-lib/aws-lamb
12
12
  import { CfnIndex, CfnVectorBucket, CfnVectorBucketPolicy } from "aws-cdk-lib/aws-s3vectors";
13
13
  import { dirname, resolve } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
+ import { rebuildTriggerSettings } from "./rebuild-trigger-settings.js";
15
16
  import { authConfigFromEnv, defineSiteAuth } from "./auth/resource.js";
16
17
  import { data } from "./data/resource.js";
17
18
  import { assignmentAction } from "./functions/assignment-action/resource.js";
@@ -333,6 +334,23 @@ export function defineSiteBackend(papyrusSite) {
333
334
  actions: ["appsync:GraphQL"],
334
335
  resources: ["*"],
335
336
  }));
337
+ const rebuildSettings = rebuildTriggerSettings({
338
+ reader: site.reader,
339
+ stagingBuildEnabled: site.stagingBuild?.enabled === true,
340
+ cmsAppId: amplifyAppId,
341
+ region: Stack.of(contentActionsLambda).region,
342
+ account: Stack.of(contentActionsLambda).account,
343
+ });
344
+ for (const [name, value] of Object.entries(rebuildSettings.environment)) {
345
+ contentActionsLambda.addEnvironment(name, value);
346
+ }
347
+ if (rebuildSettings.resources.length > 0) {
348
+ contentActionsLambda.addToRolePolicy(new PolicyStatement({ actions: rebuildSettings.actions, resources: rebuildSettings.resources }));
349
+ }
350
+ if ((site.revalidateBaseUrl ?? "").trim() !== "") {
351
+ backend.contentActions.addEnvironment("PAPYRUS_REVALIDATE_BASE_URL", (site.revalidateBaseUrl ?? "").trim());
352
+ backend.contentActions.addEnvironment("PAPYRUS_REVALIDATE_SECRET", secret("PAPYRUS_REVALIDATE_SECRET"));
353
+ }
336
354
  grantNewsroomReadWriteDelete(backend.modelAttachmentUpload.resources.lambda);
337
355
  grantMediaReadWriteDelete(backend.modelAttachmentUpload.resources.lambda);
338
356
  if (backend.sesInboundReceive) {
@@ -13,6 +13,7 @@ import * as s3 from "aws-cdk-lib/aws-s3";
13
13
  import { CfnIndex, CfnVectorBucket, CfnVectorBucketPolicy } from "aws-cdk-lib/aws-s3vectors";
14
14
  import { dirname, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
+ import { rebuildTriggerSettings } from "./rebuild-trigger-settings";
16
17
  import { authConfigFromEnv, defineSiteAuth } from "./auth/resource";
17
18
  import { data } from "./data/resource";
18
19
  import { assignmentAction } from "./functions/assignment-action/resource";
@@ -414,6 +415,25 @@ export function defineSiteBackend(papyrusSite: PapyrusSite) {
414
415
  resources: ["*"],
415
416
  }),
416
417
  );
418
+ const rebuildSettings = rebuildTriggerSettings({
419
+ reader: site.reader,
420
+ stagingBuildEnabled: site.stagingBuild?.enabled === true,
421
+ cmsAppId: amplifyAppId,
422
+ region: Stack.of(contentActionsLambda).region,
423
+ account: Stack.of(contentActionsLambda).account,
424
+ });
425
+ for (const [name, value] of Object.entries(rebuildSettings.environment)) {
426
+ contentActionsLambda.addEnvironment(name, value);
427
+ }
428
+ if (rebuildSettings.resources.length > 0) {
429
+ contentActionsLambda.addToRolePolicy(
430
+ new PolicyStatement({ actions: rebuildSettings.actions, resources: rebuildSettings.resources }),
431
+ );
432
+ }
433
+ if ((site.revalidateBaseUrl ?? "").trim() !== "") {
434
+ backend.contentActions.addEnvironment("PAPYRUS_REVALIDATE_BASE_URL", (site.revalidateBaseUrl ?? "").trim());
435
+ backend.contentActions.addEnvironment("PAPYRUS_REVALIDATE_SECRET", secret("PAPYRUS_REVALIDATE_SECRET"));
436
+ }
417
437
  grantNewsroomReadWriteDelete(backend.modelAttachmentUpload.resources.lambda as LambdaFunction);
418
438
  grantMediaReadWriteDelete(backend.modelAttachmentUpload.resources.lambda as LambdaFunction);
419
439
  if (backend.sesInboundReceive) {
@@ -0,0 +1,15 @@
1
+ import { NewsroomArticleEditor } from "../../../../components/newsroom-article-editor";
2
+
3
+ export const dynamic = "force-dynamic";
4
+
5
+ type NewsroomArticleEditorPageProps = {
6
+ params: Promise<{ id: string }>;
7
+ searchParams?: Promise<{ demo?: string | string[] }>;
8
+ };
9
+
10
+ export default async function NewsroomArticleEditorPage({ params, searchParams }: NewsroomArticleEditorPageProps) {
11
+ const { id } = await params;
12
+ const resolved = await searchParams;
13
+ const demoValue = Array.isArray(resolved?.demo) ? resolved?.demo[0] : resolved?.demo;
14
+ return <NewsroomArticleEditor articleId={decodeURIComponent(id)} demo={demoValue === "1"} />;
15
+ }
@@ -0,0 +1,13 @@
1
+ import { NewsroomArticlesView } from "../../../components/newsroom-articles-view";
2
+
3
+ export const dynamic = "force-dynamic";
4
+
5
+ type NewsroomArticlesPageProps = {
6
+ searchParams?: Promise<{ demo?: string | string[] }>;
7
+ };
8
+
9
+ export default async function NewsroomArticlesPage({ searchParams }: NewsroomArticlesPageProps) {
10
+ const resolved = await searchParams;
11
+ const demoValue = Array.isArray(resolved?.demo) ? resolved?.demo[0] : resolved?.demo;
12
+ return <NewsroomArticlesView demo={demoValue === "1"} />;
13
+ }
@@ -0,0 +1,300 @@
1
+ import type { ReactNode } from "react";
2
+ import {
3
+ parseMarkusDocument,
4
+ type MarkusBlock,
5
+ type MarkusDirective,
6
+ type MarkusInline,
7
+ type MarkusNode,
8
+ } from "../lib/markus-ir";
9
+
10
+ const TOKEN_PATTERN = /PAPYRUSMARKUP\d{5}END/g;
11
+ const WHOLE_TOKEN_PATTERN = /^PAPYRUSMARKUP\d{5}END$/;
12
+
13
+ type PreviewSidecar = {
14
+ images: Record<string, Record<string, unknown>>;
15
+ citations: Record<string, string[]>;
16
+ citationLists: Record<string, unknown>;
17
+ bibliography: string[];
18
+ };
19
+
20
+ type PreviewContext = {
21
+ sidecar: PreviewSidecar;
22
+ citationNumbers: Map<string, number>;
23
+ imageUrls: Record<string, string>;
24
+ };
25
+
26
+ function isRecord(value: unknown): value is Record<string, unknown> {
27
+ return typeof value === "object" && value !== null && !Array.isArray(value);
28
+ }
29
+
30
+ function readSidecar(envelope: Record<string, unknown>): PreviewSidecar {
31
+ const sidecar = envelope.papyrus;
32
+ if (!isRecord(sidecar)) throw new Error("bodyIr.papyrus is missing");
33
+ const { images, citations, citationLists, bibliography } = sidecar;
34
+ if (!isRecord(images) || !isRecord(citations) || !isRecord(citationLists) || !Array.isArray(bibliography)) {
35
+ throw new Error("bodyIr.papyrus must contain images, citations, citationLists and bibliography");
36
+ }
37
+ return {
38
+ images: images as PreviewSidecar["images"],
39
+ citations: citations as PreviewSidecar["citations"],
40
+ citationLists,
41
+ bibliography: bibliography.map(String),
42
+ };
43
+ }
44
+
45
+ function numberCitationsByFirstAppearance(document: unknown, sidecar: PreviewSidecar): Map<string, number> {
46
+ const numbers = new Map<string, number>();
47
+ for (const token of JSON.stringify(document).match(TOKEN_PATTERN) ?? []) {
48
+ for (const key of sidecar.citations[token] ?? []) {
49
+ if (!numbers.has(key)) numbers.set(key, numbers.size + 1);
50
+ }
51
+ }
52
+ return numbers;
53
+ }
54
+
55
+ function imagePlaceholder(token: string, context: PreviewContext): ReactNode {
56
+ const entry = context.sidecar.images[token];
57
+ const src = typeof entry?.src === "string" ? entry.src : "";
58
+ const alt = typeof entry?.alt === "string" ? entry.alt : "";
59
+ const url = context.imageUrls[src];
60
+ if (url) {
61
+ return (
62
+ // eslint-disable-next-line @next/next/no-img-element
63
+ <img
64
+ alt={alt}
65
+ className="my-3 h-auto max-w-full rounded-lg"
66
+ data-markus-preview-image-loaded
67
+ loading="lazy"
68
+ src={url}
69
+ />
70
+ );
71
+ }
72
+ return (
73
+ <div
74
+ className="my-3 rounded-lg border border-dashed border-border bg-muted/30 px-3 py-6 text-center text-xs text-muted-foreground"
75
+ data-markus-preview-image
76
+ >
77
+ {`Image: ${src} (${alt})`}
78
+ </div>
79
+ );
80
+ }
81
+
82
+ function renderText(text: string, context: PreviewContext): ReactNode {
83
+ const parts: ReactNode[] = [];
84
+ let cursor = 0;
85
+ for (const match of text.matchAll(TOKEN_PATTERN)) {
86
+ const token = match[0];
87
+ const index = match.index ?? 0;
88
+ const keys = context.sidecar.citations[token];
89
+ if (!keys) continue;
90
+ if (index > cursor) parts.push(text.slice(cursor, index));
91
+ parts.push(
92
+ <sup className="text-primary" key={`${index}-${token}`}>
93
+ {keys.map((key) => `[${context.citationNumbers.get(key)}]`).join("")}
94
+ </sup>,
95
+ );
96
+ cursor = index + token.length;
97
+ }
98
+ if (cursor < text.length) parts.push(text.slice(cursor));
99
+ return parts;
100
+ }
101
+
102
+ function renderInlines(inlines: MarkusInline[], context: PreviewContext): ReactNode[] {
103
+ return inlines.map((node, index) => {
104
+ switch (node.type) {
105
+ case "text":
106
+ return <span key={index}>{renderText(node.text, context)}</span>;
107
+ case "emphasis":
108
+ return <em key={index}>{renderInlines(node.children, context)}</em>;
109
+ case "strong":
110
+ return <strong key={index}>{renderInlines(node.children, context)}</strong>;
111
+ case "strikethrough":
112
+ return <s key={index}>{renderInlines(node.children, context)}</s>;
113
+ case "code_span":
114
+ return <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]" key={index}>{node.code}</code>;
115
+ case "link":
116
+ return node.href ? (
117
+ <a className="text-primary underline" href={node.href} key={index} rel="noopener noreferrer" target="_blank">
118
+ {renderInlines(node.children, context)}
119
+ </a>
120
+ ) : (
121
+ <span key={index}>{renderInlines(node.children, context)}</span>
122
+ );
123
+ case "image":
124
+ return (
125
+ <span className="rounded border border-dashed border-border px-1 text-xs text-muted-foreground" key={index}>
126
+ {`Image: ${node.src ?? ""} (${node.alt})`}
127
+ </span>
128
+ );
129
+ case "soft_break":
130
+ return <span key={index}>{" "}</span>;
131
+ case "hard_break":
132
+ return <br key={index} />;
133
+ case "html_inline":
134
+ return <code className="font-mono text-xs" key={index}>{node.value}</code>;
135
+ }
136
+ });
137
+ }
138
+
139
+ function soleToken(inlines: MarkusInline[]): string | null {
140
+ if (inlines.length !== 1 || inlines[0].type !== "text") return null;
141
+ const text = inlines[0].text.trim();
142
+ return WHOLE_TOKEN_PATTERN.test(text) ? text : null;
143
+ }
144
+
145
+ const HEADING_CLASSES = [
146
+ "mt-5 mb-2 text-2xl font-semibold tracking-tight",
147
+ "mt-5 mb-2 text-xl font-semibold tracking-tight",
148
+ "mt-4 mb-2 text-lg font-semibold",
149
+ "mt-4 mb-1 text-base font-semibold",
150
+ "mt-3 mb-1 text-sm font-semibold",
151
+ "mt-3 mb-1 text-sm font-medium",
152
+ ];
153
+
154
+ function renderBlock(block: MarkusBlock, index: number, context: PreviewContext): ReactNode {
155
+ switch (block.type) {
156
+ case "paragraph": {
157
+ const token = soleToken(block.inline);
158
+ if (token && token in context.sidecar.images) return <div key={index}>{imagePlaceholder(token, context)}</div>;
159
+ if (token && token in context.sidecar.citationLists) {
160
+ return (
161
+ <ol className="my-3 list-decimal space-y-1 pl-6 text-sm" data-markus-preview-bibliography key={index}>
162
+ {context.sidecar.bibliography.map((entry, entryIndex) => (
163
+ <li key={entryIndex}>{entry}</li>
164
+ ))}
165
+ </ol>
166
+ );
167
+ }
168
+ return <p className="my-3 leading-relaxed" key={index}>{renderInlines(block.inline, context)}</p>;
169
+ }
170
+ case "heading": {
171
+ const level = Math.min(Math.max(block.level, 1), 6);
172
+ const Tag = `h${level}` as "h1";
173
+ return <Tag className={HEADING_CLASSES[level - 1]} key={index}>{renderInlines(block.inline, context)}</Tag>;
174
+ }
175
+ case "list": {
176
+ const items = block.items.map((item, itemIndex) => (
177
+ <li key={itemIndex}>{renderBlocks(item.children, context)}</li>
178
+ ));
179
+ return block.ordered ? (
180
+ <ol className="my-3 list-decimal space-y-1 pl-6" key={index} start={block.start ?? undefined}>{items}</ol>
181
+ ) : (
182
+ <ul className="my-3 list-disc space-y-1 pl-6" key={index}>{items}</ul>
183
+ );
184
+ }
185
+ case "blockquote":
186
+ return (
187
+ <blockquote className="my-3 border-l-4 border-border pl-4 italic text-muted-foreground" key={index}>
188
+ {renderBlocks(block.children, context)}
189
+ </blockquote>
190
+ );
191
+ case "code":
192
+ return (
193
+ <pre className="my-3 overflow-x-auto rounded-lg bg-muted p-3 font-mono text-xs" key={index}>
194
+ <code>{block.value}</code>
195
+ </pre>
196
+ );
197
+ case "thematic_break":
198
+ return <hr className="my-4 border-border" key={index} />;
199
+ case "table":
200
+ return (
201
+ <div className="my-3 overflow-x-auto" key={index}>
202
+ <table className="w-full border-collapse text-sm">
203
+ <thead>
204
+ <tr>
205
+ {block.header.map((cell, cellIndex) => (
206
+ <th className="border border-border bg-muted/40 px-2 py-1 text-left" key={cellIndex}>
207
+ {renderInlines(cell, context)}
208
+ </th>
209
+ ))}
210
+ </tr>
211
+ </thead>
212
+ <tbody>
213
+ {block.rows.map((row, rowIndex) => (
214
+ <tr key={rowIndex}>
215
+ {row.map((cell, cellIndex) => (
216
+ <td className="border border-border px-2 py-1" key={cellIndex}>{renderInlines(cell, context)}</td>
217
+ ))}
218
+ </tr>
219
+ ))}
220
+ </tbody>
221
+ </table>
222
+ </div>
223
+ );
224
+ case "html":
225
+ return (
226
+ <pre className="my-3 overflow-x-auto rounded-lg bg-muted p-3 font-mono text-xs" key={index}>{block.value}</pre>
227
+ );
228
+ }
229
+ }
230
+
231
+ function renderDirective(directive: MarkusDirective, index: number, context: PreviewContext): ReactNode {
232
+ if (directive.name === "pull-quote") {
233
+ const attribution = directive.attributes.attribution;
234
+ return (
235
+ <blockquote
236
+ className="my-4 border-y border-border px-4 py-3 text-lg font-medium italic"
237
+ data-markus-preview-directive="pull-quote"
238
+ key={index}
239
+ >
240
+ {renderBlocks(directive.children, context)}
241
+ {typeof attribution === "string" && attribution ? (
242
+ <footer className="mt-1 text-sm not-italic text-muted-foreground">{`— ${attribution}`}</footer>
243
+ ) : null}
244
+ </blockquote>
245
+ );
246
+ }
247
+ const attributeEntries = Object.entries(directive.attributes).filter(([, value]) => value !== null && value !== "");
248
+ return (
249
+ <section
250
+ className="my-3 rounded-lg border border-border"
251
+ data-markus-preview-directive={directive.name}
252
+ key={index}
253
+ >
254
+ <header className="border-b border-border bg-muted/40 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
255
+ {directive.name}
256
+ </header>
257
+ <div className="px-3 py-1">
258
+ {directive.leaf && attributeEntries.length > 0 ? (
259
+ <p className="my-2 font-mono text-xs text-muted-foreground">
260
+ {attributeEntries.map(([key, value]) => `${key}=${String(value)}`).join(" ")}
261
+ </p>
262
+ ) : null}
263
+ {renderBlocks(directive.children, context)}
264
+ </div>
265
+ </section>
266
+ );
267
+ }
268
+
269
+ function renderBlocks(nodes: MarkusNode[], context: PreviewContext): ReactNode[] {
270
+ return nodes.map((node, index) =>
271
+ node.type === "directive" ? renderDirective(node, index, context) : renderBlock(node, index, context),
272
+ );
273
+ }
274
+
275
+ export function MarkusIrPreview({
276
+ bodyIr,
277
+ imageUrls = {},
278
+ }: {
279
+ bodyIr: unknown;
280
+ imageUrls?: Record<string, string>;
281
+ }) {
282
+ try {
283
+ const envelope = typeof bodyIr === "string" ? JSON.parse(bodyIr) : bodyIr;
284
+ if (!isRecord(envelope)) throw new Error("bodyIr must be a JSON object");
285
+ const document = parseMarkusDocument(envelope.document);
286
+ const sidecar = readSidecar(envelope);
287
+ const context: PreviewContext = {
288
+ sidecar,
289
+ citationNumbers: numberCitationsByFirstAppearance(envelope.document, sidecar),
290
+ imageUrls,
291
+ };
292
+ return <div data-markus-preview>{renderBlocks(document.children, context)}</div>;
293
+ } catch (error) {
294
+ return (
295
+ <p className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive" data-markus-preview-error role="alert">
296
+ {`The preview could not be rendered: ${error instanceof Error ? error.message : "unknown error"}`}
297
+ </p>
298
+ );
299
+ }
300
+ }