-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathdeploy.js
More file actions
325 lines (268 loc) · 8.79 KB
/
Copy pathdeploy.js
File metadata and controls
325 lines (268 loc) · 8.79 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
'use strict'
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const { dnsLinkersMap } = require('./dnslinkers')
const { pinnersMap } = require('./pinners')
const { guessPath, getReadableSize, terminalUrl } = require('./utils')
/**
* @typedef {import('./dnslinkers/types').DNSLinker} DNSLinker
* @typedef {import('./pinners/types').PinningService} PinningService
* @typedef {import('./pinners/types').PinDirOptions} PinDirOptions
* @typedef {import('./types').DeployOptions} DeployOptions
* @typedef {import('./types').Logger} Logger
*/
/**
* @param {PinningService[]} services
* @param {string|undefined} cid
* @param {string|undefined} dir
* @param {PinDirOptions} pinOpts
* @param {Logger} logger
*/
async function pinCidOrDir (services, cid, dir, pinOpts, logger) {
const pinnedCids = []
const gatewayUrls = []
if (!cid && !dir) {
throw new Error('either cid or dir is required')
}
if (dir) {
dir = path.resolve(dir)
}
for (const service of services) {
const serviceName = chalk.whiteBright(service.displayName)
let lastCid
if (cid) {
logger.info(`📠 Pinning CID to ${serviceName}…`)
await service.pinCid(cid, pinOpts.tag)
lastCid = cid
logger.info(`📌 CID pinned to ${serviceName}:`)
} else {
logger.info(`📠 Uploading and pinning to ${serviceName}…`)
// @ts-ignore
lastCid = await service.pinDir(dir, pinOpts)
logger.info(`📌 Added and pinned to ${serviceName} with CID:`)
}
const url = service.gatewayUrl(lastCid)
logger.info(terminalUrl(lastCid, url))
gatewayUrls.push(url)
pinnedCids.push(lastCid)
}
return {
pinnedCids,
gatewayUrls
}
}
/**
* @param {DNSLinker[]} services
* @param {string} cid
* @param {Logger} logger
*/
async function dnsLink (services, cid, logger) {
const hostnames = []
for (const provider of services) {
const providerName = chalk.whiteBright(provider.displayName)
logger.info(`📡 Beaming new CID to DNS provider ${providerName}…`)
const { record, value } = await provider.link(cid)
logger.info(`🔄 Updated DNS TXT ${chalk.whiteBright(record)} to:`)
logger.info(`🔗 ${chalk.whiteBright(value)}`)
hostnames.push(record.split('.').slice(1).join('.'))
}
return hostnames
}
/**
* Copy URL to clipboard. This function does not throw, but
* prints any error instead as it is not a fundamental part of
* the deploying process.
*
* @param {string[]} hostnames
* @param {string[]} gatewayUrls
* @param {Logger} logger
*/
function copyToClipboard (hostnames, gatewayUrls, logger) {
let toCopy
if (hostnames.length > 0) {
toCopy = hostnames[hostnames.length - 1]
} else {
toCopy = gatewayUrls[gatewayUrls.length - 1]
}
logger.info('📋 Copying HTTP gateway URL to clipboard…')
if (!toCopy.startsWith('https')) {
toCopy = `https://${toCopy}`
}
try {
const clipboardy = require('clipboardy')
clipboardy.writeSync(toCopy)
logger.info('📋 Copied HTTP gateway URL to clipboard:')
logger.info(terminalUrl(toCopy, toCopy))
} catch (e) {
logger.info('⚠️ Could not copy URL to clipboard.')
logger.error(e.stack || e.toString())
}
}
/**
* Open URLs on web browser. This function does not throw, but
* prints any error instead as it is not a fundamental part of
* the deploying process.
*
* @param {string[]} gatewayUrls
* @param {string[]} hostnames
* @param {Logger} logger
*/
function openUrlsBrowser (gatewayUrls, hostnames, logger) {
logger.info('🏄 Opening URLs on web browser...')
try {
const open = require('open')
gatewayUrls.forEach(url => { open(url) })
hostnames.forEach(hostname => open(`https://${hostname}`))
logger.info('🏄 All URLs opened.')
} catch (e) {
logger.info('⚠️ Could not open URLs on web browser.')
logger.error(e.stack || e.toString())
}
}
const dummyLogger = /** @type {Logger} */({
info: () => {},
error: () => {},
out: () => {}
})
/**
* @param {string|undefined} dir
* @param {string|undefined} cid
* @param {Logger} logger
*/
async function checkDirAndCid (dir, cid, logger) {
if (dir && cid) {
throw new Error('cannot deploy a directory and a CID at the same time')
}
if (!dir && !cid) {
logger.info(`🤔 No ${chalk.whiteBright('path')} argument specified. Looking for common ones…`)
dir = guessPath()
logger.info(`📂 Found local ${chalk.blueBright(dir)} directory. Deploying that.`)
} else if (dir) {
logger.info(`📂 Deploying ${chalk.blueBright(dir)} directory.`)
} else if (cid) {
logger.info(`📂 Deploying ${chalk.blueBright(cid)}.`)
}
if (dir) {
logger.info(`📦 Calculating size of ${chalk.blueBright(dir)}…`)
const readableSize = await getReadableSize(dir)
logger.info(`🚚 Directory ${chalk.blueBright(dir)} weighs ${readableSize}.`)
dir = path.normalize(dir)
if (!fs.statSync(dir).isDirectory()) {
logger.info('⚠️ Given path is not a directory. Continuing.')
}
}
return { cid, dir }
}
/**
* @param {DNSLinker[]} dnsServices
* @param {PinningService[]} pinServices
* @param {Logger} logger
*/
async function unpin (dnsServices, pinServices, logger) {
/** @type {string[]} */
const linkedCids = []
for (const dnsProvider of dnsServices) {
logger.info(`Getting linked cid from ${dnsProvider.displayName}`)
const cid = await dnsProvider.getLinkedCid()
logger.info(`Got cid: ${cid}`)
linkedCids.push(cid)
}
if (linkedCids.some(v => v !== linkedCids[0])) {
throw new Error(`Found inconsistency in linked CIDs: ${linkedCids}`)
}
const cidToUnpin = linkedCids[0]
if (!cidToUnpin) {
logger.info('There is nothing to unpin')
return
}
for (const pinProvider of pinServices) {
logger.info(`Unpinning ${cidToUnpin} from ${pinProvider.displayName}`)
await pinProvider.unpinCid(cidToUnpin, logger)
}
}
/**
* @param {DeployOptions} options
* @returns {Promise<string>}
*/
async function deploy ({
dir,
cid,
tag,
copyUrl = false,
openUrls = false,
hiddenFiles = false,
unpinOld = false,
uploadServices: uploadServicesIds = [],
pinningServices: pinningServicesIds = [],
dnsProviders: dnsProvidersIds = [],
dnsProvidersCredentials = {},
pinningServicesCredentials = {},
logger = dummyLogger
}) {
const res = await checkDirAndCid(dir, cid, logger)
dir = res.dir
cid = res.cid
tag = tag || __dirname
// In the case we only set pinning services and we're deploying a directory,
// then call those upload services.
if (pinningServicesIds.length > 0 && uploadServicesIds.length === 0 && dir) {
uploadServicesIds = pinningServicesIds
pinningServicesIds = []
}
if (uploadServicesIds.length + pinningServicesIds.length === 0) {
throw new Error('an upload or pinning service is required to deploy')
}
if (cid && uploadServicesIds.length > 0) {
throw new Error('cannot use uploading services to deploy CIDs')
}
logger.info('⚙️ Validating pinners configurations…')
const uploadServices = uploadServicesIds.map(name => {
const Pinner = pinnersMap.get(name)
return new Pinner(pinningServicesCredentials[name])
})
const pinningServices = pinningServicesIds.map(name => {
const Pinner = pinnersMap.get(name)
return new Pinner(pinningServicesCredentials[name])
})
logger.info('⚙️ Validating DNS providers configurations…')
const dnsProviders = dnsProvidersIds.map(name => {
const DNSLinker = dnsLinkersMap.get(name)
// logger.info(dnsProvidersCredentials[name])
return new DNSLinker(dnsProvidersCredentials[name])
})
if (unpinOld) {
if (dnsProviders.length === 0) {
throw new Error('If you want to unpin you must provide dns provider')
}
await unpin(dnsProviders, uploadServices.concat(pinningServices), logger)
}
const pinnedCids = /** @type {string[]} */([])
const gatewayUrls = /** @type {string[]} */([])
if (uploadServices.length > 0) {
const res = await pinCidOrDir(uploadServices, undefined, dir, { tag, hidden: hiddenFiles }, logger)
pinnedCids.push(...res.pinnedCids)
gatewayUrls.push(...res.gatewayUrls)
}
// If one of the pinned CIDs doesn't match the other ones,
// alert about that.
if (pinnedCids.some(v => v !== pinnedCids[0])) {
throw new Error(`Found inconsistency in pinned CIDs: ${pinnedCids}`)
}
cid = cid || pinnedCids[0]
if (pinningServices.length > 0) {
const res = await pinCidOrDir(pinningServices, cid, undefined, { tag }, logger)
pinnedCids.push(...res.pinnedCids)
gatewayUrls.push(...res.gatewayUrls)
}
const hostnames = await dnsLink(dnsProviders, cid, logger)
if (openUrls) {
openUrlsBrowser(gatewayUrls, hostnames, logger)
}
if (copyUrl) {
copyToClipboard(hostnames, gatewayUrls, logger)
}
logger.out(cid)
return cid
}
module.exports = deploy