Skip to content

Commit

Permalink
feat(twoslash): configure whether to throw, tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ap0nia committed Aug 11, 2024
1 parent 33ea3d9 commit 44069dd
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 6 additions & 4 deletions packages/twoslash/src/includes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function addIncludes(map: Map<string, string>, name: string, code: string
map.set(name, lines.join('\n'))
}

export function replaceIncludesInCode(_map: Map<string, string>, code: string) {
export function replaceIncludesInCode(_map: Map<string, string>, code: string, shouldThrow = true) {
const includes = /\/\/ @include: (.*)$/gm

// Basically run a regex over the code replacing any // @include: thing with
Expand All @@ -36,10 +36,12 @@ export function replaceIncludesInCode(_map: Map<string, string>, code: string) {

if (!replaceWith) {
const msg = `Could not find an include with the key: '${key}'.\nThere is: ${Array.from(_map.keys())}.`
throw new Error(msg)
if (shouldThrow)
throw new Error(msg)
}
else {
toReplace.push([match.index, match[0].length, replaceWith])
}

toReplace.push([match.index, match[0].length, replaceWith])
}

let newCode = code.toString()
Expand Down
18 changes: 17 additions & 1 deletion packages/twoslash/test/includes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ it('replaces the code', () => {
`)
})

it('throws an error if key not found', () => {
const map = new Map()

const sample = `// @include: main`
expect(() => replaceIncludesInCode(map, sample)).toThrow()
})

it('does not throw an error if key not found but shouldThrow is false', () => {
const map = new Map()

const sample = `// @include: main`
expect(() => replaceIncludesInCode(map, sample, false)).not.toThrow()
})

it('replaces @include directives with previously transformed code blocks', async () => {
const main = `
export const hello = { str: "world" };
Expand Down Expand Up @@ -104,5 +118,7 @@ hello.
transformers: [transformer],
})

expect(styleTag + html).toMatchFileSnapshot('./out/includes/replaced_directives.html')
expect(styleTag + html).toMatchFileSnapshot(
'./out/includes/replaced_directives.html',
)
})

0 comments on commit 44069dd

Please sign in to comment.