Skip to content

Commit 7302f24

Browse files
Matte22csmig
andauthored
refactor: migrate from cjs to esm (#88)
* Migration to ESM * update building to support esm --------- Co-authored-by: csmig <[email protected]>
1 parent 331a8b6 commit 7302f24

15 files changed

+639
-214
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ watched/
33
.vscode/
44
.env
55
*.log
6-
log.json
6+
log.json
7+
bundle.js

build.sh

+3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ printf "[BUILD_TASK] Fetching node_modules\n"
2929
rm -rf ./node_modules
3030
npm ci
3131

32+
# bundle
33+
npx esbuild index.js --bundle --platform=node --outfile=bundle.js
34+
3235
# version=$(git describe --tags | sed 's/\(.*\)-.*/\1/')
3336
version=$(jq -r .version package.json)
3437
printf "\n[BUILD_TASK] Using version string: $version\n"

index.js

+27-27
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
#!/usr/bin/env node
2-
3-
const minApiVersion = '1.2.7'
4-
5-
const { logger, getSymbol } = require('./lib/logger')
6-
const config = require('./lib/args')
7-
if (!config) {
2+
import { logger, getSymbol } from './lib/logger.js'
3+
import { options, configValid } from './lib/args.js'
4+
if (!configValid) {
5+
logger.error({ component: 'main', message: 'invalid configuration... Exiting'})
86
logger.end()
9-
return
7+
process.exit(1)
108
}
11-
const auth = require('./lib/auth')
12-
const api = require('./lib/api')
13-
const {serializeError} = require('serialize-error')
9+
import startFsEventWatcher from './lib/events.js'
10+
import { getOpenIDConfiguration, getToken } from './lib/auth.js'
11+
import * as api from './lib/api.js'
12+
import { serializeError } from 'serialize-error'
13+
import startScanner from './lib/scan.js'
14+
import semverGte from 'semver/functions/gte.js'
15+
16+
const minApiVersion = '1.2.7'
1417

1518
run()
1619

@@ -19,22 +22,20 @@ async function run() {
1922
logger.info({
2023
component: 'main',
2124
message: 'running',
22-
config: getObfuscatedConfig(config)
25+
options: getObfuscatedConfig(options)
2326
})
2427

2528
await preflightServices()
26-
if (config.mode === 'events') {
27-
const watcher = require('./lib/events')
28-
watcher.startFsEventWatcher()
29+
if (options.mode === 'events') {
30+
startFsEventWatcher()
2931
}
30-
else if (config.mode === 'scan') {
31-
const scanner = require('./lib/scan')
32-
scanner.startScanner()
32+
else if (options.mode === 'scan') {
33+
startScanner()
3334
}
3435
}
3536
catch (e) {
3637
logError(e)
37-
await logger.end()
38+
logger.end()
3839
}
3940
}
4041

@@ -63,25 +64,24 @@ function logError(e) {
6364
}
6465

6566
async function hasMinApiVersion () {
66-
const semverGte = require('semver/functions/gte')
6767
const [remoteApiVersion] = await api.getDefinition('$.info.version')
6868
logger.info({ component: 'main', message: `preflight API version`, minApiVersion, remoteApiVersion})
6969
if (semverGte(remoteApiVersion, minApiVersion)) {
7070
return true
7171
}
7272
else {
73-
throw( `Remote API version ${remoteApiVersion} is not compatible with this release.` )
73+
throw new Error(`Remote API version ${remoteApiVersion} is not compatible with this release.`)
7474
}
7575
}
7676

7777
async function preflightServices () {
7878
await hasMinApiVersion()
79-
await auth.getOpenIDConfiguration()
80-
await auth.getToken()
79+
await getOpenIDConfiguration()
80+
await getToken()
8181
logger.info({ component: 'main', message: `preflight token request suceeded`})
8282
const promises = [
83-
api.getCollection(config.collectionId),
84-
api.getCollectionAssets(config.collectionId),
83+
api.getCollection(options.collectionId),
84+
api.getCollectionAssets(options.collectionId),
8585
api.getInstalledStigs(),
8686
api.getScapBenchmarkMap()
8787
]
@@ -100,8 +100,8 @@ async function preflightServices () {
100100
logger.info({ component: 'main', message: `prefilght api requests suceeded`})
101101
}
102102

103-
function getObfuscatedConfig (config) {
104-
const securedConfig = {...config}
103+
function getObfuscatedConfig (options) {
104+
const securedConfig = {...options}
105105
if (securedConfig.clientSecret) {
106106
securedConfig.clientSecret = '[hidden]'
107107
}
@@ -119,7 +119,7 @@ async function refreshUser() {
119119

120120
async function refreshCollection() {
121121
try {
122-
await api.getCollection(config.collectionId)
122+
await api.getCollection(options.collectionId)
123123
}
124124
catch (e) {
125125
logError(e)

lib/api.js

+30-32
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
2-
const got = require('got')
3-
const config = require('./args')
4-
const auth = require('./auth')
5-
const { logger, getSymbol } = require('./logger')
6-
const { serializeError } = require('serialize-error')
1+
import got from 'got'
2+
import { options } from './args.js'
3+
import { getToken, tokens } from './auth.js'
4+
import { logger, getSymbol } from './logger.js'
75

86
const cache = {
97
collection: null,
@@ -13,21 +11,21 @@ const cache = {
1311
scapBenchmarkMap: null,
1412
stigs: null
1513
}
16-
17-
module.exports.cache = cache
14+
const _cache = cache
15+
export { _cache as cache }
1816

1917
async function apiGet(endpoint, authenticate = true) {
2018
try {
21-
const options = {
19+
const requestOptions = {
2220
responseType: 'json'
2321
}
2422
if (authenticate) {
25-
await auth.getToken()
26-
options.headers = {
27-
Authorization: `Bearer ${auth.tokens.access_token}`
23+
await getToken()
24+
requestOptions.headers = {
25+
Authorization: `Bearer ${tokens.access_token}`
2826
}
2927
}
30-
const response = await got.get(`${config.api}${endpoint}`, options)
28+
const response = await got.get(`${options.api}${endpoint}`, requestOptions)
3129
logResponse (response )
3230
return response.body
3331
}
@@ -38,38 +36,38 @@ async function apiGet(endpoint, authenticate = true) {
3836
}
3937
}
4038

41-
module.exports.getScapBenchmarkMap = async function () {
39+
export async function getScapBenchmarkMap() {
4240
const response = await apiGet('/stigs/scap-maps')
4341
cache.scapBenchmarkMap = new Map(response.map(apiScapMap => [apiScapMap.scapBenchmarkId, apiScapMap.benchmarkId]))
4442
return cache.scapBenchmarkMap
4543
}
4644

47-
module.exports.getDefinition = async function (jsonPath) {
45+
export async function getDefinition(jsonPath) {
4846
cache.definition = await apiGet(`/op/definition${jsonPath ? '?jsonpath=' + encodeURIComponent(jsonPath) : ''}`, false)
4947
return cache.definition
5048
}
5149

52-
module.exports.getCollection = async function (collectionId) {
50+
export async function getCollection(collectionId) {
5351
cache.collection = await apiGet(`/collections/${collectionId}`)
5452
return cache.collection
5553
}
5654

57-
module.exports.getCollectionAssets = async function (collectionId) {
55+
export async function getCollectionAssets(collectionId) {
5856
cache.assets = await apiGet(`/assets?collectionId=${collectionId}&projection=stigs`)
5957
return cache.assets
6058
}
6159

62-
module.exports.getInstalledStigs = async function () {
60+
export async function getInstalledStigs() {
6361
cache.stigs = await apiGet('/stigs')
6462
return cache.stigs
6563
}
6664

67-
module.exports.createOrGetAsset = async function (asset) {
65+
export async function createOrGetAsset(asset) {
6866
try {
69-
await auth.getToken()
70-
const response = await got.post(`${config.api}/assets?projection=stigs`, {
67+
await getToken()
68+
const response = await got.post(`${options.api}/assets?projection=stigs`, {
7169
headers: {
72-
Authorization: `Bearer ${auth.tokens.access_token}`
70+
Authorization: `Bearer ${tokens.access_token}`
7371
},
7472
json: asset,
7573
responseType: 'json'
@@ -87,12 +85,12 @@ module.exports.createOrGetAsset = async function (asset) {
8785
}
8886
}
8987

90-
module.exports.patchAsset = async function (assetId, body) {
88+
export async function patchAsset(assetId, body) {
9189
try {
92-
await auth.getToken()
93-
const response = await got.patch(`${config.api}/assets/${assetId}?projection=stigs`, {
90+
await getToken()
91+
const response = await got.patch(`${options.api}/assets/${assetId}?projection=stigs`, {
9492
headers: {
95-
Authorization: `Bearer ${auth.tokens.access_token}`
93+
Authorization: `Bearer ${tokens.access_token}`
9694
},
9795
json: body,
9896
responseType: 'json'
@@ -106,12 +104,12 @@ module.exports.patchAsset = async function (assetId, body) {
106104
}
107105
}
108106

109-
module.exports.postReviews = async function (collectionId, assetId, reviews) {
107+
export async function postReviews(collectionId, assetId, reviews) {
110108
try {
111-
await auth.getToken()
112-
const response = await got.post(`${config.api}/collections/${collectionId}/reviews/${assetId}`, {
109+
await getToken()
110+
const response = await got.post(`${options.api}/collections/${collectionId}/reviews/${assetId}`, {
113111
headers: {
114-
Authorization: `Bearer ${auth.tokens.access_token}`
112+
Authorization: `Bearer ${tokens.access_token}`
115113
},
116114
json: reviews,
117115
responseType: 'json'
@@ -125,12 +123,12 @@ module.exports.postReviews = async function (collectionId, assetId, reviews) {
125123
}
126124
}
127125

128-
module.exports.getUser = async function () {
126+
export async function getUser() {
129127
cache.user = await apiGet('/user')
130128
return cache.user
131129
}
132130

133-
module.exports.canUserAccept = function () {
131+
export function canUserAccept() {
134132
const curUser = cache.user
135133
const apiCollection = cache.collection
136134
const userGrant = curUser.collectionGrants.find( i => i.collection.collectionId === apiCollection.collectionId )?.accessLevel

0 commit comments

Comments
 (0)