Skip to content
This repository has been archived by the owner on Sep 14, 2023. It is now read-only.

Commit

Permalink
chore: semicolon purge (#393)
Browse files Browse the repository at this point in the history
  • Loading branch information
tjjfvi authored Nov 12, 2022
1 parent da95af1 commit 1909919
Show file tree
Hide file tree
Showing 146 changed files with 2,739 additions and 2,736 deletions.
8 changes: 4 additions & 4 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ deno run -A -r https://deno.land/x/capi/codegen.ts \
Make use of those bindings.

```ts
import * as C from "capi";
import { system } from "./polkadot/frame.ts";
import * as C from "capi"
import { system } from "./polkadot/frame.ts"

// bind to the last inserted key
const key = system.account.keys.first;
const key = system.account.keys.first

// bind to the corresponding value
const value = C.run(system.account.get(key));
const value = C.run(system.account.get(key))
```

## The Thesis
Expand Down
16 changes: 8 additions & 8 deletions _tasks/build_wasm.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import * as path from "../deps/std/path.ts";
import * as hex from "../util/hex.ts";
import * as path from "../deps/std/path.ts"
import * as hex from "../util/hex.ts"

const wasmPaths = [
"hashers/xxhash",
"hashers/blake2b",
];
]

await Promise.all(wasmPaths.map(build));
await Promise.all(wasmPaths.map(build))

async function build(wasmPath: string) {
const process = Deno.run({
cmd: ["wat2wasm", wasmPath + ".wat", "--output=-"],
stdout: "piped",
stderr: "inherit",
stdin: "null",
});
})

if (!(await process.status()).success) {
throw new Error(wasmPath + ".wat build failed");
throw new Error(wasmPath + ".wat build failed")
}

const wasm = await process.output();
const wasm = await process.output()

