/
ceramic-http-client.ts
262 lines (229 loc) · 7.42 KB
/
ceramic-http-client.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
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
import { typeStreamID } from './utils.js'
import { Document } from './document.js'
import type { DID } from 'dids'
import {
CreateOpts,
CeramicCommit,
fetchJson,
Stream,
StreamConstructor,
StreamHandler,
StreamUtils,
LoadOpts,
MultiQuery,
PinApi,
UpdateOpts,
SyncOptions,
AnchorStatus,
IndexApi,
StreamState,
AdminApi,
AnchorOpts,
CeramicSigner,
CreateJWSOptions,
DagJWS,
DagJWSResult,
VerifyJWSOptions,
VerifyJWSResult,
UnderlyingCeramicSigner,
StreamReaderWriter,
} from '@ceramicnetwork/common'
import { TileDocument } from '@ceramicnetwork/stream-tile'
import { Caip10Link } from '@ceramicnetwork/stream-caip10-link'
import { Model } from '@ceramicnetwork/stream-model'
import { ModelInstanceDocument } from '@ceramicnetwork/stream-model-instance'
import { StreamID, CommitID, StreamRef } from '@ceramicnetwork/streamid'
import { RemoteIndexApi } from './remote-index-api.js'
import { RemoteAdminApi } from './remote-admin-api.js'
import { DummyPinApi } from './dummy-pin-api.js'
const API_PATH = './api/v0/'
const CERAMIC_HOST = 'http://localhost:7007'
/**
* Default Ceramic client configuration
*/
export const DEFAULT_CLIENT_CONFIG: CeramicClientConfig = {
syncInterval: 5000,
}
const DEFAULT_APPLY_COMMIT_OPTS = { anchor: true, publish: true, sync: SyncOptions.PREFER_CACHE }
const DEFAULT_CREATE_FROM_GENESIS_OPTS = {
anchor: true,
publish: true,
sync: SyncOptions.PREFER_CACHE,
}
const DEFAULT_LOAD_OPTS = { sync: SyncOptions.PREFER_CACHE }
/**
* Ceramic client configuration
*/
export interface CeramicClientConfig {
/**
* How frequently the http-client polls the daemon for updates to subscribed-to streams, in milliseconds.
*/
syncInterval: number
}
/**
* Ceramic client implementation
*/
export class CeramicClient implements StreamReaderWriter {
// Stored as a member to make it easier to inject a mock in unit tests
private readonly _fetchJson: typeof fetchJson = fetchJson
private readonly _apiUrl: URL
private _supportedChains: Array<string>
public readonly pin: PinApi
public readonly admin: AdminApi
public readonly index: IndexApi
private _signer: CeramicSigner
private _did?: DID
private readonly _config: CeramicClientConfig
public readonly _streamConstructors: Record<number, StreamConstructor<Stream>>
constructor(apiHost: string = CERAMIC_HOST, config: Partial<CeramicClientConfig> = {}) {
this._signer = CeramicSigner.invalid()
this._config = { ...DEFAULT_CLIENT_CONFIG, ...config }
// API_PATH contains leading dot-slash, so preserves the full path
this._apiUrl = new URL(API_PATH, apiHost)
this.pin = new DummyPinApi()
this.index = new RemoteIndexApi(this._apiUrl)
const getDidFn = (() => {
return this.did
}).bind(this)
this.admin = new RemoteAdminApi(this._apiUrl, getDidFn)
this._streamConstructors = {
[Caip10Link.STREAM_TYPE_ID]: Caip10Link,
[Model.STREAM_TYPE_ID]: Model,
[ModelInstanceDocument.STREAM_TYPE_ID]: ModelInstanceDocument,
[TileDocument.STREAM_TYPE_ID]: TileDocument,
}
}
get signer(): CeramicSigner {
return this._signer
}
get did(): DID | undefined {
return this._did
}
/**
* Sets the DID instance that will be used to author commits to streams.
* @param did
*/
set did(did: DID) {
this._did = did
this._signer = CeramicSigner.fromDID(did)
}
/**
* @deprecated
*/
async setDID(did: DID): Promise<void> {
this.did = did
}
async createStreamFromGenesis<T extends Stream>(
type: number,
genesis: any,
opts: CreateOpts = {}
): Promise<T> {
opts = { ...DEFAULT_CREATE_FROM_GENESIS_OPTS, ...opts }
const stream = await Document.createFromGenesis(
this._apiUrl,
type,
genesis,
opts,
this._config.syncInterval
)
return this.buildStreamFromDocument<T>(stream)
}
async loadStream<T extends Stream>(
streamId: StreamID | CommitID | string,
opts: LoadOpts = {}
): Promise<T> {
opts = { ...DEFAULT_LOAD_OPTS, ...opts }
const streamRef = StreamRef.from(streamId)
const stream = await Document.load(streamRef, this._apiUrl, this._config.syncInterval, opts)
return this.buildStreamFromDocument<T>(stream)
}
async multiQuery(queries: Array<MultiQuery>, timeout?: number): Promise<Record<string, Stream>> {
const queriesJSON = queries.map((q) => {
return {
...q,
genesis: q.genesis ? StreamUtils.serializeCommit(q.genesis) : undefined,
streamId: typeof q.streamId === 'string' ? q.streamId : q.streamId.toString(),
}
})
const url = new URL('./multiqueries', this._apiUrl)
const results = await this._fetchJson(url, {
method: 'POST',
body: {
queries: queriesJSON,
...{ timeout },
},
})
return Object.entries(results).reduce((acc, e) => {
const [k, v] = e
const state = StreamUtils.deserializeState(v)
const stream = new Document(state, this._apiUrl, this._config.syncInterval)
acc[k] = this.buildStreamFromDocument(stream)
return acc
}, {})
}
loadStreamCommits(streamId: string | StreamID): Promise<Record<string, any>[]> {
const effectiveStreamId = typeStreamID(streamId)
return Document.loadStreamCommits(effectiveStreamId, this._apiUrl)
}
async applyCommit<T extends Stream>(
streamId: string | StreamID,
commit: CeramicCommit,
opts: UpdateOpts = {}
): Promise<T> {
opts = { ...DEFAULT_APPLY_COMMIT_OPTS, ...opts }
const effectiveStreamId: StreamID = typeStreamID(streamId)
const document = await Document.applyCommit(
this._apiUrl,
effectiveStreamId,
commit,
opts,
this._config.syncInterval
)
return this.buildStreamFromDocument<T>(document)
}
async requestAnchor(
streamId: string | StreamID,
opts: LoadOpts & AnchorOpts = {}
): Promise<AnchorStatus> {
opts = { ...DEFAULT_LOAD_OPTS, ...opts }
const { anchorStatus } = await this._fetchJson(
`${this._apiUrl}streams/${streamId.toString()}/anchor`,
{
method: 'POST',
body: {
opts,
},
}
)
return anchorStatus
}
addStreamHandler<T extends Stream>(streamHandler: StreamHandler<T>): void {
this._streamConstructors[streamHandler.name] = streamHandler.stream_constructor
}
/**
* Turns +state+ into a Stream instance of the appropriate StreamType.
* Does not add the resulting instance to a cache.
* @param state StreamState for a stream.
*/
buildStreamFromState<T extends Stream = Stream>(state: StreamState): T {
const stream$ = new Document(state, this._apiUrl, this._config.syncInterval)
return this.buildStreamFromDocument(stream$) as T
}
private buildStreamFromDocument<T extends Stream = Stream>(stream: Document): T {
const type = stream.state.type
const streamConstructor = this._streamConstructors[type]
if (!streamConstructor) throw new Error(`Failed to find constructor for stream ${type}`)
return new streamConstructor(stream, this) as T
}
async getSupportedChains(): Promise<Array<string>> {
if (this._supportedChains) {
return this._supportedChains
}
// Fetch the chainId from the daemon and cache the result
const { supportedChains } = await this._fetchJson(new URL('./node/chains', this._apiUrl))
this._supportedChains = supportedChains
return supportedChains
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async close(): Promise<void> {}
}