All files / toolbox / resolve.ts

91.67% Branches 11/12
100.00% Functions 1/1
100.00% Lines 16/16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
x1
x1
x1
 
 
 
 
 
 
 
 
 
 
x1
x21
x10
x3
x3
x10
x2
x2
x10
x10
x10
x11
x21


















I





// Imports
import { dirname, fromFileUrl, isAbsolute, join, toFileUrl } from "@std/path"
import { normalize } from "@std/path/posix/normalize"
import { cwd } from "./filesystem.ts"

/** Options for {@linkcode resolve} */
export type ResolveOptions = {
  /** Base URL (defaults to current working directory). */
  base?: string | ImportMeta
  /** Entrypoint (defaults to "mod.ts"). */
  entrypoint?: string
}

/** Resolve a module specifier in a similar way to `import.meta.resolve`. */
export function resolve(specifier: string, { base, entrypoint = "mod.ts" }: ResolveOptions = {}): string {
  if (["./", "../", "/"].some((prefix) => specifier.startsWith(prefix))) {
    if (specifier.endsWith("/")) {
      specifier += entrypoint
    }
    if (typeof base === "object") {
      base = (new URL(base.url).protocol === "file:") ? dirname(fromFileUrl(base.url)) : undefined
    }
    base ??= cwd()
    return toFileUrl(normalize(isAbsolute(specifier) ? specifier : join(base, specifier))).href
  }
  return import.meta.resolve(specifier)
}