@open-document/core 0.15.0 → 0.16.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.
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-DdaKKd7_.js";
1
+ import { r as createViteConfig } from "./session-Cx7Msl_F.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { R as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-DdaKKd7_.js";
2
- import "./ops-DQbZmYRF.js";
3
- import { t as cliContext } from "./context-DGp1jwN5.js";
1
+ import { R as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-Cx7Msl_F.js";
2
+ import "./ops-CouYBa1O.js";
3
+ import { t as cliContext } from "./context-Cli81dhF.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -143,39 +143,39 @@ async function run(argv) {
143
143
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
144
144
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
145
145
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
146
- const { dev } = await import("../dev-DmzGncKf.js");
146
+ const { dev } = await import("../dev-n222xdoE.js");
147
147
  await dev(flags);
148
148
  });
149
149
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
150
- const { build } = await import("../build-CBMroMqd.js");
150
+ const { build } = await import("../build-BS_CoazO.js");
151
151
  await build(flags);
152
152
  });
153
153
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
154
- const { preview } = await import("../preview-CERhZ_FX.js");
154
+ const { preview } = await import("../preview-DV0GDIsj.js");
155
155
  await preview(flags);
156
156
  });
157
157
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, PNG, or DOCX").addOption(new Option("-f, --format <format>", "output format").choices([...EXPORT_FORMATS])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").option("--each", "one copy per row of the document's `records`").option("--name <pattern>", "with --each: file name, e.g. \"certificate-{name}\" ({#} is the row number)").action(async (docIds, flags) => {
158
- const { exportDocs } = await import("../export-BQMUBoBB.js");
158
+ const { exportDocs } = await import("../export-CCFtdscQ.js");
159
159
  await exportDocs(docIds, flags);
160
160
  });
161
161
  program.command("diff <docId>").description("Show what changed in a document since a git revision, page by page").option("-s, --since <rev>", "revision to compare against (defaults to HEAD)").option("-o, --out-dir <dir>", "directory to write the report into (defaults to `out`)").option("--json", "print the result as JSON").action(async (docId, flags) => {
162
- const { diffDoc } = await import("../diff-CMI_PVzz.js");
162
+ const { diffDoc } = await import("../diff-DB_qruzT.js");
163
163
  await diffDoc(docId, flags);
164
164
  });
165
165
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
166
- const { checkDocs } = await import("../check-C2kIZr3f.js");
166
+ const { checkDocs } = await import("../check-tTjyMCrU.js");
167
167
  await checkDocs(docIds, flags);
168
168
  });
169
169
  program.command("templates").description("List the templates a new document can start from").option("--json", "print them as JSON").action(async (flags) => {
170
- const { printTemplates } = await import("../templates-CBeC-v7e.js");
170
+ const { printTemplates } = await import("../templates-C-7VcMMV.js");
171
171
  await printTemplates(flags);
172
172
  });
173
173
  program.command("new [docId]").description("Create a document under docs/ from a template (see `open-doc templates`)").option("-t, --template <name>", "template to start from (defaults to blank)").option("--title <title>", "title of the new document").action(async (docId, flags) => {
174
- const { newDoc } = await import("../templates-CBeC-v7e.js");
174
+ const { newDoc } = await import("../templates-C-7VcMMV.js");
175
175
  await newDoc(docId, flags);
176
176
  });
177
177
  program.command("import <file>").description("Turn a Markdown file into a document under docs/").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--lang <tag>", "language of the text, e.g. zh-Hant-TW (detected for CJK when omitted)").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page").option("--contents", "add a self-filling contents page").action(async (file, flags) => {
178
- const { importDoc } = await import("../import-CiSRqZyo.js");
178
+ const { importDoc } = await import("../import-D7k0yYZh.js");
179
179
  await importDoc(file, flags);
180
180
  });
181
181
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -1,6 +1,6 @@
1
1
  import { n as readCoreVersion } from "./package-version-C89gtYSk.js";
2
2
  import { n as loadUserConfig } from "./open-doc-plugin-DnX5usgI.js";
3
- import { W as makeContext } from "./session-DdaKKd7_.js";
3
+ import { W as makeContext } from "./session-Cx7Msl_F.js";
4
4
  //#region src/cli/context.ts
