Skip to content

Commit

Permalink
feat(utils): add resolve utilities to handle cross esm/cjs dynamic im…
Browse files Browse the repository at this point in the history
…ports.

Signed-off-by: Braden Mars <bradenmars@bradenmars.me>
  • Loading branch information
BradenM committed Feb 13, 2023
1 parent 72c90e2 commit 79e1606
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"consola": "^2.15.3",
"fs-extra": "^11.1.0",
"got": "^12.5.3",
"jiti": "^1.17.0",
"list-github-dir-content": "^3.0.0"
}
}
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './get-temp-dir'
export * from './create-file-checksum'
export * from './download-git-dir'
export * from './resolve'
37 changes: 37 additions & 0 deletions packages/utils/src/resolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import process from 'node:process'
import jiti from 'jiti'
import consola from 'consola'

const createJiti = (rootDir: string = process.cwd()) =>
jiti(rootDir, {interopDefault: true, esmResolve: true})

export const requireFrom = <T>(id: string, rootDir?: string) =>
createJiti(rootDir)(id) as T
export const resolveFrom = (id: string, rootDir?: string) =>
createJiti(rootDir).resolve(id)

const tryCatchModule = <T extends (...args: any[]) => any>(
func: T,
fallback: T extends (...args: infer ArgT) => ReturnType<T>
? (...args: ArgT) => ReturnType<T>
: never,
): (<RT>(...args: Parameters<T>) => RT) => {
return (...args: Parameters<T>) => {
try {
return func(...args) as ReturnType<T>
} catch (error: unknown) {
if (
'code' in (error as {code: string}) &&
(error as {code: string}).code !== 'MODULE_NOT_FOUND'
) {
consola.error(`Failed to import:`, args, error)
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return fallback(...args)
}
}
}

export const maybeRequireFrom = tryCatchModule(requireFrom, () => ({}))
export const maybeResolveFrom = tryCatchModule(resolveFrom, (id: string) => id)
11 changes: 6 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 79e1606

Please sign in to comment.