-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcar.js
67 lines (58 loc) · 1.76 KB
/
car.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
import * as API from '@ucanto/interface'
import * as CAR from './car/codec.js'
import { Delegation } from '@ucanto/core'
export { CAR as codec }
const HEADERS = Object.freeze({
'content-type': 'application/car',
})
/**
* Encodes invocation batch into an HTTPRequest.
*
* @template {API.Tuple<API.IssuedInvocation>} I
* @param {I} invocations
* @param {API.EncodeOptions} [options]
* @returns {Promise<API.HTTPRequest<I>>}
*/
export const encode = async (invocations, options) => {
const roots = []
const blocks = new Map()
for (const invocation of invocations) {
const delegation = await Delegation.delegate(invocation, options)
roots.push(delegation.root)
for (const block of delegation.export()) {
blocks.set(block.cid.toString(), block)
}
blocks.delete(delegation.root.cid.toString())
}
const body = CAR.encode({ roots, blocks })
return {
headers: HEADERS,
body,
}
}
/**
* Decodes HTTPRequest to an invocation batch.
*
* @template {API.Tuple<API.IssuedInvocation>} Invocations
* @param {API.HTTPRequest<Invocations>} request
* @returns {Promise<API.InferInvocations<Invocations>>}
*/
export const decode = async ({ headers, body }) => {
const contentType = headers['content-type'] || headers['Content-Type']
if (contentType !== 'application/car') {
throw TypeError(
`Only 'content-type: application/car' is supported, instead got '${contentType}'`
)
}
const { roots, blocks } = await CAR.decode(body)
const invocations = []
for (const root of /** @type {API.UCANBlock[]} */ (roots)) {
invocations.push(
Delegation.create({
root,
blocks: /** @type {Map<string, API.Block>} */ (blocks),
})
)
}
return /** @type {API.InferInvocations<Invocations>} */ (invocations)
}