5
5
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
6
6
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-DdaKKd7_.js";
1
+ import { r as createViteConfig } from "./session-Cx7Msl_F.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,5 +1,5 @@
1
- import { t as diffDocument } from "./ops-DQbZmYRF.js";
2
- import { t as cliContext } from "./context-DGp1jwN5.js";
1
+ import { o as diffDocument } from "./ops-CouYBa1O.js";
2
+ import { t as cliContext } from "./context-Cli81dhF.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/diff.ts
5
5
  const MARK = {
@@ -1,7 +1,7 @@
1
1
  import { r as EXPORT_FORMATS } from "./sdk-CqNZzbkz.js";
2
- import { C as exportDocument, R as listDocIds, S as closeRenderSession } from "./session-DdaKKd7_.js";
3
- import "./ops-DQbZmYRF.js";
4
- import { t as cliContext } from "./context-DGp1jwN5.js";
2
+ import { C as exportDocument, R as listDocIds, S as closeRenderSession } from "./session-Cx7Msl_F.js";
3
+ import "./ops-CouYBa1O.js";
4
+ import { t as cliContext } from "./context-Cli81dhF.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/cli/export.ts
7
7
  const FORMATS = EXPORT_FORMATS;
@@ -1,6 +1,6 @@
1
- import { T as importMarkdown } from "./session-DdaKKd7_.js";
2
- import "./ops-DQbZmYRF.js";
3
- import { t as cliContext } from "./context-DGp1jwN5.js";
1
+ import { T as importMarkdown } from "./session-Cx7Msl_F.js";
2
+ import "./ops-CouYBa1O.js";
3
+ import { t as cliContext } from "./context-Cli81dhF.js";
4
4
  import chalk from "chalk";
5
5
  import path from "node:path";
6
6
  //#region src/cli/import.ts
@@ -384,6 +384,68 @@ declare function createFolder(ctx: ApiContext, rawName: unknown, rawIcon?: unkno
384
384
  /** Filing only edits assignments — a document id never moves on disk. */
385
385
  declare function fileDocument(ctx: ApiContext, docId: string, folderId: string | null): Promise<void>;
386
386
  //#endregion
387
+ //#region src/ops/source.d.ts
388
+ interface OutlineBlock {
389
+ /** The declared name (`design`, `Cover`, `Body`), or `default` for the default export. */
390
+ name: string;
391
+ /** 1-based, inclusive. */
392
+ lines: [number, number];
393
+ }
394
+ interface OutlineHeading {
395
+ level: 1 | 2 | 3;
396
+ text: string;
397
+ line: number;
398
+ }
399
+ interface DocumentOutline {
400
+ id: string;
401
+ hash: string;
402
+ totalLines: number;
403
+ /** Top-level declarations in source order: the design, helper components, pages. */
404
+ blocks: OutlineBlock[];
405
+ /** h1–h3 in source order, with their text as a reader sees it. */
406
+ headings: OutlineHeading[];
407
+ }
408
+ /** Where things are in a document's source, without the source itself. */
409
+ declare function outlineDocument(ctx: ApiContext, docId: string): Promise<DocumentOutline>;
410
+ declare function outlineSource(source: string): Omit<DocumentOutline, 'id' | 'hash'>;
411
+ /** Lines `fromLine`–`toLine` (1-based, inclusive) exactly as they are; either end may be left out. */
412
+ declare function readDocumentLines(ctx: ApiContext, docId: string, fromLine?: number, toLine?: number): Promise<{
413
+ id: string;
414
+ entry: string;
415
+ hash: string;
416
+ lines: [number, number];
417
+ totalLines: number;
418
+ text: string;
419
+ }>;
420
+ /** Every line that contains `text` (exact, case-sensitive), at most `limit` of them; `total` counts all. */
421
+ declare function searchDocument(ctx: ApiContext, docId: string, text: string, limit?: number): Promise<{
422
+ id: string;
423
+ hash: string;
424
+ matches: Array<{
425
+ line: number;
426
+ text: string;
427
+ }>;
428
+ total: number;
429
+ }>;
430
+ /**
431
+ * Replaces `find` with `replace` in the source. `find` must occur exactly once
432
+ * (within `fromLine`–`toLine` when given), unless `all` is set, which replaces
433
+ * every occurrence. Text copied with its JSON escapes (`\\n` for a line break)
434
+ * is matched as what it stands for when only that reading occurs. Refused when
435
+ * the file changed since `expectedHash` was read.
436
+ */
437
+ declare function editDocument(ctx: ApiContext, docId: string, find: string, replace: string, opts?: {
438
+ all?: boolean;
439
+ expectedHash?: string;
440
+ fromLine?: number;
441
+ toLine?: number;
442
+ }): Promise<{
443
+ id: string;
444
+ replaced: number;
445
+ hash: string;
446
+ unescaped?: true;
447
+ }>;
448
+ //#endregion
387
449
  //#region src/ops/templates.d.ts
388
450
  type TemplateSummary = {
389
451
  /** What `--template` takes. */
@@ -541,4 +603,4 @@ declare function addComment(ctx: ApiContext, docId: string, loc: Loc, note: stri
541
603
  hash: string;
542
604
  }>;
543
605
  //#endregion
544
- export { type ApiContext, type AssetSummary, type ChangesResult, type DiffResult, type DocumentSummary, EXPORT_FORMATS, type ExportFormat, type ExportResult, type ImportMarkdownOptions, type ImportResult, type LayoutFinding, type LayoutReport, type Loc, ORIENTATIONS, OpsError, type Orientation, PAGE_SIZE_NAMES, type PageChange, type PageSizeName, type PageStatus, type Revision, type TemplateSummary, type ThemeSummary, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
606
+ export { type ApiContext, type AssetSummary, type ChangesResult, type DiffResult, type DocumentOutline, type DocumentSummary, EXPORT_FORMATS, type ExportFormat, type ExportResult, type ImportMarkdownOptions, type ImportResult, type LayoutFinding, type LayoutReport, type Loc, ORIENTATIONS, OpsError, type Orientation, type OutlineBlock, type OutlineHeading, PAGE_SIZE_NAMES, type PageChange, type PageSizeName, type PageStatus, type Revision, type TemplateSummary, type ThemeSummary, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, editDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, outlineDocument, outlineSource, readChanges, readDocument, readDocumentLines, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, searchDocument, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as assertExpectedSource, B as readDocument, C as exportDocument, D as listRevisions, E as slugify, F as deleteDocument, H as resolveEntry, I as docDir, L as duplicateDocument, M as withFileLock, N as OpsError, O as readChanges, P as createDocument, R as listDocIds, S as closeRenderSession, T as importMarkdown, U as writeDocument, V as renameDocument, W as makeContext, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as hashSource, k as revertChange, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as renderDocPage, x as checkLayout, y as readTheme, z as listDocuments } from "../session-DdaKKd7_.js";
3
- import { t as diffDocument } from "../ops-DQbZmYRF.js";
4
- export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
2
+ import { A as assertExpectedSource, B as readDocument, C as exportDocument, D as listRevisions, E as slugify, F as deleteDocument, H as resolveEntry, I as docDir, L as duplicateDocument, M as withFileLock, N as OpsError, O as readChanges, P as createDocument, R as listDocIds, S as closeRenderSession, T as importMarkdown, U as writeDocument, V as renameDocument, W as makeContext, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as hashSource, k as revertChange, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as renderDocPage, x as checkLayout, y as readTheme, z as listDocuments } from "../session-Cx7Msl_F.js";
3
+ import { a as searchDocument, i as readDocumentLines, n as outlineDocument, o as diffDocument, r as outlineSource, t as editDocument } from "../ops-CouYBa1O.js";
4
+ export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, editDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, outlineDocument, outlineSource, readChanges, readDocument, readDocumentLines, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, searchDocument, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
@@ -1,4 +1,4 @@
1
- import { H as resolveEntry, N as OpsError, n as createRenderSession, t as RenderUnavailableError } from "./session-DdaKKd7_.js";
1
+ import { A as assertExpectedSource, H as resolveEntry, M as withFileLock, N as OpsError, j as hashSource, n as createRenderSession, t as RenderUnavailableError } from "./session-Cx7Msl_F.js";
2
2
  import path from "node:path";
3
3
  import fs from "node:fs/promises";
4
4
  import { execFile } from "node:child_process";
@@ -398,4 +398,171 @@ async function diffDocument(ctx, docId, opts = {}) {
398
398
  }
399
399
  }
400
400
  //#endregion
401
- export { diffDocument as t };
401
+ //#region src/ops/source.ts
402
+ /**
403
+ * Working on part of a document's source: its outline, a range of lines, the
404
+ * lines that contain some text, and an exact find-and-replace. A long document
405
+ * (hundreds of lines) need not be read whole to change a sentence or a colour,
406
+ * which matters to an agent: whatever it reads is sent again on every later
407
+ * model call.
408
+ */
409
+ async function sourceOf(ctx, docId) {
410
+ const entry = resolveEntry(ctx, docId);
411
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
412
+ return {
413
+ entry,
414
+ source: await fs.readFile(entry, "utf8")
415
+ };
416
+ }
417
+ const DECLARATION = /^(?:export\s+)?(?:const|let|function|class)\s+([A-Za-z_$][\w$]*)/;
418
+ /** The text inside a heading, without tags or `{…}` expressions, spaces collapsed. */
419
+ function headingText(inner) {
420
+ return inner.replace(/\{[^{}]*\}/g, " ").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
421
+ }
422
+ /** Where things are in a document's source, without the source itself. */
423
+ async function outlineDocument(ctx, docId) {
424
+ const { source } = await sourceOf(ctx, docId);
425
+ return {
426
+ id: docId,
427
+ hash: hashSource(source),
428
+ ...outlineSource(source)
429
+ };
430
+ }
431
+ function outlineSource(source) {
432
+ const lines = source.split("\n");
433
+ const starts = [];
434
+ lines.forEach((l, i) => {
435
+ const m = DECLARATION.exec(l);
436
+ if (m) starts.push({
437
+ name: m[1] ?? "",
438
+ line: i + 1
439
+ });
440
+ else if (/^export\s+default\b/.test(l)) starts.push({
441
+ name: "default",
442
+ line: i + 1
443
+ });
444
+ });
445
+ const blocks = starts.map((s, i) => {
446
+ let end = (starts[i + 1]?.line ?? lines.length + 1) - 1;
447
+ while (end > s.line && !lines[end - 1]?.trim()) end -= 1;
448
+ return {
449
+ name: s.name,
450
+ lines: [s.line, end]
451
+ };
452
+ });
453
+ const headings = [];
454
+ const lineAt = (offset) => source.slice(0, offset).split("\n").length;
455
+ for (const m of source.matchAll(/<h([1-3])\b(?:[^>{]|\{[^}]*\})*>([\s\S]*?)<\/h\1>/g)) {
456
+ const text = headingText(m[2] ?? "");
457
+ if (text) headings.push({
458
+ level: Number(m[1]),
459
+ text: text.slice(0, 160),
460
+ line: lineAt(m.index)
461
+ });
462
+ }
463
+ return {
464
+ totalLines: lines.length,
465
+ blocks,
466
+ headings
467
+ };
468
+ }
469
+ /** Lines `fromLine`–`toLine` (1-based, inclusive) exactly as they are; either end may be left out. */
470
+ async function readDocumentLines(ctx, docId, fromLine, toLine) {
471
+ const { entry, source } = await sourceOf(ctx, docId);
472
+ const all = source.split("\n");
473
+ const from = Math.max(1, Math.floor(fromLine ?? 1));
474
+ const to = Math.min(all.length, Math.floor(toLine ?? all.length));
475
+ if (from > to) throw new OpsError(400, `lines ${from}–${to} are outside the document (${all.length} lines)`);
476
+ return {
477
+ id: docId,
478
+ entry: path.relative(ctx.userCwd, entry),
479
+ hash: hashSource(source),
480
+ lines: [from, to],
481
+ totalLines: all.length,
482
+ text: all.slice(from - 1, to).join("\n")
483
+ };
484
+ }
485
+ /** Every line that contains `text` (exact, case-sensitive), at most `limit` of them; `total` counts all. */
486
+ async function searchDocument(ctx, docId, text, limit = 60) {
487
+ if (!text) throw new OpsError(400, "text to search for is required");
488
+ const { source } = await sourceOf(ctx, docId);
489
+ const matches = [];
490
+ let total = 0;
491
+ source.split("\n").forEach((l, i) => {
492
+ if (!l.includes(text)) return;
493
+ total += 1;
494
+ if (matches.length < limit) matches.push({
495
+ line: i + 1,
496
+ text: l.length > 240 ? `${l.slice(0, 240)}…` : l
497
+ });
498
+ });
499
+ return {
500
+ id: docId,
501
+ hash: hashSource(source),
502
+ matches,
503
+ total
504
+ };
505
+ }
506
+ /** Text a model copied out of a JSON string, escapes and all: `\\n`, `\\t`, `\\"` back to what they stand for. */
507
+ function unescapeCopied(text) {
508
+ return text.replace(/\\(["\\nt])/g, (_m, c) => c === "n" ? "\n" : c === "t" ? " " : c);
509
+ }
510
+ const occurrences = (text, find) => text.split(find).length - 1;
511
+ /**
512
+ * Replaces `find` with `replace` in the source. `find` must occur exactly once
513
+ * (within `fromLine`–`toLine` when given), unless `all` is set, which replaces
514
+ * every occurrence. Text copied with its JSON escapes (`\\n` for a line break)
515
+ * is matched as what it stands for when only that reading occurs. Refused when
516
+ * the file changed since `expectedHash` was read.
517
+ */
518
+ async function editDocument(ctx, docId, find, replace, opts = {}) {
519
+ if (!find) throw new OpsError(400, "`find` is empty: copy the exact text to change from the source");
520
+ const entry = resolveEntry(ctx, docId);
521
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
522
+ return withFileLock(entry, async () => {
523
+ const source = await fs.readFile(entry, "utf8");
524
+ assertExpectedSource(source, { expectedHash: opts.expectedHash });
525
+ const lines = source.split("\n");
526
+ const from = Math.max(1, Math.floor(opts.fromLine ?? 1));
527
+ const to = Math.min(lines.length, Math.floor(opts.toLine ?? lines.length));
528
+ if (from > to) throw new OpsError(400, `lines ${from}–${to} are outside the document (${lines.length} lines)`);
529
+ const scope = lines.slice(from - 1, to).join("\n");
530
+ let needle = find;
531
+ let replacement = replace;
532
+ let count = occurrences(scope, needle);
533
+ let unescaped = false;
534
+ if (count === 0) {
535
+ const plain = unescapeCopied(find);
536
+ if (plain !== find && occurrences(scope, plain) > 0) {
537
+ needle = plain;
538
+ replacement = unescapeCopied(replace);
539
+ count = occurrences(scope, plain);
540
+ unescaped = true;
541
+ }
542
+ }
543
+ const where = opts.fromLine !== void 0 || opts.toLine !== void 0 ? ` in lines ${from}–${to}` : "";
544
+ if (count === 0) throw new OpsError(404, `\`find\` is not in the document${where}: copy it exactly, spacing and quotes included`);
545
+ if (count > 1 && !opts.all) {
546
+ const at = [];
547
+ scope.split("\n").forEach((l, i) => {
548
+ if (l.includes(needle.split("\n")[0] ?? needle)) at.push(from + i);
549
+ });
550
+ throw new OpsError(409, `\`find\` occurs ${count} times${where} (lines ${at.slice(0, 12).join(", ")}${at.length > 12 ? ", …" : ""}): pass fromLine/toLine around the one you mean, include more of the text around it, or pass all to change every one`);
551
+ }
552
+ const changed = opts.all ? scope.split(needle).join(replacement) : scope.replace(needle, () => replacement);
553
+ const next = [
554
+ ...lines.slice(0, from - 1),
555
+ ...changed.split("\n"),
556
+ ...lines.slice(to)
557
+ ].join("\n");
558
+ await fs.writeFile(entry, next, "utf8");
559
+ return {
560
+ id: docId,
561
+ replaced: opts.all ? count : 1,
562
+ hash: hashSource(next),
563
+ ...unescaped ? { unescaped: true } : {}
564
+ };
565
+ });
566
+ }
567
+ //#endregion
568
+ export { searchDocument as a, readDocumentLines as i, outlineDocument as n, diffDocument as o, outlineSource as r, editDocument as t };
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-DdaKKd7_.js";
1
+ import { r as createViteConfig } from "./session-Cx7Msl_F.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -2311,19 +2311,11 @@ async function importWorkspacePackage(userCwd, name) {
2311
2311
  //#endregion
2312
2312
  //#region src/agent/types.ts
2313
2313
  const AGENT_PROVIDER_IDS = ["codex", "antigravity"];
2314
- const AGENT_EFFORTS = [
2315
- "minimal",
2316
- "low",
2317
- "medium",
2318
- "high",
2319
- "xhigh",
2320
- "max"
2321
- ];
2322
2314
  function isAgentProviderId(value) {
2323
2315
  return typeof value === "string" && AGENT_PROVIDER_IDS.includes(value);
2324
2316
  }
2325
2317
  function isAgentEffort(value) {
2326
- return typeof value === "string" && AGENT_EFFORTS.includes(value);
2318
+ return typeof value === "string" && /^[a-z][a-z0-9_-]{0,31}$/.test(value);
2327
2319
  }
2328
2320
  function sessionSummary(session) {
2329
2321
  const { providerSessionId: _p, providerCheckpoint: _c, trimmed: _t, items: _i, ...summary } = session;
@@ -7961,7 +7953,7 @@ async function createViteConfig(opts) {
7961
7953
  return {
7962
7954
  base: config.base ?? "/",
7963
7955
  root: APP_ROOT,
7964
- cacheDir: path.join(userCwd, "node_modules", ".vite", opts.headless ? "open-doc-headless" : "open-doc"),
7956
+ cacheDir: path.join(process.env.OPEN_DOC_CACHE_DIR || path.join(userCwd, "node_modules", ".vite"), opts.headless ? "open-doc-headless" : "open-doc"),
7965
7957
  configFile: false,
7966
7958
  envDir: userCwd,
7967
7959
  plugins: [
@@ -8005,10 +7997,23 @@ async function createViteConfig(opts) {
8005
7997
  ...allowedHosts !== void 0 ? { allowedHosts } : {}
8006
7998
  })] : []
8007
7999
  ],
8008
- resolve: { alias: {
8009
- "@": APP_ROOT,
8010
- "@assets": assetsAbs
8011
- } },
8000
+ resolve: {
8001
+ alias: [
8002
+ {
8003
+ find: "@",
8004
+ replacement: APP_ROOT
8005
+ },
8006
+ {
8007
+ find: "@assets",
8008
+ replacement: assetsAbs
8009
+ },
8010
+ {
8011
+ find: /^@open-document\/core$/,
8012
+ replacement: path.join(PKG_ROOT, "dist", "index.js")
8013
+ }
8014
+ ],
8015
+ dedupe: ["react", "react-dom"]
8016
+ },
8012
8017
  optimizeDeps: {
8013
8018
  entries: [path.join(APP_ROOT, "main.tsx")],
8014
8019
  include: [
@@ -1,6 +1,6 @@
1
- import { l as createFromTemplate, u as listTemplates } from "./session-DdaKKd7_.js";
2
- import "./ops-DQbZmYRF.js";
3
- import { t as cliContext } from "./context-DGp1jwN5.js";
1
+ import { l as createFromTemplate, u as listTemplates } from "./session-Cx7Msl_F.js";
2
+ import "./ops-CouYBa1O.js";
3
+ import { t as cliContext } from "./context-Cli81dhF.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/templates.ts
6
6
  /**
@@ -1,3 +1,3 @@
1
1
  import { r as openDocPlugin } from "../open-doc-plugin-DnX5usgI.js";
2
- import { r as createViteConfig } from "../session-DdaKKd7_.js";
2
+ import { r as createViteConfig } from "../session-Cx7Msl_F.js";
3
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -22,6 +22,8 @@ Read the matching reference **before** using a primitive:
22
22
  | Tables, stat rows, `<Chart>`, `<Sparkline>`, `<Callout>` | rendering data or callouts | `references/tables-and-charts.md` |
23
23
  | Assets + `<ImagePlaceholder>` | importing images or leaving a placeholder | `references/assets.md` |
24
24
  | Footnotes, `<Figure>`, `<Ref>`, `<DataTable>`, `<Cite>`, `<Bibliography>`, `<CodeBlock>` | notes, figures, cross-references, citations, code blocks, or `.csv` | `references/long-form.md` |
25
+ | `<Diagram>` and `.mmd` diagrams | drawing a flow, architecture, or sequence | `references/diagrams.md` |
26
+ | Exports, `open-doc diff`, Word output, Inspect mode, Design panel | telling the user what they can do next, or an export / review step | `references/runtime.md` |
25
27
 
26
28
  ## Themes
27
29
 
@@ -145,59 +147,19 @@ Bare elements on the sheet start from a base drawn from the design, not from a b
145
147
 
146
148
  ## Footnotes, numbering, and data
147
149
 
148
- Four primitives resolve themselves from the rendered pages, the same way the
149
- contents list does. Read `references/long-form.md` before using any of them.
150
-
151
- - **`<Footnote>`** — numbered by position, printed at the foot of the page its
152
- marker landed on, and its height is taken out of that page's budget before the
153
- packer breaks. On a fixed page, add `<Footnotes />` where they should print.
154
- - **`<Figure caption id>`** — a numbered figure (or `kind="table"`), caption and
155
- content in one unbreakable block. `<ListOfFigures />` / `<ListOfTables />`
156
- build the lists.
157
- - **`<Ref to="id" />`** — "Figure 3", plus the page when the target is elsewhere.
158
- - **`<Cite id="…" source="…" />` & `<Bibliography />`** — academic/report citations numbered in order of first appearance (`[1]`), deduplicated by `id`, and listed by `<Bibliography />`.
159
- - **`<DataTable rows={…} splittable summaryRow>`** — a print-shaped table from an imported `.csv` (supports automatic multi-page splitting with repeated headers when `splittable` is set, plus `summaryRow`, `dataBar`, `'currency'`, and `'delta'` formats).
160
- - **`<CodeBlock code={…} lang="ts" lineNumbers highlightLines={[…]} caption="…" />`** — zero-dependency syntax-highlighted code block with optional line numbers, highlighted lines, and figure numbering when given `caption`.
161
- - **`<Callout type="note|tip|warning|danger" title="…">`** — semantic callout box styled with `--od-*` tokens.
162
- - **`<Diagram chart={…} caption>`** — an architecture, flow, or sequence drawing from an imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
163
- - **`<Chart data x y caption>` & `<Sparkline data={…} />`** — `bar`, `horizontal-bar`, `line`, `area`, or `pie` charts from rows, plus inline SVG `<Sparkline>` for tables and stat cards. See `references/tables-and-charts.md`.
150
+ These primitives resolve themselves from the rendered pages, the same way the
151
+ contents list does. Read the reference in brackets before using one.
152
+
153
+ - **`<Footnote>`** — numbered by position, printed at the foot of its page, its height taken out of that page's budget. On a fixed page, add `<Footnotes />` where they print. (`long-form.md`)
154
+ - **`<Figure caption id>`**, **`<Ref to="id" />`**, `<ListOfFigures />` / `<ListOfTables />` — numbered figures and tables, and references to them with the page. (`long-form.md`)
155
+ - **`<Cite id source />`** & **`<Bibliography />`** — citations numbered by first appearance. (`long-form.md`)
156
+ - **`<DataTable rows>`** from an imported `.csv`, splittable across pages; **`<CodeBlock code lang>`** with line numbers and highlights. (`long-form.md`)
157
+ - **`<Chart>`**, **`<Sparkline>`**, **`<Callout type>`** — charts from rows and semantic callouts. (`tables-and-charts.md`)
158
+ - **`<Diagram chart caption>`** — flowcharts and sequence diagrams written as `.mmd` text, compiled to SVG in the document's own ink. Never use an image of a diagram that can be written. (`diagrams.md`)
164
159
 
165
160
  `meta.labels` sets what they are called (`圖`, `表`) — the numbering itself is
166
161
  structural.
167
162
 
168
- ## Diagrams
169
-
170
- Write the drawing as Mermaid-flavoured text in `docs/<id>/<name>.mmd`, import
171
- it, and hand it to `<Diagram>`:
172
-
173
- ```mermaid
174
- %% docs/my-doc/architecture.mmd
175
- flowchart TD
176
- Client[使用者] -->|HTTPS| Gate{驗證}
177
- Gate -->|通過| App[應用伺服器]
178
- Gate -.->|拒絕| Deny([401])
179
- App --> DB[資料庫]
180
- ```
181
-
182
- ```tsx
183
- import { Diagram } from '@open-document/core';
184
- import architecture from './architecture.mmd';
185
-
186
- <Diagram chart={architecture} caption="請求路徑" width={420} />
187
- ```
188
-
189
- It is compiled to SVG at build time and drawn with the document's own theme
190
- variables, so it prints with the same ink and faces as the prose around it.
191
- Never reach for an image of a diagram when the diagram can be written.
192
-
193
- Supported:
194
- - `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
195
- - `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
196
- - Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
197
-
198
- Keep `width` inside the text block: a drawing wider than the column is a layout
199
- fault, and `open-doc check` reports it as one.
200
-
201
163
  ## Table of contents
202
164
 
203
165
  ```tsx
@@ -356,19 +318,9 @@ A document is not a slide deck. Long-form copy is the point — but it still has
356
318
  - Cite numbers with their source and date inline (`Q3 billing export, 2026-08-01`) — a report that can't be traced gets ignored.
357
319
  - Don't invent data. If a number must come from the user, leave `<ImagePlaceholder>` for a chart or an explicit `TODO:` marker in the copy and tell them at hand-off.
358
320
 
359
- ## Runtime behavior you get for free
360
-
361
- - Home page lists every folder under `docs/` with a live thumbnail of page 1.
362
- - Document view: vertical scroll of real-size pages, a left rail that switches between page thumbnails, the outline, and the document's assets, zoom (actual size / fit width / fit page), page counter, and fullscreen reading (`F`).
363
- - Export PDF (print pipeline, correct `@page` size) and export HTML (self-contained, printable).
364
- - Hot reload: edit `index.tsx` and the pages update live.
365
- - **Assets panel** (`/assets` in the dev UI): upload, rename, and delete files in the global `assets/` folder or any document's `assets/` folder, with an "unused" badge and a copy-ready import line. Files you reference in source are what it scans, so an import you write by hand shows up there immediately.
366
- - **Inspect mode** (the "Inspect" button, dev only): click any element on a page to edit its text in place — the change is written straight back into `docs/<id>/index.tsx` — or leave a note for the agent, which is stored as a `@doc-comment` marker and processed by the `apply-comments` skill.
367
- - **Download menu** — PDF (true page size) and self-contained HTML.
368
- - **Headless render** — `open-doc export <id> --format pdf|html|png|docx` produces the same output from a script, and `open-doc check <id>` reports layout faults. Both drive the real viewer in a headless browser, so what they produce is what the Download menu produces. A PDF exported this way also carries the outline as bookmarks and is tagged for screen readers — the same headings the sidebar and `<TableOfContents />` list, so a heading marked `data-od-outline="skip"` stays out and `data-od-heading` sets the bookmark's text. (The Download menu prints through the browser's dialog, which writes no bookmarks.)
369
- - **What changed** — `open-doc diff <id> [--since <rev>]` (MCP: `diff_document`) renders the document as it is and as it was at a git revision (default `HEAD`), pairs the pages by content, and lists each page as same, changed, added or removed, with the lines of text that moved. It also writes `out/<id>-diff.html`, a self-contained before/after report with the changed regions outlined — hand that to a reviewer. Run it before handing back an edit, so your summary of what changed is what actually changed on the page.
370
- - **Word (DOCX)** — for review that runs in Word. It carries structure, not page breaks: headings become Word heading styles, `<TableOfContents />` a TOC field, `<Footnote>` real footnotes, a `flow()` header and footer a Word header and footer with page-number fields, and the theme's CJK font the East Asian font. Write headings as real `h1`–`h3` and tables as `<table>`/`<DataTable>` so they arrive as structure; anything drawn with boxes (a chart made of `div`s) arrives as a picture, and absolutely positioned layouts on fixed pages flow as plain paragraphs.
371
- - **Design panel** (the "Design" button in the document view, dev only): live-tweaks the `design` const — palette, fonts, type scale, margin, leading, radius — previewing on the real pages and writing the values back into `docs/<id>/index.tsx` on save.
321
+ ## Writing for the viewer's editors
322
+
323
+ The viewer, exports, `open-doc check` / `export` / `diff`, the Inspect mode and the Design panel come with the framework — `references/runtime.md` lists what each does. Two of them edit your source, so write it in the shape they can read.
372
324
 
373
325
  ### Writing for the inspector
374
326
 
@@ -0,0 +1,32 @@
1
+ # Diagrams
2
+
3
+ Write the drawing as Mermaid-flavoured text in `docs/<id>/<name>.mmd`, import
4
+ it, and hand it to `<Diagram>`:
5
+
6
+ ```mermaid
7
+ %% docs/my-doc/architecture.mmd
8
+ flowchart TD
9
+ Client[使用者] -->|HTTPS| Gate{驗證}
10
+ Gate -->|通過| App[應用伺服器]
11
+ Gate -.->|拒絕| Deny([401])
12
+ App --> DB[資料庫]
13
+ ```
14
+
15
+ ```tsx
16
+ import { Diagram } from '@open-document/core';
17
+ import architecture from './architecture.mmd';
18
+
19
+ <Diagram chart={architecture} caption="請求路徑" width={420} />
20
+ ```
21
+
22
+ It is compiled to SVG at build time and drawn with the document's own theme
23
+ variables, so it prints with the same ink and faces as the prose around it.
24
+ Never reach for an image of a diagram when the diagram can be written.
25
+
26
+ Supported:
27
+ - `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
28
+ - `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
29
+ - Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
30
+
31
+ Keep `width` inside the text block: a drawing wider than the column is a layout
32
+ fault, and `open-doc check` reports it as one.
@@ -0,0 +1,15 @@
1
+ # Runtime behavior you get for free
2
+
3
+ What the framework and its viewer already do, so a document never re-implements it.
4
+
5
+ - Home page lists every folder under `docs/` with a live thumbnail of page 1.
6
+ - Document view: vertical scroll of real-size pages, a left rail that switches between page thumbnails, the outline, and the document's assets, zoom (actual size / fit width / fit page), page counter, and fullscreen reading (`F`).
7
+ - Export PDF (print pipeline, correct `@page` size) and export HTML (self-contained, printable).
8
+ - Hot reload: edit `index.tsx` and the pages update live.
9
+ - **Assets panel** (`/assets` in the dev UI): upload, rename, and delete files in the global `assets/` folder or any document's `assets/` folder, with an "unused" badge and a copy-ready import line. Files you reference in source are what it scans, so an import you write by hand shows up there immediately.
10
+ - **Inspect mode** (the "Inspect" button, dev only): click any element on a page to edit its text in place — the change is written straight back into `docs/<id>/index.tsx` — or leave a note for the agent, which is stored as a `@doc-comment` marker and processed by the `apply-comments` skill.
11
+ - **Download menu** — PDF (true page size) and self-contained HTML.
12
+ - **Headless render** — `open-doc export <id> --format pdf|html|png|docx` produces the same output from a script, and `open-doc check <id>` reports layout faults. Both drive the real viewer in a headless browser, so what they produce is what the Download menu produces. A PDF exported this way also carries the outline as bookmarks and is tagged for screen readers — the same headings the sidebar and `<TableOfContents />` list, so a heading marked `data-od-outline="skip"` stays out and `data-od-heading` sets the bookmark's text. (The Download menu prints through the browser's dialog, which writes no bookmarks.)
13
+ - **What changed** — `open-doc diff <id> [--since <rev>]` (MCP: `diff_document`) renders the document as it is and as it was at a git revision (default `HEAD`), pairs the pages by content, and lists each page as same, changed, added or removed, with the lines of text that moved. It also writes `out/<id>-diff.html`, a self-contained before/after report with the changed regions outlined — hand that to a reviewer. Run it before handing back an edit, so your summary of what changed is what actually changed on the page.
14
+ - **Word (DOCX)** — for review that runs in Word. It carries structure, not page breaks: headings become Word heading styles, `<TableOfContents />` a TOC field, `<Footnote>` real footnotes, a `flow()` header and footer a Word header and footer with page-number fields, and the theme's CJK font the East Asian font. Write headings as real `h1`–`h3` and tables as `<table>`/`<DataTable>` so they arrive as structure; anything drawn with boxes (a chart made of `div`s) arrives as a picture, and absolutely positioned layouts on fixed pages flow as plain paragraphs.
15
+ - **Design panel** (the "Design" button in the document view, dev only): live-tweaks the `design` const — palette, fonts, type scale, margin, leading, radius — previewing on the real pages and writing the values back into `docs/<id>/index.tsx` on save.
@@ -6,16 +6,23 @@ export const AGENT_PROVIDER_IDS = ['codex', 'antigravity'] as const;
6
6
 
7
7
  export type AgentProviderId = (typeof AGENT_PROVIDER_IDS)[number];
8
8
 
9
+ // The levels the panel has words for. A model may offer others (a new level such
10
+ // as 'ultra'): those pass through as given and show under their own name.
9
11
  export const AGENT_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
10
12
 
11
- export type AgentEffort = (typeof AGENT_EFFORTS)[number];
13
+ export type AgentEffort = string;
12
14
 
13
15
  export function isAgentProviderId(value: unknown): value is AgentProviderId {
14
16
  return typeof value === 'string' && (AGENT_PROVIDER_IDS as readonly string[]).includes(value);
15
17
  }
16
18
 
17
19
  export function isAgentEffort(value: unknown): value is AgentEffort {
18
- return typeof value === 'string' && (AGENT_EFFORTS as readonly string[]).includes(value);
20
+ return typeof value === 'string' && /^[a-z][a-z0-9_-]{0,31}$/.test(value);
21
+ }
22
+
23
+ /** Words for a reasoning level: the translation when the panel has one, else its own name. */
24
+ export function effortLabel(effort: string, words: Partial<Record<string, string>>): string {
25
+ return words[effort] ?? effort.charAt(0).toUpperCase() + effort.slice(1);
19
26
  }
20
27
 
21
28
  export type AgentModelOption = {
@@ -48,6 +48,7 @@ import type {
48
48
  AgentTurnContext,
49
49
  RespondPayload,
50
50
  } from '../../../agent/types';
51
+ import { effortLabel } from '../../../agent/types';
51
52
  import { Composer, ContextChip } from './composer';
52
53
  import { ConnectView, PreviewBadge, ProviderConsent } from './connect-view';
53
54
  import { HistoryView } from './history-view';
@@ -451,7 +452,7 @@ function ModelMenu({
451
452
  {current?.preview && <PreviewBadge />}
452
453
  {effort && (
453
454
  <span className="shrink-0 font-normal text-muted-foreground">
454
- {t.agent.efforts[effort]}
455
+ {effortLabel(effort, t.agent.efforts)}
455
456
  </span>
456
457
  )}
457
458
  <ChevronDown className="size-3 text-muted-foreground" aria-hidden />
@@ -557,7 +558,7 @@ function ModelMenu({
557
558
  checked && 'bg-background font-medium text-foreground shadow-edge',
558
559
  )}
559
560
  >
560
- {e ? t.agent.efforts[e] : t.agent.effortAuto}
561
+ {e ? effortLabel(e, t.agent.efforts) : t.agent.effortAuto}
561
562
  </button>
562
563
  );
563
564
  })}
@@ -0,0 +1,49 @@
1
+ import { useTheme } from 'next-themes';
2
+ import { useEffect } from 'react';
3
+ import { documentPathForHost, getHost, hostCan } from '../lib/host';
4
+
5
+ /**
6
+ * Connects the viewer to a host app, when there is one: the theme follows the
7
+ * host's, and opening another document goes through the host (a desktop host
8
+ * opens it in its own tab). Renders nothing; with no host it does nothing.
9
+ */
10
+ export function HostBridge() {
11
+ const { setTheme } = useTheme();
12
+
13
+ useEffect(() => {
14
+ const host = getHost();
15
+ if (!host?.theme || !hostCan(host, 'theme')) return;
16
+ setTheme(host.theme.current().mode);
17
+ return host.theme.onChange((theme) => setTheme(theme.mode));
18
+ }, [setTheme]);
19
+
20
+ useEffect(() => {
21
+ const host = getHost();
22
+ if (!host?.openItem || !hostCan(host, 'openItem')) return;
23
+ const open = host.openItem.bind(host);
24
+ const onClick = (e: MouseEvent) => {
25
+ if (
26
+ e.defaultPrevented ||
27
+ e.button !== 0 ||
28
+ e.metaKey ||
29
+ e.ctrlKey ||
30
+ e.shiftKey ||
31
+ e.altKey
32
+ ) {
33
+ return;
34
+ }
35
+ const anchor = (e.target as Element | null)?.closest?.('a[href]');
36
+ if (!(anchor instanceof HTMLAnchorElement) || (anchor.target && anchor.target !== '_self')) {
37
+ return;
38
+ }
39
+ if (anchor.hasAttribute('download')) return;
40
+ const path = documentPathForHost(anchor.href, window.location.href);
41
+ if (path && open({ path, title: anchor.textContent?.trim() || undefined }))
42
+ e.preventDefault();
43
+ };
44
+ document.addEventListener('click', onClick, true);
45
+ return () => document.removeEventListener('click', onClick, true);
46
+ }, []);
47
+
48
+ return null;
49
+ }
@@ -1,4 +1,5 @@
1
- import { type MutableRefObject, useCallback, useEffect, useState } from 'react';
1
+ import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react';
2
+ import { getHost, hostCan } from '../../lib/host';
2
3
  import { useT } from '../../lib/i18n';
3
4
  import { useDesignPanelState } from '../design-panel/design-provider';
4
5
  import { useHistory } from '../history-provider';
@@ -88,6 +89,24 @@ export function EditSaveCard({
88
89
  return () => window.removeEventListener('keydown', onKey, true);
89
90
  }, [count, save, history]);
90
91
 
92
+ // A host app asks before it closes, reloads or quits.
93
+ const latest = useRef({ count, committing, save, discard });
94
+ latest.current = { count, committing, save, discard };
95
+ useEffect(() => {
96
+ const host = getHost();
97
+ if (!host?.guardUnsaved || !hostCan(host, 'guardUnsaved')) return;
98
+ return host.guardUnsaved({
99
+ status: () => ({ drafts: latest.current.count > 0, pending: latest.current.committing }),
100
+ settle: async (action) => {
101
+ if (action === 'save' && latest.current.count > 0) {
102
+ return (await latest.current.save()) ? { ok: true } : { ok: false, error: 'not saved' };
103
+ }
104
+ latest.current.discard();
105
+ return { ok: true };
106
+ },
107
+ });
108
+ }, []);
109
+
91
110
  useEffect(() => {
92
111
  if (!design.dirty) return;
93
112
  const onBeforeUnload = (e: BeforeUnloadEvent) => e.preventDefault();
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The open-x host protocol, v1: what a host app (a desktop shell, an editor
3
+ * extension) offers the viewer. Every member is optional, and with no host the
4
+ * viewer behaves exactly as in a browser. Hosts keep the same types.
5
+ */
6
+ export type HostCapability =
7
+ | 'theme'
8
+ | 'openItem'
9
+ | 'openHome'
10
+ | 'guardUnsaved'
11
+ | 'printToPdf'
12
+ | 'translucent';
13
+
14
+ export interface HostTheme {
15
+ mode: 'light' | 'dark';
16
+ accent: string | null;
17
+ }
18
+
19
+ export type UnsavedStatus = { drafts: boolean; pending: boolean };
20
+ export type UnsavedAction = 'save' | 'discard' | 'abandon';
21
+ export type UnsavedOutcome = { ok: true } | { ok: false; error: string };
22
+
23
+ export interface UnsavedGuard {
24
+ status(): UnsavedStatus;
25
+ settle(action: UnsavedAction): Promise<UnsavedOutcome>;
26
+ }
27
+
28
+ export interface OpenxHost {
29
+ protocol: 1;
30
+ name: string;
31
+ capabilities: HostCapability[];
32
+ theme?: {
33
+ current(): HostTheme;
34
+ onChange(listener: (theme: HostTheme) => void): () => void;
35
+ };
36
+ openItem?(item: { path: string; title?: string }): boolean;
37
+ openHome?(path?: string): boolean;
38
+ guardUnsaved?(guard: UnsavedGuard): () => void;
39
+ printToPdf?(filename: string): Promise<boolean>;
40
+ translucent?: boolean;
41
+ }
42
+
43
+ declare global {
44
+ interface Window {
45
+ openxHost?: OpenxHost;
46
+ }
47
+ }
48
+
49
+ export function getHost(): OpenxHost | undefined {
50
+ const host = typeof window === 'undefined' ? undefined : window.openxHost;
51
+ return host?.protocol === 1 ? host : undefined;
52
+ }
53
+
54
+ export function hostCan(host: OpenxHost | undefined, capability: HostCapability): boolean {
55
+ return Boolean(host?.capabilities?.includes(capability));
56
+ }
57
+
58
+ /**
59
+ * The server path a click should hand to the host: a same-origin link to a
60
+ * document other than the one shown. Null leaves the click to the viewer.
61
+ */
62
+ export function documentPathForHost(href: string, current: string): string | null {
63
+ const target = new URL(href, current);
64
+ const here = new URL(current);
65
+ if (target.origin !== here.origin) return null;
66
+ const doc = /\/d\/([^/?#]+)/.exec(target.pathname);
67
+ if (!doc) return null;
68
+ const shownDoc = /\/d\/([^/?#]+)/.exec(here.pathname)?.[1];
69
+ if (shownDoc === doc[1]) return null;
70
+ return target.pathname + target.search;
71
+ }
package/src/app/main.tsx CHANGED
@@ -2,6 +2,7 @@ import { ThemeProvider } from 'next-themes';
2
2
  import { StrictMode } from 'react';
3
3
  import { createRoot } from 'react-dom/client';
4
4
  import { App } from './app';
5
+ import { HostBridge } from './components/host-bridge';
5
6
  import { LocaleProvider } from './lib/i18n';
6
7
  import './styles.css';
7
8
 
@@ -10,6 +11,7 @@ createRoot(document.getElementById('root')!).render(
10
11
  <StrictMode>
11
12
  <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
12
13
  <LocaleProvider>
14
+ <HostBridge />
13
15
  <App />
14
16
  </LocaleProvider>
15
17
  </ThemeProvider>