@ysgroup/core 0.1.23 → 0.1.25

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/core",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -23,6 +23,6 @@
23
23
  "access": "public"
24
24
  },
25
25
  "devDependencies": {
26
- "@ysgroup/theme": "^0.2.5"
26
+ "@ysgroup/theme": "^0.2.6"
27
27
  }
28
28
  }
@@ -1,11 +1,22 @@
1
- /* @ysgroup/core —— 业务 WS 分块文件传输(上传 begin → 按序发块 → finish 核对 sha256;读取逐块拼成 Blob)。 */
1
+ /* @ysgroup/core —— 业务 WS 分块文件传输(先算整份 sha256,再秒传 / 续传 / 分块上传;读取逐块拼成 Blob)。 */
2
2
 
3
- /** 每块原始字节数:1 MiB,与 Template `app/files.py` 的 CHUNK_SIZE 一致。服务端 begin 返回 chunk_size 时以服务端为准。 */
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+
5
+ /** 每块原始字节数:1 MiB,与 ys_base.files 的 CHUNK_SIZE 一致。服务端 begin 返回 chunk_size 时以服务端为准。 */
4
6
  export const FILE_CHUNK_SIZE = 1024 * 1024;
5
7
 
6
8
  /** 单块上传、读取、finish 的默认超时:一块 1 MiB 的 base64,慢网下也够。 */
7
9
  export const FILE_CHUNK_TIMEOUT_MS = 60_000;
8
10
 
11
+ /** 计算 sha256 时每次从文件读出的字节数(不把整个文件读进内存)。 */
12
+ export const FILE_HASH_SLICE_SIZE = 1024 * 1024;
13
+
14
+ /**
15
+ * uploadChunked 合并进度里「计算校验」所占的比例:算 sha256 时 ratio 从 0 走到 0.1,上传从 0.1 走到 1。
16
+ * 计算是本地的,一般远快于上传;需要分开显示时用 onProgress 的 phase 和第三个参数(本阶段 0~1)。
17
+ */
18
+ export const FILE_HASH_PROGRESS_WEIGHT = 0.1;
19
+
9
20
  /**
10
21
  * 业务调用函数:`store.call` 或业务仓自己的包装(如 `callWs`)都能直接传。
11
22
  * 第三个参数只用到 `{ timeoutMs }`。
@@ -16,8 +27,18 @@ export type YsFileCall = (
16
27
  options?: { timeoutMs?: number },
17
28
  ) => Promise<unknown>;
18
29
 
19
- /** 进度 0~1。 */
20
- export type YsFileProgress = (ratio: number) => void;
30
+ /** 上传的阶段:`hash` 计算整份 sha256,`upload` 发块(秒传时没有 upload 阶段)。 */
31
+ export type YsFilePhase = "hash" | "upload";
32
+
33
+ /**
34
+ * 进度回调。ratio 为总进度 0~1,只增不减。uploadChunked 另传 phase 与本阶段进度 phaseRatio(0~1);
35
+ * readChunked 只传 ratio。只写 `(ratio) => …` 的旧回调不受影响。
36
+ */
37
+ export type YsFileProgress = (
38
+ ratio: number,
39
+ phase?: YsFilePhase,
40
+ phaseRatio?: number,
41
+ ) => void;
21
42
 
22
43
  /** 浏览器本地读文件出的错(不是服务端错误),调用方可单独提示「请重新选择文件」。 */
