Created
February 4, 2022 13:55
-
-
Save ball6847/94b7d102308f6376686605c6e3756ab5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env -S deno run --unstable --allow-read --allow-write --allow-run --allow-net | |
import { ensureDirSync } from "https://deno.land/[email protected]/fs/mod.ts"; | |
import { join } from "https://deno.land/[email protected]/path/mod.ts"; | |
import pLimit from "https://cdn.skypack.dev/[email protected]"; | |
function readJson(file: string) { | |
const jsonString = Deno.readTextFileSync(file); | |
const json = JSON.parse(jsonString); | |
return json; | |
} | |
function denoCache(file: string) { | |
return Deno.run({ cmd: [Deno.execPath(), "cache", file] }).status(); | |
} | |
async function hasDefaultExport(url: string) { | |
const code = `import __default from "${url}";`; | |
const p = Deno.run({ | |
cmd: [Deno.execPath(), "eval", code], | |
stdout: "piped", | |
stderr: "piped", | |
}); | |
await p.status(); | |
const stderr = new TextDecoder().decode(await p.stderrOutput()); | |
return stderr.indexOf("does not provide an export named 'default'") === -1; | |
} | |
// start actual code | |
const limit = pLimit(4); | |
const __dirname = new URL(".", import.meta.url).pathname; | |
const dirname = "deno_modules"; | |
const target = join(__dirname, dirname); | |
const extension = ".ts"; | |
const importMap = await readJson("./import_map.json"); | |
// create all files and update cache | |
// TODO: handle remove, and compare hash before updating | |
const entries = Object.entries(importMap.imports).map(([key, value]) => | |
limit(async () => { | |
const name = `${key}${extension}`; | |
const filepath = join(target, name); | |
console.log(`processing ${filepath}`); | |
ensureDirSync(target); | |
const withDefault = await hasDefaultExport(value as string); | |
const source = !withDefault | |
? `export * from "${value}"; | |
` | |
: `export * from "${value}"; | |
import ${key} from "${value}"; | |
export default ${key}; | |
`; | |
Deno.writeTextFileSync(filepath, source); | |
await denoCache(filepath); | |
}) | |
); | |
await Promise.all(entries); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment