@gongfpp/dsh-novel-fish 1.1.0 → 1.2.1

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 (106) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +47 -35
  3. package/docs/evidence/reading-box-121.png +0 -0
  4. package/docs/evidence/settings-121.png +0 -0
  5. package/index.json +24 -0
  6. package/lib/client.js +924 -323
  7. package/locale/en.json +22 -10
  8. package/locale/zh.json +22 -10
  9. package/package.json +5 -7
  10. package/samples/ebooks/{aq-zheng-zhuan-wikisource.md → aq-zheng-zhuan.md} +9 -360
  11. package/samples/ebooks/{million-pound-bank-note-pg61522.txt → million-pound-bank-note.txt} +6476 -6970
  12. package/samples/ebooks/sources.json +13 -49
  13. package/screenshots.json +6 -0
  14. package/docs/acceptance.md +0 -42
  15. package/docs/community-markets.md +0 -88
  16. package/docs/compatibility-017.md +0 -70
  17. package/docs/compatibility-101.md +0 -41
  18. package/docs/continuous-reading-020.md +0 -46
  19. package/docs/ebook-tests.md +0 -99
  20. package/docs/evidence/abc-result.json +0 -9
  21. package/docs/evidence/banner-100.png +0 -0
  22. package/docs/evidence/community-market-014-result.json +0 -170
  23. package/docs/evidence/compatibility-017-result.json +0 -65
  24. package/docs/evidence/continuous-reading-020-result.json +0 -72
  25. package/docs/evidence/formats-result.json +0 -12
  26. package/docs/evidence/live-ab.png +0 -0
  27. package/docs/evidence/live-collapsed.png +0 -0
  28. package/docs/evidence/live-disabled.png +0 -0
  29. package/docs/evidence/live-epub.png +0 -0
  30. package/docs/evidence/live-market.png +0 -0
  31. package/docs/evidence/live-resume.png +0 -0
  32. package/docs/evidence/live-unloaded.png +0 -0
  33. package/docs/evidence/long-result.json +0 -11
  34. package/docs/evidence/multi-region-014-result.json +0 -47
  35. package/docs/evidence/native-disclosure-013-result.json +0 -36
  36. package/docs/evidence/native-disclosures-013.png +0 -0
  37. package/docs/evidence/native-open-013.png +0 -0
  38. package/docs/evidence/native-settings-sample.md +0 -11
  39. package/docs/evidence/native-settings-types-015.png +0 -0
  40. package/docs/evidence/npm-market-014-result.json +0 -132
  41. package/docs/evidence/plugin-settings-details.png +0 -0
  42. package/docs/evidence/public-release-014-result.json +0 -51
  43. package/docs/evidence/public-release-015-result.json +0 -36
  44. package/docs/evidence/public-release-result.json +0 -48
  45. package/docs/evidence/reading-demo-100.png +0 -0
  46. package/docs/evidence/reading-demo-110.png +0 -0
  47. package/docs/evidence/reading-two-expansions-110.gif +0 -0
  48. package/docs/evidence/reading-two-expansions-110.json +0 -89
  49. package/docs/evidence/samples-110-capture.json +0 -49
  50. package/docs/evidence/settings-011-result.json +0 -28
  51. package/docs/evidence/settings-011.png +0 -0
  52. package/docs/evidence/settings-100.png +0 -0
  53. package/docs/evidence/settings-110.png +0 -0
  54. package/docs/evidence/settings-chat-011.png +0 -0
  55. package/docs/evidence/type-append-012-result.json +0 -30
  56. package/docs/evidence/type-append-012.png +0 -0
  57. package/docs/evidence/type-settings-012.png +0 -0
  58. package/docs/evidence/unload-result.json +0 -7
  59. package/docs/host-adapter.md +0 -43
  60. package/docs/icon-metadata-021.md +0 -40
  61. package/docs/interaction-paths-020.md +0 -39
  62. package/docs/marketplace.md +0 -42
  63. package/docs/multi-region-update.md +0 -53
  64. package/docs/native-disclosure-update.md +0 -39
  65. package/docs/native-settings-update.md +0 -48
  66. package/docs/plugin-settings-update.md +0 -61
  67. package/docs/release.md +0 -151
  68. package/docs/settings-update.md +0 -49
  69. package/docs/type-append-update.md +0 -50
  70. package/pnpm-workspace.yaml +0 -5
  71. package/samples/ebooks/LICENSE.md +0 -355
  72. package/samples/ebooks/NOTICE.md +0 -33
  73. package/scripts/build.mjs +0 -70
  74. package/scripts/check-host-contracts.mjs +0 -247
  75. package/scripts/licenses/path-webpack.txt +0 -28
  76. package/scripts/make-readme-gif.mjs +0 -69
  77. package/scripts/test-browser-samples.mjs +0 -665
  78. package/scripts/test-candidate-books.mjs +0 -71
  79. package/scripts/test-ebook-corpus.mjs +0 -161
  80. package/src/bundled-books.js +0 -42
  81. package/src/chat-adapter.js +0 -278
  82. package/src/client.js +0 -61
  83. package/src/epub.js +0 -166
  84. package/src/novel-content.js +0 -28
  85. package/src/persistence.js +0 -271
  86. package/src/pg-notice.js +0 -19
  87. package/src/segments.js +0 -185
  88. package/src/settings.js +0 -243
  89. package/src/store.js +0 -429
  90. package/src/text-decoding.js +0 -28
  91. package/test/bundled-library.test.js +0 -526
  92. package/test/chat-adapter.test.js +0 -518
  93. package/test/client.test.js +0 -124
  94. package/test/ebooks.test.js +0 -192
  95. package/test/epub.test.js +0 -185
  96. package/test/helpers/host-primitives.js +0 -28
  97. package/test/helpers/memory-storage.js +0 -48
  98. package/test/host-contracts.test.js +0 -32
  99. package/test/import.test.js +0 -102
  100. package/test/persistence.test.js +0 -27
  101. package/test/pg-notice.test.js +0 -109
  102. package/test/release.test.js +0 -87
  103. package/test/segments.test.js +0 -182
  104. package/test/settings.test.js +0 -312
  105. package/test/store.test.js +0 -617
  106. package/test/text-decoding.test.js +0 -49
