vvvfs 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -68,8 +68,51 @@ export interface VVVFSDownloadOptions {
68
68
  onProgress?: (progress: number) => void;
69
69
  onError?: (error: any) => void;
70
70
  onSuccess?: (success: boolean) => void;
71
+ /**
72
+ * 多线程下载的线程数(1-8,默认 4)
73
+ * @description 小于等于 1 时强制单线程下载;服务器不支持 Range 请求时自动回退单线程
74
+ */
75
+ threads?: number;
76
+ /**
77
+ * 多线程下载的最小分片大小(字节,默认 256KB)
78
+ * @description 文件小于 threads * minChunkSize 时使用单线程下载
79
+ */
80
+ minChunkSize?: number;
81
+ }
82
+
83
+ /**
84
+ * 远端文件 HEAD 信息
85
+ */
86
+ export interface VVVFSHeadResult {
87
+ /**
88
+ * 远端文件大小(字节),无法获取时为 null
89
+ */
90
+ contentLength: number | null;
91
+ /**
92
+ * 远端 Content-Type,无法获取时为 null
93
+ */
94
+ contentType: string | null;
95
+ /**
96
+ * 服务器是否声明支持 Range 请求(跨域时可能读取不到该响应头)
97
+ */
98
+ acceptRanges: boolean;
71
99
  }
72
100
 
101
+ /**
102
+ * 默认下载线程数
103
+ */
104
+ const DEFAULT_DOWNLOAD_THREADS = 4;
105
+
106
+ /**
107
+ * 最大下载线程数
108
+ */
109
+ const MAX_DOWNLOAD_THREADS = 8;
110
+
111
+ /**
112
+ * 多线程下载的最小分片大小(字节)
113
+ */
114
+ const MIN_DOWNLOAD_CHUNK_SIZE = 256 * 1024;
115
+
73
116
  /**
74
117
  * 虚拟文件系统错误类
75
118
  */
@@ -1427,6 +1470,44 @@ class VVVFS {
1427
1470
  return true;
1428
1471
  }, false);
1429
1472
  }
