import "@johnlindquist/kit";
const Resolver = {
requiredParams: {
"youtube.com": ["v"],
"facebook.com": ["v"],
},
getURL(input: string) {
let processed = input;
if (!input.match(/^https?:\/\//)) {
processed = `https://${processed}`;
}
return new URL(processed);
},
sanitizeUrl(url: URL) {
function getBaseDomain(hostname: string) {
const [tld, base] = hostname.split(".").reverse();
return `${base}.${tld}`;
}
const searchParams = new URLSearchParams(url.searchParams);
searchParams.forEach((_value, key) => {
const baseDomain = getBaseDomain(url.hostname);
const skip = this.requiredParams[baseDomain];
if (skip?.includes(key)) {
return;
}
url.searchParams.delete(key);
});
return url.href;
},
async fetchHead(input: string) {
let url: URL;
try {
url = this.getURL(input);
} catch (error) {
return { resolvedUrl: undefined, error: "Invaid or unreachable URL" };
}
const options = { method: "HEAD", credentials: "omit" } as const;
try {
const response = await fetch(url, options);
const responseUrl = new URL(response.url);
const sanitizedUrl = this.sanitizeUrl(responseUrl);
return { resolvedUrl: sanitizedUrl, error: undefined };
} catch (error) {
return { resolvedUrl: undefined, error: this.getErrorMessage(error) };
}
},
getErrorMessage(error: unknown) {
return error instanceof Error
? error.message
: "Something unexpected happened.";
},
async resolve(url: string) {
return this.fetchHead(url);
},
};
const url = await arg("Enter a shortened URL");
const response = await Resolver.resolve(url);
const { resolvedUrl, error } = response;
const result = error ?? resolvedUrl ?? "(Something went wrong)";
const shouldCopy = !!resolvedUrl;
if (shouldCopy) {
await copy(result);
}
await div(
md(`# ๐ฌ Result${shouldCopy ? " (automatically copied to clipboard)" : ""}
\`\`\`
${result}
\`\`\`
`)
);