Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Commit

Permalink
fix(flatten): flatten now expands nested imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Golden committed Oct 3, 2020
1 parent 2c8f2aa commit d23f598
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 18 deletions.
4 changes: 2 additions & 2 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
yarn 1.22.0
nodejs 14.3.0
nodejs 14.13.0
yarn 1.22.10
39 changes: 39 additions & 0 deletions src/flatten/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,45 @@ describe('flatten', () => {
})
})

test('grandchild config to test recursion', async () => {
const start: Ainsley = {
children: [
{
children: ['$missing-config']
},
{
variables: {
unused: {
var: 'iable'
}
}
},
'body{margin:0}'
]
}

expect(
await flatten(
start,
async (ref: string): Promise<AinsleyChild> => `/* $${ref} */`
)
).toEqual({
children: [
{
children: ['/* $missing-config */']
},
{
variables: {
unused: {
var: 'iable'
}
}
},
'body{margin:0}'
]
})
})

test('default getConfig', async () => {
expect(
await flatten({
Expand Down
42 changes: 26 additions & 16 deletions src/flatten/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,25 @@ import { Ainsley, AinsleyChild, AinsleyChildren } from '../types'
import { validate } from '../validate'
import { isObject } from '../utils'

type CfgLoc = [AinsleyChildren, number]
const findConfigs = (ainsley: Ainsley): CfgLoc[] => {
const cfgLocs: CfgLoc[] = []
if (ainsley.children) {
const children = ainsley.children
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (typeof child === 'string') {
if (child[0] === '$') {
cfgLocs.push([children, i])
}
} else if (!Array.isArray(child)) {
cfgLocs.push(...findConfigs(child))
}
}
}
return cfgLocs
}

/* config with external dependencies => flat config */
export const flatten = async (
configWithPlugins: Ainsley,
Expand All @@ -17,23 +36,14 @@ export const flatten = async (

// deep clone as we'll be mutating
const flatAinsley = copy(configWithPlugins)
const allConfigs = findConfigs(flatAinsley)

// check for configs and inject them
if (Array.isArray(flatAinsley.children)) {
await Promise.all(
flatAinsley.children.map(
async (child: AinsleyChild, i: number): Promise<AinsleyChild> => {
if (typeof child === 'string') {
if (child.startsWith('$')) {
const flatConfig = await getFlatConfig(child.slice(1), getConfig)
;(flatAinsley.children as AinsleyChildren)[i] = flatConfig
}
}
return child
}
)
)
}
await Promise.all(
allConfigs.map(async ([children, index]) => {
const child = children[index] as string
children[index] = await getFlatConfig(child.slice(1), getConfig)
})
)

return flatAinsley
}
Expand Down

0 comments on commit d23f598

Please sign in to comment.