Skip to content

Commit

Permalink
feat(cli): export config methods and adopt Command instances instea…
Browse files Browse the repository at this point in the history
…d of global `program`(#1130)
  • Loading branch information
mirceanis committed Feb 23, 2023
1 parent 44bb365 commit 9c73d98
Show file tree
Hide file tree
Showing 22 changed files with 406 additions and 209 deletions.
24 changes: 21 additions & 3 deletions jest.config.json → jest.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
{
// import path from "path";
// import { createRequire } from 'module';
//
// const chalkPath = (await import.meta.resolve("chalk"))

export default {
"moduleFileExtensions": [
"ts",
"tsx",
Expand All @@ -23,7 +28,9 @@
],
"coverageProvider": "v8",
"coverageDirectory": "./coverage",
"extensionsToTreatAsEsm": [".ts"],
"extensionsToTreatAsEsm": [
".ts"
],
"testMatch": [
"**/__tests__/**/*.test.*"
],
Expand All @@ -33,7 +40,18 @@
"./setupJest.js"
],
"moduleNameMapper": {
"^(\\.{1,2}/.*)\\.js$": "$1"
"^(\\.{1,2}/.*)\\.js$": "$1",

// // https://github.com/facebook/jest/issues/12270#issuecomment-1111533936
// chalk: path.join(chalkPath.split("chalk/")[0], "chalk").substring(5),
// "#ansi-styles": path.join(
// chalkPath.split("chalk/")[0],
// "chalk/source/vendor/ansi-styles/index.js",
// ).substring(5),
// "#supports-color": path.join(
// chalkPath.split("chalk/")[0],
// "chalk/source/vendor/supports-color/index.js",
// ).substring(5),
},
"transform": {
"^.+\\.m?tsx?$": [
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"test:integration-pretty": "prettier --write __tests__/shared/documentationExamples.ts",
"test:integration": "pnpm test:integration-build && pnpm test:ci",
"test:ci": "pnpm test -- --coverage=true",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"test": "cross-env NODE_OPTIONS=\"--experimental-vm-modules --experimental-import-meta-resolve\" jest",
"test:watch": "pnpm test --watch --verbose",
"test:browser": "cd packages/test-react-app && pnpm test:browser",
"veramo": "cross-env ./packages/cli/bin/veramo.js",
Expand Down Expand Up @@ -88,5 +88,7 @@
"engines": {
"node": ">= 18.0.0"
},
"workspaces": ["packages/*"]
"workspaces": [
"packages/*"
]
}
22 changes: 20 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,26 @@
"name": "@veramo/cli",
"description": "Veramo command line application.",
"version": "5.0.0",
"exports": {
".": {
"types": "./build/cli.d.ts",
"import": "./build/cli.js"
},
"./build/setup": {
"types": "./build/setup.d.ts",
"import": "./build/setup.js"
},
"./build/lib/objectCreator": {
"types": "./build/lib/objectCreator.d.ts",
"import": "./build/lib/objectCreator.js"
},
"./build/lib/agentCreator": {
"types":"./build/lib/agentCreator.d.ts",
"import":"./build/lib/agentCreator.js"
},
"./package.json": "./package.json"
},
"main": "build/cli.js",
"exports": "./build/cli.js",
"types": "build/cli.d.ts",
"bin": {
"veramo": "bin/veramo.js"
Expand Down Expand Up @@ -45,7 +63,7 @@
"@veramo/url-handler": "^5.0.0",
"@veramo/utils": "^5.0.0",
"blessed": "^0.1.81",
"commander": "^9.0.0",
"commander": "^10.0.0",
"console-table-printer": "^2.10.0",
"cors": "^2.8.5",
"cross-fetch": "^3.1.4",
Expand Down
42 changes: 42 additions & 0 deletions packages/cli/src/__tests__/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { veramo } from '../createCommand.js'
import { jest } from '@jest/globals'
import { createObjects } from '../lib/objectCreator'
import { getConfig } from '../setup'

jest.useFakeTimers()

describe('cli version', () => {
const writeMock = jest.fn()

beforeAll(() => {
// veramo
// .exitOverride()
// .configureOutput({ writeOut: writeMock })
})

afterAll(() => {
jest.clearAllMocks()
})

it.skip('should list version number', async () => {
expect(() => {
// veramo.parse(['--version'], { from: 'user' })
}).toThrow()
expect(writeMock).toHaveBeenCalledWith(expect.stringMatching(/^\d\.\d\.\d\n?$/))
})

it.skip('should load the dbConnection', async () => {
// this seems to fail because of some timing issues or an incompatibility with the `chalk` transitive dependency
// all other tests that need to load the dbConnection fail similarly
const res = await createObjects(getConfig('./packages/cli/default/default.yml'), {
my: '/dbConnection',
})
})

it.skip('should check the default config', async () => {
expect(() => {
// veramo.parse(['config', 'check', '-f', './packages/cli/default/default.yml'], { from: 'user' })
}).toThrow(/hello/)
expect(writeMock).toHaveBeenCalledWith(expect.stringMatching(/^\d\.\d\.\d\n?$/))
})
})
6 changes: 0 additions & 6 deletions packages/cli/src/__tests__/default.test.ts

This file was deleted.

20 changes: 3 additions & 17 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
import { program } from 'commander'
import inquirer from 'inquirer'
import inquirerAutoPrompt from 'inquirer-autocomplete-prompt'

inquirer.registerPrompt('autocomplete', inquirerAutoPrompt)

import './did.js'
import './credential.js'
import './presentation.js'
import './explore/index.js'
import './sdr.js'
import './message.js'
import './discover.js'
import './version.js'
import './execute.js'
import './server.js'
import './setup.js'
import './config.js'
import './dev.js'
import { veramo } from './createCommand.js'

if (!process.argv.slice(2).length) {
program.outputHelp()
veramo.outputHelp()
} else {
program.parse(process.argv)
veramo.parse(process.argv)
}
15 changes: 9 additions & 6 deletions packages/cli/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { program } from 'commander'
import { Command } from 'commander'
import { SecretBox } from '@veramo/kms-local'
import { getAgent } from './setup.js'
import fs from "fs"
import fs from 'fs'
import { dirname } from 'path'

import * as url from 'url';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
import * as url from 'url'

program.option('--config <path>', 'Configuration file', './agent.yml')
const __dirname = url.fileURLToPath(new URL('.', import.meta.url))

const config = program.command('config').description('Agent configuration')
const config = new Command('config').description('Agent configuration')

config
.command('create', { isDefault: true })
Expand Down Expand Up @@ -43,6 +42,8 @@ config
.command('create-secret-key')
.alias('gen-key')
.alias('key-gen')
.alias('keygen')
.alias('genkey')
.description('generate secret key')
.option('-q, --quiet', 'Only print the raw key, no instructions', false)
.action(async (options) => {
Expand Down Expand Up @@ -89,3 +90,5 @@ config
}
}
})

export { config }
34 changes: 34 additions & 0 deletions packages/cli/src/createCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Command } from 'commander'
import module from 'module'

import { config } from './config.js'
import { credential } from './credential.js'
import { dev } from './dev.js'
import { did } from './did.js'
import { discover } from './discover.js'
import { execute } from './execute.js'
import { message } from './message.js'
import { presentation } from './presentation.js'
import { explore } from './explore/index.js'
import { sdr } from './sdr.js'
import { server } from './server.js'

const requireCjs = module.createRequire(import.meta.url)
const { version } = requireCjs('../package.json')

const veramo = new Command('veramo')
.version(version, '-v, --version')
.option('--config <string>', 'Configuration file', './agent.yml')
.addCommand(config)
.addCommand(credential)
.addCommand(dev)
.addCommand(did)
.addCommand(discover)
.addCommand(execute)
.addCommand(explore)
.addCommand(message)
.addCommand(presentation)
.addCommand(sdr)
.addCommand(server)

export { veramo }
24 changes: 13 additions & 11 deletions packages/cli/src/credential.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAgent } from './setup.js'
import { program } from 'commander'
import { Command } from 'commander'
import inquirer from 'inquirer'
import qrcode from 'qrcode-terminal'
import * as fs from 'fs'
Expand All @@ -9,16 +9,16 @@ import { CredentialPayload } from '@veramo/core-types'

