Skip to content

Commit

Permalink
Created a QuickStart example/test, to ensure README QuickStart is wor…
Browse files Browse the repository at this point in the history
…king (#83)

* Updated the README and added tests for the quickstart code

* Added quickstart example tests
  • Loading branch information
torch2424 committed May 28, 2021
1 parent 5f277be commit 69b2d02
Show file tree
Hide file tree
Showing 10 changed files with 286 additions and 4 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ For **browser** JavaScript. We can do the following:

```javascript
// If you are using a Javascript bundler, use the ESM bundle with import syntax
import { AsBind } from "as-bind";
import * as AsBind from "as-bind";

// If you are not using a bundler add a <script> tag to your HTML
// Where the `src` points to the iife bundle (as-bind.iife.js), for example: https://unpkg.com/as-bind
Expand All @@ -93,10 +93,14 @@ const asyncTask = async () => {
asyncTask();
```

For **Node** JavaScript, we would use the CommonJS bundle by do the following:
For **Node** JavaScript, we would use the CommonJS bundle by doing the following:

```javascript
const { AsBind } = require("as-bind");
// We need to import the direct as-bind.cjs.js for Node applications.
// This is because the default "main" key in the `package.json`,
// is the as-bind transform script
const AsBind = require("as-bind/dist/as-bind.cjs.js");

const fs = require("fs");

const wasm = fs.readFileSync("./path-to-my-wasm.wasm");
Expand Down
85 changes: 85 additions & 0 deletions examples/quickstart/browser-puppeteer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Use pupeteer to run in the browser
const puppeteer = require("puppeteer");

// Require rollup to compile our browser.js
const rollup = require("rollup");
const { nodeResolve } = require("@rollup/plugin-node-resolve");

// Get some native node libs, in order to host a static server
const path = require("path");
const fs = require("fs");
const http = require("http");

// Host a static server of the local directory
// https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/
http
.createServer(function(req, res) {
fs.readFile(__dirname + req.url, function(err, data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
})
.listen(8000);

(async () => {
// Create a rollup bundle and get our compiled browser.js as a string
const bundle = await rollup.rollup({
input: "./browser.js",
plugins: [nodeResolve()]
});
const { output } = await bundle.generate({
format: "iife"
});
const browserQuickstartJs = output[0].code;

// Launch the pupeteer browser and page
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("http://localhost:8000/browser.html");

// Create a promise that we will resolve or reject once we see any expected behavior
let pageResolve;
let pageReject;
const pageResultPromise = new Promise((resolve, reject) => {
pageResolve = resolve;
pageReject = reject;
});

// Listen to JS Console messages, log them, and resolve our promise on an expected message
page.on("console", message => {
console.log(
`${message
.type()
.substr(0, 3)
.toUpperCase()} ${message.text()}`
);

if (message.text() === "AsBind: Hello World!") {
pageResolve();
return;
}
});

// Listen to JS / Page errors, log them, and reject our promise
page.on("pageerror", err => {
theTempValue = err.toString();
console.log("Error: " + theTempValue);

console.log("Browser Quickstart Failed.");
pageReject();
return;
});

// Run the compiled browser.js code
await page.evaluate(browserQuickstartJs);

// Wait for the promise, and then close everything out
await pageResultPromise;
await browser.close();
process.exit();
})();
8 changes: 8 additions & 0 deletions examples/quickstart/browser.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
</head>
<body></body>
</html>
25 changes: 25 additions & 0 deletions examples/quickstart/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// If you are using a Javascript bundler, use the ESM bundle with import syntax
import * as AsBind from "as-bind";

// If you are not using a bundler add a <script> tag to your HTML
// Where the `src` points to the iife bundle (as-bind.iife.js), for example: https://unpkg.com/as-bind
// Then, INSTEAD of using the import syntax, do: `const { AsBind } = AsBindIIFE;`

const wasm = fetch("./path-to-my-wasm.wasm");

const asyncTask = async () => {
// There is a buge with WebAssembly.compileStreaming with pupeteer, so going to
// Get the Wasm Binary here and instantiate sync. This is slightly different
// from the README unfortunately
const wasmResponse = await wasm;
const wasmBuffer = await wasmResponse.arrayBuffer();

const asBindInstance = await AsBind.instantiate(wasmBuffer);

// You can now use your wasm / as-bind instance!
const response = asBindInstance.exports.myExportedFunctionThatTakesAString(
"Hello World!"
);
console.log(response); // AsBind: Hello World!
};
asyncTask();
19 changes: 19 additions & 0 deletions examples/quickstart/nodejs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// We need to import the direct as-bind.cjs.js for Node applications.
// This is because the default "main" key in the `package.json`,
// is the as-bind transform script
const AsBind = require("as-bind/dist/as-bind.cjs.js");

const fs = require("fs");

const wasm = fs.readFileSync("./path-to-my-wasm.wasm");

const asyncTask = async () => {
const asBindInstance = await AsBind.instantiate(wasm);

// You can now use your wasm / as-bind instance!
const response = asBindInstance.exports.myExportedFunctionThatTakesAString(
"Hello World!"
);
console.log(response); // AsBind: Hello World!
};
asyncTask();
119 changes: 119 additions & 0 deletions examples/quickstart/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions examples/quickstart/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "as-bind-quickstart",
"version": "0.0.1",
"description": "Project that tests the README QuickStart examples to ensure that the README works. This depends on node modules from the root package.json",
"main": "index.js",
"scripts": {
"build": "asc your-entryfile.ts --exportRuntime --transform as-bind -b path-to-my-wasm.wasm",
"test": "npm run test:node && npm run test:browser",
"test:node": "node nodejs.js",
"test:browser": "node browser-puppeteer.js"
},
"author": "Aaron Turner",
"license": "MIT",
"dependencies": {
"as-bind": "file:../.."
}
}
Binary file added examples/quickstart/path-to-my-wasm.wasm
Binary file not shown.
3 changes: 3 additions & 0 deletions examples/quickstart/your-entryfile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function myExportedFunctionThatTakesAString(value: string): string {
return "AsBind: " + value;
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
"build": "run-s lib:js:build",
"dev": "run-p lib:watch lib:test:watch",
"serve": "serve dist -p 8080",
"test": "node ./test/test-runner.js",
"test": "run-s test:lib test:quickstart",
"test:lib": "node ./test/test-runner.js",
"test:quickstart": "(cd examples/quickstart && npm install && npm run test)",
"lint": "prettier --write **/*.js **/*.ts **/*.json !build/**/* !dist/**/*",
"lint:ci": "prettier --check **/*.js **/*.ts **/*.json !build/**/* !dist/**/*",
"lib:watch": "chokidar --initial \"lib/**/*\" -c \"run-s lib:js:build:dev test\"",
Expand Down

0 comments on commit 69b2d02

Please sign in to comment.