dsh-pdf-workbench 1.3.4 → 1.4.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.
package/docs/DETAIL.md CHANGED
@@ -1,69 +1 @@
1
- # PDF阅读
2
-
3
- 以「书 → 章」为骨架的整页PDF阅读。点左侧栏的工作台图标打开:书架列出书,点书卡进入章节页。
4
-
5
- ## 功能
6
-
7
- - **书库**:可添加多个书库;分片目录 `<库根>\分片\<书 id>\`、整本 PDF 放 `<库根>\整本\`;
8
- 分片文件名带页码范围即可(如 `概率论_积分和数学期望_97-138.pdf`),按页序自动编号。
9
- - **书架**:单击选中、双击进入章节;空白处拖拽框选;隐藏书籍、自定义多文件书架(可嵌套)、右键删除书架并释放书。
10
- - **章节会话**:提取 / 答疑 / 习题三组;「+ 新建」优先进已有会话,上下文接近上限才续开;
11
- 支持导入已有会话、重命名、取消挂载;标题形如 `[书 id c04] 答疑`。
12
- - **产物**:目录 `<库根>\产物\<书 id>\<章号>\`;文本类文件在右侧预览;md 可一键转 PDF(需 Python + TeX Live);
13
- 产物会话挂在对应 PDF 行下,可折叠、可「另起」。
14
- - **阅读器**:内置 pdf.js,单页/连续、翻页、缩放、页码跳转、键盘操作;右栏预览可开关。
15
- - **清理**:产物删除进 `<库根>\回收站\`;会话归档后工作台不再列出;隐藏书架可整体释放。
16
- - **其他**:设置菜单显示版本号、右侧预览与「非PDF删除」保护开关;底部使用提示可折叠。
17
-
18
- ## 使用
19
-
20
- 1. 添加书库(选库根目录),进入书架;
21
- 2. 按目录拆分章节 PDF,或直接放整本 PDF;
22
- 3. 展开章节 → 打开 PDF 或新建会话;会话自带书名/章名/产物目录上下文。
23
-
24
- ## 限制
25
-
26
- - 仅面向数学书工作流;PDF 阅读器只读,不做标注/笔记;
27
- - Markdown→PDF 需要本机 Python 与 TeX Live(xelatex),插件运行时不依赖;
28
- - 书 id 由目录/文件名推导,添加书库后不要重命名该目录,否则旧会话与产物会对不上;
29
- - 界面只显示本机真实路径;跨机器需重新添加书库。
30
-
31
- ## 作者想说
32
-
33
-
34
- 开发这一个插件是为了契合我自己学习数学的工作流!
35
-
36
- 虽然数学看起来已经没有什么前景了,但是学习数学带来的思维上的好处还是很明显的:第一是应用的场景也会对数学能力有进一步的要求,以前可能学个线性代数,凑合能干活就行了,但是现在不学习到抽象代数,可能连如何向AI去问问题,让它干活都不足够;第二是数学教育和美的体会都还在,只是前进、探索的路会有AI走一遍而已。
37
-
38
- 读数学书则是学习数学的最好方式之一,而为什么不让AI去辅助解答,去给出标答,去辅助笔记呢?有了这个插件,我们不再需要事事与别人讨论,我们拥有至少一条的实现问题的路径,我们不再需要做摘抄这样费时费力的事情!
39
-
40
- 当然这个插件不是必须的,我早就在用这套工作流了,只是把这套工作流以插件集成的形式体现出来而已,希望大家用的愉快,有问题也可以随时反馈。
41
-
42
-
43
- GitHub: https://github.com/minggemofashi/dsh-pdf-workbench
44
-
45
-
46
- ## Token 消耗
47
-
48
- - 打开书架、展开章节、预览产物、右侧 PDF 预览:不进入模型上下文,不消耗对话 token。
49
- - 新建会话草稿只带一行上下文(书名 / 章名 / PDF / 产物目录),约几百 token 级。
50
- - 会话问答按对话长度计费;「整理提纲」会把该章多个会话再汇总一次。
51
- - 整本 PDF 会话很贵(一次可能几十万 token),只适合小文件/小论文。
52
- - 插件不会自动把 PDF 塞进上下文;AI 需要时会自己读取,读多少取决于它。
53
-
54
- ## 不能做什么
55
-
56
- - 阅读器只读:无标注、高亮、批注、笔记,也不写回 PDF。
57
- - 不做 OCR、不整本拆分;整本 PDF 只作为一本书显示。
58
- - 章节与三种会话的语义面向数学书,不是通用阅读器。
59
- - 书库在本机,跨机器需重新添加;没有全书语义搜索。
60
-
61
- ## 归档不是删除
62
-
63
- 会话行的「归档」只把会话移出工作台列表,不会删除会话本身;已归档会话仍保存在 DSH 中,可从 DSH 的归档恢复或在 DSH 里清理。工作台的「清理空会话」只处理没有发过消息的空白会话。
64
-
65
- ## 平台支持
66
-
67
- - **仅支持 Windows 10 / 11(x64)**,且只在这两个系统上验证过。
68
- - macOS / Linux 未适配、未测试:路径分隔符、`py`/`python` 启动器、TeX 检测目录都按 Windows 编写,其他系统上大概率无法正常工作。
69
- - 可选环境:Python 3 + TeX Live(xelatex、ctex);缺失时「md→PDF」按钮隐藏,其余功能正常。
1
+ ![PDF 阅读工作台:书架、页内批注与按章答疑](preview.svg)
@@ -252,6 +252,9 @@ ctx.contextMenus.register({
252
252
  - **同一章多个标签**:地址即内容 id,同一章在同一栏只有一张标签;重复打开是「指向同页」而不是新标签。
253
253
  - **跨书跳转**:`openFromSide` 会先切书页再开阅读器,避免「返回章节」落到旧书。
254
254
  - **桌面挂件遮挡**:`dsh-whale-widget-bowl` 的根节点是 `.dshwv-root`(`position:fixed; z-index:9999`,本身 `pointer-events:none`),跨插件无法把它压到页面下方,所以做成**悬停淡化**:指针进入预览时给 `body` 打 `data-pdfdesk-reading`,注入的样式把它淡到 28%;该插件不在时规则匹配不到元素。若以后挂件类名变了,淡化失效但不影响阅读功能。
255
+ - **不再重复打开同一份 PDF(2026-11-24)**:右栏以前是第二个独立 `getDocument`——同一章要下载两次、起两个 worker、解析两遍(38 MB 扫描章节实测首屏 327 ms,其中 233 ms 是重复加载)。现在阅读器、右栏、双语、遮罩都走 `sharedDocuments.claim(url, …)`:以完整 URL 为键,引用计数,最后一个视图离开后保留 30 s(最多 2 份)再销毁——跳到会话时「阅读器卸载 → 右栏挂载」正好落在保留窗口内,右栏只剩一次页面渲染(同文件实测 ~94 ms)。阅读器「重试」带 `retry=`、译文/叠加带 `rev=`,不同版本不会误用旧文档。
256
+ - **Host 侧按 Range 发送(2026-11-24)**:`/pdfdesk/pdf` 改由 `src/host/pdf-stream.js` 处理——`ETag`(大小+mtime)+ `If-None-Match → 304`、`Range → 206`、越界 `416`、`HEAD` 只回头,并用 `createReadStream` 流式发送而不是整份读进内存;`/pdfdesk/vendor/*` 加 `max-age=300` + `ETag`,pdf.js 的 1.26 MB worker 不再每开一个文档重下。响应头不再是 `cache-control: no-store` / `accept-ranges: none`。
257
+ - **同章批注同步只跑一次**:打开会话时阅读器和右栏都会调 `syncChapterAnnotations`(扫全章 localStorage + 拉镜像),10 s 内同章复用第一次结果。
255
258
 
256
259
  ## 10. 关键代码位置(`client.js`)
257
260
 
@@ -267,5 +270,6 @@ ctx.contextMenus.register({
267
270
  | 注册 | `registerSidePreview(ctx)`(`apply` 末尾调用) |
268
271
  | 打开右侧 | `openPdfInSession`(`sideTabAvailable` 判定后走自建地址) |
269
272
  | 阅读器同步 | `WorkbenchPage` 的 `readerViewKey` / `readerLinkKey`;`ReaderView` 的 `docRev`、`remoteAnnotRev` 与写回判据 |
270
- | 取数路由 | `src/host/routes.js` 的 `/pdf`(`variant`、`rev`) |
273
+ | 取数路由 | `src/host/routes.js` 的 `/pdf`(`variant`、`rev`),文件由 `src/host/pdf-stream.js` 发送 |
274
+ | 共享文档 | `createDocumentCache` / `sharedDocuments` / `chapterPdfUrl`(阅读器、右栏、双语、遮罩共用) |
271
275
  | 样式 | `CSS` 里的 `.md-side*`、`.md-annot-readonly`、`.md-annot-edit` |
@@ -0,0 +1,86 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" role="img" aria-label="A reading workbench: books on a shelf, an annotated PDF page, and a side conversation">
2
+ <defs>
3
+ <filter id="soft" x="-20%" y="-20%" width="140%" height="140%">
4
+ <feDropShadow dx="0" dy="10" stdDeviation="14" flood-color="#12202b" flood-opacity=".12"/>
5
+ </filter>
6
+ <linearGradient id="cover" x1="0" y1="0" x2="1" y2="1">
7
+ <stop offset="0" stop-color="#12202b"/>
8
+ <stop offset="1" stop-color="#2a4a5e"/>
9
+ </linearGradient>
10
+ <linearGradient id="blue" x1="0" y1="0" x2="0" y2="1">
11
+ <stop offset="0" stop-color="#5b8cff"/>
12
+ <stop offset="1" stop-color="#2f6df6"/>
13
+ </linearGradient>
14
+ </defs>
15
+
16
+ <rect x="0" y="0" width="640" height="300" rx="18" fill="#f6f8fa"/>
17
+
18
+ <!-- shelf / books -->
19
+ <g filter="url(#soft)">
20
+ <rect x="42" y="66" width="86" height="150" rx="7" fill="#ffffff" stroke="#dbe3e9"/>
21
+ <rect x="53" y="78" width="64" height="88" rx="4" fill="url(#cover)"/>
22
+ <path d="M62 96h46M62 106h34" stroke="#8fa9b9" stroke-width="3" stroke-linecap="round" opacity=".8"/>
23
+ <circle cx="85" cy="132" r="13" fill="none" stroke="#5b8cff" stroke-width="2" opacity=".8"/>
24
+ <rect x="59" y="180" width="52" height="5" rx="2.5" fill="#cfd9e1"/>
25
+ <rect x="59" y="191" width="34" height="5" rx="2.5" fill="#e2e8ed"/>
26
+
27
+ <rect x="142" y="86" width="86" height="130" rx="7" fill="#ffffff" stroke="#dbe3e9"/>
28
+ <rect x="153" y="98" width="64" height="78" rx="4" fill="#eef3f7" stroke="#d7e0e7"/>
29
+ <path d="M166 118h38M166 127h26" stroke="#aab8c3" stroke-width="3" stroke-linecap="round"/>
30
+ <path d="M166 148c8-14 14-16 18-8 4 7 8 8 14 1" fill="none" stroke="#2f6df6" stroke-width="2.4" stroke-linecap="round"/>
31
+ <rect x="159" y="192" width="52" height="5" rx="2.5" fill="#cfd9e1"/>
32
+ <rect x="159" y="203" width="30" height="5" rx="2.5" fill="#e2e8ed"/>
33
+ </g>
34
+
35
+ <!-- page -->
36
+ <g filter="url(#soft)">
37
+ <rect x="258" y="38" width="200" height="222" rx="10" fill="#ffffff" stroke="#dfe6ec"/>
38
+ <rect x="274" y="56" width="168" height="6" rx="3" fill="#c9d4dd"/>
39
+ <rect x="274" y="72" width="120" height="6" rx="3" fill="#e2e8ee"/>
40
+ <rect x="274" y="94" width="150" height="5" rx="2.5" fill="#dde5eb"/>
41
+ <rect x="274" y="106" width="160" height="5" rx="2.5" fill="#dde5eb"/>
42
+ <rect x="274" y="118" width="132" height="5" rx="2.5" fill="#dde5eb"/>
43
+ <rect x="274" y="136" width="156" height="5" rx="2.5" fill="#dde5eb"/>
44
+ <rect x="274" y="148" width="144" height="5" rx="2.5" fill="#dde5eb"/>
45
+
46
+ <!-- ink mark -->
47
+ <path d="M286 196c12-22 24-27 32-16 7 9 12 11 20 2 8-9 16-3 19 8 2 8 10 9 18 3" fill="none" stroke="#2f6df6" stroke-width="3.2" stroke-linecap="round"/>
48
+ <path d="M296 218c18-2 38-2 56 0" fill="none" stroke="#12202b" stroke-width="2.4" stroke-linecap="round" opacity=".55"/>
49
+
50
+ <!-- selection box -->
51
+ <rect x="316" y="174" width="88" height="54" rx="4" fill="#2f6df6" fill-opacity=".05" stroke="#2f6df6" stroke-width="1.4" stroke-dasharray="5 4"/>
52
+
53
+ <!-- corner plus handles -->
54
+ <g fill="#ffffff" stroke="#2f6df6" stroke-width="1.3">
55
+ <rect x="352" y="28" width="12" height="12" rx="2"/>
56
+ <rect x="352" y="258" width="12" height="12" rx="2"/>
57
+ <rect x="248" y="143" width="12" height="12" rx="2"/>
58
+ <rect x="456" y="143" width="12" height="12" rx="2"/>
59
+ </g>
60
+ <g stroke="#2f6df6" stroke-width="1.5" stroke-linecap="round">
61
+ <path d="M358 31v6M355 34h6M358 261v6M355 264h6M251 146v6M248 149h6M459 146v6M456 149h6"/>
62
+ </g>
63
+ </g>
64
+
65
+ <!-- conversation -->
66
+ <g filter="url(#soft)">
67
+ <rect x="486" y="72" width="118" height="154" rx="12" fill="#ffffff" stroke="#dfe6ec"/>
68
+ <circle cx="508" cy="96" r="9" fill="#12202b"/>
69
+ <path d="M504.5 96l2.5 2.5 4.5-5" fill="none" stroke="#ffffff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
70
+ <rect x="524" y="91" width="52" height="6" rx="3" fill="#cfd9e1"/>
71
+ <rect x="502" y="116" width="84" height="5" rx="2.5" fill="#e1e8ee"/>
72
+ <rect x="502" y="128" width="70" height="5" rx="2.5" fill="#e1e8ee"/>
73
+ <rect x="502" y="140" width="78" height="5" rx="2.5" fill="#e1e8ee"/>
74
+
75
+ <rect x="502" y="164" width="72" height="42" rx="10" fill="#2f6df6" fill-opacity=".1" stroke="#2f6df6" stroke-opacity=".25"/>
76
+ <rect x="512" y="176" width="50" height="4" rx="2" fill="#2f6df6" opacity=".55"/>
77
+ <rect x="512" y="186" width="36" height="4" rx="2" fill="#2f6df6" opacity=".35"/>
78
+
79
+ <path d="M536 212c0 6-6 10-13 10l-9 6 2-9c-4-2-6-5-6-9 0-7 7-12 13-12s13 5 13 14z" fill="#12202b"/>
80
+ </g>
81
+
82
+ <!-- baseline accents -->
83
+ <path d="M42 266h556" stroke="#e1e7ec" stroke-width="1.5" stroke-linecap="round"/>
84
+ <circle cx="42" cy="266" r="3" fill="#2f6df6"/>
85
+ <circle cx="598" cy="266" r="3" fill="#cfd9e1"/>
86
+ </svg>
package/icon.svg CHANGED
@@ -1,6 +1,7 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" role="img" aria-label="Math workbench">
2
- <rect x="2.8" y="6.8" width="4" height="13.6" rx="0.9" fill="#2f6f8f"/>
3
- <rect x="9.8" y="3.8" width="4" height="16.6" rx="0.9" fill="#3f8aa6"/>
4
- <rect x="16.8" y="8.6" width="4" height="11.8" rx="0.9" fill="#2a5f78"/>
5
- <path d="M2.2 21.4h19.6" stroke="#1f4a5c" stroke-width="1.4" stroke-linecap="round"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" role="img" aria-label="PDF reading workbench">
2
+ <rect x="5" y="7" width="20" height="24" rx="2.5" fill="#12202b"/>
3
+ <rect x="9" y="4" width="22" height="26" rx="2.5" fill="#ffffff" stroke="#d5dde3" stroke-width="1.2"/>
4
+ <path d="M13 11h14M13 15h10" stroke="#9aa8b3" stroke-width="1.6" stroke-linecap="round"/>
5
+ <path d="M12.5 24.5c2.2-3.6 4.2-4.6 5.6-2.8 1.1 1.4 2 1.8 3.4.6 1.5-1.3 2.8-.6 3.5 1.1" fill="none" stroke="#2f6df6" stroke-width="2.2" stroke-linecap="round"/>
6
+ <path d="M8 31.5h20" stroke="#2f6df6" stroke-width="2" stroke-linecap="round"/>
6
7
  </svg>
package/index.js CHANGED
@@ -124,6 +124,12 @@ export function apply(ctx, rawConfig) {
124
124
  return connection.requestRejection(request)
125
125
  },
126
126
  md2texScript: join(dirname(fileURLToPath(import.meta.url)), 'tools', 'md2tex.py'),
127
+ // Session services the base-session route drives (stage 7.6).
128
+ sessionServices: () => ({
129
+ agents: ctx.get('agents'),
130
+ query: ctx.get('sessionQuery'),
131
+ workspace: ctx.get('workspaceRegistry'),
132
+ }),
127
133
  pending,
128
134
  links,
129
135
  libraries,
@@ -181,6 +187,8 @@ export function apply(ctx, rawConfig) {
181
187
 
182
188
  ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: PREFIX, handler }), 'pdfdesk: routes')
183
189
 
190
+
191
+
184
192
  // The first turn names a created session; every finished turn records how full
185
193
  // its context is, so "New" can decide between continuing and starting over.
186
194
  ctx.effect(() => ctx.on('session/event', (session, event) => {
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "PDF reading · ask as you read",
4
- "description": "A PDF reading workbench: libraries and shelves, chapter-by-chapter reading, ask-as-you-read conversations (extract / Q&A / exercises), ink and box annotations, bilingual view, and a built-in pdf.js reader, plus shelf groups, a recycle bin, and whole-book PDFs.",
4
+ "description": "A workbench for close reading of full-page PDFs, opened from the “PDF reading” sidebar entry. Libraries and shelves are organised as book → chapter; the reader supports single/continuous pages, ink and marquee annotations, an off-page canvas, bilingual view and translation overlays. Each chapter can start extract, Q&A and exercise conversations, and also carries attachments, printing and machine-to-machine migration. Libraries and notes stay on this machine; PDFs are never pushed into model context automatically. Translation needs Python + a DeepSeek API key; PPT-to-PDF optionally uses local Office or LibreOffice.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "PDF 阅读 · 随时问答",
4
- "description": "面向 PDF 阅读的工作台:书库与书架、按章阅读、随时问答(提取 / 答疑 / 习题)、笔迹与框选标注、双语对照、内置 pdf.js 阅读器,并支持书架分组、回收站与整本 PDF。",
4
+ "description": "面向整页 PDF 精读的工作台,从左侧栏「PDF 阅读」进入。书库与书架按「书 → 章」组织;阅读器支持单页/连续、手写与框选批注、页外画布、双语对照和覆盖层;每章可直接提取、答疑、习题,并带附件、打印与整机数据迁移。所有书库与笔记保存在本机,PDF 不会自动进入模型上下文;翻译需要 Python + DeepSeek API Key,PPT 转 PDF 可选本机 Office/LibreOffice。",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pdf-workbench",
3
- "version": "1.3.4",
3
+ "version": "1.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "PDF reading workbench for DSH: books and chapters, ask-as-you-read conversations, annotations, and a built-in pdf.js reader.",
package/screenshots.json CHANGED
@@ -4,5 +4,10 @@
4
4
  "assets/screenshot-reader.jpg",
5
5
  "assets/screenshot-bilingual.jpg",
6
6
  "assets/screenshot-overlay.jpg",
7
- "assets/screenshot-qa.jpg"
7
+ "assets/screenshot-qa.jpg",
8
+ "assets/screenshot-settings-reading.jpg",
9
+ "assets/screenshot-settings-data.jpg",
10
+ "assets/screenshot-attachments.jpg",
11
+ "assets/screenshot-canvas.jpg",
12
+ "assets/screenshot-questions.jpg"
8
13
  ]
@@ -43,19 +43,46 @@ const TEXT_EXTENSIONS = new Set([
43
43
  /** Extensions shown as an image badge; the reader does not draw them yet. */
