dsh-pdf-workbench 1.4.1 → 1.5.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.
- package/README.md +108 -78
- package/assets/screenshot-hero.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-env.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/assets/screenshot-shelf.jpg +0 -0
- package/client.js +4106 -469
- package/docs/LAYOUT.md +56 -0
- package/docs/RELEASE.md +8 -0
- package/docs/TESTING.md +16 -0
- package/docs/ci.md +18 -13
- package/docs/copy/templates.md +4 -4
- package/docs/decisions.md +119 -0
- package/docs/features.md +14 -8
- package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
- package/docs/roles/{release-manager.md → ci.md} +37 -47
- package/docs/roles/programmer.md +45 -59
- package/docs/roles/requirements.md +68 -0
- package/docs/todo.md +590 -32
- package/index.js +337 -1
- package/package.json +1 -1
- package/screenshots.json +6 -4
- package/src/host/backup.js +172 -33
- package/src/host/book-wizard.js +454 -0
- package/src/host/digest.js +4 -0
- package/src/host/engine.js +88 -0
- package/src/host/exports.js +159 -0
- package/src/host/http.js +28 -1
- package/src/host/imports.js +650 -0
- package/src/host/index-source.js +117 -11
- package/src/host/library-export.js +162 -0
- package/src/host/pdf-source.js +6 -2
- package/src/host/routes.js +1020 -120
- package/src/host/shortcut.js +238 -0
- package/src/host/storage.js +421 -0
- package/src/host/translate-blocks.js +49 -45
- package/src/host/translate-job.js +37 -10
- package/src/host/translate.js +19 -45
- package/src/host/translation-cache.js +209 -0
- package/src/host/typst-install.js +132 -0
- package/src/host/zip.js +486 -4
- package/tools/latex_to_typst.py +1353 -0
- package/tools/md2overlay.py +147 -152
- package/tools/md2overlay_typst.py +312 -0
- package/tools/md2typst.py +818 -0
- package/tools/overlay_layout.py +332 -0
- package/tools/pdf_blocks.py +82 -10
- package/tools/realign_overlay.py +4 -1
- package/tools/rebuild_overlay.py +3 -1
- package/tools/split_pdf.py +158 -0
- package/tools/typst_runtime.py +98 -0
- package/vendor/katex/LICENSE +21 -0
- package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- package/vendor/katex/katex.min.css +1 -0
- package/vendor/katex/katex.min.js +1 -0
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
- package/docs/boss-handover.md +0 -84
- package/docs/roles/auditor.md +0 -123
- package/docs/roles/boss.md +0 -162
- package/docs/roles/code-reviewer.md +0 -132
- package/docs/roles/feature-inventory.md +0 -119
- package/docs/roles/feedback-collector.md +0 -105
- package/docs/roles/tester.md +0 -140
- package/docs/roles/ui-copywriter.md +0 -122
- package/src/host/book-import.js +0 -98
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read the target path out of a Windows Shell Link (`.lnk`) file.
|
|
3
|
+
*
|
|
4
|
+
* The browser uploads the shortcut's *bytes*, so the Host has to rebuild the
|
|
5
|
+
* target path from the file itself (MS-SHLLINK) before it can read that file.
|
|
6
|
+
* Only the fields needed to find one path are read, and every offset is bounds
|
|
7
|
+
* checked because the bytes come from the user.
|
|
8
|
+
*
|
|
9
|
+
* Two details matter in practice:
|
|
10
|
+
*
|
|
11
|
+
* - A link saved by `WScript.Shell` almost always carries the optional
|
|
12
|
+
* LinkTargetIDList, so the LinkInfo section does *not* start at 0x4C; the
|
|
13
|
+
* IDList length at 0x4C decides where it starts.
|
|
14
|
+
* - The ANSI `LocalBasePath` is written in the system code page (GBK on a
|
|
15
|
+
* Chinese Windows), while the Unicode copy only exists when
|
|
16
|
+
* `LinkInfoHeaderSize >= 0x24` — which is not guaranteed even for paths with
|
|
17
|
+
* Chinese characters. The Unicode copy wins when present, and the ANSI copy
|
|
18
|
+
* is decoded as UTF-8, then GBK, then latin1.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-pdf-workbench/shortcut
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Shell Link header size, fixed by MS-SHLLINK. */
|
|
24
|
+
const HEADER_SIZE = 0x4c
|
|
25
|
+
|
|
26
|
+
/** LinkCLSID {00021401-0000-0000-C000-000000000046}. */
|
|
27
|
+
const LINK_CLSID = Buffer.from('0114020000000000c000000000000046', 'hex')
|
|
28
|
+
|
|
29
|
+
/** `LinkFlags` bit: a LinkTargetIDList follows the header. */
|
|
30
|
+
const FLAG_HAS_ID_LIST = 0x01
|
|
31
|
+
|
|
32
|
+
/** `LinkFlags` bit: a LinkInfo section follows. */
|
|
33
|
+
const FLAG_HAS_LINK_INFO = 0x02
|
|
34
|
+
|
|
35
|
+
/** `LinkInfoHeaderSize` of the oldest layout: no Unicode offsets. */
|
|
36
|
+
const LINK_INFO_HEADER_BASE = 0x1c
|
|
37
|
+
|
|
38
|
+
/** `LinkInfoHeaderSize` from which the Unicode path offsets exist. */
|
|
39
|
+
const LINK_INFO_HEADER_UNICODE = 0x24
|
|
40
|
+
|
|
41
|
+
/** `LinkInfoFlags` bit: VolumeID and LocalBasePath (a local target). */
|
|
42
|
+
const LINK_INFO_HAS_VOLUME = 0x01
|
|
43
|
+
|
|
44
|
+
/** `LinkInfoFlags` bit: CommonNetworkRelativeLink (a network target). */
|
|
45
|
+
const LINK_INFO_HAS_NETWORK = 0x02
|
|
46
|
+
|
|
47
|
+
/** GBK decoder for the ANSI copy on Chinese Windows; null when ICU lacks it. */
|
|
48
|
+
const gbk = (() => {
|
|
49
|
+
try {
|
|
50
|
+
return new TextDecoder('gbk')
|
|
51
|
+
} catch {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
})()
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {Buffer} bytes - link bytes.
|
|
58
|
+
* @param {number} offset - absolute offset.
|
|
59
|
+
* @returns {number|null} a little-endian uint32, or null when out of range.
|
|
60
|
+
*/
|
|
61
|
+
function u32(bytes, offset) {
|
|
62
|
+
if (offset < 0 || offset + 4 > bytes.length) return null
|
|
63
|
+
return bytes.readUInt32LE(offset)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {Buffer} bytes - link bytes.
|
|
68
|
+
* @param {number} offset - absolute offset.
|
|
69
|
+
* @returns {number|null} a little-endian uint16, or null when out of range.
|
|
70
|
+
*/
|
|
71
|
+
function u16(bytes, offset) {
|
|
72
|
+
if (offset < 0 || offset + 2 > bytes.length) return null
|
|
73
|
+
return bytes.readUInt16LE(offset)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Decode a path the writer stored as ANSI: UTF-8 when it is valid (a UTF-8
|
|
78
|
+
* locale), else GBK (Chinese Windows), else latin1 so the bytes stay readable.
|
|
79
|
+
* @param {Buffer} bytes - raw string bytes.
|
|
80
|
+
* @returns {string} the decoded text.
|
|
81
|
+
*/
|
|
82
|
+
function decodeAnsi(bytes) {
|
|
83
|
+
if (bytes.length === 0) return ''
|
|
84
|
+
if (!bytes.some(byte => byte > 0x7f)) return bytes.toString('latin1')
|
|
85
|
+
try {
|
|
86
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes)
|
|
87
|
+
} catch {
|
|
88
|
+
if (gbk !== null) {
|
|
89
|
+
const text = gbk.decode(bytes)
|
|
90
|
+
if (!text.includes('\uFFFD')) return text
|
|
91
|
+
}
|
|
92
|
+
return bytes.toString('latin1')
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Read one NUL-terminated string that must end before `end`.
|
|
98
|
+
* @param {Buffer} bytes - link bytes.
|
|
99
|
+
* @param {number} start - absolute offset of the first byte.
|
|
100
|
+
* @param {number} end - exclusive end of the containing section.
|
|
101
|
+
* @param {boolean} unicode - UTF-16LE (two NUL bytes) instead of ANSI.
|
|
102
|
+
* @returns {string|null} the text, or null when the section is malformed.
|
|
103
|
+
*/
|
|
104
|
+
function readTerminated(bytes, start, end, unicode) {
|
|
105
|
+
if (start <= 0 || start >= end) return null
|
|
106
|
+
if (unicode) {
|
|
107
|
+
let stop = start
|
|
108
|
+
while (stop + 1 < end && !(bytes[stop] === 0 && bytes[stop + 1] === 0)) stop += 2
|
|
109
|
+
if (stop + 1 >= end) return null
|
|
110
|
+
return bytes.subarray(start, stop).toString('utf16le')
|
|
111
|
+
}
|
|
112
|
+
let stop = start
|
|
113
|
+
while (stop < end && bytes[stop] !== 0) stop += 1
|
|
114
|
+
if (stop >= end) return null
|
|
115
|
+
return decodeAnsi(bytes.subarray(start, stop))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The first non-empty string, so a present-but-empty Unicode copy falls back to
|
|
120
|
+
* the ANSI one instead of producing no path at all.
|
|
121
|
+
* @param {...(string|null)} values - candidates in priority order.
|
|
122
|
+
* @returns {string|null} the chosen text.
|
|
123
|
+
*/
|
|
124
|
+
function firstText(...values) {
|
|
125
|
+
for (const value of values) {
|
|
126
|
+
if (typeof value === 'string' && value !== '') return value
|
|
127
|
+
}
|
|
128
|
+
return null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Join `LocalBasePath` with the common path suffix. A local file link usually
|
|
133
|
+
* carries the whole path in the base and an empty or `\` suffix.
|
|
134
|
+
* @param {string} base - base path.
|
|
135
|
+
* @param {string|null} suffix - common path suffix.
|
|
136
|
+
* @returns {string} the full path.
|
|
137
|
+
*/
|
|
138
|
+
function joinPath(base, suffix) {
|
|
139
|
+
const path = base.replace(/[\\/]+$/, '')
|
|
140
|
+
if (suffix === null || suffix === '' || suffix === '\\') return path
|
|
141
|
+
if (path.toLowerCase().endsWith(suffix.toLowerCase())) return path
|
|
142
|
+
return suffix.startsWith('\\') ? `${path}${suffix}` : `${path}\\${suffix}`
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Read `NetName` from a CommonNetworkRelativeLink structure.
|
|
147
|
+
* @param {Buffer} bytes - link bytes.
|
|
148
|
+
* @param {number} start - absolute offset of the structure.
|
|
149
|
+
* @param {number} end - exclusive end of the LinkInfo section.
|
|
150
|
+
* @returns {string|null} the share path (`\\server\share`), or null.
|
|
151
|
+
*/
|
|
152
|
+
function readNetName(bytes, start, end) {
|
|
153
|
+
const nameOffset = u32(bytes, start)
|
|
154
|
+
if (nameOffset === null || nameOffset < 0x14) return null
|
|
155
|
+
let unicodeName = null
|
|
156
|
+
// NetNameOffsetUnicode sits at +0x0C and only exists when NetName is not the
|
|
157
|
+
// first string (offset > 0x14).
|
|
158
|
+
if (nameOffset > 0x14) {
|
|
159
|
+
const unicodeOffset = u32(bytes, start + 0x0c)
|
|
160
|
+
if (unicodeOffset !== null && unicodeOffset !== 0) {
|
|
161
|
+
unicodeName = readTerminated(bytes, start + unicodeOffset, end, true)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return firstText(unicodeName, readTerminated(bytes, start + nameOffset, end, false))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Read one LinkInfo section (a local or a network target).
|
|
169
|
+
* @param {Buffer} bytes - link bytes.
|
|
170
|
+
* @param {number} start - absolute offset of the section.
|
|
171
|
+
* @returns {{ path: string }|null} the target path, or null.
|
|
172
|
+
*/
|
|
173
|
+
function readLinkInfo(bytes, start) {
|
|
174
|
+
const size = u32(bytes, start)
|
|
175
|
+
const headerSize = u32(bytes, start + 4)
|
|
176
|
+
const flags = u32(bytes, start + 8)
|
|
177
|
+
if (size === null || headerSize === null || flags === null) return null
|
|
178
|
+
if (headerSize < LINK_INFO_HEADER_BASE || size < headerSize) return null
|
|
179
|
+
const end = Math.min(start + size, bytes.length)
|
|
180
|
+
const localOffset = u32(bytes, start + 0x10)
|
|
181
|
+
const networkOffset = u32(bytes, start + 0x14)
|
|
182
|
+
const suffixOffset = u32(bytes, start + 0x18)
|
|
183
|
+
if (localOffset === null || networkOffset === null || suffixOffset === null) return null
|
|
184
|
+
// The Unicode offsets must beat the ANSI ones: the ANSI copy is in the
|
|
185
|
+
// writer's code page and mangles Chinese paths when decoded naively.
|
|
186
|
+
let localUnicode = null
|
|
187
|
+
let suffixUnicode = null
|
|
188
|
+
if (headerSize >= LINK_INFO_HEADER_UNICODE) {
|
|
189
|
+
localUnicode = u32(bytes, start + 0x1c)
|
|
190
|
+
suffixUnicode = u32(bytes, start + 0x20)
|
|
191
|
+
}
|
|
192
|
+
const suffix = firstText(
|
|
193
|
+
suffixUnicode === null || suffixUnicode === 0 ? null : readTerminated(bytes, start + suffixUnicode, end, true),
|
|
194
|
+
suffixOffset === 0 ? null : readTerminated(bytes, start + suffixOffset, end, false),
|
|
195
|
+
)
|
|
196
|
+
if ((flags & LINK_INFO_HAS_VOLUME) !== 0) {
|
|
197
|
+
const base = firstText(
|
|
198
|
+
localUnicode === null || localUnicode === 0 ? null : readTerminated(bytes, start + localUnicode, end, true),
|
|
199
|
+
localOffset === 0 ? null : readTerminated(bytes, start + localOffset, end, false),
|
|
200
|
+
)
|
|
201
|
+
return base === null ? null : { path: joinPath(base, suffix) }
|
|
202
|
+
}
|
|
203
|
+
if ((flags & LINK_INFO_HAS_NETWORK) !== 0 && networkOffset !== 0) {
|
|
204
|
+
const netName = readNetName(bytes, start + networkOffset, end)
|
|
205
|
+
return netName === null ? null : { path: joinPath(netName, suffix) }
|
|
206
|
+
}
|
|
207
|
+
return null
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The target path stored in one Windows shortcut.
|
|
212
|
+
*
|
|
213
|
+
* Local targets come from `LocalBasePath` (+ common suffix); network targets come
|
|
214
|
+
* from `CommonNetworkRelativeLink.NetName` and are returned as the `\\server\...`
|
|
215
|
+
* path they are, so the caller can refuse them with its own message. Anything
|
|
216
|
+
* malformed, truncated, or unreadable yields null instead of throwing.
|
|
217
|
+
*
|
|
218
|
+
* @param {Buffer} bytes - the uploaded `.lnk` bytes.
|
|
219
|
+
* @returns {{ path: string }|null} the target path, or null when there is none.
|
|
220
|
+
*/
|
|
221
|
+
export function resolveShortcutTarget(bytes) {
|
|
222
|
+
try {
|
|
223
|
+
if (!Buffer.isBuffer(bytes) || bytes.length < HEADER_SIZE) return null
|
|
224
|
+
if (bytes.readUInt32LE(0) !== HEADER_SIZE) return null
|
|
225
|
+
if (!bytes.subarray(4, 20).equals(LINK_CLSID)) return null
|
|
226
|
+
const flags = bytes.readUInt32LE(0x14)
|
|
227
|
+
if ((flags & FLAG_HAS_LINK_INFO) === 0) return null
|
|
228
|
+
let offset = HEADER_SIZE
|
|
229
|
+
if ((flags & FLAG_HAS_ID_LIST) !== 0) {
|
|
230
|
+
const idListSize = u16(bytes, offset)
|
|
231
|
+
if (idListSize === null) return null
|
|
232
|
+
offset += 2 + idListSize
|
|
233
|
+
}
|
|
234
|
+
return readLinkInfo(bytes, offset)
|
|
235
|
+
} catch {
|
|
236
|
+
return null
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the plugin's disk space goes, and which of it may be deleted.
|
|
3
|
+
*
|
|
4
|
+
* The panel only ever answers two questions: "what is using space" and "which
|
|
5
|
+
* of that is rebuildable". Reading is always safe. Deleting is split by risk:
|
|
6
|
+
*
|
|
7
|
+
* - `rebuild` — translation caches, finished job state, upload scratch, the
|
|
8
|
+
* staging tree a crashed packing job left behind. The plugin recreates any of
|
|
9
|
+
* it on demand, so one click may remove all of it.
|
|
10
|
+
* - `manual` — packages the user asked for (`backup/*.zip`), pre-import
|
|
11
|
+
* snapshots (the only copy of the state before an import), and `回收站/`
|
|
12
|
+
* (documents the user deleted but did not empty). These are only ever removed
|
|
13
|
+
* by an explicit user action with its own confirmation, never by the general
|
|
14
|
+
* cleanup and never automatically.
|
|
15
|
+
*
|
|
16
|
+
* Bookmarks, artifacts and PDFs are not listed at all: they are data, not cache
|
|
17
|
+
* (DEC-0014 §4). Symbolic links are skipped so a link cannot be followed out of
|
|
18
|
+
* a library and measured or deleted somewhere else.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-pdf-workbench/storage
|
|
21
|
+
*/
|
|
22
|
+
import { createHash } from 'node:crypto'
|
|
23
|
+
import { createReadStream } from 'node:fs'
|
|
24
|
+
import { readdir, readFile, rm, stat } from 'node:fs/promises'
|
|
25
|
+
import { dirname, join } from 'node:path'
|
|
26
|
+
import { isExportName } from './exports.js'
|
|
27
|
+
import { legacyTranslationRoot, translationRoot } from './translation-cache.js'
|
|
28
|
+
|
|
29
|
+
/** Book-import stage packages expire after two hours (the wizard's own rule). */
|
|
30
|
+
const STAGE_TTL = 2 * 60 * 60 * 1000
|
|
31
|
+
|
|
32
|
+
/** Upload scratch and page-export temp files die after an hour. */
|
|
33
|
+
const TMP_TTL = 60 * 60 * 1000
|
|
34
|
+
|
|
35
|
+
/** Library folder holding removed books and artifacts; never auto-emptied. */
|
|
36
|
+
const TRASH = '回收站'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Size, file count and newest mtime of one tree. Missing folders read as empty;
|
|
40
|
+
* symbolic links are skipped rather than followed. The newest file time is what
|
|
41
|
+
* "unused for N days" means: editing a file inside a folder does not update the
|
|
42
|
+
* folder's own mtime on Windows.
|
|
43
|
+
* @param {string} dir - folder to measure.
|
|
44
|
+
* @returns {Promise<{ bytes: number, files: number, latest: number }>} the total.
|
|
45
|
+
*/
|
|
46
|
+
async function measureTree(dir) {
|
|
47
|
+
let bytes = 0
|
|
48
|
+
let files = 0
|
|
49
|
+
let latest = 0
|
|
50
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
const path = join(dir, entry.name)
|
|
53
|
+
if (entry.isSymbolicLink()) continue
|
|
54
|
+
if (entry.isDirectory()) {
|
|
55
|
+
const nested = await measureTree(path)
|
|
56
|
+
bytes += nested.bytes
|
|
57
|
+
files += nested.files
|
|
58
|
+
latest = Math.max(latest, nested.latest)
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
if (!entry.isFile()) continue
|
|
62
|
+
const info = await stat(path).catch(() => null)
|
|
63
|
+
if (info === null) continue
|
|
64
|
+
bytes += info.size
|
|
65
|
+
files += 1
|
|
66
|
+
latest = Math.max(latest, info.mtimeMs)
|
|
67
|
+
}
|
|
68
|
+
return { bytes, files, latest }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Size, file count and newest mtime of one file or folder.
|
|
73
|
+
* @param {string} path - file or folder.
|
|
74
|
+
* @returns {Promise<{ bytes: number, files: number, latest: number }>} the total.
|
|
75
|
+
*/
|
|
76
|
+
async function measurePath(path) {
|
|
77
|
+
const info = await stat(path).catch(() => null)
|
|
78
|
+
if (info === null) return { bytes: 0, files: 0, latest: 0 }
|
|
79
|
+
if (info.isDirectory()) return measureTree(path)
|
|
80
|
+
return { bytes: info.size, files: 1, latest: info.mtimeMs }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Delete one file or folder, reporting whether it really went away. Windows can
|
|
85
|
+
* refuse a file another process holds open; that must not be counted as deleted.
|
|
86
|
+
* @param {string} path - file or folder.
|
|
87
|
+
* @returns {Promise<boolean>} true when the path is gone.
|
|
88
|
+
*/
|
|
89
|
+
async function removePath(path) {
|
|
90
|
+
try {
|
|
91
|
+
await rm(path, { recursive: true, force: true })
|
|
92
|
+
return true
|
|
93
|
+
} catch {
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Split `<dataDir>/backup` into the packages the user asked for and the
|
|
100
|
+
* leftovers of an interrupted packing/import.
|
|
101
|
+
* @param {string} dataDir - the plugin data folder.
|
|
102
|
+
* @returns {Promise<{ packages: { bytes: number, files: number }, staging: { bytes: number, files: number }, preImport: { bytes: number, files: number } }>} the split.
|
|
103
|
+
*/
|
|
104
|
+
async function measureBackup(dataDir) {
|
|
105
|
+
const root = join(dataDir, 'backup')
|
|
106
|
+
const result = {
|
|
107
|
+
packages: { bytes: 0, files: 0 },
|
|
108
|
+
staging: { bytes: 0, files: 0 },
|
|
109
|
+
preImport: { bytes: 0, files: 0 },
|
|
110
|
+
}
|
|
111
|
+
const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
if (entry.isSymbolicLink()) continue
|
|
114
|
+
const path = join(root, entry.name)
|
|
115
|
+
const nested = await measurePath(path)
|
|
116
|
+
if (entry.isDirectory() && entry.name.startsWith('staging-')) {
|
|
117
|
+
result.staging.bytes += nested.bytes
|
|
118
|
+
result.staging.files += nested.files
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
if (entry.name.startsWith('pre-import-')) {
|
|
122
|
+
result.preImport.bytes += nested.bytes
|
|
123
|
+
result.preImport.files += nested.files
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
if (entry.isFile() && isExportName(entry.name)) {
|
|
127
|
+
result.packages.bytes += nested.bytes
|
|
128
|
+
result.packages.files += nested.files
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return result
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Measure every folder the plugin owns. Read-only; safe to call while other
|
|
136
|
+
* work runs. A folder that does not exist contributes zero.
|
|
137
|
+
* @param {{ dataDir: string, libraries?: Array<{ libraryDir: string }> }} options - plugin data folder and registered libraries.
|
|
138
|
+
* @returns {Promise<{ total: { bytes: number, files: number }, areas: Array<{ key: string, bytes: number, files: number, safe: 'rebuild' | 'manual' }> }>} the report.
|
|
139
|
+
*/
|
|
140
|
+
export async function measureStorage(options) {
|
|
141
|
+
const dataDir = String(options.dataDir ?? '')
|
|
142
|
+
const libraries = (Array.isArray(options.libraries) ? options.libraries : [])
|
|
143
|
+
.filter(item => item !== null && typeof item === 'object' && typeof item.libraryDir === 'string' && item.libraryDir !== '')
|
|
144
|
+
let translation = { bytes: 0, files: 0 }
|
|
145
|
+
let trash = { bytes: 0, files: 0 }
|
|
146
|
+
for (const library of libraries) {
|
|
147
|
+
const cache = await measureTree(translationRoot(library))
|
|
148
|
+
translation = { bytes: translation.bytes + cache.bytes, files: translation.files + cache.files }
|
|
149
|
+
const removed = await measureTree(join(library.libraryDir, TRASH))
|
|
150
|
+
trash = { bytes: trash.bytes + removed.bytes, files: trash.files + removed.files }
|
|
151
|
+
}
|
|
152
|
+
const legacy = await measureTree(legacyTranslationRoot(dataDir))
|
|
153
|
+
const jobs = await measureTree(join(dataDir, 'translate-jobs'))
|
|
154
|
+
const exportJobs = await measureTree(join(dataDir, 'export-jobs'))
|
|
155
|
+
const tmp = await measureTree(join(dataDir, 'tmp'))
|
|
156
|
+
const backup = await measureBackup(dataDir)
|
|
157
|
+
// A migration package is dominated by the DSH session logs, so the panel has
|
|
158
|
+
// to show them; the folder only moves when plugin data sits in a profile. The
|
|
159
|
+
// home folder is derived the way `collectBackup` derives it.
|
|
160
|
+
const home = dirname(dataDir)
|
|
161
|
+
const sessions = await measureTree(join(home, 'sessions'))
|
|
162
|
+
const fonts = await measureTree(join(dataDir, 'fonts'))
|
|
163
|
+
const projcache = await measureTree(join(home, 'storages', 'session_projcache'))
|
|
164
|
+
const areas = [
|
|
165
|
+
{ key: 'sessions', ...sessions, safe: 'manual' },
|
|
166
|
+
{ key: 'fonts', ...fonts, safe: 'manual' },
|
|
167
|
+
{ key: 'projcache', ...projcache, safe: 'rebuild' },
|
|
168
|
+
{ key: 'translation', ...translation, safe: 'rebuild' },
|
|
169
|
+
{ key: 'legacy', ...legacy, safe: 'rebuild' },
|
|
170
|
+
{ key: 'jobs', bytes: jobs.bytes + exportJobs.bytes, files: jobs.files + exportJobs.files, safe: 'rebuild' },
|
|
171
|
+
{ key: 'tmp', ...tmp, safe: 'rebuild' },
|
|
172
|
+
{ key: 'staging', ...backup.staging, safe: 'rebuild' },
|
|
173
|
+
{ key: 'preImport', ...backup.preImport, safe: 'manual' },
|
|
174
|
+
{ key: 'packages', ...backup.packages, safe: 'manual' },
|
|
175
|
+
{ key: 'trash', ...trash, safe: 'manual' },
|
|
176
|
+
]
|
|
177
|
+
const total = areas.reduce((sum, area) => ({
|
|
178
|
+
bytes: sum.bytes + area.bytes,
|
|
179
|
+
files: sum.files + area.files,
|
|
180
|
+
}), { bytes: 0, files: 0 })
|
|
181
|
+
return { total, areas }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Delete whatever an interrupted run left behind: upload scratch and page-export
|
|
186
|
+
* temp files older than an hour, book-import stage packages older than two
|
|
187
|
+
* hours (the wizard's own deadline), and `staging-*` trees from a packing job
|
|
188
|
+
* that never finished. Nothing else is touched.
|
|
189
|
+
* @param {{ dataDir: string, busy?: boolean }} options - plugin data folder and whether a packing job holds a staging tree right now.
|
|
190
|
+
* @returns {Promise<{ removed: number, bytes: number }>} what was deleted.
|
|
191
|
+
*/
|
|
192
|
+
export async function cleanTemporary(options) {
|
|
193
|
+
const dataDir = String(options.dataDir ?? '')
|
|
194
|
+
const busy = options.busy === true
|
|
195
|
+
let removed = 0
|
|
196
|
+
let bytes = 0
|
|
197
|
+
const now = Date.now()
|
|
198
|
+
const tmpDir = join(dataDir, 'tmp')
|
|
199
|
+
const entries = await readdir(tmpDir, { withFileTypes: true }).catch(() => [])
|
|
200
|
+
for (const entry of entries) {
|
|
201
|
+
if (entry.isSymbolicLink()) continue
|
|
202
|
+
const path = join(tmpDir, entry.name)
|
|
203
|
+
const info = await stat(path).catch(() => null)
|
|
204
|
+
if (info === null) continue
|
|
205
|
+
const limit = /^stage-[0-9a-f-]{36}\.zip$/.test(entry.name) ? STAGE_TTL : TMP_TTL
|
|
206
|
+
if (now - info.mtimeMs < limit) continue
|
|
207
|
+
const size = await measurePath(path)
|
|
208
|
+
if (!(await removePath(path))) continue
|
|
209
|
+
removed += 1
|
|
210
|
+
bytes += size.bytes
|
|
211
|
+
}
|
|
212
|
+
// A running packing job owns the one staging tree that exists; without a job
|
|
213
|
+
// any `staging-*` folder is the debris of a crash.
|
|
214
|
+
if (!busy) {
|
|
215
|
+
const backupDir = join(dataDir, 'backup')
|
|
216
|
+
for (const entry of await readdir(backupDir, { withFileTypes: true }).catch(() => [])) {
|
|
217
|
+
if (!entry.isDirectory() || !entry.name.startsWith('staging-')) continue
|
|
218
|
+
const path = join(backupDir, entry.name)
|
|
219
|
+
const size = await measurePath(path)
|
|
220
|
+
if (!(await removePath(path))) continue
|
|
221
|
+
removed += 1
|
|
222
|
+
bytes += size.bytes
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return { removed, bytes }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Empty one library's `回收站`. Only ever called for an explicit user action:
|
|
230
|
+
* the folder holds books and artifacts the user deleted, not cache.
|
|
231
|
+
* @param {{ libraryDir: string }} library - the library to empty.
|
|
232
|
+
* @returns {Promise<{ removed: number, bytes: number }>} what was deleted.
|
|
233
|
+
*/
|
|
234
|
+
export async function emptyTrash(library) {
|
|
235
|
+
const libraryDir = String(library?.libraryDir ?? '')
|
|
236
|
+
if (libraryDir === '') return { removed: 0, bytes: 0 }
|
|
237
|
+
const trashDir = join(libraryDir, TRASH)
|
|
238
|
+
const info = await stat(trashDir).catch(() => null)
|
|
239
|
+
if (info === null || !info.isDirectory()) return { removed: 0, bytes: 0 }
|
|
240
|
+
let removed = 0
|
|
241
|
+
let bytes = 0
|
|
242
|
+
for (const entry of await readdir(trashDir, { withFileTypes: true }).catch(() => [])) {
|
|
243
|
+
if (entry.isSymbolicLink()) continue
|
|
244
|
+
const path = join(trashDir, entry.name)
|
|
245
|
+
const size = await measurePath(path)
|
|
246
|
+
if (!(await removePath(path))) continue
|
|
247
|
+
removed += 1
|
|
248
|
+
bytes += size.bytes
|
|
249
|
+
}
|
|
250
|
+
return { removed, bytes }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** One day, for the retention actions. */
|
|
254
|
+
const DAY = 24 * 60 * 60 * 1000
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Delete the `回收站` entries nothing touched for `days` days. Still an explicit
|
|
258
|
+
* action — the button is the retention policy, no timer deletes anything.
|
|
259
|
+
* @param {{ library: object, days: number }} options - the library and the retention window.
|
|
260
|
+
* @returns {Promise<{ removed: number, bytes: number }>} what was deleted.
|
|
261
|
+
*/
|
|
262
|
+
export async function pruneTrash(options) {
|
|
263
|
+
const libraryDir = String(options?.library?.libraryDir ?? '')
|
|
264
|
+
const days = Math.max(1, Math.round(Number(options?.days) || 30))
|
|
265
|
+
if (libraryDir === '') return { removed: 0, bytes: 0 }
|
|
266
|
+
const trashDir = join(libraryDir, TRASH)
|
|
267
|
+
const cutoff = Date.now() - days * DAY
|
|
268
|
+
let removed = 0
|
|
269
|
+
let bytes = 0
|
|
270
|
+
for (const entry of await readdir(trashDir, { withFileTypes: true }).catch(() => [])) {
|
|
271
|
+
if (entry.isSymbolicLink()) continue
|
|
272
|
+
const path = join(trashDir, entry.name)
|
|
273
|
+
const size = await measurePath(path)
|
|
274
|
+
if (size.latest === 0 || size.latest > cutoff) continue
|
|
275
|
+
if (!(await removePath(path))) continue
|
|
276
|
+
removed += 1
|
|
277
|
+
bytes += size.bytes
|
|
278
|
+
}
|
|
279
|
+
return { removed, bytes }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Delete the per-chapter translation caches of every library that have not been
|
|
284
|
+
* touched for `days` days. The caches are rebuildable by translating again, and
|
|
285
|
+
* the produced PDFs are not touched.
|
|
286
|
+
* @param {{ libraries: object[], days: number }} options - libraries and the retention window.
|
|
287
|
+
* @returns {Promise<{ removed: number, bytes: number }>} what was deleted.
|
|
288
|
+
*/
|
|
289
|
+
export async function pruneTranslationIdle(options) {
|
|
290
|
+
const days = Math.max(1, Math.round(Number(options?.days) || 30))
|
|
291
|
+
const cutoff = Date.now() - days * DAY
|
|
292
|
+
const libraries = (Array.isArray(options?.libraries) ? options.libraries : [])
|
|
293
|
+
.filter(item => item !== null && typeof item === 'object' && typeof item.libraryDir === 'string' && item.libraryDir !== '')
|
|
294
|
+
let removed = 0
|
|
295
|
+
let bytes = 0
|
|
296
|
+
for (const library of libraries) {
|
|
297
|
+
const root = translationRoot(library)
|
|
298
|
+
for (const book of await readdir(root, { withFileTypes: true }).catch(() => [])) {
|
|
299
|
+
if (!book.isDirectory() || book.isSymbolicLink()) continue
|
|
300
|
+
const bookDir = join(root, book.name)
|
|
301
|
+
for (const chapter of await readdir(bookDir, { withFileTypes: true }).catch(() => [])) {
|
|
302
|
+
if (!chapter.isDirectory() || chapter.isSymbolicLink()) continue
|
|
303
|
+
const dir = join(bookDir, chapter.name)
|
|
304
|
+
const size = await measureTree(dir)
|
|
305
|
+
if (size.latest === 0 || size.latest > cutoff) continue
|
|
306
|
+
if (!(await removePath(dir))) continue
|
|
307
|
+
removed += 1
|
|
308
|
+
bytes += size.bytes
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { removed, bytes }
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Drop job state files that nothing will resume: a state file untouched for
|
|
317
|
+
* `days` days that does not say `running`. Running jobs and their siblings are
|
|
318
|
+
* always kept.
|
|
319
|
+
* @param {{ dataDir: string, days: number }} options - plugin data folder and the retention window.
|
|
320
|
+
* @returns {Promise<{ removed: number, bytes: number }>} what was deleted.
|
|
321
|
+
*/export async function pruneStaleJobs(options) {
|
|
322
|
+
const dataDir = String(options?.dataDir ?? '')
|
|
323
|
+
const days = Math.max(1, Math.round(Number(options?.days) || 30))
|
|
324
|
+
const cutoff = Date.now() - days * DAY
|
|
325
|
+
let removed = 0
|
|
326
|
+
let bytes = 0
|
|
327
|
+
for (const folder of ['translate-jobs', 'export-jobs']) {
|
|
328
|
+
const dir = join(dataDir, folder)
|
|
329
|
+
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
330
|
+
if (!entry.isFile() || entry.isSymbolicLink()) continue
|
|
331
|
+
if (!entry.name.endsWith('.json')) continue
|
|
332
|
+
const path = join(dir, entry.name)
|
|
333
|
+
const info = await stat(path).catch(() => null)
|
|
334
|
+
if (info === null || info.mtimeMs > cutoff) continue
|
|
335
|
+
let running = false
|
|
336
|
+
try {
|
|
337
|
+
const state = JSON.parse(await readFile(path, 'utf8'))
|
|
338
|
+
running = state !== null && typeof state === 'object' && state.status === 'running'
|
|
339
|
+
} catch {
|
|
340
|
+
running = false
|
|
341
|
+
}
|
|
342
|
+
if (running) continue
|
|
343
|
+
const size = info.size
|
|
344
|
+
if (!(await removePath(path))) continue
|
|
345
|
+
removed += 1
|
|
346
|
+
bytes += size
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return { removed, bytes }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* SHA-256 of one file, streamed so a 2 GB PDF is not read into memory.
|
|
354
|
+
* @param {string} path - file to hash.
|
|
355
|
+
* @returns {Promise<string|null>} the hex digest, or null when unreadable.
|
|
356
|
+
*/
|
|
357
|
+
function hashOf(path) {
|
|
358
|
+
return new Promise(resolve => {
|
|
359
|
+
const hash = createHash('sha256')
|
|
360
|
+
const stream = createReadStream(path)
|
|
361
|
+
stream.on('data', chunk => hash.update(chunk))
|
|
362
|
+
stream.on('error', () => resolve(null))
|
|
363
|
+
stream.on('end', () => resolve(hash.digest('hex')))
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Group the library's PDFs by content. Report only: nothing is deleted, the user
|
|
369
|
+
* decides what to remove (their PDFs are theirs). Files are grouped by size
|
|
370
|
+
* first, so only same-size candidates are hashed.
|
|
371
|
+
* @param {{ library: object }} options - the library to scan.
|
|
372
|
+
* @returns {Promise<{ scanned: number, wasted: number, groups: Array<{ size: number, count: number, wasted: number, files: string[] }> }>} the report.
|
|
373
|
+
*/
|
|
374
|
+
export async function scanDuplicates(options) {
|
|
375
|
+
const libraryDir = String(options?.library?.libraryDir ?? '')
|
|
376
|
+
const report = { scanned: 0, wasted: 0, groups: [] }
|
|
377
|
+
if (libraryDir === '') return report
|
|
378
|
+
const candidates = []
|
|
379
|
+
const add = async (dir, prefix) => {
|
|
380
|
+
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
381
|
+
if (!entry.isFile() || entry.isSymbolicLink()) continue
|
|
382
|
+
if (!/\.pdf$/i.test(entry.name)) continue
|
|
383
|
+
const info = await stat(join(dir, entry.name)).catch(() => null)
|
|
384
|
+
if (info === null || info.size === 0) continue
|
|
385
|
+
candidates.push({ size: info.size, path: join(dir, entry.name), label: `${prefix}${entry.name}` })
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
await add(join(libraryDir, '整本'), '整本/')
|
|
389
|
+
for (const book of await readdir(join(libraryDir, '分片'), { withFileTypes: true }).catch(() => [])) {
|
|
390
|
+
if (!book.isDirectory() || book.isSymbolicLink()) continue
|
|
391
|
+
await add(join(libraryDir, '分片', book.name), `分片/${book.name}/`)
|
|
392
|
+
}
|
|
393
|
+
report.scanned = candidates.length
|
|
394
|
+
const bySize = new Map()
|
|
395
|
+
for (const item of candidates) {
|
|
396
|
+
const list = bySize.get(item.size) ?? []
|
|
397
|
+
list.push(item)
|
|
398
|
+
bySize.set(item.size, list)
|
|
399
|
+
}
|
|
400
|
+
const groups = []
|
|
401
|
+
for (const [size, list] of bySize) {
|
|
402
|
+
if (list.length < 2) continue
|
|
403
|
+
const byHash = new Map()
|
|
404
|
+
for (const item of list) {
|
|
405
|
+
const hash = await hashOf(item.path)
|
|
406
|
+
if (hash === null) continue
|
|
407
|
+
const bucket = byHash.get(hash) ?? []
|
|
408
|
+
bucket.push(item.label)
|
|
409
|
+
byHash.set(hash, bucket)
|
|
410
|
+
}
|
|
411
|
+
for (const files of byHash.values()) {
|
|
412
|
+
if (files.length < 2) continue
|
|
413
|
+
const wasted = size * (files.length - 1)
|
|
414
|
+
groups.push({ size, count: files.length, wasted, files: files.sort() })
|
|
415
|
+
report.wasted += wasted
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
groups.sort((left, right) => right.wasted - left.wasted)
|
|
419
|
+
report.groups = groups
|
|
420
|
+
return report
|
|
421
|
+
}
|