1473
+ /**
1474
+ * 获取远端文件信息(HEAD 请求)
1475
+ * @param url 文件链接
1476
+ * @param options 请求配置项
1477
+ * @description 用于下载前校验缓存、判断能否多线程下载;请求失败时返回各字段为 null / false 的默认值
1478
+ */
1479
+ async head(
1480
+ url: string | URL | Request,
1481
+ options: VVVFSDownloadOptions = {},
1482
+ ): Promise<VVVFSHeadResult> {
1483
+ return this.#withErrorHandling(
1484
+ "head",
1485
+ async () => {
1486
+ const headers = url instanceof Request ? url.headers : options.headers;
1487
+ const request = new Request(url instanceof Request ? url.url : url, {
1488
+ method: "HEAD",
1489
+ headers,
1490
+ });
1491
+ const response = await fetch(request);
1492
+ if (!response.ok) {
1493
+ throw new Error(`HEAD 失败,HTTP ${response.status}`);
1494
+ }
1495
+ const length = response.headers.get("Content-Length");
1496
+ return {
1497
+ contentLength:
1498
+ length != null && /^\d+$/.test(length.trim())
1499
+ ? Number(length)
1500
+ : null,
1501
+ contentType: response.headers.get("Content-Type"),
1502
+ acceptRanges: (response.headers.get("Accept-Ranges") || "")
1503
+ .toLowerCase()
1504
+ .includes("bytes"),
1505
+ };
1506
+ },
1507
+ { contentLength: null, contentType: null, acceptRanges: false },
1508
+ );
1509
+ }
1510
+
1430
1511
  /**
1431
1512
  * 下载文件
1432
1513
  * @param url 文件链接
@@ -1441,10 +1522,27 @@ class VVVFS {
1441
1522
  return this.#withErrorHandling("downloadFile", async () => {
1442
1523
  const targetPath = joinPath(path);
1443
1524
  if (!(await this.#checkAccess(targetPath, "write"))) return false;
1444
- const content =
1445
- (options.mode || "fetch") === "xhr"
1446
- ? await this.#downloadWithXHR(url, options)
1447
- : await this.#downloadWithFetch(url, options);
1525
+
1526
+ // 多线程下载需要预先知道文件大小,先发送 HEAD 请求;单线程模式无需 HEAD
1527
+ const wantMultiThread =
1528
+ Math.floor(options.threads ?? DEFAULT_DOWNLOAD_THREADS) > 1;
1529
+ const info = wantMultiThread ? await this.head(url, options) : null;
1530
+
1531
+ let content: Blob | null = null;
1532
+ if (info?.contentLength && info.contentLength > 0) {
1533
+ content = await this.#downloadWithThreads(
1534
+ url,
1535
+ info.contentLength,
1536
+ options,
1537
+ );
1538
+ }
1539
+ // 不支持多线程(文件过小 / 服务器不支持 Range / 分片失败)时回退单线程
1540
+ if (!content) {
1541
+ content =
1542
+ (options.mode || "fetch") === "xhr"
1543
+ ? await this.#downloadWithXHR(url, options)
1544
+ : await this.#downloadWithFetch(url, options);
1545
+ }
1448
1546
  if (!content) return false;
1449
1547
  const blob = new Blob([content], {
1450
1548
  type: mime.getType(targetPath) || "application/octet-stream",
@@ -1456,6 +1554,84 @@ class VVVFS {
1456
1554
  return success;
1457
1555
  }, false);
1458
1556
  }
1557
+
1558
+ /**
1559
+ * 使用多线程(Range 分片)下载文件
1560
+ * @param url 文件链接
1561
+ * @param total 文件总大小(字节)
1562
+ * @param options 下载配置项
1563
+ * @returns 下载成功的 Blob;不支持多线程或任一分片失败时返回 null,由调用方回退单线程
1564
+ */
1565
+ async #downloadWithThreads(
1566
+ url: string | URL | Request,
1567
+ total: number,
1568
+ options: VVVFSDownloadOptions,
1569
+ ): Promise<Blob | null> {
1570
+ const threads = Math.min(
1571
+ MAX_DOWNLOAD_THREADS,
1572
+ Math.max(1, Math.floor(options.threads ?? DEFAULT_DOWNLOAD_THREADS)),
1573
+ );
1574
+ const minChunkSize = Math.max(
1575
+ 1,
1576
+ Math.floor(options.minChunkSize ?? MIN_DOWNLOAD_CHUNK_SIZE),
1577
+ );
1578
+ // 文件过小或线程数不足时无需分片
1579
+ if (threads <= 1 || total <= 0 || total < threads * minChunkSize) return null;
1580
+
1581
+ const ranges: Array<[number, number]> = [];
1582
+ const baseSize = Math.floor(total / threads);
1583
+ let start = 0;
1584
+ for (let i = 0; i < threads; i++) {
1585
+ const end = i === threads - 1 ? total - 1 : start + baseSize - 1;
1586
+ ranges.push([start, end]);
1587
+ start = end + 1;
1588
+ }
1589
+
1590
+ const request =
1591
+ url instanceof Request ? url : new Request(url, { headers: options.headers });
1592
+ const controller = new AbortController();
1593
+ const chunks: (Uint8Array | null)[] = new Array(ranges.length).fill(null);
1594
+ let loaded = 0;
1595
+
1596
+ const tasks = ranges.map(async ([rangeStart, rangeEnd], index) => {
1597
+ try {
1598
+ const headers = new Headers(request.headers);
1599
+ headers.set("Range", `bytes=${rangeStart}-${rangeEnd}`);
1600
+ const response = await fetch(request, {
1601
+ headers,
1602
+ signal: controller.signal,
1603
+ });
1604
+ // 服务器忽略 Range 返回 200,说明不支持多线程下载
1605
+ if (response.status !== 206) {
1606
+ throw new Error(
1607
+ `服务器不支持 Range 请求,HTTP ${response.status}`,
1608
+ );
1609
+ }
1610
+ const buffer = await response.arrayBuffer();
1611
+ chunks[index] = new Uint8Array(buffer);
1612
+ loaded += buffer.byteLength;
1613
+ if (options.onProgress) {
1614
+ options.onProgress(Math.min(100, Math.round((loaded / total) * 100)));
1615
+ }
1616
+ } catch (error) {
1617
+ // 任一分片失败即中止其余分片,回退单线程
1618
+ controller.abort();
1619
+ throw error;
1620
+ }
1621
+ });
1622
+
1623
+ try {
1624
+ await Promise.all(tasks);
1625
+ } catch {
1626
+ // 静默回退单线程;若单线程也失败,由单线程逻辑上报错误
1627
+ return null;
1628
+ }
1629
+
1630
+ if (chunks.some((chunk) => chunk === null)) return null;
1631
+ const received = chunks.reduce((sum, chunk) => sum + (chunk?.length ?? 0), 0);
1632
+ if (received !== total) return null;
1633
+ return new Blob(chunks as BlobPart[]);
1634
+ }
1459
1635
  /**
1460
1636
  * 使用fetch下载文件
1461
1637
  * @param url 文件链接
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vvvfs",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "一个使用IndexDB实现的虚拟文件系统",
5
5
  "keywords": [
6
6
  "Virtual",
package/types/index.d.ts CHANGED
@@ -72,6 +72,8 @@ export interface VVVFSOptions {
72
72
  * @param onProgress 下载进度事件
73
73
  * @param onError 下载出错事件
74
74
  * @param onSuccess 下载成功事件
75
+ * @param threads 多线程下载的线程数(1-8,默认 4);小于等于 1 时强制单线程,服务器不支持 Range 时自动回退单线程
76
+ * @param minChunkSize 多线程下载的最小分片大小(字节,默认 256KB);文件小于 threads * minChunkSize 时使用单线程
75
77
  */
