cdn-resolve
Version:
Resolves import paths to their CDN equivalents
42 lines (38 loc) • 1.07 kB
JavaScript
;
// src/parse.ts
function parsePackage(pkg) {
const matched = /^(@(?<scope>[^/]+)\/(?<name>[^@/]+))(?:@(?<version>[^/]+))?(?<path>\/.*)?$/.exec(
pkg
) || /^(?<name>[^@/]+)(?:@(?<version>[^/]+))?(?<path>\/.*)?$/.exec(pkg);
if (!matched || !matched.groups?.name) {
throw new Error(`Invalid package name: ${pkg}`);
}
const version = matched.groups?.version || "latest";
const path = matched.groups?.path;
const scope = matched.groups?.scope;
const name = scope ? `@${scope}/${matched.groups.name}` : matched.groups.name;
return {
name,
version,
path,
scope,
full: `${name}@${version}${path || ""}`
};
}
// src/unpkg.ts
function buildUnpkgUrl(module, options) {
try {
const pkg = parsePackage(module);
const url = new URL(pkg.full, "https://unpkg.com/");
if (options?.meta) {
url.searchParams.set("meta", "true");
}
if (options?.module) {
url.searchParams.set("module", "true");
}
return url;
} catch {
return void 0;
}
}
exports.buildUnpkgUrl = buildUnpkgUrl;