codekingpro/portable-devtools
114k
1'use strict'
2
3const { URL } = require('node:url')
4
5function packageName (href) {
6 try {
7 let basePath = new URL(href).pathname.slice(1)
8 if (!basePath.match(/^-/)) {
9 basePath = basePath.split('/')
10 var index = basePath.indexOf('_rewrite')
11 if (index === -1) {
12 index = basePath.length - 1
13 } else {
14 index++
15 }
16 return decodeURIComponent(basePath[index])
17 }
18 } catch {
19 // this is ok
20 }
21}
22
23class HttpErrorBase extends Error {
24 constructor (method, res, body, spec) {
25 super()
26 this.name = this.constructor.name
27 this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers
28 this.statusCode = res.status
29 this.code = `E${res.status}`
30 this.method = method
31 this.uri = res.url
32 this.body = body
33 this.pkgid = spec ? spec.toString() : packageName(res.url)
34 Error.captureStackTrace(this, this.constructor)
35 }
36}
37
38class HttpErrorGeneral extends HttpErrorBase {
39 constructor (method, res, body, spec) {
40 super(method, res, body, spec)
41 this.message = `${res.status} ${res.statusText} - ${
42 this.method.toUpperCase()
43 } ${
44 this.spec || this.uri
45 }${
46 (body && body.error) ? ' - ' + body.error : ''
47 }`
48 }
49}
50
51class HttpErrorAuthOTP extends HttpErrorBase {
52 constructor (method, res, body, spec) {
53 super(method, res, body, spec)
54 this.message = 'OTP required for authentication'
55 this.code = 'EOTP'
56 }
57}
58
59class HttpErrorAuthIPAddress extends HttpErrorBase {
60 constructor (method, res, body, spec) {
61 super(method, res, body, spec)
62 this.message = 'Login is not allowed from your IP address'
63 this.code = 'EAUTHIP'
64 }
65}
66
67class HttpErrorAuthUnknown extends HttpErrorBase {
68 constructor (method, res, body, spec) {
69 super(method, res, body, spec)
70 this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate')
71 }
72}
73
74module.exports = {
75 HttpErrorBase,
76 HttpErrorGeneral,
77 HttpErrorAuthOTP,
78 HttpErrorAuthIPAddress,
79 HttpErrorAuthUnknown,
80}
81 