@gongfpp/dsh-novel-fish 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +41 -20
  3. package/docs/evidence/settings-reliability.png +0 -0
  4. package/index.json +12 -0
  5. package/lib/client.js +734 -128
  6. package/locale/en.json +15 -0
  7. package/locale/zh.json +15 -0
  8. package/package.json +5 -7
  9. package/screenshots.json +6 -0
  10. package/docs/acceptance.md +0 -42
  11. package/docs/community-markets.md +0 -88
  12. package/docs/compatibility-017.md +0 -70
  13. package/docs/compatibility-101.md +0 -41
  14. package/docs/continuous-reading-020.md +0 -46
  15. package/docs/ebook-tests.md +0 -99
  16. package/docs/evidence/abc-result.json +0 -9
  17. package/docs/evidence/banner-100.png +0 -0
  18. package/docs/evidence/community-market-014-result.json +0 -170
  19. package/docs/evidence/compatibility-017-result.json +0 -65
  20. package/docs/evidence/continuous-reading-020-result.json +0 -72
  21. package/docs/evidence/formats-result.json +0 -12
  22. package/docs/evidence/live-ab.png +0 -0
  23. package/docs/evidence/live-collapsed.png +0 -0
  24. package/docs/evidence/live-disabled.png +0 -0
  25. package/docs/evidence/live-epub.png +0 -0
  26. package/docs/evidence/live-market.png +0 -0
  27. package/docs/evidence/live-resume.png +0 -0
  28. package/docs/evidence/live-unloaded.png +0 -0
  29. package/docs/evidence/long-result.json +0 -11
  30. package/docs/evidence/multi-region-014-result.json +0 -47
  31. package/docs/evidence/native-disclosure-013-result.json +0 -36
  32. package/docs/evidence/native-disclosures-013.png +0 -0
  33. package/docs/evidence/native-open-013.png +0 -0
  34. package/docs/evidence/native-settings-sample.md +0 -11
  35. package/docs/evidence/native-settings-types-015.png +0 -0
  36. package/docs/evidence/npm-market-014-result.json +0 -132
  37. package/docs/evidence/plugin-settings-details.png +0 -0
  38. package/docs/evidence/public-release-014-result.json +0 -51
  39. package/docs/evidence/public-release-015-result.json +0 -36
  40. package/docs/evidence/public-release-result.json +0 -48
  41. package/docs/evidence/reading-demo-100.png +0 -0
  42. package/docs/evidence/reading-two-expansions-110.gif +0 -0
  43. package/docs/evidence/reading-two-expansions-110.json +0 -89
  44. package/docs/evidence/samples-110-capture.json +0 -49
  45. package/docs/evidence/settings-011-result.json +0 -28
  46. package/docs/evidence/settings-011.png +0 -0
  47. package/docs/evidence/settings-100.png +0 -0
  48. package/docs/evidence/settings-110.png +0 -0
  49. package/docs/evidence/settings-chat-011.png +0 -0
  50. package/docs/evidence/type-append-012-result.json +0 -30
  51. package/docs/evidence/type-append-012.png +0 -0
  52. package/docs/evidence/type-settings-012.png +0 -0
  53. package/docs/evidence/unload-result.json +0 -7
  54. package/docs/host-adapter.md +0 -43
  55. package/docs/icon-metadata-021.md +0 -40
  56. package/docs/interaction-paths-020.md +0 -39
  57. package/docs/marketplace.md +0 -42
  58. package/docs/multi-region-update.md +0 -53
  59. package/docs/native-disclosure-update.md +0 -39
  60. package/docs/native-settings-update.md +0 -48
  61. package/docs/plugin-settings-update.md +0 -61
  62. package/docs/release.md +0 -151
  63. package/docs/settings-update.md +0 -49
  64. package/docs/type-append-update.md +0 -50
  65. package/pnpm-workspace.yaml +0 -5
  66. package/scripts/build.mjs +0 -70
  67. package/scripts/check-host-contracts.mjs +0 -247
  68. package/scripts/licenses/path-webpack.txt +0 -28
  69. package/scripts/make-readme-gif.mjs +0 -69
  70. package/scripts/test-browser-samples.mjs +0 -665
  71. package/scripts/test-candidate-books.mjs +0 -71
  72. package/scripts/test-ebook-corpus.mjs +0 -161
  73. package/src/bundled-books.js +0 -42
  74. package/src/chat-adapter.js +0 -278
  75. package/src/client.js +0 -61
  76. package/src/epub.js +0 -166
  77. package/src/novel-content.js +0 -28
  78. package/src/persistence.js +0 -271
  79. package/src/pg-notice.js +0 -19
  80. package/src/segments.js +0 -185
  81. package/src/settings.js +0 -243
  82. package/src/store.js +0 -429
  83. package/src/text-decoding.js +0 -28
  84. package/test/bundled-library.test.js +0 -526
  85. package/test/chat-adapter.test.js +0 -518
  86. package/test/client.test.js +0 -124
  87. package/test/ebooks.test.js +0 -192
  88. package/test/epub.test.js +0 -185
  89. package/test/helpers/host-primitives.js +0 -28
  90. package/test/helpers/memory-storage.js +0 -48
  91. package/test/host-contracts.test.js +0 -32
  92. package/test/import.test.js +0 -102
  93. package/test/persistence.test.js +0 -27
  94. package/test/pg-notice.test.js +0 -109
  95. package/test/release.test.js +0 -87
  96. package/test/segments.test.js +0 -182
  97. package/test/settings.test.js +0 -312
  98. package/test/store.test.js +0 -617
  99. package/test/text-decoding.test.js +0 -49
