dsh-half-page 0.3.34 → 0.3.36

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/index.js CHANGED
@@ -1,9 +1,10 @@
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'
7
+ import { fileURLToPath } from 'node:url'
7
8
 
8
9
  export const inject = ['webServer', 'tools', 'systemPrompt']
9
10
 
@@ -41,7 +42,18 @@ export async function config() {
41
42
  }
42
43
 
43
44
  export async function ensureDir(dir) {
44
- await mkdir(join(dir, 'books'), { recursive: true })
45
+ const books = join(dir, 'books')
46
+ await mkdir(books, { recursive: true })
47
+ // 第一次装:书架是空的,就放一本自带的书进去(《古文观止》,公版,121 篇选)。
48
+ // 只在空书架时放一次,删掉之后不会再回来。
49
+ try {
50
+ const have = (await readdir(books)).filter((f) => /\.(txt|md)$/i.test(f))
51
+ if (!have.length) {
52
+ const src = join(dirname(fileURLToPath(import.meta.url)), 'books', '古文观止.txt')
53
+ const buf = await readFile(src)
54
+ await writeFile(join(books, '古文观止.txt'), buf)
55
+ }
56
+ } catch {}
45
57
  return dir
46
58
  }
47
59
 
@@ -92,6 +104,159 @@ export function chapterText(text, chapters, n) {
92
104
  return text.slice(c.start, c.end).trim()
93
105
  }
94
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
+
95
260
  /** 书库:books/*.txt */
96
261
  export async function listBooks(dir) {
97
262
  const out = []
@@ -107,18 +272,13 @@ export async function listBooks(dir) {
107
272
  return out
108
273
  }
109
274
 
110
- /** 打开某本书并缓存它有多少章 */
275
+ /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
111
276
  export async function bookInfo(dir, id) {
112
- const p = join(dir, 'books', id + '.txt')
113
- let text
114
- try {
115
- text = await readTextSmart(await readFile(p))
116
- } catch {
117
- const p2 = join(dir, 'books', id + '.md')
118
- text = await readTextSmart(await readFile(p2))
119
- }
120
- const chapters = splitChapters(text)
121
- return { text, chapters }
277
+ const toc = await tocFor(dir, id)
278
+ if (toc) return { chapters: toc.chapters, toc, tocPath: toc.tocPath, text: null }
279
+ const file = await bookFile(dir, id)
280
+ const text = await readTextSmart(await readFile(file.path))
281
+ return { text, chapters: splitChapters(text), toc: null, tocPath: '' }
122
282
  }
123
283
 
124
284
  export async function importBook(dir, srcPath) {
@@ -306,7 +466,7 @@ export function apply(ctx) {
306
466
  const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
307
467
  res.end(JSON.stringify({
308
468
  ok: true, book: id, chapter: ch, total: info.chapters.length,
309
- title: info.chapters[ch - 1]?.title || '', text: chapterText(info.text, info.chapters, ch),
469
+ title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
310
470
  }))
311
471
  } catch (e) {
312
472
  res.end(JSON.stringify({ ok: false, error: String(e && e.message || e) }))
@@ -879,7 +1039,7 @@ async function signWork(rel, who) {
879
1039
  rec.chapters = info.chapters.length
880
1040
  const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
881
1041
  if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
882
- const body = chapterText(info.text, info.chapters, n)
1042
+ const body = await chapterBody(dir, id, info, n)
883
1043
  rec.readThrough = Math.max(rec.readThrough || 0, n)
884
1044
  rec.next = Math.min(info.chapters.length, n + 1)
885
1045
  rec.lastReadAt = new Date().toISOString()
@@ -894,6 +1054,7 @@ async function signWork(rel, who) {
894
1054
  chapter: n,
895
1055
  title: info.chapters[n - 1].title,
896
1056
  chapters: info.chapters.length,
1057
+ tocPath: info.tocPath || '',
897
1058
  chars: body.length,
898
1059
  next: rec.next,
899
1060
  perDay,
@@ -985,7 +1146,7 @@ async function signWork(rel, who) {
985
1146
  const { dir, st } = await stateOf()
986
1147
  const id = args?.book || st.current
987
1148
  if (!id) throw new Error('还没有正在读的书')
988
- const { text, chapters } = await bookInfo(dir, id)
1149
+ const { text, chapters } = await fullTextOf(dir, id)
989
1150
  const hits = []
990
1151
  let at = text.indexOf(q)
991
1152
  while (at >= 0 && hits.length < limit) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-half-page",
3
- "version": "0.3.34",
3
+ "version": "0.3.36",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",
@@ -19,6 +19,7 @@
19
19
  "locale/*.json",
20
20
  "icon.svg",
21
21
  "assets/*",
22
+ "books/*.txt",
22
23
  "screenshots.json"
23
24
  ],
24
25
  "dsh": {
@@ -44,4 +45,4 @@
44
45
  "engines": {
45
46
  "dsh": ">=0.2.1-rc.0 <0.3.0-0"
46
47
  }
47
- }
48
+ }