diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml
index 3567e20c3..04a0476a4 100644
--- a/.github/workflows/documentation.yml
+++ b/.github/workflows/documentation.yml
@@ -1,6 +1,6 @@
name: Documentation
-on:
+on:
push:
branches: [master]
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 000000000..24e5b0a1a
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1 @@
+.build
diff --git a/.prettierrc b/.prettierrc
new file mode 100644
index 000000000..c7d8640bf
--- /dev/null
+++ b/.prettierrc
@@ -0,0 +1,10 @@
+{
+ "overrides": [
+ {
+ "files": ["tsconfig.json", "*.js", "*.ts"],
+ "options": {
+ "tabWidth": 4
+ }
+ }
+ ]
+}
diff --git a/Example/README.md b/Example/README.md
index c2664edb0..aa1775a54 100644
--- a/Example/README.md
+++ b/Example/README.md
@@ -1,10 +1,9 @@
# Example project of JavaScriptKit
-
## Bootstrap
```sh
$ make build
$ npm run start
-$ # Open http://localhost:8080 on your browser
+$ # Open http://localhost:8080 on your browser
```
diff --git a/Example/public/index.html b/Example/public/index.html
index f04d3f61f..b5c67fcf9 100644
--- a/Example/public/index.html
+++ b/Example/public/index.html
@@ -1,4 +1,4 @@
-
+
Getting Started
diff --git a/Example/src/index.js b/Example/src/index.js
index 61e835d5b..f26a76c64 100644
--- a/Example/src/index.js
+++ b/Example/src/index.js
@@ -2,7 +2,6 @@ import { SwiftRuntime } from "javascript-kit-swift";
import { WASI } from "@wasmer/wasi";
import { WasmFs } from "@wasmer/wasmfs";
-
const swift = new SwiftRuntime();
// Instantiate a new WASI Instance
const wasmFs = new WasmFs();
@@ -10,46 +9,46 @@ const wasmFs = new WasmFs();
// Output stdout and stderr to console
const originalWriteSync = wasmFs.fs.writeSync;
wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
- const text = new TextDecoder("utf-8").decode(buffer);
-
- // Filter out standalone "\n" added by every `print`, `console.log`
- // always adds its own "\n" on top.
- if (text !== "\n") {
- switch (fd) {
- case 1:
- console.log(text);
- break;
- case 2:
- console.error(text);
- break;
+ const text = new TextDecoder("utf-8").decode(buffer);
+
+ // Filter out standalone "\n" added by every `print`, `console.log`
+ // always adds its own "\n" on top.
+ if (text !== "\n") {
+ switch (fd) {
+ case 1:
+ console.log(text);
+ break;
+ case 2:
+ console.error(text);
+ break;
+ }
}
- }
- return originalWriteSync(fd, buffer, offset, length, position);
+ return originalWriteSync(fd, buffer, offset, length, position);
};
let wasi = new WASI({
- args: [],
- env: {},
- bindings: {
- ...WASI.defaultBindings,
- fs: wasmFs.fs
- }
+ args: [],
+ env: {},
+ bindings: {
+ ...WASI.defaultBindings,
+ fs: wasmFs.fs,
+ },
});
const startWasiTask = async () => {
- // Fetch our Wasm File
- const response = await fetch("JavaScriptKitExample.wasm");
- const responseArrayBuffer = await response.arrayBuffer();
+ // Fetch our Wasm File
+ const response = await fetch("JavaScriptKitExample.wasm");
+ const responseArrayBuffer = await response.arrayBuffer();
- // Instantiate the WebAssembly file
- const wasm_bytes = new Uint8Array(responseArrayBuffer).buffer;
- let { instance } = await WebAssembly.instantiate(wasm_bytes, {
- wasi_snapshot_preview1: wasi.wasiImport,
- javascript_kit: swift.importObjects(),
- });
+ // Instantiate the WebAssembly file
+ const wasm_bytes = new Uint8Array(responseArrayBuffer).buffer;
+ let { instance } = await WebAssembly.instantiate(wasm_bytes, {
+ wasi_snapshot_preview1: wasi.wasiImport,
+ javascript_kit: swift.importObjects(),
+ });
- swift.setInstance(instance);
- // Start the WebAssembly WASI instance!
- wasi.start(instance);
+ swift.setInstance(instance);
+ // Start the WebAssembly WASI instance!
+ wasi.start(instance);
};
startWasiTask();
diff --git a/Example/webpack.config.js b/Example/webpack.config.js
index 0d318efe5..1296c0023 100644
--- a/Example/webpack.config.js
+++ b/Example/webpack.config.js
@@ -1,19 +1,19 @@
-const path = require('path');
-const outputPath = path.resolve(__dirname, 'dist');
+const path = require("path");
+const outputPath = path.resolve(__dirname, "dist");
module.exports = {
- entry: './src/index.js',
- mode: 'development',
- output: {
- filename: 'main.js',
- path: outputPath,
- },
- devServer: {
- inline: true,
- watchContentBase: true,
- contentBase: [
- path.join(__dirname, 'public'),
- path.join(__dirname, 'dist'),
- ],
- },
+ entry: "./src/index.js",
+ mode: "development",
+ output: {
+ filename: "main.js",
+ path: outputPath,
+ },
+ devServer: {
+ inline: true,
+ watchContentBase: true,
+ contentBase: [
+ path.join(__dirname, "public"),
+ path.join(__dirname, "dist"),
+ ],
+ },
};
diff --git a/IntegrationTests/Makefile b/IntegrationTests/Makefile
index 4d6847fd7..8f3de13b5 100644
--- a/IntegrationTests/Makefile
+++ b/IntegrationTests/Makefile
@@ -16,7 +16,7 @@ node_modules: package-lock.json
.PHONY: build_rt
build_rt: node_modules
- cd ../Runtime && npm run build
+ cd .. && npm run build
.PHONY: benchmark
benchmark: build_rt dist/BenchmarkTests.wasm
diff --git a/IntegrationTests/bin/benchmark-tests.js b/IntegrationTests/bin/benchmark-tests.js
index 7f7dd35d6..daf5a5e1b 100644
--- a/IntegrationTests/bin/benchmark-tests.js
+++ b/IntegrationTests/bin/benchmark-tests.js
@@ -1,42 +1,44 @@
-const { startWasiTask } = require("../lib")
+const { startWasiTask } = require("../lib");
const { performance } = require("perf_hooks");
-global.benchmarkRunner = function(name, body) {
- console.log(`Running '${name}' ...`)
- const startTime = performance.now();
- body(5000)
- const endTime = performance.now();
- console.log("done " + (endTime - startTime) + " ms");
-}
+global.benchmarkRunner = function (name, body) {
+ console.log(`Running '${name}' ...`);
+ const startTime = performance.now();
+ body(5000);
+ const endTime = performance.now();
+ console.log("done " + (endTime - startTime) + " ms");
+};
class JSBenchmark {
- constructor(title) { this.title = title }
+ constructor(title) {
+ this.title = title;
+ }
testSuite(name, body) {
benchmarkRunner(`${this.title}/${name}`, (iteration) => {
for (let idx = 0; idx < iteration; idx++) {
- body()
+ body();
}
- })
+ });
}
}
-const serialization = new JSBenchmark("Serialization")
+const serialization = new JSBenchmark("Serialization");
serialization.testSuite("Write JavaScript number directly", () => {
- const jsNumber = 42
- const object = global
+ const jsNumber = 42;
+ const object = global;
for (let idx = 0; idx < 100; idx++) {
- object["numberValue" + idx] = jsNumber
+ object["numberValue" + idx] = jsNumber;
}
-})
+});
serialization.testSuite("Write JavaScript string directly", () => {
- const jsString = "Hello, world"
- const object = global
+ const jsString = "Hello, world";
+ const object = global;
for (let idx = 0; idx < 100; idx++) {
- object["stringValue" + idx] = jsString
+ object["stringValue" + idx] = jsString;
}
-})
+});
-startWasiTask("./dist/BenchmarkTests.wasm").catch(err => {
- console.log(err)
-});
\ No newline at end of file
+startWasiTask("./dist/BenchmarkTests.wasm").catch((err) => {
+ console.log(err);
+});
diff --git a/IntegrationTests/bin/primary-tests.js b/IntegrationTests/bin/primary-tests.js
index 9bd87c93d..1d7c47b78 100644
--- a/IntegrationTests/bin/primary-tests.js
+++ b/IntegrationTests/bin/primary-tests.js
@@ -1,46 +1,58 @@
global.globalObject1 = {
- "prop_1": {
- "nested_prop": 1,
- },
- "prop_2": 2,
- "prop_3": true,
- "prop_4": [
- 3, 4, "str_elm_1", null, undefined, 5,
- ],
- "prop_5": {
- "func1": function () { return },
- "func2": function () { return 1 },
- "func3": function (n) { return n * 2},
- "func4": function (a, b, c) { return a + b + c },
- "func5": function (x) { return "Hello, " + x },
- "func6": function (c, a, b) {
- if (c) { return a } else { return b }
+ prop_1: {
+ nested_prop: 1,
},
- },
- "prop_6": {
- "call_host_1": () => {
- return global.globalObject1.prop_6.host_func_1()
- }
- },
- "prop_7": 3.14,
- "prop_8": [0, , 2, 3, , , 6],
-}
+ prop_2: 2,
+ prop_3: true,
+ prop_4: [3, 4, "str_elm_1", null, undefined, 5],
+ prop_5: {
+ func1: function () {
+ return;
+ },
+ func2: function () {
+ return 1;
+ },
+ func3: function (n) {
+ return n * 2;
+ },
+ func4: function (a, b, c) {
+ return a + b + c;
+ },
+ func5: function (x) {
+ return "Hello, " + x;
+ },
+ func6: function (c, a, b) {
+ if (c) {
+ return a;
+ } else {
+ return b;
+ }
+ },
+ },
+ prop_6: {
+ call_host_1: () => {
+ return global.globalObject1.prop_6.host_func_1();
+ },
+ },
+ prop_7: 3.14,
+ prop_8: [0, , 2, 3, , , 6],
+};
-global.Animal = function(name, age, isCat) {
- this.name = name
- this.age = age
- this.bark = () => {
- return isCat ? "nyan" : "wan"
- }
- this.isCat = isCat
- this.getIsCat = function() {
- return this.isCat
- }
-}
+global.Animal = function (name, age, isCat) {
+ this.name = name;
+ this.age = age;
+ this.bark = () => {
+ return isCat ? "nyan" : "wan";
+ };
+ this.isCat = isCat;
+ this.getIsCat = function () {
+ return this.isCat;
+ };
+};
-const { startWasiTask } = require("../lib")
+const { startWasiTask } = require("../lib");
-startWasiTask("./dist/PrimaryTests.wasm").catch(err => {
- console.log(err)
- process.exit(1)
+startWasiTask("./dist/PrimaryTests.wasm").catch((err) => {
+ console.log(err);
+ process.exit(1);
});
diff --git a/IntegrationTests/lib.js b/IntegrationTests/lib.js
index d1c9b64c9..ee0a6a33f 100644
--- a/IntegrationTests/lib.js
+++ b/IntegrationTests/lib.js
@@ -7,44 +7,44 @@ const fs = require("fs");
const readFile = promisify(fs.readFile);
const startWasiTask = async (wasmPath) => {
- // Instantiate a new WASI Instance
- const wasmFs = new WasmFs();
- // Output stdout and stderr to console
- const originalWriteSync = wasmFs.fs.writeSync;
- wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
- const text = new TextDecoder("utf-8").decode(buffer);
- switch (fd) {
- case 1:
- console.log(text);
- break;
- case 2:
- console.error(text);
- break;
- }
- return originalWriteSync(fd, buffer, offset, length, position);
- };
- let wasi = new WASI({
- args: [],
- env: {},
- bindings: {
- ...WASI.defaultBindings,
- fs: wasmFs.fs
- }
- });
+ // Instantiate a new WASI Instance
+ const wasmFs = new WasmFs();
+ // Output stdout and stderr to console
+ const originalWriteSync = wasmFs.fs.writeSync;
+ wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
+ const text = new TextDecoder("utf-8").decode(buffer);
+ switch (fd) {
+ case 1:
+ console.log(text);
+ break;
+ case 2:
+ console.error(text);
+ break;
+ }
+ return originalWriteSync(fd, buffer, offset, length, position);
+ };
+ let wasi = new WASI({
+ args: [],
+ env: {},
+ bindings: {
+ ...WASI.defaultBindings,
+ fs: wasmFs.fs,
+ },
+ });
- const swift = new SwiftRuntime();
- // Fetch our Wasm File
- const wasmBinary = await readFile(wasmPath);
+ const swift = new SwiftRuntime();
+ // Fetch our Wasm File
+ const wasmBinary = await readFile(wasmPath);
- // Instantiate the WebAssembly file
- let { instance } = await WebAssembly.instantiate(wasmBinary, {
- wasi_snapshot_preview1: wasi.wasiImport,
- javascript_kit: swift.importObjects(),
- });
+ // Instantiate the WebAssembly file
+ let { instance } = await WebAssembly.instantiate(wasmBinary, {
+ wasi_snapshot_preview1: wasi.wasiImport,
+ javascript_kit: swift.importObjects(),
+ });
- swift.setInstance(instance);
- // Start the WebAssembly WASI instance!
- wasi.start(instance);
+ swift.setInstance(instance);
+ // Start the WebAssembly WASI instance!
+ wasi.start(instance);
};
-module.exports = { startWasiTask }
\ No newline at end of file
+module.exports = { startWasiTask };
diff --git a/IntegrationTests/package.json b/IntegrationTests/package.json
index 96997ba5e..41f58cf17 100644
--- a/IntegrationTests/package.json
+++ b/IntegrationTests/package.json
@@ -1,6 +1,7 @@
{
+ "private": true,
"dependencies": {
- "javascript-kit-swift": "file:../Runtime",
+ "javascript-kit-swift": "file:..",
"@wasmer/wasi": "^0.12.0",
"@wasmer/wasmfs": "^0.12.0"
}
diff --git a/Makefile b/Makefile
index 928f37c45..c247ec141 100644
--- a/Makefile
+++ b/Makefile
@@ -2,12 +2,12 @@ MAKEFILE_DIR := $(dir $(lastword $(MAKEFILE_LIST)))
.PHONY: bootstrap
bootstrap:
- cd Runtime && npm install
+ npm install
.PHONY: build
build:
swift build --triple wasm32-unknown-wasi
- cd Runtime && npm run build
+ npm run build
.PHONY: test
test:
diff --git a/README.md b/README.md
index e8955230a..dcd752833 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@ This library only supports [`swiftwasm/swift`](https://github.com/swiftwasm/swif
The toolchains can be installed via [`swiftenv`](https://github.com/kylef/swiftenv) like official nightly toolchain.
e.g.
+
```sh
$ swiftenv install https://github.com/swiftwasm/swift/releases/download/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-06-03-a/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-06-03-a-osx.tar.gz
@@ -24,22 +25,22 @@ Target: x86_64-apple-darwin19.3.0
This JavaScript code
```javascript
-const alert = window.alert
-const document = window.document
+const alert = window.alert;
+const document = window.document;
-const divElement = document.createElement("div")
-divElement.innerText = "Hello, world"
-const body = document.body
-body.appendChild(divElement)
+const divElement = document.createElement("div");
+divElement.innerText = "Hello, world";
+const body = document.body;
+body.appendChild(divElement);
const pet = {
age: 3,
owner: {
name: "Mike",
},
-}
+};
-alert("JavaScript is running on browser!")
+alert("JavaScript is running on browser!");
```
Can be written in Swift using JavaScriptKit
@@ -70,5 +71,4 @@ let swiftPet: Pet = try JSValueDecoder().decode(from: jsPet)
alert("Swift is running on browser!")
```
-
Please see [Example](https://github.com/swiftwasm/JavaScriptKit/tree/master/Example) directory for more information
diff --git a/Runtime/src/index.ts b/Runtime/src/index.ts
index 506858634..a88d03845 100644
--- a/Runtime/src/index.ts
+++ b/Runtime/src/index.ts
@@ -1,32 +1,32 @@
interface ExportedMemory {
- buffer: any
+ buffer: any;
}
type ref = number;
type pointer = number;
-interface GlobalVariable { }
+interface GlobalVariable {}
declare const window: GlobalVariable;
declare const global: GlobalVariable;
let globalVariable: any;
if (typeof globalThis !== "undefined") {
- globalVariable = globalThis
+ globalVariable = globalThis;
} else if (typeof window !== "undefined") {
- globalVariable = window
+ globalVariable = window;
} else if (typeof global !== "undefined") {
- globalVariable = global
+ globalVariable = global;
} else if (typeof self !== "undefined") {
- globalVariable = self
+ globalVariable = self;
}
-
interface SwiftRuntimeExportedFunctions {
swjs_library_version(): number;
swjs_prepare_host_function_call(size: number): pointer;
swjs_cleanup_host_function_call(argv: pointer): void;
swjs_call_host_function(
host_func_id: number,
- argv: pointer, argc: number,
+ argv: pointer,
+ argc: number,
callback_func_ref: ref
): void;
}
@@ -52,13 +52,12 @@ type TypedArray =
// | BigInt64ArrayConstructor
// | BigUint64ArrayConstructor
| Float32ArrayConstructor
- | Float64ArrayConstructor
-
+ | Float64ArrayConstructor;
type SwiftRuntimeHeapEntry = {
- id: number,
- rc: number,
-}
+ id: number;
+ rc: number;
+};
class SwiftRuntimeHeap {
private _heapValueById: Map;
private _heapEntryByValue: Map;
@@ -79,45 +78,47 @@ class SwiftRuntimeHeap {
const isObject = typeof value == "object";
const entry = this._heapEntryByValue.get(value);
if (isObject && entry) {
- entry.rc++
- return entry.id
+ entry.rc++;
+ return entry.id;
}
const id = this._heapNextKey++;
- this._heapValueById.set(id, value)
+ this._heapValueById.set(id, value);
if (isObject) {
- this._heapEntryByValue.set(value, { id: id, rc: 1 })
+ this._heapEntryByValue.set(value, { id: id, rc: 1 });
}
- return id
+ return id;
}
release(ref: ref) {
const value = this._heapValueById.get(ref);
- const isObject = typeof value == "object"
+ const isObject = typeof value == "object";
if (isObject) {
const entry = this._heapEntryByValue.get(value)!;
entry.rc--;
if (entry.rc != 0) return;
this._heapEntryByValue.delete(value);
- this._heapValueById.delete(ref)
+ this._heapValueById.delete(ref);
} else {
- this._heapValueById.delete(ref)
+ this._heapValueById.delete(ref);
}
}
referenceHeap(ref: ref) {
- const value = this._heapValueById.get(ref)
+ const value = this._heapValueById.get(ref);
if (value === undefined) {
- throw new ReferenceError("Attempted to read invalid reference " + ref)
+ throw new ReferenceError(
+ "Attempted to read invalid reference " + ref
+ );
}
- return value
+ return value;
}
}
export class SwiftRuntime {
private instance: WebAssembly.Instance | null;
- private heap: SwiftRuntimeHeap
- private version: number = 611
+ private heap: SwiftRuntimeHeap;
+ private version: number = 611;
constructor() {
this.instance = null;
@@ -125,10 +126,11 @@ export class SwiftRuntime {
}
setInstance(instance: WebAssembly.Instance) {
- this.instance = instance
- const exports = this.instance.exports as any as SwiftRuntimeExportedFunctions;
+ this.instance = instance;
+ const exports = (this.instance
+ .exports as any) as SwiftRuntimeExportedFunctions;
if (exports.swjs_library_version() != this.version) {
- throw new Error("The versions of JavaScriptKit are incompatible.")
+ throw new Error("The versions of JavaScriptKit are incompatible.");
}
}
@@ -137,79 +139,89 @@ export class SwiftRuntime {
if (this.instance)
return this.instance.exports.memory as ExportedMemory;
throw new Error("WebAssembly instance is not set yet");
- }
-
+ };
const callHostFunction = (host_func_id: number, args: any[]) => {
if (!this.instance)
throw new Error("WebAssembly instance is not set yet");
- const exports = this.instance.exports as any as SwiftRuntimeExportedFunctions;
- const argc = args.length
- const argv = exports.swjs_prepare_host_function_call(argc)
+ const exports = (this.instance
+ .exports as any) as SwiftRuntimeExportedFunctions;
+ const argc = args.length;
+ const argv = exports.swjs_prepare_host_function_call(argc);
for (let index = 0; index < args.length; index++) {
- const argument = args[index]
- const base = argv + 16 * index
- writeValue(argument, base, base + 4, base + 8)
+ const argument = args[index];
+ const base = argv + 16 * index;
+ writeValue(argument, base, base + 4, base + 8);
}
let output: any;
const callback_func_ref = this.heap.retain(function (result: any) {
- output = result
- })
- exports.swjs_call_host_function(host_func_id, argv, argc, callback_func_ref)
- exports.swjs_cleanup_host_function_call(argv)
- return output
- }
-
- const textDecoder = new TextDecoder('utf-8');
+ output = result;
+ });
+ exports.swjs_call_host_function(
+ host_func_id,
+ argv,
+ argc,
+ callback_func_ref
+ );
+ exports.swjs_cleanup_host_function_call(argv);
+ return output;
+ };
+
+ const textDecoder = new TextDecoder("utf-8");
const textEncoder = new TextEncoder(); // Only support utf-8
const readString = (ref: ref) => {
return this.heap.referenceHeap(ref);
- }
+ };
const writeString = (ptr: pointer, bytes: Uint8Array) => {
const uint8Memory = new Uint8Array(memory().buffer);
for (const [index, byte] of bytes.entries()) {
- uint8Memory[ptr + index] = byte
+ uint8Memory[ptr + index] = byte;
}
- uint8Memory[ptr]
- }
+ uint8Memory[ptr];
+ };
const readUInt32 = (ptr: pointer) => {
const uint8Memory = new Uint8Array(memory().buffer);
- return uint8Memory[ptr + 0]
- + (uint8Memory[ptr + 1] << 8)
- + (uint8Memory[ptr + 2] << 16)
- + (uint8Memory[ptr + 3] << 24)
- }
+ return (
+ uint8Memory[ptr + 0] +
+ (uint8Memory[ptr + 1] << 8) +
+ (uint8Memory[ptr + 2] << 16) +
+ (uint8Memory[ptr + 3] << 24)
+ );
+ };
const readFloat64 = (ptr: pointer) => {
const dataView = new DataView(memory().buffer);
return dataView.getFloat64(ptr, true);
- }
+ };
const writeUint32 = (ptr: pointer, value: number) => {
const uint8Memory = new Uint8Array(memory().buffer);
- uint8Memory[ptr + 0] = (value & 0x000000ff) >> 0
- uint8Memory[ptr + 1] = (value & 0x0000ff00) >> 8
- uint8Memory[ptr + 2] = (value & 0x00ff0000) >> 16
- uint8Memory[ptr + 3] = (value & 0xff000000) >> 24
- }
+ uint8Memory[ptr + 0] = (value & 0x000000ff) >> 0;
+ uint8Memory[ptr + 1] = (value & 0x0000ff00) >> 8;
+ uint8Memory[ptr + 2] = (value & 0x00ff0000) >> 16;
+ uint8Memory[ptr + 3] = (value & 0xff000000) >> 24;
+ };
const writeFloat64 = (ptr: pointer, value: number) => {
const dataView = new DataView(memory().buffer);
dataView.setFloat64(ptr, value, true);
- }
+ };
const decodeValue = (
kind: JavaScriptValueKind,
- payload1: number, payload2: number
+ payload1: number,
+ payload2: number
) => {
switch (kind) {
case JavaScriptValueKind.Boolean: {
switch (payload1) {
- case 0: return false
- case 1: return true
+ case 0:
+ return false;
+ case 1:
+ return true;
}
}
case JavaScriptValueKind.Number: {
@@ -219,25 +231,27 @@ export class SwiftRuntime {
return readString(payload1);
}
case JavaScriptValueKind.Object: {
- return this.heap.referenceHeap(payload1)
+ return this.heap.referenceHeap(payload1);
}
case JavaScriptValueKind.Null: {
- return null
+ return null;
}
case JavaScriptValueKind.Undefined: {
- return undefined
+ return undefined;
}
case JavaScriptValueKind.Function: {
- return this.heap.referenceHeap(payload1)
+ return this.heap.referenceHeap(payload1);
}
default:
- throw new Error(`Type kind "${kind}" is not supported`)
+ throw new Error(`Type kind "${kind}" is not supported`);
}
- }
+ };
const writeValue = (
- value: any, kind_ptr: pointer,
- payload1_ptr: pointer, payload2_ptr: pointer
+ value: any,
+ kind_ptr: pointer,
+ payload1_ptr: pointer,
+ payload2_ptr: pointer
) => {
if (value === null) {
writeUint32(kind_ptr, JavaScriptValueKind.Null);
@@ -274,54 +288,68 @@ export class SwiftRuntime {
break;
}
default:
- throw new Error(`Type "${typeof value}" is not supported yet`)
+ throw new Error(
+ `Type "${typeof value}" is not supported yet`
+ );
}
- }
+ };
// Note:
// `decodeValues` assumes that the size of RawJSValue is 16.
const decodeValues = (ptr: pointer, length: number) => {
- let result = []
+ let result = [];
for (let index = 0; index < length; index++) {
- const base = ptr + 16 * index
- const kind = readUInt32(base)
- const payload1 = readUInt32(base + 4)
- const payload2 = readFloat64(base + 8)
- result.push(decodeValue(kind, payload1, payload2))
+ const base = ptr + 16 * index;
+ const kind = readUInt32(base);
+ const payload1 = readUInt32(base + 4);
+ const payload2 = readFloat64(base + 8);
+ result.push(decodeValue(kind, payload1, payload2));
}
- return result
- }
+ return result;
+ };
return {
swjs_set_prop: (
- ref: ref, name: ref,
+ ref: ref,
+ name: ref,
kind: JavaScriptValueKind,
- payload1: number, payload2: number
+ payload1: number,
+ payload2: number
) => {
const obj = this.heap.referenceHeap(ref);
- Reflect.set(obj, readString(name), decodeValue(kind, payload1, payload2))
+ Reflect.set(
+ obj,
+ readString(name),
+ decodeValue(kind, payload1, payload2)
+ );
},
swjs_get_prop: (
- ref: ref, name: ref,
+ ref: ref,
+ name: ref,
kind_ptr: pointer,
- payload1_ptr: pointer, payload2_ptr: pointer
+ payload1_ptr: pointer,
+ payload2_ptr: pointer
) => {
const obj = this.heap.referenceHeap(ref);
const result = Reflect.get(obj, readString(name));
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr);
},
swjs_set_subscript: (
- ref: ref, index: number,
+ ref: ref,
+ index: number,
kind: JavaScriptValueKind,
- payload1: number, payload2: number
+ payload1: number,
+ payload2: number
) => {
const obj = this.heap.referenceHeap(ref);
- Reflect.set(obj, index, decodeValue(kind, payload1, payload2))
+ Reflect.set(obj, index, decodeValue(kind, payload1, payload2));
},
swjs_get_subscript: (
- ref: ref, index: number,
+ ref: ref,
+ index: number,
kind_ptr: pointer,
- payload1_ptr: pointer, payload2_ptr: pointer
+ payload1_ptr: pointer,
+ payload2_ptr: pointer
) => {
const obj = this.heap.referenceHeap(ref);
const result = Reflect.get(obj, index);
@@ -335,7 +363,10 @@ export class SwiftRuntime {
},
swjs_decode_string: (bytes_ptr: pointer, length: number) => {
const uint8Memory = new Uint8Array(memory().buffer);
- const bytes = uint8Memory.subarray(bytes_ptr, bytes_ptr + length);
+ const bytes = uint8Memory.subarray(
+ bytes_ptr,
+ bytes_ptr + length
+ );
const string = textDecoder.decode(bytes);
return this.heap.retain(string);
},
@@ -344,64 +375,90 @@ export class SwiftRuntime {
writeString(buffer, bytes);
},
swjs_call_function: (
- ref: ref, argv: pointer, argc: number,
+ ref: ref,
+ argv: pointer,
+ argc: number,
kind_ptr: pointer,
- payload1_ptr: pointer, payload2_ptr: pointer
+ payload1_ptr: pointer,
+ payload2_ptr: pointer
) => {
- const func = this.heap.referenceHeap(ref)
- const result = Reflect.apply(func, undefined, decodeValues(argv, argc))
+ const func = this.heap.referenceHeap(ref);
+ const result = Reflect.apply(
+ func,
+ undefined,
+ decodeValues(argv, argc)
+ );
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr);
},
swjs_call_function_with_this: (
- obj_ref: ref, func_ref: ref,
- argv: pointer, argc: number,
+ obj_ref: ref,
+ func_ref: ref,
+ argv: pointer,
+ argc: number,
kind_ptr: pointer,
- payload1_ptr: pointer, payload2_ptr: pointer
+ payload1_ptr: pointer,
+ payload2_ptr: pointer
) => {
- const obj = this.heap.referenceHeap(obj_ref)
- const func = this.heap.referenceHeap(func_ref)
- const result = Reflect.apply(func, obj, decodeValues(argv, argc))
+ const obj = this.heap.referenceHeap(obj_ref);
+ const func = this.heap.referenceHeap(func_ref);
+ const result = Reflect.apply(
+ func,
+ obj,
+ decodeValues(argv, argc)
+ );
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr);
},
swjs_create_function: (
host_func_id: number,
- func_ref_ptr: pointer,
+ func_ref_ptr: pointer
) => {
const func_ref = this.heap.retain(function () {
- return callHostFunction(host_func_id, Array.prototype.slice.call(arguments))
- })
- writeUint32(func_ref_ptr, func_ref)
+ return callHostFunction(
+ host_func_id,
+ Array.prototype.slice.call(arguments)
+ );
+ });
+ writeUint32(func_ref_ptr, func_ref);
},
swjs_call_new: (
- ref: ref, argv: pointer, argc: number,
+ ref: ref,
+ argv: pointer,
+ argc: number,
result_obj: pointer
) => {
- const obj = this.heap.referenceHeap(ref)
- const result = Reflect.construct(obj, decodeValues(argv, argc))
+ const obj = this.heap.referenceHeap(ref);
+ const result = Reflect.construct(obj, decodeValues(argv, argc));
if (typeof result != "object")
- throw Error(`Invalid result type of object constructor of "${obj}": "${result}"`)
+ throw Error(
+ `Invalid result type of object constructor of "${obj}": "${result}"`
+ );
writeUint32(result_obj, this.heap.retain(result));
},
- swjs_instanceof: (
- obj_ref: ref, constructor_ref: ref
- ) => {
- const obj = this.heap.referenceHeap(obj_ref)
- const constructor = this.heap.referenceHeap(constructor_ref)
- return obj instanceof constructor
+ swjs_instanceof: (obj_ref: ref, constructor_ref: ref) => {
+ const obj = this.heap.referenceHeap(obj_ref);
+ const constructor = this.heap.referenceHeap(constructor_ref);
+ return obj instanceof constructor;
},
swjs_create_typed_array: (
constructor_ref: ref,
- elementsPtr: pointer, length: number,
+ elementsPtr: pointer,
+ length: number,
result_obj: pointer
) => {
- const ArrayType: TypedArray = this.heap.referenceHeap(constructor_ref);
- const array = new ArrayType(memory().buffer, elementsPtr, length);
+ const ArrayType: TypedArray = this.heap.referenceHeap(
+ constructor_ref
+ );
+ const array = new ArrayType(
+ memory().buffer,
+ elementsPtr,
+ length
+ );
// Call `.slice()` to copy the memory
writeUint32(result_obj, this.heap.retain(array.slice()));
},
swjs_release: (ref: ref) => {
- this.heap.release(ref)
- }
- }
+ this.heap.release(ref);
+ },
+ };
}
}
diff --git a/Runtime/tsconfig.json b/Runtime/tsconfig.json
index 44ce979ac..011c119de 100644
--- a/Runtime/tsconfig.json
+++ b/Runtime/tsconfig.json
@@ -9,10 +9,6 @@
"target": "es2017",
"skipLibCheck": true
},
- "include": [
- "src/**/*"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/Runtime/package-lock.json b/package-lock.json
similarity index 60%
rename from Runtime/package-lock.json
rename to package-lock.json
index d535aa394..44b3e1657 100644
--- a/Runtime/package-lock.json
+++ b/package-lock.json
@@ -4,6 +4,12 @@
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+ "prettier": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.1.2.tgz",
+ "integrity": "sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg==",
+ "dev": true
+ },
"typescript": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.0.2.tgz",
diff --git a/Runtime/package.json b/package.json
similarity index 85%
rename from Runtime/package.json
rename to package.json
index bc5b54820..e039b9150 100644
--- a/Runtime/package.json
+++ b/package.json
@@ -2,14 +2,14 @@
"name": "javascript-kit-swift",
"version": "0.6.0",
"description": "A runtime library of JavaScriptKit which is Swift framework to interact with JavaScript through WebAssembly.",
- "main": "lib/index.js",
+ "main": "Runtime/lib/index.js",
"files": [
"lib"
],
"scripts": {
"build": "npm run build:clean && npm run build:ts",
- "build:clean": "rm -rf lib",
- "build:ts": "tsc -b",
+ "build:clean": "rm -rf Runtime/lib",
+ "build:ts": "cd Runtime; tsc -b",
"prepublishOnly": "npm run build"
},
"keywords": [
@@ -31,6 +31,7 @@
"author": "swiftwasm",
"license": "MIT",
"devDependencies": {
+ "prettier": "2.1.2",
"typescript": "^4.0.2"
}
}