44
44
  const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'avif'])
45
45
 
46
+ /** Word documents: listed, but previewed by DSH/Office rather than in this plugin. */
47
+ const OFFICE_EXTENSIONS = new Set(['doc', 'docx'])
48
+
49
+ /**
50
+ * Products the workbench lists. This is a whitelist on purpose: a chapter
51
+ * directory also holds build intermediates (`tex`, `aox`/`aux`/`log`/`out`/
52
+ * `bbl`/`blg`/`synctex` …), spreadsheets, slides and scratch files. None of
53
+ * them are reading material here, and an extension nobody thought of must not
54
+ * leak into the list. The files stay on disk untouched; only the listing
55
+ * ignores them.
56
+ */
57
+ const VISIBLE_EXTENSIONS = new Set([
58
+ 'pdf', 'md', 'markdown', 'doc', 'docx',
59
+ 'png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'avif',
60
+ ])
61
+
62
+ /**
63
+ * Whether one produced file belongs in the list.
64
+ * @param {string} name - file name.
65
+ * @returns {boolean} true when the row should be shown.
66
+ */
67
+ function visibleName(name) {
68
+ const extension = extname(name).replace(/^\./, '').toLowerCase()
69
+ return VISIBLE_EXTENSIONS.has(extension)
70
+ }
71
+
46
72
  /** Decoders tried in order for a preview; UTF-8 first, then the common Chinese Windows code page. */