76
78
  export interface VVVFSDownloadOptions {
77
79
  headers?: Record<string, string>;
@@ -79,6 +81,26 @@ export interface VVVFSDownloadOptions {
79
81
  onProgress?: (progress: number) => void;
80
82
  onError?: (error: any) => void;
81
83
  onSuccess?: (success: boolean) => void;
84
+ threads?: number;
85
+ minChunkSize?: number;
86
+ }
87
+
88
+ /**
89
+ * 远端文件 HEAD 信息
90
+ */
91
+ export interface VVVFSHeadResult {
92
+ /**
93
+ * 远端文件大小(字节),无法获取时为 null
94
+ */
95
+ contentLength: number | null;
96
+ /**
97
+ * 远端 Content-Type,无法获取时为 null
98
+ */
99
+ contentType: string | null;
100
+ /**
101
+ * 服务器是否声明支持 Range 请求(跨域时可能读取不到该响应头)
102
+ */
103
+ acceptRanges: boolean;
82
104
  }
83
105
 
84
106
  /**
@@ -588,6 +610,16 @@ export class VVVFS {
588
610
  * @param name 文件名
589
611
  */
590
612
  saveFile(path: string, name?: string): Promise<boolean>;
613
+ /**
614
+ * 获取远端文件信息(HEAD 请求)
615
+ * @param url 文件链接
616
+ * @param options 请求配置项
617
+ * @description 用于下载前校验缓存、判断能否多线程下载;请求失败时返回各字段为 null / false 的默认值
618
+ */
619
+ head(
620
+ url: string | URL | Request,
621
+ options?: VVVFSDownloadOptions,
622
+ ): Promise<VVVFSHeadResult>;
591
623
  /**
592
624
  * 下载文件
593
625
  * @param url 文件链接
@@ -613,7 +645,7 @@ export class VVVFS {
613
645
  */
614
646
  export interface FsMediaLoadDetail {
615
647
  /**
616
- * 媒体文件路径
648
+ * 媒体文件在 vvvfs 中的实际路径(云端文件为本地缓存路径)
617
649
  */
618
650
  path: string;
619
651
  /**
@@ -638,12 +670,12 @@ export interface FsMediaErrorDetail {
638
670
 
639
671
  /**
640
672
  * 自定义图片元素 <fs-img>
641
- * @description 直接读取并显示存储在 vvvfs 中的图片文件
673
+ * @description 直接显示 vvvfs 中的图片文件;src 为 http(s) 云端地址时,先下载到 /home/.cache/cloud/<hostname>/<pathname> 再显示
642
674
  * @attributes
643
- * - src / path:图片在 vvvfs 中的路径(src 优先,其次 path)
675
+ * - src / path:图片路径(src 优先,其次 path),支持 http(s) 云端地址
644
676
  * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
645
677
  * - alt / width / height:透传到内部 <img> 元素
646
- * - watch:存在时,文件发生变化自动刷新
678
+ * - watch:true 启用文件监听,false 停止监听
647
679
  * @events
648
680
  * - load:图片加载完成(detail: { path, file })
649
681
  * - error:图片加载失败(detail: { path, message })
@@ -687,13 +719,13 @@ export class FsImg extends HTMLElement {
687
719
 
688
720
  /**
689
721
  * 自定义音频元素 <fs-audio>
690
- * @description 直接读取并播放存储在 vvvfs 中的音频文件
722
+ * @description 直接播放 vvvfs 中的音频文件;src 为 http(s) 云端地址时,先下载到 /home/.cache/cloud/<hostname>/<pathname> 再播放
691
723
  * @attributes
692
- * - src / path:音频在 vvvfs 中的路径(src 优先,其次 path)
724
+ * - src / path:音频路径(src 优先,其次 path),支持 http(s) 云端地址
693
725
  * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
694
726
  * - controls:是否显示控制条(默认显示)
695
727
  * - autoplay / loop / muted / preload:透传到内部 <audio> 元素
696
- * - watch:存在时,文件发生变化自动刷新
728
+ * - watch:true 启用文件监听,false 停止监听
697
729
  * @events
698
730
  * - load:音频数据加载完成(detail: { path, file })
699
731
  * - error:音频加载失败(detail: { path, message })
@@ -737,13 +769,13 @@ export class FsAudio extends HTMLElement {
737
769
 
738
770
  /**
739
771
  * 自定义视频元素 <fs-video>
740
- * @description 直接读取并播放存储在 vvvfs 中的视频文件
772
+ * @description 直接播放 vvvfs 中的视频文件;src 为 http(s) 云端地址时,先下载到 /home/.cache/cloud/<hostname>/<pathname> 再播放
741
773
  * @attributes
742
- * - src / path:视频在 vvvfs 中的路径(src 优先,其次 path)
774
+ * - src / path:视频路径(src 优先,其次 path),支持 http(s) 云端地址
743
775
  * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
744
776
  * - controls:是否显示控制条(默认显示)
745
777
  * - autoplay / loop / muted / preload / width / height:透传到内部 <video> 元素
746
- * - watch:存在时,文件发生变化自动刷新
778
+ * - watch:true 启用文件监听,false 停止监听
747
779
  * @events
748
780
  * - load:视频数据加载完成(detail: { path, file })
749
781
  * - error:视频加载失败(detail: { path, message })