Last active
May 20, 2023 09:38
-
-
Save mizchi/4876fa2d7d784a412e4250900fd6a0b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Env {} | |
// very easy pattren only for this case | |
const path$join = (...paths: string[]) => { | |
return paths | |
.map(x => x.replace(/^\.\//, '')) | |
.join("/").replace(/\/+/g, "/"); | |
} | |
const path$dirname = (path: string) => { | |
const parts = path.split("/"); | |
parts.pop(); | |
return parts.join("/"); | |
} | |
const importTargetExpr = /(import|export)(?:[\s.*]([\w*{}\n\r\t, ]+)[\s*]from)?[\s*](?:["'](?<target>.*?[\w]+)["'])?/g; | |
function extractImportTargets(source: string): string[] { | |
const matches = [...source.matchAll(importTargetExpr)]; | |
return matches.map((m) => m.groups?.target).filter((t) => t) as string[]; | |
} | |
// // script body -> preload link header | |
function getPreloadLinkHeaderFromScript(code: string, fromUrl: URL) { | |
// parsed | |
const parsedTargets = extractImportTargets(code); | |
const fromDir = path$dirname(fromUrl.pathname); | |
const fullpaths = parsedTargets.map((link) => path$join(fromDir, link!)); | |
const preloadLinkHeader = fullpaths.map((link) => { | |
return `<${link}>; rel=preload; as=script; crossorigin`; | |
}).join(", "); | |
return preloadLinkHeader || ""; | |
} | |
const indexhtml = ` | |
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Preload< itle> | |
</head> | |
<body> | |
<h1>Preload</h1> | |
<script type="module" src="http://127.0.0.1:8787/assets/main.js" crossorigin="anonymous"></script> | |
</body> | |
<html> | |
`; | |
const assetsMap = { | |
"/assets/main.js": `import { sub } from "./sub.js"; console.log("main", sub);`, | |
"/assets/sub.js": `import { nest } from "./nest/nest.js"; export const sub = nest + "sub";`, | |
"/assets/nest/nest.js": `export const nest = "nest";`, | |
} | |
export default { | |
async fetch( | |
request: Request, | |
env: Env, | |
ctx: ExecutionContext | |
): Promise<Response> { | |
const parsed = new URL(request.url); | |
if (parsed.pathname.endsWith(".js")) { | |
const asset = (assetsMap as any)[parsed.pathname]; | |
await new Promise((resolve) => setTimeout(resolve, 500)); | |
return new Response(asset, { | |
headers: { | |
"content-type": "application/javascript", | |
"Access-Control-Allow-Origin": "*", | |
"Link": getPreloadLinkHeaderFromScript(asset, parsed), | |
} | |
}); | |
} else { | |
console.log("Not handle", parsed.pathname); | |
} | |
return new Response(indexhtml, { | |
headers: { | |
"content-type": "text/html", | |
} | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment