-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
273 lines (252 loc) · 7.76 KB
/
index.js
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/* eslint max-depth: ["error", 7] */
import { Token, Type } from 'cborg'
import * as cborgJson from 'cborg/json'
import { CID } from 'multiformats'
import { base64 } from 'multiformats/bases/base64'
/**
* @template T
* @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
*/
/**
* @template T
* @typedef {import('multiformats').ToString<T>} ToString
*/
/**
* @typedef {import('cborg/interface').DecodeTokenizer} DecodeTokenizer
*/
/**
* cidEncoder will receive all Objects during encode, it needs to filter out
* anything that's not a CID and return `null` for that so it's encoded as
* normal. Encoding a CID means replacing it with a `{"/":"<CidString>}`
* object as per the DAG-JSON spec.
*
* @param {any} obj
* @returns {Token[]|null}
*/
function cidEncoder (obj) {
if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
return null // any other kind of object
}
const cid = CID.asCID(obj)
/* c8 ignore next 4 */
// very unlikely case, and it'll probably throw a recursion error in cborg
if (!cid) {
return null
}
const cidString = cid.toString()
return [
new Token(Type.map, Infinity, 1),
new Token(Type.string, '/', 1), // key
new Token(Type.string, cidString, cidString.length), // value
new Token(Type.break, undefined, 1)
]
}
/**
* bytesEncoder will receive all Uint8Arrays (and friends) during encode, it
* needs to replace it with a `{"/":{"bytes":"Base64ByteString"}}` object as
* per the DAG-JSON spec.
*
* @param {Uint8Array} bytes
* @returns {Token[]|null}
*/
function bytesEncoder (bytes) {
const bytesString = base64.encode(bytes).slice(1) // no mbase prefix
return [
new Token(Type.map, Infinity, 1),
new Token(Type.string, '/', 1), // key
new Token(Type.map, Infinity, 1), // value
new Token(Type.string, 'bytes', 5), // inner key
new Token(Type.string, bytesString, bytesString.length), // inner value
new Token(Type.break, undefined, 1),
new Token(Type.break, undefined, 1)
]
}
/**
* taBytesEncoder wraps bytesEncoder() but for the more exotic typed arrays so
* that we access the underlying ArrayBuffer data
*
* @param {Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|Uint8ClampedArray|BigInt64Array|BigUint64Array} obj
* @returns {Token[]|null}
*/
function taBytesEncoder (obj) {
return bytesEncoder(new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
}
/**
* abBytesEncoder wraps bytesEncoder() but for plain ArrayBuffers
*
* @param {ArrayBuffer} ab
* @returns {Token[]|null}
*/
function abBytesEncoder (ab) {
return bytesEncoder(new Uint8Array(ab))
}
// eslint-disable-next-line jsdoc/require-returns-check
/**
* Intercept all `undefined` values from an object walk and reject the entire
* object if we find one.
*
* @returns {null}
*/
function undefinedEncoder () {
throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}
/**
* Intercept all `number` values from an object walk and reject the entire
* object if we find something that doesn't fit the IPLD data model (NaN &
* Infinity).
*
* @param {number} num
* @returns {null}
*/
function numberEncoder (num) {
if (Number.isNaN(num)) {
throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
}
if (num === Infinity || num === -Infinity) {
throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
}
return null // process with standard number encoder
}
const encodeOptions = {
typeEncoders: {
Object: cidEncoder,
Buffer: bytesEncoder,
Uint8Array: bytesEncoder,
Int8Array: taBytesEncoder,
Uint16Array: taBytesEncoder,
Int16Array: taBytesEncoder,
Uint32Array: taBytesEncoder,
Int32Array: taBytesEncoder,
Float32Array: taBytesEncoder,
Float64Array: taBytesEncoder,
Uint8ClampedArray: taBytesEncoder,
BigInt64Array: taBytesEncoder,
BigUint64Array: taBytesEncoder,
DataView: taBytesEncoder,
ArrayBuffer: abBytesEncoder,
undefined: undefinedEncoder,
number: numberEncoder
}
}
/**
* @implements {DecodeTokenizer}
*/
class DagJsonTokenizer extends cborgJson.Tokenizer {
/**
* @param {Uint8Array} data
* @param {object} [options]
*/
constructor (data, options) {
super(data, options)
/** @type {Token[]} */
this.tokenBuffer = []
}
/**
* @returns {boolean}
*/
done () {
return this.tokenBuffer.length === 0 && super.done()
}
/**
* @returns {Token}
*/
_next () {
if (this.tokenBuffer.length > 0) {
// @ts-ignore https://github.com/Microsoft/TypeScript/issues/30406
return this.tokenBuffer.pop()
}
return super.next()
}
/**
* Implements rules outlined in https://github.com/ipld/specs/pull/356
*
* @returns {Token}
*/
next () {
const token = this._next()
if (token.type === Type.map) {
const keyToken = this._next()
if (keyToken.type === Type.string && keyToken.value === '/') {
const valueToken = this._next()
if (valueToken.type === Type.string) { // *must* be a CID
const breakToken = this._next() // swallow the end-of-map token
if (breakToken.type !== Type.break) {
throw new Error('Invalid encoded CID form')
}
this.tokenBuffer.push(valueToken) // CID.parse will pick this up after our tag token
return new Token(Type.tag, 42, 0)
}
if (valueToken.type === Type.map) {
const innerKeyToken = this._next()
if (innerKeyToken.type === Type.string && innerKeyToken.value === 'bytes') {
const innerValueToken = this._next()
if (innerValueToken.type === Type.string) { // *must* be Bytes
for (let i = 0; i < 2; i++) {
const breakToken = this._next() // swallow two end-of-map tokens
if (breakToken.type !== Type.break) {
throw new Error('Invalid encoded Bytes form')
}
}
const bytes = base64.decode(`m${innerValueToken.value}`)
return new Token(Type.bytes, bytes, innerValueToken.value.length)
}
this.tokenBuffer.push(innerValueToken) // bail
}
this.tokenBuffer.push(innerKeyToken) // bail
}
this.tokenBuffer.push(valueToken) // bail
}
this.tokenBuffer.push(keyToken) // bail
}
return token
}
}
const decodeOptions = {
allowIndefinite: false,
allowUndefined: false,
allowNaN: false,
allowInfinity: false,
allowBigInt: true, // this will lead to BigInt for ints outside of
// safe-integer range, which may surprise users
strict: true,
useMaps: false,
rejectDuplicateMapKeys: true,
/** @type {import('cborg').TagDecoder[]} */
tags: []
}
// we're going to get TAG(42)STRING("bafy...") from the tokenizer so we only need
// to deal with the STRING("bafy...") at this point
decodeOptions.tags[42] = CID.parse
export const name = 'dag-json'
export const code = 0x0129
/**
* @template T
* @param {T} node
* @returns {ByteView<T>}
*/
export const encode = (node) => cborgJson.encode(node, encodeOptions)
/**
* @template T
* @param {ByteView<T>} data
* @returns {T}
*/
export const decode = (data) => {
// the tokenizer is stateful so we need a single instance of it
const options = Object.assign(decodeOptions, { tokenizer: new DagJsonTokenizer(data, decodeOptions) })
return cborgJson.decode(data, options)
}
/**
* @template T
* @param {T} node
* @returns {ToString<T>}
*/
export const format = (node) => utf8Decoder.decode(encode(node))
export { format as stringify }
const utf8Decoder = new TextDecoder()
/**
* @template T
* @param {ToString<T>} data
* @returns {T}
*/
export const parse = (data) => decode(utf8Encoder.encode(data))
const utf8Encoder = new TextEncoder()