47
73
  const DECODERS = ['utf-8', 'gb18030']
48
74
 
49
75
  /**
50
76
  * The kind shown as a badge and used to decide whether the reader can draw it.
51
77
  * @param {string} name - file name.
52
- * @returns {'pdf' | 'text' | 'image' | 'other'} the kind.
78
+ * @returns {'pdf' | 'text' | 'image' | 'office' | 'other'} the kind.
53
79
  */
54
80
  export function kindOf(name) {
55
81
  const extension = extname(name).replace(/^\./, '').toLowerCase()
56
82
  if (extension === 'pdf') return 'pdf'
57
83
  if (TEXT_EXTENSIONS.has(extension)) return 'text'
58
84
  if (IMAGE_EXTENSIONS.has(extension)) return 'image'
85
+ if (OFFICE_EXTENSIONS.has(extension)) return 'office'
59
86
  return 'other'
60
87
  }
61
88
 
@@ -202,8 +229,9 @@ async function readingNames(dir) {
202
229
  return entries
203
230
  .filter(entry => entry.isFile() || entry.isSymbolicLink())
204
231
  .map(entry => entry.name)
205
- // Office lock files and editor droppings are noise in a reading list.
206
- .filter(name => !name.startsWith('.') && !name.startsWith('~$'))
232
+ // Office lock files and editor droppings are noise in a reading list; TeX
233
+ // sources, spreadsheets and slides are not reading material for this plugin.
234
+ .filter(name => !name.startsWith('.') && !name.startsWith('~$') && visibleName(name))
207
235
  .sort((left, right) => left.localeCompare(right, 'zh'))
208
236
  }
