-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
90 lines (70 loc) · 1.7 KB
/
Copy pathutils.js
File metadata and controls
90 lines (70 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class NReader {
#reader;
#remainder;
constructor(reader) {
this.#reader = reader;
this.#remainder = new Uint8Array();
}
async readExactly(n) {
if (this.#remainder.length >= n) {
const buf = this.#remainder.slice(0, n);
this.#remainder = this.#remainder.slice(n);
return buf;
}
const buf = new Uint8Array(n);
let offset = 0;
while (offset < n) {
const { value, done } = await this.#reader.read();
if (done) {
throw new Error("Done too soon");
}
const needed = n - offset;
if (value.length >= needed) {
buf.set(value.slice(0, needed), offset);
this.#remainder = value.slice(needed);
break;
}
else {
buf.set(value, offset);
offset += value.length;
}
}
return buf;
}
}
async function* readStreamLines(readableStream) {
const reader = readableStream.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true });
let lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
yield line;
}
}
if (buffer) {
yield buffer;
}
} finally {
reader.releaseLock();
}
}
const encoder = new TextEncoder();
async function computeHash(input) {
const data = encoder.encode(input);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hashBuffer))
.map(byte => byte.toString(16).padStart(2, "0"))
.join("");
}
export {
readStreamLines,
computeHash,
}