-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
encode.ts
236 lines (198 loc) · 5.49 KB
/
encode.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import * as constants from './constants'
import { FullJid, jidDecode } from './jid-utils'
import type { BinaryNode, BinaryNodeCodingOptions } from './types'
export const encodeBinaryNode = (
{ tag, attrs, content }: BinaryNode,
opts: Pick<BinaryNodeCodingOptions, 'TAGS' | 'TOKEN_MAP'> = constants,
buffer: number[] = [0]
) => {
const { TAGS, TOKEN_MAP } = opts
const pushByte = (value: number) => buffer.push(value & 0xff)
const pushInt = (value: number, n: number, littleEndian = false) => {
for(let i = 0; i < n; i++) {
const curShift = littleEndian ? i : n - 1 - i
buffer.push((value >> (curShift * 8)) & 0xff)
}
}
const pushBytes = (bytes: Uint8Array | Buffer | number[]) => (
bytes.forEach (b => buffer.push(b))
)
const pushInt16 = (value: number) => {
pushBytes([(value >> 8) & 0xff, value & 0xff])
}
const pushInt20 = (value: number) => (
pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
)
const writeByteLength = (length: number) => {
if(length >= 4294967296) {
throw new Error('string too large to encode: ' + length)
}
if(length >= 1 << 20) {
pushByte(TAGS.BINARY_32)
pushInt(length, 4) // 32 bit integer
} else if(length >= 256) {
pushByte(TAGS.BINARY_20)
pushInt20(length)
} else {
pushByte(TAGS.BINARY_8)
pushByte(length)
}
}
const writeStringRaw = (str: string) => {
const bytes = Buffer.from (str, 'utf-8')
writeByteLength(bytes.length)
pushBytes(bytes)
}
const writeJid = ({ domainType, device, user, server }: FullJid) => {
if(typeof device !== 'undefined') {
pushByte(TAGS.AD_JID)
pushByte(domainType || 0)
pushByte(device || 0)
writeString(user)
} else {
pushByte(TAGS.JID_PAIR)
if(user.length) {
writeString(user)
} else {
pushByte(TAGS.LIST_EMPTY)
}
writeString(server)
}
}
const packNibble = (char: string) => {
switch (char) {
case '-':
return 10
case '.':
return 11
case '\0':
return 15
default:
if(char >= '0' && char <= '9') {
return char.charCodeAt(0) - '0'.charCodeAt(0)
}
throw new Error(`invalid byte for nibble "${char}"`)
}
}
const packHex = (char: string) => {
if(char >= '0' && char <= '9') {
return char.charCodeAt(0) - '0'.charCodeAt(0)
}
if(char >= 'A' && char <= 'F') {
return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
}
if(char >= 'a' && char <= 'f') {
return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
}
if(char === '\0') {
return 15
}
throw new Error(`Invalid hex char "${char}"`)
}
const writePackedBytes = (str: string, type: 'nibble' | 'hex') => {
if(str.length > TAGS.PACKED_MAX) {
throw new Error('Too many bytes to pack')
}
pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
let roundedLength = Math.ceil(str.length / 2.0)
if(str.length % 2 !== 0) {
roundedLength |= 128
}
pushByte(roundedLength)
const packFunction = type === 'nibble' ? packNibble : packHex
const packBytePair = (v1: string, v2: string) => {
const result = (packFunction(v1) << 4) | packFunction(v2)
return result
}
const strLengthHalf = Math.floor(str.length / 2)
for(let i = 0; i < strLengthHalf;i++) {
pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
}
if(str.length % 2 !== 0) {
pushByte(packBytePair(str[str.length - 1], '\x00'))
}
}
const isNibble = (str: string) => {
if(str.length > TAGS.PACKED_MAX) {
return false
}
for(let i = 0;i < str.length;i++) {
const char = str[i]
const isInNibbleRange = char >= '0' && char <= '9'
if(!isInNibbleRange && char !== '-' && char !== '.') {
return false
}
}
return true
}
const isHex = (str: string) => {
if(str.length > TAGS.PACKED_MAX) {
return false
}
for(let i = 0;i < str.length;i++) {
const char = str[i]
const isInNibbleRange = char >= '0' && char <= '9'
if(!isInNibbleRange && !(char >= 'A' && char <= 'F') && !(char >= 'a' && char <= 'f')) {
return false
}
}
return true
}
const writeString = (str: string) => {
const tokenIndex = TOKEN_MAP[str]
if(tokenIndex) {
if(typeof tokenIndex.dict === 'number') {
pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
}
pushByte(tokenIndex.index)
} else if(isNibble(str)) {
writePackedBytes(str, 'nibble')
} else if(isHex(str)) {
writePackedBytes(str, 'hex')
} else if(str) {
const decodedJid = jidDecode(str)
if(decodedJid) {
writeJid(decodedJid)
} else {
writeStringRaw(str)
}
}
}
const writeListStart = (listSize: number) => {
if(listSize === 0) {
pushByte(TAGS.LIST_EMPTY)
} else if(listSize < 256) {
pushBytes([TAGS.LIST_8, listSize])
} else {
pushByte(TAGS.LIST_16)
pushInt16(listSize)
}
}
const validAttributes = Object.keys(attrs).filter(k => (
typeof attrs[k] !== 'undefined' && attrs[k] !== null
))
writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
writeString(tag)
for(const key of validAttributes) {
if(typeof attrs[key] === 'string') {
writeString(key)
writeString(attrs[key])
}
}
if(typeof content === 'string') {
writeString(content)
} else if(Buffer.isBuffer(content) || content instanceof Uint8Array) {
writeByteLength(content.length)
pushBytes(content)
} else if(Array.isArray(content)) {
writeListStart(content.length)
for(const item of content) {
encodeBinaryNode(item, opts, buffer)
}
} else if(typeof content === 'undefined') {
// do nothing
} else {
throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
}
return Buffer.from(buffer)
}