-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjoin.ts
79 lines (58 loc) · 1.84 KB
/
join.ts
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
/**
* (c) Copyright 2024 by Coinkite Inc. This file is in the public domain.
*
* QR code decoding/joining.
*/
import { ENCODINGS, FILETYPES } from './consts';
import { Encoding, FileType, JoinResult } from './types';
import { decodeData } from './utils';
/**
* Decodes and joins QR code parts back to binary data.
*
* @param parts Array of QR code parts
* @returns Object containing the file type, encoding, and raw binary data.
*/
export function joinQRs(parts: string[]): JoinResult {
const headers = new Set(parts.map((p) => p.slice(0, 6)));
if (headers.size !== 1) {
throw new Error('conflicting/variable filetype/encodings/sizes');
}
const header = [...headers][0];
if (header.slice(0, 2) !== 'B$') {
throw new Error('fixed header not found, expected B$');
}
if (!ENCODINGS.has(header[2])) {
throw new Error(`bad encoding: ${header[2]}`);
}
if (!FILETYPES.has(header[3])) {
throw new Error(`bad file type: ${header[3]}`);
}
const encoding = header[2] as Encoding;
const fileType = header[3] as FileType;
const numParts = parseInt(header.slice(4, 6), 36);
if (numParts < 1) {
throw new Error('zero parts?');
}
const data = new Map<number, string>();
for (const p of parts) {
const idx = parseInt(p.slice(6, 8), 36);
if (idx >= numParts) {
throw new Error(`got part ${idx} but only expecting ${numParts}`);
}
if (data.has(idx) && data.get(idx) !== p.slice(8)) {
throw new Error(`Duplicate part 0x${idx.toString(16)} has wrong content`);
}
data.set(idx, p.slice(8));
}
const orderedParts = [];
for (let i = 0; i < numParts; i++) {
const p = data.get(i);
if (!p) {
throw new Error(`Part ${i} is missing`);
}
orderedParts.push(p);
}
const raw = decodeData(orderedParts, encoding);
return { fileType, encoding, raw };
}
// EOF