dsh-half-page 0.3.35 → 0.3.37

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/README.md CHANGED
@@ -40,6 +40,7 @@ dsh plugin add dsh-half-page
40
40
  ~/.dsh/reading/
41
41
  ├── books/ 书(.txt / .md)
42
42
  │ └── .trash/ 下架的书挪到这儿,可手工找回
43
+ ├── books/<id>.toc.json 章表:每章的字符偏移 + 字节偏移
43
44
  ├── 读后感.md 所有读后感,按 ## 书名 / ### 章名 分块
44
45
  ├── 作品/ 它自己写的东西
45
46
  └── state.json 读到哪了
@@ -53,10 +54,26 @@ dsh plugin add dsh-half-page
53
54
  |---|---|
54
55
  | `reading_shelf` | 书架与进度 |
55
56
  | `reading_next` | 打开下一章(或指定章) |
57
+ | `reading_mark` | 只记进度、不返回正文:已读到第 N 章(自己切文件读完整章时用它补记) |
56
58
  | `reading_note` | 给这章写一两句读后感,可带 `by` |
57
59
  | `reading_search` | 在书里搜词,返回第几章、哪一行 |
58
60
  | `reading_recap` | 已读部分压成一页 |
59
61
 
62
+ ## 章表(读一章不整本 decode)
63
+
64
+ 第一次打开某本书时扫一遍,把每章的位置换算成字节偏移,落成 `books/<id>.toc.json`:
65
+
66
+ ```json
67
+ { "version": 1, "encoding": "gb18030", "bytes": 9638898, "chars": 3123456,
68
+ "chapters": [{ "title": "第一章 小二上酒", "charStart": 0, "charEnd": 3201, "byteStart": 0, "byteEnd": 6430 }] }
69
+ ```
70
+
71
+ 以后 `reading_next` 只 `fs.open` + 读 `byteStart..byteEnd` 那一段,再单独解这一段的编码——14MB 的书读一章不再把整本读进内存。
72
+
73
+ - 章表过期(文件 mtime 或字节数变了)会自动重建;删掉也能自动重建。
74
+ - `reading_next` 的返回里带 `tocPath`,能看到表在哪。
75
+ - `reading_search` 还是要整本,它是搜全文的。
76
+
60
77
  ## License
61
78
 
62
79
  MIT
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // dsh-half-page · 半页(自己的读书与写字)
2
2
  // 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
3
- import { readFile, writeFile, mkdir, readdir, stat, rename } from 'node:fs/promises'
3
+ import { readFile, writeFile, mkdir, readdir, stat, rename, open } from 'node:fs/promises'
4
4
  import { readFileSync } from 'node:fs'
5
5
  import { join, basename, dirname, extname, resolve } from 'node:path'
6
6
  import { homedir } from 'node:os'
@@ -104,6 +104,159 @@ export function chapterText(text, chapters, n) {
104
104
  return text.slice(c.start, c.end).trim()
105
105
  }
106
106
 
