support url base

This commit is contained in:
velzie 2024-09-01 13:26:24 -04:00
parent a1ce4e33b3
commit 7a9c990b01
No known key found for this signature in database
GPG key ID: 048413F95F0DDE1F
32 changed files with 213 additions and 158 deletions

View file

@ -1,5 +1,10 @@
import { rewriteJs } from "./js";
export type URLMeta = {
origin: URL;
base: URL;
};
function tryCanParseURL(url: string, origin?: string | URL): URL | null {
try {
return new URL(url, origin);
@ -9,36 +14,34 @@ function tryCanParseURL(url: string, origin?: string | URL): URL | null {
}
// something is broken with this but i didn't debug it
export function encodeUrl(url: string | URL, origin?: URL) {
export function encodeUrl(url: string | URL, meta: URLMeta) {
if (url instanceof URL) {
url = url.href;
}
if (!origin) {
if (location.pathname.startsWith(self.$scramjet.config.prefix + "worker")) {
origin = new URL(new URL(location.href).searchParams.get("origin"));
} else
origin = new URL(
self.$scramjet.codec.decode(
location.href.slice(
(location.origin + self.$scramjet.config.prefix).length
)
)
);
}
// is this the correct behavior?
if (!url) url = origin.href;
// if (!origin) {
// if (location.pathname.startsWith(self.$scramjet.config.prefix + "worker")) {
// origin = new URL(new URL(location.href).searchParams.get("origin"));
// } else
// origin = new URL(
// self.$scramjet.codec.decode(
// location.href.slice(
// (location.origin + self.$scramjet.config.prefix).length
// )
// )
// );
// }
if (url.startsWith("javascript:")) {
return "javascript:" + rewriteJs(url.slice("javascript:".length), origin);
return "javascript:" + rewriteJs(url.slice("javascript:".length), meta);
} else if (/^(#|mailto|about|data|blob)/.test(url)) {
// TODO this regex is jank but i'm not fixing it
return url;
} else if (tryCanParseURL(url, origin)) {
} else {
return (
location.origin +
self.$scramjet.config.prefix +
self.$scramjet.codec.encode(new URL(url, origin).href)
self.$scramjet.codec.encode(new URL(url, meta.base).href)
);
}
}