@ds-hu/dsh-bvi-local 0.0.0-stage → 0.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.
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Minimal streaming ZIP reader for the archive-only model variants.
3
+ *
4
+ * Three catalog variants (FunASR Nano MLT, Qwen3-ASR 1.7B and the optional punctuation model)
5
+ * are only distributed as GitHub release zips, so the local component has to unpack them without
6
+ * adding a dependency. This module reads the end-of-central-directory record and the central
7
+ * directory to locate members, then streams exactly the whitelisted members through
8
+ * `node:zlib`'s raw inflater into a temporary directory. Stored and deflated members are
9
+ * supported; ZIP64 and multi-volume archives are rejected explicitly.
10
+ *
11
+ * Security rules: the whitelist is the archive-internal layout recorded in the model catalog, so
12
+ * a member is extracted only when its **exact** central-directory name is listed there. Every
13
+ * other member is ignored (`__MACOSX/`, `.DS_Store`, README files, test audio). Absolute paths,
14
+ * drive letters, `..` segments, backslashes, encrypted members and symlinks reject the whole
15
+ * archive before anything is written. Each extracted member is hashed while streaming and must
16
+ * match the catalog's byte count and SHA-256 digest.
17
+ *
18
+ * @module @ds-hu/dsh-bvi-local/provision/archive
19
+ */
20
+ import { createHash, randomUUID } from 'node:crypto'
21
+ import { createReadStream, createWriteStream } from 'node:fs'
22
+ import { mkdir, open, rename, rm, stat } from 'node:fs/promises'
23
+ import { dirname, join, resolve, sep } from 'node:path'
24
+ import { Transform } from 'node:stream'
25
+ import { pipeline } from 'node:stream/promises'
26
+ import { createInflateRaw } from 'node:zlib'
27
+
28
+ /** End-of-central-directory signature (`PK\x05\x06`). */
29
+ const EOCD_SIGNATURE = 0x06054b50
30
+ /** Central-directory file header signature (`PK\x01\x02`). */
31
+ const CENTRAL_SIGNATURE = 0x02014b50
32
+ /** Local file header signature (`PK\x03\x04`). */
33
+ const LOCAL_SIGNATURE = 0x04034b50
34
+ /** Bytes in an end-of-central-directory record without a trailing comment. */
35
+ const EOCD_MIN_BYTES = 22
36
+ /** Largest ZIP comment allowed by the specification; bounds the tail scan. */
37
+ const MAX_COMMENT_BYTES = 0xffff
38
+ /** Bytes in a central-directory record without name/extra/comment fields. */
39
+ const CENTRAL_HEADER_BYTES = 46
40
+ /** Bytes in a local file header without name/extra fields. */
41
+ const LOCAL_HEADER_BYTES = 30
42
+ /** Defensive cap on the member count of a model archive. */
43
+ const MAX_ENTRIES = 100_000
44
+
45
+ /** One archive that cannot be used, carrying a stable machine code. */
46
+ export class ArchiveError extends Error {
47
+ /**
48
+ * @param {'format'|'unsafe-entry'|'layout'|'integrity'} code - stable code.
49
+ * @param {string} message - human-readable explanation.
50
+ * @param {ErrorOptions} [options] - native error options.
51
+ */
52
+ constructor(code, message, options) {
53
+ super(message, options)
54
+ this.name = 'ArchiveError'
55
+ this.code = code
56
+ }
57
+ }
58
+
59
+ /**
60
+ * @param {AbortSignal|undefined} signal - cancellation signal.
61
+ * @returns {void}
62
+ * @throws {Error} when the signal is already aborted.
63
+ */
64
+ function throwIfAborted(signal) {
65
+ if (signal !== undefined) signal.throwIfAborted()
66
+ }
67
+
68
+ /**
69
+ * @param {string} name - central-directory member name.
70
+ * @returns {boolean} whether the member is packaging noise that is always ignored.
71
+ */
72
+ export function isIgnoredEntry(name) {
73
+ if (name === '' || name.endsWith('/')) return true
74
+ const segments = name.split('/')
75
+ if (segments.includes('__MACOSX')) return true
76
+ const basename = segments[segments.length - 1]
77
+ return basename === '.DS_Store' || basename.startsWith('._')
78
+ }
79
+
80
+ /**
81
+ * Reject member names that could escape the extraction directory.
82
+ * @param {string} name - central-directory member name.
83
+ * @returns {string} the validated POSIX-style relative path.
84
+ * @throws {ArchiveError} when the name is absolute, contains a traversal segment, a backslash or a
85
+ * drive prefix, or has empty segments.
86
+ */
87
+ export function safeEntryName(name) {
88
+ if (name === '' || name.startsWith('/') || name.startsWith('\\')) {
89
+ throw new ArchiveError('unsafe-entry', `zip member has an absolute path: ${JSON.stringify(name)}`)
90
+ }
91
+ if (name.includes('\\')) throw new ArchiveError('unsafe-entry', `zip member uses a backslash path: ${JSON.stringify(name)}`)
92
+ if (/^[A-Za-z]:/.test(name)) throw new ArchiveError('unsafe-entry', `zip member has a drive letter: ${JSON.stringify(name)}`)
93
+ for (const character of name) {
94
+ const codePoint = character.codePointAt(0) ?? 0
95
+ if (codePoint < 0x20 || codePoint === 0x7f) {
96
+ throw new ArchiveError('unsafe-entry', `zip member name has control characters: ${JSON.stringify(name)}`)
97
+ }
98
+ }
99
+ const segments = name.split('/')
100
+ for (const segment of segments) {
101
+ if (segment === '' || segment === '.' || segment === '..') {
102
+ throw new ArchiveError('unsafe-entry', `zip member has a traversal segment: ${JSON.stringify(name)}`)
103
+ }
104
+ }
105
+ return segments.join('/')
106
+ }
107
+
108
+ /**
109
+ * @param {string} path - candidate file.
110
+ * @returns {Promise<number>} file size in bytes.
111
+ */
112
+ async function sizeOf(path) {
113
+ const info = await stat(path)
114
+ if (!info.isFile()) throw new ArchiveError('format', `archive is not a regular file: ${path}`)
115
+ return info.size
116
+ }
117
+
118
+ /**
119
+ * Read and validate the central directory of one ZIP archive.
120
+ * @param {string} archivePath - local ZIP file.
121
+ * @returns {Promise<{ size: number, entries: Array<{ name: string, method: number, compressedBytes: number, bytes: number, localOffset: number }> }>} usable members (directories, packaging noise and unsafe names are handled here).
122
+ * @throws {ArchiveError} when the file is not a supported single-volume ZIP archive or a member is unsafe.
123
+ */
124
+ export async function readZipEntries(archivePath) {
125
+ const size = await sizeOf(archivePath)
126
+ const tailBytes = Math.min(size, EOCD_MIN_BYTES + MAX_COMMENT_BYTES)
127
+ const tail = Buffer.alloc(tailBytes)
128
+ const handle = await open(archivePath, 'r')
129
+ try {
130
+ await handle.read(tail, 0, tailBytes, size - tailBytes)
131
+ let eocd = -1
132
+ for (let offset = tailBytes - EOCD_MIN_BYTES; offset >= 0; offset -= 1) {
133
+ if (tail.readUInt32LE(offset) === EOCD_SIGNATURE) {
134
+ eocd = offset
135
+ break
136
+ }
137
+ }
138
+ if (eocd < 0) throw new ArchiveError('format', 'not a zip archive: no end-of-central-directory record')
139
+ const diskNumber = tail.readUInt16LE(eocd + 4)
140
+ const directoryDisk = tail.readUInt16LE(eocd + 6)
141
+ const entriesOnDisk = tail.readUInt16LE(eocd + 8)
142
+ const totalEntries = tail.readUInt16LE(eocd + 10)
143
+ const directoryBytes = tail.readUInt32LE(eocd + 12)
144
+ const directoryOffset = tail.readUInt32LE(eocd + 16)
145
+ if (totalEntries === 0xffff || entriesOnDisk === 0xffff || directoryBytes === 0xffffffff || directoryOffset === 0xffffffff) {
146
+ throw new ArchiveError('format', 'zip64 archives are not supported')
147
+ }
148
+ if (diskNumber !== 0 || directoryDisk !== 0 || entriesOnDisk !== totalEntries) {
149
+ throw new ArchiveError('format', 'multi-volume zip archives are not supported')
150
+ }
151
+ if (totalEntries > MAX_ENTRIES) throw new ArchiveError('format', `zip archive has too many members (${totalEntries})`)
152
+ if (directoryOffset + directoryBytes > size) throw new ArchiveError('format', 'zip central directory overruns the archive')
153
+ const directory = Buffer.alloc(directoryBytes)
154
+ if (directoryBytes > 0) await handle.read(directory, 0, directoryBytes, directoryOffset)
155
+ /** @type {Array<{ name: string, method: number, compressedBytes: number, bytes: number, localOffset: number }>} */
156
+ const entries = []
157
+ let offset = 0
158
+ for (let index = 0; index < totalEntries; index += 1) {
159
+ if (offset + CENTRAL_HEADER_BYTES > directoryBytes || directory.readUInt32LE(offset) !== CENTRAL_SIGNATURE) {
160
+ throw new ArchiveError('format', 'corrupt zip central directory')
161
+ }
162
+ const flags = directory.readUInt16LE(offset + 8)
163
+ const method = directory.readUInt16LE(offset + 10)
164
+ const compressedBytes = directory.readUInt32LE(offset + 20)
165
+ const bytes = directory.readUInt32LE(offset + 24)
166
+ const nameBytes = directory.readUInt16LE(offset + 28)
167
+ const extraBytes = directory.readUInt16LE(offset + 30)
168
+ const commentBytes = directory.readUInt16LE(offset + 32)
169
+ const externalAttributes = directory.readUInt32LE(offset + 38)
170
+ const localOffset = directory.readUInt32LE(offset + 42)
171
+ const nameEnd = offset + CENTRAL_HEADER_BYTES + nameBytes
172
+ if (nameEnd > directoryBytes) throw new ArchiveError('format', 'corrupt zip central directory')
173
+ const name = directory.toString('utf8', offset + CENTRAL_HEADER_BYTES, nameEnd)
174
+ if ((flags & 0x0001) !== 0) throw new ArchiveError('unsafe-entry', `encrypted zip members are not supported: ${JSON.stringify(name)}`)
175
+ const unixMode = (externalAttributes >>> 16) & 0xffff
176
+ if ((unixMode & 0xf000) === 0xa000) throw new ArchiveError('unsafe-entry', `zip members may not be symbolic links: ${JSON.stringify(name)}`)
177
+ if (!isIgnoredEntry(name)) {
178
+ safeEntryName(name)
179
+ entries.push({ name, method, compressedBytes, bytes, localOffset })
180
+ }
181
+ offset = nameEnd + extraBytes + commentBytes
182
+ }
183
+ return { size, entries }
184
+ } finally {
185
+ await handle.close()
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Stream one storable/deflated member into a file while hashing it.
191
+ * @param {{
192
+ * archivePath: string,
193
+ * archiveBytes: number,
194
+ * entry: { name: string, method: number, compressedBytes: number, bytes: number, localOffset: number },
195
+ * targetPath: string,
196
+ * expected: { bytes: number, sha256: string },
197
+ * signal?: AbortSignal,
198
+ * }} options - extraction request.
199
+ * @returns {Promise<void>} when the member is written and verified.
200
+ * @throws {ArchiveError} when headers, compression or the pinned identity disagree.
201
+ */
202
+ async function extractEntry(options) {
203
+ const { archivePath, archiveBytes, entry, targetPath, expected, signal } = options
204
+ throwIfAborted(signal)
205
+ const handle = await open(archivePath, 'r')
206
+ let dataOffset
207
+ try {
208
+ const header = Buffer.alloc(LOCAL_HEADER_BYTES)
209
+ await handle.read(header, 0, LOCAL_HEADER_BYTES, entry.localOffset)
210
+ if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) throw new ArchiveError('format', `zip local header is missing for ${entry.name}`)
211
+ const nameBytes = header.readUInt16LE(26)
212
+ const extraBytes = header.readUInt16LE(28)
213
+ const name = Buffer.alloc(nameBytes)
214
+ if (nameBytes > 0) await handle.read(name, 0, nameBytes, entry.localOffset + LOCAL_HEADER_BYTES)
215
+ if (name.toString('utf8') !== entry.name) throw new ArchiveError('format', `zip local header disagrees with the central directory for ${entry.name}`)
216
+ dataOffset = entry.localOffset + LOCAL_HEADER_BYTES + nameBytes + extraBytes
217
+ } finally {
218
+ await handle.close()
219
+ }
220
+ if (dataOffset + entry.compressedBytes > archiveBytes) throw new ArchiveError('format', `zip member overruns the archive: ${entry.name}`)
221
+ if (entry.method !== 0 && entry.method !== 8) {
222
+ throw new ArchiveError('format', `zip member ${entry.name} uses unsupported compression method ${entry.method}`)
223
+ }
224
+ const digest = createHash('sha256')
225
+ let completedBytes = 0
226
+ const hashing = new Transform({
227
+ /**
228
+ * @param {Buffer} chunk - inflated bytes.
229
+ * @param {BufferEncoding} _encoding - unused.
230
+ * @param {(error?: Error|null, data?: Buffer) => void} callback - stream continuation.
231
+ * @returns {void}
232
+ */
233
+ transform(chunk, _encoding, callback) {
234
+ completedBytes += chunk.length
235
+ if (completedBytes > expected.bytes) {
236
+ callback(new ArchiveError('integrity', `zip member ${entry.name} is larger than its pinned ${expected.bytes} bytes`))
237
+ return
238
+ }
239
+ digest.update(chunk)
240
+ callback(null, chunk)
241
+ },
242
+ })
243
+ const source = createReadStream(archivePath, {
244
+ start: dataOffset,
245
+ end: dataOffset + entry.compressedBytes - 1,
246
+ signal,
247
+ })
248
+ const target = createWriteStream(targetPath, { flags: 'wx', mode: 0o600 })
249
+ try {
250
+ if (entry.method === 0) {
251
+ await pipeline(source, hashing, target, { signal })
252
+ } else {
253
+ await pipeline(source, createInflateRaw(), hashing, target, { signal })
254
+ }
255
+ } catch (error) {
256
+ if (error instanceof ArchiveError) throw error
257
+ if (signal !== undefined && signal.aborted) throw signal.reason instanceof Error ? signal.reason : error
258
+ throw new ArchiveError('format', `unable to extract zip member ${entry.name}`, { cause: error })
259
+ }
260
+ if (completedBytes !== expected.bytes) {
261
+ throw new ArchiveError('integrity', `zip member ${entry.name} produced ${completedBytes} bytes, expected ${expected.bytes}`)
262
+ }
263
+ if (digest.digest('hex') !== expected.sha256) {
264
+ throw new ArchiveError('integrity', `zip member ${entry.name} failed SHA-256 verification`)
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Extract the whitelisted members of one archive into a dedicated variant directory.
270
+ *
271
+ * The archive is unpacked into a sibling temporary directory; only after every whitelisted member
272
+ * matches its pinned byte count and SHA-256 digest is the destination directory replaced by an
273
+ * atomic rename.
274
+ * @param {{
275
+ * archivePath: string,
276
+ * innerLayout: Record<string, string>,
277
+ * files: Array<{ relativePath: string, bytes: number, sha256: string }>,
278
+ * destination: string,
279
+ * signal?: AbortSignal,
280
+ * onProgress?: (progress: { relativePath: string, completedBytes: number, totalBytes: number }) => void,
281
+ * }} options - archive, catalog layout and destination directory.
282
+ * @returns {Promise<void>} when the destination holds the verified variant files.
283
+ * @throws {ArchiveError} when the archive does not match the catalog or the caller aborts.
284
+ */
285
+ export async function extractArchive(options) {
286
+ const { archivePath, innerLayout, files, destination, signal } = options
287
+ throwIfAborted(signal)
288
+ const { size, entries } = await readZipEntries(archivePath)
289
+ const byName = new Map(entries.map((entry) => [entry.name, entry]))
290
+ /** @type {Array<{ entry: { name: string, method: number, compressedBytes: number, bytes: number, localOffset: number }, file: { relativePath: string, bytes: number, sha256: string } }>} */
291
+ const plan = []
292
+ for (const file of files) {
293
+ const archiveName = innerLayout[file.relativePath]
294
+ if (typeof archiveName !== 'string' || archiveName === '') {
295
+ throw new ArchiveError('layout', `catalog layout has no archive path for ${file.relativePath}`)
296
+ }
297
+ const entry = byName.get(archiveName)
298
+ if (entry === undefined) throw new ArchiveError('layout', `archive is missing ${archiveName}`)
299
+ plan.push({ entry, file })
300
+ }
301
+ const totalBytes = files.reduce((sum, file) => sum + file.bytes, 0)
302
+ const temporary = `${destination}.extract-${process.pid}-${randomUUID()}`
303
+ let completedBytes = 0
304
+ try {
305
+ await mkdir(temporary, { recursive: true })
306
+ for (const { entry, file } of plan) {
307
+ throwIfAborted(signal)
308
+ const targetPath = resolve(temporary, ...file.relativePath.split('/'))
309
+ const root = resolve(temporary) + sep
310
+ if (targetPath !== resolve(temporary) && !targetPath.startsWith(root)) {
311
+ throw new ArchiveError('unsafe-entry', `catalog path escapes the extraction directory: ${file.relativePath}`)
312
+ }
313
+ await mkdir(dirname(targetPath), { recursive: true })
314
+ await extractEntry({ archivePath, archiveBytes: size, entry, targetPath, expected: file, signal })
315
+ completedBytes += file.bytes
316
+ options.onProgress?.({ relativePath: file.relativePath, completedBytes, totalBytes })
317
+ }
318
+ throwIfAborted(signal)
319
+ await rm(destination, { recursive: true, force: true })
320
+ await mkdir(dirname(destination), { recursive: true })
321
+ await rename(temporary, destination)
322
+ } finally {
323
+ await rm(temporary, { recursive: true, force: true })
324
+ }
325
+ }
326
+
327
+ /**
328
+ * @param {string} directory - variant directory.
329
+ * @param {string} relativePath - catalog-relative file path.
330
+ * @returns {string} joined absolute path.
331
+ */
332
+ export function variantFilePath(directory, relativePath) {
333
+ return join(directory, ...relativePath.split('/'))
334
+ }
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Streaming, verified downloads for local model assets.
3
+ *
4
+ * Every asset is identified by its exact byte count and SHA-256 digest (pinned in the model
5
+ * catalog). This module writes the response into a unique `.part` file next to the destination,
6
+ * hashes it while it streams, rejects HTML error pages and truncated transfers, and only then
7
+ * renames it into place. A file that already matches its pinned identity is reused without any
8
+ * network request, so a retried installation never re-downloads verified files.
9
+ *
10
+ * Source policy: the catalog file URL is tried first and its `mirrorURL` second. When the caller
11
+ * passes explicit origins (`sources`, from the official preparation `downloadSource` choice) only
12
+ * those origins are used — no fallback — and a size/HTTP failure surfaces instead of silently
13
+ * switching hosts. SHA-256 mismatches are always a hard failure: the upstream identity changed and
14
+ * retrying another origin could install a different model than the catalog describes.
15
+ *
16
+ * @module @ds-hu/dsh-bvi-local/provision/download
17
+ */
18
+ import { createHash, randomUUID } from 'node:crypto'
19
+ import { createReadStream, createWriteStream } from 'node:fs'
20
+ import { mkdir, rename, rm, stat } from 'node:fs/promises'
21
+ import { basename, dirname, join } from 'node:path'
22
+ import { Readable, Transform } from 'node:stream'
23
+ import { pipeline } from 'node:stream/promises'
24
+
25
+ /** Default deadline for one file download; large variants (2 GB) need room on slow links. */
26
+ export const DEFAULT_DOWNLOAD_TIMEOUT_MS = 30 * 60_000
27
+
28
+ /** Report progress at most once per MiB so callers never receive a listener storm. */
29
+ const PROGRESS_STEP_BYTES = 1024 * 1024
30
+
31
+ /** Response content types that mean a proxy or captive portal answered instead of the file. */
32
+ const HTML_CONTENT_TYPE = /^\s*(?:text\/html|application\/xhtml\+xml)/i
33
+
34
+ /** One download that could not produce a verified file, carrying a stable machine code. */
35
+ export class DownloadError extends Error {
36
+ /**
37
+ * @param {'http'|'network'|'timeout'|'size'|'integrity'|'source'} code - stable code.
38
+ * @param {string} message - human-readable explanation (no credentials, no signed query strings).
39
+ * @param {{ cause?: unknown, status?: number, source?: string }} [options] - native error cause and diagnostics.
40
+ */
41
+ constructor(code, message, options = {}) {
42
+ super(message, options)
43
+ this.name = 'DownloadError'
44
+ this.code = code
45
+ /** @type {number|undefined} HTTP status of the failed response. */
46
+ this.status = options.status
47
+ /** @type {string|undefined} origin or URL that failed (never contains a query string). */
48
+ this.source = options.source
49
+ }
50
+ }
51
+
52
+ /**
53
+ * @param {AbortSignal|undefined} signal - cancellation signal.
54
+ * @returns {void}
55
+ * @throws {Error} when the signal is already aborted.
56
+ */
57
+ function throwIfAborted(signal) {
58
+ if (signal !== undefined) signal.throwIfAborted()
59
+ }
60
+
61
+ /**
62
+ * @param {unknown} value - candidate.
63
+ * @returns {value is Record<string, any>} whether the value is a plain object.
64
+ */
65
+ function isPlainObject(value) {
66
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
67
+ }
68
+
69
+ /**
70
+ * @param {string} url - absolute URL.
71
+ * @returns {string} its origin.
72
+ */
73
+ function originOf(url) {
74
+ return new URL(url).origin
75
+ }
76
+
77
+ /**
78
+ * Hash one whole file with SHA-256.
79
+ * @param {string} path - existing regular file.
80
+ * @param {{ signal?: AbortSignal }} [options] - cancellation signal.
81
+ * @returns {Promise<string>} lowercase hexadecimal digest.
82
+ */
83
+ export async function sha256File(path, { signal } = {}) {
84
+ throwIfAborted(signal)
85
+ const digest = createHash('sha256')
86
+ for await (const chunk of createReadStream(path, signal === undefined ? {} : { signal })) {
87
+ digest.update(chunk)
88
+ }
89
+ return digest.digest('hex')
90
+ }
91
+
92
+ /**
93
+ * Compare one file with a pinned asset identity (byte count first, then SHA-256).
94
+ *
95
+ * A missing file is a normal negative answer; filesystem failures other than ENOENT propagate so
96
+ * a permission problem is never mistaken for "not downloaded yet".
97
+ * @param {string} path - candidate file.
98
+ * @param {{ bytes: number, sha256: string }} asset - pinned identity.
99
+ * @param {AbortSignal} [signal] - cancellation signal.
100
+ * @returns {Promise<boolean>} whether the file already is exactly this asset.
101
+ */
102
+ export async function verifyAsset(path, asset, signal) {
103
+ throwIfAborted(signal)
104
+ try {
105
+ const info = await stat(path)
106
+ if (!info.isFile() || info.size !== asset.bytes) return false
107
+ return (await sha256File(path, { signal })) === asset.sha256
108
+ } catch (error) {
109
+ if (isPlainObject(error) && /** @type {any} */ (error).code === 'ENOENT') return false
110
+ throw error
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Build the ordered list of URLs to try for one asset.
116
+ *
117
+ * Without `sources` the pinned URL wins over its mirror. With `sources` each requested origin is
118
+ * mapped onto the asset path and no other origin is added: the user's explicit choice controls
119
+ * reachability, exactly like the official seam's `downloadSource` option.
120
+ * @param {{ url?: string, mirrorURL?: string }} asset - pinned per-file source.
121
+ * @param {readonly string[]} [sources] - explicit origins chosen by the caller.
122
+ * @returns {string[]} candidate URLs in attempt order (deduplicated, may be empty when the assets
123
+ * has no per-file source — archive assets are downloaded by the installation layer instead).
124
+ * @throws {DownloadError} when an explicit source is not an absolute URL.
125
+ */
126
+ export function candidateUrls(asset, sources) {
127
+ const primary = typeof asset.url === 'string' && asset.url !== '' ? asset.url : undefined
128
+ const mirror = typeof asset.mirrorURL === 'string' && asset.mirrorURL !== '' ? asset.mirrorURL : undefined
129
+ const pinned = [...new Set([primary, mirror].filter((url) => url !== undefined))]
130
+ if (sources === undefined || sources.length === 0) return pinned
131
+ const base = new URL(primary ?? pinned[0] ?? 'https://invalid.invalid/')
132
+ /** @type {string[]} */
133
+ const urls = []
134
+ for (const source of sources) {
135
+ let origin
136
+ try {
137
+ origin = originOf(source)
138
+ } catch {
139
+ throw new DownloadError('source', `Invalid download source: ${String(source)}`)
140
+ }
141
+ const direct = pinned.find((url) => originOf(url) === origin)
142
+ urls.push(direct ?? new URL(base.pathname + base.search, origin).href)
143
+ }
144
+ return [...new Set(urls)]
145
+ }
146
+
147
+ /**
148
+ * Stream one URL into a temporary file and publish it atomically once verified.
149
+ * @param {string} url - source URL.
150
+ * @param {{
151
+ * asset: { bytes: number, sha256: string },
152
+ * destination: string,
153
+ * resource: string,
154
+ * partPath: string,
155
+ * signal?: AbortSignal,
156
+ * onProgress?: (progress: { resource: string, completedBytes: number, totalBytes: number }) => void,
157
+ * fetchImpl: typeof fetch,
158
+ * timeoutMs: number,
159
+ * }} options - download request.
160
+ * @returns {Promise<string>} the source URL that served the verified file.
161
+ */
162
+ async function downloadOnce(url, options) {
163
+ const { asset, destination, resource, partPath, fetchImpl, timeoutMs } = options
164
+ const timeout = AbortSignal.timeout(timeoutMs)
165
+ let timedOut = false
166
+ timeout.addEventListener('abort', () => { timedOut = true }, { once: true })
167
+ const combined = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
168
+ /** @type {Response} */
169
+ let response
170
+ try {
171
+ response = await fetchImpl(url, { signal: combined, redirect: 'follow' })
172
+ } catch (error) {
173
+ throwIfAborted(options.signal)
174
+ if (timedOut) throw new DownloadError('timeout', `Downloading ${resource} timed out after ${timeoutMs} ms`, { cause: error, source: originOf(url) })
175
+ throw new DownloadError('network', `Unable to download ${resource} from ${originOf(url)}`, { cause: error, source: originOf(url) })
176
+ }
177
+ if (!response.ok) {
178
+ await response.body?.cancel().catch(() => undefined)
179
+ throw new DownloadError('http', `Downloading ${resource} from ${originOf(url)} returned HTTP ${response.status}`, {
180
+ status: response.status, source: originOf(url),
181
+ })
182
+ }
183
+ const contentType = response.headers.get('content-type') ?? ''
184
+ if (HTML_CONTENT_TYPE.test(contentType)) {
185
+ await response.body?.cancel().catch(() => undefined)
186
+ throw new DownloadError('http', `Downloading ${resource} from ${originOf(url)} returned an HTML page instead of the model file`, {
187
+ source: originOf(url),
188
+ })
189
+ }
190
+ // `Content-Length` is optional (HF's CDN answers with chunked transfer encoding for some
191
+ // redirects), so a missing header means "unknown", never zero. Only a declared numeric value is
192
+ // comparable with the pinned size.
193
+ const declaredHeader = response.headers.get('content-length')
194
+ const declaredLength = declaredHeader === null || declaredHeader.trim() === '' ? undefined : Number(declaredHeader)
195
+ if (declaredLength !== undefined && Number.isFinite(declaredLength) && declaredLength !== asset.bytes) {
196
+ await response.body?.cancel().catch(() => undefined)
197
+ throw new DownloadError('size', `Downloading ${resource} from ${originOf(url)} declared ${declaredLength} bytes, expected ${asset.bytes}`, {
198
+ source: originOf(url),
199
+ })
200
+ }
201
+ if (response.body === null) throw new DownloadError('http', `Downloading ${resource} from ${originOf(url)} returned no body`, { source: originOf(url) })
202
+
203
+ await rm(partPath, { force: true })
204
+ const digest = createHash('sha256')
205
+ let completedBytes = 0
206
+ let reportedBytes = 0
207
+ const report = () => options.onProgress?.({ resource, completedBytes, totalBytes: asset.bytes })
208
+ const hashing = new Transform({
209
+ /**
210
+ * @param {Buffer} chunk - received bytes.
211
+ * @param {BufferEncoding} _encoding - unused.
212
+ * @param {(error?: Error|null, data?: Buffer) => void} callback - stream continuation.
213
+ * @returns {void}
214
+ */
215
+ transform(chunk, _encoding, callback) {
216
+ completedBytes += chunk.length
217
+ if (completedBytes > asset.bytes) {
218
+ callback(new DownloadError('integrity', `Downloading ${resource} exceeded its pinned ${asset.bytes} bytes`, { source: originOf(url) }))
219
+ return
220
+ }
221
+ digest.update(chunk)
222
+ if (completedBytes - reportedBytes >= PROGRESS_STEP_BYTES) {
223
+ reportedBytes = completedBytes
224
+ report()
225
+ }
226
+ callback(null, chunk)
227
+ },
228
+ })
229
+ try {
230
+ await pipeline(Readable.fromWeb(/** @type {any} */ (response.body)), hashing,
231
+ createWriteStream(partPath, { flags: 'wx', mode: 0o600 }), { signal: combined })
232
+ } catch (error) {
233
+ throwIfAborted(options.signal)
234
+ if (timedOut) throw new DownloadError('timeout', `Downloading ${resource} timed out after ${timeoutMs} ms`, { cause: error, source: originOf(url) })
235
+ if (error instanceof DownloadError) throw error
236
+ throw new DownloadError('network', `Downloading ${resource} from ${originOf(url)} was interrupted`, { cause: error, source: originOf(url) })
237
+ }
238
+ report()
239
+ if (completedBytes !== asset.bytes) {
240
+ throw new DownloadError('size', `Downloading ${resource} from ${originOf(url)} produced ${completedBytes} bytes, expected ${asset.bytes}`, {
241
+ source: originOf(url),
242
+ })
243
+ }
244
+ const sha256 = digest.digest('hex')
245
+ if (sha256 !== asset.sha256) {
246
+ throw new DownloadError('integrity', `${resource} failed SHA-256 verification (expected ${asset.sha256}, received ${sha256})`, {
247
+ source: originOf(url),
248
+ })
249
+ }
250
+ throwIfAborted(options.signal)
251
+ await rename(partPath, destination)
252
+ return url
253
+ }
254
+
255
+ /**
256
+ * Download one asset into its destination.
257
+ *
258
+ * Reuses a destination that already matches the pinned identity. A fresh download is written to
259
+ * `<destination>.<pid>.<random>.part`, verified against both the byte count and SHA-256, then
260
+ * renamed atomically; the partial file is always removed on failure.
261
+ * @param {{
262
+ * asset: { bytes: number, sha256: string, url?: string, mirrorURL?: string },
263
+ * destination: string,
264
+ * resource?: string,
265
+ * signal?: AbortSignal,
266
+ * onProgress?: (progress: { resource: string, completedBytes: number, totalBytes: number }) => void,
267
+ * sources?: readonly string[],
268
+ * fetchImpl?: typeof fetch,
269
+ * timeoutMs?: number,
270
+ * }} options - the pinned asset, destination path and transport overrides.
271
+ * @returns {Promise<{ path: string, source: string, skipped: boolean }>} verified file location and serving source.
272
+ * @throws {DownloadError} when no source can produce the verified file or the caller aborts.
273
+ */
274
+ export async function downloadAsset(options) {
275
+ const { asset, destination, signal } = options
276
+ if (!isPlainObject(asset) || !Number.isSafeInteger(asset.bytes) || asset.bytes <= 0
277
+ || typeof asset.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(asset.sha256)) {
278
+ throw new DownloadError('source', `Invalid asset identity for ${options.resource ?? destination}`)
279
+ }
280
+ throwIfAborted(signal)
281
+ if (await verifyAsset(destination, asset, signal)) return { path: destination, source: 'cache', skipped: true }
282
+ const urls = candidateUrls(asset, options.sources)
283
+ if (urls.length === 0) {
284
+ throw new DownloadError('source', `No per-file download source is pinned for ${options.resource ?? basename(destination)}`)
285
+ }
286
+ const resource = options.resource ?? basename(destination)
287
+ const fetchImpl = options.fetchImpl ?? fetch
288
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
289
+ ? Number(options.timeoutMs)
290
+ : DEFAULT_DOWNLOAD_TIMEOUT_MS
291
+ await mkdir(dirname(destination), { recursive: true })
292
+ const partPath = `${destination}.${process.pid}.${randomUUID()}.part`
293
+ /** @type {DownloadError|undefined} */
294
+ let lastError
295
+ /** @type {Map<string, number>} */
296
+ const sizeRetries = new Map(urls.map((url) => [url, 1]))
297
+ try {
298
+ for (const url of urls) {
299
+ for (;;) {
300
+ try {
301
+ const source = await downloadOnce(url, {
302
+ asset, destination, resource, partPath, signal, onProgress: options.onProgress,
303
+ fetchImpl, timeoutMs,
304
+ })
305
+ return { path: destination, source, skipped: false }
306
+ } catch (error) {
307
+ if (!(error instanceof DownloadError)) throw error
308
+ if (error.code === 'integrity' || error.code === 'source') throw error
309
+ throwIfAborted(signal)
310
+ lastError = error
311
+ const retries = sizeRetries.get(url) ?? 0
312
+ if (error.code === 'size' && retries > 0) {
313
+ sizeRetries.set(url, retries - 1)
314
+ continue
315
+ }
316
+ break
317
+ } finally {
318
+ await rm(partPath, { force: true })
319
+ }
320
+ }
321
+ }
322
+ } finally {
323
+ await rm(partPath, { force: true })
324
+ }
325
+ throw lastError ?? new DownloadError('network', `No download source is available for ${resource}`)
326
+ }
327
+
328
+ /**
329
+ * Verify a list of expected files under one directory.
330
+ * @param {Array<{ relativePath: string, bytes: number, sha256: string }>} files - pinned file list.
331
+ * @param {string} directory - variant directory that should hold them.
332
+ * @param {AbortSignal} [signal] - cancellation signal.
333
+ * @returns {Promise<Array<{ relativePath: string, verified: boolean }>>} one entry per expected file.
334
+ */
335
+ export async function verifyFiles(files, directory, signal) {
336
+ throwIfAborted(signal)
337
+ /** @type {Array<{ relativePath: string, verified: boolean }>} */
338
+ const results = []
339
+ for (const file of files) {
340
+ const path = join(directory, file.relativePath)
341
+ results.push({ relativePath: file.relativePath, verified: await verifyAsset(path, file, signal) })
342
+ }
343
+ return results
344
+ }