Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Commit

Permalink
chore: render code frames for errors (wip) (#178)
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel authored Aug 27, 2024
1 parent 2512b07 commit c106e09
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 25 deletions.
3 changes: 3 additions & 0 deletions packages/openapi-parser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,13 @@
},
"devDependencies": {
"@apidevtools/swagger-parser": "^10.1.0",
"@babel/code-frame": "^7.24.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"glob": "^11.0.0",
"@types/node": "^20.14.0",
"json-to-ast": "^2.1.0",
"just-diff": "^6.0.2",
"rollup": "^4.19.2",
"rollup-plugin-output-size": "^1.4.1",
Expand Down
67 changes: 67 additions & 0 deletions packages/openapi-parser/tests/code-frame.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { codeFrameColumns } from '@babel/code-frame'
import { describe, it } from 'vitest'

import { toJson } from '../src'

// const JsonAsty = require('json-asty')
const parse = require('json-to-ast')

const example = {
openapi: '3.1.0',
info: {
title: 'Hello World',
version: '1.0.0',
},
paths: {},
}

describe('code-frame', () => {
it('load object', async () => {
const pointer = '#/info/title'
const json = toJson(example)

// Generate AST from JSON string
const ast = parse(json, {
// with location information
loc: true,
})

// Get node from AST
const segments = pointer.substring(1).split('/').slice(1)
const node = segments.reduce((acc, key) => {
if (acc?.type === 'Object') {
return acc.children.find(
(child) => child.type === 'Property' && child.key.value === key,
)
}

if (acc?.value?.type === 'Object') {
return acc.value.children.find(
(child) => child.type === 'Property' && child.key.value === key,
)
}
}, ast)

const location = {
start: { line: node.loc.start.line, column: node.loc.start.column },
end: { line: node.loc.end.line, column: node.loc.end.column },
}

console.log()
console.log('JSON')
console.log()
console.log(json)

console.log()

console.log('ERROR')
const result = codeFrameColumns(json, location, {
highlightCode: true,
message:
'This is the location of the key "title" in the OpenAPI document.',
})
console.log()

console.log(result)
})
})
67 changes: 42 additions & 25 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c106e09

Please sign in to comment.