await Deno.writeTextFile(
wasmPath + ".wasm.ts",
Expand All @@ -31,5 +31,5 @@ import { Hex, hex } from "${path.relative(path.dirname(wasmPath), "util/mod.ts")
export default hex.decode(\n"${hex.encode(wasm).replace(/.{0,64}|$/g, "\\\n$&")}" as Hex,\n);
`.trimStart(),
);
)
}
12 changes: 6 additions & 6 deletions _tasks/dnt.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { build } from "https://deno.land/x/[email protected]/mod.ts";
import * as fs from "../deps/std/fs.ts";
import * as path from "../deps/std/path.ts";
import { build } from "https://deno.land/x/[email protected]/mod.ts"
import * as fs from "../deps/std/fs.ts"
import * as path from "../deps/std/path.ts"

const outDir = path.join("target", "npm");
const outDir = path.join("target", "npm")

await fs.emptyDir(outDir);
await fs.emptyDir(outDir)

await Promise.all([
build({
Expand Down Expand Up @@ -49,4 +49,4 @@ await Promise.all([
}),
fs.copy("LICENSE", path.join(outDir, "LICENSE")),
fs.copy("Readme.md", path.join(outDir, "Readme.md")),
]);
])
34 changes: 17 additions & 17 deletions _tasks/download_frame_metadata.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import * as fs from "../deps/std/fs.ts";
import * as path from "../deps/std/path.ts";
import * as Z from "../deps/zones.ts";
import * as C from "../mod.ts";
import * as U from "../util/mod.ts";
import * as fs from "../deps/std/fs.ts"
import * as path from "../deps/std/path.ts"
import * as Z from "../deps/zones.ts"
import * as C from "../mod.ts"
import * as U from "../util/mod.ts"

const outDir = path.join(Deno.cwd(), "frame_metadata", "_downloaded");
await fs.emptyDir(outDir);
U.throwIfError(await Z.ls(...Object.entries(C.knownClients).map(download)).run());
const outDir = path.join(Deno.cwd(), "frame_metadata", "_downloaded")
await fs.emptyDir(outDir)
U.throwIfError(await Z.ls(...Object.entries(C.knownClients).map(download)).run())

function download<Name extends Z.$<string>, Client extends Z.$<C.rpc.Client>>(
entry: [name: Name, client: Client],
) {
return Z.ls(...entry).next(async ([name, client]) => {
try {
const metadataHex = U.throwIfError(await C.state.getMetadata(client)().run());
const outPath = path.join(outDir, `${name}.scale`);
console.log(`Downloading ${name} metadata to "${outPath}".`);
await Deno.writeTextFile(outPath, metadataHex);
return;
const metadataHex = U.throwIfError(await C.state.getMetadata(client)().run())
const outPath = path.join(outDir, `${name}.scale`)
console.log(`Downloading ${name} metadata to "${outPath}".`)
await Deno.writeTextFile(outPath, metadataHex)
return
} catch (cause) {
return new MetadataDownloadError(name, { cause });
return new MetadataDownloadError(name, { cause })
}
});
})
}

class MetadataDownloadError extends Error {
override readonly name = "MetadataDownloadError";
override readonly name = "MetadataDownloadError"

constructor(readonly chainName: string, options: ErrorOptions) {
super(undefined, options);
super(undefined, options)
}
}
148 changes: 74 additions & 74 deletions _tasks/run_browser.ts
Original file line number Diff line number Diff line change
@@ -1,151 +1,151 @@
import { contentType } from "https://deno.land/x/[email protected]/mod.ts";
import { Application, send } from "https://deno.land/x/[email protected]/mod.ts";
import { babel, babelPresetTypeScript } from "https://escad.dev/deps/babel.ts";
import * as path from "../deps/std/path.ts";
import { contentType } from "https://deno.land/x/[email protected]/mod.ts"
import { Application, send } from "https://deno.land/x/[email protected]/mod.ts"
import { babel, babelPresetTypeScript } from "https://escad.dev/deps/babel.ts"
import * as path from "../deps/std/path.ts"

const dirname = path.dirname(path.fromFileUrl(import.meta.url));
const dirname = path.dirname(path.fromFileUrl(import.meta.url))

const port = +(Deno.env.get("PORT") ?? "8080");
const port = +(Deno.env.get("PORT") ?? "8080")

const transpiledDir = path.join(dirname, "../target/transpiled");
const transpiledDir = path.join(dirname, "../target/transpiled")

const getTranspiledLocation = (url: string) => path.join(transpiledDir, getTranspiledPath(url));
const getTranspiledLocation = (url: string) => path.join(transpiledDir, getTranspiledPath(url))
const getTranspiledPath = (url: string) => {
return `/${url}`;
};
return `/${url}`
}
const transpiler = createTranspiler({
cache: {
has: async (url) => {
if (url.startsWith("file://")) return false;
if (url.startsWith("file://")) return false
try {
await Deno.lstat(getTranspiledLocation(url));
return true;
await Deno.lstat(getTranspiledLocation(url))
return true
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return false;
return false
} else {
throw e;
throw e
}
}
},
set: async (url, result) => {
const loc = getTranspiledLocation(url);
await Deno.mkdir(path.dirname(loc), { recursive: true });
await Deno.writeTextFile(loc, result);
const loc = getTranspiledLocation(url)
await Deno.mkdir(path.dirname(loc), { recursive: true })
await Deno.writeTextFile(loc, result)
},
},
transformUrl: getTranspiledPath,
});
})

const rootFile = new URL(Deno.args[0]!, path.toFileUrl(Deno.cwd() + "/")).toString();
const rootFile = new URL(Deno.args[0]!, path.toFileUrl(Deno.cwd() + "/")).toString()

const app = new Application();
const app = new Application()

app.use(async (ctx) => {
let path = ctx.request.url.pathname;
let path = ctx.request.url.pathname
if (ctx.request.url.pathname === "/") {
transpiler.memo.clear();
await transpiler.transpile(rootFile);
path = "/index.html";
transpiler.memo.clear()
await transpiler.transpile(rootFile)
path = "/index.html"
}
await send(ctx, path, {
root: transpiledDir,
contentTypes: new Proxy({}, {
get: (_target, key) => {
return contentType(key as string) ?? contentType(".js");
return contentType(key as string) ?? contentType(".js")
},
}),
});
});
})
})

const rootFilePath = getTranspiledPath(transformUrl(rootFile));
const rootFilePath = getTranspiledPath(transformUrl(rootFile))
await Deno.writeTextFile(
path.join(transpiledDir, "index.html"),
`
<script>Deno = { _browserShim: true, args: [], build: { arch: "x86_64" }, errors: { PermissionDenied: Error } }</script>
<script type="module" src="${rootFilePath}"></script>
`.trim(),
);
)

console.log(`http://localhost:${port}/`);
console.log(`http://localhost:${port}/`)

await app.listen({ port });
await app.listen({ port })

function transformUrl(url: string) {
return url
.replace(/[?#]/g, "_")
.replace(/\.\./g, "__")
.replace(/\.ts$|(?<!\.[^\W\d]+)$/, ".js");
.replace(/\.ts$|(?<!\.[^\W\d]+)$/, ".js")
}

interface TranspilerHost {
cache: {
has: (url: string) => Promise<boolean>;
set: (url: string, result: string) => Promise<void>;
};
transformUrl: (url: string) => string;
has: (url: string) => Promise<boolean>
set: (url: string, result: string) => Promise<void>
}
transformUrl: (url: string) => string
}

interface Transpiler extends TranspilerHost {
memo: Map<string, Promise<unknown>>;
transpile: (url: string, force?: boolean) => Promise<unknown>;
transpileAll: (urls: string[], force?: boolean) => Promise<unknown>;
memo: Map<string, Promise<unknown>>
transpile: (url: string, force?: boolean) => Promise<unknown>
transpileAll: (urls: string[], force?: boolean) => Promise<unknown>
}

function createTranspiler(ctx: TranspilerHost): Transpiler {
const memo = new Map<string, Promise<readonly string[]>>();
const memo = new Map<string, Promise<readonly string[]>>()

return { ...ctx, memo, transpile, transpileAll };
return { ...ctx, memo, transpile, transpileAll }

function transpile(url: string, force = false) {
return transpileAll([url], force);
return transpileAll([url], force)
}

async function transpileAll(urls: string[], force = false) {
const done = new Set(urls);
const waiting = urls.map((url) => _transpile(url, force));
const done = new Set(urls)
const waiting = urls.map((url) => _transpile(url, force))
while (waiting.length) {
for (const dep of await waiting.pop()!) {
if (done.has(dep)) continue;
done.add(dep);
waiting.push(_transpile(dep));
if (done.has(dep)) continue
done.add(dep)
waiting.push(_transpile(dep))
}
}
}

function _transpile(url: string, force = false) {
if (!force) {
const running = memo.get(url);
const running = memo.get(url)
if (running) {
return running;
return running
}
}
console.log("transpiling", url);
console.log("transpiling", url)
const prom = (async () => {
if (!force && await ctx.cache.has(url)) {
return [];
return []
}
const [result, deps] = await __transpile(url);
deps.map((x) => transpile(x));
await ctx.cache.set(transformUrl(url), result);
return deps;
})();
memo.set(url, prom);
return prom;
const [result, deps] = await __transpile(url)
deps.map((x) => transpile(x))
await ctx.cache.set(transformUrl(url), result)
return deps
})()
memo.set(url, prom)
return prom
}

async function fetchFile(url: string) {
const response = await fetch(url);
const response = await fetch(url)
if (!response.ok) {
throw Object.assign(new Error(`Error fetching ${url} for transpilation`), { response });
throw Object.assign(new Error(`Error fetching ${url} for transpilation`), { response })
}
const content = await response.text();
return content;
const content = await response.text()
return content
}

async function __transpile(url: string) {
const content = await fetchFile(url);
const deps: string[] = [];
const content = await fetchFile(url)
const deps: string[] = []
const result = await babel.transformAsync(content, {
filename: url,
presets: [
Expand All @@ -166,21 +166,21 @@ function createTranspiler(ctx: TranspilerHost): Transpiler {
path.parent.type,
)
) {
return;
return
}
const str = path.node.value;
const resolved = (new URL(str, url)).toString();
deps.push(resolved);
const str = path.node.value
const resolved = (new URL(str, url)).toString()
deps.push(resolved)
path.replaceWith(babel.types.stringLiteral(
ctx.transformUrl(transformUrl(resolved)),
));
path.skip();
))
path.skip()
},
},
},
],
});
if (result?.code == null) throw new Error("Babel returned null");
return [result.code, deps] as const;
})
if (result?.code == null) throw new Error("Babel returned null")
return [result.code, deps] as const
}
}
Loading

0 comments on commit 1909919

Please sign in to comment.