23
44
  export class YsLocalFileError extends Error {
@@ -51,23 +72,103 @@ export function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {
51
72
  return bytes;
52
73
  }
53
74
 
75
+ function toHex(bytes: Uint8Array): string {
76
+ let hex = "";
77
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
78
+ return hex;
79
+ }
80
+
81
+ async function readBytes(blob: Blob): Promise<Uint8Array> {
82
+ try {
83
+ return new Uint8Array(await blob.arrayBuffer());
84
+ } catch (error) {
85
+ throw new YsLocalFileError(undefined, { cause: error });
86
+ }
87
+ }
88
+
89
+ export interface YsSha256Options {
90
+ /** 本次计算的进度 0~1。 */
91
+ onProgress?: (ratio: number) => void;
92
+ signal?: AbortSignal;
93
+ /** 每次读出的字节数,默认 FILE_HASH_SLICE_SIZE(1 MiB)。 */
94
+ sliceSize?: number;
95
+ }
96
+
54
97
  /**
55
- * 整个 Blob 的 sha256(小写十六进制)。非 HTTPS 访问时浏览器不提供摘要接口,返回空串,
56
- * 由服务端自己算(各系统 finish 都接受空 checksum)。
98
+ * 整个 Blob 的 sha256(小写十六进制)。按 1 MiB 切片流式计算,不把整个文件读进内存;
99
+ * 用 `@noble/hashes`(纯 JS),不依赖 HTTPS 下才有的 Web Crypto,HTTP 访问也能算。读失败抛 YsLocalFileError。
57
100
  */
58
- export async function sha256Hex(blob: Blob): Promise<string> {
59
- if (!globalThis.crypto?.subtle) return "";
60
- const digest = await crypto.subtle.digest(
61
- "SHA-256",
62
- await blob.arrayBuffer(),
63
- );
64
- return [...new Uint8Array(digest)]
65
- .map((byte) => byte.toString(16).padStart(2, "0"))
66
- .join("");
101
+ export async function sha256Hex(
102
+ blob: Blob,
103
+ options: YsSha256Options = {},
104
+ ): Promise<string> {
105
+ const { signal, onProgress } = options;
106
+ const sliceSize = Math.max(1, options.sliceSize ?? FILE_HASH_SLICE_SIZE);
107
+ signal?.throwIfAborted();
108
+ const hasher = sha256.create();
109
+ onProgress?.(0);
110
+ for (let start = 0; start < blob.size; start += sliceSize) {
111
+ const bytes = await abortable(
112
+ readBytes(blob.slice(start, start + sliceSize)),
113
+ signal,
114
+ );
115
+ hasher.update(bytes);
116
+ onProgress?.(Math.min(start + sliceSize, blob.size) / blob.size);
117
+ }
118
+ if (!blob.size) onProgress?.(1);
119
+ return toHex(hasher.digest());
67
120
  }
68
121
 
122
+ /** 持有验证:每段 sha256(nonce + 文件里这一段原文)。 */
123
+ async function proveRanges(
124
+ file: Blob,
125
+ nonce: string,
126
+ ranges: { start: number; length: number }[],
127
+ signal?: AbortSignal,
128
+ ): Promise<string[]> {
129
+ const prefix = new TextEncoder().encode(nonce);
130
+ const proofs: string[] = [];
131
+ for (const { start, length } of ranges) {
132
+ const segment = await abortable(
133
+ readBytes(file.slice(start, start + length)),
134
+ signal,
135
+ );
136
+ proofs.push(toHex(sha256.create().update(prefix).update(segment).digest()));
137
+ }
138
+ return proofs;
139
+ }
140
+
141
+ /** 续传记录在 localStorage 里的键前缀。 */
142
+ export const FILE_UPLOAD_RESUME_PREFIX = "ys:upload:";
143
+
144
+ /** 续传记录默认保留 24 小时,与服务端 ys_base.files 未完成上传的默认过期时间一致。 */
145
+ export const FILE_UPLOAD_RESUME_TTL_MS = 24 * 3600 * 1000;
146
+
147
+ /** 开启续传、重试时每块最多重试的次数(不含第一次)。 */
148
+ export const FILE_CHUNK_RETRIES = 3;
149
+
150
+ /** 秒传的持有验证事件默认名。 */
151
+ export const FILE_PROVE_EVENT = "prove_file_upload";
152
+
153
+ export interface YsUploadResumeOptions {
154
+ /**
155
+ * 0.1.24 的按编号续传事件(如 `resume_file_upload`)。0.1.25 起续传由 begin 按内容决定,不再调用,保留只为兼容旧写法。
156
+ */
157
+ event?: string;
158
+ /** 区分「同一文件传给不同业务对象」的附加键,如业务对象 id;同时作为 begin 的 `resume_key` 发给服务端。 */
159
+ key?: string;
160
+ /** 本地续传记录保留时长,默认 FILE_UPLOAD_RESUME_TTL_MS。 */
161
+ ttlMs?: number;
162
+ }
163
+
164
+ /** begin 返回的同内容文件(字段由服务端 visible_duplicates 决定,常见有 `_id`、`name`、上传时间)。 */
165
+ export type YsFileDuplicate = Record<string, unknown>;
166
+
69
167
  export interface YsUploadChunkedOptions {
70
- /** 开始上传的事件与附加数据。实际发送 `{ name: file.name, size: file.size, ...data }`,data 里同名字段优先(如 content_type 自己传)。 */
168
+ /**
169
+ * 开始上传的事件与附加数据。实际发送 `{ name, size, checksum, resume_key?, resume_id?, ...data }`,
170
+ * data 里同名字段优先(如 content_type 自己传)。checksum 为整份 sha256。
171
+ */
71
172
  begin: { event: string; data?: Record<string, unknown> };
72
173
  /** 发块事件,如 `upload_file_chunk`。数据 `{ [idKey]: id, index, size, data }`,size 为这一块原始字节数。 */
73
174
  chunkEvent: string;
@@ -75,35 +176,84 @@ export interface YsUploadChunkedOptions {
75
176
  finishEvent: string;
76
177
  /** 取消事件,如 `cancel_file_upload`。出错或中止时发 `{ [idKey]: id }`,不等结果、不抛错。 */
77
178
  cancelEvent: string;
179
+ /** 秒传的持有验证事件,默认 FILE_PROVE_EVENT(`prove_file_upload`)。数据 `{ challenge_id, proofs }`。 */
180
+ proveEvent?: string;
78
181
  /**
79
182
  * 上传编号字段名:既用来从 begin 结果里读编号,也用作后续请求里的字段名。
80
183
  * 不传时先看 `upload_id`,没有再看 `_id`,找到哪个就用哪个。
81
184
  */
82
185
  idKey?: string;
186
+ /** 进度:`(ratio, phase, phaseRatio)`,见 YsFileProgress 与 FILE_HASH_PROGRESS_WEIGHT。 */
83
187
  onProgress?: YsFileProgress;
84
- /** 中止:立即发 cancel 并抛出 signal.reason(默认 AbortError),不等正在进行的请求。 */
188
+ /**
189
+ * begin 返回同内容的已有文件时调用(列表由服务端按权限过滤)。返回 false 或抛错则中止上传
190
+ * (已建的上传会话发 cancel;返回 false 时抛 name 为 AbortError 的错误),可返回 Promise(如等用户确认)。
191
+ */
192
+ onDuplicates?: (
193
+ list: YsFileDuplicate[],
194
+ ) => boolean | void | Promise<boolean | void>;
195
+ /** 中止(用户主动取消):立即发 cancel 并抛出 signal.reason(默认 AbortError),不等正在进行的请求;清掉续传记录。 */
85
196
  signal?: AbortSignal;
86
- /** 每块、finish 的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。begin、cancel 用调用方默认超时。 */
197
+ /** 每块、finish、prove 的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。begin、cancel 用调用方默认超时。 */
87
198
  timeoutMs?: number;
199
+ /**
200
+ * 断点续传(服务端需 ys_base 0.1.100 起的 FileStore)。服务端按「上传人 + 内容 sha256 + resume_key」找到未完成的
201
+ * 上传就从已收到的块接着发,改了文件名也能续。开启时另按「begin 事件 + sha256 + 大小 + key」把上传编号记在
202
+ * localStorage(`ys:upload:` 前缀),下次 begin 带 `resume_id` 精确指定会话。成功或取消后清掉记录。
203
+ * 连接断开、超时、页面关闭导致的失败不发 cancel、保留记录;服务端明确拒绝(带 code 的业务错误)与用户中止照旧
204
+ * 发 cancel 并清记录。不传或 false 时:失败一律发 cancel、不重试。
205
+ */
206
+ resume?: YsUploadResumeOptions | false;
207
+ /** 每块遇到网络中断、超时(以及服务端 408/429/502/503/504)时的重试次数。开启 resume 时默认 FILE_CHUNK_RETRIES,否则 0。 */
208
+ retries?: number;
209
+ /** 第一次重试前等待的毫秒数,之后每次翻倍。默认 500。 */
210
+ retryDelayMs?: number;
211
+ }
212
+
213
+ interface ResumeRecord {
214
+ id: string;
215
+ idKey: string;
216
+ expiresAt: number;
88
217
  }
89
218
 
219
+ /** uploadChunked 的结果:服务端 finish / prove 的返回值;是普通对象时一定带 `instant`(true 为秒传)。 */
220
+ export type YsUploadResult<T> = T extends object ? T & { instant: boolean } : T;
221
+
90
222
  /**
91
- * 分块上传:begin → 按序发块 → finish(带整个文件 sha256),返回 finish 的结果。
92
- * 块大小、块数以 begin 返回的 chunk_size、chunk_count 为准(没返回时按 FILE_CHUNK_SIZE 计算,空文件 0 块)。
93
- * 任一步出错或中止:拿到上传编号后不等结果地发 cancel,再把原错误抛出。
223
+ * 上传一个文件:先流式算整份 sha256(phase=hash),begin 带上 checksum,按服务端答复走三条路之一:
224
+ * - `challenge`(内容已存在):读出指定的几段算 sha256(nonce + 片段),调 proveEvent 证明持有,通过即秒传;
225
+ * - `resume`(同一上传人有该内容未完成的上传):从服务端已收到的块接着发;
226
+ * - `upload`(或旧服务端没有 status):从第 0 块按序发。块大小、块数以服务端返回为准。
227
+ * 发完调 finish(带 sha256)。返回 finish / prove 的结果,普通对象结果补上 `instant`。
228
+ * 出错:拿到上传编号后不等结果地发 cancel,再把原错误抛出;开启 resume 时网络类失败例外(保留可续传)。
94
229
  */
95
230
  export async function uploadChunked<T = unknown>(
96
231
  call: YsFileCall,
97
- file: Blob & { name?: string },
232
+ file: Blob & { name?: string; lastModified?: number },
98
233
  options: YsUploadChunkedOptions,
99
- ): Promise<T> {
100
- const { signal, onProgress } = options;
234
+ ): Promise<YsUploadResult<T>> {
235
+ const { signal } = options;
101
236
  const timeoutMs = options.timeoutMs ?? FILE_CHUNK_TIMEOUT_MS;
237
+ const resume = options.resume || undefined;
238
+ const retries = Math.max(
239
+ 0,
240
+ options.retries ?? (resume ? FILE_CHUNK_RETRIES : 0),
241
+ );
242
+ const retryDelayMs = options.retryDelayMs ?? 500;
102
243
  signal?.throwIfAborted();
244
+ const name = file.name ?? "";
103
245
  let idKey = options.idKey ?? "";
104
246
  let id = "";
247
+ let resumeKey = "";
105
248
  let cancelled = false;
249
+ let reported = -1;
250
+ const report = (ratio: number, phase: YsFilePhase, phaseRatio: number) => {
251
+ if (ratio <= reported) return;
252
+ reported = ratio;
253
+ options.onProgress?.(ratio, phase, phaseRatio);
254
+ };
106
255
  const cancel = () => {
256
+ if (resumeKey) removeRecord(resumeKey);
107
257
  if (cancelled || !id) return;
108
258
  cancelled = true;
109
259
  // 不等结果:半截文件让服务端尽快清掉,取消失败也不影响抛出原错误。
@@ -111,52 +261,238 @@ export async function uploadChunked<T = unknown>(
111
261
  .then(() => call(options.cancelEvent, { [idKey]: id }))
112
262
  .catch(() => undefined);
113
263
  };
114
- const beginPromise = call(options.begin.event, {
115
- name: file.name ?? "",
116
- size: file.size,
117
- ...options.begin.data,
118
- }).then((result) => {
119
- const begin = (result ?? {}) as Record<string, unknown>;
120
- if (!idKey) idKey = "upload_id" in begin ? "upload_id" : "_id";
121
- id = String(begin[idKey] ?? "");
122
- // begin 回来前已经中止:补发 cancel,丢掉服务端刚建的上传。
123
- if (signal?.aborted) cancel();
124
- return begin;
125
- });
264
+
126
265
  try {
127
- const begin = await abortable(beginPromise, signal);
266
+ const checksum = await sha256Hex(file, {
267
+ signal,
268
+ onProgress: (ratio) =>
269
+ report(ratio * FILE_HASH_PROGRESS_WEIGHT, "hash", ratio),
270
+ });
271
+ let record: ResumeRecord | undefined;
272
+ if (resume) {
273
+ sweepRecords();
274
+ resumeKey =
275
+ FILE_UPLOAD_RESUME_PREFIX +
276
+ [options.begin.event, checksum, file.size, resume.key ?? ""].join("|");
277
+ record = readRecord(resumeKey);
278
+ }
279
+ const beginPromise = call(options.begin.event, {
280
+ name,
281
+ size: file.size,
282
+ checksum,
283
+ ...(resume ? { resume_key: resume.key ?? "" } : {}),
284
+ ...(record ? { resume_id: record.id } : {}),
285
+ ...options.begin.data,
286
+ }).then((result) => {
287
+ const begin = (result ?? {}) as Record<string, unknown>;
288
+ if (begin.status !== "challenge") {
289
+ if (!idKey) idKey = "upload_id" in begin ? "upload_id" : "_id";
290
+ id = String(begin[idKey] ?? "");
291
+ if (id && resumeKey)
292
+ writeRecord(resumeKey, {
293
+ id,
294
+ idKey,
295
+ expiresAt:
296
+ Date.now() + (resume?.ttlMs ?? FILE_UPLOAD_RESUME_TTL_MS),
297
+ });
298
+ }
299
+ // begin 回来前已经中止:补发 cancel,丢掉服务端刚建的上传。
300
+ if (signal?.aborted) cancel();
301
+ return begin;
302
+ });
303
+ const session = await abortable(beginPromise, signal);
304
+
305
+ const duplicates = Array.isArray(session.duplicates)
306
+ ? (session.duplicates as YsFileDuplicate[])
307
+ : [];
308
+ if (duplicates.length && options.onDuplicates) {
309
+ const decision = await abortable(
310
+ Promise.resolve(options.onDuplicates(duplicates)),
311
+ signal,
312
+ );
313
+ if (decision === false)
314
+ throw new DOMException(
315
+ "已存在相同内容的文件,已取消上传",
316
+ "AbortError",
317
+ );
318
+ }
319
+
320
+ if (session.status === "challenge") {
321
+ const ranges = Array.isArray(session.ranges)
322
+ ? (session.ranges as { start: number; length: number }[])
323
+ : [];
324
+ const proofs = await proveRanges(
325
+ file,
326
+ String(session.nonce ?? ""),
327
+ ranges,
328
+ signal,
329
+ );
330
+ const result = await abortable(
331
+ call(
332
+ options.proveEvent ?? FILE_PROVE_EVENT,
333
+ { challenge_id: session.challenge_id, proofs },
334
+ { timeoutMs },
335
+ ),
336
+ signal,
337
+ );
338
+ if (resumeKey) removeRecord(resumeKey);
339
+ report(1, "upload", 1);
340
+ return withInstant(result, true) as YsUploadResult<T>;
341
+ }
342
+
128
343
  if (!id)
129
344
  throw new Error(`${options.begin.event} 没有返回上传编号 ${idKey}`);
130
- const chunkSize = positive(begin.chunk_size) ?? FILE_CHUNK_SIZE;
345
+ const chunkSize = positive(session.chunk_size) ?? FILE_CHUNK_SIZE;
131
346
  const count =
132
- nonNegative(begin.chunk_count) ?? Math.ceil(file.size / chunkSize);
133
- onProgress?.(0);
134
- for (let index = 0; index < count; index += 1) {
347
+ nonNegative(session.chunk_count) ?? Math.ceil(file.size / chunkSize);
348
+ const start = Math.min(nonNegative(session.received) ?? 0, count);
349
+ const uploadReport = (done: number) => {
350
+ const phaseRatio = count ? done / count : 0;
351
+ report(
352
+ FILE_HASH_PROGRESS_WEIGHT +
353
+ (1 - FILE_HASH_PROGRESS_WEIGHT) * phaseRatio,
354
+ "upload",
355
+ phaseRatio,
356
+ );
357
+ };
358
+ uploadReport(start);
359
+ for (let index = start; index < count; index += 1) {
135
360
  const piece = file.slice(index * chunkSize, (index + 1) * chunkSize);
136
361
  const data = await abortable(blobToBase64(piece), signal);
137
- await abortable(
138
- call(
139
- options.chunkEvent,
140
- { [idKey]: id, index, size: piece.size, data },
141
- { timeoutMs },
142
- ),
362
+ await withRetry(
363
+ () =>
364
+ abortable(
365
+ call(
366
+ options.chunkEvent,
367
+ { [idKey]: id, index, size: piece.size, data },
368
+ { timeoutMs },
369
+ ),
370
+ signal,
371
+ ),
372
+ retries,
373
+ retryDelayMs,
143
374
  signal,
144
375
  );
145
- onProgress?.((index + 1) / count);
376
+ uploadReport(index + 1);
146
377
  }
147
- const checksum = await abortable(sha256Hex(file), signal);
148
- const result = (await abortable(
378
+ const result = await abortable(
149
379
  call(options.finishEvent, { [idKey]: id, checksum }, { timeoutMs }),
150
380
  signal,
151
- )) as T;
152
- if (!count) onProgress?.(1);
153
- return result;
381
+ );
382
+ if (resumeKey) removeRecord(resumeKey);
383
+ report(1, "upload", 1);
384
+ return withInstant(result, false) as YsUploadResult<T>;
154
385
  } catch (error) {
386
+ // 开启续传时,连接断开、超时这类失败保留记录、不发 cancel,下次同一内容从断点接着传。
387
+ if (resumeKey && !signal?.aborted && isTransient(error)) throw error;
155
388
  cancel();
156
389
  throw error;
157
390
  }
158
391
  }
159
392
 
393
+ function withInstant(result: unknown, instant: boolean): unknown {
394
+ if (
395
+ result &&
396
+ typeof result === "object" &&
397
+ !Array.isArray(result) &&
398
+ !("instant" in result)
399
+ )
400
+ return { ...(result as Record<string, unknown>), instant };
401
+ return result;
402
+ }
403
+
404
+ /** 网络中断、超时、服务暂不可用:可以重试或续传。带数字 code 的错误视为服务端已明确答复。 */
405
+ function isTransient(error: unknown): boolean {
406
+ if (error instanceof YsLocalFileError) return false;
407
+ if ((error as { name?: unknown } | null)?.name === "AbortError") return false;
408
+ const code = (error as { code?: unknown } | null)?.code;
409
+ if (typeof code === "number") return RETRY_CODES.has(code);
410
+ return true;
411
+ }
412
+
413
+ const RETRY_CODES = new Set([408, 429, 502, 503, 504]);
414
+
415
+ async function withRetry<T>(
416
+ run: () => Promise<T>,
417
+ retries: number,
418
+ delayMs: number,
419
+ signal?: AbortSignal,
420
+ ): Promise<T> {
421
+ for (let attempt = 0; ; attempt += 1) {
422
+ try {
423
+ return await run();
424
+ } catch (error) {
425
+ if (attempt >= retries || signal?.aborted || !isTransient(error))
426
+ throw error;
427
+ await abortable(
428
+ new Promise((resolve) => setTimeout(resolve, delayMs * 2 ** attempt)),
429
+ signal,
430
+ );
431
+ }
432
+ }
433
+ }
434
+
435
+ function storage(): Storage | undefined {
436
+ try {
437
+ return globalThis.localStorage ?? undefined;
438
+ } catch {
439
+ return undefined;
440
+ }
441
+ }
442
+
443
+ function readRecord(key: string): ResumeRecord | undefined {
444
+ try {
445
+ const raw = storage()?.getItem(key);
446
+ if (!raw) return undefined;
447
+ const record = JSON.parse(raw) as Partial<ResumeRecord>;
448
+ if (
449
+ typeof record.id === "string" &&
450
+ record.id &&
451
+ typeof record.idKey === "string" &&
452
+ record.idKey &&
453
+ typeof record.expiresAt === "number" &&
454
+ record.expiresAt > Date.now()
455
+ )
456
+ return record as ResumeRecord;
457
+ } catch {
458
+ // 记录损坏:当作没有。
459
+ }
460
+ removeRecord(key);
461
+ return undefined;
462
+ }
463
+
464
+ function writeRecord(key: string, record: ResumeRecord): void {
465
+ try {
466
+ storage()?.setItem(key, JSON.stringify(record));
467
+ } catch {
468
+ // 存不下(隐私模式、配额满)就不记,服务端照样按内容续传。
469
+ }
470
+ }
471
+
472
+ function removeRecord(key: string): void {
473
+ try {
474
+ storage()?.removeItem(key);
475
+ } catch {
476
+ // 忽略
477
+ }
478
+ }
479
+
480
+ /** 顺手清掉过期的续传记录,免得 localStorage 越积越多。 */
481
+ function sweepRecords(): void {
482
+ const store = storage();
483
+ if (!store) return;
484
+ try {
485
+ const keys: string[] = [];
486
+ for (let index = 0; index < store.length; index += 1) {
487
+ const key = store.key(index);
488
+ if (key?.startsWith(FILE_UPLOAD_RESUME_PREFIX)) keys.push(key);
489
+ }
490
+ keys.forEach((key) => readRecord(key));
491
+ } catch {
492
+ // 忽略
493
+ }
494
+ }
495
+
160
496
  export interface YsReadChunkedOptions {
161
497
  onProgress?: YsFileProgress;
162
498
  signal?: AbortSignal;
package/src/index.ts CHANGED
@@ -41,8 +41,14 @@ export {
41
41
  type PasswordWrap,
42
42
  } from "./password";
43
43
  export {
44
+ FILE_CHUNK_RETRIES,
44
45
  FILE_CHUNK_SIZE,
45
46
  FILE_CHUNK_TIMEOUT_MS,
47
+ FILE_HASH_PROGRESS_WEIGHT,
48
+ FILE_HASH_SLICE_SIZE,
49
+ FILE_PROVE_EVENT,
50
+ FILE_UPLOAD_RESUME_PREFIX,
51
+ FILE_UPLOAD_RESUME_TTL_MS,
46
52
  YsLocalFileError,
47
53
  base64ToBytes,
48
54
  blobToBase64,
@@ -50,9 +56,14 @@ export {
50
56
  sha256Hex,
51
57
  uploadChunked,
52
58
  type YsFileCall,
59
+ type YsFileDuplicate,
60
+ type YsFilePhase,
53
61
  type YsFileProgress,
54
62
  type YsReadChunkedOptions,
63
+ type YsSha256Options,
55
64
  type YsUploadChunkedOptions,
65
+ type YsUploadResult,
66
+ type YsUploadResumeOptions,
56
67
  } from "./fileTransfer";
57
68
  export {
58
69
  normalizeSearchText,