@@ -1,71 +0,0 @@
1
- // Optional local-only probe. Restricted candidates are never bundled or downloaded here.
2
- // Usage: node scripts/test-candidate-books.mjs
3
- import assert from 'node:assert/strict'
4
- import { readFile, mkdir, writeFile } from 'node:fs/promises'
5
- import { createHash } from 'node:crypto'
6
- import { dirname, resolve } from 'node:path'
7
- import { fileURLToPath } from 'node:url'
8
- import { NovelStore } from '../src/store.js'
9
- import { MemoryStorage } from '../test/helpers/memory-storage.js'
10
- import { DEFAULT_SEGMENT_LENGTH, parseTextBook } from '../src/segments.js'
11
-
12
- const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
13
- const input = resolve(root, 'samples/ebooks-next')
14
- const manifest = JSON.parse(await readFile(resolve(input, 'sources.json'), 'utf8'))
15
- const storage = new MemoryStorage()
16
- const store = new NovelStore(storage)
17
- const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
18
- function units(text) {
19
- let total = 0
20
- for (const { segment } of graphemes.segment(text)) {
21
- total += segment === '\n' ? 40 : segment === '\t' ? 4
22
- : /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\p{Regional_Indicator}\u3000-\u303f\uff01-\uff60\uffe0-\uffe6]/u.test(segment) ? 2 : 1
23
- }
24
- return total
25
- }
26
- function distribution(values) {
27
- const sorted = [...values].sort((a, b) => a - b)
28
- const at = p => sorted[Math.floor((sorted.length - 1) * p)]
29
- return { min: sorted[0], median: at(0.5), p90: at(0.9), max: sorted.at(-1) }
30
- }
31
- const results = []
32
- try {
33
- await store.ready
34
- const original = await store.importFile({ name: 'existing.txt', arrayBuffer: async () => new TextEncoder().encode('保留原来的书与阅读进度。'.repeat(100)).buffer })
35
- await store.claimPassage('existing-before-candidates')
36
- const originalProgress = storage.books.get(original.id).progress
37
- const originalSegments = [...storage.passages.entries()]
38
- for (const source of manifest.books) {
39
- assert.equal(source.format, 'txt', 'this probe only covers the two acquired TXT candidates')
40
- const path = resolve(input, source.file)
41
- assert.ok(path.startsWith(input + '/'), 'manifest must not escape its candidate directory')
42
- const bytes = await readFile(path)
43
- assert.equal(bytes.length, source.bytes)
44
- assert.equal(createHash('sha256').update(bytes).digest('hex'), source.sha256)
45
- const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
46
- const parsed = parseTextBook(text)
47
- const normalizedBody = parsed.chapters.map(chapter => chapter.text).join('').replace(/\s/gu, '')
48
- assert.equal(parsed.segments.map(segment => segment.text).join('').replace(/\s/gu, ''), normalizedBody)
49
- const book = await store.importFile({ name: source.file, arrayBuffer: async () => Uint8Array.from(bytes).buffer })
50
- const segments = await Promise.all(Array.from({ length: book.segmentCount }, (_, index) => storage.getSegment(book.id, index)))
51
- assert.deepEqual(segments.map(segment => segment.text), parsed.segments.map(segment => segment.text))
52
- const widths = segments.map(segment => units(segment.text))
53
- assert.ok(widths.every(width => width <= Math.floor(DEFAULT_SEGMENT_LENGTH * 1.25)))
54
- assert.ok(segments.every(segment => !segment.text.includes('\uFFFD')))
55
- assert.equal(store.getSettingsSnapshot().currentBookId, original.id)
56
- assert.equal(storage.books.get(original.id).progress, originalProgress)
57
- for (const [key, segment] of originalSegments) assert.deepEqual(storage.passages.get(key), segment)
58
- results.push({ file: source.file, bytes: bytes.length, sha256: source.sha256,
59
- packaged: false, packageByDefault: source.redistribution?.packageByDefault ?? false, chapters: parsed.chapters.length,
60
- segments: segments.length, displayUnits: distribution(widths),
61
- characters: distribution(segments.map(segment => [...segment.text].length)),
62
- englishWords: distribution(segments.map(segment => (segment.text.match(/\b[A-Za-z]+\b/gu) ?? []).length)),
63
- below200DisplayUnits: widths.filter(width => width < 200).length,
64
- preservedBody: true, originalLibraryUnchanged: true })
65
- }
66
- const report = { scope: 'local candidate TXT import + MemoryStorage, not GUI, not redistribution clearance',
67
- softDisplayUnits: DEFAULT_SEGMENT_LENGTH, hardDisplayUnits: Math.floor(DEFAULT_SEGMENT_LENGTH * 1.25), results }
68
- await mkdir(resolve(root, 'dist/ebooks'), { recursive: true })
69
- await writeFile(resolve(root, 'dist/ebooks/candidate-results.json'), JSON.stringify(report, null, 2) + '\n')
70
- console.log(JSON.stringify(report, null, 2))
71
- } finally { store.dispose() }
@@ -1,161 +0,0 @@
1
- import assert from 'node:assert/strict'
2
- import { readFile, writeFile, copyFile, mkdir } from 'node:fs/promises'
3
- import { createHash } from 'node:crypto'
4
- import { resolve, dirname } from 'node:path'
5
- import { fileURLToPath } from 'node:url'
6
- import JSZip from 'jszip'
7
- import { NovelStore } from '../src/store.js'
8
- import { MemoryStorage } from '../test/helpers/memory-storage.js'
9
-
10
- // Explicit local-only extended probe; ordinary tests never read these downloads.
11
- // Use existing dist/ebooks Alice files, or --copy-from <download-directory>.
12
- // Generates one clearly labelled test-only EPUB from the complete AQ export;
13
- // this is NOT a downloaded original EPUB or a new bundled book.
14
- // This script does not download anything or add support for negative formats.
15
- const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
16
- const output = resolve(root, 'dist/ebooks')
17
- const args = process.argv.slice(2)
18
- if (args.length && (args.length !== 2 || args[0] !== '--copy-from')) {
19
- throw new Error('Usage: node scripts/test-ebook-corpus.mjs [--copy-from <download-directory>]')
20
- }
21
- const { books } = JSON.parse(await readFile(resolve(root, 'samples/ebooks/sources.json'), 'utf8'))
22
- assert.deepEqual(books.map(book => book.id), ['million-pound-bank-note', 'aq-zheng-zhuan'])
23
- const additional = [
24
- { file: 'alice.html', format: 'html', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.html.images' },
25
- { file: 'alice.azw3', format: 'azw3', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.kf8.images' },
26
- { file: 'alice.mobi', format: 'mobi', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.kindle.noimages' },
27
- { file: 'alice.pdf', format: 'pdf', source: 'https://www.adobe.com/be_en/active-use/pdf/Alice_in_Wonderland.pdf', download: 'https://www.adobe.com/be_en/active-use/pdf/Alice_in_Wonderland.pdf' },
28
- ]
29
- const compact = text => text.replace(/\s+/gu, '')
30
- const asFile = (name, bytes) => ({ name, arrayBuffer: async () => Uint8Array.from(bytes).buffer })
31
- const aqChapters = ['第一章 序', '第二章 優勝記略', '第三章 續優勝記略', '第四章 戀愛的悲劇', '第五章 生計問題', '第六章 從中興到末路', '第七章 革命', '第八章 不准革命', '第九章 大團圓']
32
- await mkdir(output, { recursive: true })
33
- for (const source of books) await copyFile(resolve(root, 'samples/ebooks', source.file), resolve(output, source.file))
34
- if (args.length) {
35
- const input = resolve(args[1])
36
- for (const source of additional) {
37
- if (resolve(input, source.file) !== resolve(output, source.file)) await copyFile(resolve(input, source.file), resolve(output, source.file))
38
- }
39
- }
40
- const aq = books.find(book => book.id === 'aq-zheng-zhuan')
41
- const aqText = await readFile(resolve(output, aq.file), 'utf8')
42
- const prefix = aq.derivation.prefix
43
- assert.ok(aqText.startsWith(prefix))
44
- const originalAqText = aqText.slice(prefix.length)
45
- assert.equal(Buffer.byteLength(originalAqText), aq.derivation.originalBytes)
46
- assert.equal(createHash('sha256').update(originalAqText).digest('hex'), aq.derivation.originalSha256)
47
- // A deterministic EPUB container around the entire recovered export, including
48
- // all credits/license text. No source EPUB is claimed and no obsolete sample is read.
49
- const escapeXml = text => text.replace(/&/gu, '&amp;').replace(/</gu, '&lt;').replace(/>/gu, '&gt;')
50
- const zip = new JSZip()
51
- const add = (path, text) => zip.file(path, text, { date: new Date('2000-01-01T00:00:00Z'), compression: 'STORE', createFolders: false })
52
- add('mimetype', 'application/epub+zip')
53
- add('META-INF/container.xml', '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
54
- add('OEBPS/content.opf', '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book-id">aq-derived-test-fixture</dc:identifier><dc:title>阿Q正傳 · derived test fixture</dc:title><dc:language>zh</dc:language><meta property="dcterms:modified">2000-01-01T00:00:00Z</meta></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="text" href="text.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="text"/></spine></package>')
55
- add('OEBPS/nav.xhtml', '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Test fixture</title></head><body><nav epub:type="toc"><ol><li><a href="text.xhtml">阿Q正傳</a></li></ol></nav></body></html>')
56
- add('OEBPS/text.xhtml', `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Test fixture</title></head><body><h1>阿Q正傳</h1><pre>${escapeXml(originalAqText)}</pre></body></html>`)
57
- const fixtureFile = 'aq-derived-test-fixture.epub'
58
- const fixtureBytes = await zip.generateAsync({ type: 'nodebuffer', compression: 'STORE' })
59
- const checked = await JSZip.loadAsync(fixtureBytes, { checkCRC32: true })
60
- assert.equal(await checked.file('mimetype').async('string'), 'application/epub+zip')
61
- await writeFile(resolve(output, fixtureFile), fixtureBytes)
62
- const corpus = [
63
- ...books.map(book => ({ ...book, expectedSegments: book.format === 'txt' ? 820 : 100, expected: 'imported' })),
64
- { id: aq.id, file: fixtureFile, format: 'epub', title: '阿Q正傳 · derived test fixture', source: aq.source,
65
- derivedFrom: aq.file, transformation: 'Test-only EPUB container with an XML-escaped complete original TXT export and one title heading; not an original downloaded EPUB; never bundled.', expected: 'imported' },
66
- ...additional.map(book => ({ ...book, title: "Alice's Adventures in Wonderland", expected: 'rejected' })),
67
- ]
68
- const storage = new MemoryStorage()
69
- const store = new NovelStore(storage)
70
- await store.ready
71
- const results = []
72
- try {
73
- const original = await store.importFile(asFile('existing.txt', new TextEncoder().encode('第一章 原书\n\n保留的原有内容。'.repeat(200))))
74
- const first = await store.claimPassage('original-before-import')
75
- assert.equal(first.kind, 'ready')
76
- const originalBook = structuredClone(storage.books.get(original.id))
77
- const originalPassages = structuredClone([...storage.passages.entries()])
78
- let bundledBytes = 0
79
- for (const source of corpus) {
80
- const bytes = await readFile(resolve(output, source.file))
81
- if (source.format === 'pdf') assert.equal(bytes.subarray(0, 5).toString(), '%PDF-')
82
- if (['mobi', 'azw3'].includes(source.format)) assert.equal(bytes.subarray(60, 68).toString(), 'BOOKMOBI')
83
- if (source.format === 'html') assert.match(bytes.toString('utf8').slice(0, 200), /<!DOCTYPE html|<html/iu)
84
- const hash = createHash('sha256').update(bytes).digest('hex')
85
- if (source.sha256) {
86
- assert.equal(bytes.length, source.bytes, source.file)
87
- assert.equal(hash, source.sha256, source.file)
88
- bundledBytes += bytes.length
89
- }
90
- const file = asFile(source.file, bytes)
91
- const started = performance.now()
92
- const result = {
93
- file: source.file, title: source.title, format: source.format, source: source.source,
94
- ...(source.download ? { download: source.download } : {}),
95
- ...(source.edition ? { edition: source.edition, license: source.license } : {}),
96
- ...(source.derivedFrom ? { derivedFrom: source.derivedFrom, transformation: source.transformation } : {}),
97
- bytes: bytes.length, sha256: hash, expected: source.expected,
98
- }
99
- if (source.expected === 'rejected') {
100
- const before = await storage.load()
101
- const passages = structuredClone([...storage.passages.entries()])
102
- await assert.rejects(store.importFile(file), error => {
103
- assert.match(error.message, /只支持 EPUB、TXT、MD 文件/u)
104
- result.message = error.message
105
- return true
106
- })
107
- assert.deepEqual(await storage.load(), before)
108
- assert.deepEqual([...storage.passages.entries()], passages)
109
- result.actual = 'rejected-with-library-unchanged'
110
- } else {
111
- const book = await store.importFile(file)
112
- assert.equal(book.format, source.format)
113
- assert.ok(book.segmentCount > 1)
114
- if (source.expectedSegments) assert.equal(book.segmentCount, source.expectedSegments)
115
- assert.equal(book.progress, 0)
116
- const segments = await Promise.all(Array.from({ length: book.segmentCount }, (_, index) => storage.getSegment(book.id, index)))
117
- const body = segments.map(segment => segment.text).join('\n')
118
- const text = compact(body)
119
- assert.doesNotMatch(body, /\uFFFD/u)
120
- if (source.id === 'million-pound-bank-note') {
121
- assert.ok(text.includes(compact('When I was twenty-seven years old, I was a mining-broker’s clerk in San Francisco')), 'not merely PG metadata/license')
122
- assert.ok(text.includes(compact('My Portia’s papa took that friendly and hospitable bill back to the Bank of England and cashed it')))
123
- assert.match(body, /_A MAJESTIC LITERARY FOSSIL_/u)
124
- assert.match(body, /START: FULL LICENSE/u)
125
- assert.match(body, /Section 5\. General Information/u)
126
- result.actual = 'imported-readable-english-collection'
127
- } else {
128
- assert.equal(source.id, 'aq-zheng-zhuan')
129
- assert.ok(text.includes('我要給阿Q做正傳,已經不止一兩年了。'))
130
- assert.ok(text.includes('他們白跟一趟了。'))
131
- assert.ok(text.includes('(一九二一年十二月。)'))
132
- assert.match(body, /About this digital edition/u)
133
- assert.match(body, /Creative Commons Attribution-ShareAlike 3\.0 Unported.*GNU FDL/u)
134
- assert.match(body, /Dbenbenn/u)
135
- assert.equal(text, compact(originalAqText), 'Markdown and test EPUB retain the complete exported text')
136
- assert.equal(segments[0].chapterTitle, '阿Q正傳')
137
- for (const title of aqChapters) assert.ok(text.includes(compact(title)), title)
138
- result.actual = source.format === 'md' ? 'imported-readable-complete-chinese-markdown-derivative' : 'imported-readable-complete-chinese-derived-test-epub'
139
- }
140
- result.segmentCount = book.segmentCount
141
- }
142
- assert.equal(store.getSettingsSnapshot().currentBookId, original.id)
143
- assert.deepEqual(storage.books.get(original.id), originalBook)
144
- for (const [key, passage] of originalPassages) assert.deepEqual(storage.passages.get(key), passage)
145
- assert.deepEqual(await store.claimPassage('original-before-import'), first, 'imports do not invalidate or advance the existing passage')
146
- result.milliseconds = Math.round((performance.now() - started) * 100) / 100
147
- results.push(result)
148
- }
149
- assert.equal(bundledBytes, 462708)
150
- assert.ok(bundledBytes < 600 * 1024)
151
- const report = {
152
- verifiedOn: new Date().toISOString(), scope: 'NovelStore + MemoryStorage; no GUI claims; no network requests',
153
- output: 'dist/ebooks', bundledBytes, originalSelectionAndProgressUnchanged: true,
154
- redistribution: 'Bundled samples comprise one unchanged English TXT download and one clearly labelled complete AQ Markdown derivative, under their individual notices, not plugin MIT. The Markdown suffix retains the full original official TXT export and credits byte-for-byte. The generated AQ EPUB is a local test-only derivative preserving the complete export, not an original EPUB download or package asset. The four Alice files are local negative-test downloads, not package assets; the Adobe PDF is not cleared for redistribution.',
155
- results,
156
- }
157
- await writeFile(resolve(output, 'results.json'), `${JSON.stringify(report, null, 2)}\n`)
158
- console.log(JSON.stringify(report, null, 2))
159
- } finally {
160
- store.dispose()
161
- }
@@ -1,42 +0,0 @@
1
- import manifest from '../samples/ebooks/sources.json'
2
- import millionPoundBankNote from '../samples/ebooks/million-pound-bank-note-pg61522.txt'
3
- import aqZhengZhuan from '../samples/ebooks/aq-zheng-zhuan-wikisource.md'
4
- import notices from '../samples/ebooks/LICENSE.md'
5
-
6
- // TXT uses the existing base64 loader; Markdown stays text, like legal notices.
7
- // Encode/decode lazily during hydration/import, without File or network access.
8
- const payloads = {
9
- 'million-pound-bank-note': () => Uint8Array.from(atob(millionPoundBankNote), character => character.charCodeAt(0)),
10
- 'aq-zheng-zhuan': () => new TextEncoder().encode(aqZhengZhuan),
11
- }
12
- export const sampleBooks = manifest.books.map(({ id, title, author, format, bytes, source, license }) => ({ id, title, author, format, bytes, source, license }))
13
-
14
- export function createSampleFile(id) {
15
- const book = sampleBooks.find(book => book.id === id)
16
- if (!book || !Object.hasOwn(payloads, id)) throw new Error('Unknown bundled ebook')
17
- const bytes = payloads[id]()
18
- return { name: `${book.title}.${book.format}`, arrayBuffer: async () => bytes.buffer }
19
- }
20
-
21
- // Separate from the original seeding marker: upgrades must not restore deleted
22
- // defaults or claim ownership of untagged manual imports, even identical ones.
23
- export const bundledCatalog = {
24
- version: 2,
25
- removedIds: ['shanhaijing-illustrated'],
26
- updates: [{
27
- id: 'aq-zheng-zhuan', fromFormat: 'txt', format: 'md',
28
- createFile: () => {
29
- const prefix = '# 阿Q正傳\n\n'
30
- if (!aqZhengZhuan.startsWith(prefix)) throw new Error('Invalid bundled Markdown source prefix')
31
- const bytes = new TextEncoder().encode(aqZhengZhuan.slice(prefix.length))
32
- return { name: '阿Q正傳.txt', arrayBuffer: async () => bytes.buffer }
33
- },
34
- }],
35
- }
36
-
37
- // Combined full licenses and attribution are immediately accessible offline.
38
- let licenseHref
39
- export function getSampleLicenseHref() {
40
- if (!licenseHref) licenseHref = `data:text/plain;charset=utf-8,${encodeURIComponent(notices)}`
41
- return licenseHref
42
- }
@@ -1,278 +0,0 @@
1
- import { passageSnapshotKey } from './store.js'
2
- import { NOVEL_STYLE, PASSAGE_STYLE, SEPARATOR_STYLE, novelContent } from './novel-content.js'
3
- import { PG_NOTICE, PG_NOTICE_STYLE, PG_LICENSE_LABEL, PG_LICENSE_DOWNLOAD } from './pg-notice.js'
4
-
5
- const THOUGHT = '[data-chat-flow-kind="assistant-step"] [data-variant="think"]'
6
- const TOOL = '[data-chat-call-id] [data-tool], [data-chat-call-id] [data-sample="bash"]'
7
- const REGIONS = `${THOUGHT}, ${TOOL}`
8
- const EMPTY = Object.freeze({ kind: 'empty' })
9
-
10
- /** DSH 0.2.1 窄适配:保留原生控件和正文,只改标题文字并追加本地纯文本。 */
11
- export function registerChatAdapter(ctx, store, React, locale, { getSampleLicenseHref } = {}) {
12
- const t = ctx.locale?.bind(locale) ?? (key => key)
13
- ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register({
14
- name: 'conversation.chat.reasoning.body', priority: -10, locale,
15
- inject: () => ({ hooks: { novelSettings: store.settingsSource, novelPassages: store.passageSource } }),
16
- }, createBody(React, getSampleLicenseHref)))
17
-
18
- ctx.effect(() => {
19
- const decorated = new Map()
20
- const pending = new Map()
21
- const view = document.defaultView
22
- let disposed = false
23
-
24
- const restore = root => {
25
- const record = decorated.get(root)
26
- if (!record) return
27
- for (const [node, text] of record.texts) restoreText(node, text)
28
- record.append?.remove()
29
- root.removeAttribute('data-novel-target')
30
- decorated.delete(root)
31
- }
32
- const refresh = () => {
33
- const settings = store.getSettingsSnapshot()
34
- for (const [toggle, intent] of pending) {
35
- const id = identityOf(intent.root)
36
- if (!toggle.isConnected || !settings.enabled || settings.currentBookId !== intent.bookId
37
- || !isTarget(settings, id) || readingKey(id) !== intent.key || store.cacheGeneration !== intent.generation) {
38
- if (intent.frame !== null) view.cancelAnimationFrame(intent.frame)
39
- pending.delete(toggle)
40
- }
41
- }
42
- for (const root of decorated.keys()) {
43
- if (!root.isConnected || !settings.enabled || !isTarget(settings, identityOf(root))) restore(root)
44
- }
45
- for (const root of document.querySelectorAll(REGIONS)) {
46
- const id = identityOf(root)
47
- const header = headerOf(root)
48
- if (!header || !settings.enabled || !isTarget(settings, id)) continue
49
- let record = decorated.get(root)
50
- if (!record || record.header !== header) {
51
- restore(root)
52
- record = { header, texts: new Map(), append: null, signature: null }
53
- decorated.set(root, record)
54
- root.setAttribute('data-novel-target', '')
55
- }
56
- const desired = new Map()
57
- // 原生基础层和 shimmer 高亮层保持同一文字,不改变其样式、SVG或身份。
58
- const content = [...header.children].find(child => child.querySelector('[data-shimmer-decoration]'))
59
- const layers = [content?.firstElementChild, content?.querySelector('[inert]')?.firstElementChild?.firstElementChild]
60
- for (const layer of layers) {
61
- const title = layer?.firstElementChild
62
- if (!title) continue
63
- collectText(title, settings.mainTitle.trim(), desired)
64
- const separator = title.nextElementSibling
65
- if (separator?.hasAttribute('data-shimmer-decoration')) collectText(separator.nextElementSibling, settings.extraTitle.trim(), desired)
66
- }
67
- for (const [node, text] of record.texts) {
68
- if (!desired.has(node)) { restoreText(node, text); record.texts.delete(node) }
69
- }
70
- for (const [node, value] of desired) {
71
- const current = readText(node)
72
- const previous = record.texts.get(node)
73
- const native = previous && current === previous.shown ? previous.native : current
74
- record.texts.set(node, { native, shown: value })
75
- if (current !== value) writeText(node, value)
76
- }
77
- // 工具没有公开的“正文末尾”slot;只添加自己的兄弟节点,不接管工具 renderer。
78
- if (id.type !== 'reasoning') {
79
- const toggle = toggleOf(header)
80
- if (toggle?.getAttribute('aria-expanded') !== 'true') {
81
- record.append?.remove(); record.append = null; record.signature = null
82
- continue
83
- }
84
- const status = store.getPassageStatus(settings.currentBookId, readingKey(id))
85
- const model = novelContent(status, Boolean(settings.currentBookId), t)
86
- const signature = JSON.stringify(model)
87
- const container = root.matches('[data-sample="bash"]') ? root.parentElement : root
88
- if (!record.append || !container.contains(record.append)) {
89
- record.append = document.createElement('div')
90
- record.append.setAttribute('data-novel-append', '')
91
- container.append(record.append)
92
- record.signature = null
93
- }
94
- if (signature !== record.signature) {
95
- renderPlainAppend(record.append, model, getSampleLicenseHref)
96
- record.signature = signature
97
- }
98
- }
99
- }
100
- }
101
-
102
- // Streaming text mutates the DOM far more often than a frame; merge observer
103
- // bursts into one scan so a long session cannot turn every token into a full
104
- // rescan. Settings/passage updates still refresh immediately.
105
- let queued = null
106
- const coalescedRefresh = () => {
107
- if (!queued) return
108
- queued = null
109
- if (!disposed) refresh()
110
- }
111
- const scheduleRefresh = () => {
112
- if (queued) return
113
- const entry = { frame: null }
114
- queued = entry
115
- if (view?.requestAnimationFrame) entry.frame = view.requestAnimationFrame(coalescedRefresh)
116
- else queueMicrotask(coalescedRefresh)
117
- }
118
-
119
- const activate = event => {
120
- if (!event.isTrusted || event.defaultPrevented) return
121
- if (event.type === 'keydown' && (event.repeat || !['Enter', ' '].includes(event.key))) return
122
- if (event.type === 'click' && event.button > 0) return
123
- const target = event.target instanceof Element ? event.target : event.target?.parentElement
124
- const header = target?.closest('[data-disclosure-row], [data-sample="bash"][aria-expanded]')
125
- const root = header?.matches('[data-sample="bash"]') ? header : header?.closest('[data-tool], [data-variant="think"]')
126
- if (!root?.matches(REGIONS)) return
127
- const toggle = toggleOf(header)
128
- if (!toggle || !toggle.contains(target) || toggle.getAttribute('aria-expanded') !== 'false') return
129
- const control = target.closest('button, [role="button"], a, input, select, textarea, [contenteditable="true"]')
130
- if (control && control !== toggle) return
131
- if (event.type === 'keydown' && target !== toggle) return
132
- const id = identityOf(root)
133
- const settings = store.getSettingsSnapshot()
134
- if (!settings.enabled || !isTarget(settings, id) || pending.has(toggle)) return
135
- const bookId = settings.currentBookId
136
- const intent = { frame: null, root, key: readingKey(id), bookId, generation: store.cacheGeneration }
137
- pending.set(toggle, intent)
138
- const verify = () => {
139
- if (pending.get(toggle) !== intent) return
140
- pending.delete(toggle)
141
- const current = store.getSettingsSnapshot()
142
- const currentId = identityOf(root)
143
- if (!disposed && toggle.isConnected && toggle.getAttribute('aria-expanded') === 'true'
144
- && current.enabled && current.currentBookId === bookId && isTarget(current, currentId)
145
- && store.cacheGeneration === intent.generation && readingKey(currentId) === intent.key) {
146
- if (current.continueOnReopen === true) void store.continuePassage(readingKey(id), id.type)
147
- else void store.claimPassage(readingKey(id), id.type)
148
- }
149
- }
150
- if (view?.requestAnimationFrame) intent.frame = view.requestAnimationFrame(verify)
151
- else queueMicrotask(verify)
152
- }
153
- const observer = new MutationObserver(scheduleRefresh)
154
- observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true,
155
- attributeFilter: ['data-shimmer-text', 'aria-expanded', 'data-tool', 'data-state'] })
156
- document.addEventListener('click', activate, true)
157
- document.addEventListener('keydown', activate, true)
158
- const stopSettings = store.subscribeSettings(refresh)
159
- const stopPassages = store.subscribePassages(refresh)
160
- refresh()
161
- return () => {
162
- disposed = true
163
- observer.disconnect(); stopSettings(); stopPassages()
164
- document.removeEventListener('click', activate, true)
165
- document.removeEventListener('keydown', activate, true)
166
- if (queued && queued.frame !== null && view?.cancelAnimationFrame) view.cancelAnimationFrame(queued.frame)
167
- queued = null
168
- for (const intent of pending.values()) if (intent.frame !== null) view.cancelAnimationFrame(intent.frame)
169
- pending.clear()
170
- for (const root of decorated.keys()) restore(root)
171
- }
172
- }, 'novel-fish: native disclosure adapter')
173
- }
174
-
175
- function headerOf(root) {
176
- return root.matches('[data-sample="bash"]') ? root : root.querySelector('[data-disclosure-row]')
177
- }
178
- function toggleOf(header) {
179
- return header.matches('[role="button"][aria-expanded]') ? header : header.querySelector(':scope > button[aria-expanded]')
180
- }
181
- function collectText(element, value, desired) {
182
- if (!element || !value) return
183
- const walker = element.ownerDocument.createTreeWalker(element, 4)
184
- let first = true
185
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
186
- desired.set(node, first ? value : ''); first = false
187
- }
188
- for (const node of [element, ...element.querySelectorAll('[data-shimmer-text]')]) {
189
- if (node.hasAttribute('data-shimmer-text')) desired.set(node, value)
190
- }
191
- }
192
- function readText(node) { return node.nodeType === 3 ? node.nodeValue : node.getAttribute('data-shimmer-text') }
193
- function writeText(node, value) {
194
- if (node.nodeType === 3) node.nodeValue = value
195
- else node.setAttribute('data-shimmer-text', value)
196
- }
197
- function restoreText(node, text) { if (readText(node) === text.shown) writeText(node, text.native) }
198
-
199
- function createBody(React, getSampleLicenseHref) {
200
- const h = React.createElement
201
- return function NovelBody({ text, running, sessionId, useNovelSettings, useNovelPassages, renderFactorySlot, t }) {
202
- const ref = React.useRef(null)
203
- const [identity, setIdentity] = React.useState(null)
204
- const settings = useNovelSettings(value => value)
205
- React.useEffect(() => { setIdentity(identityOf(ref.current)) }, [sessionId])
206
- const selected = settings.enabled && isTarget(settings, identity)
207
- const key = settings.currentBookId && identity ? passageSnapshotKey(settings.currentBookId, readingKey(identity)) : null
208
- const status = useNovelPassages(snapshot => key ? snapshot[key] : undefined) ?? EMPTY
209
- const model = selected ? novelContent(status, Boolean(settings.currentBookId), t) : null
210
- return h('div', { ref },
211
- h('div', { 'data-novel-original': true }, renderFactorySlot('conversation.chat.reasoning.content', { text, running })),
212
- model === null ? null : h('div', { 'data-novel-append': true, style: NOVEL_STYLE },
213
- h('hr', { style: SEPARATOR_STYLE }),
214
- h('div', { 'data-novel-label': true }, model.chapter ? `${model.label} · ${model.chapter}` : model.label),
215
- model.projectGutenberg ? h('aside', { 'data-novel-pg-notice': true, style: PG_NOTICE_STYLE },
216
- h('p', { style: { margin: '0 0 6px' } }, PG_NOTICE),
217
- h('a', { href: getSampleLicenseHref?.(), download: PG_LICENSE_DOWNLOAD }, PG_LICENSE_LABEL)) : null,
218
- h('div', { 'data-novel-passage': model.index, role: model.role, style: PASSAGE_STYLE,
219
- tabIndex: model.index ? 0 : undefined, 'aria-label': model.index ? model.label : undefined }, model.text)),
220
- )
221
- }
222
- }
223
- function renderPlainAppend(element, model, getSampleLicenseHref) {
224
- Object.assign(element.style, NOVEL_STYLE)
225
- const divider = document.createElement('hr')
226
- Object.assign(divider.style, SEPARATOR_STYLE)
227
- const label = document.createElement('div')
228
- label.setAttribute('data-novel-label', '')
229
- label.textContent = model.chapter ? `${model.label} · ${model.chapter}` : model.label
230
- const content = document.createElement('div')
231
- Object.assign(content.style, PASSAGE_STYLE)
232
- if (model.index) {
233
- content.setAttribute('data-novel-passage', model.index)
234
- content.tabIndex = 0
235
- content.setAttribute('aria-label', model.label)
236
- }
237
- if (model.role) content.setAttribute('role', model.role)
238
- content.textContent = model.text
239
- const notice = []
240
- if (model.projectGutenberg) {
241
- const aside = document.createElement('aside')
242
- aside.setAttribute('data-novel-pg-notice', '')
243
- Object.assign(aside.style, PG_NOTICE_STYLE)
244
- const statement = document.createElement('p')
245
- statement.style.margin = '0 0 6px'
246
- statement.textContent = PG_NOTICE
247
- const license = document.createElement('a')
248
- license.href = getSampleLicenseHref?.() ?? ''
249
- license.download = PG_LICENSE_DOWNLOAD
250
- license.textContent = PG_LICENSE_LABEL
251
- aside.append(statement, license)
252
- notice.push(aside)
253
- }
254
- element.replaceChildren(divider, label, ...notice, content)
255
- }
256
- function identityOf(element) {
257
- const root = element?.closest('[data-variant="think"], [data-tool], [data-sample="bash"]')
258
- const node = root?.closest('[data-chat-node-key]')
259
- const container = node?.closest('[data-conversation-session]')
260
- if (!root || !node || !container) return null
261
- const sessionId = container.getAttribute('data-conversation-session')
262
- const nodeKey = node.getAttribute('data-chat-node-key')
263
- if (!sessionId || !nodeKey) return null
264
- if (root.matches(THOUGHT)) {
265
- const regions = [...node.querySelectorAll('[data-variant="think"]')].filter(region => region.closest('[data-chat-node-key]') === node)
266
- const index = regions.indexOf(root)
267
- return index < 0 ? null : { sessionId, nodeKey, type: 'reasoning', index }
268
- }
269
- const call = root.closest('[data-chat-call-id]')
270
- if (!call || !call.getAttribute('data-chat-call-id')) return null
271
- const variant = root.getAttribute('data-variant')
272
- const name = root.getAttribute('data-tool')
273
- const type = variant === 'bash' ? 'command' : ['read', 'read_image'].includes(name) ? 'read-file'
274
- : ['grep', 'glob'].includes(name) ? 'file-search' : 'tool-call'
275
- return { sessionId, nodeKey, type, index: call.getAttribute('data-chat-call-id') }
276
- }
277
- function readingKey(identity) { return JSON.stringify([identity.sessionId, identity.nodeKey, identity.type, identity.index]) }
278
- function isTarget(settings, identity) { return identity !== null && settings.targetTypes?.includes(identity.type) }
package/src/client.js DELETED
@@ -1,61 +0,0 @@
1
- import { IndexedDbStorage } from './persistence.js'
2
- import { NovelStore } from './store.js'
3
- import { registerChatAdapter } from './chat-adapter.js'
4
- import { createSettingsRow } from './settings.js'
5
- import { sampleBooks, bundledCatalog, createSampleFile, getSampleLicenseHref } from './bundled-books.js'
6
- import zh from '../locale/zh.json'
7
- import en from '../locale/en.json'
8
-
9
- const MODULE_ID = '@gongfpp/dsh-novel-fish'
10
- const LOCALE = 'novel-fish'
11
-
12
- function flatten(value, prefix = '') {
13
- return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {
14
- const path = prefix ? `${prefix}.${key}` : key
15
- return typeof item === 'string' ? [[path, item]] : Object.entries(flatten(item, path))
16
- }))
17
- }
18
-
19
- window.__ModuleLoader__.load({
20
- id: MODULE_ID,
21
- factory(require) {
22
- const React = require('react')
23
- const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
24
- return {
25
- inject: ['slots', 'locale'],
26
- apply(ctx) {
27
- const storage = new IndexedDbStorage()
28
- const store = new NovelStore(storage, {
29
- bundledBooks: sampleBooks.map(book => ({ ...book, createFile: () => createSampleFile(book.id) })),
30
- bundledCatalog,
31
- })
32
- const SettingsRow = createSettingsRow(React, primitives)
33
- const settingsActions = {
34
- onSetOption: (key, value) => store.setOption(key, value),
35
- onSetNotice: notice => store.setNotice(notice),
36
- onSelectBook: bookId => store.selectBook(bookId),
37
- onDeleteBook: bookId => store.deleteBook(bookId),
38
- onImportFile: file => store.importFile(file),
39
- sampleBooks,
40
- getSampleLicenseHref,
41
- }
42
-
43
- ctx.effect(() => ctx.locale.register(LOCALE, { zh: flatten(zh), en: flatten(en) }), 'novel-fish: locale')
44
- ctx.effect(() => () => store.dispose(), 'novel-fish: store')
45
- ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
46
- name: 'plugins.bundle.config',
47
- key: MODULE_ID,
48
- locale: LOCALE,
49
- inject: () => ({
50
- hooks: {
51
- novelState: store.stateSource,
52
- novelUi: store.uiSource,
53
- },
54
- ...settingsActions,
55
- }),
56
- }, SettingsRow))
57
- registerChatAdapter(ctx, store, React, LOCALE, { getSampleLicenseHref })
58
- },
59
- }
60
- },
61
- })