import fuzzy from 'fuzzy'

const credential = program.command('credential').description('W3C Verifiable Credential')
const credential = new Command('credential').description('W3C Verifiable Credential')

credential
.command('create', { isDefault: true })
.description('Create W3C Verifiable Credential')
.option('-s, --send', 'Send')
.option('-j, --json', 'Output in JSON')
.option('-q, --qrcode', 'Show qrcode')
.action(async (cmd) => {
const agent = await getAgent(program.opts().config)
.action(async (opts: { send: boolean; qrcode: boolean; json: boolean }, cmd: Command) => {
const agent = await getAgent(cmd.optsWithGlobals().config)
const identifiers = await agent.didManagerFind()

const knownDids = await agent.dataStoreORMGetIdentifiers()
Expand Down Expand Up @@ -127,7 +127,7 @@ credential
proofFormat: answers.proofFormat,
})

if (cmd.send) {
if (opts.send) {
let body
let type
if (answers.proofFormat == 'jwt') {
Expand All @@ -153,10 +153,10 @@ credential
}
}

if (cmd.qrcode) {
if (opts.qrcode) {
qrcode.generate(verifiableCredential.proof.jwt)
} else {
if (cmd.json) {
if (opts.json) {
console.log(JSON.stringify(verifiableCredential, null, 2))
} else {
console.dir(verifiableCredential, { depth: 10 })
Expand All @@ -169,8 +169,8 @@ credential
.description('Verify a W3C Verifiable Credential provided as raw string, file or stdin')
.option('-f, --filename <string>', 'Optional. Read the credential from a file instead of stdin')
.option('-r, --raw <string>', 'Optional. Specify the credential as a parameter instead of file or stdin')
.action(async (options) => {
const agent = await getAgent(program.opts().config)
.action(async (options: { raw: string; filename: string }, cmd: Command) => {
const agent = await getAgent(cmd.optsWithGlobals().config)
let raw: string = ''
if (options.raw) {
raw = options.raw
Expand Down Expand Up @@ -205,8 +205,8 @@ credential
credential
.command('output')
.description('Print W3C Verifiable Credential to stdout')
.action(async (cmd) => {
const agent = await getAgent(program.opts().config)
.action(async (opts: {}, cmd: Command) => {
const agent = await getAgent(cmd.optsWithGlobals().config)

const credentials = await agent.dataStoreORMGetVerifiableCredentials()

Expand Down Expand Up @@ -236,3 +236,5 @@ credential
console.log('No credentials found.')
}
})

export { credential }
14 changes: 8 additions & 6 deletions packages/cli/src/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ import {
ApiParameterListMixin,
ApiReturnTypeMixin,
} from '@microsoft/api-extractor-model'
import { program } from 'commander'
import { Command } from 'commander'
import { writeFileSync } from 'fs'
import { OpenAPIV3 } from 'openapi-types'
import { resolve } from 'path'
import * as TJS from 'ts-json-schema-generator'
import fs from 'fs'

import module from "module"
const requireCjs = module.createRequire(import.meta.url);
import module from 'module'

const requireCjs = module.createRequire(import.meta.url)

interface Method {
packageName: string
Expand All @@ -24,6 +23,7 @@ interface Method {
parameters?: string
response: string
}

const genericTypes = ['boolean', 'string', 'number', 'any', 'Array<string>']

function createSchema(generator: TJS.SchemaGenerator, symbol: string) {
Expand Down Expand Up @@ -84,7 +84,7 @@ function getReference(response: string): OpenAPIV3.ReferenceObject | OpenAPIV3.S
}
}

const dev = program.command('dev').description('Plugin developer tools')
const dev = new Command('dev').description('Plugin developer tools')

dev
.command('generate-plugin-schema')
Expand Down Expand Up @@ -129,7 +129,7 @@ dev
path: resolve(entryFile),
encodeRefs: false,
additionalProperties: true,
skipTypeCheck: true
skipTypeCheck: true,
})

const apiModel: ApiModel = new ApiModel()
Expand Down Expand Up @@ -208,3 +208,5 @@ dev
process.exitCode = 1
}
})

export { dev }
Loading

0 comments on commit 9c73d98

Please sign in to comment.