diff --git a/backend-assemblyscript/step-2-json-encoding/.gitignore b/backend-assemblyscript/step-2-json-encoding/.gitignore new file mode 100644 index 0000000..dd87e2d --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/.gitignore @@ -0,0 +1,2 @@ +node_modules +build diff --git a/backend-assemblyscript/step-2-json-encoding/as-pect.config.js b/backend-assemblyscript/step-2-json-encoding/as-pect.config.js new file mode 100644 index 0000000..30150c7 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/as-pect.config.js @@ -0,0 +1,69 @@ +module.exports = { + /** + * A set of globs passed to the glob package that qualify typescript files for testing. + */ + include: ["assembly/__tests__/**/*.spec.ts"], + /** + * A set of globs passed to the glob package that quality files to be added to each test. + */ + add: ["assembly/__tests__/**/*.include.ts"], + /** + * All the compiler flags needed for this test suite. Make sure that a binary file is output. + */ + flags: { + /** To output a wat file, uncomment the following line. */ + // "--textFile": ["output.wat"], + /** A runtime must be provided here. */ + "--runtime": ["full"] // Acceptable values are: full, half, stub (arena), and none + }, + /** + * A set of regexp that will disclude source files from testing. + */ + disclude: [/node_modules/], + /** + * Add your required AssemblyScript imports here. + */ + imports: {}, + /** + * All performance statistics reporting can be configured here. + */ + performance: { + /** Enable performance statistics gathering for every test. */ + enabled: false, + /** Set the maximum number of samples to run for every test. */ + maxSamples: 10000, + /** Set the maximum test run time in milliseconds for every test. */ + maxTestRunTime: 5000, + /** Report the median time in the default reporter for every test. */ + reportMedian: true, + /** Report the average time in milliseconds for every test. */ + reportAverage: true, + /** Report the standard deviation for every test. */ + reportStandardDeviation: false, + /** Report the maximum run time in milliseconds for every test. */ + reportMax: false, + /** Report the minimum run time in milliseconds for every test. */ + reportMin: false, + }, + /** + * Add a custom reporter here if you want one. The following example is in typescript. + * + * @example + * import { TestReporter, TestGroup, TestResult, TestContext } from "as-pect"; + * + * export class CustomReporter extends TestReporter { + * // implement each abstract method here + * public abstract onStart(suite: TestContext): void; + * public abstract onGroupStart(group: TestGroup): void; + * public abstract onGroupFinish(group: TestGroup): void; + * public abstract onTestStart(group: TestGroup, result: TestResult): void; + * public abstract onTestFinish(group: TestGroup, result: TestResult): void; + * public abstract onFinish(suite: TestContext): void; + * } + */ + // reporter: new CustomReporter(), + /** + * Specify if the binary wasm file should be written to the file system. + */ + outputBinary: false, +}; diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/as-pect.d.ts b/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/as-pect.d.ts new file mode 100644 index 0000000..0a5912a --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/as-pect.d.ts @@ -0,0 +1,865 @@ +/** + * This function creates a test group in the test loader. + * + * @param {string} description - This is the name of the test group. + * @param {() => void} callback - A function that contains all of the closures for this test group. + * + * @example + * + * ```ts + * describe("my test suite", (): void => { + * // put your tests here + * }); + * ``` + */ +declare function describe(description: string, callback: () => void): void; + +/** + * This function creates a test inside the given test group. It must be placed inside a describe + * block. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + * + * @example + * + * ```ts + * describe("the meaning of life", (): void => { + * it("should be 42", (): void => { + * // put your expectations here + * expect(29 + 13).toBe(42); + * }); + * }); + * ``` + */ +declare function it(description: string, callback: () => void): void; + +/** + * A test that does not run, and is longhand equivalent to using todo function without a + * callback. This test does not get run and is reported like a todo. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + */ +declare function xit(description: string, callback: () => void): void; + +/** + * A test that does not run, and is longhand equivalent to using todo function without a + * callback. This test does not get run and is reported like a todo. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + */ +declare function xtest(description: string, callback: () => void): void; + +/** + * This function creates a test inside the given test group. It must be placed inside a describe + * block. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + * + * @example + * ```ts + * describe("the meaning of life", (): void => { + * test("the value should be 42", (): void => { + * // put your expectations here + * expect(29 + 13).toBe(42); + * }); + * }); + * ``` + */ +declare function test(description: string, callback: () => void): void; + +/** + * This function creates a test that is expected to fail. This is useful to verify if a given + * behavior is expected to throw. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + * @param {string?} message - A message that describes why the test should fail. + * + * @example + * + * ```ts + * describe("the meaning of life", (): void => { + * throws("the value should be 42", (): void => { + * // put your expectations here + * expect(29 + 13).not.toBe(42); + * }); + * }); + * ``` + */ +declare function throws(description: string, callback: () => void, message?: string): void; + + +/** + * This function creates a test that is expected to fail. This is useful to verify if a given + * behavior is expected to throw. + * + * @param {string} description - This is the name of the test, and should describe a behavior. + * @param {() => void} callback - A function that contains a set of expectations for this test. + * @param {string?} message - A message that describes why the test should fail. + * + * @example + * + * ```ts + * describe("the meaning of life", (): void => { + * itThrows("when the value should be 42", (): void => { + * // put your expectations here + * expect(29 + 13).not.toBe(42); + * }, "The value is actually 42."); + * }); + * ``` + */ +declare function itThrows(description: string, callback: () => void, message?: string): void; + +/** + * This function creates a callback that is called before each individual test is run in this test + * group. + * + * @param {function} callback - The function to be run before each test in the current test group. + * + * @example + * + * ```ts + * // create a global + * var cat: Cat = new Cat(); + * + * describe("cats", (): void => { + * beforeEach((): void => { + * cat.meow(1); // meow once per test + * }); + * }); + * ``` + */ +declare function beforeEach(callback: () => void): void; + +/** + * This function creates a callback that is called before the whole test group is run, and only + * once. + * + * @param {function} callback - The function to be run before each test in the current test group. + * + * @example + * + * ```ts + * // create a global + * var dog: Dog = null; + * describe("dogs", (): void => { + * beforeAll((): void => { + * dog = new Dog(); // create a single dog once before the tests start + * }); + * }); + * ``` + */ +declare function beforeAll(callback: () => void): void; + +/** + * This function creates a callback that is called after each individual test is run in this test + * group. + * + * @param {function} callback - The function to be run after each test in the current test group. + * + * @example + * + * ```ts + * // create a global + * var cat: Cat = new Cat(); + * + * describe("cats", (): void => { + * afterEach((): void => { + * cat.sleep(12); // cats sleep a lot + * }); + * }); + * ``` + */ +declare function afterEach(callback: () => void): void; + +/** + * This function creates a callback that is called after the whole test group is run, and only + * once. + * + * @param {function} callback - The function to be run after each test in the current test group. + * + * @example + * + * ```ts + * // create a global + * var dog: Dog = null; + * describe("dogs", (): void => { + * afterAll((): void => { + * memory.free(changetype(dog)); // free some memory + * }); + * }); + * ``` + */ +declare function afterAll(callback: () => void): void; + +/** + * Describes a value and returns an expectation to test the value. + * + * @type {T} - The expectation's type. + * @param {T} actual - The value being tested. + * + * @example + * + * ```ts + * expect(42).not.toBe(-1, "42 should not be -1"); + * expect(19 + 23).toBe(42, "19 + 23 should equal 42"); + * ``` + */ +declare function expect(actual: T | null): Expectation; + +/** + * Describes a void function and returns an expectation to test the function. + * + * @param {() => void} callback - The callback being tested. + * + * @example + * + * ```ts + * expectFn((): void => unreachable()).toThrow("unreachables do not throw"); + * expectFn((): void => { + * cat.meow(); + * }).not.toThrow("Uhoh, cats can't meow!");; + * ``` + */ +declare function expectFn(cb: () => void): Expectation<() => void>; + +/** + * Describes a test that needs to be written. + * + * @param {string} description - The description of the test that needs to be written. + */ +declare function todo(description: string): void; + +/** + * Logs a single value to the logger, and is stringified. It works for references, values, and + * strings. + * + * @type {T} - The type to be logged. + * @param {T | null} value - The value to be logged. + * + * @example + * + * ```ts + * log("This is a logged value."); + * log(42); + * log(new Vec(1, 2, 3)); + * log(null); + * ``` + */ +declare function log(value: T | null): void; + +/** + * An expectation for a value. + */ +// @ts-ignore +declare class Expectation { + + /** + * Create a new expectation. + * + * @param {T | null} actual - The actual value of the expectation. + */ + constructor(actual: T | null); + + /** + * This expectation performs a strict equality on value types and reference types. + * + * @param {T | null} expected - The value to be compared. + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(42).not.toBe(-1, "42 should not be -1"); + * expect(19 + 23).toBe(42, "19 + 23 should equal 42"); + * ``` + */ + toBe(expected: T | null, message?: string): void; + + /** + * This expectation performs a strict equality on value types and performs a memcompare on + * reference types. If the reference type `T` has reference types as properties, the comparison does + * not perform property traversal. It will only compare the pointer values in the memory block, and + * only compare `offsetof()` bytes, regardless of the allocated block size. + * + * @param {T | null} expected - The value to be compared. + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(new Vec3(1, 2, 3)).toStrictEqual(new Vec(1, 2, 3), "Vectors of the same shape should be equal"); + * ``` + */ + toStrictEqual(expected: T | null, message?: string): void; + + /** + * This expectation performs a strict memory block equality based on the allocated block sizes. + * + * @param {T | null} expected - The value to be compared. + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(new Vec3(1, 2, 3)).toBlockEqual(new Vec(1, 2, 3), "Vectors of the same shape should be equal"); + * ``` + */ + toBlockEqual(expected: T | null, message?: string): void; + + /** + * If the value is callable, it calls the function, and fails the expectation if it throws, or hits + * an unreachable(). + * + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expectFn((): void => unreachable()).toThrow("unreachable() should throw."); + * expectFn((): void => { + * cat.sleep(100); // cats can sleep quite a lot + * }).not.toThrow("cats should sleep, not throw"); + * ``` + */ + toThrow(message?: string): void; + + /** + * This expecation asserts that the value is truthy, like in javascript. If the value is a string, + * then strings of length 0 are not truthy. + * + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(true).toBeTruthy("true is truthy."); + * expect(1).toBeTruthy("numeric values that are not 0 are truthy."); + * expect(new Vec3(1, 2, 3)).toBeTruthy("reference types that aren't null are truthy."); + * expect(false).not.toBeTruthy("false is not truthy."); + * expect(0).not.toBeTruthy("0 is not truthy."); + * expect(null).not.toBeTruthy("null is not truthy."); + * ``` + */ + toBeTruthy(message?: string): void; + + /** + * This expectation tests the value to see if it is null. If the value is a value type, it is + * never null. If the value is a reference type, it performs a strict null comparison. + * + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(0).not.toBeNull("numbers are never null"); + * expect(null).toBeNull("null reference types are null."); + * ``` + */ + toBeNull(message?: string): void; + + /** + * This expecation assert that the value is falsy, like in javascript. If the value is a string, + * then strings of length 0 are falsy. + * + * @param {string} message - The optional message that describes the expectation. + * + * @example + * + * ```ts + * expect(false).toBeFalsy("false is falsy."); + * expect(0).toBeFalsy("0 is falsy."); + * expect(null).toBeFalsy("null is falsy."); + * expect(true).not.toBeFalsy("true is not falsy."); + * expect(1).not.toBeFalsy("numeric values that are not 0 are not falsy."); + * expect(new Vec3(1, 2, 3)).not.toBeFalsy("reference types that aren't null are not falsy."); + * ``` + */ + toBeFalsy(message?: string): void; + + /** + * This expectation asserts that the value is greater than the expected value. Since operators can + * be overloaded in assemblyscript, it's possible for this to work on reference types. + * + * @param {T | null} expected - The expected value that the actual value should be greater than. + * @param {string} message - The optional message that describes this expectation. + * + * @example + * + * ```ts + * expect(10).toBeGreaterThan(4); + * expect(12).not.toBeGreaterThan(42); + * ``` + */ + toBeGreaterThan(expected: T | null, message?: string): void; + + /** + * This expectation asserts that the value is less than the expected value. Since operators can + * be overloaded in assemblyscript, it's possible for this to work on reference types. + * + * @param {T | null} value - The expected value that the actual value should be less than. + * @param {string} message - The optional message that describes this expectation. + * + * @example + * + * ```ts + * expect(10).not.toBeLessThan(4); + * expect(12).toBeLessThan(42); + * ``` + */ + toBeLessThan(expected: T | null, message?: string): void; + + /** + * This expectation asserts that the value is greater than or equal to the expected value. Since + * operators can be overloaded in assemblyscript, it's possible for this to work on reference + * types. + * + * @param {T | null} value - The expected value that the actual value should be greater than or + * equal to. + * @param {string} message - The optional message that describes this expectation. + * + * @example + * + * ```ts + * expect(42).toBeGreaterThanOrEqual(42); + * expect(10).toBeGreaterThanOrEqual(4); + * expect(12).not.toBeGreaterThanOrEqual(42); + * ``` + */ + toBeGreaterThanOrEqual(expected: T | null, message?: string): void; + + /** + * This expectation asserts that the value is less than or equal to the expected value. Since + * operators can be overloaded in assemblyscript, it's possible for this to work on reference + * types. + * + * @param {T | null} value - The expected value that the actual value should be less than or equal + * to. + * @param {string} message - The optional message that describes this expectation. + * + * @example + * + * ```ts + * expect(42).toBeLessThanOrEqual(42); + * expect(10).not.toBeLessThanOrEqual(4); + * expect(12).toBeLessThanOrEqual(42); + * ``` + */ + toBeLessThanOrEqual(expected: T | null, message?: string): void; + + /** + * This expectation asserts that the value is close to another value. Both numbers must be finite, + * and T must extend f64 or f32. + * + * @param {T extends f64 | f32} value - The expected value to be close to. + * @param {i32} decimalPlaces - The number of decimal places used to calculate epsilon. Default is + * 2. + * @param {string} message - The optional message that describes this expectation. + * + * @example + * + * ```ts + * expect(0.1 + 0.2).toBeCloseTo(0.3); + * ``` + */ + toBeCloseTo(expected: T, decimalPlaces?: number, message?: string): void; + + /** + * This function asserts the float type value is NaN. + * + * @param {string} message - The optional message the describes this expectation. + * + * @example + * + * ```ts + * expect(NaN).toBeNaN(); + * expect(42).not.toBeNaN(); + * ``` + */ + toBeNaN(message?: string): void; + + /** + * This function asserts a float is finite. + * + * @param {string} message - The optional message the describes this expectation. + * @example + * + * ```ts + * expect(42).toBeFinite(); + * expect(Infinity).not.toBeFinite(); + * ``` + */ + toBeFinite(message?: string): void; + + /** + * This method asserts the item has the expected length. + * + * @param {i32} expected - The expected length. + * @param {string} message - The optional message the describes this expectation. + * + * ```ts + * expect([1, 2, 3]).toHaveLength(3); + * ``` + */ + toHaveLength(expected: i32, message?: string): void; + + /** + * This method asserts that a given T that extends `Array` has a value/reference included. + * + * @param {valueof} expected - The expected item to be included in the Array. + * @param {string} message - The optional message the describes this expectation. + * + * @example + * + * ```ts + * expect([1, 2, 3]).toInclude(3); + * ``` + */ + // @ts-ignore: expected value should be known at compile time + toInclude(expected: valueof, message?: string): void; + + /** + * This method asserts that a given T that extends `Array` has a value/reference included. + * + * @param {valueof} expected - The expected item to be included in the Array. + * @param {string} message - The optional message the describes this expectation. + * + * @example + * + * ```ts + * expect([1, 2, 3]).toContain(3); + * ``` + */ + // @ts-ignore: expected value should be known at compile time + toContain(expected: valueof, message?: string): void; + + /** + * This method asserts that a given T that extends `Array` has a value/reference included and + * compared via memory.compare(). + * + * @param {i32} expected - The expected item to be included in the Array. + * @param {string} message - The optional message the describes this expectation. + * + * @example + * ```ts + * expect([new Vec3(1, 2, 3)]).toInclude(new Vec3(1, 2, 3)); + * ``` + */ + // @ts-ignore: expected value should be known at compile time + toIncludeEqual(expected: valueof, message?: string): void; + + /** + * This method asserts that a given T that extends `Array` has a value/reference included and + * compared via memory.compare(). + * + * @param {i32} expected - The expected item to be included in the Array. + * @param {string} message - The optional message the describes this expectation. + * + * @example + * ```ts + * expect([new Vec3(1, 2, 3)]).toInclude(new Vec3(1, 2, 3)); + * ``` + */ + // @ts-ignore: expected value should be known at compile time + toContainEqual(expected: valueof, message?: string): void; + + /** + * This computed property is chainable, and negates the existing expectation. It returns itself. + * + * @example + * ```ts + * expect(42).not.toBe(0, "42 is not 0"); + */ + not: Expectation; + + /** + * The actual value of the expectation. + */ + actual: T | null; +} + +/** + * This is called to stop the debugger. e.g. `node --inspect-brk asp`. + */ +declare function debug(): void; + +/** + * This class contains a set of methods related to performance configuration. + */ +// @ts-ignore +declare class Performance { + /** + * This function call enables performance statistics gathering for the following test. + * + * @param {bool} enabled - The bool to indicate if performance statistics should be gathered. + */ + public static enabled(enabled: bool): void; + + /** + * This function call sets the maximum number of samples to complete the following test. + * + * @param {f64} count - The maximum number of samples required. + */ + public static maxSamples(count: f64): void; + + /** + * This function call sets the number of decimal places to round to for the following test. + * + * @param {i32} deicmalPlaces - The number of decimal places to round to + */ + public static roundDecimalPlaces(count: i32): void; + + /** + * This function call will set the maximum amount of time that should pass before it can stop + * gathering samples for the following test. + * + * @param {f64} time - The ammount of time in milliseconds. + */ + public static maxTestRunTime(time: f64): void; + + /** + * This function call enables gathering the average/mean run time of each sample for the following + * test. + * + * @param {bool} enabled - The bool to indicate if the average/mean should be gathered. + */ + public static reportAverage(enabled: bool): void; + + /** + * This function call enables gathering the median run time of each sample for the following test. + * + * @param {bool} enabled - The bool to indicate if the median should be gathered. + */ + public static reportMedian(value: bool): void; + + /** + * This function call enables gathering the standard deviation of the run times of the samples + * collected for the following test. + * + * @param {bool} enabled - The bool to indicate if the standard deviation should be gathered. + */ + public static reportStdDev(value: bool): void; + + /** + * This function call enables gathering the largest run time of the samples collected for the + * following test. + * + * @param {bool} enabled - The bool to indicate if the max should be gathered. + */ + public static reportMax(value: bool): void; + + /** + * This function call enables gathering the smallest run time of the samples collected for the + * following test. + * + * @param {bool} enabled - The bool to indicate if the min should be gathered. + */ + public static reportMin(value: bool): void; + + /** + * This function call enables gathering the varaince of the samples collected for the following test. + * + * @param {bool} enabled - The bool to indicate if the variance should be calculated. + */ + public static reportVariance(value: bool): void; +} +/** + * Assemblyscript uses reference counting to perform garbage collection. This means when you + * allocate a managed object and return it, it's reference count is one. If another variable aliases + * it then the reference count goes up. This static class contains a few convenience methods for + * developers to test the current number of blocks allocated on the heap to make sure you aren't leaking + * references, e.i. keeping references to objects you expect to be collected. + */ +declare class RTrace { + /** + * This bool indicates if `RTrace` should call into JavaScript to obtain reference counts. + */ + public static enabled: bool; + + /** + * This method returns the current number of active references on the heap. + */ + public static count(): i32; + + /** + * This method starts a new refcounting group, and causes the next call to `RTrace.end(label)` to + * return a delta in reference counts on the heap. + * + * @param {i32} label - The numeric label for this refcounting group. + */ + public static start(label: i32): void; + + /** + * This method returns a delta of how many new (positive) or collected (negative) are on the heap. + * + * @param {i32} label - The numeric label for this refcounting group. + */ + public static end(label: i32): i32; + + /** + * This method returns the number of increments that have occurred over the course of a test + * file. + */ + public static increments(): i32; + + /** + * This method returns the number of decrements that have occurred over the course of a test + * file. + */ + public static decrements(): i32; + + /** + * This method returns the number of increments that have occurred over the course of a test + * group. + */ + public static groupIncrements(): i32; + + /** + * This method returns the number of decrements that have occurred over the course of a test + * group. + */ + public static groupDecrements(): i32; + + /** + * This method returns the number of increments that have occurred over the course of a test + * group. + */ + public static testIncrements(): i32; + + /** + * This method returns the number of decrements that have occurred over the course of a test + * group. + */ + public static testDecrements(): i32; + + /** + * This method returns the number of allocations that have occurred over the course of a test + * file. + */ + public static allocations(): i32; + + /** + * This method returns the number of frees that have occurred over the course of a test + * file. + */ + public static frees(): i32; + + /** + * This method returns the number of allocations that have occurred over the course of a test + * group. + */ + public static groupAllocations(): i32; + + /** + * This method returns the number of frees that have occurred over the course of a test + * group. + */ + public static groupFrees(): i32; + + /** + * This method returns the number of allocations that have occurred over the course of a test + * group. + */ + public static testAllocations(): i32; + + /** + * This method returns the number of frees that have occurred over the course of a test + * group. + */ + public static testFrees(): i32; + + /** + * This method triggers a garbage collection. + */ + public static collect(): void; + + /** + * Get the class id of the pointer. + * + * @param {usize} pointer - The pointer. + * @returns {u32} - The class id of the allocated block. + */ + public static classIdOf(pointer: usize): u32; + + /** + * Get the size of a block or buffer. + * + * @param {T} reference - The reference. + * @returns {u32} - The size of the allocated block. + */ + public static sizeOf(reference: T): u32; + + /** + * Get the currently allocated blocks. + */ + public static activeBlocks(): usize[]; + + /** + * Get the current groups allocated blocks. + */ + public static activeGroupBlocks(): usize[]; + + /** + * Get the current tests allocated blocks. + */ + public static activeTestBlocks(): usize[]; +} + + +/** + * This class is static and contains private global values that contain metadata about the Actual + * value. + * + * @example + * ```ts + * Actual.report("This is an expected string."); + * Actual.report([1, 2, 3]); + * Actual.report(42); + * ``` + */ +declare class Actual { + /** + * This function performs reporting to javascript what the actual value of this expectation is. + * + * @param {T} actual - The actual value to be reported. + */ + public static report(value: T): void; + + /** + * Clear the actual value and release any private memory stored as a global. + */ + public static clear(): void; +} + + +/** + * This class is static and contains private global values that contain metadata about the Expected + * value. + * + * @example + * ```ts + * Expected.report("This is an expected string."); + * Expected.report([1, 2, 3]); + * Expected.report(42, i32(true)); // not 42 + * ``` + */ +declare class Expected { + /** + * This function performs reporting to javascript what the expected value of this expectation is. + * It notifies javascript if the expectation is negated. + * + * @param {T} value - The actual value to be reported. + * @param {i32} negated - An indicator if the expectation is negated. Pass `1` to negate the + * expectation. (default: 0) + */ + public static report(value: T, negated?: i32): void; + + /** + * Clear the expected value and release any private memory stored as a global. + */ + public static clear(): void; +} diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/twit.spec.ts b/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/twit.spec.ts new file mode 100644 index 0000000..c16949e --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/__tests__/twit.spec.ts @@ -0,0 +1,15 @@ +import {handler} from "../main"; + +describe("example", () => { + + it("can log some values to the console", () => { + log("Hello world!"); // strings! + log(3.1415); // floats! + log(244); // integers! + log(0xFFFFFFFF); // long values! + log(handler('{"hi": "hi"}')); + log(handler('{"action": "Post", "msg": "Hello, Fluence!", "handle": "fluencer"}')); + log(handler('{"action": "Post", "msg": "Hello, fluencer!", "handle": "John Doe"}')); + log(handler('{"action": "Fetch"}')); + }); +}); diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/index.ts b/backend-assemblyscript/step-2-json-encoding/assembly/index.ts new file mode 100644 index 0000000..9c857e6 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/index.ts @@ -0,0 +1,22 @@ + +import {handler} from "./main"; +import {loggedStringHandler} from "../node_modules/assemblyscript-sdk/assembly/index"; +import {log} from "../node_modules/assemblyscript-sdk/assembly/logger"; + +// VM wrapper will put requests to memory through this function +export function allocate(size: usize) :i32 { + return __alloc(size, 0); +} + +// VM wrapper will deallocate response from memory after handling it +export function deallocate(ptr: i32, size: usize): void { + __free(ptr); +} + +// VM wrapper calls this function with a pointer on request in memory. +// Returns pointer on a response. +export function invoke(ptr: i32, size: i32): i32 { + // this function will parse a request as a string and return result string as a pointer in memory + // you can look on other functions in 'assemblyscript-sdk' library to handle own types of requests and responses + return loggedStringHandler(ptr, size, handler, log); +} diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/main.ts b/backend-assemblyscript/step-2-json-encoding/assembly/main.ts new file mode 100644 index 0000000..086e706 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/main.ts @@ -0,0 +1,24 @@ +import {Action, decode, PostRequest} from "./request"; +import {PostResponse, FetchResponse, UnknownResponse} from "./response"; + +let messages = new Array(); +messages.push("hello"); +messages.push("hi!"); + +// main handler for an application +export function handler(input: string): string { + + let request = decode(input); + + if (request.action == Action.Post) { + let post = request as PostRequest; + let response = new PostResponse(0); + return response.serialize() + } else if (request.action == Action.Fetch) { + let response = new FetchResponse(messages); + return response.serialize() + } + + let response = new UnknownResponse(); + return response.serialize(); +} diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/request.ts b/backend-assemblyscript/step-2-json-encoding/assembly/request.ts new file mode 100644 index 0000000..be585cc --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/request.ts @@ -0,0 +1,85 @@ +import {JSONDecoder, JSONHandler} from "../node_modules/assemblyscript-json/assembly/decoder"; + +export enum Action { + Post, + Fetch, + Unknown + // Error +} + +export abstract class Request { + public action: Action = Action.Unknown; +} + +export class PostRequest extends Request { + + public readonly msg: string; + public readonly handle: string; + + constructor(msg: string, handle: string) { + super(); + this.msg = msg; + this.handle = handle; + this.action = Action.Post; + } +} + +export class FetchRequest extends Request { + constructor() { + super(); + this.action = Action.Fetch; + } +} + +export class UnknownRequest extends Request { + constructor() { + super(); + this.action = Action.Unknown; + } +} + +export function string2Bytes(str: string): Uint8Array { + return Uint8Array.wrap(String.UTF8.encode(str)); +} + +export function decode(input: string): Request { + let jsonHandler = new RequestJSONEventsHandler(); + let decoder = new JSONDecoder(jsonHandler); + + let bytes = string2Bytes(input); + + decoder.deserialize(bytes); + + let action = jsonHandler.action; + + let request: Request; + + if (action == "Fetch") { + request = new FetchRequest(); + } else if (action == "Post") { + request = new PostRequest(jsonHandler.msg, jsonHandler.handle) + } else { + request = new UnknownRequest() + } + + return request; +} + +class RequestJSONEventsHandler extends JSONHandler { + + public action: string; + public msg: string; + public handle: string; + + setString(name: string, value: string): void { + + if (name == "action") { + this.action = value; + } else if (name == "msg") { + this.msg = value; + } else if (name == "handle") { + this.handle = value; + } + // json scheme is not strict, so we won't throw an error on excess fields + } +} diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/response.ts b/backend-assemblyscript/step-2-json-encoding/assembly/response.ts new file mode 100644 index 0000000..0b07521 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/response.ts @@ -0,0 +1,78 @@ +import {JSONEncoder} from "../node_modules/assemblyscript-json/assembly/encoder"; + +export abstract class Response { + serialize(): string { + unreachable(); + return ""; + }; +} + +export class Twit { + msg: string; + handle: string; + + constructor(msg: string, handle: string) { + this.msg = msg; + this.handle = handle; + } +} + +export class UnknownResponse extends Response { + constructor() { + super(); + } + + serialize(): string { + let encoder = new JSONEncoder(); + encoder.pushObject(null); + encoder.setString("action", "Unknown"); + encoder.setString("msg", "cannot handle request"); + encoder.popObject(); + + return encoder.toString(); + } +} + +export class PostResponse extends Response { + numberOfTwits: i32; + constructor(numberOfTwits: i32) { + super(); + this.numberOfTwits = numberOfTwits; + } + + serialize(): string { + let encoder = new JSONEncoder(); + encoder.pushObject(null); + encoder.setString("action", "Post"); + encoder.setInteger("number_of_twits", this.numberOfTwits); + encoder.popObject(); + + return encoder.toString(); + } +} + +export class FetchResponse extends Response { + messageList: Array; + + constructor(messageList: Array) { + super(); + this.messageList = messageList; + } + + serialize(): string { + let encoder = new JSONEncoder(); + encoder.pushObject(null); + encoder.setString("action", "Fetch"); + encoder.pushArray("msg_list"); + for (let i = 0; i < this.messageList.length; i++) { + let message = this.messageList[i]; + encoder.pushObject(null); + encoder.setString("msg", message); + encoder.popObject(); + } + encoder.popArray(); + encoder.popObject(); + + return encoder.toString(); + } +} diff --git a/backend-assemblyscript/step-2-json-encoding/assembly/tsconfig.json b/backend-assemblyscript/step-2-json-encoding/assembly/tsconfig.json new file mode 100644 index 0000000..c614e5c --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/assembly/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../node_modules/assemblyscript/std/assembly.json", + "include": [ + "./**/*.ts" + ] +} \ No newline at end of file diff --git a/backend-assemblyscript/step-2-json-encoding/package-lock.json b/backend-assemblyscript/step-2-json-encoding/package-lock.json new file mode 100644 index 0000000..89dfcd1 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/package-lock.json @@ -0,0 +1,235 @@ +{ + "name": "example-project", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@as-pect/assembly": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@as-pect/assembly/-/assembly-2.3.1.tgz", + "integrity": "sha512-KYBhyTEnaVcJjN/1EpzLhpbUHKT3pJjCPxm+Mdc7obnZ9EdVz6vN/lw+BQjeL4cUi1YLsnvgl8ftXcup5jVbQA==" + }, + "@as-pect/cli": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@as-pect/cli/-/cli-2.3.1.tgz", + "integrity": "sha512-ipcxrXnK9Xj1Foy92nSRsganapB+yxFe4HJ/RuwnjRQ9s8bqu0UwH12XbiHktcK7bJMs1H77/sqbQVxqoYHQcA==", + "requires": { + "@as-pect/assembly": "^2.3.1", + "@as-pect/core": "^2.3.1", + "chalk": "^2.4.2", + "glob": "^7.1.4" + } + }, + "@as-pect/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@as-pect/core/-/core-2.3.1.tgz", + "integrity": "sha512-iwd4MkGuO1wZqo9/sPlT567XYK0PkMLzBvwfkXOM2zq1wwuc5GZQrKoofgYorA40KI0edJW39djtOmPwIhx2vA==", + "requires": { + "@as-pect/assembly": "^2.3.1", + "chalk": "^2.4.2", + "csv-stringify": "^5.3.0", + "long": "^4.0.0" + } + }, + "@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "assemblyscript": { + "version": "github:assemblyscript/assemblyscript#25b92769119389c581977da12b5147d1449043db", + "from": "github:assemblyscript/assemblyscript", + "dev": true, + "requires": { + "@protobufjs/utf8": "^1.1.0", + "binaryen": "87.0.0-nightly.20190716", + "glob": "^7.1.4", + "long": "^4.0.0", + "opencollective-postinstall": "^2.0.0", + "source-map-support": "^0.5.12" + } + }, + "assemblyscript-json": { + "version": "github:fluencelabs/assemblyscript-json#a177d4b61fe1fb5e096d73019ea9bc4af5599a6a", + "from": "github:fluencelabs/assemblyscript-json#update-as1", + "dev": true + }, + "assemblyscript-sdk": { + "version": "github:fluencelabs/assemblyscript-sdk#1c5a552b5babb4d4c01e0f748165d4904dd38489", + "from": "github:fluencelabs/assemblyscript-sdk", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "binaryen": { + "version": "87.0.0-nightly.20190716", + "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-87.0.0-nightly.20190716.tgz", + "integrity": "sha512-qRGfV8cLV4HVVo1oUCtTaDmOhbwctaW7vyW0G6HKftywWOJI9t9IsCrUEFKya50RqyEnanuS2w3nfOg4bxTGqg==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "csv-stringify": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/csv-stringify/-/csv-stringify-5.3.3.tgz", + "integrity": "sha512-q8Qj+/lN74LRmG7Mg0LauE5WcnJOD5MEGe1gI57IYJCB61KWuEbAFHm1uIPDkI26aqElyBB57SlE2GGwq2EY5A==", + "optional": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "opencollective-postinstall": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.2.tgz", + "integrity": "sha512-pVOEP16TrAO2/fjej1IdOyupJY8KDUM1CvsaScRbw6oddvpQoOfGk4ywha0HKKVAD6RkW4x6Q+tNBwhf3Bgpuw==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + } + } +} diff --git a/backend-assemblyscript/step-2-json-encoding/package.json b/backend-assemblyscript/step-2-json-encoding/package.json new file mode 100644 index 0000000..c5973a5 --- /dev/null +++ b/backend-assemblyscript/step-2-json-encoding/package.json @@ -0,0 +1,21 @@ +{ + "name": "example-project", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "flbuild": "asc assembly/index.ts -b build/optimized.wasm --validate --optimize --use abort='' --runtime half", + "test": "asp" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "devDependencies": { + "assemblyscript": "github:assemblyscript/assemblyscript", + "assemblyscript-json": "github:fluencelabs/assemblyscript-json#update-as1", + "assemblyscript-sdk": "github:fluencelabs/assemblyscript-sdk", + "@as-pect/assembly": "^2.3.1", + "@as-pect/cli": "^2.3.1", + "@as-pect/core": "^2.3.1" + } +}