/
helia.ts
94 lines (80 loc) · 2.65 KB
/
helia.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
/* globals globalThis */
import { type Helia } from '@helia/interface'
import initHelia from '../lib/init-helia.js'
import type { KuboGatewayOptions } from '../types.d.js'
interface HeliaBundleState {
kuboGatewayOptions: KuboGatewayOptions
instance: Helia | null
error: Error | null
}
const defaultState: HeliaBundleState = {
kuboGatewayOptions: {
host: '127.0.0.1',
port: '8080',
protocol: 'http'
},
instance: null,
error: null
}
function getUserOpts (key: string): Record<string, unknown> {
let userOpts = {}
if (globalThis.localStorage != null) {
try {
const optsStr = globalThis.localStorage.getItem(key) ?? '{}'
userOpts = JSON.parse(optsStr)
} catch (error) {
console.error(`Error reading '${key}' value from localStorage`, error)
}
}
return userOpts
}
const bundle = {
name: 'helia',
reducer (state: HeliaBundleState, { type, payload, error }: { type: string, payload: Partial<HeliaBundleState>, error?: Error }) {
state = state ?? defaultState
if (type === 'HELIA_INIT_FINISHED') {
return Object.assign({}, state, {
instance: payload.instance ?? state.instance,
kuboGatewayOptions: payload.kuboGatewayOptions ?? state.kuboGatewayOptions,
error: null
})
}
if (type === 'HELIA_INIT_FAILED') {
return Object.assign({}, state, { error })
}
return state
},
selectHelia: ({ helia }: { helia: HeliaBundleState }) => helia.instance,
selectHeliaReady: ({ helia }: { helia: HeliaBundleState }) => helia.instance !== null,
selectHeliaIdentity: ({ helia }: { helia: HeliaBundleState }) => {
const identifyService = helia.instance?.libp2p.services?.identify as { host: Record<'agentVersion', string> }
return identifyService?.host?.agentVersion.split(' ')[0] ?? 'null'
},
doInitHelia: () => async ({ dispatch, getState }: any) => {
dispatch({ type: 'HELIA_INIT_STARTED' })
const kuboGatewayOptions = Object.assign(
{},
getState().helia.kuboGatewayOptions,
getUserOpts('kuboGateway')
)
try {
console.info(
"🎛️ Customise your Kubo gateway opts by setting an `kuboGateway` value in localStorage. e.g. localStorage.setItem('kuboGateway', JSON.stringify({port: '1337'}))"
)
console.time('HELIA_INIT')
const helia = await initHelia(kuboGatewayOptions)
console.timeEnd('HELIA_INIT')
return dispatch({
type: 'HELIA_INIT_FINISHED',
payload: {
kuboGatewayOptions,
instance: helia,
provider: 'helia'
}
})
} catch (error) {
return dispatch({ type: 'HELIA_INIT_FAILED', error })
}
}
}
export default bundle