Skip to content

Commit

Permalink
Add support for Browser SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
surma committed Apr 2, 2021
1 parent d932dec commit 3ff3072
Show file tree
Hide file tree
Showing 6 changed files with 14,013 additions and 28 deletions.
96 changes: 96 additions & 0 deletions examples/browser-sdk/index.html
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AssemblyScript SDK Example</title>
</head>
<body>
<script src="/dist/as-bind.iife.js"></script>
<script src="./require.js"></script>
<script>
const SOURCE_CODE = `
export function test(): string {
return "ohai";
}`;

// A symbol allows us to store something as a global without risking
// name clashes or pollution.
const asbindTransform = Symbol();

// Shimming the require() call to *synchronously*
// return our transform module that we expect to be on a global.
// Any calls unrelated to the transform
// are implicitly passed through to RequireJS.
self.require = new Proxy(self.require, {
apply(target, thisArg, [path, ...args]) {
if (path !== "/dist/transform.js") {
return target.call(target, path, ...args);
}
return self[asbindTransform];
},
get(target, propName) {
if (propName !== "resolve") {
return target[propName];
}
return (path, ...args) => {
return path;
};
}
});

require(["/node_modules/assemblyscript/dist/sdk.js"], ({
asc,
assemblyscript
}) => {
// Register the `assemblyscript` property as a module of its own
// as is expected by most transform modules.
define("assemblyscript", assemblyscript);
// Load our ASBind transform...
require(["/dist/transform.amd.js"], transform => {
// ... and put it on a global
self[asbindTransform] = transform;
asc.ready.then(() => {
const stdout = asc.createMemoryStream();
const stderr = asc.createMemoryStream();
asc.main(
// prettier-ignore
[
"module.ts",
"-O3",
"--exportRuntime",
"--runtime", "stub",
"--binaryFile", "module.wasm",
"--transform", "/dist/transform.js",
],
{
stdout,
stderr,
readFile(name, baseDir) {
return name === "module.ts" ? SOURCE_CODE : null;
},
async writeFile(name, data, baseDir) {
if (name.endsWith(".wasm")) {
const instance = await AsBindIIFE.instantiate(data);
console.log("Output:", instance.exports.test());
}
},
listFiles(dirname, baseDir) {
return [];
}
},
err => {
console.log(`>>> STDOUT >>>\n${stdout.toString()}`);
console.log(`>>> STDERR >>>\n${stderr.toString()}`);
if (err) {
console.log(">>> THROWN >>>");
console.log(err);
}
}
);
});
});
});
</script>
<p>See the browser console!</p>
</body>
</html>

0 comments on commit 3ff3072

Please sign in to comment.