@open-press/core 0.7.1 → 0.8.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 (115) hide show
  1. package/engine/commands/dev.mjs +2 -2
  2. package/engine/output/chrome-pdf.mjs +18 -3
  3. package/engine/output/static-server.mjs +39 -0
  4. package/engine/react/comment-endpoint.mjs +13 -39
  5. package/engine/react/comment-marker.mjs +30 -6
  6. package/engine/react/document-entry.mjs +11 -0
  7. package/engine/react/document-export.mjs +30 -5
  8. package/engine/react/http-json.mjs +24 -0
  9. package/engine/react/mdx-compile.mjs +96 -3
  10. package/engine/react/measurement-css.mjs +93 -1
  11. package/engine/react/object-entities.mjs +119 -0
  12. package/engine/react/pipeline/allocate.mjs +10 -7
  13. package/engine/react/pipeline/frame-measurement.mjs +2 -0
  14. package/engine/react/project-asset-endpoint.mjs +6 -24
  15. package/engine/react/source-edit-endpoint.d.mts +10 -0
  16. package/engine/react/source-edit-endpoint.mjs +75 -0
  17. package/engine/react/sources/mdx-resolver.mjs +12 -14
  18. package/engine/react/style-discovery.mjs +1 -4
  19. package/engine/runtime/file-walk.mjs +22 -0
  20. package/engine/runtime/inspection.mjs +1 -20
  21. package/engine/runtime/path-utils.mjs +20 -0
  22. package/engine/runtime/source-text-tools.d.mts +102 -0
  23. package/engine/runtime/source-text-tools.mjs +551 -16
  24. package/engine/runtime/source-workspace.mjs +4 -31
  25. package/package.json +1 -1
  26. package/src/openpress/{App.tsx → app/OpenPressApp.tsx} +25 -12
  27. package/src/openpress/{renderer.tsx → app/OpenPressRuntime.tsx} +10 -7
  28. package/src/openpress/app/index.ts +2 -0
  29. package/src/openpress/core/Frame.tsx +9 -11
  30. package/src/openpress/core/FrameContext.tsx +8 -3
  31. package/src/openpress/core/MdxArea.tsx +11 -12
  32. package/src/openpress/core/cn.ts +4 -0
  33. package/src/openpress/core/index.tsx +2 -1
  34. package/src/openpress/core/primitives.tsx +29 -8
  35. package/src/openpress/core/types.ts +8 -0
  36. package/src/openpress/{anchorMap.ts → document-model/anchorMapModel.ts} +1 -1
  37. package/src/openpress/{indexes.ts → document-model/documentIndexes.ts} +1 -1
  38. package/src/openpress/{types.ts → document-model/documentTypes.ts} +42 -0
  39. package/src/openpress/document-model/index.ts +6 -0
  40. package/src/openpress/document-model/objectEntityModel.ts +51 -0
  41. package/src/openpress/{projectIdentity.ts → document-model/projectIdentityModel.ts} +1 -1
  42. package/src/openpress/{reactDocumentMetadata.ts → document-model/reactDocumentMetadataModel.ts} +1 -1
  43. package/src/openpress/manuscript/index.tsx +49 -7
  44. package/src/openpress/{publicPage.tsx → reader/PublicReaderPage.tsx} +31 -51
  45. package/src/openpress/{workbenchPanels.tsx → reader/ReaderNavigationPanel.tsx} +6 -5
  46. package/src/openpress/reader/index.ts +10 -0
  47. package/src/openpress/reader/pageViewportScaleModel.ts +73 -0
  48. package/src/openpress/reader/readerTypes.ts +4 -0
  49. package/src/openpress/reader/usePageViewportScale.ts +119 -0
  50. package/src/openpress/reader/usePanelState.ts +56 -0
  51. package/src/openpress/reader/useReaderHashSync.ts +61 -0
  52. package/src/openpress/reader/useReaderKeyboardNav.ts +48 -0
  53. package/src/openpress/reader/useReaderRuntime.ts +146 -0
  54. package/src/openpress/reader/useReaderScrollAnchor.ts +64 -0
  55. package/src/openpress/shared/Panel.tsx +77 -0
  56. package/src/openpress/shared/index.ts +4 -0
  57. package/src/openpress/shared/numberUtils.ts +3 -0
  58. package/src/openpress/{runtimeMode.ts → shared/runtimeMode.ts} +0 -11
  59. package/src/openpress/workbench/Workbench.tsx +407 -0
  60. package/src/openpress/workbench/actions/DeploymentControl.tsx +157 -0
  61. package/src/openpress/workbench/actions/PageZoomControl.tsx +182 -0
  62. package/src/openpress/workbench/actions/SearchControl.tsx +345 -0
  63. package/src/openpress/workbench/actions/deploymentStatusModel.ts +112 -0
  64. package/src/openpress/workbench/actions/index.ts +5 -0
  65. package/src/openpress/workbench/actions/useDeploymentWorkbench.ts +136 -0
  66. package/src/openpress/workbench/dialog/WorkbenchDialog.tsx +72 -0
  67. package/src/openpress/workbench/dialog/index.ts +1 -0
  68. package/src/openpress/workbench/document/components/DocumentPanel.tsx +127 -0
  69. package/src/openpress/workbench/document/components/InlineSourceEditorLayer.tsx +207 -0
  70. package/src/openpress/workbench/document/components/ReaderStage.tsx +9 -0
  71. package/src/openpress/workbench/document/hooks/useDocumentWorkbenchModel.ts +34 -0
  72. package/src/openpress/workbench/document/hooks/useInlineDocumentEditor.ts +525 -0
  73. package/src/openpress/workbench/document/index.ts +10 -0
  74. package/src/openpress/workbench/index.ts +2 -0
  75. package/src/openpress/workbench/inspector/InlineInspectorLayer.tsx +459 -0
  76. package/src/openpress/workbench/inspector/index.ts +5 -0
  77. package/src/openpress/workbench/inspector/inlineCommentModel.ts +125 -0
  78. package/src/openpress/workbench/inspector/inspectorGeometryModel.ts +160 -0
  79. package/src/openpress/workbench/inspector/inspectorModel.ts +408 -0
  80. package/src/openpress/workbench/inspector/useInspectorComments.ts +248 -0
  81. package/src/openpress/workbench/mentions/MentionSuggestionList.tsx +41 -0
  82. package/src/openpress/workbench/mentions/index.ts +2 -0
  83. package/src/openpress/{composerMentions.ts → workbench/mentions/useComposerMentions.ts} +1 -4
  84. package/src/openpress/workbench/panels/Panel.tsx +1 -0
  85. package/src/openpress/workbench/panels/PendingCommentsPanel.tsx +76 -0
  86. package/src/openpress/workbench/panels/WorkbenchControlPanel.tsx +29 -0
  87. package/src/openpress/workbench/panels/index.ts +3 -0
  88. package/src/openpress/workbench/project/ProjectEntryPanel.tsx +523 -0
  89. package/src/openpress/workbench/project/ProjectPreviewDialog.tsx +35 -0
  90. package/src/openpress/workbench/project/index.ts +2 -0
  91. package/src/openpress/workbench/project/projectPreviewTypes.ts +11 -0
  92. package/src/openpress/workbench/shell/WorkbenchShell.tsx +167 -0
  93. package/src/openpress/workbench/shell/index.ts +1 -0
  94. package/src/openpress/workbench/workbenchFormatters.ts +120 -0
  95. package/src/openpress/workbench/workbenchTypes.ts +35 -0
  96. package/src/styles/openpress/print-route.css +0 -2
  97. package/src/styles/openpress/{project-workspace.css → project-preview-panel.css} +13 -407
  98. package/src/styles/openpress/public-viewer.css +25 -320
  99. package/src/styles/openpress/reader-runtime.css +243 -55
  100. package/src/styles/openpress/responsive.css +145 -270
  101. package/src/styles/openpress/workbench-panels.css +214 -178
  102. package/src/styles/openpress/workbench.css +986 -451
  103. package/src/styles/openpress.css +1 -1
  104. package/vite.config.ts +50 -0
  105. package/src/openpress/inspector.ts +0 -282
  106. package/src/openpress/projectWorkspace.tsx +0 -919
  107. package/src/openpress/readerRuntime.ts +0 -230
  108. package/src/openpress/workbench.tsx +0 -1265
  109. package/src/openpress/workbenchTypes.ts +0 -4
  110. /package/src/openpress/{readerPageRegistry.ts → reader/readerPageRegistry.ts} +0 -0
  111. /package/src/openpress/{pageRoute.ts → reader/readerPageRoute.ts} +0 -0
  112. /package/src/openpress/{readerScroll.ts → reader/readerScroll.ts} +0 -0
  113. /package/src/openpress/{readerState.ts → reader/readerStateModel.ts} +0 -0
  114. /package/src/openpress/{frameScheduler.ts → shared/frameScheduler.ts} +0 -0
  115. /package/src/openpress/{projectSources.ts → workbench/project/projectSourceModel.ts} +0 -0
