This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathcore.js
212 lines (178 loc) · 5.45 KB
/
core.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
/* eslint-env browser */
import { isMultiaddr } from '@multiformats/multiaddr'
import { isBrowser, isWebWorker, isNode } from 'ipfs-utils/src/env.js'
import parseDuration from 'parse-duration'
import { logger } from '@libp2p/logger'
import HTTP from 'ipfs-utils/src/http.js'
import mergeOpts from 'merge-options'
import { toUrlString } from 'ipfs-core-utils/to-url-string'
import getAgent from 'ipfs-core-utils/agent'
const log = logger('ipfs-http-client:lib:error-handler')
const merge = mergeOpts.bind({ ignoreUndefined: true })
const DEFAULT_PROTOCOL = isBrowser || isWebWorker ? location.protocol : 'http'
const DEFAULT_HOST = isBrowser || isWebWorker ? location.hostname : 'localhost'
const DEFAULT_PORT = isBrowser || isWebWorker ? location.port : '5001'
/**
* @typedef {import('ipfs-utils/src/types').HTTPOptions} HTTPOptions
* @typedef {import('../types').Options} Options
* @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr
*/
/**
* @param {Options|URL|Multiaddr|string} [options]
* @returns {Options}
*/
const normalizeOptions = (options = {}) => {
let url
/** @type {Options} */
let opts = {}
let agent
if (typeof options === 'string' || isMultiaddr(options)) {
url = new URL(toUrlString(options))
} else if (options instanceof URL) {
url = options
} else if (typeof options.url === 'string' || isMultiaddr(options.url)) {
url = new URL(toUrlString(options.url))
opts = options
} else if (options.url instanceof URL) {
url = options.url
opts = options
} else {
opts = options || {}
const protocol = (opts.protocol || DEFAULT_PROTOCOL).replace(':', '')
const host = (opts.host || DEFAULT_HOST).split(':')[0]
const port = (opts.port || DEFAULT_PORT)
url = new URL(`${protocol}://${host}:${port}`)
}
if (opts.apiPath) {
url.pathname = opts.apiPath
} else if (url.pathname === '/' || url.pathname === undefined) {
url.pathname = 'api/v0'
}
if (isNode) {
const Agent = getAgent(url)
agent = opts.agent || new Agent({
keepAlive: true,
// Similar to browsers which limit connections to six per host
maxSockets: 6
})
}
return {
...opts,
host: url.host,
protocol: url.protocol.replace(':', ''),
port: Number(url.port),
apiPath: url.pathname,
url,
agent
}
}
/**
* @param {Response} response
*/
export const errorHandler = async (response) => {
let msg
try {
if ((response.headers.get('Content-Type') || '').startsWith('application/json')) {
const data = await response.json()
log(data)
msg = data.Message || data.message
} else {
msg = await response.text()
}
} catch (/** @type {any} */ err) {
log('Failed to parse error response', err)
// Failed to extract/parse error message from response
msg = err.message
}
/** @type {Error} */
let error = new HTTP.HTTPError(response)
if (msg) {
// This is what rs-ipfs returns where there's a timeout
if (msg.includes('deadline has elapsed')) {
error = new HTTP.TimeoutError()
}
// This is what go-ipfs returns where there's a timeout
if (msg && msg.includes('context deadline exceeded')) {
error = new HTTP.TimeoutError()
}
}
// This also gets returned
if (msg && msg.includes('request timed out')) {
error = new HTTP.TimeoutError()
}
// If we managed to extract a message from the response, use it
if (msg) {
error.message = msg
}
throw error
}
const KEBAB_REGEX = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g
/**
* @param {string} str
*/
const kebabCase = (str) => {
return str.replace(KEBAB_REGEX, function (match) {
return '-' + match.toLowerCase()
})
}
/**
* @param {string | number} value
*/
const parseTimeout = (value) => {
return typeof value === 'string' ? parseDuration(value) : value
}
export class Client extends HTTP {
/**
* @param {Options|URL|Multiaddr|string} [options]
*/
constructor (options = {}) {
const opts = normalizeOptions(options)
super({
timeout: parseTimeout(opts.timeout || 0) || undefined,
headers: opts.headers,
base: `${opts.url}`,
handleError: errorHandler,
transformSearchParams: (search) => {
const out = new URLSearchParams()
for (const [key, value] of search) {
if (
value !== 'undefined' &&
value !== 'null' &&
key !== 'signal'
) {
out.append(kebabCase(key), value)
}
// @ts-expect-error server timeouts are strings
if (key === 'timeout' && !isNaN(value)) {
out.append(kebabCase(key), value)
}
}
return out
},
// @ts-expect-error this can be a https agent or a http agent
agent: opts.agent
})
// @ts-expect-error - cannot delete no-optional fields
delete this.get
// @ts-expect-error - cannot delete no-optional fields
delete this.put
// @ts-expect-error - cannot delete no-optional fields
delete this.delete
// @ts-expect-error - cannot delete no-optional fields
delete this.options
const fetch = this.fetch
/**
* @param {string | Request} resource
* @param {HTTPOptions} options
*/
this.fetch = (resource, options = {}) => {
if (typeof resource === 'string' && !resource.startsWith('/')) {
resource = `${opts.url}/${resource}`
}
return fetch.call(this, resource, merge(options, {
method: 'POST'
}))
}
}
}
export const HTTPError = HTTP.HTTPError