Skip to content
This repository was archived by the owner on Jan 24, 2025. It is now read-only.

Commit 9c564d0

Browse files
committed
feat(docz-utils): add exports parser to add to Playground scope
#1247
1 parent 99ebf82 commit 9c564d0

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

core/docz-utils/src/exports.ts

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import * as parser from '@babel/parser'
2+
import traverse from '@babel/traverse'
3+
import get from 'lodash/get'
4+
5+
const fromDeclarations = (declarations: any = []) =>
6+
Array.isArray(declarations) && declarations.length > 0
7+
? declarations.map(declaration => get(declaration, 'id.name'))
8+
: []
9+
10+
const traverseOnExports = (fn: (path: any) => any[]) => (node: any) => {
11+
try {
12+
const ast = parser.parse(node.value, {
13+
sourceType: 'module',
14+
})
15+
let populated: any[] = []
16+
traverse(ast, {
17+
enter(path: any): void {
18+
if (path.isExportDeclaration()) {
19+
populated = populated.concat(fn(path))
20+
return
21+
}
22+
},
23+
})
24+
return populated
25+
} catch (err) {
26+
return []
27+
}
28+
}
29+
30+
export const getExportsVariables = traverseOnExports(path => {
31+
const type = get(path, 'node.declaration.type')
32+
switch (type) {
33+
case 'VariableDeclaration':
34+
return fromDeclarations(get(path, 'node.declaration.declarations', []))
35+
case 'FunctionDeclaration':
36+
const declaration = get(path, 'node.declaration', false)
37+
return fromDeclarations(declaration ? [declaration] : [])
38+
case 'Identifier':
39+
return get(path, 'node.declaration.name')
40+
default:
41+
console.error(`Unexpected export type ${type} in docz-utils/exports`)
42+
}
43+
})

core/docz-utils/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export * from './ast'
22
export * from './fs'
33
export * from './imports'
4+
export * from './exports'
45
export * from './jsx'
56
export * from './mdast'
67
export { format } from './format'

0 commit comments

Comments
 (0)