@@ -20,7 +20,7 @@ export async function buildReactMeasurementCss(root, config, workspace) {
20
20
  parts.push("\n/* === public/openpress/chapter-scoped.css === */\n");
21
21
  parts.push(chapterCss);
22
22
  }
23
- return rewriteAssetUrls(parts.join("\n"), config);
23
+ return rewriteAssetUrls(stripViewportMediaQueries(parts.join("\n")), config);
24
24
  }
25
25
 
26
26
  async function appendOptionalFile(parts, filePath, label) {
@@ -42,3 +42,95 @@ function rewriteAssetUrls(css, config) {
42
42
  .replace(/url\((["'])?\/openpress\/fonts\//g, `url($1${themeFontsDir}`)
43
43
  .replace(/url\((["'])?\/openpress\/katex-fonts\//g, `url($1${katexFontsDir}`);
44
44
  }
45
+
46
+ function stripViewportMediaQueries(css) {
47
+ let output = "";
48
+ let cursor = 0;
49
+
50
+ while (cursor < css.length) {
51
+ const mediaIndex = css.indexOf("@media", cursor);
52
+ if (mediaIndex < 0) {
53
+ output += css.slice(cursor);
54
+ break;
55
+ }
56
+
57
+ output += css.slice(cursor, mediaIndex);
58
+ const blockStart = css.indexOf("{", mediaIndex);
59
+ if (blockStart < 0) {
60
+ output += css.slice(mediaIndex);
61
+ break;
62
+ }
63
+
64
+ const prelude = css.slice(mediaIndex + "@media".length, blockStart);
65
+ const blockEnd = findCssBlockEnd(css, blockStart);
66
+ if (blockEnd < 0) {
67
+ output += css.slice(mediaIndex);
68
+ break;
69
+ }
70
+
71
+ if (!isViewportMediaPrelude(prelude)) {
72
+ output += css.slice(mediaIndex, blockEnd + 1);
73
+ }
74
+ cursor = blockEnd + 1;
75
+ }
76
+
77
+ return output;
78
+ }
79
+
80
+ function isViewportMediaPrelude(prelude) {
81
+ if (/\bprint\b/i.test(prelude)) return false;
82
+ return /\(\s*(?:min-|max-)?(?:device-)?(?:width|height)\s*:/i.test(prelude)
83
+ || /\(\s*orientation\s*:/i.test(prelude)
84
+ || /\(\s*(?:min-|max-)?aspect-ratio\s*:/i.test(prelude);
85
+ }
86
+
87
+ function findCssBlockEnd(css, blockStart) {
88
+ let depth = 0;
89
+ let quote = "";
90
+ let inComment = false;
91
+
92
+ for (let index = blockStart; index < css.length; index += 1) {
93
+ const current = css[index];
94
+ const next = css[index + 1];
95
+
96
+ if (inComment) {
97
+ if (current === "*" && next === "/") {
98
+ inComment = false;
99
+ index += 1;
100
+ }
101
+ continue;
102
+ }
103
+
104
+ if (quote) {
105
+ if (current === "\\") {
106
+ index += 1;
107
+ continue;
108
+ }
109
+ if (current === quote) quote = "";
110
+ continue;
111
+ }
112
+
113
+ if (current === "/" && next === "*") {
114
+ inComment = true;
115
+ index += 1;
116
+ continue;
117
+ }
118
+
119
+ if (current === "\"" || current === "'") {
120
+ quote = current;
121
+ continue;
122
+ }
123
+
124
+ if (current === "{") {
125
+ depth += 1;
126
+ continue;
127
+ }
128
+
129
+ if (current === "}") {
130
+ depth -= 1;
131
+ if (depth === 0) return index;
132
+ }
133
+ }
134
+
135
+ return -1;
136
+ }
@@ -0,0 +1,119 @@
1
+ export function createObjectEntityId(kind, ...parts) {
2
+ return [kind, ...parts.map((part) => encodeURIComponent(String(part)))].join(":");
3
+ }
4
+
5
+ export function createBlockObjectEntityId(blockId) {
6
+ return createObjectEntityId("mdx-block", blockId);
7
+ }
8
+
9
+ export function createPageObjectEntityId(frameKey) {
10
+ return createObjectEntityId("page", frameKey);
11
+ }
12
+
13
+ export function createFrameObjectEntityId(frameKey) {
14
+ return createObjectEntityId("frame", frameKey);
15
+ }
16
+
17
+ export function createMdxAreaObjectEntityId(frameKey, chainId, indexInFrame) {
18
+ return createObjectEntityId("mdx-area", frameKey, chainId, indexInFrame);
19
+ }
20
+
21
+ export function buildObjectEntities({ frames, blocks, blockMap }) {
22
+ const entities = {};
23
+ const blockParentIdByBlockId = new Map();
24
+
25
+ for (const block of blocks) {
26
+ const frameKey = block.frameKey ?? block.id;
27
+ const sourcePath = block.source?.path;
28
+ const pageId = createPageObjectEntityId(frameKey);
29
+ const base = {
30
+ frameKey,
31
+ pageId,
32
+ source: sourcePath
33
+ ? {
34
+ path: sourcePath,
35
+ file: block.source?.file,
36
+ line: 1,
37
+ column: 1,
38
+ }
39
+ : undefined,
40
+ };
41
+
42
+ entities[pageId] = {
43
+ id: pageId,
44
+ kind: "page",
45
+ label: block.title || `Page ${block.pageNumber}`,
46
+ ...base,
47
+ };
48
+
49
+ const frameId = createFrameObjectEntityId(frameKey);
50
+ entities[frameId] = {
51
+ id: frameId,
52
+ kind: "frame",
53
+ label: block.role || block.title || frameKey,
54
+ ...base,
55
+ parentId: pageId,
56
+ metadata: { role: block.role ?? null, chrome: block.chrome ?? null },
57
+ };
58
+ }
59
+
60
+ for (const frame of frames) {
61
+ const pageId = createPageObjectEntityId(frame.frameKey);
62
+ const frameId = createFrameObjectEntityId(frame.frameKey);
63
+ for (const area of frame.mdxAreas ?? []) {
64
+ const id = createMdxAreaObjectEntityId(frame.frameKey, area.chainId, area.indexInFrame);
65
+ const firstEditableBlock = (area.blockIds ?? [])
66
+ .map((blockId) => blockMap[blockId])
67
+ .find((block) => block?.path);
68
+ for (const blockId of area.blockIds ?? []) blockParentIdByBlockId.set(blockId, id);
69
+ entities[id] = {
70
+ id,
71
+ kind: "mdx-area",
72
+ label: `${area.chainId} area ${area.indexInFrame + 1}`,
73
+ parentId: frameId,
74
+ pageId,
75
+ frameKey: frame.frameKey,
76
+ chainId: area.chainId,
77
+ source: firstEditableBlock
78
+ ? {
79
+ path: firstEditableBlock.path,
80
+ source: firstEditableBlock.source,
81
+ line: firstEditableBlock.source?.line,
82
+ column: firstEditableBlock.source?.column,
83
+ }
84
+ : undefined,
85
+ metadata: { blockCount: area.blockIds?.length ?? 0 },
86
+ };
87
+ }
88
+ }
89
+
90
+ for (const block of Object.values(blockMap)) {
91
+ if (!block?.id) continue;
92
+ const id = createBlockObjectEntityId(block.id);
93
+ const pageId = block.frameKey ? createPageObjectEntityId(block.frameKey) : undefined;
94
+ entities[id] = {
95
+ id,
96
+ kind: "mdx-block",
97
+ label: block.name ? `${block.name} ${block.id}` : block.id,
98
+ parentId: blockParentIdByBlockId.get(block.id),
99
+ pageId,
100
+ blockId: block.id,
101
+ frameKey: block.frameKey,
102
+ chainId: block.chainId,
103
+ source: block.path
104
+ ? {
105
+ path: block.path,
106
+ source: block.source,
107
+ line: block.source?.line,
108
+ column: block.source?.column,
109
+ }
110
+ : undefined,
111
+ metadata: {
112
+ blockKind: block.kind ?? null,
113
+ componentName: block.kind === "component" ? block.name ?? null : null,
114
+ },
115
+ };
116
+ }
117
+
118
+ return entities;
119
+ }
@@ -179,7 +179,8 @@ function greedyAllocate(blocks, regions) {
179
179
 
180
180
  function shouldKeepWithNext(block, nextBlock) {
181
181
  if (!nextBlock) return false;
182
- return /^h[1-6]$/.test(String(block?.name ?? ""));
182
+ const name = String(block?.name ?? "");
183
+ return /^h[1-6]$/.test(name) || name === "caption";
183
184
  }
184
185
 
185
186
  function recordAllocation(allocation, result, regions) {
@@ -223,12 +224,14 @@ function groupBlockHeights(blockHeights) {
223
224
 
224
225
  function buildBlockStream(chainSource, heightMap) {
225
226
  if (!chainSource || !heightMap) return [];
226
- return chainSource.map((block) => ({
227
- id: block.id,
228
- kind: block.kind,
229
- name: block.name,
230
- height: heightMap.get(block.id) ?? 0,
231
- }));
227
+ return chainSource
228
+ .filter((block) => block.layout !== "attached")
229
+ .map((block) => ({
230
+ id: block.id,
231
+ kind: block.kind,
232
+ name: block.name,
233
+ height: heightMap.get(block.id) ?? 0,
234
+ }));
232
235
  }
233
236
 
234
237
  function* iterateChains(sources) {
@@ -221,6 +221,8 @@ async function runChromiumMeasurement(html, viewport) {
221
221
  const parentTop = chain.parentElement?.getBoundingClientRect().top ?? chain.getBoundingClientRect().top;
222
222
  let previousBottom = parentTop;
223
223
  for (const el of Array.from(chain.querySelectorAll("[data-openpress-block-id]"))) {
224
+ if (el.tagName.toLowerCase() === "caption") continue;
225
+ if (el.getAttribute("data-openpress-block-layout") === "attached") continue;
224
226
  const rect = el.getBoundingClientRect();
225
227
  out.push({
226
228
  id: el.getAttribute("data-openpress-block-id"),
@@ -3,8 +3,7 @@ import path from "node:path";
3
3
  import { loadConfig } from "../runtime/config.mjs";
4
4
  import { collectSourceTextFiles } from "../runtime/source-text-tools.mjs";
5
5
  import { insertCommentMarker } from "./comment-marker.mjs";
6
-
7
- const MAX_PROJECT_ASSET_BODY_BYTES = 64 * 1024;
6
+ import { readJsonBody, writeJson } from "./http-json.mjs";
8
7
 
9
8
  export async function handleProjectAssetRequest(req, res, {
10
9
  root = ".",
@@ -16,7 +15,7 @@ export async function handleProjectAssetRequest(req, res, {
16
15
  }
17
16
 
18
17
  try {
19
- const body = await readJsonBody(req);
18
+ const body = await readJsonBody(req, { bodyLabel: "Project asset request" });
20
19
  const config = await loadConfig(root);
21
20
  const action = stringValue(body?.action);
22
21
  const kind = stringValue(body?.kind);
@@ -53,6 +52,7 @@ export async function handleProjectAssetRequest(req, res, {
53
52
  note: body?.note,
54
53
  commentTarget: body?.commentTarget,
55
54
  currentSource: body?.currentSource,
55
+ objectEntity: body?.objectEntity,
56
56
  timestamp,
57
57
  });
58
58
  writeJson(res, 200, { ok: true, ...result });
@@ -133,6 +133,7 @@ async function createProjectAssetComment({
133
133
  note,
134
134
  commentTarget,
135
135
  currentSource,
136
+ objectEntity,
136
137
  timestamp,
137
138
  }) {
138
139
  const normalizedName = normalizeAssetName(kind, name);
@@ -146,13 +147,14 @@ async function createProjectAssetComment({
146
147
  commentTarget: stringValue(commentTarget),
147
148
  currentSource,
148
149
  });
150
+ const objectHint = stringValue(objectEntity?.id) ? ` object=${stringValue(objectEntity.id)}` : "";
149
151
 
150
152
  const result = await insertCommentMarker({
151
153
  root: config.root,
152
154
  path: target.path,
153
155
  source: { line: target.line, column: 1 },
154
156
  note: `${assetLabel(kind, normalizedName)}:${noteText}`,
155
- hint: `openpress-project-asset kind=${kind} action=comment target=${target.reason} asset=${normalizedName}`,
157
+ hint: `openpress-project-asset kind=${kind} action=comment target=${target.reason} asset=${normalizedName}${objectHint}`,
156
158
  timestamp,
157
159
  });
158
160
 
@@ -357,23 +359,3 @@ async function fileExists(filePath) {
357
359
  return false;
358
360
  }
359
361
  }
360
-
361
- async function readJsonBody(req) {
362
- let body = "";
363
- for await (const chunk of req) {
364
- body += String(chunk);
365
- if (Buffer.byteLength(body, "utf8") > MAX_PROJECT_ASSET_BODY_BYTES) {
366
- throw new Error("Project asset request body is too large.");
367
- }
368
- }
369
- try {
370
- return JSON.parse(body || "{}");
371
- } catch {
372
- throw new Error("Project asset request body must be valid JSON.");
373
- }
374
- }
375
-
376
- function writeJson(res, status, body) {
377
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
378
- res.end(`${JSON.stringify(body, null, 2)}\n`);
379
- }
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+
3
+ export function handleSourceEditRequest(
4
+ req: IncomingMessage,
5
+ res: ServerResponse,
6
+ options?: {
7
+ root?: string;
8
+ refreshDocument?: boolean;
9
+ },
10
+ ): Promise<void>;
@@ -0,0 +1,75 @@
1
+ import { loadConfig } from "../runtime/config.mjs";
2
+ import { applySourceBlockTextEdit, readSourceBlockText } from "../runtime/source-text-tools.mjs";
3
+ import { exportReactDocument } from "./document-export.mjs";
4
+ import { readJsonBody, writeJson } from "./http-json.mjs";
5
+
6
+ export async function handleSourceEditRequest(req, res, {
7
+ root = ".",
8
+ refreshDocument = true,
9
+ } = {}) {
10
+ if (req.method === "GET") {
11
+ try {
12
+ const requestUrl = new URL(req.url ?? "/", "http://localhost");
13
+ const config = await loadConfig(root);
14
+ const sourceText = await readSourceBlockText({
15
+ config,
16
+ path: requestUrl.searchParams.get("path"),
17
+ source: {
18
+ line: Number(requestUrl.searchParams.get("line")),
19
+ column: Number(requestUrl.searchParams.get("column") || 1),
20
+ endLine: Number(requestUrl.searchParams.get("endLine") || requestUrl.searchParams.get("line")),
21
+ endColumn: Number(requestUrl.searchParams.get("endColumn") || requestUrl.searchParams.get("column") || 1),
22
+ },
23
+ });
24
+ writeJson(res, 200, { ok: true, source: sourceText });
25
+ } catch (error) {
26
+ writeJson(res, 400, {
27
+ ok: false,
28
+ message: error instanceof Error ? error.message : String(error),
29
+ });
30
+ }
31
+ return;
32
+ }
33
+
34
+ if (req.method !== "POST") {
35
+ writeJson(res, 405, { ok: false, message: "OpenPress source edit endpoint requires GET or POST." });
36
+ return;
37
+ }
38
+
39
+ try {
40
+ const body = await readJsonBody(req, {
41
+ bodyLabel: "OpenPress source edit request",
42
+ maxBytes: 256 * 1024,
43
+ });
44
+ const config = await loadConfig(root);
45
+ const edit = await applySourceBlockTextEdit({
46
+ config,
47
+ path: body?.path,
48
+ source: body?.source,
49
+ text: body?.text,
50
+ kind: body?.kind,
51
+ name: body?.name,
52
+ blockId: body?.blockId,
53
+ sourceMode: body?.sourceMode === true,
54
+ });
55
+ const exported = refreshDocument && body?.refreshDocument !== false
56
+ ? await exportReactDocument(root, { syncAssets: false })
57
+ : null;
58
+
59
+ writeJson(res, 200, {
60
+ ok: true,
61
+ edit,
62
+ document: exported
63
+ ? {
64
+ path: exported.documentPath,
65
+ pageCount: exported.pageCount,
66
+ }
67
+ : undefined,
68
+ });
69
+ } catch (error) {
70
+ writeJson(res, 400, {
71
+ ok: false,
72
+ message: error instanceof Error ? error.message : String(error),
73
+ });
74
+ }
75
+ }
@@ -10,6 +10,7 @@
10
10
  import fs from "node:fs/promises";
11
11
  import path from "node:path";
12
12
  import React from "react";
13
+ import { documentRelativePath, resolveDocumentRelativePath } from "../../runtime/path-utils.mjs";
13
14
  import { compileMdx } from "../mdx-compile.mjs";
14
15
  import { createHeadingState, fallbackOutlineItems, headingAttributesForBlock } from "./heading-numbering.mjs";
15
16
 
@@ -103,6 +104,7 @@ async function resolveSource({ sourceId, descriptor, documentRoot, globalCompone
103
104
  kind: block.kind,
104
105
  name: block.name,
105
106
  text: block.text,
107
+ layout: block.layout,
106
108
  chainId,
107
109
  sectionSlug: section.slug,
108
110
  path: documentRelative(file.absolutePath, documentRoot),
@@ -323,6 +325,7 @@ function compileTocBlocks({ tocBlocks, chainId, blockIds, toc }) {
323
325
  {
324
326
  className,
325
327
  "data-openpress-block-id": block.id,
328
+ "data-openpress-object-id": createBlockObjectEntityId(block.id),
326
329
  "data-openpress-toc-entry": block.sectionSlug,
327
330
  },
328
331
  React.createElement(
@@ -352,6 +355,14 @@ function locateSection(renderData, chainId) {
352
355
  throw new Error(`No section found for chainId "${chainId}" in source "${renderData.sourceId}".`);
353
356
  }
354
357
 
358
+ function createObjectEntityId(kind, ...parts) {
359
+ return [kind, ...parts.map((part) => encodeURIComponent(String(part)))].join(":");
360
+ }
361
+
362
+ function createBlockObjectEntityId(blockId) {
363
+ return createObjectEntityId("mdx-block", blockId);
364
+ }
365
+
355
366
  // ---------------------------------------------------------------------------
356
367
  // Validation
357
368
  // ---------------------------------------------------------------------------
@@ -425,17 +436,4 @@ function deriveTitleFromDirName(name) {
425
436
  .join(" ");
426
437
  }
427
438
 
428
- function documentRelative(absolutePath, documentRoot) {
429
- return path.relative(documentRoot, absolutePath).split(path.sep).join("/");
430
- }
431
-
432
- function resolveDocumentRelativePath(documentRoot, rel, label) {
433
- if (typeof rel !== "string" || !rel.trim()) throw new Error(`${label} must be a non-empty document-relative path.`);
434
- if (rel.includes("..")) throw new Error(`${label} contains "..", rejected.`);
435
- const absolutePath = path.resolve(documentRoot, rel);
436
- const relCheck = path.relative(documentRoot, absolutePath);
437
- if (relCheck.startsWith("..") || path.isAbsolute(relCheck)) {
438
- throw new Error(`${label} escapes the document root.`);
439
- }
440
- return absolutePath;
441
- }
439
+ const documentRelative = documentRelativePath;
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { documentRelativePath } from "../runtime/path-utils.mjs";
3
4
 
4
5
  // Style discovery — only used to find per-section CSS files for the
5
6
  // section-folders preset. MDX content discovery lives in `sources/mdx-resolver`.
@@ -102,10 +103,6 @@ function pathRecord(absolutePath, documentRoot) {
102
103
  };
103
104
  }
104
105
 
105
- function documentRelativePath(absolutePath, documentRoot) {
106
- return path.relative(documentRoot, absolutePath).split(path.sep).join("/");
107
- }
108
-
109
106
  function compareSectionDirectories(a, b) {
110
107
  const left = sectionSortKey(a.name);
111
108
  const right = sectionSortKey(b.name);
@@ -0,0 +1,22 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ export async function walkFiles(directory, visit) {
5
+ let entries;
6
+ try {
7
+ entries = await fs.readdir(directory, { withFileTypes: true });
8
+ } catch (error) {
9
+ if (error?.code === "ENOENT") return;
10
+ throw error;
11
+ }
12
+
13
+ for (const entry of entries) {
14
+ if (entry.name.startsWith(".")) continue;
15
+ const absolutePath = path.join(directory, entry.name);
16
+ if (entry.isDirectory()) {
17
+ await walkFiles(absolutePath, visit);
18
+ } else if (entry.isFile()) {
19
+ await visit(absolutePath);
20
+ }
21
+ }
22
+ }
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { evaluateUrlWithChrome, stopChildProcess } from "../output/chrome-pdf.mjs";
4
4
  import { buildReactStatic, startStaticServer } from "../commands/_shared.mjs";
5
+ import { walkFiles } from "./file-walk.mjs";
5
6
  import { createIssue, createIssueReport } from "./issue-report.mjs";
6
7
  import { collectActiveContentFiles, resolveActiveSourceWorkspace } from "./source-workspace.mjs";
7
8
 
@@ -217,26 +218,6 @@ async function readMediaFiles(directory) {
217
218
  return files;
218
219
  }
219
220
 
220
- async function walkFiles(directory, visit) {
221
- let entries;
222
- try {
223
- entries = await fs.readdir(directory, { withFileTypes: true });
224
- } catch (error) {
225
- if (error?.code === "ENOENT") return;
226
- throw error;
227
- }
228
-
229
- for (const entry of entries) {
230
- if (entry.name.startsWith(".")) continue;
231
- const absolutePath = path.join(directory, entry.name);
232
- if (entry.isDirectory()) {
233
- await walkFiles(absolutePath, visit);
234
- } else if (entry.isFile()) {
235
- await visit(absolutePath);
236
- }
237
- }
238
- }
239
-
240
221
  function summarizeComponentUsage(contentFiles) {
241
222
  const usages = new Map();
242
223
  for (const file of contentFiles) {
@@ -0,0 +1,20 @@
1
+ import path from "node:path";
2
+
3
+ export function rootRelativePath(config, absolutePath) {
4
+ return path.relative(config.root, absolutePath).replaceAll("\\", "/");
5
+ }
6
+
7
+ export function documentRelativePath(absolutePath, documentRoot) {
8
+ return path.relative(documentRoot, absolutePath).split(path.sep).join("/");
9
+ }
10
+
11
+ export function resolveDocumentRelativePath(documentRoot, rel, label) {
12
+ if (typeof rel !== "string" || !rel.trim()) throw new Error(`${label} must be a non-empty document-relative path.`);
13
+ if (rel.includes("..")) throw new Error(`${label} contains "..", rejected.`);
14
+ const absolutePath = path.resolve(documentRoot, rel);
15
+ const relCheck = path.relative(documentRoot, absolutePath);
16
+ if (relCheck.startsWith("..") || path.isAbsolute(relCheck)) {
17
+ throw new Error(`${label} escapes the document root.`);
18
+ }
19
+ return absolutePath;
20
+ }
@@ -0,0 +1,102 @@
1
+ import type { ResolvedConfig } from "./config.mjs";
2
+
3
+ export type SourceTextScope = "content" | "all";
4
+
5
+ export type SourceTextMatch = {
6
+ id: string;
7
+ scope: string;
8
+ file: string;
9
+ path: string;
10
+ line: number;
11
+ column: number;
12
+ index: number;
13
+ text: string;
14
+ preview: string;
15
+ };
16
+
17
+ export type SourceTextFileSummary = {
18
+ scope: string;
19
+ file: string;
20
+ path: string;
21
+ matchCount: number;
22
+ };
23
+
24
+ export type SourceSearchReport = {
25
+ kind: "search";
26
+ query: string;
27
+ scope: SourceTextScope;
28
+ caseSensitive: boolean;
29
+ matchCount: number;
30
+ files: Array<SourceTextFileSummary>;
31
+ matches: Array<SourceTextMatch>;
32
+ };
33
+
34
+ export type SourceBlockTextEditInput = {
35
+ config: ResolvedConfig;
36
+ path: string;
37
+ source: {
38
+ line: number;
39
+ column?: number;
40
+ endLine?: number;
41
+ endColumn?: number;
42
+ };
43
+ text: string;
44
+ kind?: string;
45
+ name?: string;
46
+ blockId?: string;
47
+ cellIndex?: number;
48
+ sourceMode?: boolean;
49
+ };
50
+
51
+ export type SourceBlockTextEdit = {
52
+ blockId?: string;
53
+ path: string;
54
+ requestedPath: string;
55
+ file: string;
56
+ line: number;
57
+ column: number;
58
+ endLine: number;
59
+ endColumn: number;
60
+ before: string;
61
+ after: string;
62
+ text: string;
63
+ cellIndex?: number;
64
+ };
65
+
66
+ export function searchSourceText(options: {
67
+ config: ResolvedConfig;
68
+ query: string;
69
+ scope?: SourceTextScope;
70
+ caseSensitive?: boolean;
71
+ }): Promise<SourceSearchReport>;
72
+
73
+ export function applySourceBlockTextEdit(options: SourceBlockTextEditInput): Promise<SourceBlockTextEdit>;
74
+
75
+ export function applySourceBlockTextEditToText(documentText: string, options: Omit<SourceBlockTextEditInput, "config" | "path">): {
76
+ text: string;
77
+ edit: Omit<SourceBlockTextEdit, "path" | "requestedPath" | "file">;
78
+ };
79
+
80
+ export function readSourceBlockText(options: Pick<SourceBlockTextEditInput, "config" | "path" | "source">): Promise<{
81
+ path: string;
82
+ requestedPath: string;
83
+ file: string;
84
+ text: string;
85
+ }>;
86
+
87
+ export function readSourceBlockTextFromText(documentText: string, options: Pick<SourceBlockTextEditInput, "source">): string;
88
+
89
+ export function applySourceBlockSourceEditToText(documentText: string, options: Pick<SourceBlockTextEditInput, "source" | "text" | "blockId">): {
90
+ text: string;
91
+ edit: Omit<SourceBlockTextEdit, "path" | "requestedPath" | "file">;
92
+ };
93
+
94
+ export function collectSourceTextFiles(config: ResolvedConfig, options?: {
95
+ scope?: SourceTextScope;
96
+ }): Promise<Array<{
97
+ scope: string;
98
+ name: string;
99
+ absolutePath: string;
100
+ relativePath: string;
101
+ text: string;
102
+ }>>;