209
237
 
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Chapter attachments: user-supplied files kept beside the chapter, outside the
3
+ * PDF reader. A first version accepts PDFs and images; the manifest records what
4
+ * was copied so the browser can list it without rescanning metadata.
5
+ * @module dsh-pdf-workbench/attachments
6
+ */
7
+
8
+ import { copyFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
9
+ import { basename, extname, join } from 'node:path'
10
+
11
+ /** Extensions the first version accepts, with the kind shown in the UI. */
12
+ export const ATTACHMENT_KINDS = {
13
+ pdf: 'pdf',
14
+ png: 'image',
15
+ jpg: 'image',
16
+ jpeg: 'image',
17
+ webp: 'image',
18
+ gif: 'image',
19
+ bmp: 'image',
20
+ avif: 'image',
21
+ }
22
+
23
+ /** Per-file ceiling for a copied attachment. */
24
+ export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024
25
+
26
+ /**
27
+ * Where one chapter's attachments live.
28
+ * @param {string} libraryDir - the library root.
29
+ * @param {string} book - book id.
30
+ * @param {string} code - chapter code.
31
+ * @returns {string} the absolute directory.
32
+ */
33
+ export function attachmentsDir(libraryDir, book, code) {
34
+ return join(libraryDir, '.pdfdesk', 'attachments', book, code)
35
+ }
36
+
37
+ /**
38
+ * The manifest beside the files.
39
+ * @param {string} libraryDir - the library root.
40
+ * @param {string} book - book id.
41
+ * @param {string} code - chapter code.
42
+ * @returns {string} the manifest path.
43
+ */
44
+ export function attachmentManifestPath(libraryDir, book, code) {
45
+ return join(attachmentsDir(libraryDir, book, code), 'manifest.json')
46
+ }
47
+
48
+ /**
49
+ * Strip directories and characters Windows or the browser would misread.
50
+ * @param {string} value - proposed file name.
51
+ * @returns {string} a safe base name (never empty).
52
+ */
53
+ export function safeAttachmentName(value) {
54
+ const base = basename(String(value ?? '')).replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim()
55
+ return base === '' || base === '.' || base === '..' ? 'attachment' : base.slice(0, 120)
56
+ }
57
+
58
+ /**
59
+ * Read the manifest, tolerating a missing or broken file.
60
+ * @param {string} dir - the chapter's attachment directory.
61
+ * @returns {Promise<{ version: number, items: object[] }>} parsed manifest.
62
+ */
63
+ async function readManifest(dir) {
64
+ const raw = await readFile(join(dir, 'manifest.json'), 'utf8').catch(() => null)
65
+ if (raw === null) return { version: 1, items: [] }
66
+ try {
67
+ const parsed = JSON.parse(raw)
68
+ const items = Array.isArray(parsed.items) ? parsed.items.filter(item => item !== null && typeof item === 'object' && typeof item.name === 'string') : []
69
+ return { version: 1, items }
70
+ } catch {
71
+ return { version: 1, items: [] }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Write the manifest atomically.
77
+ * @param {string} dir - the chapter's attachment directory.
78
+ * @param {{ version: number, items: object[] }} manifest - the value.
79
+ * @returns {Promise<void>} completion.
80
+ */
81
+ async function writeManifest(dir, manifest) {
82
+ const path = join(dir, 'manifest.json')
83
+ const temporary = `${path}.${process.pid}.tmp`
84
+ await writeFile(temporary, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
85
+ await copyFile(temporary, path)
86
+ await unlink(temporary).catch(() => {})
87
+ }
88
+
89
+ /**
90
+ * List one chapter's attachments, including files the manifest does not know
91
+ * about yet (a copy interrupted before the manifest write).
92
+ * @param {string} libraryDir - the library root.
93
+ * @param {string} book - book id.
94
+ * @param {string} code - chapter code.
95
+ * @returns {Promise<{ dir: string, items: object[] }>} the manifest items.
96
+ */
97
+ export async function listAttachments(libraryDir, book, code) {
98
+ const dir = attachmentsDir(libraryDir, book, code)
99
+ const manifest = await readManifest(dir)
100
+ const known = new Set(manifest.items.map(item => item.name))
101
+ const names = await readdir(dir).catch(() => [])
102
+ const extra = []
103
+ for (const name of names) {
104
+ if (name === 'manifest.json' || known.has(name)) continue
105
+ const info = await stat(join(dir, name)).catch(() => null)
106
+ if (info === null || !info.isFile()) continue
107
+ const extension = extname(name).slice(1).toLowerCase()
108
+ if (ATTACHMENT_KINDS[extension] === undefined) continue
109
+ extra.push({ name, kind: ATTACHMENT_KINDS[extension], bytes: info.size, addedAt: info.mtimeMs })
110
+ }
111
+ return { dir, items: [...manifest.items, ...extra] }
112
+ }
113
+
114
+ /**
115
+ * Copy one local file into the chapter's attachments.
116
+ * @param {{ libraryDir: string, book: string, code: string, sourcePath: string, name?: string }} options - the library, chapter and source.
117
+ * @returns {Promise<{ name: string, kind: string, bytes: number, addedAt: number }>} the stored item.
118
+ */
119
+ export async function addAttachment(options) {
120
+ const extension = extname(String(options.sourcePath ?? '')).slice(1).toLowerCase()
121
+ const kind = ATTACHMENT_KINDS[extension]
122
+ if (kind === undefined) throw Object.assign(new Error('只支持 PDF 与图片附件'), { code: 'bad-type' })
123
+ const info = await stat(options.sourcePath)
124
+ if (!info.isFile()) throw Object.assign(new Error('附件必须是文件'), { code: 'not-file' })
125
+ if (info.size > MAX_ATTACHMENT_BYTES) throw Object.assign(new Error('附件超过 50 MB'), { code: 'too-large' })
126
+ const dir = attachmentsDir(options.libraryDir, options.book, options.code)
127
+ await mkdir(dir, { recursive: true })
128
+ const manifest = await readManifest(dir)
129
+ const wanted = safeAttachmentName(options.name ?? options.sourcePath)
130
+ const stem = wanted.slice(0, Math.max(1, wanted.length - extension.length - 1))
131
+ let name = wanted
132
+ let counter = 0
133
+ const taken = new Set([...manifest.items.map(item => item.name), 'manifest.json'])
134
+ while (taken.has(name)) {
135
+ counter += 1
136
+ name = `${stem}-${counter}.${extension}`
137
+ }
138
+ await copyFile(options.sourcePath, join(dir, name))
139
+ const item = { name, kind, bytes: info.size, addedAt: Date.now() }
140
+ manifest.items.push(item)
141
+ await writeManifest(dir, manifest)
142
+ return item
143
+ }
144
+
145
+ /**
146
+ * Delete one attachment and drop it from the manifest.
147
+ * @param {{ libraryDir: string, book: string, code: string, name: string }} options - the library, chapter and file.
148
+ * @returns {Promise<{ removed: boolean }>} whether a file was deleted.
149
+ */
150
+ export async function removeAttachment(options) {
151
+ const dir = attachmentsDir(options.libraryDir, options.book, options.code)
152
+ const name = safeAttachmentName(options.name)
153
+ const manifest = await readManifest(dir)
154
+ const index = manifest.items.findIndex(item => item.name === name)
155
+ if (index >= 0) manifest.items.splice(index, 1)
156
+ const result = await unlink(join(dir, name)).then(() => true).catch(() => false)
157
+ if (index >= 0 || result) await writeManifest(dir, manifest)
158
+ return { removed: result || index >= 0 }
159
+ }