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