2021-10-20 09:47:18 +00:00
|
|
|
import { promises as fsp, existsSync } from 'fs'
|
2022-01-18 16:43:41 +00:00
|
|
|
import { parse as parsePath } from 'pathe'
|
2021-10-20 09:47:18 +00:00
|
|
|
import { findExports } from 'mlly'
|
|
|
|
import { camelCase } from 'scule'
|
2022-01-18 16:43:41 +00:00
|
|
|
import { resolveFiles } from '@nuxt/kit'
|
2022-03-11 08:09:11 +00:00
|
|
|
import { Unimport } from 'unimport'
|
2021-10-20 09:47:18 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
export async function scanForComposables (dir: string | string[], ctx: Unimport) {
|
2022-03-07 10:39:54 +00:00
|
|
|
const performScan = async (entry: string) => {
|
|
|
|
const files = await resolveFiles(entry, [
|
|
|
|
'*.{ts,js,mjs,cjs,mts,cts}',
|
|
|
|
'*/index.{ts,js,mjs,cjs,mts,cts}'
|
|
|
|
])
|
2021-10-20 09:47:18 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
await ctx.modifyDynamicImports(async (dynamicImports) => {
|
|
|
|
await Promise.all(
|
|
|
|
files.map(async (path) => {
|
|
|
|
// Remove original entries from the same import (for build watcher)
|
|
|
|
filterInPlace(dynamicImports, i => i.from !== path)
|
2021-10-20 09:47:18 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
const code = await fsp.readFile(path, 'utf-8')
|
|
|
|
const exports = findExports(code)
|
|
|
|
const defaultExport = exports.find(i => i.type === 'default')
|
2021-10-20 09:47:18 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
if (defaultExport) {
|
|
|
|
let name = parsePath(path).name
|
|
|
|
if (name === 'index') {
|
|
|
|
name = parsePath(path.split('/').slice(0, -1).join('/')).name
|
|
|
|
}
|
|
|
|
dynamicImports.push({ name: 'default', as: camelCase(name), from: path })
|
2022-03-07 10:39:54 +00:00
|
|
|
}
|
2022-03-11 08:09:11 +00:00
|
|
|
for (const exp of exports) {
|
|
|
|
if (exp.type === 'named') {
|
|
|
|
for (const name of exp.names) {
|
|
|
|
dynamicImports.push({ name, as: name, from: path })
|
|
|
|
}
|
|
|
|
} else if (exp.type === 'declaration') {
|
|
|
|
dynamicImports.push({ name: exp.name, as: exp.name, from: path })
|
2022-03-07 10:39:54 +00:00
|
|
|
}
|
2021-10-20 09:47:18 +00:00
|
|
|
}
|
2022-03-11 08:09:11 +00:00
|
|
|
})
|
|
|
|
)
|
|
|
|
})
|
2022-03-07 10:39:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for (const entry of Array.isArray(dir) ? dir : [dir]) {
|
|
|
|
if (!existsSync(entry)) { continue }
|
|
|
|
|
|
|
|
await performScan(entry)
|
|
|
|
}
|
2021-10-20 09:47:18 +00:00
|
|
|
}
|
2022-03-11 08:09:11 +00:00
|
|
|
|
|
|
|
function filterInPlace<T> (arr: T[], predicate: (v: T) => any) {
|
|
|
|
let i = arr.length
|
|
|
|
while (i--) {
|
|
|
|
if (!predicate(arr[i])) {
|
|
|
|
arr.splice(i, 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|