Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: graceful error handling of invalid svgs #195

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 27 additions & 21 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ export default defineNuxtModule<ModuleOptions>({
...(isBundling
? []
: [
`import { createRequire } from 'module'`,
`const require = createRequire(import.meta.url)`,
`import { createRequire } from 'module'`,
`const require = createRequire(import.meta.url)`,
]
),
`export const collections = {`,
Expand Down Expand Up @@ -202,27 +202,33 @@ async function resolveCollection(nuxt: Nuxt, collection: string | IconifyJSON |
const files = (await fg('*.svg', { cwd: dir, onlyFiles: true }))
.sort()

const json: IconifyJSON = {
...collection,
icons: Object.fromEntries(await Promise.all(files.map(async (file) => {
const name = basename(file, '.svg')
let svg = await fs.readFile(join(dir, file), 'utf-8')
const cleanupIdx = svg.indexOf('<svg')
if (cleanupIdx > 0)
svg = svg.slice(cleanupIdx)
const data = convertParsedSVG(parseSVGContent(svg)!)!
if (data.top === 0)
delete data.top
if (data.left === 0)
delete data.left
return [name, data]
}))),
}
const parsedIcons = await Promise.all(files.map(async (file) => {
const name = basename(file, '.svg')
let svg = await fs.readFile(join(dir, file), 'utf-8')
const cleanupIdx = svg.indexOf('<svg')
if (cleanupIdx > 0)
svg = svg.slice(cleanupIdx)
const data = convertParsedSVG(parseSVGContent(svg)!)
if (!data) {
logger.error(`Nuxt Icon could not parse the SVG content for icon \`${name}\``)
return [name, {}]
}
if (data.top === 0)
delete data.top
if (data.left === 0)
delete data.left
return [name, data]
}))

const successfulIcons = parsedIcons.filter(([_, data]) => Object.keys(data).length > 0)
// @ts-expect-error remove extra properties
delete json.dir
delete collection.dir

logger.success(`Nuxt Icon loaded local collection \`${json.prefix}\` with ${files.length} icons`)
return json
logger.success(`Nuxt Icon loaded local collection \`${collection.prefix}\` with ${successfulIcons.length} icons`)
return {
...collection,
icons: Object.fromEntries(successfulIcons),
}
}
return collection
}