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
191 lines (163 loc) · 5.7 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
'use strict'
/* eslint-env browser */
const Multiaddr = require('multiaddr')
const { isBrowser, isWebWorker, isNode } = require('ipfs-utils/src/env')
const parseDuration = require('parse-duration').default
const log = require('debug')('ipfs-http-client:lib:error-handler')
const HTTP = require('ipfs-utils/src/http')
const merge = require('merge-options')
const toUrlString = require('ipfs-core-utils/src/to-url-string')
const http = require('http')
const https = require('https')
const DEFAULT_PROTOCOL = isBrowser || isWebWorker ? location.protocol : 'http'
const DEFAULT_HOST = isBrowser || isWebWorker ? location.hostname : 'localhost'
const DEFAULT_PORT = isBrowser || isWebWorker ? location.port : '5001'
/**
* @param {ClientOptions|URL|Multiaddr|string} [options]
* @returns {ClientOptions}
*/
const normalizeOptions = (options = {}) => {
let url
let opts = {}
let agent
if (typeof options === 'string' || Multiaddr.isMultiaddr(options)) {
url = new URL(toUrlString(options))
} else if (options instanceof URL) {
url = options
} else if (typeof options.url === 'string' || Multiaddr.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 = url.protocol.startsWith('https') ? https.Agent : http.Agent
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
}
}
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 (err) {
log('Failed to parse error response', err)
// Failed to extract/parse error message from response
msg = err.message
}
let error = new HTTP.HTTPError(response)
// This is what go-ipfs returns where there's a timeout
if (msg && msg.includes('context deadline exceeded')) {
error = new HTTP.TimeoutError(response)
}
// This also gets returned
if (msg && msg.includes('request timed out')) {
error = new HTTP.TimeoutError(response)
}
// 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
const kebabCase = (str) => {
return str.replace(KEBAB_REGEX, function (match) {
return '-' + match.toLowerCase()
})
}
const parseTimeout = (value) => {
return typeof value === 'string' ? parseDuration(value) : value
}
/**
* @typedef {import('http').Agent} HttpAgent
* @typedef {import('https').Agent} HttpsAgent
*
* @typedef {Object} ClientOptions
* @property {string} [host]
* @property {number} [port]
* @property {string} [protocol]
* @property {Headers|Record<string, string>} [headers] - Request headers.
* @property {number|string} [timeout] - Amount of time until request should timeout in ms or humand readable. https://www.npmjs.com/package/parse-duration for valid string values.
* @property {string} [apiPath] - Path to the API.
* @property {URL|string|Multiaddr} [url] - Full API URL.
* @property {object} [ipld]
* @property {any[]} [ipld.formats] - An array of additional [IPLD formats](https://github.com./ipld/interface-ipld-format) to support
* @property {(format: string) => Promise<any>} [ipld.loadFormat] - an async function that takes the name of an [IPLD format](https://github.com./ipld/interface-ipld-format) as a string and should return the implementation of that codec
* @property {HttpAgent|HttpsAgent} [agent] - A [http.Agent](https://nodejs.org/api/http.html#http_class_http_agent) used to control connection persistence and reuse for HTTP clients (only supported in node.js)
*/
class Client extends HTTP {
/**
* @param {ClientOptions|URL|Multiaddr|string} [options]
*/
constructor (options = {}) {
const opts = normalizeOptions(options)
super({
timeout: parseTimeout(opts.timeout) || 60000 * 20,
headers: opts.headers,
base: `${opts.url}`,
handleError: errorHandler,
transformSearchParams: (search) => {
const out = new URLSearchParams()
// @ts-ignore https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
for (const [key, value] of search) {
if (
value !== 'undefined' &&
value !== 'null' &&
key !== 'signal'
) {
out.append(kebabCase(key), value)
}
// server timeouts are strings
if (key === 'timeout' && !isNaN(value)) {
out.append(kebabCase(key), value)
}
}
return out
},
agent: opts.agent
})
delete this.get
delete this.put
delete this.delete
delete this.options
const fetch = this.fetch
this.fetch = (resource, options = {}) => {
return fetch.call(this, resource, merge(options, {
method: 'POST'
}))
}
}
}
Client.errorHandler = errorHandler
module.exports = Client