@@ -1,109 +0,0 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import { readFile } from 'node:fs/promises'
4
- import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'
5
- import { IndexedDbStorage } from '../src/persistence.js'
6
- import { DEFAULT_SETTINGS, NovelStore } from '../src/store.js'
7
- import { parseTextBook } from '../src/segments.js'
8
- import { PG_NOTICE, hasProjectGutenbergReference } from '../src/pg-notice.js'
9
- import { novelContent } from '../src/novel-content.js'
10
- import { MemoryStorage } from './helpers/memory-storage.js'
11
-
12
- const source = await readFile(new URL('../samples/ebooks/million-pound-bank-note-pg61522.txt', import.meta.url), 'utf8')
13
- const pgSegments = parseTextBook(source).segments
14
- const file = (name, text) => ({ name, arrayBuffer: async () => new TextEncoder().encode(text).buffer })
15
-
16
- test('notice is exactly the licensed §1.E.1 statement, including ™', async () => {
17
- const license = await readFile(new URL('../samples/ebooks/LICENSE.md', import.meta.url), 'utf8')
18
- const statement = license.slice(license.indexOf(' This eBook'), license.indexOf('1.E.2.')).trim().replace(/\s+/gu, ' ')
19
- assert.equal(PG_NOTICE, statement)
20
- assert.match(PG_NOTICE, /Project Gutenberg™ License/u)
21
- assert.equal(hasProjectGutenbergReference('The PROJECT\nGUTENBERG eBook'), true)
22
- assert.equal(hasProjectGutenbergReference('阿Q正傳'), false)
23
- assert.equal(hasProjectGutenbergReference('notProject Gutenbergish'), false)
24
- })
25
-
26
- test('real bundled PG default is detected without tagging AQ or title-based lookalikes', async () => {
27
- const storage = new IndexedDbStorage(new IDBFactory(), IDBKeyRange)
28
- const aq = await readFile(new URL('../samples/ebooks/aq-zheng-zhuan-wikisource.md', import.meta.url), 'utf8')
29
- const store = new NovelStore(storage, { bundledBooks: [
30
- { id: 'million-pound-bank-note', title: '百萬英鎊', format: 'txt', createFile: () => file('default.txt', source) },
31
- { id: 'aq-zheng-zhuan', title: '阿Q正傳', format: 'md', createFile: () => file('aq.md', aq) },
32
- { id: 'unrelated', title: 'Project Gutenberg', format: 'txt', createFile: () => file('other.txt', 'Unrelated original text.') },
33
- ] })
34
- try {
35
- await store.ready
36
- assert.equal(store.getSnapshot().error, null)
37
- assert.equal((await store.claimPassage('pg')).projectGutenberg, true)
38
- await store.selectBook('bundled:aq-zheng-zhuan')
39
- assert.equal((await store.claimPassage('aq')).projectGutenberg, false)
40
- await store.selectBook('bundled:unrelated')
41
- assert.equal((await store.claimPassage('other')).projectGutenberg, false)
42
- } finally { store.dispose() }
43
- })
44
-
45
- test('adopted legacy PG with arbitrary ID/title resumes using cached segment-zero provenance without migration', async () => {
46
- const book = { id: 'old-random-import-42', title: 'Renamed by reader', format: 'txt', progress: 8, segmentCount: pgSegments.length, importedAt: 42 }
47
- const storage = new MemoryStorage({ books: [book], settings: { ...DEFAULT_SETTINGS, currentBookId: book.id }, passages: { [book.id]: pgSegments } })
48
- const indices = []
49
- const getSegment = storage.getSegment.bind(storage)
50
- storage.getSegment = async (id, index) => { indices.push(index); return getSegment(id, index) }
51
- const store = new NovelStore(storage)
52
- try {
53
- await store.ready
54
- assert.deepEqual(storage.books.get(book.id), book)
55
- assert.equal(storage.reads, 0, 'hydration does not scan books or consume progress')
56
- const first = await store.claimPassage('first')
57
- assert.equal(first.projectGutenberg, true)
58
- assert.equal(first.index, 8)
59
- assert.equal(first.passage.text, pgSegments[8].text)
60
- assert.equal(novelContent(first, true, key => key).projectGutenberg, true)
61
- const next = await store.continuePassage('first')
62
- assert.equal(next.projectGutenberg, true)
63
- assert.deepEqual(indices, [8, 0, 9], 'header is loaded once; subsequent claims reuse provenance')
64
- assert.deepEqual(storage.books.get(book.id), { ...book, progress: 10 }, 'only normal progress changes, not IDs, ownership or metadata')
65
- assert.strictEqual(await store.claimPassage('first'), next)
66
- assert.deepEqual(indices, [8, 0, 9], 'cached remount does not read again')
67
- } finally { store.dispose() }
68
- })
69
-
70
- test('manual import of the identical PG TXT is detected despite arbitrary filename and no bundled identity', async () => {
71
- const storage = new MemoryStorage()
72
- const store = new NovelStore(storage)
73
- try {
74
- await store.ready
75
- const imported = await store.importFile(file('reader-chosen-name.txt', source))
76
- assert.equal(imported.bundledId, undefined)
77
- const first = await store.claimPassage('import')
78
- assert.equal(first.projectGutenberg, true)
79
- assert.equal(first.passage.text, pgSegments[0].text)
80
- assert.equal(storage.reads, 1, 'first claim reuses its segment-zero read')
81
- assert.equal((await store.continuePassage('import')).projectGutenberg, true)
82
- assert.equal(storage.reads, 2)
83
- } finally { store.dispose() }
84
- })
85
-
86
- test('a canceled provenance read never publishes a passage or advances resumed progress', async () => {
87
- const book = { id: 'legacy', title: 'Renamed', format: 'txt', progress: 2, segmentCount: 4 }
88
- const storage = new MemoryStorage({ books: [book], settings: { ...DEFAULT_SETTINGS, currentBookId: book.id }, passages: { legacy: pgSegments.slice(0, 4) } })
89
- let release, entered
90
- const gate = new Promise(resolve => { release = resolve })
91
- const started = new Promise(resolve => { entered = resolve })
92
- const getSegment = storage.getSegment.bind(storage)
93
- storage.getSegment = async (id, index) => {
94
- if (index === 0) { entered(); await gate }
95
- return getSegment(id, index)
96
- }
97
- const store = new NovelStore(storage)
98
- try {
99
- await store.ready
100
- const reading = store.claimPassage('pending')
101
- await started
102
- const disabling = store.setOption('enabled', false)
103
- release()
104
- assert.equal((await reading).kind, 'empty')
105
- await disabling
106
- assert.equal(storage.books.get(book.id).progress, 2)
107
- assert.equal(store.getPassageStatus(book.id, 'pending').kind, 'empty')
108
- } finally { release(); store.dispose() }
109
- })
@@ -1,87 +0,0 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import semver from 'semver'
4
- import { readFile, access } from 'node:fs/promises'
5
-
6
- const root = new URL('../', import.meta.url)
7
- const read = path => readFile(new URL(path, root), 'utf8')
8
-
9
- test('public package identity matches the Host patch and browser module', async () => {
10
- const manifest = JSON.parse(await read('package.json'))
11
- assert.equal(manifest.name, '@gongfpp/dsh-novel-fish')
12
- assert.equal(manifest.repository.url, 'https://github.com/gongfpp/dsh-novel-fish.git')
13
- assert.equal(manifest.engines.dsh, '>=0.2.1-rc.2 <0.3.0-0')
14
- assert.ok((await read('cordis.patch.yml')).includes(`name: '${manifest.name}'`))
15
- assert.ok((await read('src/client.js')).includes(`const MODULE_ID = '${manifest.name}'`))
16
- assert.ok((await read('lib/client.js')).includes(manifest.name))
17
- for (const path of ['./index.js', './lib/client.js', './assets/icon.png', './locale/en.json', './locale/zh.json']) {
18
- await access(new URL(path, root))
19
- }
20
- })
21
-
22
- test('host compatibility covers the whole 0.2.x line but not earlier work or 0.3', async () => {
23
- const { engines } = JSON.parse(await read('package.json'))
24
- // DSH preflight evaluates prereleases explicitly, unlike npm's default semver rules.
25
- // A ceiling of the form `<=0.2.2-alpha.2` sorts below `0.2.2-rc.1`, which is how
26
- // 1.0.0 locked out the rc hosts it was meant to serve; `<0.3.0-0` keeps every
27
- // 0.2.x prerelease admissible and still rejects 0.3.0's own prereleases.
28
- for (const version of [
29
- '0.2.1-rc.2',
30
- '0.2.1-rc.3',
31
- '0.2.1-rc.4',
32
- '0.2.1-rc.5',
33
- '0.2.2-alpha.2',
34
- '0.2.2-alpha.3',
35
- '0.2.2-rc.1',
36
- '0.2.2',
37
- ]) {
38
- assert.equal(semver.satisfies(version, engines.dsh, { includePrerelease: true }), true, version)
39
- }
40
- for (const version of ['0.2.0', '0.2.1-alpha.5', '0.2.1-rc.1', '0.3.0-rc.1', '0.3.0', '1.0.0']) {
41
- assert.equal(semver.satisfies(version, engines.dsh, { includePrerelease: true }), false, version)
42
- }
43
- })
44
-
45
- test('notices include JSZip prebundled libraries and the zlib copyright', async () => {
46
- const notices = await read('THIRD-PARTY-NOTICES.txt')
47
- for (const name of ['pako@1.0.11', 'lie@3.3.0', 'immediate@3.0.6', 'setimmediate@1.0.5', 'crc-32@1.2.2', 'Jean-loup Gailly and Mark Adler']) {
48
- assert.ok(notices.includes(name), `Missing third-party notice: ${name}`)
49
- }
50
- })
51
-
52
- test('市场索引保留固定提交来源、版本唯一和宿主兼容范围', async () => {
53
- const manifest = JSON.parse(await read('package.json'))
54
- const index = JSON.parse(await read('index.json'))
55
- assert.equal(index.format, 1)
56
- const entry = index.plugins.find(plugin => plugin.name === manifest.name)
57
- assert.ok(entry)
58
- assert.equal(entry.author, manifest.author)
59
- assert.equal(entry.repository.url + '.git', manifest.repository.url)
60
- await access(new URL(entry.icon, root))
61
- assert.ok(entry.versions.length)
62
- assert.equal(new Set(entry.versions.map(version => version.version)).size, entry.versions.length)
63
- for (const version of entry.versions) {
64
- assert.match(version.version, /^\d+\.\d+\.\d+$/u)
65
- assert.ok(Number.isSafeInteger(version.publishTimestamp) && version.publishTimestamp > 0)
66
- if (version.version === manifest.version) assert.equal(version.engines.dsh, manifest.engines.dsh)
67
- else assert.match(version.engines.dsh, /^(?:\^|~|>=)?\d+\.\d+\.\d+(?:-[\w.-]+)?/u)
68
- assert.equal(version.source.type, 'git')
69
- assert.equal(version.source.url, entry.repository.url)
70
- assert.match(version.source.commit, /^[a-f0-9]{40}$/u)
71
- }
72
- })
73
-
74
- test('README local links resolve and installation contains no personal absolute path', async () => {
75
- const readme = await read('README.md')
76
- assert.doesNotMatch(readme, /\/Users\/|C:\\Users\\/u)
77
- const manifest = JSON.parse(await read('package.json'))
78
- // Source docs describe the version being built. The public index is appended
79
- // only after release, when its immutable source SHA and timestamp are known.
80
- assert.ok(readme.includes(`github:gongfpp/dsh-novel-fish#v${manifest.version}`), 'installation matches the release being built')
81
- assert.ok(readme.includes(`@gongfpp/dsh-novel-fish@${manifest.version}`))
82
- for (const match of readme.matchAll(/\]\(([^)]+)\)/gu)) {
83
- const path = match[1].replace(/^<|>$/gu, '').split('#')[0]
84
- if (!path || /^[a-z]+:/iu.test(path)) continue
85
- await access(new URL(path, root))
86
- }
87
- })
@@ -1,182 +0,0 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import { DEFAULT_SEGMENT_LENGTH, parseTextBook, segmentChapters } from '../src/segments.js'
4
-
5
- test('Markdown headings become chapter labels and paragraph breaks survive import', () => {
6
- const result = parseTextBook('# 序章\n\n第一段。\n\n第二段。\n\n## 章节二\n\n正文。', 'md', 600)
7
- assert.deepEqual(result.chapters.map(chapter => chapter.title), ['序章', '章节二'])
8
- assert.equal(result.chapters[0].text, '第一段。\n\n第二段。')
9
- assert.equal(result.segments[0].chapterTitle, '序章')
10
- assert.equal(result.segments[0].text, '第一段。\n\n第二段。')
11
- })
12
-
13
- test('TXT chapter headings are kept as chapter labels', () => {
14
- const result = parseTextBook('第一章 初见\n\n内容甲。\n\n第二章 重逢\n\n内容乙。', 'txt', 600)
15
- assert.deepEqual(result.chapters.map(chapter => chapter.title), ['第一章 初见', '第二章 重逢'])
16
- assert.deepEqual(result.segments.map(segment => segment.text), ['内容甲。', '内容乙。'])
17
- })
18
-
19
- test('TXT narrative starting with an ordinal stays in the readable body', () => {
20
- const prose = '第二天,他回到家里,看见一封信。'
21
- const result = parseTextBook(`第一章 初见\n\n${prose}\n\n他读完信后,缓缓坐下。`, 'txt', 600)
22
- assert.deepEqual(result.chapters.map(chapter => chapter.title), ['第一章 初见'])
23
- assert.equal(result.segments[0].text, `${prose}\n\n他读完信后,缓缓坐下。`)
24
- assert.equal(parseTextBook(prose, 'txt').segments[0].text, prose)
25
- })
26
-
27
- test('TXT headings require a chapter number immediately followed by a chapter unit', () => {
28
- const result = parseTextBook('第十二回 故人重来\n\n内容甲。\n\nChapter 13 The Letter\n\n内容乙。', 'txt')
29
- assert.deepEqual(result.chapters.map(chapter => chapter.title), ['第十二回 故人重来', 'Chapter 13 The Letter'])
30
- })
31
-
32
- test('long text is split around target length without breaking Unicode code points', () => {
33
- const source = '猫🐈'.repeat(401)
34
- const segments = segmentChapters([{ title: '正文', text: source }], 600)
35
- assert.ok(segments.every(segment => [...segment.text].length <= 600))
36
- assert.equal(segments.map(segment => segment.text).join(''), source)
37
- })
38
-
39
- test('paragraph boundaries take priority within the default display-width budget', () => {
40
- assert.equal(DEFAULT_SEGMENT_LENGTH, 800)
41
- const segments = segmentChapters([{ title: '正文', text: `${'甲'.repeat(300)}。\n\n${'乙'.repeat(300)}。` }])
42
- assert.equal(segments.length, 2)
43
- assert.ok(segments.every(segment => [...segment.text].length < 600))
44
- })
45
-
46
- test('empty plain text is rejected instead of importing an unreadable book', () => {
47
- assert.throws(() => parseTextBook(' \n\n ', 'txt'), /没有可阅读的正文文本/u)
48
- })
49
-
50
- // Synthetic narrative fixtures, not quotations or claims about a real edition.
51
- export const englishNarrative = 'When I reached the little office by the river, the clerk had already put away his books. "You must come again tomorrow," he said, looking from my muddy coat to the sealed envelope. I explained that the gentleman was leaving on the morning train, and that a delay of even one night might change everything. '
52
- export const chineseNarrative = '天色已经暗了下来,街上的人却还没有散。他把车停在门口,抹去额上的汗,望了望远处亮着灯的窗口。“再等一会儿吧,”老人说,“也许他马上就回来了。”他没有回答,只把那封信仔细地放回衣袋里。'
53
- export const narrativeCorpora = {
54
- english: Array.from({ length: 36 }, (_, i) => i % 6 === 0 ? '"Not tonight," he replied.' : englishNarrative.repeat(1 + i % 5).trim()).join('\n\n'),
55
- chinese: Array.from({ length: 36 }, (_, i) => i % 6 === 0 ? '“还早呢。”' : chineseNarrative.repeat(1 + i % 5)).join('\n\n'),
56
- dialogue: Array.from({ length: 90 }, (_, i) => i % 2 ? '“你当真要走?”' : '“天亮以前,我就得赶到城门外。”').join('\n\n'),
57
- }
58
- const compact = text => text.replace(/\s/gu, '')
59
- const passages = (text, target) => segmentChapters([{ title: 'Sample', text }], target).map(segment => segment.text)
60
- function displayUnits(text) {
61
- return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), ({ segment }) => {
62
- if (segment === '\n') return 40
63
- if (segment === '\t') return 4
64
- return /[\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
65
- }).reduce((sum, value) => sum + value, 0)
66
- }
67
-
68
- for (const [language, text] of Object.entries(narrativeCorpora)) {
69
- test(`${language} narrative balances short dialogue and long paragraphs without losing body text`, () => {
70
- const result = passages(text)
71
- assert.ok(result.length > 2, 'a complete chapter must not become one huge passage')
72
- assert.equal(compact(result.join('')), compact(text))
73
- assert.ok(result.every(part => displayUnits(part) <= 1000))
74
- assert.ok(result.every(part => displayUnits(part) >= 400), 'avoid isolated short paragraphs and short tails')
75
- if (language === 'english') {
76
- assert.ok(result.length < 45, 'do not require a click for each short English fragment')
77
- assert.ok(result.every(part => (part.match(/\b[A-Za-z]+\b/gu) ?? []).length >= 60))
78
- }
79
- if (language === 'chinese') assert.ok(result.every(part => [...part].length <= 500))
80
- if (language === 'dialogue') assert.ok(result.every(part => part.split('\n').length <= 22), 'blank lines count toward the visible reading budget')
81
- })
82
- }
83
-
84
- test('targetLength means a soft half-width budget with a 1.25x hard limit, not raw characters', () => {
85
- const latin = passages('a'.repeat(4000))
86
- const han = passages('甲'.repeat(2000))
87
- assert.equal(latin.length, han.length)
88
- assert.deepEqual(latin.map(part => displayUnits(part)), han.map(part => displayUnits(part)))
89
- assert.ok(latin.every(part => [...part].length === DEFAULT_SEGMENT_LENGTH))
90
- for (const target of [1, 2, 7, 31, 600]) {
91
- assert.ok(passages('abcd'.repeat(1800), target).every(part => displayUnits(part) <= Math.floor(target * 1.25)))
92
- }
93
- })
94
-
95
- test('sentence and quotation boundaries preserve exact intra-paragraph spacing', () => {
96
- for (const text of [englishNarrative.repeat(14).trim(), chineseNarrative.repeat(30)]) {
97
- const result = passages(text)
98
- assert.equal(compact(result.join('')), compact(text))
99
- assert.ok(result.every(part => text.includes(part)), 'never insert spaces into Chinese prose or rewrite English spacing')
100
- assert.ok(result.slice(0, -1).every(part => /[.!?。!?][”’"'」』】))]?$/u.test(part)))
101
- assert.ok(result.every(part => !/^[”’」』】))]/u.test(part)), 'closing quotes stay with preceding sentences')
102
- }
103
- })
104
-
105
- test('punctuation-free English splits at complete words unless one token exceeds the hard cap', () => {
106
- const words = Array.from({ length: 1100 }, (_, i) => `word${i}`)
107
- const result = passages(words.join(' '), 100)
108
- assert.deepEqual(result.join(' ').split(/\s+/u), words)
109
- assert.ok(result.every(part => displayUnits(part) <= 125))
110
- const hugeWord = 'pneumonoultramicroscopic'.repeat(500)
111
- assert.equal(passages(hugeWord, 100).join(''), hugeWord)
112
- // A long but still fitting word cannot be split just to fill the target.
113
- for (const [prefix, word] of [['a'.repeat(20), 'b'.repeat(980)], ['a'.repeat(300), 'b'.repeat(800)], ['a'.repeat(990), 'b'.repeat(80)]]) {
114
- assert.deepEqual(passages(`${prefix} ${word}`), [prefix, word])
115
- }
116
- })
117
-
118
- test('commas are a fallback after sentences and do not create unbounded Chinese clauses', () => {
119
- const clause = '他把信放回衣袋里,又在门前等了一阵,街上渐渐没有了行人,'
120
- const text = clause.repeat(60)
121
- const result = passages(text, 200)
122
- assert.equal(result.join(''), text)
123
- assert.ok(result.every(part => displayUnits(part) <= 250))
124
- assert.ok(result.slice(0, -1).every(part => part.endsWith(',')))
125
- })
126
-
127
- test('a short final paragraph is balanced with its predecessor, but never with the next chapter', () => {
128
- const text = `${'甲'.repeat(390)}。\n\n最后一封信。`
129
- const result = passages(text)
130
- assert.equal(result.length, 1)
131
- const split = passages(`${'alpha '.repeat(165)}${'bravo '.repeat(14)}`)
132
- assert.equal(split.length, 2)
133
- assert.ok(split.every(part => part.length >= 400))
134
- const chapters = segmentChapters([{ title: 'Chapter I', text }, { title: 'Chapter II', text: 'Next day.' }])
135
- assert.deepEqual(chapters.map(part => part.chapterTitle), ['Chapter I', 'Chapter II'])
136
- assert.deepEqual(chapters.map(part => part.chapterIndex), [0, 1])
137
- assert.equal(chapters[1].text, 'Next day.')
138
- })
139
-
140
- test('TXT Roman numeral headings are chapter boundaries, not prose or merged labels', () => {
141
- const book = parseTextBook('Chapter I\n\nFirst short passage.\n\nChapter II The visitor\n\nAnother short passage.\n\nChapter in the old house was unfinished.', 'txt')
142
- assert.deepEqual(book.chapters.map(chapter => chapter.title), ['Chapter I', 'Chapter II The visitor'])
143
- assert.equal(book.segments.length, 2)
144
- assert.match(book.segments[1].text, /Chapter in the old house/u)
145
- })
146
-
147
- test('grapheme clusters, flags, combining accents and ZWJ families survive every cut', () => {
148
- const tokens = ['👨‍👩‍👧‍👦', '🇨🇳', 'e\u0301', '👍🏽', '猫']
149
- const text = tokens.join('').repeat(300)
150
- const expected = Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), item => item.segment)
151
- const result = passages(text, 7)
152
- assert.equal(result.join(''), text)
153
- assert.deepEqual(result.flatMap(part => Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(part), item => item.segment)), expected)
154
- assert.ok(result.every(part => displayUnits(part) <= 8))
155
- assert.equal(passages('👨‍👩‍👧‍👦', 1)[0], '👨‍👩‍👧‍👦', 'one indivisible grapheme wins over a tiny budget')
156
- })
157
-
158
- test('fallback without Intl.Segmenter remains Unicode-safe and splits Latin full stops', t => {
159
- const original = Intl.Segmenter
160
- Intl.Segmenter = undefined
161
- t.after(() => { Intl.Segmenter = original })
162
- const source = `Mr. Green waited. Then he went home. ${'👨‍👩‍👧‍👦🇨🇳e\u0301👍🏽'.repeat(180)}`
163
- const result = passages(source, 45)
164
- assert.equal(compact(result.join('')), compact(source))
165
- assert.ok(result.every(part => !/^[\p{Mark}\p{Emoji_Modifier}\u200d]/u.test(part) && !part.endsWith('\u200d')))
166
- const prose = passages('He waited at the door. '.repeat(40).trim(), 80)
167
- assert.ok(prose.every(part => part.endsWith('.')))
168
- })
169
-
170
- test('large punctuation-free chapters and newline-only tails terminate within bounded passages', { timeout: 4000 }, () => {
171
- for (const source of ['字'.repeat(120000), 'x'.repeat(120000), 'word\n'.repeat(6000), `${'甲'.repeat(900)}\n\n `]) {
172
- const result = passages(source)
173
- assert.equal(compact(result.join('')), compact(source))
174
- assert.ok(result.every(part => part.length && displayUnits(part) <= 1000))
175
- }
176
- })
177
-
178
- test('invalid targets reject immediately rather than causing an infinite split loop', () => {
179
- for (const value of [0, -1, 0.5, Infinity, NaN, '600', Number.MAX_SAFE_INTEGER + 1]) {
180
- assert.throws(() => passages('正文', value), RangeError)
181
- }
182
- })