107
+ /* ------------------------------------------------------------------ 章表
108
+ * 读一章不再整本 decode:第一次打开某本书时扫一遍,把每章的字符偏移换算成
109
+ * 字节偏移,落盘成 books/<id>.toc.json;以后按 byteStart..byteEnd 只读这一段。
110
+ */
111
+
112
+ const TOC_VERSION = 1
113
+
114
+ export function tocPath(dir, id) {
115
+ return join(dir, 'books', id + '.toc.json')
116
+ }
117
+
118
+ async function bookFile(dir, id) {
119
+ for (const ext of ['.txt', '.md']) {
120
+ const p = join(dir, 'books', id + ext)
121
+ try {
122
+ const st = await stat(p)
123
+ return { path: p, size: st.size, mtimeMs: st.mtimeMs }
124
+ } catch {}
125
+ }
126
+ throw new Error(`没有这本书:${id}`)
127
+ }
128
+
129
+ function utf8Width(cp) {
130
+ return cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
131
+ }
132
+
133
+ /** GB18030 的字节宽度:ASCII 1;0x81–0xFE + 0x30–0x39 是四字节;其余两字节 */
134
+ function gbWidth(buf, i) {
135
+ const b = buf[i]
136
+ if (b < 0x80) return 1
137
+ if (b >= 0x81 && b <= 0xfe && i + 1 < buf.length && buf[i + 1] >= 0x30 && buf[i + 1] <= 0x39) return 4
138
+ return 2
139
+ }
140
+
141
+ /** 认编码(顺带认出 BOM 长度) */
142
+ export function sniffEncoding(buf) {
143
+ try {
144
+ new TextDecoder('utf-8', { fatal: true }).decode(buf)
145
+ const bom = buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0
146
+ return { encoding: 'utf-8', bom }
147
+ } catch {
148
+ return { encoding: 'gb18030', bom: 0 }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * 扫一遍整本,产出章表。字符偏移 → 字节偏移走一遍累加,不建大数组。
154
+ * 返回 null 表示宽度累加对不上(文件坏了或怪编码),调用方退回整本方案。
155
+ */
156
+ export function buildToc(buffer, id) {
157
+ const { encoding, bom } = sniffEncoding(buffer)
158
+ const body = bom ? buffer.subarray(bom) : buffer
159
+ const text = stripBom(new TextDecoder(encoding).decode(body))
160
+ const chapters = splitChapters(text)
161
+ const starts = chapters.map((c) => c.start)
162
+ let ci = 0
163
+ let bi = bom
164
+ let k = 0
165
+ for (const ch of text) {
166
+ while (k < chapters.length && starts[k] === ci) {
167
+ chapters[k].byteStart = bi
168
+ k += 1
169
+ }
170
+ const cp = ch.codePointAt(0)
171
+ bi += encoding === 'utf-8' ? utf8Width(cp) : gbWidth(body, bi)
172
+ ci += ch.length
173
+ }
174
+ while (k < chapters.length) {
175
+ chapters[k].byteStart = bi
176
+ k += 1
177
+ }
178
+ for (let i = 0; i < chapters.length; i += 1) {
179
+ chapters[i].byteEnd = i + 1 < chapters.length ? chapters[i + 1].byteStart : buffer.length
180
+ }
181
+ if (bi !== buffer.length) return null
182
+ return {
183
+ version: TOC_VERSION,
184
+ id,
185
+ encoding,
186
+ bom,
187
+ bytes: buffer.length,
188
+ chars: text.length,
189
+ chapters,
190
+ }
191
+ }
192
+
193
+ /** 取章表:有且没过期就用,否则整本扫一次并重写 */
194
+ export async function tocFor(dir, id, opts = {}) {
195
+ const file = await bookFile(dir, id)
196
+ const tp = tocPath(dir, id)
197
+ if (!opts.force) {
198
+ try {
199
+ const saved = JSON.parse(stripBom(await readFile(tp, 'utf8')))
200
+ const fresh = saved
201
+ && saved.version === TOC_VERSION
202
+ && saved.bytes === file.size
203
+ && Number(saved.mtimeMs) === Math.round(file.mtimeMs)
204
+ && Array.isArray(saved.chapters)
205
+ && saved.chapters.length > 0
206
+ && saved.chapters.every((c) => Number.isInteger(c.byteStart) && Number.isInteger(c.byteEnd))
207
+ if (fresh) return { ...saved, file: file.path, tocPath: tp }
208
+ } catch {}
209
+ }
210
+ const buffer = await readFile(file.path)
211
+ const built = buildToc(buffer, id)
212
+ if (!built) return null
213
+ const rec = { ...built, file: basename(file.path), mtimeMs: Math.round(file.mtimeMs) }
214
+ await writeJson(tp, rec)
215
+ return { ...rec, file: file.path, tocPath: tp }
216
+ }
217
+
218
+ /** 只按偏移读那一章,不碰整本 */
219
+ export async function readChapterByOffset(dir, id, n) {
220
+ const toc = await tocFor(dir, id)
221
+ if (!toc) return null
222
+ const c = toc.chapters[n - 1]
223
+ if (!c) return { text: '', chapter: null, toc }
224
+ const len = c.byteEnd - c.byteStart
225
+ const buf = Buffer.alloc(len)
226
+ let off = 0
227
+ const fh = await open(toc.file, 'r')
228
+ try {
229
+ while (off < len) {
230
+ const { bytesRead } = await fh.read(buf, off, len - off, c.byteStart + off)
231
+ if (!bytesRead) break
232
+ off += bytesRead
233
+ }
234
+ } finally {
235
+ await fh.close()
236
+ }
237
+ const text = stripBom(new TextDecoder(toc.encoding).decode(buf.subarray(0, off)))
238
+ return { text: text.trim(), chapter: c, toc, tocPath: toc.tocPath }
239
+ }
240
+
241
+ /** 一章正文:先走章表,实在没有才退回整本切 */
242
+ export async function chapterBody(dir, id, info, n) {
243
+ try {
244
+ const got = await readChapterByOffset(dir, id, n)
245
+ if (got) return got.text
246
+ } catch {}
247
+ if (typeof info?.text === 'string') return chapterText(info.text, info.chapters, n)
248
+ const file = await bookFile(dir, id)
249
+ const text = await readTextSmart(await readFile(file.path))
250
+ return chapterText(text, splitChapters(text), n)
251
+ }
252
+
253
+ /** 搜东西这种确实要整本的,才整本读 */
254
+ export async function fullTextOf(dir, id) {
255
+ const file = await bookFile(dir, id)
256
+ const text = await readTextSmart(await readFile(file.path))
257
+ return { text, chapters: splitChapters(text) }
258
+ }
259
+
107
260
  /** 书库:books/*.txt */
108
261
  export async function listBooks(dir) {
109
262
  const out = []
@@ -119,18 +272,34 @@ export async function listBooks(dir) {
119
272
  return out
120
273
  }
121
274
 
122
- /** 打开某本书并缓存它有多少章 */
275
+ /** 只读章表,不存在就返回 null(不触发建表) */
276
+ async function readTocOnly(dir, id) {
277
+ const t = await readJson(tocPath(dir, id), null)
278
+ return t && t.version === TOC_VERSION && Array.isArray(t.chapters) ? t : null
279
+ }
280
+
281
+ /** 书名匹配:先精确 id,再书名精确,再片段(唯一命中才算认出) */
282
+ export function resolveBookId(st, shelf, query) {
283
+ const key = String(query || '').trim()
284
+ if (!key) throw new Error('没有这本书:')
285
+ const ids = shelf.map((b) => b.id)
286
+ if (ids.includes(key)) return key
287
+ const books = st.books || {}
288
+ const exact = ids.filter((id) => (books[id]?.title || id) === key)
289
+ if (exact.length === 1) return exact[0]
290
+ const hits = ids.filter((id) => id.includes(key) || String(books[id]?.title || '').includes(key))
291
+ if (hits.length === 1) return hits[0]
292
+ if (hits.length > 1) throw new Error(`书名不唯一:${key}(可能是 ${hits.join(' / ')})`)
293
+ throw new Error(`没有这本书:${key}`)
294
+ }
295
+
296
+ /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
123
297
  export async function bookInfo(dir, id) {
124
- const p = join(dir, 'books', id + '.txt')
125
- let text
126
- try {
127
- text = await readTextSmart(await readFile(p))
128
- } catch {
129
- const p2 = join(dir, 'books', id + '.md')
130
- text = await readTextSmart(await readFile(p2))
131
- }
132
- const chapters = splitChapters(text)
133
- return { text, chapters }
298
+ const toc = await tocFor(dir, id)
299
+ if (toc) return { chapters: toc.chapters, toc, tocPath: toc.tocPath, text: null }
300
+ const file = await bookFile(dir, id)
301
+ const text = await readTextSmart(await readFile(file.path))
302
+ return { text, chapters: splitChapters(text), toc: null, tocPath: '' }
134
303
  }
135
304
 
136
305
  export async function importBook(dir, srcPath) {
@@ -318,7 +487,7 @@ export function apply(ctx) {
318
487
  const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
319
488
  res.end(JSON.stringify({
320
489
  ok: true, book: id, chapter: ch, total: info.chapters.length,
321
- title: info.chapters[ch - 1]?.title || '', text: chapterText(info.text, info.chapters, ch),
490
+ title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
322
491
  }))
323
492
  } catch (e) {
324
493
  res.end(JSON.stringify({ ok: false, error: String(e && e.message || e) }))
@@ -891,7 +1060,7 @@ async function signWork(rel, who) {
891
1060
  rec.chapters = info.chapters.length
892
1061
  const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
893
1062
  if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
894
- const body = chapterText(info.text, info.chapters, n)
1063
+ const body = await chapterBody(dir, id, info, n)
895
1064
  rec.readThrough = Math.max(rec.readThrough || 0, n)
896
1065
  rec.next = Math.min(info.chapters.length, n + 1)
897
1066
  rec.lastReadAt = new Date().toISOString()
@@ -906,6 +1075,7 @@ async function signWork(rel, who) {
906
1075
  chapter: n,
907
1076
  title: info.chapters[n - 1].title,
908
1077
  chapters: info.chapters.length,
1078
+ tocPath: info.tocPath || '',
909
1079
  chars: body.length,
910
1080
  next: rec.next,
911
1081
  perDay,
@@ -917,6 +1087,47 @@ async function signWork(rel, who) {
917
1087
  }),
918
1088
  )
919
1089
 
1090
+ ctx.effect(() =>
1091
+ ctx.tools.register({
1092
+ name: 'reading_mark',
1093
+ description:
1094
+ '只记进度、不返回正文:把某本书记成「已读到第 N 章」。'
1095
+ + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1096
+ + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1097
+ parameters: obj({
1098
+ book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
1099
+ chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1100
+ todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1101
+ }),
1102
+ output: textOut,
1103
+ async execute(args) {
1104
+ const { dir, st, shelf } = await stateOf()
1105
+ const id = resolveBookId(st, shelf, args?.book)
1106
+ // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1107
+ const toc = await readTocOnly(dir, id)
1108
+ const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
1109
+ const n = Math.floor(Number(args?.chapter))
1110
+ if (!(n >= 1)) throw new Error('章号要从 1 开始')
1111
+ if (chapters && n > chapters) throw new Error(`章号超出范围:1–${chapters}`)
1112
+ const incRaw = Math.floor(Number(args?.todayCount))
1113
+ const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1114
+ const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1115
+ const before = Number(rec.readThrough) || 0
1116
+ if (chapters) rec.chapters = chapters
1117
+ rec.readThrough = Math.max(before, n)
1118
+ rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1119
+ rec.lastReadAt = new Date().toISOString()
1120
+ st.current = id
1121
+ const t = today()
1122
+ st.log = st.log || {}
1123
+ st.log[t] = st.log[t] || {}
1124
+ st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
1125
+ await saveState(dir, st)
1126
+ return `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${st.log[t][id] || 0}`
1127
+ },
1128
+ }),
1129
+ )
1130
+
920
1131
  ctx.effect(() =>
921
1132
  ctx.tools.register({
922
1133
  name: 'reading_note',
@@ -997,7 +1208,7 @@ async function signWork(rel, who) {
997
1208
  const { dir, st } = await stateOf()
998
1209
  const id = args?.book || st.current
999
1210
  if (!id) throw new Error('还没有正在读的书')
1000
- const { text, chapters } = await bookInfo(dir, id)
1211
+ const { text, chapters } = await fullTextOf(dir, id)
1001
1212
  const hits = []
1002
1213
  let at = text.indexOf(q)
1003
1214
  while (at >= 0 && hits.length < limit) {
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "半页",
4
+ "description": "一间会自己读书的书房:一章一章地读,把读到哪儿记下来;读完想说什么,就写在那一章的边上;想写点自己的东西,也放在这儿。打开面板就能看见它今天翻了几页、这次写下了什么。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-half-page",
3
- "version": "0.3.35",
3
+ "version": "0.3.37",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",
@@ -45,4 +45,4 @@
45
45
  "engines": {
46
46
  "dsh": ">=0.2.1-rc.0 <0.3.0-0"
47
47
  }
48
- }
48
+ }