Skip to content

Commit 4ab69ec

Browse files
author
Pelle Wessman
authored
Convert to CJS (#15)
1 parent f1a9014 commit 4ab69ec

File tree

7 files changed

+146
-98
lines changed

7 files changed

+146
-98
lines changed

build/generate-types.js

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
1-
import openapiTS from 'openapi-typescript'
1+
'use strict'
22

3-
const localPath = new URL('../openapi.json', import.meta.url)
3+
Promise.resolve().then(async () => {
4+
const { default: openapiTS } = await import('openapi-typescript')
45

5-
const output = await openapiTS(localPath, {
6-
formatter (node) {
7-
if (node.format === 'binary') {
8-
return 'never'
6+
const localPath = new URL('../openapi.json', import.meta.url)
7+
const output = await openapiTS(localPath, {
8+
formatter (node) {
9+
if (node.format === 'binary') {
10+
return 'never'
11+
}
912
}
10-
}
11-
})
13+
})
1214

13-
// eslint-disable-next-line no-console
14-
console.log(output)
15+
// eslint-disable-next-line no-console
16+
console.log(output)
17+
}).catch(err => {
18+
// eslint-disable-next-line no-console
19+
console.error('Failed with error:', err.stack)
20+
process.exit(1)
21+
})

build/prettify-base-json.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
1-
import { readFile, writeFile } from 'node:fs/promises'
2-
import path from 'node:path'
1+
'use strict'
32

4-
const openApiData = await readFile(path.join(__dirname, '../openapi.json'), 'utf8')
3+
const { readFile, writeFile } = require('node:fs/promises')
4+
const path = require('node:path')
55

6-
await writeFile(path.join(__dirname, '../openapi.json'), JSON.stringify(JSON.parse(openApiData), undefined, 2))
6+
Promise.resolve().then(async () => {
7+
const openApiData = await readFile(path.join(__dirname, '../openapi.json'), 'utf8')
8+
9+
await writeFile(path.join(__dirname, '../openapi.json'), JSON.stringify(JSON.parse(openApiData), undefined, 2))
10+
}).catch(err => {
11+
// eslint-disable-next-line no-console
12+
console.error('Failed with error:', err.stack)
13+
process.exit(1)
14+
})

index.js

Lines changed: 110 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import path from 'node:path'
1+
'use strict'
22

3-
import { FormData } from 'formdata-node'
4-
import { fileFromPath } from 'formdata-node/file-from-path'
5-
import got from 'got'
3+
const path = require('node:path')
64

7-
import { handleApiError } from './lib/helpers.js'
5+
const { ErrorWithCause } = require('pony-cause')
86

97
/**
108
* @template {keyof import('./types/api').operations} T
@@ -27,10 +25,16 @@ import { handleApiError } from './lib/helpers.js'
2725
* @property {string} [baseUrl]
2826
*/
2927

30-
export class SocketSdk {
31-
/** @type {import('got').Got} */
28+
class SocketSdk {
29+
/** @type {import('got').Got|undefined} */
3230
#client
3331

32+
/** @type {typeof import('got').HTTPError|undefined} */
33+
#HTTPError
34+
35+
/** @type {import('got').ExtendOptions} */
36+
#gotOptions
37+
3438
/**
3539
* @param {string} apiKey
3640
* @param {SocketSdkOptions} options
@@ -42,12 +46,29 @@ export class SocketSdk {
4246
baseUrl = 'https://api.socket.dev/v0/',
4347
} = options
4448

45-
this.#client = got.extend({
49+
this.#gotOptions = {
4650
prefixUrl: baseUrl,
4751
retry: { limit: 0 },
4852
username: apiKey,
4953
...(agent ? { agent } : {}),
50-
})
54+
}
55+
}
56+
57+
/**
58+
* @returns {Promise<import('got').Got>}
59+
*/
60+
async #getClient () {
61+
if (!this.#client) {
62+
const {
63+
default: got,
64+
HTTPError,
65+
} = await import('got')
66+
67+
this.#HTTPError = HTTPError
68+
this.#client = got.extend(this.#gotOptions)
69+
}
70+
71+
return this.#client
5172
}
5273

5374
/**
@@ -59,6 +80,16 @@ export class SocketSdk {
5980
const basePath = path.resolve(process.cwd(), pathsRelativeTo)
6081
const absoluteFilePaths = filePaths.map(filePath => path.resolve(basePath, filePath))
6182

83+
const [
84+
{ FormData },
85+
{ fileFromPath },
86+
client
87+
] = await Promise.all([
88+
import('formdata-node'),
89+
import('formdata-node/file-from-path'),
90+
this.#getClient(),
91+
])
92+
6293
const body = new FormData()
6394

6495
const files = await Promise.all(absoluteFilePaths.map(absoluteFilePath => fileFromPath(absoluteFilePath)))
@@ -72,11 +103,11 @@ export class SocketSdk {
72103
}
73104

74105
try {
75-
const data = await this.#client.put('report/upload', { body }).json()
106+
const data = await client.put('report/upload', { body }).json()
76107

77108
return { success: true, status: 200, data }
78109
} catch (err) {
79-
return /** @type {SocketSdkErrorType<'createReport'>} */ (handleApiError(err))
110+
return /** @type {SocketSdkErrorType<'createReport'>} */ (this.#handleApiError(err))
80111
}
81112
}
82113

@@ -90,10 +121,11 @@ export class SocketSdk {
90121
const versionParam = encodeURIComponent(version)
91122

92123
try {
93-
const data = await this.#client.get(`npm/${pkgParam}/${versionParam}/score`).json()
124+
const client = await this.#getClient()
125+
const data = await client.get(`npm/${pkgParam}/${versionParam}/score`).json()
94126
return { success: true, status: 200, data }
95127
} catch (err) {
96-
return /** @type {SocketSdkErrorType<'getScoreByNPMPackage'>} */ (handleApiError(err))
128+
return /** @type {SocketSdkErrorType<'getScoreByNPMPackage'>} */ (this.#handleApiError(err))
97129
}
98130
}
99131

@@ -107,20 +139,22 @@ export class SocketSdk {
107139
const versionParam = encodeURIComponent(version)
108140

109141
try {
110-
const data = await this.#client.get(`npm/${pkgParam}/${versionParam}/issues`).json()
142+
const client = await this.#getClient()
143+
const data = await client.get(`npm/${pkgParam}/${versionParam}/issues`).json()
111144
return { success: true, status: 200, data }
112145
} catch (err) {
113-
return /** @type {SocketSdkErrorType<'getIssuesByNPMPackage'>} */ (handleApiError(err))
146+
return /** @type {SocketSdkErrorType<'getIssuesByNPMPackage'>} */ (this.#handleApiError(err))
114147
}
115148
}
116149

117150
/** @returns {Promise<SocketSdkResultType<'getReportList'>>} */
118151
async getReportList () {
119152
try {
120-
const data = await this.#client.get('report/list').json()
153+
const client = await this.#getClient()
154+
const data = await client.get('report/list').json()
121155
return { success: true, status: 200, data }
122156
} catch (err) {
123-
return /** @type {SocketSdkErrorType<'getReportList'>} */ (handleApiError(err))
157+
return /** @type {SocketSdkErrorType<'getReportList'>} */ (this.#handleApiError(err))
124158
}
125159
}
126160

@@ -132,20 +166,75 @@ export class SocketSdk {
132166
const idParam = encodeURIComponent(id)
133167

134168
try {
135-
const data = await this.#client.get(`report/view/${idParam}`).json()
169+
const client = await this.#getClient()
170+
const data = await client.get(`report/view/${idParam}`).json()
136171
return { success: true, status: 200, data }
137172
} catch (err) {
138-
return /** @type {SocketSdkErrorType<'getReport'>} */ (handleApiError(err))
173+
return /** @type {SocketSdkErrorType<'getReport'>} */ (this.#handleApiError(err))
139174
}
140175
}
141176

142177
/** @returns {Promise<SocketSdkResultType<'getQuota'>>} */
143178
async getQuota () {
144179
try {
145-
const data = await this.#client.get('quota').json()
180+
const client = await this.#getClient()
181+
const data = await client.get('quota').json()
146182
return { success: true, status: 200, data }
147183
} catch (err) {
148-
return /** @type {SocketSdkErrorType<'getQuota'>} */ (handleApiError(err))
184+
return /** @type {SocketSdkErrorType<'getQuota'>} */ (this.#handleApiError(err))
149185
}
150186
}
187+
188+
/**
189+
* @param {unknown} err
190+
* @returns {{ success: false, status: number, error: Record<string,unknown> }}
191+
*/
192+
#handleApiError (err) {
193+
if (this.#HTTPError && err instanceof this.#HTTPError) {
194+
if (err.response.statusCode >= 500) {
195+
throw new ErrorWithCause('API returned an error', { cause: err })
196+
}
197+
198+
return {
199+
success: false,
200+
status: err.response.statusCode,
201+
error: this.#getApiErrorDescription(err)
202+
}
203+
}
204+
205+
throw new ErrorWithCause('Unexpected error when calling API', { cause: err })
206+
}
207+
208+
/**
209+
* @param {import('got').HTTPError} err
210+
* @returns {Record<string,unknown>}
211+
*/
212+
#getApiErrorDescription (err) {
213+
/** @type {unknown} */
214+
let rawBody
215+
216+
try {
217+
rawBody = JSON.parse(/** @type {string} */ (err.response.body))
218+
} catch (cause) {
219+
throw new ErrorWithCause('Could not parse API error response', { cause })
220+
}
221+
222+
const errorDescription = ensureObject(rawBody) ? rawBody['error'] : undefined
223+
224+
if (!ensureObject(errorDescription)) {
225+
throw new Error('Invalid body on API error response')
226+
}
227+
228+
return errorDescription
229+
}
230+
}
231+
232+
/**
233+
* @param {unknown} value
234+
* @returns {value is { [key: string]: unknown }}
235+
*/
236+
function ensureObject (value) {
237+
return !!(value && typeof value === 'object' && !Array.isArray(value))
151238
}
239+
240+
module.exports = { SocketSdk }

lib/helpers.js

Lines changed: 0 additions & 53 deletions
This file was deleted.

package.json

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,12 @@
1313
"type": "git",
1414
"url": "git://github.com/SocketDev/socket-sdk-js.git"
1515
},
16-
"type": "module",
1716
"main": "index.js",
1817
"types": "index.d.ts",
1918
"files": [
2019
"index.d.ts.map",
2120
"index.d.ts",
2221
"index.js",
23-
"lib/**/*.d.ts.map",
24-
"lib/**/*.d.ts",
25-
"lib/**/*.js",
2622
"types/**/*.d.ts"
2723
],
2824
"engines": {

test/main.spec.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import chai from 'chai'
2-
import chaiAsPromised from 'chai-as-promised'
3-
import nock from 'nock'
4-
import { ErrorWithCause } from 'pony-cause'
1+
'use strict'
52

6-
import { SocketSdk } from '../index.js'
3+
const chai = require('chai')
4+
const chaiAsPromised = require('chai-as-promised')
5+
const nock = require('nock')
6+
const { ErrorWithCause } = require('pony-cause')
7+
8+
const { SocketSdk } = require('../index.js')
79

810
chai.use(chaiAsPromised)
911
chai.should()

tsconfig.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
],
66
"include": [
77
"build/**/*",
8-
"lib/**/*",
98
"test/**/*",
109
],
1110
"compilerOptions": {

0 commit comments

Comments
 (0)