diff --git a/CHANGELOG.md b/CHANGELOG.md index 543514ee3b..784f3a6591 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,21 @@ +# Polywrap 0.0.1-prealpha.91 +## Features +* [PR-989](https://github.com/polywrap/monorepo/pull/989/files) `@polywrap/core-js`: Add job status in workflow job's result object. +* [PR-992](https://github.com/polywrap/monorepo/pull/992) `polywrap` CLI: Allow configuring the client using the `--client-config` on all applicable commands. +* [PR-1000](https://github.com/polywrap/monorepo/pull/1000) `@polywrap/core-js`: Added the `encodeResult` property to `InvokeOptions`. +* [PR-1000](https://github.com/polywrap/monorepo/pull/1000) `@polywrap/core-js`: Introduced the concept of `Invoker` and `Invocable`. +* [PR-988](https://github.com/polywrap/monorepo/pull/988) `polywrap` CLI, `wasm/rust`: Updates to the default build-image (`Dockerfile`): + * Added the system dependencies `clang`, `llvm` and `build-essentials`. + * Added steps to remove any `wasm-bindgen` imports that may have been injected. + +## Bugs +* [PR-1000](https://github.com/polywrap/monorepo/pull/1000) Fixed inconsistencies around `ArrayBuffer` and `Uint8Array`. +* [PR-1000](https://github.com/polywrap/monorepo/pull/1000) `@polywrap/client-js`: The `noDecode` flag (renamed to `encodeResult`) now enfoces the decoding properly, where before it could get confused with returning `Bytes` from a wrapper. +* [PR-981](https://github.com/polywrap/monorepo/pull/981) `polywrap-wasm-rs`: Remove the `wrap-invoke` feature because it is not being used at the moment. + +## Breaking Changes +* [PR-980](https://github.com/polywrap/monorepo/pull/980) `@polywrap/schema-parse`: Rename `TypeInfo` from `Abi`. + # Polywrap 0.0.1-prealpha.90 ## Features * [PR-912](https://github.com/polywrap/monorepo/pull/912) [PR-930](https://github.com/polywrap/monorepo/pull/930) [PR-958](https://github.com/polywrap/monorepo/pull/958) All URI resolver extensions have been decoupled and moved into their own plugin packages: diff --git a/VERSION b/VERSION index 6941142df8..91c458e97a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.1-prealpha.90 +0.0.1-prealpha.91 diff --git a/package.json b/package.json index df6124491e..d6c26d87d5 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,9 @@ "reset": "yarn clean && yarn && yarn build", "clean": "npx rimraf ./**/node_modules ./**/yarn.lock ./**/build ./**/coverage ./**/.polywrap", "dependencies:install": "cd dependencies && yarn", - "dependencies:link": "yarn link:schema:parse && yarn link:schema:bind", + "dependencies:link": "yarn link:schema:parse && yarn link:schema:compose && yarn link:schema:bind", "link:schema:parse": "cd packages/schema/parse && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-parse && cd ../", + "link:schema:compose": "cd packages/schema/compose && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-compose && cd ../", "link:schema:bind": "cd packages/schema/bind && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-bind && cd ../", "preinstall": "yarn dependencies:install", "build": "yarn build:core && yarn dependencies:link && yarn build:interfaces && yarn build:plugins && yarn build:client && yarn build:test-env && yarn build:cli", diff --git a/packages/cli/lang/en.json b/packages/cli/lang/en.json index 5d436c0d88..97bf197ff6 100644 --- a/packages/cli/lang/en.json +++ b/packages/cli/lang/en.json @@ -1,4 +1,6 @@ { + "commands_common_options_configPath": "config-path", + "commands_common_options_config": "Add custom configuration to the PolywrapClient", "commands_build_description": "Builds a wrapper", "commands_build_error_manifestPathMissing": "{option} option missing {argument} argument", "commands_build_error_manifestNotFound": "Manifest not found. Search paths used: {paths}", @@ -141,9 +143,7 @@ "commands_plugin_options_codegen": "Output directory for the generated types (default: {default})", "commands_run_options_workflow": "workflow", "commands_run_options_workflowScript": "Path to workflow script", - "commands_run_options_configPath": "config-path", "commands_run_options_outputFilePath": "output-file-path", - "commands_run_options_config": "Add custom configuration to the PolywrapClient", "commands_run_options_validateScript": "Validate the output of the workflow jobs", "commands_run_options_validate": "cue-file", "commands_run_options_outputFile": "Output file path for the workflow result", @@ -182,6 +182,7 @@ "commands_run_error_noApi": "API needs to be initialized", "commands_run_error_readFail": "Failed to read query {query}", "commands_run_error_unsupportedOutputFileExt": "Unsupported outputFile extention: ${outputFileExt}", + "commands_run_error_cueDoesNotExist": "Require cue to run validator, checkout https://cuelang.org/ for more information", "commands_run_error_noWorkflowScriptFound": "Workflow script not found at path: {path}", "commands_run_error_noTestEnvFound": "polywrap test-env not found, please run 'polywrap infra up --modules=eth-ens-ipfs'", "commands_testEnv_description": "Manage a test environment for Polywrap", @@ -207,7 +208,7 @@ "lib_codeGenerator_templateNoModify": "NOTE: This is generated by 'polywrap codegen', DO NOT MODIFY", "lib_codeGenerator_nogenerateBindingMethod": "The generation file provided doesn't have the 'generateBinding' method.", "lib_codeGenerator_noComposedSchema": "The schema does not exist, please define one.", - "lib_codeGenerator_typeInfoMissing": "The TypeInfo is missing from the composer output.", + "lib_codeGenerator_abiMissing": "The ABI is missing from the composer output.", "lib_compiler_compileError": "Failed to compile Polywrap", "lib_compiler_compileText": "Compile Polywrap", "lib_compiler_compileWarning": "Warnings while compiling Polywrap", diff --git a/packages/cli/lang/es.json b/packages/cli/lang/es.json index 3c8bdbe892..2cb3ac43f0 100644 --- a/packages/cli/lang/es.json +++ b/packages/cli/lang/es.json @@ -1,4 +1,6 @@ { + "commands_common_options_configPath": "config-path", + "commands_common_options_config": "Add custom configuration to the PolywrapClient", "commands_build_description": "Builds a wrapper", "commands_build_error_manifestPathMissing": "{option} option missing {argument} argument", "commands_build_error_manifestNotFound": "Manifest not found. Search paths used: {paths}", @@ -141,9 +143,7 @@ "commands_plugin_options_codegen": "Output directory for the generated types (default: {default})", "commands_run_options_workflow": "workflow", "commands_run_options_workflowScript": "Path to workflow script", - "commands_run_options_configPath": "config-path", "commands_run_options_outputFilePath": "output-file-path", - "commands_run_options_config": "Add custom configuration to the PolywrapClient", "commands_run_options_validateScript": "Validate the output of the workflow jobs", "commands_run_options_validate": "cue-file", "commands_run_options_outputFile": "Output file path for the workflow result", @@ -182,6 +182,7 @@ "commands_run_error_noApi": "API needs to be initialized", "commands_run_error_readFail": "Failed to read query {query}", "commands_run_error_unsupportedOutputFileExt": "Unsupported outputFile extention: ${outputFileExt}", + "commands_run_error_cueDoesNotExist": "Require cue to run validator, checkout https://cuelang.org/ for more information", "commands_run_error_noWorkflowScriptFound": "Workflow script not found at path: {path}", "commands_run_error_noTestEnvFound": "polywrap test-env not found, please run 'polywrap infra up --modules=eth-ens-ipfs'", "commands_testEnv_description": "Manage a test environment for Polywrap", @@ -207,7 +208,7 @@ "lib_codeGenerator_templateNoModify": "NOTE: This is generated by 'polywrap codegen', DO NOT MODIFY", "lib_codeGenerator_nogenerateBindingMethod": "The generation file provided doesn't have the 'generateBinding' method.", "lib_codeGenerator_noComposedSchema": "The schema does not exist, please define one.", - "lib_codeGenerator_typeInfoMissing": "The TypeInfo is missing from the composer output.", + "lib_codeGenerator_abiMissing": "The ABI is missing from the composer output.", "lib_compiler_compileError": "Failed to compile Polywrap", "lib_compiler_compileText": "Compile Polywrap", "lib_compiler_compileWarning": "Warnings while compiling Polywrap", diff --git a/packages/cli/src/__tests__/e2e/app.spec.ts b/packages/cli/src/__tests__/e2e/app.spec.ts index f6a7f82b32..2c7d43e12e 100644 --- a/packages/cli/src/__tests__/e2e/app.spec.ts +++ b/packages/cli/src/__tests__/e2e/app.spec.ts @@ -4,7 +4,8 @@ import { runCLI } from "@polywrap/test-env-js"; import { GetPathToCliTestFiles } from "@polywrap/test-cases"; import path from "path"; import fs from "fs"; - +import rimraf from "rimraf"; +import { compareSync } from "dir-compare"; const HELP = `Usage: polywrap app|a [options] [command] @@ -16,7 +17,7 @@ Options: Commands: codegen [options] Generate code for the app help [command] display help for command -` +`; const CODEGEN_SUCCESS = `- Manifest loaded from ./polywrap.app.yaml ✔ Manifest loaded from ./polywrap.app.yaml @@ -26,88 +27,190 @@ const CODEGEN_SUCCESS = `- Manifest loaded from ./polywrap.app.yaml `; describe("e2e tests for app command", () => { - const testCaseRoot = path.join(GetPathToCliTestFiles(), "app/codegen"); - const testCases = - fs.readdirSync(testCaseRoot, { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name); + const testCaseRoot = path.join(GetPathToCliTestFiles(), "app", "codegen"); + const testCases = fs + .readdirSync(testCaseRoot, { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory()) + .map((dirent) => dirent.name); const getTestCaseDir = (index: number) => path.join(testCaseRoot, testCases[index]); - test("Should show help text", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["app", "--help"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, + const testCliOutput = ( + testCaseDir: string, + exitCode: number, + stdout: string, + stder: string + ) => { + const output = clearStyle(stdout); + const error = clearStyle(stder); + + const expected = JSON.parse( + fs.readFileSync( + path.join(testCaseDir, "expected", "stdout.json"), + "utf-8" + ) ); + if (expected.stdout) { + if (Array.isArray(expected.stdout)) { + for (const line of expected.stdout) { + expect(output).toContain(line); + } + } else { + expect(output).toContain(expected.stdout); + } + } + + if (expected.stderr) { + if (Array.isArray(expected.stderr)) { + for (const line of expected.stderr) { + expect(error).toContain(line); + } + } else { + expect(error).toContain(expected.stderr); + } + } + + if (expected.exitCode) { + expect(exitCode).toEqual(expected.exitCode); + } + + if (expected.files) { + for (const file of expected.files) { + expect(fs.existsSync(path.join(testCaseDir, file))).toBeTruthy(); + } + } + }; + + const testCodegenOutput = (testCaseDir: string, codegenDir: string) => { + if (fs.existsSync(path.join(testCaseDir, "expected", "wrap"))) { + const expectedTypesResult = compareSync( + codegenDir, + path.join(testCaseDir, "expected", "wrap"), + { compareContent: true } + ); + expect(expectedTypesResult.differences).toBe(0); + } + }; + + it("Should show help text", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "--help"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + expect(code).toEqual(0); expect(error).toBe(""); expect(clearStyle(output)).toEqual(HELP); }); - test("Should throw error for invalid params - no command", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["app", "--output-dir"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, - ); + it("Should show help for no command", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); expect(code).toEqual(1); - expect(error).toBe("error: unknown option '--output-dir'\n"); + expect(error).toBe(HELP); + expect(output).toBe(""); + }); + + it("Should throw error for invalid command", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "invalid"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe("error: unknown command 'invalid'\n"); expect(output).toEqual(``); }); - test("Should throw error for invalid params - codegen-dir", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["app", "codegen", "--codegen-dir"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, - ); + it("Should throw error for unknown option --output-dir", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "--output-dir"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); expect(code).toEqual(1); - expect(error).toBe(`error: option '-c, --codegen-dir ' argument missing\n`); + expect(error).toBe("error: unknown option '--output-dir'\n"); expect(output).toEqual(``); }); - test("Should throw error for invalid params - ens", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["app", "codegen", "--ens"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, + describe("missing option arguments", () => { + const missingOptionArgs = { + "--manifest-file": "-m, --manifest-file ", + "--codegen-dir": "-g, --codegen-dir ", + "--client-config": "-c, --client-config " + } + + for (const [option, errorMessage] of Object.entries(missingOptionArgs)) { + it(`Should throw error if params not specified for ${option} option`, async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "codegen", option], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe( + `error: option '${errorMessage}' argument missing\n` + ); + expect(output).toEqual(``); + }); + } + }); + + it("Should store generated files to specified codegen dir", async () => { + const testCaseDir = getTestCaseDir(0); + const codegenDir = path.resolve( + process.env.TMPDIR || "/tmp", + `codegen-${Date.now()}` ); + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "codegen", "--codegen-dir", codegenDir], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); - expect(code).toEqual(1); - expect(error).toBe("error: option '-e, --ens [
]' argument missing\n"); - expect(output) - .toEqual(``); + expect(error).toBe(""); + expect(code).toEqual(0); + expect(clearStyle(output)).toEqual(CODEGEN_SUCCESS); + + testCodegenOutput(testCaseDir, codegenDir); + + rimraf.sync(codegenDir); }); describe("test-cases", () => { for (let i = 0; i < testCases.length; ++i) { const testCaseName = testCases[i]; const testCaseDir = getTestCaseDir(i); + + let cmdArgs: string[] = []; + let cmdFile = path.join(testCaseDir, "cmd.json"); + if (fs.existsSync(cmdFile)) { + const cmdConfig = JSON.parse(fs.readFileSync(cmdFile, "utf-8")); + if (cmdConfig.args) { + cmdArgs.push(...cmdConfig.args); + } + } test(testCaseName, async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["app", "codegen"], - cwd: testCaseDir, - cli: polywrapCli, - }, - ); + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["app", "codegen", ...cmdArgs], + cwd: testCaseDir, + cli: polywrapCli, + }); + + const codegenDir = path.resolve(testCaseDir, "src", "wrap"); - expect(error).toBe(""); - expect(code).toEqual(0); - expect(clearStyle(output)).toEqual(CODEGEN_SUCCESS); + testCliOutput(testCaseDir, code, output, error); + testCodegenOutput(testCaseDir, codegenDir); }); } }); diff --git a/packages/cli/src/__tests__/e2e/build.spec.ts b/packages/cli/src/__tests__/e2e/build.spec.ts index b40f705b9f..6a651ee2ff 100644 --- a/packages/cli/src/__tests__/e2e/build.spec.ts +++ b/packages/cli/src/__tests__/e2e/build.spec.ts @@ -11,73 +11,203 @@ const HELP = `Usage: polywrap build|b [options] Builds a wrapper Options: - -m, --manifest-file Path to the Polywrap Build manifest file - (default: polywrap.yaml | polywrap.yml) - -o, --output-dir Output directory for build results (default: - build/) - -w, --watch Automatically rebuild when changes are made - (default: false) - -v, --verbose Verbose output (default: false) - -h, --help display help for command + -m, --manifest-file Path to the Polywrap Build manifest file + (default: polywrap.yaml | polywrap.yml) + -o, --output-dir Output directory for build results + (default: build/) + -c, --client-config Add custom configuration to the + PolywrapClient + -w, --watch Automatically rebuild when changes are + made (default: false) + -v, --verbose Verbose output (default: false) + -h, --help display help for command `; jest.setTimeout(500000); describe("e2e tests for build command", () => { const testCaseRoot = path.join(GetPathToCliTestFiles(), "wasm/build-cmd"); - const testCases = - fs.readdirSync(testCaseRoot, { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name); + const testCases = fs + .readdirSync(testCaseRoot, { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory()) + .map((dirent) => dirent.name); const getTestCaseDir = (index: number) => path.join(testCaseRoot, testCases[index]); - test("Should show help text", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["build", "--help"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, + const testCliOutput = ( + testCaseDir: string, + exitCode: number, + stdout: string, + stder: string + ) => { + const output = clearStyle(stdout); + const error = clearStyle(stder); + + const expected = JSON.parse( + fs.readFileSync( + path.join(testCaseDir, "expected", "stdout.json"), + "utf-8" + ) ); + if (expected.stdout) { + if (Array.isArray(expected.stdout)) { + for (const line of expected.stdout) { + expect(output).toContain(line); + } + } else { + expect(output).toContain(expected.stdout); + } + } + + if (expected.stderr) { + if (Array.isArray(expected.stderr)) { + for (const line of expected.stderr) { + expect(error).toContain(line); + } + } else { + expect(error).toContain(expected.stderr); + } + } + + if (expected.exitCode) { + expect(exitCode).toEqual(expected.exitCode); + } + + if (expected.files) { + for (const file of expected.files) { + expect(fs.existsSync(path.join(testCaseDir, file))).toBeTruthy(); + } + } + }; + + const testBuildOutput = (testCaseDir: string, buildDir: string) => { + const expectedOutputFile = path.join( + testCaseDir, + "expected", + "output.json" + ); + if (fs.existsSync(expectedOutputFile)) { + const expectedFiles = JSON.parse( + fs.readFileSync(expectedOutputFile, { encoding: "utf8" }) + ); + + for (const file of expectedFiles) { + if (!fs.existsSync(path.join(buildDir, file))) { + expect(path.join(buildDir, file)).toBe("debug") + } + expect(fs.existsSync(path.join(buildDir, file))).toBeTruthy(); + } + } + }; + + it("Should show help text", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["build", "--help"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + expect(code).toEqual(0); expect(error).toBe(""); expect(clearStyle(output)).toEqual(HELP); }); - test("Should throw error for invalid params - outputDir", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["build", "--output-dir"], - cwd: getTestCaseDir(0), - cli: polywrapCli, - }, - ); + it("Should throw error for unknown option --invalid", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["build", "--invalid"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe("error: unknown option '--invalid'\n"); + expect(output).toEqual(``); + }); + + describe("missing option arguments", () => { + const missingOptionArgs = { + "--manifest-file": "-m, --manifest-file ", + "--output-dir": "-o, --output-dir ", + "--client-config": "-c, --client-config " + } + + for (const [option, errorMessage] of Object.entries(missingOptionArgs)) { + it(`Should throw error if params not specified for ${option} option`, async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["build", option], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe( + `error: option '${errorMessage}' argument missing\n` + ); + expect(output).toEqual(``); + }); + } + }); + + it("Should throw error if params not specified for --client-config option", async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["build", "--client-config"], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); expect(code).toEqual(1); - expect(error).toContain("error: option '-o, --output-dir ' argument missing"); - expect(output).toBe("") + expect(error).toContain( + "error: option '-c, --client-config ' argument missing" + ); + expect(output).toBe(""); + }); + + it("Should store build files in specified output dir", async () => { + const outputDir = path.resolve( + process.env.TMPDIR || "/tmp", + `codegen-${Date.now()}` + ); + const testCaseDir = getTestCaseDir(0); + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["build", "-v", "--output-dir", outputDir], + cwd: testCaseDir, + cli: polywrapCli, + }); + + const buildDir = `./${path.relative(testCaseDir, outputDir)}`; + + expect(error).toBe(""); + expect(code).toEqual(0); + expect(output).toContain(`Artifacts written to ${buildDir}`); + expect(output).toContain(`Manifest written to ${buildDir}/polywrap.json`); + + testBuildOutput(testCaseDir, outputDir); }); - test("Adds uuid-v4 suffix to build image if no build manifest specified", async () => { + it("Should add uuid-v4 suffix to build image if no build manifest specified", async () => { const projectRoot = getTestCaseDir(0); const project = new PolywrapProject({ rootDir: projectRoot, - polywrapManifestPath: path.join(projectRoot, "polywrap.yaml") + polywrapManifestPath: path.join(projectRoot, "polywrap.yaml"), }); await project.cacheDefaultBuildImage(); - const cacheBuildEnvPath = path.join(projectRoot, ".polywrap/wasm/build/image") + const cacheBuildEnvPath = path.join( + projectRoot, + ".polywrap/wasm/build/image" + ); const cachedBuildManifest = await loadBuildManifest( path.join(cacheBuildEnvPath, "polywrap.build.yaml") ); - const buildImageName = cachedBuildManifest.docker?.name + const buildImageName = cachedBuildManifest.docker?.name; - expect(buildImageName?.length).toBeGreaterThan(36) - expect((buildImageName?.match(/-/g) || []).length).toBeGreaterThanOrEqual(4); + expect(buildImageName?.length).toBeGreaterThan(36); + expect((buildImageName?.match(/-/g) || []).length).toBeGreaterThanOrEqual( + 4 + ); }); describe("test-cases", () => { @@ -85,53 +215,25 @@ describe("e2e tests for build command", () => { const testCaseName = testCases[i]; const testCaseDir = getTestCaseDir(i); - test(testCaseName, async () => { - let { exitCode, stdout, stderr } = await runCLI( - { - args: ["build", "-v"], - cwd: testCaseDir, - cli: polywrapCli, - }, - ); - - stdout = clearStyle(stdout); - stderr = clearStyle(stderr); - - const expected = JSON.parse( - fs.readFileSync( - path.join(testCaseDir, "expected/output.json"), "utf-8" - ) - ); - - if (expected.stdout) { - if (Array.isArray(expected.stdout)) { - for (const line of expected.stdout) { - expect(stdout).toContain(line); - } - } else { - expect(stdout).toContain(expected.stdout); - } + let cmdArgs: string[] = []; + let cmdFile = path.join(testCaseDir, "cmd.json"); + if (fs.existsSync(cmdFile)) { + const cmdConfig = JSON.parse(fs.readFileSync(cmdFile, "utf-8")); + if (cmdConfig.args) { + cmdArgs.push(...cmdConfig.args); } + } - if (expected.stderr) { - if (Array.isArray(expected.stderr)) { - for (const line of expected.stderr) { - expect(stderr).toContain(line); - } - } else { - expect(stderr).toContain(expected.stderr); - } - } - - if (expected.exitCode) { - expect(exitCode).toEqual(expected.exitCode); - } - - if (expected.files) { - for (const file of expected.files) { - expect(fs.existsSync(path.join(testCaseDir, file))).toBeTruthy(); - } - } + test(testCaseName, async () => { + let { exitCode, stdout, stderr } = await runCLI({ + args: ["build", "-v", ...cmdArgs], + cwd: testCaseDir, + cli: polywrapCli, + }); + const buildDir = path.join(testCaseDir, "build"); + + testCliOutput(testCaseDir, exitCode, stdout, stderr); + testBuildOutput(testCaseDir, buildDir); }); } }); diff --git a/packages/cli/src/__tests__/e2e/codegen.spec.ts b/packages/cli/src/__tests__/e2e/codegen.spec.ts index b78634cdae..1f40032eef 100644 --- a/packages/cli/src/__tests__/e2e/codegen.spec.ts +++ b/packages/cli/src/__tests__/e2e/codegen.spec.ts @@ -1,4 +1,3 @@ -import { defaultPolywrapManifest } from "../../lib"; import { clearStyle, polywrapCli } from "./utils"; import { runCLI } from "@polywrap/test-env-js"; @@ -6,23 +5,22 @@ import { GetPathToCliTestFiles } from "@polywrap/test-cases"; import path from "path"; import fs from "fs"; import rimraf from "rimraf"; +import { compareSync } from "dir-compare"; const HELP = `Usage: polywrap codegen|g [options] Auto-generate Wrapper Types Options: - -m, --manifest-file Path to the Polywrap manifest file (default: - ${defaultPolywrapManifest.join(" | ")}) - -c, --codegen-dir Output directory for the generated code - (default: ./wrap) - -s, --script Path to a custom generation script (JavaScript | - TypeScript) - -i, --ipfs [] IPFS node to load external schemas (default: - ipfs.io & localhost) - -e, --ens [
] ENS address to lookup external schemas (default: - 0x0000...2e1e) - -h, --help display help for command + -m, --manifest-file Path to the Polywrap manifest file + (default: polywrap.yaml | polywrap.yml) + -g, --codegen-dir Output directory for the generated code + (default: ./wrap) + -s, --script Path to a custom generation script + (JavaScript | TypeScript) + -c, --client-config Add custom configuration to the + PolywrapClient + -h, --help display help for command `; describe("e2e tests for codegen command", () => { @@ -34,6 +32,64 @@ describe("e2e tests for codegen command", () => { const getTestCaseDir = (index: number) => path.join(testCaseRoot, testCases[index]); + const testCliOutput = ( + testCaseDir: string, + exitCode: number, + stdout: string, + stder: string + ) => { + const output = clearStyle(stdout); + const error = clearStyle(stder); + + const expected = JSON.parse( + fs.readFileSync( + path.join(testCaseDir, "expected", "stdout.json"), + "utf-8" + ) + ); + + if (expected.stdout) { + if (Array.isArray(expected.stdout)) { + for (const line of expected.stdout) { + expect(output).toContain(line); + } + } else { + expect(output).toContain(expected.stdout); + } + } + + if (expected.stderr) { + if (Array.isArray(expected.stderr)) { + for (const line of expected.stderr) { + expect(error).toContain(line); + } + } else { + expect(error).toContain(expected.stderr); + } + } + + if (expected.exitCode) { + expect(exitCode).toEqual(expected.exitCode); + } + + if (expected.files) { + for (const file of expected.files) { + expect(fs.existsSync(path.join(testCaseDir, file))).toBeTruthy(); + } + } + }; + + const testCodegenOutput = (testCaseDir: string, codegenDir: string) => { + if (fs.existsSync(path.join(testCaseDir, "expected", "wrap"))) { + const expectedTypesResult = compareSync( + codegenDir, + path.join(testCaseDir, "expected", "wrap"), + { compareContent: true } + ); + expect(expectedTypesResult.differences).toBe(0); + } + }; + test("Should show help text", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["codegen", "--help"], @@ -46,21 +102,44 @@ describe("e2e tests for codegen command", () => { expect(clearStyle(output)).toEqual(HELP); }); - test("Should throw error for invalid params - ens", async () => { + it("Should throw error for unknown option --invalid", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ - args: ["codegen", "--ens"], + args: ["codegen", "--invalid"], cwd: getTestCaseDir(0), cli: polywrapCli, }); expect(code).toEqual(1); - expect(error).toBe( - "error: option '-e, --ens [
]' argument missing\n" - ); - expect(clearStyle(output)).toEqual(``); + expect(error).toBe("error: unknown option '--invalid'\n"); + expect(output).toEqual(``); + }); + + describe("missing option arguments", () => { + const missingOptionArgs = { + "--manifest-file": "-m, --manifest-file ", + "--codegen-dir": "-g, --codegen-dir ", + "--client-config": "-c, --client-config ", + "--script": "-s, --script ", + }; + + for (const [option, errorMessage] of Object.entries(missingOptionArgs)) { + it(`Should throw error if params not specified for ${option} option`, async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["codegen", option], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe( + `error: option '${errorMessage}' argument missing\n` + ); + expect(output).toEqual(``); + }); + } }); - test("Should throw error for invalid generation file - wrong file", async () => { + it("Should throw error for invalid generation file - wrong file", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["codegen", "--script", `polywrap-invalid.gen.js`], cwd: getTestCaseDir(0), @@ -78,7 +157,7 @@ describe("e2e tests for codegen command", () => { ); }); - test("Should throw error for invalid generation file - no run() method", async () => { + it("Should throw error for invalid generation file - no run() method", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["codegen", "--script", `polywrap-norun.gen.js`], cwd: getTestCaseDir(0), @@ -92,7 +171,26 @@ describe("e2e tests for codegen command", () => { ); }); - test("Should successfully generate types", async () => { + it("Should store build files in specified codegen dir", async () => { + const codegenDir = path.resolve( + process.env.TMPDIR || "/tmp", + `codegen-${Date.now()}` + ); + const testCaseDir = getTestCaseDir(0); + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["codegen", "--codegen-dir", codegenDir], + cwd: testCaseDir, + cli: polywrapCli, + }); + + expect(error).toBe(""); + expect(code).toEqual(0); + expect(clearStyle(output)).toContain( + `🔥 Types were generated successfully 🔥` + ); + }); + + it("Should successfully generate types", async () => { rimraf.sync(`${getTestCaseDir(0)}/types`); const { exitCode: code, stdout: output, stderr: error } = await runCLI({ @@ -109,60 +207,35 @@ describe("e2e tests for codegen command", () => { rimraf.sync(`${getTestCaseDir(0)}/types`); }); + describe("test-cases", () => { for (let i = 0; i < testCases.length; ++i) { const testCaseName = testCases[i]; const testCaseDir = getTestCaseDir(i); - test(testCaseName, async () => { - let cmdArgs = []; - let cmdFile = path.join(testCaseDir, "cmd.json"); - if (fs.existsSync(cmdFile)) { - const cmdConfig = JSON.parse(fs.readFileSync(cmdFile, "utf-8")); - if (cmdConfig.args) { - cmdArgs.push(...cmdConfig.args); - } + let codegenDir = path.join(testCaseDir, "src", "wrap"); + let cmdArgs: string[] = []; + let cmdFile = path.join(testCaseDir, "cmd.json"); + if (fs.existsSync(cmdFile)) { + const cmdConfig = JSON.parse(fs.readFileSync(cmdFile, "utf-8")); + if (cmdConfig.args) { + cmdArgs.push(...cmdConfig.args); } + if(cmdConfig.codegenDir) { + codegenDir = path.join(testCaseDir, cmdConfig.codegenDir); + } + } + + test(testCaseName, async () => { let { exitCode, stdout, stderr } = await runCLI({ args: ["codegen", ...cmdArgs], cwd: testCaseDir, cli: polywrapCli, }); - stdout = clearStyle(stdout); - stderr = clearStyle(stderr); - - const expected = JSON.parse( - fs.readFileSync( - path.join(testCaseDir, "expected/output.json"), - "utf-8" - ) - ); - - if (expected.stdout) { - if (Array.isArray(expected.stdout)) { - for (const line of expected.stdout) { - expect(stdout).toContain(line); - } - } else { - expect(stdout).toContain(expected.stdout); - } - } - - if (expected.stderr) { - if (Array.isArray(expected.stderr)) { - for (const line of expected.stderr) { - expect(stderr).toContain(line); - } - } else { - expect(stderr).toContain(expected.stderr); - } - } - - if (expected.exitCode) { - expect(exitCode).toEqual(expected.exitCode); - } + testCliOutput(testCaseDir, exitCode, stdout, stderr); + testCodegenOutput(testCaseDir, codegenDir); }); } }); diff --git a/packages/cli/src/__tests__/e2e/create.spec.ts b/packages/cli/src/__tests__/e2e/create.spec.ts index eb5bc43b65..411ed29330 100644 --- a/packages/cli/src/__tests__/e2e/create.spec.ts +++ b/packages/cli/src/__tests__/e2e/create.spec.ts @@ -22,7 +22,7 @@ Commands: `; describe("e2e tests for create command", () => { - test("Should show help text", async () => { + it("Should show help text", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", "--help"], cli: polywrapCli, @@ -33,7 +33,7 @@ describe("e2e tests for create command", () => { expect(clearStyle(output)).toEqual(HELP); }); - test("Should show help for no parameters", async () => { + it("Should show help for no parameters", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create"], cli: polywrapCli, @@ -44,7 +44,7 @@ describe("e2e tests for create command", () => { expect(output).toBe(""); }); - test("Should throw error for invalid project type", async () => { + it("Should throw error for invalid project type", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", "unknown", "app", "name"], cli: polywrapCli, @@ -57,7 +57,7 @@ describe("e2e tests for create command", () => { for (const project of Object.keys(supportedLangs)) { describe(project, () => { - test("Should throw error for missing required argument - language", async () => { + it("Should throw error for missing required argument - language", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", project], cli: polywrapCli, @@ -68,7 +68,7 @@ describe("e2e tests for create command", () => { expect(output).toBe(""); }); - test("Should throw error for missing required argument - name", async () => { + it("Should throw error for missing required argument - name", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", project, "lang"], cli: polywrapCli, @@ -79,7 +79,7 @@ describe("e2e tests for create command", () => { expect(output).toBe(""); }); - test("Should throw error for invalid lang parameter", async () => { + it("Should throw error for invalid lang parameter", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", project, "lang", "demo"], cli: polywrapCli, @@ -94,7 +94,7 @@ describe("e2e tests for create command", () => { for (const lang of supportedLangs[project as ProjectType]) { describe(lang, () => { - test("Should throw error for missing path argument for output-dir option", async () => { + it("Should throw error for missing path argument for --output-dir option", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["create", project, lang, "name", "-o"], cli: polywrapCli, @@ -107,7 +107,7 @@ describe("e2e tests for create command", () => { expect(output).toBe(""); }); - test("Should successfully generate project", async () => { + it("Should successfully generate project", async () => { rimraf.sync(`${__dirname}/test`); const { exitCode: code, stdout: output } = await runCLI({ diff --git a/packages/cli/src/__tests__/e2e/deploy.spec.ts b/packages/cli/src/__tests__/e2e/deploy.spec.ts index 86a752935f..1a35a0387a 100644 --- a/packages/cli/src/__tests__/e2e/deploy.spec.ts +++ b/packages/cli/src/__tests__/e2e/deploy.spec.ts @@ -121,7 +121,7 @@ describe("e2e tests for deploy command", () => { await stopTestEnvironment(); }); - test("Should show help text", async () => { + it("Should show help text", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI( { args: ["deploy", "--help"], @@ -135,7 +135,7 @@ describe("e2e tests for deploy command", () => { expect(clearStyle(output)).toEqual(HELP); }); - test("Successfully deploys the project", async () => { + it("Should deploy the project successfully", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI( { args: ["deploy"], @@ -157,7 +157,7 @@ describe("e2e tests for deploy command", () => { ); }); - test("Should show warning if no manifest ext is found in deploy package", async () => { + it("Should show warning if no manifest ext is found in deploy package", async () => { const { exitCode: code, stdout: output } = await runCLI( { args: ["deploy"], @@ -177,7 +177,7 @@ describe("e2e tests for deploy command", () => { ); }); - test("Throws if manifest ext exists and config property is invalid", async () => { + it("Should throw if manifest ext exists and config property is invalid", async () => { const { exitCode: code, stderr } = await runCLI( { args: ["deploy"], @@ -192,7 +192,7 @@ describe("e2e tests for deploy command", () => { expect(sanitizedErr).toContain("domainName is not of a type(s) string") }); - test("Throws and stops chain if error is found", async () => { + it("Should throw and stop chain if error is found", async () => { const { exitCode: code, stdout: output, stderr } = await runCLI( { args: ["deploy"], @@ -217,7 +217,7 @@ describe("e2e tests for deploy command", () => { ); }); - test("Throws if environment variable is not loaded but defined in manifest", async () => { + it("Should throw if environment variable is not loaded but defined in manifest", async () => { const { exitCode: code, stderr } = await runCLI( { args: ["deploy"], diff --git a/packages/cli/src/__tests__/e2e/help.spec.ts b/packages/cli/src/__tests__/e2e/help.spec.ts index 8c9f3797ef..2596ec9927 100644 --- a/packages/cli/src/__tests__/e2e/help.spec.ts +++ b/packages/cli/src/__tests__/e2e/help.spec.ts @@ -22,7 +22,7 @@ Commands: describe("e2e tests for no help", () => { - test("Should display the help content", async () => { + it("Should display the help content", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["help"], cli: polywrapCli, diff --git a/packages/cli/src/__tests__/e2e/infra.spec.ts b/packages/cli/src/__tests__/e2e/infra.spec.ts index 09ab572bc6..93151060a1 100644 --- a/packages/cli/src/__tests__/e2e/infra.spec.ts +++ b/packages/cli/src/__tests__/e2e/infra.spec.ts @@ -126,7 +126,7 @@ describe("e2e tests for infra command", () => { ]); }); - test("Should throw error for no command given", async () => { + it("Should throw error for no command given", async () => { const { exitCode: code, stderr: error } = await runPolywrapCli( ["infra"], getTestCaseDir(0), @@ -136,7 +136,7 @@ describe("e2e tests for infra command", () => { expect(error).toContain(`error: missing required argument 'action'`); }); - test("Should show help text", async () => { + it("Should show help text", async () => { const { exitCode: code, stdout: output, stderr: error } = await runPolywrapCli( ["infra", "--help"], getTestCaseDir(0), @@ -147,7 +147,7 @@ describe("e2e tests for infra command", () => { expect(clearStyle(output)).toEqual(HELP); }); - test("Extracts composed docker manifest's environment variable list", async () => { + it("Should extract composed docker manifest's environment variable list", async () => { const { exitCode: code, stdout: output } = await runPolywrapCli( ["infra", "vars"], getTestCaseDir(0), @@ -161,7 +161,7 @@ describe("e2e tests for infra command", () => { expect(sanitizedOutput).toContain("DEV_SERVER_ETH_TESTNET_PORT"); }); - test("Validates and displays composed docker manifest", async () => { + it("Should validate and display composed docker manifest", async () => { const { exitCode: code, stdout: output } = await runPolywrapCli( ["infra", "config"], getTestCaseDir(0), @@ -175,7 +175,7 @@ describe("e2e tests for infra command", () => { expect(sanitizedOutput).toContain("ipfs:"); }); - test("Sets environment up with all modules if no --modules are passed", async () => { + it("Should set environment up with all modules if no --modules are passed", async () => { await runPolywrapCli( ["infra", "down", "--manifest=./polywrap.infra.yaml"], getTestCaseDir(0), @@ -199,7 +199,7 @@ describe("e2e tests for infra command", () => { ]); }); - test("Should correctly fetch default & local module", async () => { + it("Should correctly fetch default & local module", async () => { await runPolywrapCli( ["infra", "up"], getTestCaseDir(4), @@ -216,7 +216,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Should correctly open one process for default module because modules flag overwrites it", async () => { + it("Should correctly open one process for default module because modules flag overwrites it", async () => { await runPolywrapCli( ["infra", "up", "--modules=eth-ens-ipfs"], getTestCaseDir(4), @@ -232,7 +232,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Should throw because default module declared in manifest is not recognized", async () => { + it("Should throw because default module declared in manifest is not recognized", async () => { const { stderr } = await runPolywrapCli( ["infra", "up", "--manifest=./polywrap.infra.wrong.yaml"], getTestCaseDir(4), @@ -243,7 +243,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Should correctly fetch different local modules when they are declared as folder or file", async () => { + it("Should correctly fetch different local modules when they are declared as folder or file", async () => { await runPolywrapCli( ["infra", "up"], getTestCaseDir(4), @@ -261,7 +261,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Tears down environment", async () => { + it("Should tear down environment", async () => { await runPolywrapCli( ["infra", "up"], getTestCaseDir(0), @@ -285,7 +285,7 @@ describe("e2e tests for infra command", () => { ]); }); - test("Sets environment up with only selected modules", async () => { + it("Should set environment up with only selected modules", async () => { await runPolywrapCli( ["infra", "up", "--modules=ipfs"], getTestCaseDir(0), @@ -307,7 +307,7 @@ describe("e2e tests for infra command", () => { ]); }); - test("Should throw error for --modules that don't exist in infra manifest and are not default modules", async () => { + it("Should throw error for --modules that don't exist in infra manifest and are not default modules", async () => { const { exitCode: code, stderr } = await runPolywrapCli( [ "infra", @@ -323,7 +323,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Should setup and use a default module if --modules arg is passed and the module does not exist in the manifest", async () => { + it("Should setup and use a default module if --modules arg is passed and the module does not exist in the manifest", async () => { await runPolywrapCli( [ "infra", @@ -370,7 +370,7 @@ describe("e2e tests for infra command", () => { expect(withoutManifestModSanitizedOutput).not.toContain("dev-server:") }) - test("Should set up a default environment if no manifest is present, but --modules option is passed", async () => { + it("Should set up a default environment if no manifest is present, but --modules option is passed", async () => { await runPolywrapCli( [ @@ -388,7 +388,7 @@ describe("e2e tests for infra command", () => { ]); }) - test("Should not include default modules if no --modules option is passed and manifest exists", async () => { + it("Should not include default modules if no --modules option is passed and manifest exists", async () => { const { stdout } = await runPolywrapCli( [ @@ -404,7 +404,7 @@ describe("e2e tests for infra command", () => { expect(output).not.toContain("ens-scripts") }) - test("Should fail if no manifest is present and no --modules option is passed", async () => { + it("Should fail if no manifest is present and no --modules option is passed", async () => { const { exitCode, stderr } = await runPolywrapCli( [ @@ -421,7 +421,7 @@ describe("e2e tests for infra command", () => { }); describe("Duplicates", () => { - test("Should handle duplicate services", async () => { + it("Should handle duplicate services", async () => { await runPolywrapCli( [ "infra", @@ -442,7 +442,7 @@ describe("e2e tests for infra command", () => { ); }); - test("Should correctly duplicate pkg in different module", async () => { + it("Should correctly duplicate pkg in different module", async () => { await runPolywrapCli( [ "infra", diff --git a/packages/cli/src/__tests__/e2e/no-command.spec.ts b/packages/cli/src/__tests__/e2e/no-command.spec.ts index 87976e9502..4848d95faf 100644 --- a/packages/cli/src/__tests__/e2e/no-command.spec.ts +++ b/packages/cli/src/__tests__/e2e/no-command.spec.ts @@ -22,7 +22,7 @@ Commands: describe("e2e tests for no command", () => { - test("Should throw error for unrecognized command", async () => { + it("Should throw error for unrecognized command", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: ["unknown"], cli: polywrapCli @@ -32,7 +32,7 @@ describe("e2e tests for no command", () => { expect(output).toEqual(``); }); - test("Should let the user to type polywrap help", async () => { + it("Should let the user to type polywrap help", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI({ args: [], cli: polywrapCli, diff --git a/packages/cli/src/__tests__/e2e/plugin.spec.ts b/packages/cli/src/__tests__/e2e/plugin.spec.ts index c2fd2b8457..b03588c5d0 100644 --- a/packages/cli/src/__tests__/e2e/plugin.spec.ts +++ b/packages/cli/src/__tests__/e2e/plugin.spec.ts @@ -1,4 +1,4 @@ -import { clearStyle } from "./utils"; +import { clearStyle, polywrapCli } from "./utils"; import { runCLI } from "@polywrap/test-env-js"; import { GetPathToCliTestFiles } from "@polywrap/test-cases"; @@ -18,14 +18,6 @@ Commands: help [command] display help for command `; -const CODEGEN_SUCCESS = `- Manifest loaded from ./polywrap.plugin.yaml -✔ Manifest loaded from ./polywrap.plugin.yaml -- Generate types -✔ Generate types -- Manifest written to ./build/polywrap.plugin.json -✔ Manifest written to ./build/polywrap.plugin.json -`; - describe("e2e tests for plugin command", () => { const testCaseRoot = path.join(GetPathToCliTestFiles(), "plugin/codegen"); const testCases = @@ -35,6 +27,73 @@ describe("e2e tests for plugin command", () => { const getTestCaseDir = (index: number) => path.join(testCaseRoot, testCases[index]); + const testCliOutput = ( + testCaseDir: string, + exitCode: number, + stdout: string, + stder: string + ) => { + const output = clearStyle(stdout); + const error = clearStyle(stder); + + const expected = JSON.parse( + fs.readFileSync( + path.join(testCaseDir, "expected", "stdout.json"), + "utf-8" + ) + ); + + if (expected.stdout) { + if (Array.isArray(expected.stdout)) { + for (const line of expected.stdout) { + expect(output).toContain(line); + } + } else { + expect(output).toContain(expected.stdout); + } + } + + if (expected.stderr) { + if (Array.isArray(expected.stderr)) { + for (const line of expected.stderr) { + expect(error).toContain(line); + } + } else { + expect(error).toContain(expected.stderr); + } + } + + if (expected.exitCode) { + expect(exitCode).toEqual(expected.exitCode); + } + + if (expected.files) { + for (const file of expected.files) { + expect(fs.existsSync(path.join(testCaseDir, file))).toBeTruthy(); + } + } + }; + + const testCodegenOutput = (testCaseDir: string, codegenDir: string, buildDir: string) => { + if (fs.existsSync(path.join(testCaseDir, "expected", "wrap"))) { + const expectedCodegenResult = compareSync( + codegenDir, + path.join(testCaseDir, "expected", "wrap"), + { compareContent: true } + ); + expect(expectedCodegenResult.differences).toBe(0); + } + + if (fs.existsSync(path.join(testCaseDir, "expected", "build-artifacts"))) { + const expectedBuildResult = compareSync( + buildDir, + path.join(testCaseDir, "expected", "build-artifacts"), + { compareContent: true } + ); + expect(expectedBuildResult.differences).toBe(0); + } + }; + test("Should show help text", async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI( { @@ -61,43 +120,29 @@ describe("e2e tests for plugin command", () => { expect(output).toBe(""); }); - test("Should throw error for invalid params - publish-dir", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["plugin", "codegen", "--publish-dir"], - cwd: getTestCaseDir(0), - } - ); - - expect(code).toEqual(1); - expect(error).toContain("error: option '-p, --publish-dir ' argument missing"); - expect(output).toBe(""); - }); - - test("Should throw error for invalid params - codegen-dir", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["plugin", "codegen", "--codegen-dir"], - cwd: getTestCaseDir(0), - } - ); - - expect(code).toEqual(1); - expect(error).toContain("error: option '-c, --codegen-dir ' argument missing"); - expect(output).toBe(""); - }); - - test("Should throw error for invalid params - ens", async () => { - const { exitCode: code, stdout: output, stderr: error } = await runCLI( - { - args: ["plugin", "codegen", "--ens"], - cwd: getTestCaseDir(0), - } - ); - - expect(code).toEqual(1); - expect(error).toContain("error: option '-e, --ens [
]' argument missing"); - expect(output).toBe(""); + describe("missing option arguments", () => { + const missingOptionArgs = { + "--manifest-file": "-m, --manifest-file ", + "--publish-dir": "-p, --publish-dir ", + "--codegen-dir": "-g, --codegen-dir ", + "--client-config": "-c, --client-config " + }; + + for (const [option, errorMessage] of Object.entries(missingOptionArgs)) { + it(`Should throw error if params not specified for ${option} option`, async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["plugin", "codegen", option], + cwd: getTestCaseDir(0), + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe( + `error: option '${errorMessage}' argument missing\n` + ); + expect(output).toEqual(``); + }); + } }); describe("test-cases", () => { @@ -105,32 +150,35 @@ describe("e2e tests for plugin command", () => { const testCaseName = testCases[i]; const testCaseDir = getTestCaseDir(i); + let codegenDir = path.join(testCaseDir, "src", "wrap"); + let buildDir = path.join(testCaseDir, "build"); + let cmdArgs: string[] = []; + let cmdFile = path.join(testCaseDir, "cmd.json"); + if (fs.existsSync(cmdFile)) { + const cmdConfig = JSON.parse(fs.readFileSync(cmdFile, "utf-8")); + if (cmdConfig.args) { + cmdArgs.push(...cmdConfig.args); + } + + if(cmdConfig.codegenDir) { + codegenDir = path.join(testCaseDir, cmdConfig.codegenDir); + } + + if(cmdConfig.buildDir) { + buildDir = path.join(testCaseDir, cmdConfig.buildDir); + } + } + test(testCaseName, async () => { const { exitCode: code, stdout: output, stderr: error } = await runCLI( { - args: ["plugin", "codegen"], + args: ["plugin", "codegen", ...cmdArgs], cwd: testCaseDir, } ); - expect(error).toBe(""); - expect(code).toEqual(0); - expect(clearStyle(output)).toEqual(CODEGEN_SUCCESS); - - const expectedTypesResult = compareSync( - `${testCaseDir}/src/wrap`, - `${testCaseDir}/expected/src/wrap`, - { compareContent: true } - ); - expect(expectedTypesResult.differences).toBe(0); - - const expectedBuildResult = compareSync( - `${testCaseDir}/build`, - `${testCaseDir}/expected/build-artifacts`, - { compareContent: true } - ); - - expect(expectedBuildResult.differences).toBe(0); + testCliOutput(testCaseDir, code, output, error); + testCodegenOutput(testCaseDir, codegenDir, buildDir); }); } }); diff --git a/packages/cli/src/__tests__/e2e/run.spec.ts b/packages/cli/src/__tests__/e2e/run.spec.ts index 2be7b972f6..98fe2ef35b 100644 --- a/packages/cli/src/__tests__/e2e/run.spec.ts +++ b/packages/cli/src/__tests__/e2e/run.spec.ts @@ -59,18 +59,29 @@ describe("sanity tests for workflow command", () => { expect(stdout).toEqual(``); }); - it("Should throw error is --client-config doesn't contain arguments", async () => { - const { exitCode, stdout, stderr } = await runCLI({ - args: ["run", "./recipes/e2e.json", "--client-config"], - cwd: testCaseRoot, - cli: polywrapCli, - }); - - expect(exitCode).toEqual(1); - expect(stderr).toBe( - "error: option '-c, --client-config ' argument missing\n" - ); - expect(stdout).toEqual(``); + describe("missing option arguments", () => { + const missingOptionArgs = { + "--validate-script": "-v, --validate-script ", + "--client-config": "-c, --client-config ", + "--output-file": "-o, --output-file ", + "--jobs": "-j, --jobs ", + }; + + for (const [option, errorMessage] of Object.entries(missingOptionArgs)) { + it(`Should throw error if params not specified for ${option} option`, async () => { + const { exitCode: code, stdout: output, stderr: error } = await runCLI({ + args: ["run", option], + cwd: testCaseRoot, + cli: polywrapCli, + }); + + expect(code).toEqual(1); + expect(error).toBe( + `error: option '${errorMessage}' argument missing\n` + ); + expect(output).toEqual(``); + }); + } }); }); @@ -225,9 +236,9 @@ describe("e2e tests for run command", () => { cli: polywrapCli, }); - expect(code).toEqual(0); - expect(stderr).toBe(""); expect(stdout).toBe(""); + expect(stderr).toBe(""); + expect(code).toEqual(0); }, 48000); diff --git a/packages/cli/src/commands/app.ts b/packages/cli/src/commands/app.ts index e58ade9c69..03afaf9d6f 100644 --- a/packages/cli/src/commands/app.ts +++ b/packages/cli/src/commands/app.ts @@ -4,13 +4,12 @@ import { CodeGenerator, SchemaComposer, intlMsg, - getSimpleClient, - getTestEnvProviders, parseAppManifestFileOption, parseAppCodegenDirOption, + parseClientConfigOption, } from "../lib"; -import { PolywrapClient } from "@polywrap/client-js"; +import { PolywrapClient, PolywrapClientConfig } from "@polywrap/client-js"; import * as path from "path"; const defaultOutputTypesDir = "./src/wrap"; @@ -18,8 +17,7 @@ const defaultOutputTypesDir = "./src/wrap"; type AppCommandOptions = { manifestFile: string; codegenDir: string; - ipfs?: string; - ens?: string; + clientConfig: Partial; }; export const app: Command = { @@ -39,18 +37,14 @@ export const app: Command = { }) ) .option( - `-c, --codegen-dir <${intlMsg.commands_codegen_options_o_path()}>`, + `-g, --codegen-dir <${intlMsg.commands_codegen_options_o_path()}>`, `${intlMsg.commands_app_options_codegen({ default: defaultOutputTypesDir, })}` ) .option( - `-i, --ipfs [<${intlMsg.commands_codegen_options_i_node()}>] `, - `${intlMsg.commands_codegen_options_i()}` - ) - .option( - `-e, --ens [<${intlMsg.commands_codegen_options_e_address()}>]`, - `${intlMsg.commands_codegen_options_e()}` + `-c, --client-config <${intlMsg.commands_common_options_configPath()}>`, + `${intlMsg.commands_common_options_config()}` ) .action(async (options) => { await run({ @@ -59,6 +53,10 @@ export const app: Command = { options.manifestFile, undefined ), + clientConfig: await parseClientConfigOption( + options.clientConfig, + undefined + ), codegenDir: parseAppCodegenDirOption(options.codegenDir, undefined), }); }); @@ -66,16 +64,10 @@ export const app: Command = { }; async function run(options: AppCommandOptions) { - const { manifestFile, codegenDir, ipfs, ens } = options; + const { manifestFile, codegenDir, clientConfig } = options; - // Get providers and client - const { ipfsProvider, ethProvider } = await getTestEnvProviders(ipfs); - const ensAddress: string | undefined = ens; - const client: PolywrapClient = getSimpleClient({ - ensAddress, - ethProvider, - ipfsProvider, - }); + // Get client + const client = new PolywrapClient(clientConfig); // App project const project = new AppProject({ diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts index 98bed82949..bade0b53df 100644 --- a/packages/cli/src/commands/build.ts +++ b/packages/cli/src/commands/build.ts @@ -12,11 +12,13 @@ import { FileLock, parseWasmManifestFileOption, parseBuildOutputDirOption, + parseClientConfigOption, } from "../lib"; import { print } from "gluegun"; import path from "path"; import readline from "readline"; +import { PolywrapClient, PolywrapClientConfig } from "@polywrap/client-js"; const defaultManifestStr = defaultPolywrapManifest.join(" | "); const pathStr = intlMsg.commands_build_options_o_path(); @@ -24,6 +26,7 @@ const pathStr = intlMsg.commands_build_options_o_path(); type BuildCommandOptions = { manifestFile: string; outputDir: string; + clientConfig: Partial; watch?: boolean; verbose?: boolean; }; @@ -44,6 +47,10 @@ export const build: Command = { `-o, --output-dir <${pathStr}>`, `${intlMsg.commands_build_options_o()}` ) + .option( + `-c, --client-config <${intlMsg.commands_common_options_configPath()}>`, + `${intlMsg.commands_common_options_config()}` + ) .option(`-w, --watch`, `${intlMsg.commands_build_options_w()}`) .option(`-v, --verbose`, `${intlMsg.commands_build_options_v()}`) .action(async (options) => { @@ -53,6 +60,10 @@ export const build: Command = { options.manifestFile, undefined ), + clientConfig: await parseClientConfigOption( + options.clientConfig, + undefined + ), outputDir: parseBuildOutputDirOption(options.outputDir, undefined), }); }); @@ -60,7 +71,10 @@ export const build: Command = { }; async function run(options: BuildCommandOptions) { - const { watch, verbose, manifestFile, outputDir } = options; + const { watch, verbose, manifestFile, outputDir, clientConfig } = options; + + // Get Client + const client = new PolywrapClient(clientConfig); // Ensure docker is installed if (!isDockerInstalled()) { @@ -82,6 +96,7 @@ async function run(options: BuildCommandOptions) { const schemaComposer = new SchemaComposer({ project, + client, }); const compiler = new Compiler({ diff --git a/packages/cli/src/commands/codegen.ts b/packages/cli/src/commands/codegen.ts index 3f43881d9e..2b061de702 100644 --- a/packages/cli/src/commands/codegen.ts +++ b/packages/cli/src/commands/codegen.ts @@ -6,27 +6,25 @@ import { SchemaComposer, intlMsg, defaultPolywrapManifest, - getTestEnvProviders, parseCodegenDirOption, parseCodegenScriptOption, parseWasmManifestFileOption, + parseClientConfigOption, } from "../lib"; import path from "path"; import { filesystem } from "gluegun"; +import { PolywrapClient, PolywrapClientConfig } from "@polywrap/client-js"; const defaultCodegenDir = "./wrap"; -const nodeStr = intlMsg.commands_codegen_options_i_node(); const pathStr = intlMsg.commands_codegen_options_o_path(); -const addrStr = intlMsg.commands_codegen_options_e_address(); const defaultManifestStr = defaultPolywrapManifest.join(" | "); type CodegenCommandOptions = { manifestFile: string; codegenDir: string; script?: string; - ipfs?: string; - ens?: string; + clientConfig: Partial; }; export const codegen: Command = { @@ -42,7 +40,7 @@ export const codegen: Command = { })}` ) .option( - `-c, --codegen-dir <${pathStr}>`, + `-g, --codegen-dir <${pathStr}>`, ` ${intlMsg.commands_codegen_options_codegen({ default: defaultCodegenDir, })}` @@ -52,16 +50,16 @@ export const codegen: Command = { `${intlMsg.commands_codegen_options_s()}` ) .option( - `-i, --ipfs [<${nodeStr}>]`, - `${intlMsg.commands_codegen_options_i()}` - ) - .option( - `-e, --ens [<${addrStr}>]`, - `${intlMsg.commands_codegen_options_e()}` + `-c, --client-config <${intlMsg.commands_common_options_configPath()}>`, + `${intlMsg.commands_common_options_config()}` ) .action(async (options) => { await run({ ...options, + clientConfig: await parseClientConfigOption( + options.clientConfig, + undefined + ), codegenDir: parseCodegenDirOption(options.codegenDir, undefined), script: parseCodegenScriptOption(options.script, undefined), manifestFile: parseWasmManifestFileOption( @@ -74,9 +72,10 @@ export const codegen: Command = { }; async function run(options: CodegenCommandOptions) { - const { ipfs, ens, manifestFile, codegenDir, script } = options; - const { ipfsProvider, ethProvider } = await getTestEnvProviders(ipfs); - const ensAddress: string | undefined = ens; + const { manifestFile, codegenDir, script, clientConfig } = options; + + // Get Client + const client = new PolywrapClient(clientConfig); // Polywrap Project const project = new PolywrapProject({ @@ -86,9 +85,7 @@ async function run(options: CodegenCommandOptions) { await project.validate(); const schemaComposer = new SchemaComposer({ project, - ipfsProvider, - ethProvider, - ensAddress, + client, }); let result = false; diff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.ts index e72e8771f9..9571bd2e66 100644 --- a/packages/cli/src/commands/plugin.ts +++ b/packages/cli/src/commands/plugin.ts @@ -6,30 +6,28 @@ import { defaultPluginManifest, outputManifest, intlMsg, - getTestEnvProviders, parsePluginCodegenDirOption, parsePluginManifestFileOption, parsePluginPublishDirOption, + parseClientConfigOption, } from "../lib"; import { ComposerFilter } from "@polywrap/schema-compose"; import { writeFileSync } from "@polywrap/os-js"; import path from "path"; import fs from "fs"; +import { PolywrapClient, PolywrapClientConfig } from "@polywrap/client-js"; const defaultPublishDir = "./build"; const defaultCodegenDir = "./wrap"; const pathStr = intlMsg.commands_plugin_options_path(); const defaultManifestStr = defaultPluginManifest.join(" | "); -const nodeStr = intlMsg.commands_plugin_options_i_node(); -const addrStr = intlMsg.commands_plugin_options_e_address(); type PluginCommandOptions = { manifestFile: string; publishDir: string; codegenDir: string; - ipfs?: string; - ens?: string; + clientConfig: Partial; }; export const plugin: Command = { @@ -54,22 +52,22 @@ export const plugin: Command = { })}` ) .option( - `-c, --codegen-dir <${pathStr}>`, + `-g, --codegen-dir <${pathStr}>`, `${intlMsg.commands_plugin_options_codegen({ default: defaultCodegenDir, })}` ) .option( - `-i, --ipfs [<${nodeStr}>]`, - `${intlMsg.commands_plugin_options_i()}` - ) - .option( - `-e, --ens [<${addrStr}>]`, - `${intlMsg.commands_plugin_options_e()}` + `-c, --client-config <${intlMsg.commands_common_options_configPath()}>`, + `${intlMsg.commands_common_options_config()}` ) .action(async (options) => { await run({ ...options, + clientConfig: await parseClientConfigOption( + options.clientConfig, + undefined + ), manifestFile: parsePluginManifestFileOption( options.manifestFile, undefined @@ -87,10 +85,10 @@ export const plugin: Command = { }, }; async function run(options: PluginCommandOptions) { - const { ipfs, ens, manifestFile, codegenDir, publishDir } = options; + const { manifestFile, codegenDir, publishDir, clientConfig } = options; - const { ipfsProvider, ethProvider } = await getTestEnvProviders(ipfs); - const ensAddress: string | undefined = ens; + // Get Client + const client = new PolywrapClient(clientConfig); // Plugin project const project = new PluginProject({ @@ -102,9 +100,7 @@ async function run(options: PluginCommandOptions) { const schemaComposer = new SchemaComposer({ project, - ipfsProvider, - ethProvider, - ensAddress, + client, }); let result = false; diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts index 66ba2f72a4..1abd593336 100644 --- a/packages/cli/src/commands/run.ts +++ b/packages/cli/src/commands/run.ts @@ -7,7 +7,7 @@ import { validateOutput, } from "../lib"; -import { InvokeResult, Workflow } from "@polywrap/core-js"; +import { InvokeResult, Workflow, JobResult } from "@polywrap/core-js"; import { PolywrapClient, PolywrapClientConfig } from "@polywrap/client-js"; import path from "path"; import yaml from "js-yaml"; @@ -32,8 +32,8 @@ export const run: Command = { intlMsg.commands_run_options_workflowScript() ) .option( - `-c, --client-config <${intlMsg.commands_run_options_configPath()}> `, - `${intlMsg.commands_run_options_config()}` + `-c, --client-config <${intlMsg.commands_common_options_configPath()}>`, + `${intlMsg.commands_common_options_config()}` ) .option( `-v, --validate-script <${intlMsg.commands_run_options_validate()}>`, @@ -85,7 +85,9 @@ const _run = async (workflowPath: string, options: WorkflowCommandOptions) => { workflow, config: clientConfig, ids: jobs, - onExecution: async (id: string, data: unknown, error: Error) => { + onExecution: async (id: string, jobResult: JobResult) => { + const { data, error } = jobResult; + if (!quiet) { console.log("-----------------------------------"); console.log(`ID: ${id}`); diff --git a/packages/cli/src/lib/CodeGenerator.ts b/packages/cli/src/lib/CodeGenerator.ts index 8c80bee808..977641eee6 100644 --- a/packages/cli/src/lib/CodeGenerator.ts +++ b/packages/cli/src/lib/CodeGenerator.ts @@ -87,11 +87,11 @@ export class CodeGenerator { throw Error(intlMsg.lib_codeGenerator_noComposedSchema()); } - const typeInfo = composed.typeInfo; + const abi = composed.abi; this._schema = composed.schema; - if (!typeInfo) { - throw Error(intlMsg.lib_codeGenerator_typeInfoMissing()); + if (!abi) { + throw Error(intlMsg.lib_codeGenerator_abiMissing()); } if (this._config.customScript) { @@ -117,7 +117,7 @@ export class CodeGenerator { const binding = await generateBinding({ projectName: await project.getName(), - typeInfo, + abi, schema: this._schema || "", outputDirAbs: codegenDirAbs, bindLanguage, @@ -128,7 +128,7 @@ export class CodeGenerator { codegenDirAbs, binding.output, (templatePath: string) => - this._generateTemplate(templatePath, typeInfo, spinner) + this._generateTemplate(templatePath, abi, spinner) ); } else { const binding = await project.generateSchemaBindings( diff --git a/packages/cli/src/lib/SchemaComposer.ts b/packages/cli/src/lib/SchemaComposer.ts index e5026d08ce..946825019e 100644 --- a/packages/cli/src/lib/SchemaComposer.ts +++ b/packages/cli/src/lib/SchemaComposer.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/no-empty-function */ -import { Project, AnyManifest, getSimpleClient } from "./"; +import { Project, AnyManifest } from "./"; import { Uri, PolywrapClient } from "@polywrap/client-js"; import { @@ -17,13 +17,7 @@ import * as gluegun from "gluegun"; export interface SchemaComposerConfig { project: Project; - - // TODO: add this to the project configuration - // and make it configurable - ensAddress?: string; - ethProvider?: string; - ipfsProvider?: string; - client?: PolywrapClient; + client: PolywrapClient; } export class SchemaComposer { @@ -31,7 +25,7 @@ export class SchemaComposer { private _composerOutput: ComposerOutput | undefined; constructor(private _config: SchemaComposerConfig) { - this._client = this._config.client ?? getSimpleClient(this._config); + this._client = this._config.client; } public async getComposedSchemas( diff --git a/packages/cli/src/lib/defaults/build-images/wasm/rust/Dockerfile.mustache b/packages/cli/src/lib/defaults/build-images/wasm/rust/Dockerfile.mustache index c44b90e96f..5efaee0309 100644 --- a/packages/cli/src/lib/defaults/build-images/wasm/rust/Dockerfile.mustache +++ b/packages/cli/src/lib/defaults/build-images/wasm/rust/Dockerfile.mustache @@ -1,4 +1,4 @@ -FROM rustlang/rust:nightly-slim as base +FROM rust:1.60.0 as base # Install the wasm32 rust build target RUN rustup target add wasm32-unknown-unknown @@ -7,7 +7,7 @@ WORKDIR /build-deps # Install curl RUN apt-get update -RUN apt-get -y install curl +RUN apt-get -y install curl clang llvm build-essential # Install wasm-opt RUN curl -L https://github.com/WebAssembly/binaryen/releases/download/version_101/binaryen-version_101-x86_64-linux.tar.gz | tar -xz \ @@ -16,10 +16,13 @@ RUN curl -L https://github.com/WebAssembly/binaryen/releases/download/version_10 && rm -rf binary-version_101 # Install the toml-cli -RUN cargo install toml-cli +RUN cargo install -f toml-cli # Install wasm-snip -RUN cargo install wasm-snip +RUN cargo install -f wasm-snip + +# Install wasm-bindgen +RUN cargo install -f wasm-bindgen-cli {{#polywrap_linked_packages.length}} WORKDIR /linked-packages @@ -55,44 +58,50 @@ RUN PACKAGE_NAME={{name}}; \ {{/polywrap_module}} true {{/polywrap_linked_packages}} + {{/polywrap_linked_packages.length}} -# Remove any Cargo.lock files {{#polywrap_module}} +# Remove any Cargo.lock files RUN rm -rf {{dir}}/Cargo.lock # Ensure the Wasm module is configured to use imported memory ENV RUSTFLAGS="-C link-arg=-z -C link-arg=stack-size=65536 -C link-arg=--import-memory" -# Enable the wrap-invoke feature for the {{dir}} module -RUN toml set ./{{dir}}/Cargo.toml features.wrap-invoke [] > ./{{dir}}/Cargo-local.toml && \ +# Ensure the module at {{dir}} has the crate-type = ["cdylib"] +RUN toml set ./{{dir}}/Cargo.toml lib.crate-type ["cdylib"] > ./{{dir}}/Cargo-local.toml && \ rm -rf ./{{dir}}/Cargo.toml && \ mv ./{{dir}}/Cargo-local.toml ./{{dir}}/Cargo.toml && \ true -# Cleanup an artifact left by the toml CLI program ("[]" -> []) -RUN sed -i 's/"\[\]"/\[\]/g' ./{{dir}}/Cargo.toml +# Clean up artifacts left by the toml CLI program ("["cdylib"]" -> ["cdylib"]) +RUN sed -i 's/"\[cdylib\]"/\["cdylib"\]/g' ./{{dir}}/Cargo.toml -# Ensure the module at {{dir}} has the crate-type = ["cdylib"] -RUN toml set ./{{dir}}/Cargo.toml lib.crate-type ["cdylib","rlib"] > ./{{dir}}/Cargo-local.toml && \ +# Ensure the package name = "module" +RUN toml set ./{{dir}}/Cargo.toml package.name "module" > ./{{dir}}/Cargo-local.toml && \ rm -rf ./{{dir}}/Cargo.toml && \ mv ./{{dir}}/Cargo-local.toml ./{{dir}}/Cargo.toml && \ true -# Clean up artifacts left by the toml CLI program ("["cdylib", "rlib"]" -> ["cdylib", "rlib"]) -RUN sed -i 's/"\[cdylib,rlib\]"/\["cdylib","rlib"\]/g' ./{{dir}}/Cargo.toml - -# Build the module at {{dir}} -RUN cargo +nightly build --manifest-path ./{{dir}}/Cargo.toml \ - --target wasm32-unknown-unknown --release --features "wrap-invoke" - # Make the build directory RUN rm -rf ./build RUN mkdir ./build +# Build the module at {{dir}} +RUN cargo build --manifest-path ./{{dir}}/Cargo.toml \ + --target wasm32-unknown-unknown --release + +# Enable the "WASM_INTERFACE_TYPES" feature, which will remove the __wbindgen_throw import. +# See: https://github.com/rustwasm/wasm-bindgen/blob/7f4663b70bd492278bf0e7bba4eeddb3d840c868/crates/cli-support/src/lib.rs#L397-L403 +ENV WASM_INTERFACE_TYPES=1 + +# Run wasm-bindgen over the module, replacing all placeholder __wbindgen_... imports +RUN wasm-bindgen ./{{dir}}/target/wasm32-unknown-unknown/release/module.wasm --out-dir ./build --out-name bg_module.wasm + +RUN wasm-snip ./build/bg_module.wasm -o ./build/snipped_module.wasm && \ + rm -rf ./build/bg_module.wasm + # Use wasm-opt to perform the "asyncify" post-processing step over all modules -RUN WASM_MODULE=$(ls ./{{dir}}/target/wasm32-unknown-unknown/release/*.wasm); \ - wasm-snip $WASM_MODULE -o ./build/snipped_{{name}}.wasm && \ - wasm-opt --asyncify -Os ./build/snipped_{{name}}.wasm -o ./build/{{name}}.wasm && \ - rm -rf ./build/snipped_{{name}}.wasm +RUN wasm-opt --asyncify -Os ./build/snipped_module.wasm -o ./build/module.wasm && \ + rm -rf ./build/snipped_module.wasm {{/polywrap_module}} diff --git a/packages/cli/src/lib/helpers/workflow-validator.ts b/packages/cli/src/lib/helpers/workflow-validator.ts index c28b3cdcef..d4fada6c07 100644 --- a/packages/cli/src/lib/helpers/workflow-validator.ts +++ b/packages/cli/src/lib/helpers/workflow-validator.ts @@ -1,4 +1,5 @@ import { runCommand } from "../system"; +import { intlMsg } from "../intl"; import fs from "fs"; import { InvokeResult } from "@polywrap/core-js"; @@ -19,6 +20,10 @@ export async function validateOutput( result: InvokeResult, validateScriptPath: string ): Promise { + if (!(await cueExists())) { + console.warn(intlMsg.commands_run_error_cueDoesNotExist()); + } + const index = id.lastIndexOf("."); const jobId = id.substring(0, index); const stepId = id.substring(index + 1); @@ -29,11 +34,17 @@ export async function validateOutput( await fs.promises.writeFile(jsonOutput, JSON.stringify(result, null, 2)); try { - await runCommand( - `cue vet -d ${selector} ${validateScriptPath} ${jsonOutput}` + const { stderr } = await runCommand( + `cue vet -d ${selector} ${validateScriptPath} ${jsonOutput}`, + true ); + + if (stderr) { + console.error(stderr); + console.log("-----------------------------------"); + } } catch (e) { - console.error(e.message); + console.error(e); console.log("-----------------------------------"); process.exitCode = 1; } diff --git a/packages/cli/src/lib/option-parsers/common.ts b/packages/cli/src/lib/option-parsers/common.ts new file mode 100644 index 0000000000..0ebb7f52a6 --- /dev/null +++ b/packages/cli/src/lib/option-parsers/common.ts @@ -0,0 +1,67 @@ +import { validateClientConfig } from "../helpers"; +import { intlMsg } from "../intl"; +import { importTypescriptModule } from "../system"; +import { getTestEnvClientConfig } from "../test-env"; + +import { executeMaybeAsyncFunction } from "@polywrap/core-js"; +import { PolywrapClientConfig } from "@polywrap/client-js"; +import path from "path"; + +export async function parseClientConfigOption( + _clientConfig: string | undefined, + _: unknown +): Promise> { + let finalClientConfig: Partial; + + try { + finalClientConfig = await getTestEnvClientConfig(); + } catch (e) { + console.error(intlMsg.commands_run_error_noTestEnvFound()); + process.exit(1); + } + + if (_clientConfig) { + let configModule; + + const configPath = path.resolve(_clientConfig); + if (configPath.endsWith(".js")) { + configModule = await import(path.resolve(configPath)); + } else if (configPath.endsWith(".ts")) { + configModule = await importTypescriptModule(path.resolve(configPath)); + } else { + const configsModuleMissingExportMessage = intlMsg.commands_run_error_clientConfigInvalidFileExt( + { module: configPath } + ); + console.error(configsModuleMissingExportMessage); + process.exit(1); + } + + if (!configModule || !configModule.getClientConfig) { + const configsModuleMissingExportMessage = intlMsg.commands_run_error_clientConfigModuleMissingExport( + { module: configModule } + ); + console.error(configsModuleMissingExportMessage); + process.exit(1); + } + + finalClientConfig = await executeMaybeAsyncFunction( + configModule.getClientConfig, + finalClientConfig + ); + + try { + validateClientConfig(finalClientConfig); + } catch (e) { + console.error(e.message); + process.exit(1); + } + } + + return finalClientConfig; +} + +export async function defaultClientConfigOption(): Promise< + Partial +> { + return await parseClientConfigOption(undefined, undefined); +} diff --git a/packages/cli/src/lib/option-parsers/index.ts b/packages/cli/src/lib/option-parsers/index.ts index f954637a56..d6c5858188 100644 --- a/packages/cli/src/lib/option-parsers/index.ts +++ b/packages/cli/src/lib/option-parsers/index.ts @@ -4,3 +4,4 @@ export * from "./codegen"; export * from "./wasm"; export * from "./plugin"; export * from "./run"; +export * from "./common"; diff --git a/packages/cli/src/lib/option-parsers/run.ts b/packages/cli/src/lib/option-parsers/run.ts index 873e8e5c92..699a840f64 100644 --- a/packages/cli/src/lib/option-parsers/run.ts +++ b/packages/cli/src/lib/option-parsers/run.ts @@ -1,12 +1,7 @@ import { intlMsg } from "../intl"; -import { importTypescriptModule } from "../system"; -import { getTestEnvClientConfig } from "../test-env"; -import { validateClientConfig } from "../helpers"; import path from "path"; import fs from "fs"; -import { PolywrapClientConfig } from "@polywrap/client-js"; -import { executeMaybeAsyncFunction } from "@polywrap/core-js"; export function parseWorkflowScriptPathOption( script: string, @@ -21,65 +16,6 @@ export function parseWorkflowScriptPathOption( return absPath; } -export async function parseClientConfigOption( - _clientConfig: string | undefined, - _: unknown -): Promise> { - let finalClientConfig: Partial; - - try { - finalClientConfig = await getTestEnvClientConfig(); - } catch (e) { - console.error(intlMsg.commands_run_error_noTestEnvFound()); - process.exit(1); - } - - if (_clientConfig) { - let configModule; - - const configPath = path.resolve(_clientConfig); - if (configPath.endsWith(".js")) { - configModule = await import(path.resolve(configPath)); - } else if (configPath.endsWith(".ts")) { - configModule = await importTypescriptModule(path.resolve(configPath)); - } else { - const configsModuleMissingExportMessage = intlMsg.commands_run_error_clientConfigInvalidFileExt( - { module: configPath } - ); - console.error(configsModuleMissingExportMessage); - process.exit(1); - } - - if (!configModule || !configModule.getClientConfig) { - const configsModuleMissingExportMessage = intlMsg.commands_run_error_clientConfigModuleMissingExport( - { module: configModule } - ); - console.error(configsModuleMissingExportMessage); - process.exit(1); - } - - finalClientConfig = await executeMaybeAsyncFunction( - configModule.getClientConfig, - finalClientConfig - ); - - try { - validateClientConfig(finalClientConfig); - } catch (e) { - console.error(e.message); - process.exit(1); - } - } - - return finalClientConfig; -} - -export async function defaultClientConfigOption(): Promise< - Partial -> { - return await parseClientConfigOption(undefined, undefined); -} - export function parseWorkflowOutputFilePathOption( outputFile: string, _: unknown diff --git a/packages/cli/src/lib/project/AppProject.ts b/packages/cli/src/lib/project/AppProject.ts index bf13baa276..c340378bfb 100644 --- a/packages/cli/src/lib/project/AppProject.ts +++ b/packages/cli/src/lib/project/AppProject.ts @@ -10,7 +10,7 @@ import { import { AppManifest, Client } from "@polywrap/core-js"; import { ComposerOutput } from "@polywrap/schema-compose"; import { bindSchema, BindOutput } from "@polywrap/schema-bind"; -import { TypeInfo } from "@polywrap/schema-parse"; +import { Abi } from "@polywrap/schema-parse"; import path from "path"; export interface AppProjectConfig extends ProjectConfig { @@ -110,7 +110,7 @@ export class AppProject extends Project { ): Promise { return bindSchema({ projectName: await this.getName(), - typeInfo: composerOutput.typeInfo as TypeInfo, + abi: composerOutput.abi as Abi, schema: composerOutput.schema as string, outputDirAbs: this._getGenerationDirectory(generationSubPath), bindLanguage: appManifestLanguageToBindLanguage( diff --git a/packages/cli/src/lib/project/PluginProject.ts b/packages/cli/src/lib/project/PluginProject.ts index 6321a02ba7..173c476856 100644 --- a/packages/cli/src/lib/project/PluginProject.ts +++ b/packages/cli/src/lib/project/PluginProject.ts @@ -11,7 +11,7 @@ import { import { PluginManifest } from "@polywrap/core-js"; import { bindSchema, BindOutput, BindOptions } from "@polywrap/schema-bind"; import { ComposerOutput } from "@polywrap/schema-compose"; -import { TypeInfo } from "@polywrap/schema-parse"; +import { Abi } from "@polywrap/schema-parse"; import path from "path"; export interface PluginProjectConfig extends ProjectConfig { @@ -124,7 +124,7 @@ export class PluginProject extends Project { const options: BindOptions = { projectName: manifest.name, - typeInfo: composerOutput.typeInfo as TypeInfo, + abi: composerOutput.abi as Abi, schema: composerOutput.schema as string, outputDirAbs: moduleDirectory, bindLanguage, diff --git a/packages/cli/src/lib/project/PolywrapProject.ts b/packages/cli/src/lib/project/PolywrapProject.ts index 05d90c9459..58ab71858d 100644 --- a/packages/cli/src/lib/project/PolywrapProject.ts +++ b/packages/cli/src/lib/project/PolywrapProject.ts @@ -29,7 +29,7 @@ import { import { normalizePath } from "@polywrap/os-js"; import { bindSchema, BindOutput, BindOptions } from "@polywrap/schema-bind"; import { ComposerOutput } from "@polywrap/schema-compose"; -import { TypeInfo } from "@polywrap/schema-parse"; +import { Abi } from "@polywrap/schema-parse"; import regexParser from "regex-parser"; import path from "path"; import { Schema as JsonSchema } from "jsonschema"; @@ -168,7 +168,7 @@ export class PolywrapProject extends Project { const options: BindOptions = { projectName: manifest.name, - typeInfo: composerOutput.typeInfo as TypeInfo, + abi: composerOutput.abi as Abi, schema: composerOutput.schema as string, outputDirAbs: moduleDirectory, bindLanguage, diff --git a/packages/core-interfaces/logger/package.json b/packages/core-interfaces/logger/package.json index feb30d5f15..b36462b07b 100644 --- a/packages/core-interfaces/logger/package.json +++ b/packages/core-interfaces/logger/package.json @@ -1,5 +1,5 @@ { - "name": "logger-interface", + "name": "@polywrap/logger-interface", "description": "Polywrap Logger Interface", "private": true, "version": "0.0.1-prealpha.90", diff --git a/packages/core-interfaces/uri-resolver/package.json b/packages/core-interfaces/uri-resolver/package.json index 5bbc94a572..a896c3f3c8 100644 --- a/packages/core-interfaces/uri-resolver/package.json +++ b/packages/core-interfaces/uri-resolver/package.json @@ -1,5 +1,5 @@ { - "name": "uri-resolver-interface", + "name": "@polywrap/uri-resolver-interface", "description": "URI Resolver Interface", "private": true, "version": "0.0.1-prealpha.90", diff --git a/packages/js/asyncify/src/AsyncWasmInstance.ts b/packages/js/asyncify/src/AsyncWasmInstance.ts index 7ca2f7a2d1..f43845cf93 100644 --- a/packages/js/asyncify/src/AsyncWasmInstance.ts +++ b/packages/js/asyncify/src/AsyncWasmInstance.ts @@ -44,9 +44,7 @@ export class AsyncWasmInstance { private constructor() {} - public static createMemory(config: { module: ArrayBuffer }): WasmMemory { - const bytecode = new Uint8Array(config.module); - + public static createMemory(config: { module: Uint8Array }): WasmMemory { // extract the initial memory page size, as it will // throw an error if the imported page size differs: // https://chromium.googlesource.com/v8/v8/+/644556e6ed0e6e4fac2dfabb441439820ec59813/src/wasm/module-instantiate.cc#924 @@ -73,7 +71,7 @@ export class AsyncWasmInstance { // 0x__, ]); - const sigIdx = indexOfArray(bytecode, envMemoryImportSignature); + const sigIdx = indexOfArray(config.module, envMemoryImportSignature); if (sigIdx < 0) { throw Error( @@ -86,7 +84,7 @@ export class AsyncWasmInstance { // Extract the initial memory page-range size const memoryInitalLimits = - bytecode[sigIdx + envMemoryImportSignature.length + 1]; + config.module[sigIdx + envMemoryImportSignature.length + 1]; if (memoryInitalLimits === undefined) { throw Error( @@ -98,7 +96,7 @@ export class AsyncWasmInstance { } public static async createInstance(config: { - module: ArrayBuffer; + module: Uint8Array; imports: WasmImports; requiredExports?: readonly string[]; }): Promise { diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 013c957e44..96db5439e1 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -18,6 +18,7 @@ import { InterfaceImplementations, InvokeOptions, InvokeResult, + InvokerOptions, PluginRegistration, QueryOptions, QueryResult, @@ -47,6 +48,8 @@ import { JobRunner, PluginPackage, RunOptions, + msgpackEncode, + msgpackDecode, } from "@polywrap/core-js"; import { Tracer } from "@polywrap/tracing-js"; @@ -197,7 +200,7 @@ export class PolywrapClient implements Client { public async getFile( uri: TUri, options: GetFileOptions - ): Promise { + ): Promise { const wrapper = await this._loadWrapper(this._toUri(uri), options); const client = contextualizeClient(this, options.contextId); return await wrapper.getFile(options, client); @@ -309,14 +312,14 @@ export class PolywrapClient implements Client { @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( - options: InvokeOptions + options: InvokerOptions ): Promise> { const { contextId, shouldClearContext } = this._setContext( options.contextId, options.config ); - let result: InvokeResult; + let error: Error | undefined; try { const typedOptions: InvokeOptions = { @@ -327,18 +330,39 @@ export class PolywrapClient implements Client { const wrapper = await this._loadWrapper(typedOptions.uri, { contextId }); - result = (await wrapper.invoke( + const invocableResult = await wrapper.invoke( typedOptions, contextualizeClient(this, contextId) - )) as TData; - } catch (error) { - result = { error }; + ); + + if (invocableResult.data !== undefined) { + if (options.encodeResult && !invocableResult.encoded) { + return { + // TODO: if options.encodeResult, fix return type to Uint8Array + data: (msgpackEncode(invocableResult.data) as unknown) as TData, + }; + } else if (invocableResult.encoded && !options.encodeResult) { + return { + // TODO: if result.encoded, fix return type to Uint8Array + data: msgpackDecode(invocableResult.data as Uint8Array) as TData, + }; + } else { + return { + data: invocableResult.data as TData, + }; + } + } else { + error = invocableResult.error; + } + } catch (e) { + error = e; } if (shouldClearContext) { this._clearContext(contextId); } - return result; + + return { error }; } @Tracer.traceMethod("PolywrapClient: run") diff --git a/packages/js/client/src/__tests__/core/interface-impls.spec.ts b/packages/js/client/src/__tests__/core/interface-impls.spec.ts index 266ef84d6c..732026e0f2 100644 --- a/packages/js/client/src/__tests__/core/interface-impls.spec.ts +++ b/packages/js/client/src/__tests__/core/interface-impls.spec.ts @@ -83,7 +83,7 @@ describe("interface-impls", () => { { uri: implementation4Uri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [], @@ -145,7 +145,7 @@ describe("interface-impls", () => { { uri: interface1Uri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [], @@ -155,7 +155,7 @@ describe("interface-impls", () => { { uri: interface2Uri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [], @@ -197,7 +197,7 @@ describe("interface-impls", () => { { uri: interfaceUri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [], @@ -295,7 +295,7 @@ describe("interface-impls", () => { { uri: implementation1Uri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [new Uri(interfaceUri)], @@ -330,7 +330,7 @@ describe("interface-impls", () => { { uri: implementation1Uri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [], diff --git a/packages/js/client/src/__tests__/core/resolveUri.spec.ts b/packages/js/client/src/__tests__/core/resolveUri.spec.ts index 7e7209394e..e4635a2587 100644 --- a/packages/js/client/src/__tests__/core/resolveUri.spec.ts +++ b/packages/js/client/src/__tests__/core/resolveUri.spec.ts @@ -190,7 +190,7 @@ describe("resolveUri", () => { uri: pluginUri.uri, plugin: { factory: () => { - return ({} as unknown) as PluginModule; + return ({} as unknown) as PluginModule<{}>; }, manifest: { schema: "", diff --git a/packages/js/client/src/__tests__/core/sanity.spec.ts b/packages/js/client/src/__tests__/core/sanity.spec.ts index 78ea0cf9b7..a3205afebd 100644 --- a/packages/js/client/src/__tests__/core/sanity.spec.ts +++ b/packages/js/client/src/__tests__/core/sanity.spec.ts @@ -90,7 +90,7 @@ describe("sanity", () => { { uri: implementationUri, plugin: { - factory: () => ({} as PluginModule), + factory: () => ({} as PluginModule<{}>), manifest: { schema: schemaStr, implements: [], diff --git a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts index f58ce78a34..6ea30b2d41 100644 --- a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts +++ b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts @@ -113,13 +113,13 @@ describe("wasm-wrapper", () => { networkNameOrChainId: "testnet", }, }, - noDecode: true, + encodeResult: true, }); expect(result.error).toBeFalsy(); expect(result.data).toBeTruthy(); - expect(result.data instanceof ArrayBuffer).toBeTruthy(); - expect(msgpackDecode(result.data as ArrayBuffer)).toContain("0x"); + expect(result.data instanceof Uint8Array).toBeTruthy(); + expect(msgpackDecode(result.data as Uint8Array)).toContain("0x"); }); it("should invoke wrapper with custom redirects", async () => { @@ -291,9 +291,9 @@ describe("wasm-wrapper", () => { ): Int! `); - const fileBuffer: ArrayBuffer = (await client.getFile(wrapperUri, { + const fileBuffer: Uint8Array = (await client.getFile(wrapperUri, { path: manifest.schema!, - })) as ArrayBuffer; + })) as Uint8Array; const decoder = new TextDecoder("utf8"); const text = decoder.decode(fileBuffer); expect(text).toContain(`getData( diff --git a/packages/js/client/src/__tests__/e2e/workflow.spec.ts b/packages/js/client/src/__tests__/e2e/workflow.spec.ts index b6f8745424..a8f557b98d 100644 --- a/packages/js/client/src/__tests__/e2e/workflow.spec.ts +++ b/packages/js/client/src/__tests__/e2e/workflow.spec.ts @@ -6,7 +6,7 @@ import { ensAddresses, providers } from "@polywrap/test-env-js"; -import { createPolywrapClient, PolywrapClient, PolywrapClientConfig } from "../.."; +import { createPolywrapClient, JobResult, PolywrapClient, PolywrapClientConfig } from "../.."; import { outPropWorkflow, sanityWorkflow } from "./workflow-test-cases"; jest.setTimeout(200000); @@ -89,8 +89,8 @@ describe("workflow", () => { test("sanity workflow", async () => { await client.run({ workflow: sanityWorkflow, - onExecution: async (id: string, data: unknown, error: unknown) => { - await tests[id](data, error); + onExecution: async (id: string, jobResult: JobResult) => { + await tests[id](jobResult.data, jobResult.error); }, }); }); @@ -98,8 +98,8 @@ describe("workflow", () => { test("workflow with output propagation", async () => { await client.run({ workflow: outPropWorkflow, - onExecution: async (id: string, data: unknown, error: unknown) => { - await tests[id](data, error); + onExecution: async (id: string, jobResult: JobResult) => { + await tests[id](jobResult.data, jobResult.error); }, }); }); diff --git a/packages/js/client/src/plugin/PluginWrapper.ts b/packages/js/client/src/plugin/PluginWrapper.ts index 38c44e3b53..79116087a5 100644 --- a/packages/js/client/src/plugin/PluginWrapper.ts +++ b/packages/js/client/src/plugin/PluginWrapper.ts @@ -3,7 +3,7 @@ import { Client, GetManifestOptions, InvokeOptions, - InvokeResult, + InvocableResult, PluginModule, PluginPackage, Uri, @@ -11,8 +11,8 @@ import { ManifestArtifactType, GetFileOptions, Env, - msgpackEncode, msgpackDecode, + isBuffer, } from "@polywrap/core-js"; import { Tracer } from "@polywrap/tracing-js"; @@ -51,15 +51,15 @@ export class PluginWrapper extends Wrapper { public async getFile( _options: GetFileOptions, _client: Client - ): Promise { + ): Promise { throw Error("client.getFile(...) is not implemented for Plugins."); } @Tracer.traceMethod("PluginWrapper: invoke") - public async invoke( + public async invoke( options: InvokeOptions, client: Client - ): Promise> { + ): Promise> { try { const { method } = options; const args = options.args || {}; @@ -79,7 +79,7 @@ export class PluginWrapper extends Wrapper { let jsArgs: Record; // If the args are a msgpack buffer, deserialize it - if (args instanceof ArrayBuffer) { + if (isBuffer(args)) { const result = msgpackDecode(args); Tracer.addEvent("msgpack-decoded", result); @@ -97,36 +97,16 @@ export class PluginWrapper extends Wrapper { // Invoke the function try { - const result = (await module._wrap_invoke( - method, - jsArgs, - client - )) as TData; + const result = await module._wrap_invoke(method, jsArgs, client); if (result !== undefined) { const data = result as unknown; - if (process.env.TEST_PLUGIN) { - // try to encode the returned result, - // ensuring it's msgpack compliant - try { - msgpackEncode(data); - } catch (e) { - throw Error( - `TEST_PLUGIN msgpack encode failure.` + - `uri: ${this._uri.uri}\nmodule: ${module}\n` + - `method: ${method}\n` + - `args: ${JSON.stringify(jsArgs, null, 2)}\n` + - `result: ${JSON.stringify(data, null, 2)}\n` + - `exception: ${e}` - ); - } - } - Tracer.addEvent("Result", data); return { - data: data as TData, + data: data, + encoded: false, }; } else { return {}; diff --git a/packages/js/client/src/wasm/WasmWrapper.ts b/packages/js/client/src/wasm/WasmWrapper.ts index 56e82b8d80..29e43bb189 100644 --- a/packages/js/client/src/wasm/WasmWrapper.ts +++ b/packages/js/client/src/wasm/WasmWrapper.ts @@ -5,6 +5,7 @@ import { createImports } from "./imports"; import { InvokeOptions, InvokeResult, + InvocableResult, Wrapper, PolywrapManifest, Uri, @@ -20,13 +21,13 @@ import { UriResolverInterface, GetFileOptions, msgpackEncode, - msgpackDecode, + isBuffer, } from "@polywrap/core-js"; import { Tracer } from "@polywrap/tracing-js"; import { AsyncWasmInstance } from "@polywrap/asyncify-js"; type InvokeResultOrError = - | { type: "InvokeResult"; invokeResult: ArrayBuffer } + | { type: "InvokeResult"; invokeResult: Uint8Array } | { type: "InvokeError"; invokeError: string }; const hasExport = (name: string, exports: Record): boolean => { @@ -39,36 +40,36 @@ const hasExport = (name: string, exports: Record): boolean => { export interface State { method: string; - args: ArrayBuffer; + args: Uint8Array; invoke: { - result?: ArrayBuffer; + result?: Uint8Array; error?: string; }; subinvoke: { - result?: ArrayBuffer; + result?: Uint8Array; error?: string; args: unknown[]; }; subinvokeImplementation: { - result?: ArrayBuffer; + result?: Uint8Array; error?: string; args: unknown[]; }; invokeResult: InvokeResult; - getImplementationsResult?: ArrayBuffer; + getImplementationsResult?: Uint8Array; sanitizeEnv: { - args?: ArrayBuffer; - result?: ArrayBuffer; + args?: Uint8Array; + result?: Uint8Array; }; - env?: ArrayBuffer; + env?: Uint8Array; } export class WasmWrapper extends Wrapper { public static requiredExports: readonly string[] = ["_wrap_invoke"]; private _schema?: string; - private _wasm: ArrayBuffer | undefined = undefined; - private _sanitizedEnv: ArrayBuffer | undefined = undefined; + private _wasm: Uint8Array | undefined = undefined; + private _sanitizedEnv: Uint8Array | undefined = undefined; constructor( private _uri: Uri, @@ -136,12 +137,14 @@ export class WasmWrapper extends Wrapper { public async getFile( options: GetFileOptions, client: Client - ): Promise { + ): Promise { const { path, encoding } = options; const { data, error } = await UriResolverInterface.Query.getFile( - ( - options: InvokeOptions - ): Promise> => client.invoke(options), + { + invoke: ( + options: InvokeOptions + ): Promise> => client.invoke(options), + }, // TODO: support all types of URI resolvers (cache, etc) new Uri(this._uriResolver), combinePaths(this._uri.path, path) @@ -176,9 +179,9 @@ export class WasmWrapper extends Wrapper { public async invoke( options: InvokeOptions, client: Client - ): Promise> { + ): Promise> { try { - const { method, noDecode } = options; + const { method } = options; const args = options.args || {}; const wasm = await this._getWasmModule(client); @@ -193,7 +196,7 @@ export class WasmWrapper extends Wrapper { invokeResult: {} as InvokeResult, method, sanitizeEnv: {}, - args: args instanceof ArrayBuffer ? args : msgpackEncode(args), + args: isBuffer(args) ? args : msgpackEncode(args), }; const abort = (message: string) => { @@ -238,23 +241,10 @@ export class WasmWrapper extends Wrapper { ); } case "InvokeResult": { - if (noDecode) { - return { - data: invokeResult.invokeResult, - } as InvokeResult; - } - - try { - return { - data: msgpackDecode(invokeResult.invokeResult as ArrayBuffer), - } as InvokeResult; - } catch (err) { - throw Error( - `WasmWrapper: Failed to decode query result.\nResult: ${JSON.stringify( - invokeResult.invokeResult - )}\nError: ${err}` - ); - } + return { + data: invokeResult.invokeResult, + encoded: true, + }; } default: { throw Error(`WasmWrapper: Unknown state "${state}"`); @@ -318,7 +308,7 @@ export class WasmWrapper extends Wrapper { ): Promise { if (hasExport("_wrap_load_env", exports)) { if (this._sanitizedEnv !== undefined) { - state.env = this._sanitizedEnv as ArrayBuffer; + state.env = this._sanitizedEnv; } else { const clientEnv = this._getClientEnv(); @@ -326,7 +316,7 @@ export class WasmWrapper extends Wrapper { state.sanitizeEnv.args = msgpackEncode({ env: clientEnv }); await exports._wrap_sanitize_env(state.sanitizeEnv.args.byteLength); - state.env = state.sanitizeEnv.result as ArrayBuffer; + state.env = state.sanitizeEnv.result; this._sanitizedEnv = state.env; } else { state.env = msgpackEncode(clientEnv); @@ -334,7 +324,7 @@ export class WasmWrapper extends Wrapper { } } - await exports._wrap_load_env(state.env.byteLength); + await exports._wrap_load_env(state.env?.byteLength || 0); } } @@ -347,9 +337,9 @@ export class WasmWrapper extends Wrapper { } @Tracer.traceMethod("WasmWrapper: getWasmModule") - private async _getWasmModule(client: Client): Promise { + private async _getWasmModule(client: Client): Promise { if (this._wasm !== undefined) { - return this._wasm as ArrayBuffer; + return this._wasm; } const moduleManifest = this._manifest.module; @@ -361,7 +351,7 @@ export class WasmWrapper extends Wrapper { const data = (await this.getFile( { path: moduleManifest }, client - )) as ArrayBuffer; + )) as Uint8Array; this._wasm = data; return data; diff --git a/packages/js/client/src/wasm/imports.ts b/packages/js/client/src/wasm/imports.ts index e717edf191..08e9ef65ef 100644 --- a/packages/js/client/src/wasm/imports.ts +++ b/packages/js/client/src/wasm/imports.ts @@ -33,22 +33,15 @@ export const createImports = (config: { const method = readString(memory.buffer, methodPtr, methodLen); const args = readBytes(memory.buffer, argsPtr, argsLen); - const { data, error } = await client.invoke({ + const { data, error } = await client.invoke({ uri: uri, method: method, - args: args, - noDecode: true, + args: new Uint8Array(args), + encodeResult: true, }); if (!error) { - let msgpack: ArrayBuffer; - if (data instanceof ArrayBuffer) { - msgpack = data; - } else { - msgpack = msgpackEncode(data); - } - - state.subinvoke.result = msgpack; + state.subinvoke.result = data; } else { state.subinvoke.error = `${error.name}: ${error.message}`; } @@ -106,22 +99,15 @@ export const createImports = (config: { state.subinvokeImplementation.args = [implUri, method, args]; - const { data, error } = await client.invoke({ + const { data, error } = await client.invoke({ uri: implUri, method: method, - args: args, - noDecode: true, + args: new Uint8Array(args), + encodeResult: true, }); if (!error) { - let msgpack: ArrayBuffer; - if (data instanceof ArrayBuffer) { - msgpack = data; - } else { - msgpack = msgpackEncode(data); - } - - state.subinvokeImplementation.result = msgpack; + state.subinvokeImplementation.result = data; } else { state.subinvokeImplementation.error = `${error.name}: ${error.message}`; } @@ -179,7 +165,9 @@ export const createImports = (config: { }, // Store the invocation's result __wrap_invoke_result: (ptr: u32, len: u32): void => { - state.invoke.result = readBytes(memory.buffer, ptr, len); + state.invoke.result = new Uint8Array( + readBytes(memory.buffer, ptr, len) + ); }, // Store the invocation's error __wrap_invoke_error: (ptr: u32, len: u32): void => { @@ -219,7 +207,9 @@ export const createImports = (config: { writeBytes(state.sanitizeEnv.args, memory.buffer, ptr); }, __wrap_sanitize_env_result: (ptr: u32, len: u32): void => { - state.sanitizeEnv.result = readBytes(memory.buffer, ptr, len); + state.sanitizeEnv.result = new Uint8Array( + readBytes(memory.buffer, ptr, len) + ); }, __wrap_abort: ( msgPtr: u32, diff --git a/packages/js/core/src/__tests__/PluginRegistrations.spec.ts b/packages/js/core/src/__tests__/PluginRegistrations.spec.ts index 630c818f2f..18ee20c5eb 100644 --- a/packages/js/core/src/__tests__/PluginRegistrations.spec.ts +++ b/packages/js/core/src/__tests__/PluginRegistrations.spec.ts @@ -12,14 +12,14 @@ describe("sanitizePluginRegistrations", () => { const plugins = sanitizePluginRegistrations([ { uri: "wrap://polywrap/wrapper", - plugin: {} as PluginPackage, + plugin: {} as PluginPackage<{}>, } ]); expect(plugins).toEqual([ { uri: new Uri("wrap://polywrap/wrapper"), - plugin: {} as PluginPackage + plugin: {} as PluginPackage<{}> } ]); }); diff --git a/packages/js/core/src/__tests__/msgpack.spec.ts b/packages/js/core/src/__tests__/msgpack.spec.ts new file mode 100644 index 0000000000..f5e97e0c3a --- /dev/null +++ b/packages/js/core/src/__tests__/msgpack.spec.ts @@ -0,0 +1,42 @@ +import {msgpackEncode, msgpackDecode, isBuffer} from "../msgpack"; + +describe("msgpack", () => { + const expectedArrayLike = [ + 130, 168, 102, 105, 114, 115, 116, 75, + 101, 121, 170, 102, 105, 114, 115, 116, + 86, 97, 108, 117, 101, 169, 115, 101, + 99, 111, 110, 100, 75, 101, 121, 171, + 115, 101, 99, 111, 110, 100, 86, 97, + 108, 117, 101 + ] + it("Should encode and decode, returning the same object", () => { + const customObject = { + "firstKey": "firstValue", + "secondKey": "secondValue", + } + const encoded = msgpackEncode(customObject) + expect(encoded).toEqual(Uint8Array.from(expectedArrayLike)) + const decoded = msgpackDecode(encoded) + expect(decoded).toEqual(customObject); + }); + + it("Should encode and decode, returning the same map", () => { + const customMap = new Map() + customMap.set("firstKey", "firstValue") + customMap.set("secondKey", "secondValue") + + const encoded = msgpackEncode(customMap) + // [199, 43, 1] are being added because of the map structure + expect(encoded).toEqual(Uint8Array.from([ 199, 43, 1, ...expectedArrayLike])) + const decoded = msgpackDecode(encoded) + expect(decoded).toEqual(customMap); + }); + + it("Should check if object is buffer", () => { + const notBuf = isBuffer(expectedArrayLike); + expect(notBuf).toBeFalsy() + const buf = isBuffer(Uint8Array.from(expectedArrayLike)); + expect(buf).toBeTruthy() + }) + +}); diff --git a/packages/js/core/src/__tests__/resolveUri.spec.ts b/packages/js/core/src/__tests__/resolveUri.spec.ts index 910a604a22..a61e1e1cd2 100644 --- a/packages/js/core/src/__tests__/resolveUri.spec.ts +++ b/packages/js/core/src/__tests__/resolveUri.spec.ts @@ -31,7 +31,7 @@ import { describe("resolveUri", () => { const client = ( - wrappers: Record, + wrappers: Record>, plugins: PluginRegistration[] = [], interfaces: InterfaceImplementations[] = [], redirects: UriRedirect[] = [] @@ -67,7 +67,6 @@ describe("resolveUri", () => { {} as Client ) as TData }); - }, subscribe: < TData extends Record = Record @@ -111,13 +110,16 @@ describe("resolveUri", () => { }, } as unknown) as Client); - const createPluginWrapper = (uri: Uri, plugin: PluginPackage): Wrapper => { + const createPluginWrapper = (uri: Uri, plugin: PluginPackage<{}>): Wrapper => { return { invoke: () => Promise.resolve({ - uri, - plugin, - } as InvokeResult), + data: { + uri, + plugin, + }, + encoded: false + }), getSchema: (_client: Client): Promise => Promise.resolve(""), getFile: (options: GetFileOptions, client: Client) => Promise.resolve(""), getManifest: ( @@ -142,10 +144,13 @@ describe("resolveUri", () => { return { invoke: () => Promise.resolve({ - uri, - manifest, - uriResolver, - } as InvokeResult), + data: { + uri, + manifest, + uriResolver, + }, + encoded: false + }), getSchema: (_client: Client): Promise => Promise.resolve(""), getFile: (options: GetFileOptions, client: Client) => Promise.resolve(""), getManifest: ( @@ -205,7 +210,7 @@ describe("resolveUri", () => { { uri: new Uri("ens/my-plugin"), plugin: { - factory: () => ({} as Plugin), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [coreInterfaceUris.uriResolver], @@ -225,15 +230,15 @@ describe("resolveUri", () => { }, ]; - const wrappers: Record = { - "wrap://ens/ens": ensWrapper as unknown as PluginModule, - "wrap://ens/ipfs": ipfsWrapper as unknown as PluginModule, - "wrap://ens/my-plugin": pluginWrapper as unknown as PluginModule, + const wrappers: Record> = { + "wrap://ens/ens": ensWrapper as unknown as PluginModule<{}>, + "wrap://ens/ipfs": ipfsWrapper as unknown as PluginModule<{}>, + "wrap://ens/my-plugin": pluginWrapper as unknown as PluginModule<{}>, }; const uriResolvers: UriResolver[] = [ new RedirectsResolver(), - new PluginResolver((uri: Uri, plugin: PluginPackage) => + new PluginResolver((uri: Uri, plugin: PluginPackage<{}>) => createPluginWrapper(uri, plugin) ), new ExtendableUriResolver( @@ -257,8 +262,8 @@ describe("resolveUri", () => { const query = UriResolverInterface.Query; const uri = new Uri("wrap/some-uri"); - expect(query.tryResolveUri(client(wrappers).invoke, wrapper, uri)).toBeDefined(); - expect(query.getFile(client(wrappers).invoke, file, path)).toBeDefined(); + expect(query.tryResolveUri(client(wrappers), wrapper, uri)).toBeDefined(); + expect(query.getFile(client(wrappers), file, path)).toBeDefined(); }); it("works in the typical case", async () => { @@ -276,7 +281,7 @@ describe("resolveUri", () => { {} as Client ); - expect(wrapperIdentity).toMatchObject({ + expect(wrapperIdentity.data).toMatchObject({ uri: new Uri("ipfs/QmHash"), manifest: { format: "0.0.1-prealpha.9", @@ -300,7 +305,7 @@ describe("resolveUri", () => { {} as Client ); - expect(wrapperIdentity).toMatchObject({ + expect(wrapperIdentity.data).toMatchObject({ uri: new Uri("my/something-different"), manifest: { format: "0.0.1-prealpha.9", @@ -324,7 +329,7 @@ describe("resolveUri", () => { {} as Client ); - expect(wrapperIdentity).toMatchObject({ + expect(wrapperIdentity.data).toMatchObject({ uri: new Uri("ipfs/QmHash"), manifest: { format: "0.0.1-prealpha.9", @@ -349,7 +354,7 @@ describe("resolveUri", () => { {} as Client ); - expect(wrapperIdentity).toMatchObject({ + expect(wrapperIdentity.data).toMatchObject({ uri: new Uri("my/something-different"), manifest: { format: "0.0.1-prealpha.9", @@ -414,7 +419,7 @@ describe("resolveUri", () => { { uri: new Uri("some/wrapper"), plugin: { - factory: () => ({} as Plugin), + factory: () => ({} as PluginModule<{}>), manifest: { schema: "", implements: [coreInterfaceUris.uriResolver], @@ -460,7 +465,7 @@ describe("resolveUri", () => { client( { ...wrappers, - "wrap://ens/ipfs": faultyIpfsWrapper as unknown as PluginModule + "wrap://ens/ipfs": faultyIpfsWrapper as unknown as PluginModule<{}> }, plugins, interfaces diff --git a/packages/js/core/src/interfaces/uri-resolver.ts b/packages/js/core/src/interfaces/uri-resolver.ts index 46e30c52a6..fbcc1f3e38 100644 --- a/packages/js/core/src/interfaces/uri-resolver.ts +++ b/packages/js/core/src/interfaces/uri-resolver.ts @@ -1,5 +1,5 @@ // TODO: https://github.com/polywrap/monorepo/issues/101 -import { Uri, InvokeHandler, InvokeResult } from "../"; +import { Uri, Invoker, InvokeResult } from "../"; import { Tracer } from "@polywrap/tracing-js"; @@ -13,11 +13,11 @@ export const Query = { tryResolveUri: Tracer.traceFunc( "core: uri-resolver: tryResolveUri", async ( - invoke: InvokeHandler["invoke"], + invoker: Invoker, wrapper: Uri, uri: Uri ): Promise> => { - return invoke({ + return invoker.invoke({ uri: wrapper.uri, method: `tryResolveUri`, args: { @@ -30,11 +30,11 @@ export const Query = { getFile: Tracer.traceFunc( "core: uri-resolver: getFile", async ( - invoke: InvokeHandler["invoke"], + invoker: Invoker, wrapper: Uri, path: string - ): Promise> => { - return invoke({ + ): Promise> => { + return invoker.invoke({ uri: wrapper.uri, method: "getFile", args: { diff --git a/packages/js/core/src/msgpack/index.ts b/packages/js/core/src/msgpack/index.ts index 8ef3c92a4b..e5e28ee00d 100644 --- a/packages/js/core/src/msgpack/index.ts +++ b/packages/js/core/src/msgpack/index.ts @@ -33,7 +33,7 @@ extensionCodec.register({ }, }); -export function msgpackEncode(object: unknown): ArrayBuffer { +export function msgpackEncode(object: unknown): Uint8Array { const encoder = new Encoder( extensionCodec, undefined, // context @@ -45,7 +45,7 @@ export function msgpackEncode(object: unknown): ArrayBuffer { undefined // forceIntegerToFloat ); - return encoder.encode(object).buffer; + return encoder.encode(object); } export function msgpackDecode( @@ -54,3 +54,11 @@ export function msgpackDecode( const decoder = new Decoder(extensionCodec); return decoder.decode(buffer); } + +export function isBuffer(maybeBuf: unknown): maybeBuf is BufferSource { + if (maybeBuf instanceof ArrayBuffer || ArrayBuffer.isView(maybeBuf)) { + return true; + } else { + return false; + } +} diff --git a/packages/js/core/src/types/Client.ts b/packages/js/core/src/types/Client.ts index 23dfa55b8a..4a523bc468 100644 --- a/packages/js/core/src/types/Client.ts +++ b/packages/js/core/src/types/Client.ts @@ -1,6 +1,6 @@ import { QueryHandler, - InvokeHandler, + Invoker, SubscriptionHandler, UriRedirect, Uri, @@ -53,9 +53,9 @@ export interface GetImplementationsOptions extends Contextualized { } export interface Client - extends QueryHandler, + extends Invoker, + QueryHandler, SubscriptionHandler, - InvokeHandler, WorkflowHandler, UriResolverHandler { getRedirects(options: GetRedirectsOptions): readonly UriRedirect[]; @@ -91,7 +91,7 @@ export interface Client getFile( uri: TUri, options: GetFileOptions - ): Promise; + ): Promise; getImplementations( uri: TUri, diff --git a/packages/js/core/src/types/Invoke.ts b/packages/js/core/src/types/Invoke.ts index 057c23bccd..fb26eefbbe 100644 --- a/packages/js/core/src/types/Invoke.ts +++ b/packages/js/core/src/types/Invoke.ts @@ -15,13 +15,7 @@ export interface InvokeOptions< * Arguments for the method, structured as a map, * removing the chance of incorrectly ordering arguments. */ - args?: Record | ArrayBuffer; - - /** - * If set to true, the invoke function will not decode the msgpack results - * into JavaScript objects, and instead return the raw ArrayBuffer. - */ - noDecode?: boolean; + args?: Record | Uint8Array; /** * Override the client's config for all invokes within this invoke. @@ -52,8 +46,26 @@ export interface InvokeResult { error?: Error; } -export interface InvokeHandler { +export interface InvokerOptions< + TUri extends Uri | string = string, + TClientConfig extends ClientConfig = ClientConfig +> extends InvokeOptions { + encodeResult?: boolean; +} + +export interface Invoker { invoke( - options: InvokeOptions + options: InvokerOptions ): Promise>; } + +export interface InvocableResult extends InvokeResult { + encoded?: boolean; +} + +export interface Invocable { + invoke( + options: InvokeOptions, + invoker: Invoker + ): Promise>; +} diff --git a/packages/js/core/src/types/Workflow.ts b/packages/js/core/src/types/Workflow.ts index f1c0b8df86..cd7e030b56 100644 --- a/packages/js/core/src/types/Workflow.ts +++ b/packages/js/core/src/types/Workflow.ts @@ -23,6 +23,17 @@ export type Workflow = { jobs: Job; }; +export enum JobStatus { + SUCCEED, + FAILED, + SKIPPED, +} + +export interface JobResult + extends InvokeResult { + status: JobStatus; +} + export interface RunOptions< TData extends Record = Record, TUri extends Uri | string = string @@ -32,11 +43,7 @@ export interface RunOptions< contextId?: string; ids?: string[]; - onExecution?( - id: string, - data?: InvokeResult["data"], - error?: InvokeResult["error"] - ): MaybeAsync; + onExecution?(id: string, jobResult: JobResult): MaybeAsync; } export interface WorkflowHandler { diff --git a/packages/js/core/src/types/Wrapper.ts b/packages/js/core/src/types/Wrapper.ts index b9308c81b9..d940fe56b2 100644 --- a/packages/js/core/src/types/Wrapper.ts +++ b/packages/js/core/src/types/Wrapper.ts @@ -4,7 +4,9 @@ import { GetFileOptions, GetManifestOptions, InvokeOptions, - InvokeResult, + Invocable, + Invoker, + InvocableResult, } from "."; import { AnyManifestArtifact, ManifestArtifactType } from "../manifest"; @@ -14,7 +16,7 @@ import { AnyManifestArtifact, ManifestArtifactType } from "../manifest"; * this class may do things like caching WASM bytecode, spawning * worker threads, or indexing into resolvers to find the requested method. */ -export abstract class Wrapper { +export abstract class Wrapper implements Invocable { /** * Invoke the Wrapper based on the provided [[InvokeOptions]] * @@ -24,8 +26,8 @@ export abstract class Wrapper { */ public abstract invoke( options: InvokeOptions, - client: Client - ): Promise>; + invoker: Invoker + ): Promise>; /** * Get the Wrapper's schema @@ -57,7 +59,7 @@ export abstract class Wrapper { public abstract getFile( options: GetFileOptions, client: Client - ): Promise; + ): Promise; } /** Cache of Wrapper definitions, mapping the Wrapper's URI to its definition */ diff --git a/packages/js/core/src/uri-resolution/resolvers/extendable/UriResolverWrapper.ts b/packages/js/core/src/uri-resolution/resolvers/extendable/UriResolverWrapper.ts index a8cdef56d0..1c7a4910de 100644 --- a/packages/js/core/src/uri-resolution/resolvers/extendable/UriResolverWrapper.ts +++ b/packages/js/core/src/uri-resolution/resolvers/extendable/UriResolverWrapper.ts @@ -3,7 +3,7 @@ import { DeserializeManifestOptions, deserializePolywrapManifest, } from "../../../manifest"; -import { Uri, WrapperCache, Client, InvokeHandler } from "../../../types"; +import { Uri, WrapperCache, Client, Invoker } from "../../../types"; import { UriResolver, UriResolutionStack, @@ -34,7 +34,7 @@ export class UriResolverWrapper implements UriResolver { const result = await tryResolveUriWithImplementation( uri, this.implementationUri, - client.invoke.bind(client) + client ); if (!result) { @@ -82,10 +82,10 @@ export class UriResolverWrapper implements UriResolver { const tryResolveUriWithImplementation = async ( uri: Uri, implementationUri: Uri, - invoke: InvokeHandler["invoke"] + invoker: Invoker ): Promise => { const { data } = await UriResolverInterface.Query.tryResolveUri( - invoke, + invoker, implementationUri, uri ); diff --git a/packages/js/core/src/workflow/JobRunner.ts b/packages/js/core/src/workflow/JobRunner.ts index 9cfec9e880..4a3fc505c0 100644 --- a/packages/js/core/src/workflow/JobRunner.ts +++ b/packages/js/core/src/workflow/JobRunner.ts @@ -1,8 +1,9 @@ import { Client, executeMaybeAsyncFunction, - InvokeResult, Job, + JobResult, + JobStatus, MaybeAsync, Uri, } from "../types"; @@ -19,14 +20,13 @@ export class JobRunner< TData extends unknown = unknown, TUri extends Uri | string = string > { - private jobOutput: Map>; + private jobOutput: Map>; constructor( private client: Client, private onExecution?: ( id: string, - data?: InvokeResult["data"], - error?: InvokeResult["error"] + JobResult: JobResult ) => MaybeAsync ) { this.jobOutput = new Map(); @@ -45,27 +45,47 @@ export class JobRunner< const steps = jobs[jobId].steps; if (steps) { for (let i = 0; i < steps.length; i++) { + let result: JobResult | undefined; + let args: Record | undefined; + const step = steps[i]; const absoluteId = parentId ? `${parentId}.${jobId}.${i}` : `${jobId}.${i}`; - const args = this.resolveArgs(absoluteId, step.args); - const result = await this.client.invoke({ - uri: step.uri, - method: step.method, - config: step.config, - args: args, - }); - - this.jobOutput.set(absoluteId, result); - - if (this.onExecution && typeof this.onExecution === "function") { - await executeMaybeAsyncFunction( - this.onExecution, - absoluteId, - result.data, - result.error - ); + try { + args = this.resolveArgs(absoluteId, step.args); + } catch (e) { + result = { + error: e, + status: JobStatus.SKIPPED, + }; + } + + if (args) { + const invokeResult = await this.client.invoke({ + uri: step.uri, + method: step.method, + config: step.config, + args: args, + }); + + if (invokeResult.error) { + result = { ...invokeResult, status: JobStatus.FAILED }; + } else { + result = { ...invokeResult, status: JobStatus.SUCCEED }; + } + } + + if (result) { + this.jobOutput.set(absoluteId, result); + + if (this.onExecution && typeof this.onExecution === "function") { + await executeMaybeAsyncFunction( + this.onExecution, + absoluteId, + result + ); + } } } } @@ -124,8 +144,21 @@ export class JobRunner< } } const output = outputs.get(absStepId); - if (output && output[dataOrErr]) { - return output[dataOrErr]; + if ( + output && + dataOrErr === "data" && + output.status === JobStatus.SUCCEED && + output.data + ) { + return output.data; + } + if ( + output && + dataOrErr === "error" && + output.status === JobStatus.FAILED && + output.error + ) { + return output.error; } } diff --git a/packages/js/plugins/file-system/src/index.ts b/packages/js/plugins/file-system/src/index.ts index 96bb84ad92..66b46ef9f7 100644 --- a/packages/js/plugins/file-system/src/index.ts +++ b/packages/js/plugins/file-system/src/index.ts @@ -18,8 +18,12 @@ import { PluginFactory } from "@polywrap/core-js"; type NoConfig = Record; export class FileSystemPlugin extends Module { - async readFile(args: Args_readFile, _client: Client): Promise { - return fs.promises.readFile(args.path); + async readFile(args: Args_readFile, _client: Client): Promise { + return fs.promises + .readFile(args.path) + .then((buffer) => + ArrayBuffer.isView(buffer) ? buffer : new Uint8Array(buffer) + ); } async readFileAsString( diff --git a/packages/js/react/src/invoke.tsx b/packages/js/react/src/invoke.tsx index d01b2f4c00..3b11f1509c 100644 --- a/packages/js/react/src/invoke.tsx +++ b/packages/js/react/src/invoke.tsx @@ -1,7 +1,11 @@ import { usePolywrapClient } from "./client"; import { useStateReducer } from "./state"; -import { InvokeOptions, InvokeResult } from "@polywrap/core-js"; +import { + InvokeOptions, + InvokeResult, + isBuffer +} from "@polywrap/core-js"; export interface UsePolywrapInvokeState< TData = unknown @@ -21,13 +25,13 @@ export interface UsePolywrapInvokeProps extends InvokeOptions { /* Note that the initial values passed into the usePolywrapInvoke hook will be -ignored when an ArrayBuffer is passed into execute(...). +ignored when an Uint8Array is passed into execute(...). */ export interface UsePolywrapInvoke< TData = unknown > extends UsePolywrapInvokeState { execute: ( - args?: Record | ArrayBuffer + args?: Record | Uint8Array ) => Promise>; } @@ -42,11 +46,11 @@ export function usePolywrapInvoke< INITIAL_QUERY_STATE as UsePolywrapInvokeState ); - const execute = async (args?: Record | ArrayBuffer) => { + const execute = async (args?: Record | Uint8Array) => { dispatch({ loading: true }); const { data, error } = await client.invoke({ ...props, - args: args instanceof ArrayBuffer ? args : { + args: isBuffer(args) ? args : { ...props.args, ...args, }, diff --git a/packages/schema/bind/src/__tests__/index.ts b/packages/schema/bind/src/__tests__/index.ts index 770ee1190a..b30c0411ad 100644 --- a/packages/schema/bind/src/__tests__/index.ts +++ b/packages/schema/bind/src/__tests__/index.ts @@ -71,13 +71,13 @@ export function fetchTestCases(): TestCases { }; }); - // Parse the input schema into the TypeInfo structure - const typeInfo = parseSchema(schema); + // Parse the input schema into the Abi structure + const abi = parseSchema(schema); const input: BindOptions = { projectName: "Test", bindLanguage: "TBD" as BindLanguage, - typeInfo, + abi, schema, outputDirAbs: path.join(root, "combined") }; diff --git a/packages/schema/bind/src/bindings/assemblyscript/wasm-as/index.ts b/packages/schema/bind/src/bindings/assemblyscript/wasm-as/index.ts index f8b26d6e2e..0c58c083e3 100644 --- a/packages/schema/bind/src/bindings/assemblyscript/wasm-as/index.ts +++ b/packages/schema/bind/src/bindings/assemblyscript/wasm-as/index.ts @@ -4,9 +4,9 @@ import { renderTemplates, loadSubTemplates } from "../../utils/templates"; import { BindOptions, BindOutput } from "../../.."; import { - TypeInfo, + Abi, ObjectDefinition, - transformTypeInfo, + transformAbi, addFirstLast, extendType, toPrefixedGraphQLType, @@ -29,10 +29,10 @@ export const generateBinding: GenerateBindingFn = ( outputDirAbs: options.outputDirAbs, }; const output = result.output; - const typeInfo = applyTransforms(options.typeInfo); + const abi = applyTransforms(options.abi); // Generate object type folders - for (const objectType of typeInfo.objectTypes) { + for (const objectType of abi.objectTypes) { output.entries.push({ type: "Directory", name: objectType.type, @@ -48,7 +48,7 @@ export const generateBinding: GenerateBindingFn = ( const importEntries: OutputEntry[] = []; // Generate imported module type folders - for (const importedModuleType of typeInfo.importedModuleTypes) { + for (const importedModuleType of abi.importedModuleTypes) { importEntries.push({ type: "Directory", name: importedModuleType.type, @@ -61,7 +61,7 @@ export const generateBinding: GenerateBindingFn = ( } // Generate imported enum type folders - for (const importedEnumType of typeInfo.importedEnumTypes) { + for (const importedEnumType of abi.importedEnumTypes) { importEntries.push({ type: "Directory", name: importedEnumType.type, @@ -74,7 +74,7 @@ export const generateBinding: GenerateBindingFn = ( } // Generate imported object type folders - for (const importedObectType of typeInfo.importedObjectTypes) { + for (const importedObectType of abi.importedObjectTypes) { importEntries.push({ type: "Directory", name: importedObectType.type, @@ -92,13 +92,13 @@ export const generateBinding: GenerateBindingFn = ( name: "imported", data: [ ...importEntries, - ...renderTemplates(templatePath("imported"), typeInfo, subTemplates), + ...renderTemplates(templatePath("imported"), abi, subTemplates), ], }); } // Generate interface type folders - for (const interfaceType of typeInfo.interfaceTypes) { + for (const interfaceType of abi.interfaceTypes) { output.entries.push({ type: "Directory", name: interfaceType.type, @@ -111,20 +111,20 @@ export const generateBinding: GenerateBindingFn = ( } // Generate module type folders - if (typeInfo.moduleType) { + if (abi.moduleType) { output.entries.push({ type: "Directory", - name: typeInfo.moduleType.type, + name: abi.moduleType.type, data: renderTemplates( templatePath("module-type"), - typeInfo.moduleType, + abi.moduleType, subTemplates ), }); } // Generate enum type folders - for (const enumType of typeInfo.enumTypes) { + for (const enumType of abi.enumTypes) { output.entries.push({ type: "Directory", name: enumType.type, @@ -141,18 +141,16 @@ export const generateBinding: GenerateBindingFn = ( data: renderTemplates(templatePath("object-type"), def, subTemplates), }); }; - generateEnvTypeFolder(typeInfo.envType.client); - generateEnvTypeFolder(typeInfo.envType.sanitized); + generateEnvTypeFolder(abi.envType.client); + generateEnvTypeFolder(abi.envType.sanitized); // Generate root entry file - output.entries.push( - ...renderTemplates(templatePath(""), typeInfo, subTemplates) - ); + output.entries.push(...renderTemplates(templatePath(""), abi, subTemplates)); return result; }; -function applyTransforms(typeInfo: TypeInfo): TypeInfo { +function applyTransforms(abi: Abi): Abi { const transforms = [ extendType(Functions), addFirstLast, @@ -160,7 +158,7 @@ function applyTransforms(typeInfo: TypeInfo): TypeInfo { ]; for (const transform of transforms) { - typeInfo = transformTypeInfo(typeInfo, transform); + abi = transformAbi(abi, transform); } - return typeInfo; + return abi; } diff --git a/packages/schema/bind/src/bindings/rust/wasm-rs/index.ts b/packages/schema/bind/src/bindings/rust/wasm-rs/index.ts index 909c383b63..fc3c022723 100644 --- a/packages/schema/bind/src/bindings/rust/wasm-rs/index.ts +++ b/packages/schema/bind/src/bindings/rust/wasm-rs/index.ts @@ -5,8 +5,8 @@ import { renderTemplates, loadSubTemplates } from "../../utils/templates"; import { BindOptions, BindOutput } from "../../.."; import { - TypeInfo, - transformTypeInfo, + Abi, + transformAbi, extendType, addFirstLast, toPrefixedGraphQLType, @@ -33,10 +33,10 @@ export const generateBinding: GenerateBindingFn = ( outputDirAbs: options.outputDirAbs, }; const output = result.output; - const typeInfo = applyTransforms(options.typeInfo); + const abi = applyTransforms(options.abi); // Generate object type folders - for (const objectType of typeInfo.objectTypes) { + for (const objectType of abi.objectTypes) { output.entries.push({ type: "Directory", name: toLower(objectType.type), @@ -52,7 +52,7 @@ export const generateBinding: GenerateBindingFn = ( const importEntries: OutputEntry[] = []; // Generate imported module type folders - for (const importedModuleType of typeInfo.importedModuleTypes) { + for (const importedModuleType of abi.importedModuleTypes) { importEntries.push({ type: "Directory", name: toLower(importedModuleType.type), @@ -65,7 +65,7 @@ export const generateBinding: GenerateBindingFn = ( } // Generate imported enum type folders - for (const importedEnumType of typeInfo.importedEnumTypes) { + for (const importedEnumType of abi.importedEnumTypes) { importEntries.push({ type: "Directory", name: toLower(importedEnumType.type), @@ -78,7 +78,7 @@ export const generateBinding: GenerateBindingFn = ( } // Generate imported object type folders - for (const importedObectType of typeInfo.importedObjectTypes) { + for (const importedObectType of abi.importedObjectTypes) { importEntries.push({ type: "Directory", name: toLower(importedObectType.type), @@ -96,13 +96,13 @@ export const generateBinding: GenerateBindingFn = ( name: "imported", data: [ ...importEntries, - ...renderTemplates(templatePath("imported"), typeInfo, subTemplates), + ...renderTemplates(templatePath("imported"), abi, subTemplates), ], }); } // Generate interface type folders - for (const interfaceType of typeInfo.interfaceTypes) { + for (const interfaceType of abi.interfaceTypes) { output.entries.push({ type: "Directory", name: toLower(interfaceType.type), @@ -115,20 +115,20 @@ export const generateBinding: GenerateBindingFn = ( } // Generate module type folders - if (typeInfo.moduleType) { + if (abi.moduleType) { output.entries.push({ type: "Directory", - name: toLower(typeInfo.moduleType.type), + name: toLower(abi.moduleType.type), data: renderTemplates( templatePath("module-type"), - typeInfo.moduleType, + abi.moduleType, subTemplates ), }); } // Generate enum type folders - for (const enumType of typeInfo.enumTypes) { + for (const enumType of abi.enumTypes) { output.entries.push({ type: "Directory", name: toLower(enumType.type), @@ -137,14 +137,12 @@ export const generateBinding: GenerateBindingFn = ( } // Generate root entry file - output.entries.push( - ...renderTemplates(templatePath(""), typeInfo, subTemplates) - ); + output.entries.push(...renderTemplates(templatePath(""), abi, subTemplates)); return result; }; -function applyTransforms(typeInfo: TypeInfo): TypeInfo { +function applyTransforms(abi: Abi): Abi { const transforms = [ extendType(Functions), addFirstLast, @@ -156,7 +154,7 @@ function applyTransforms(typeInfo: TypeInfo): TypeInfo { ]; for (const transform of transforms) { - typeInfo = transformTypeInfo(typeInfo, transform); + abi = transformAbi(abi, transform); } - return typeInfo; + return abi; } diff --git a/packages/schema/bind/src/bindings/rust/wasm-rs/templates/entry-rs.mustache b/packages/schema/bind/src/bindings/rust/wasm-rs/templates/entry-rs.mustache index 210521da18..450d2c5cd7 100644 --- a/packages/schema/bind/src/bindings/rust/wasm-rs/templates/entry-rs.mustache +++ b/packages/schema/bind/src/bindings/rust/wasm-rs/templates/entry-rs.mustache @@ -13,7 +13,6 @@ use polywrap_wasm_rs::{ InvokeArgs, }; -#[cfg(feature = "wrap-invoke")] #[no_mangle] pub extern "C" fn _wrap_invoke(method_size: u32, args_size: u32) -> bool { // Ensure the abort handler is properly setup diff --git a/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/byRef.ts b/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/byRef.ts index 37f805b674..fd4e9eba63 100644 --- a/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/byRef.ts +++ b/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/byRef.ts @@ -1,6 +1,6 @@ -import { TypeInfoTransforms, AnyDefinition } from "@polywrap/schema-parse"; +import { AbiTransforms, AnyDefinition } from "@polywrap/schema-parse"; -export function byRef(): TypeInfoTransforms { +export function byRef(): AbiTransforms { return { enter: { // eslint-disable-next-line @typescript-eslint/naming-convention diff --git a/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/propertyDeps.ts b/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/propertyDeps.ts index 3ea0d595c6..f1d962c4ed 100644 --- a/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/propertyDeps.ts +++ b/packages/schema/bind/src/bindings/rust/wasm-rs/transforms/propertyDeps.ts @@ -7,7 +7,7 @@ import { ObjectDefinition, AnyDefinition, ModuleDefinition, - TypeInfoTransforms, + AbiTransforms, } from "@polywrap/schema-parse"; interface PropertyDep { @@ -23,7 +23,7 @@ interface PropertyDepsState { propertyDeps?: PropertyDep[]; } -export function propertyDeps(): TypeInfoTransforms { +export function propertyDeps(): AbiTransforms { const state: PropertyDepsState = {}; return { diff --git a/packages/schema/bind/src/bindings/typescript/app-ts/index.ts b/packages/schema/bind/src/bindings/typescript/app-ts/index.ts index 995d81bea1..8d9bf009b0 100644 --- a/packages/schema/bind/src/bindings/typescript/app-ts/index.ts +++ b/packages/schema/bind/src/bindings/typescript/app-ts/index.ts @@ -5,12 +5,12 @@ import { renderTemplates } from "../../utils/templates"; import { BindOptions, BindOutput } from "../../.."; import { - transformTypeInfo, + transformAbi, extendType, addFirstLast, toPrefixedGraphQLType, methodParentPointers, - TypeInfo, + Abi, } from "@polywrap/schema-parse"; import path from "path"; @@ -27,18 +27,18 @@ export const generateBinding: GenerateBindingFn = ( }; const output = result.output; const schema = options.schema; - const typeInfo = applyTransforms(options.typeInfo); + const abi = applyTransforms(options.abi); output.entries = renderTemplates( path.join(__dirname, "./templates"), - { ...typeInfo, schema }, + { ...abi, schema }, {} ); return result; }; -function applyTransforms(typeInfo: TypeInfo): TypeInfo { +function applyTransforms(abi: Abi): Abi { const transforms = [ extendType(Functions), addFirstLast, @@ -47,7 +47,7 @@ function applyTransforms(typeInfo: TypeInfo): TypeInfo { ]; for (const transform of transforms) { - typeInfo = transformTypeInfo(typeInfo, transform); + abi = transformAbi(abi, transform); } - return typeInfo; + return abi; } diff --git a/packages/schema/bind/src/bindings/typescript/app-ts/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/app-ts/templates/types-ts.mustache index 78a23f1067..9e7a07ac49 100644 --- a/packages/schema/bind/src/bindings/typescript/app-ts/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/app-ts/templates/types-ts.mustache @@ -15,7 +15,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/schema/bind/src/bindings/typescript/plugin-ts/index.ts b/packages/schema/bind/src/bindings/typescript/plugin-ts/index.ts index 278322cb4e..5a5b5c3815 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin-ts/index.ts +++ b/packages/schema/bind/src/bindings/typescript/plugin-ts/index.ts @@ -5,8 +5,8 @@ import { renderTemplates } from "../../utils/templates"; import { BindOptions, BindOutput } from "../../.."; import { - TypeInfo, - transformTypeInfo, + Abi, + transformAbi, extendType, addFirstLast, toPrefixedGraphQLType, @@ -23,8 +23,8 @@ const templatePath = (subpath: string) => export const generateBinding: GenerateBindingFn = ( options: BindOptions ): BindOutput => { - // Apply TypeInfo transforms - const typeInfo = applyTransforms(options.typeInfo); + // Apply Abi transforms + const abi = applyTransforms(options.abi); // Generate Bindings const result: BindOutput = { @@ -37,14 +37,14 @@ export const generateBinding: GenerateBindingFn = ( output.entries = renderTemplates( templatePath(""), - { ...typeInfo, schema: options.schema }, + { ...abi, schema: options.schema }, {} ); return result; }; -function applyTransforms(typeInfo: TypeInfo): TypeInfo { +function applyTransforms(abi: Abi): Abi { const transforms = [ extendType(Functions), addFirstLast, @@ -54,7 +54,7 @@ function applyTransforms(typeInfo: TypeInfo): TypeInfo { ]; for (const transform of transforms) { - typeInfo = transformTypeInfo(typeInfo, transform); + abi = transformAbi(abi, transform); } - return typeInfo; + return abi; } diff --git a/packages/schema/bind/src/bindings/typescript/plugin-ts/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/plugin-ts/templates/types-ts.mustache index 771baaab3c..e88be3796a 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin-ts/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/plugin-ts/templates/types-ts.mustache @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/schema/bind/src/index.ts b/packages/schema/bind/src/index.ts index ecdf3c5f15..8c6dd2a7db 100644 --- a/packages/schema/bind/src/index.ts +++ b/packages/schema/bind/src/index.ts @@ -10,5 +10,8 @@ export * from "./types"; export * from "./bindings"; export function bindSchema(options: BindOptions): BindOutput { + // TODO: remove this post-release, this is needed to resolve the CLI<>plugin circular dependency + /* eslint-disable @typescript-eslint/no-explicit-any */ + options.abi = options.abi || (options as any).typeInfo; return getGenerateBindingFn(options.bindLanguage)(options); } diff --git a/packages/schema/bind/src/types.ts b/packages/schema/bind/src/types.ts index 9508b2466c..974e77c202 100644 --- a/packages/schema/bind/src/types.ts +++ b/packages/schema/bind/src/types.ts @@ -1,4 +1,4 @@ -import { TypeInfo } from "@polywrap/schema-parse"; +import { Abi } from "@polywrap/schema-parse"; import { OutputDirectory } from "@polywrap/os-js"; export type BindLanguage = "wasm-as" | "wasm-rs" | "plugin-ts" | "app-ts"; @@ -11,7 +11,7 @@ export interface BindOutput { export interface BindOptions { projectName: string; bindLanguage: BindLanguage; - typeInfo: TypeInfo; + abi: Abi; schema: string; config?: Record; outputDirAbs: string; diff --git a/packages/schema/compose/src/__tests__/index.ts b/packages/schema/compose/src/__tests__/index.ts index 8f8ccbeaf7..0ece968bde 100644 --- a/packages/schema/compose/src/__tests__/index.ts +++ b/packages/schema/compose/src/__tests__/index.ts @@ -3,7 +3,7 @@ import { ComposerOutput, ComposerOptions, ComposerFilter } from ".."; import path from "path"; import { readdirSync, Dirent } from "fs"; -import { TypeInfo } from "@polywrap/schema-parse"; +import { Abi } from "@polywrap/schema-parse"; import { GetPathToComposeTestFiles, readFileIfExists, @@ -75,7 +75,7 @@ async function importCase( // Fetch the output schemas const moduleSchema = readFileIfExists("output/module.graphql", directory); - const ModuleTypeInfo = await readNamedExportIfExists("typeInfo", "output/module.ts", directory); + const ModuleAbi = await readNamedExportIfExists("abi", "output/module.ts", directory); // Fetch the error if exists const outputJson = readFileIfExists("output/output.json", directory) @@ -121,10 +121,10 @@ async function importCase( } } - if (moduleSchema && ModuleTypeInfo) { + if (moduleSchema && ModuleAbi) { output = { schema: moduleSchema, - typeInfo: ModuleTypeInfo + abi: ModuleAbi }; } diff --git a/packages/schema/compose/src/env.ts b/packages/schema/compose/src/env.ts index 55da64e76c..1daa85707b 100644 --- a/packages/schema/compose/src/env.ts +++ b/packages/schema/compose/src/env.ts @@ -2,10 +2,10 @@ import { ObjectDefinition, MODULE_NAME, AnyDefinition, - TypeInfo, + Abi, } from "@polywrap/schema-parse"; -export function validateEnv(info: TypeInfo): void { +export function validateEnv(info: Abi): void { if (info.envType.client) { validateClientEnvironment( info, @@ -16,7 +16,7 @@ export function validateEnv(info: TypeInfo): void { } export function validateClientEnvironment( - info: TypeInfo, + info: Abi, client: ObjectDefinition, sanitized?: ObjectDefinition ): void { diff --git a/packages/schema/compose/src/index.ts b/packages/schema/compose/src/index.ts index a35dfab224..a040be4f05 100644 --- a/packages/schema/compose/src/index.ts +++ b/packages/schema/compose/src/index.ts @@ -3,20 +3,20 @@ import { resolveImportsAndParseSchemas } from "./resolve"; import { renderSchema } from "./render"; import { validateEnv } from "./env"; -import { TypeInfo, combineTypeInfo } from "@polywrap/schema-parse"; +import { Abi, combineAbi } from "@polywrap/schema-parse"; export * from "./types"; export { renderSchema }; export interface ComposerOutput { schema?: string; - typeInfo?: TypeInfo; + abi?: Abi; } export enum ComposerFilter { Schema = 1 << 0, - TypeInfo = 1 << 1, - All = Schema | TypeInfo, + Abi = 1 << 1, + All = Schema | Abi, } export interface ComposerOptions { @@ -28,35 +28,36 @@ export interface ComposerOptions { export async function composeSchema( options: ComposerOptions ): Promise { - const typeInfos = await resolveImports(options.schemas, options.resolvers); + const abis = await resolveImports(options.schemas, options.resolvers); - const typeInfo = - typeInfos.length === 1 ? typeInfos[0] : combineTypeInfo(typeInfos); + const abi = abis.length === 1 ? abis[0] : combineAbi(abis); - await validateEnv(typeInfo); + await validateEnv(abi); // Forming our output structure for the caller const includeSchema = options.output & ComposerFilter.Schema; - const includeTypeInfo = options.output & ComposerFilter.TypeInfo; + const includeAbi = options.output & ComposerFilter.Abi; return { - schema: includeSchema ? renderSchema(typeInfo, true) : undefined, - typeInfo: includeTypeInfo ? typeInfo : undefined, - }; + schema: includeSchema ? renderSchema(abi, true) : undefined, + abi: includeAbi ? abi : undefined, + // TODO: remove this post-release, this is needed to resolve the CLI<>plugin circular dependency + typeInfo: includeAbi ? abi : undefined, + } as ComposerOutput; } export async function resolveImports( schemas: SchemaFile[], resolvers: SchemaResolvers -): Promise { - const typeInfos: TypeInfo[] = []; +): Promise { + const abis: Abi[] = []; if (schemas.length === 0) { throw Error("No schema provided"); } for (const schema of schemas) { - typeInfos.push( + abis.push( await resolveImportsAndParseSchemas( schema.schema, schema.absolutePath, @@ -65,5 +66,5 @@ export async function resolveImports( ); } - return typeInfos; + return abis; } diff --git a/packages/schema/compose/src/render.ts b/packages/schema/compose/src/render.ts index a529791dc6..77cc4288d7 100644 --- a/packages/schema/compose/src/render.ts +++ b/packages/schema/compose/src/render.ts @@ -3,10 +3,10 @@ import { addHeader } from "./templates/header.mustache"; import Mustache from "mustache"; import { - TypeInfo, + Abi, addFirstLast, toGraphQLType, - transformTypeInfo, + transformAbi, moduleCapabilities, addAnnotations, } from "@polywrap/schema-parse"; @@ -14,15 +14,15 @@ import { // Remove mustache's built-in HTML escaping Mustache.escape = (value) => value; -export function renderSchema(typeInfo: TypeInfo, header: boolean): string { - // Prepare the TypeInfo for the renderer - typeInfo = transformTypeInfo(typeInfo, addFirstLast); - typeInfo = transformTypeInfo(typeInfo, toGraphQLType); - typeInfo = transformTypeInfo(typeInfo, moduleCapabilities()); - typeInfo = transformTypeInfo(typeInfo, addAnnotations); +export function renderSchema(abi: Abi, header: boolean): string { + // Prepare the Abi for the renderer + abi = transformAbi(abi, addFirstLast); + abi = transformAbi(abi, toGraphQLType); + abi = transformAbi(abi, moduleCapabilities()); + abi = transformAbi(abi, addAnnotations); let schema = Mustache.render(schemaTemplate, { - typeInfo, + abi, }); if (header) { diff --git a/packages/schema/compose/src/resolve.ts b/packages/schema/compose/src/resolve.ts index 8bd5fcb77c..6a7aa674f6 100644 --- a/packages/schema/compose/src/resolve.ts +++ b/packages/schema/compose/src/resolve.ts @@ -15,12 +15,12 @@ import { addHeader } from "./templates/header.mustache"; import { checkDuplicateEnvProperties } from "./env"; import { - TypeInfo, + Abi, parseSchema, ObjectDefinition, ImportedObjectDefinition, ModuleDefinition, - TypeInfoTransforms, + AbiTransforms, visitObjectDefinition, visitModuleDefinition, visitEnvDefinition, @@ -62,7 +62,7 @@ const TYPE_NAME_REGEX = `[a-zA-Z0-9_]+`; export async function resolveUseStatements( schema: string, schemaPath: string, - typeInfo: TypeInfo + abi: Abi ): Promise { const useKeywordCapture = /^[#]*["{3}]*use[ \n\t]/gm; const useCapture = /[#]*["{3}]*use[ \n\t]*{([a-zA-Z0-9_, \n\t]+)}[ \n\t]*for[ \n\t]*(\w+)[ \n\t]/g; @@ -81,7 +81,7 @@ export async function resolveUseStatements( ImportedModuleDefinition > = {}; - typeInfo.importedModuleTypes.forEach((value) => { + abi.importedModuleTypes.forEach((value) => { importedModuleByNamespace[value.namespace] = value; }); @@ -106,7 +106,7 @@ export async function resolveUseStatements( }) .reduce((o1, o2) => ({ ...o1, ...o2 })); - typeInfo.interfaceTypes.push( + abi.interfaceTypes.push( createInterfaceDefinition({ type: parsedUse.namespace, uri: importedModule.uri, @@ -123,7 +123,7 @@ export async function resolveImportsAndParseSchemas( schemaPath: string, resolvers: SchemaResolvers, noValidate = false -): Promise { +): Promise { const importKeywordCapture = /^#+["{3}]*import\s/gm; const externalImportCapture = /#+["{3}]*import\s*(?:({[^}]+}|\*))\s*into\s*(\w+?)\s*from\s*[\"'`]([^\"'`\s]+)[\"'`]/g; const localImportCapture = /#+["{3}]*import\s*(?:({[^}]+}|\*))\s*from\s*[\"'`]([^\"'`\s]+)[\"'`]/g; @@ -159,7 +159,7 @@ export async function resolveImportsAndParseSchemas( schemaPath ); - const subTypeInfo: TypeInfo = { + const subAbi: Abi = { objectTypes: [], enumTypes: [], interfaceTypes: [], @@ -172,20 +172,20 @@ export async function resolveImportsAndParseSchemas( const externalImports = await resolveExternalImports( externalImportsToResolve, resolvers.external, - subTypeInfo + subAbi ); await resolveLocalImports( localImportsToResolve, resolvers.local, - subTypeInfo, + subAbi, resolvers ); const capabilitiesByModule = await resolveUseStatements( schema, schemaPath, - subTypeInfo + subAbi ); // Remove all import statements @@ -202,8 +202,8 @@ export async function resolveImportsAndParseSchemas( // Add the @capability directive newSchema = addCapabilityDirective(newSchema, capabilitiesByModule); - // Combine the new schema with the subTypeInfo - newSchema = header + newSchema + renderSchema(subTypeInfo, false); + // Combine the new schema with the subAbi + newSchema = header + newSchema + renderSchema(subAbi, false); newSchema = resolveInterfaces(newSchema, implementationsWithInterfaces); @@ -215,9 +215,9 @@ export async function resolveImportsAndParseSchemas( ); // Parse the newly formed schema - const typeInfo = parseSchema(newSchema, { noValidate }); + const abi = parseSchema(newSchema, { noValidate }); - return typeInfo; + return abi; } interface Namespaced { @@ -241,10 +241,10 @@ type ImportedEnumOrObject = ImportedObjectDefinition | ImportedEnumDefinition; // imported object definitions const extractObjectImportDependencies = ( importsFound: ImportMap, - rootTypeInfo: TypeInfo, + rootAbi: Abi, namespace: string, uri: string -): TypeInfoTransforms => { +): AbiTransforms => { const findImport = ( type: string, namespaceType: string, @@ -265,8 +265,8 @@ const extractObjectImportDependencies = ( if (idx === -1) { throw Error( `extractObjectImportDependencies: Cannot find the dependent type within the root type info.\n` + - `Type: ${type}\nTypeInfo: ${JSON.stringify( - rootTypeInfo + `Type: ${type}\nAbi: ${JSON.stringify( + rootAbi )}\n${namespace}\n${JSON.stringify(Object.keys(importsFound))}` ); } else if (obj === undefined) { @@ -303,8 +303,8 @@ const extractObjectImportDependencies = ( const importFound = findImport( type, namespaceType, - rootTypeInfo.objectTypes, - rootTypeInfo.importedObjectTypes, + rootAbi.objectTypes, + rootAbi.importedObjectTypes, DefinitionKind.ImportedObject ) as ImportedObjectDefinition; @@ -315,7 +315,7 @@ const extractObjectImportDependencies = ( visitObjectDefinition(importFound, { ...extractObjectImportDependencies( importsFound, - rootTypeInfo, + rootAbi, namespace, uri ), @@ -340,8 +340,8 @@ const extractObjectImportDependencies = ( const importFound = findImport( type, namespaceType, - rootTypeInfo.objectTypes, - rootTypeInfo.importedObjectTypes, + rootAbi.objectTypes, + rootAbi.importedObjectTypes, DefinitionKind.ImportedObject ) as ImportedObjectDefinition; @@ -352,7 +352,7 @@ const extractObjectImportDependencies = ( visitObjectDefinition(importFound, { ...extractObjectImportDependencies( importsFound, - rootTypeInfo, + rootAbi, namespace, uri ), @@ -372,8 +372,8 @@ const extractObjectImportDependencies = ( const importFound = findImport( def.type, namespaceType, - rootTypeInfo.enumTypes, - rootTypeInfo.importedEnumTypes, + rootAbi.enumTypes, + rootAbi.importedEnumTypes, DefinitionKind.ImportedEnum ) as ImportedEnumDefinition; @@ -387,7 +387,7 @@ const extractObjectImportDependencies = ( }; }; -const namespaceTypes = (namespace: string): TypeInfoTransforms => ({ +const namespaceTypes = (namespace: string): AbiTransforms => ({ enter: { ObjectRef: (def: ObjectRef & Namespaced) => { if (def.__namespaced) { @@ -594,7 +594,7 @@ function resolveInterfaces( async function resolveExternalImports( importsToResolve: ExternalImport[], resolveSchema: SchemaResolver, - typeInfo: TypeInfo + abi: Abi ): Promise { // Keep track of all imported object type names const typesToImport: ImportMap = {}; @@ -609,21 +609,21 @@ async function resolveExternalImports( throw Error(`Unable to resolve schema at "${uri}"`); } - // Parse the schema into TypeInfo - const extTypeInfo = parseSchema(schema); + // Parse the schema into Abi + const extAbi = parseSchema(schema); let extTypesToImport = importedTypes; // If the importedTypes array contains the catch-all "*" - // go ahead and add all extTypeInfo types to the importedTypes array + // go ahead and add all extAbi types to the importedTypes array if (extTypesToImport.indexOf("*") > -1) { extTypesToImport = [ - ...extTypeInfo.objectTypes.map((x) => x.type), - ...extTypeInfo.enumTypes.map((x) => x.type), + ...extAbi.objectTypes.map((x) => x.type), + ...extAbi.enumTypes.map((x) => x.type), ]; - if (extTypeInfo.moduleType) { - extTypesToImport.push(extTypeInfo.moduleType.type); + if (extAbi.moduleType) { + extTypesToImport.push(extAbi.moduleType.type); } } @@ -643,13 +643,13 @@ async function resolveExternalImports( // If it's a module type if (importedType === "Module") { - if (!extTypeInfo.moduleType) { - extTypeInfo.moduleType = createModuleDefinition({}); + if (!extAbi.moduleType) { + extAbi.moduleType = createModuleDefinition({}); } - extTypes = [extTypeInfo.moduleType as ModuleDefinition]; + extTypes = [extAbi.moduleType as ModuleDefinition]; visitorFunc = visitModuleDefinition; - const type = extTypeInfo.moduleType as ModuleDefinition; + const type = extAbi.moduleType as ModuleDefinition; trueType = { ...createImportedModuleDefinition({ ...type, @@ -665,27 +665,27 @@ async function resolveExternalImports( `Cannot import an import's imported module type. Tried to import ${importedType} from ${uri}.` ); } else { - const objIdx = extTypeInfo.objectTypes.findIndex( + const objIdx = extAbi.objectTypes.findIndex( (def) => def.type === importedType ); const impObjIdx = objIdx === -1 && - extTypeInfo.importedObjectTypes.findIndex( + extAbi.importedObjectTypes.findIndex( (def) => def.type === importedType ); const enumIdx = impObjIdx === -1 && - extTypeInfo.enumTypes.findIndex((def) => def.type === importedType); + extAbi.enumTypes.findIndex((def) => def.type === importedType); const impEnumIdx = enumIdx === -1 && - extTypeInfo.importedEnumTypes.findIndex( + extAbi.importedEnumTypes.findIndex( (def) => def.type === importedType ); if (objIdx > -1) { - extTypes = extTypeInfo.objectTypes; + extTypes = extAbi.objectTypes; visitorFunc = visitObjectDefinition; - const type = extTypeInfo.objectTypes[objIdx]; + const type = extAbi.objectTypes[objIdx]; trueType = { ...createImportedObjectDefinition({ ...type, @@ -699,9 +699,9 @@ async function resolveExternalImports( properties: type.properties, }; } else if (impObjIdx !== false && impObjIdx > -1) { - extTypes = extTypeInfo.importedObjectTypes; + extTypes = extAbi.importedObjectTypes; visitorFunc = visitObjectDefinition; - const type = extTypeInfo.importedObjectTypes[impObjIdx]; + const type = extAbi.importedObjectTypes[impObjIdx]; trueType = { ...createImportedObjectDefinition({ ...type, @@ -715,9 +715,9 @@ async function resolveExternalImports( properties: type.properties, }; } else if (enumIdx !== false && enumIdx > -1) { - extTypes = extTypeInfo.enumTypes; + extTypes = extAbi.enumTypes; visitorFunc = visitEnumDefinition; - const type = extTypeInfo.enumTypes[enumIdx]; + const type = extAbi.enumTypes[enumIdx]; trueType = createImportedEnumDefinition({ ...type, type: appendNamespace(namespace, importedType), @@ -728,9 +728,9 @@ async function resolveExternalImports( namespace, }); } else if (impEnumIdx !== false && impEnumIdx > -1) { - extTypes = extTypeInfo.importedEnumTypes; + extTypes = extAbi.importedEnumTypes; visitorFunc = visitEnumDefinition; - const type = extTypeInfo.importedEnumTypes[impEnumIdx]; + const type = extAbi.importedEnumTypes[impEnumIdx]; trueType = createImportedEnumDefinition({ ...type, type: appendNamespace(namespace, importedType), @@ -762,7 +762,7 @@ async function resolveExternalImports( continue; } - // Append the base type to our TypeInfo + // Append the base type to our Abi typesToImport[namespacedType] = { ...trueType, __namespaced: true, @@ -771,16 +771,11 @@ async function resolveExternalImports( // Extract all object dependencies visitorFunc( trueType, - extractObjectImportDependencies( - typesToImport, - extTypeInfo, - namespace, - uri - ) + extractObjectImportDependencies(typesToImport, extAbi, namespace, uri) ); } - // Add all imported types into the aggregate TypeInfo + // Add all imported types into the aggregate Abi for (const importName of Object.keys(typesToImport)) { const importType = typesToImport[importName]; let destArray: @@ -790,27 +785,27 @@ async function resolveExternalImports( let append; if (importType.kind === DefinitionKind.ImportedObject) { - destArray = typeInfo.importedObjectTypes; + destArray = abi.importedObjectTypes; append = () => { const importDef = importType as ImportedObjectDefinition; // Namespace all object types - typeInfo.importedObjectTypes.push( + abi.importedObjectTypes.push( visitImportedObjectDefinition(importDef, namespaceTypes(namespace)) ); }; } else if (importType.kind === DefinitionKind.ImportedModule) { - destArray = typeInfo.importedModuleTypes; + destArray = abi.importedModuleTypes; append = () => { const importDef = importType as ImportedModuleDefinition; // Namespace all object types - typeInfo.importedModuleTypes.push( + abi.importedModuleTypes.push( visitImportedModuleDefinition(importDef, namespaceTypes(namespace)) ); }; } else if (importType.kind === DefinitionKind.ImportedEnum) { - destArray = typeInfo.importedEnumTypes; + destArray = abi.importedEnumTypes; append = () => { - typeInfo.importedEnumTypes.push( + abi.importedEnumTypes.push( visitImportedEnumDefinition( importType as ImportedEnumDefinition, namespaceTypes(namespace) @@ -849,7 +844,7 @@ async function resolveExternalImports( async function resolveLocalImports( importsToResolve: LocalImport[], resolveSchema: SchemaResolver, - typeInfo: TypeInfo, + abi: Abi, resolvers: SchemaResolvers ): Promise { for (const importToResolve of importsToResolve) { @@ -867,8 +862,8 @@ async function resolveLocalImports( schema = addHeader(schema); } - // Parse the schema into TypeInfo - const localTypeInfo = await resolveImportsAndParseSchemas( + // Parse the schema into Abi + const localAbi = await resolveImportsAndParseSchemas( schema, path, resolvers, @@ -878,15 +873,15 @@ async function resolveLocalImports( let extTypesToImport = importedTypes; // If the importedTypes array contains the catch-all "*" - // go ahead and add all extTypeInfo types to the importedTypes array + // go ahead and add all extAbi types to the importedTypes array if (extTypesToImport.indexOf("*") > -1) { extTypesToImport = [ - ...localTypeInfo.objectTypes.map((x) => x.type), - ...localTypeInfo.enumTypes.map((x) => x.type), + ...localAbi.objectTypes.map((x) => x.type), + ...localAbi.enumTypes.map((x) => x.type), ]; - if (localTypeInfo.moduleType) { - extTypesToImport.push(localTypeInfo.moduleType.type); + if (localAbi.moduleType) { + extTypesToImport.push(localAbi.moduleType.type); } } @@ -906,33 +901,29 @@ async function resolveLocalImports( if (isEnvType(importedType)) { visitorFunc = visitEnvDefinition; type = isClientEnvType(importedType) - ? localTypeInfo.envType.client - : localTypeInfo.envType.sanitized; + ? localAbi.envType.client + : localAbi.envType.sanitized; } else { - const objectIdx = localTypeInfo.objectTypes.findIndex( + const objectIdx = localAbi.objectTypes.findIndex( (type) => type.type === importedType ); const enumIdx = objectIdx === -1 && - localTypeInfo.enumTypes.findIndex( - (type) => type.type === importedType - ); + localAbi.enumTypes.findIndex((type) => type.type === importedType); if (objectIdx > -1) { visitorFunc = visitObjectDefinition; - type = localTypeInfo.objectTypes[objectIdx]; + type = localAbi.objectTypes[objectIdx]; } else if (enumIdx > -1) { visitorFunc = visitEnumDefinition; - type = localTypeInfo.enumTypes.find( - (type) => type.type === importedType - ); + type = localAbi.enumTypes.find((type) => type.type === importedType); } } if (!type) { throw Error( - `Cannot find type "${importedType}" in the schema at ${path}.\nFound: [ ${localTypeInfo.objectTypes.map( + `Cannot find type "${importedType}" in the schema at ${path}.\nFound: [ ${localAbi.objectTypes.map( (type) => type.type + " " )}]` ); @@ -954,8 +945,8 @@ async function resolveLocalImports( if (idx === -1) { throw Error( - `resolveLocalImports: Cannot find the requested type within the TypeInfo.\n` + - `Type: ${def.type}\nTypeInfo: ${JSON.stringify(localTypeInfo)}` + `resolveLocalImports: Cannot find the requested type within the Abi.\n` + + `Type: ${def.type}\nAbi: ${JSON.stringify(localAbi)}` ); } @@ -983,22 +974,22 @@ async function resolveLocalImports( enter: { ObjectRef: (def: ObjectRef) => { return findImport(def, [ - ...localTypeInfo.objectTypes, - ...localTypeInfo.importedObjectTypes, + ...localAbi.objectTypes, + ...localAbi.importedObjectTypes, ]); }, EnumRef: (def: EnumRef) => { return findImport(def, [ - ...localTypeInfo.enumTypes, - ...localTypeInfo.importedEnumTypes, + ...localAbi.enumTypes, + ...localAbi.importedEnumTypes, ]); }, InterfaceImplementedDefinition: ( def: InterfaceImplementedDefinition ) => { return findImport(def, [ - ...localTypeInfo.objectTypes, - ...localTypeInfo.importedObjectTypes, + ...localAbi.objectTypes, + ...localAbi.importedObjectTypes, ]); }, }, @@ -1009,78 +1000,69 @@ async function resolveLocalImports( visitType(type); } - // Add all imported types into the aggregate TypeInfo + // Add all imported types into the aggregate Abi for (const importType of Object.keys(typesToImport)) { if (isEnvType(importType)) { if (isClientEnvType(importType)) { - if (!typeInfo.envType.client) { - typeInfo.envType.client = createObjectDefinition({ + if (!abi.envType.client) { + abi.envType.client = createObjectDefinition({ type: envTypes.ClientEnv, }); } - const sharedEnv = localTypeInfo.envType.client as ObjectDefinition; + const sharedEnv = localAbi.envType.client as ObjectDefinition; - checkDuplicateEnvProperties( - typeInfo.envType.client, - sharedEnv.properties - ); + checkDuplicateEnvProperties(abi.envType.client, sharedEnv.properties); - typeInfo.envType.client.properties.push(...sharedEnv.properties); + abi.envType.client.properties.push(...sharedEnv.properties); } else { - if (!typeInfo.envType.sanitized) { - typeInfo.envType.sanitized = createObjectDefinition({ + if (!abi.envType.sanitized) { + abi.envType.sanitized = createObjectDefinition({ type: envTypes.Env, }); } - const sharedEnv = localTypeInfo.envType.sanitized as ObjectDefinition; + const sharedEnv = localAbi.envType.sanitized as ObjectDefinition; checkDuplicateEnvProperties( - typeInfo.envType.sanitized, + abi.envType.sanitized, sharedEnv.properties ); - typeInfo.envType.sanitized.properties.push(...sharedEnv.properties); + abi.envType.sanitized.properties.push(...sharedEnv.properties); } } else if ( isKind(typesToImport[importType], DefinitionKind.ImportedObject) ) { if ( - typeInfo.importedObjectTypes.findIndex( + abi.importedObjectTypes.findIndex( (def) => def.type === importType ) === -1 ) { - typeInfo.importedObjectTypes.push( + abi.importedObjectTypes.push( typesToImport[importType] as ImportedObjectDefinition ); } } else if (isKind(typesToImport[importType], DefinitionKind.Object)) { if ( - typeInfo.objectTypes.findIndex((def) => def.type === importType) === - -1 + abi.objectTypes.findIndex((def) => def.type === importType) === -1 ) { - typeInfo.objectTypes.push( - typesToImport[importType] as ObjectDefinition - ); + abi.objectTypes.push(typesToImport[importType] as ObjectDefinition); } } else if ( isKind(typesToImport[importType], DefinitionKind.ImportedEnum) ) { if ( - typeInfo.importedEnumTypes.findIndex( - (def) => def.type === importType - ) === -1 + abi.importedEnumTypes.findIndex((def) => def.type === importType) === + -1 ) { - typeInfo.importedEnumTypes.push( + abi.importedEnumTypes.push( typesToImport[importType] as ImportedEnumDefinition ); } } else if (isKind(typesToImport[importType], DefinitionKind.Enum)) { - if ( - typeInfo.enumTypes.findIndex((def) => def.type === importType) === -1 - ) { - typeInfo.enumTypes.push(typesToImport[importType] as EnumDefinition); + if (abi.enumTypes.findIndex((def) => def.type === importType) === -1) { + abi.enumTypes.push(typesToImport[importType] as EnumDefinition); } } } diff --git a/packages/schema/compose/src/templates/schema.mustache.ts b/packages/schema/compose/src/templates/schema.mustache.ts index 6a5c157e78..7eaa1fce62 100644 --- a/packages/schema/compose/src/templates/schema.mustache.ts +++ b/packages/schema/compose/src/templates/schema.mustache.ts @@ -1,5 +1,5 @@ const template = ` -{{#typeInfo}} +{{#abi}} {{#moduleType}}{{#comment}} """ {{comment}} @@ -171,6 +171,6 @@ enum {{type}} @imported( } {{/importedEnumTypes}} -### Imported Objects END ###{{/typeInfo}}`; +### Imported Objects END ###{{/abi}}`; export { template }; diff --git a/packages/schema/parse/src/__tests__/index.ts b/packages/schema/parse/src/__tests__/index.ts index fa569a9e3c..ca1214c716 100644 --- a/packages/schema/parse/src/__tests__/index.ts +++ b/packages/schema/parse/src/__tests__/index.ts @@ -1,4 +1,4 @@ -import { TypeInfo } from "../typeInfo"; +import { Abi } from "../abi"; import path from "path"; import { readdirSync, Dirent } from "fs"; @@ -14,7 +14,7 @@ const root = GetPathToParseTestFiles(); export type TestCase = { name: string; input: string; - output: TypeInfo; + output: Abi; }; export type TestCases = { @@ -71,8 +71,8 @@ async function importCase( // Fetch the input schema const input = readFileIfExists("input.graphql", directory); - // Fetch the output TypeInfo - const output = await readNamedExportIfExists("typeInfo", "output.ts", directory); + // Fetch the output Abi + const output = await readNamedExportIfExists("abi", "output.ts", directory); if (!input) { console.error(`Missing input file "input.graphql" for test case "${name}" at ${directory}`); diff --git a/packages/schema/parse/src/__tests__/transforms.spec.ts b/packages/schema/parse/src/__tests__/transforms.spec.ts index 6556e482ec..ede85de89c 100644 --- a/packages/schema/parse/src/__tests__/transforms.spec.ts +++ b/packages/schema/parse/src/__tests__/transforms.spec.ts @@ -6,7 +6,7 @@ import { createScalarPropertyDefinition, ObjectDefinition, PropertyDefinition, - TypeInfo, + Abi, createModuleDefinition, ModuleDefinition, createMethodDefinition, @@ -14,7 +14,7 @@ import { createImportedModuleDefinition, ImportedModuleDefinition, createEnvDefinition -} from "../typeInfo"; +} from "../abi"; const schema1 = ` type MyType { @@ -68,12 +68,12 @@ type AnotherType { } `; -describe("Polywrap Schema TypeInfo Transformations", () => { +describe("Polywrap Schema Abi Transformations", () => { it("addFirstLast", () => { - const typeInfo = parseSchema(schema1, { + const abi = parseSchema(schema1, { transforms: [addFirstLast], }); - const expected: TypeInfo = { + const expected: Abi = { envType: createEnvDefinition({}), enumTypes: [], importedEnumTypes: [], @@ -276,18 +276,18 @@ describe("Polywrap Schema TypeInfo Transformations", () => { ], }; - expect(typeInfo).toMatchObject(expected); + expect(abi).toMatchObject(expected); }); it("extendType", () => { - const typeInfo = parseSchema(schema2, { + const abi = parseSchema(schema2, { transforms: [ extendType({ foo: "bar", }), ], }); - const expected: TypeInfo = { + const expected: Abi = { envType: createEnvDefinition({}), enumTypes: [], interfaceTypes: [], @@ -334,6 +334,6 @@ describe("Polywrap Schema TypeInfo Transformations", () => { importedModuleTypes: [], }; - expect(typeInfo).toMatchObject(expected); + expect(abi).toMatchObject(expected); }); }); diff --git a/packages/schema/parse/src/typeInfo/definitions.ts b/packages/schema/parse/src/abi/definitions.ts similarity index 100% rename from packages/schema/parse/src/typeInfo/definitions.ts rename to packages/schema/parse/src/abi/definitions.ts diff --git a/packages/schema/parse/src/typeInfo/env.ts b/packages/schema/parse/src/abi/env.ts similarity index 100% rename from packages/schema/parse/src/typeInfo/env.ts rename to packages/schema/parse/src/abi/env.ts diff --git a/packages/schema/parse/src/typeInfo/index.ts b/packages/schema/parse/src/abi/index.ts similarity index 81% rename from packages/schema/parse/src/typeInfo/index.ts rename to packages/schema/parse/src/abi/index.ts index f4d82cb279..99c701808a 100644 --- a/packages/schema/parse/src/typeInfo/index.ts +++ b/packages/schema/parse/src/abi/index.ts @@ -20,7 +20,7 @@ export * from "./module"; export * from "./env"; export * from "./map"; -export interface TypeInfo { +export interface Abi { objectTypes: ObjectDefinition[]; moduleType?: ModuleDefinition; enumTypes: EnumDefinition[]; @@ -31,7 +31,7 @@ export interface TypeInfo { envType: EnvDefinition; } -export function createTypeInfo(): TypeInfo { +export function createAbi(): Abi { return { objectTypes: [], enumTypes: [], @@ -45,8 +45,8 @@ export function createTypeInfo(): TypeInfo { type ImportedDefinition = ImportedObjectDefinition | ImportedModuleDefinition; -export function combineTypeInfo(typeInfos: TypeInfo[]): TypeInfo { - const combined: TypeInfo = { +export function combineAbi(abis: Abi[]): Abi { + const combined: Abi = { objectTypes: [], moduleType: createModuleDefinition({}), enumTypes: [], @@ -64,18 +64,18 @@ export function combineTypeInfo(typeInfos: TypeInfo[]): TypeInfo { return a.uri === b.uri && a.nativeType === b.nativeType; }; - for (const typeInfo of typeInfos) { - for (const enumType of typeInfo.enumTypes) { + for (const abi of abis) { + for (const enumType of abi.enumTypes) { tryInsert(combined.enumTypes, enumType); } - for (const objectType of typeInfo.objectTypes) { + for (const objectType of abi.objectTypes) { tryInsert(combined.objectTypes, objectType); } - combined.moduleType = typeInfo.moduleType; + combined.moduleType = abi.moduleType; - for (const interfaceType of typeInfo.interfaceTypes) { + for (const interfaceType of abi.interfaceTypes) { tryInsert( combined.interfaceTypes, interfaceType, @@ -107,7 +107,7 @@ export function combineTypeInfo(typeInfos: TypeInfo[]): TypeInfo { ); } - for (const importedObjectType of typeInfo.importedObjectTypes) { + for (const importedObjectType of abi.importedObjectTypes) { tryInsert( combined.importedObjectTypes, importedObjectType, @@ -115,7 +115,7 @@ export function combineTypeInfo(typeInfos: TypeInfo[]): TypeInfo { ); } - for (const importedModuleType of typeInfo.importedModuleTypes) { + for (const importedModuleType of abi.importedModuleTypes) { tryInsert( combined.importedModuleTypes, importedModuleType, @@ -126,16 +126,16 @@ export function combineTypeInfo(typeInfos: TypeInfo[]): TypeInfo { ); } - for (const importedEnumType of typeInfo.importedEnumTypes) { + for (const importedEnumType of abi.importedEnumTypes) { tryInsert(combined.importedEnumTypes, importedEnumType); } - if (typeInfo.envType.client) { - combined.envType.client = typeInfo.envType.client; + if (abi.envType.client) { + combined.envType.client = abi.envType.client; } - if (typeInfo.envType.sanitized) { - combined.envType.sanitized = typeInfo.envType.sanitized; + if (abi.envType.sanitized) { + combined.envType.sanitized = abi.envType.sanitized; } } @@ -166,7 +166,7 @@ const tryInsert = ( const valueType = JSON.stringify(value); if (destType !== valueType) { throw Error( - `combineTypeInfo found two types by the same type that are not equivalent.\n` + + `combineAbi found two types by the same type that are not equivalent.\n` + `Type: "${value.type}"\nObject A: ${destType}\nObject B: ${valueType}` ); } diff --git a/packages/schema/parse/src/typeInfo/map.ts b/packages/schema/parse/src/abi/map.ts similarity index 100% rename from packages/schema/parse/src/typeInfo/map.ts rename to packages/schema/parse/src/abi/map.ts diff --git a/packages/schema/parse/src/typeInfo/module.ts b/packages/schema/parse/src/abi/module.ts similarity index 100% rename from packages/schema/parse/src/typeInfo/module.ts rename to packages/schema/parse/src/abi/module.ts diff --git a/packages/schema/parse/src/typeInfo/scalar.ts b/packages/schema/parse/src/abi/scalar.ts similarity index 100% rename from packages/schema/parse/src/typeInfo/scalar.ts rename to packages/schema/parse/src/abi/scalar.ts diff --git a/packages/schema/parse/src/extract/enum-types.ts b/packages/schema/parse/src/extract/enum-types.ts index da2a9401e4..ae43225c42 100644 --- a/packages/schema/parse/src/extract/enum-types.ts +++ b/packages/schema/parse/src/extract/enum-types.ts @@ -1,4 +1,4 @@ -import { TypeInfo, EnumDefinition, createEnumDefinition } from "../typeInfo"; +import { Abi, EnumDefinition, createEnumDefinition } from "../abi"; import { ASTVisitor, DirectiveNode, EnumTypeDefinitionNode } from "graphql"; @@ -30,6 +30,6 @@ const visitorEnter = (enumTypes: EnumDefinition[]) => ({ }, }); -export const getEnumTypesVisitor = (typeInfo: TypeInfo): ASTVisitor => ({ - enter: visitorEnter(typeInfo.enumTypes), +export const getEnumTypesVisitor = (abi: Abi): ASTVisitor => ({ + enter: visitorEnter(abi.enumTypes), }); diff --git a/packages/schema/parse/src/extract/env-types.ts b/packages/schema/parse/src/extract/env-types.ts index 0fe22def4d..8ccf2575fb 100644 --- a/packages/schema/parse/src/extract/env-types.ts +++ b/packages/schema/parse/src/extract/env-types.ts @@ -1,10 +1,10 @@ import { - TypeInfo, + Abi, createObjectDefinition, EnvDefinition, isEnvType, isClientEnvType, -} from "../typeInfo"; +} from "../abi"; import { extractFieldDefinition, extractListType, @@ -62,11 +62,11 @@ const visitorLeave = (state: State) => ({ }, }); -export function getEnvVisitor(typeInfo: TypeInfo): ASTVisitor { +export function getEnvVisitor(abi: Abi): ASTVisitor { const state: State = {}; return { - enter: visitorEnter(typeInfo.envType, state), + enter: visitorEnter(abi.envType, state), leave: visitorLeave(state), }; } diff --git a/packages/schema/parse/src/extract/imported-enum-types.ts b/packages/schema/parse/src/extract/imported-enum-types.ts index e5ae637623..8faf6d04c1 100644 --- a/packages/schema/parse/src/extract/imported-enum-types.ts +++ b/packages/schema/parse/src/extract/imported-enum-types.ts @@ -1,8 +1,8 @@ import { - TypeInfo, + Abi, createImportedEnumDefinition, ImportedEnumDefinition, -} from "../typeInfo"; +} from "../abi"; import { extractImportedDefinition } from "./utils/imported-types-utils"; import { ASTVisitor, EnumTypeDefinitionNode } from "graphql"; @@ -34,8 +34,6 @@ const visitorEnter = (importedEnumTypes: ImportedEnumDefinition[]) => ({ }, }); -export const getImportedEnumTypesVisitor = ( - typeInfo: TypeInfo -): ASTVisitor => ({ - enter: visitorEnter(typeInfo.importedEnumTypes), +export const getImportedEnumTypesVisitor = (abi: Abi): ASTVisitor => ({ + enter: visitorEnter(abi.importedEnumTypes), }); diff --git a/packages/schema/parse/src/extract/imported-module-types.ts b/packages/schema/parse/src/extract/imported-module-types.ts index 1b4e9e51f6..ad9cd253bb 100644 --- a/packages/schema/parse/src/extract/imported-module-types.ts +++ b/packages/schema/parse/src/extract/imported-module-types.ts @@ -5,8 +5,8 @@ import { createPropertyDefinition, ImportedModuleDefinition, MapDefinition, - TypeInfo, -} from "../typeInfo"; + Abi, +} from "../abi"; import { extractImportedDefinition } from "./utils/imported-types-utils"; import { extractInputValueDefinition, @@ -114,13 +114,11 @@ const visitorLeave = (state: State) => ({ }, }); -export const getImportedModuleTypesVisitor = ( - typeInfo: TypeInfo -): ASTVisitor => { +export const getImportedModuleTypesVisitor = (abi: Abi): ASTVisitor => { const state: State = {}; return { - enter: visitorEnter(typeInfo.importedModuleTypes, state), + enter: visitorEnter(abi.importedModuleTypes, state), leave: visitorLeave(state), }; }; diff --git a/packages/schema/parse/src/extract/imported-object-types.ts b/packages/schema/parse/src/extract/imported-object-types.ts index 6e5eb73287..6a9fb15134 100644 --- a/packages/schema/parse/src/extract/imported-object-types.ts +++ b/packages/schema/parse/src/extract/imported-object-types.ts @@ -1,9 +1,9 @@ import { - TypeInfo, + Abi, ImportedObjectDefinition, createImportedObjectDefinition, createInterfaceImplementedDefinition, -} from "../typeInfo"; +} from "../abi"; import { extractFieldDefinition, extractListType, @@ -71,13 +71,11 @@ const visitorLeave = (state: State) => ({ }, }); -export const getImportedObjectTypesVisitor = ( - typeInfo: TypeInfo -): ASTVisitor => { +export const getImportedObjectTypesVisitor = (abi: Abi): ASTVisitor => { const state: State = {}; return { - enter: visitorEnter(typeInfo.importedObjectTypes, state), + enter: visitorEnter(abi.importedObjectTypes, state), leave: visitorLeave(state), }; }; diff --git a/packages/schema/parse/src/extract/index.ts b/packages/schema/parse/src/extract/index.ts index 24ab46699b..09f6f1616c 100644 --- a/packages/schema/parse/src/extract/index.ts +++ b/packages/schema/parse/src/extract/index.ts @@ -1,4 +1,4 @@ -import { TypeInfo } from "../typeInfo"; +import { Abi } from "../abi"; import { getEnumTypesVisitor } from "./enum-types"; import { getObjectTypesVisitor } from "./object-types"; import { getModuleTypesVisitor } from "./module-types"; @@ -9,7 +9,7 @@ import { getEnvVisitor } from "./env-types"; import { ASTVisitor } from "graphql"; -export type SchemaExtractorBuilder = (typeInfo: TypeInfo) => ASTVisitor; +export type SchemaExtractorBuilder = (abi: Abi) => ASTVisitor; export const extractors: SchemaExtractorBuilder[] = [ getEnumTypesVisitor, diff --git a/packages/schema/parse/src/extract/module-types.ts b/packages/schema/parse/src/extract/module-types.ts index c7edf10dcd..7106228373 100644 --- a/packages/schema/parse/src/extract/module-types.ts +++ b/packages/schema/parse/src/extract/module-types.ts @@ -1,5 +1,5 @@ import { - TypeInfo, + Abi, createModuleDefinition, createMethodDefinition, createPropertyDefinition, @@ -10,7 +10,7 @@ import { InterfaceDefinition, capabilityTypes, MapDefinition, -} from "../typeInfo"; +} from "../abi"; import { extractInputValueDefinition, extractListType, @@ -32,7 +32,7 @@ import { ASTVisitor, } from "graphql"; -const visitorEnter = (typeInfo: TypeInfo, state: State) => ({ +const visitorEnter = (abi: Abi, state: State) => ({ ObjectTypeDefinition: (node: ObjectTypeDefinitionNode) => { const nodeName = node.name.value; @@ -53,7 +53,7 @@ const visitorEnter = (typeInfo: TypeInfo, state: State) => ({ comment: node.description?.value, }); - typeInfo.moduleType = module; + abi.moduleType = module; state.currentModule = module; }, FieldDefinition: (node: FieldDefinitionNode) => { @@ -263,13 +263,10 @@ const parseImportsDirective = ( return imports; }; -const visitorLeave = (typeInfo: TypeInfo, state: State) => ({ +const visitorLeave = (abi: Abi, state: State) => ({ ObjectTypeDefinition: (_node: ObjectTypeDefinitionNode) => { if (state.currentInterfaces) { - typeInfo.interfaceTypes = [ - ...typeInfo.interfaceTypes, - ...state.currentInterfaces, - ]; + abi.interfaceTypes = [...abi.interfaceTypes, ...state.currentInterfaces]; } state.currentInterfaces = undefined; @@ -287,11 +284,11 @@ const visitorLeave = (typeInfo: TypeInfo, state: State) => ({ }, }); -export const getModuleTypesVisitor = (typeInfo: TypeInfo): ASTVisitor => { +export const getModuleTypesVisitor = (abi: Abi): ASTVisitor => { const state: State = {}; return { - enter: visitorEnter(typeInfo, state), - leave: visitorLeave(typeInfo, state), + enter: visitorEnter(abi, state), + leave: visitorLeave(abi, state), }; }; diff --git a/packages/schema/parse/src/extract/object-types.ts b/packages/schema/parse/src/extract/object-types.ts index 1e94ae52e9..96640242f6 100644 --- a/packages/schema/parse/src/extract/object-types.ts +++ b/packages/schema/parse/src/extract/object-types.ts @@ -1,11 +1,11 @@ import { - TypeInfo, + Abi, ObjectDefinition, createObjectDefinition, createInterfaceImplementedDefinition, isModuleType, isEnvType, -} from "../typeInfo"; +} from "../abi"; import { extractFieldDefinition, extractListType, @@ -79,11 +79,11 @@ const visitorLeave = (state: State) => ({ }, }); -export const getObjectTypesVisitor = (typeInfo: TypeInfo): ASTVisitor => { +export const getObjectTypesVisitor = (abi: Abi): ASTVisitor => { const state: State = {}; return { - enter: visitorEnter(typeInfo.objectTypes, state), + enter: visitorEnter(abi.objectTypes, state), leave: visitorLeave(state), }; }; diff --git a/packages/schema/parse/src/extract/utils/imported-types-utils.ts b/packages/schema/parse/src/extract/utils/imported-types-utils.ts index d3b93f2fc1..04ae2e2b67 100644 --- a/packages/schema/parse/src/extract/utils/imported-types-utils.ts +++ b/packages/schema/parse/src/extract/utils/imported-types-utils.ts @@ -1,4 +1,4 @@ -import { ImportedDefinition, MODULE_NAME } from "../../typeInfo"; +import { ImportedDefinition, MODULE_NAME } from "../../abi"; import { DirectiveNode, TypeDefinitionNode } from "graphql"; diff --git a/packages/schema/parse/src/extract/utils/map-utils.ts b/packages/schema/parse/src/extract/utils/map-utils.ts index ed3ab3df73..3f823a2745 100644 --- a/packages/schema/parse/src/extract/utils/map-utils.ts +++ b/packages/schema/parse/src/extract/utils/map-utils.ts @@ -9,7 +9,7 @@ import { isMapKeyType, } from "../.."; -type CurrentTypeInfo = { +type CurrentAbi = { currentType: string; subType: string | null; required: boolean; @@ -17,7 +17,7 @@ type CurrentTypeInfo = { // TODO: Make sure map also works for imported types and modules -const _parseCurrentType = (rootType: string, type: string): CurrentTypeInfo => { +const _parseCurrentType = (rootType: string, type: string): CurrentAbi => { let required = false; if (type.startsWith("[")) { const closeSquareBracketIdx = type.lastIndexOf("]"); @@ -173,7 +173,7 @@ const _parseMapType = ( } }; -export function parseCurrentType(type: string): CurrentTypeInfo { +export function parseCurrentType(type: string): CurrentAbi { return _parseCurrentType(type, type); } diff --git a/packages/schema/parse/src/extract/utils/module-types-utils.ts b/packages/schema/parse/src/extract/utils/module-types-utils.ts index a73ad462dd..944c422917 100644 --- a/packages/schema/parse/src/extract/utils/module-types-utils.ts +++ b/packages/schema/parse/src/extract/utils/module-types-utils.ts @@ -7,7 +7,7 @@ import { createArrayDefinition, InterfaceDefinition, MapDefinition, -} from "../../typeInfo"; +} from "../../abi"; import { setPropertyType } from "./property-utils"; import { extractAnnotateDirective } from "./object-types-utils"; diff --git a/packages/schema/parse/src/extract/utils/object-types-utils.ts b/packages/schema/parse/src/extract/utils/object-types-utils.ts index d420b8387b..9c9a926199 100644 --- a/packages/schema/parse/src/extract/utils/object-types-utils.ts +++ b/packages/schema/parse/src/extract/utils/object-types-utils.ts @@ -5,7 +5,7 @@ import { MapDefinition, ObjectDefinition, PropertyDefinition, -} from "../../typeInfo"; +} from "../../abi"; import { parseMapType } from "./map-utils"; import { setPropertyType } from "./property-utils"; diff --git a/packages/schema/parse/src/extract/utils/property-utils.ts b/packages/schema/parse/src/extract/utils/property-utils.ts index f6dab32ccd..2500f88f9f 100644 --- a/packages/schema/parse/src/extract/utils/property-utils.ts +++ b/packages/schema/parse/src/extract/utils/property-utils.ts @@ -4,7 +4,7 @@ import { createUnresolvedObjectOrEnumRef, isScalarType, PropertyDefinition, -} from "../../typeInfo"; +} from "../../abi"; const toBoolean = (val: unknown) => (val ? true : false); diff --git a/packages/schema/parse/src/index.ts b/packages/schema/parse/src/index.ts index 1f32d6657f..e64cb3d665 100644 --- a/packages/schema/parse/src/index.ts +++ b/packages/schema/parse/src/index.ts @@ -1,27 +1,24 @@ -import { TypeInfo, createTypeInfo } from "./typeInfo"; +import { Abi, createAbi } from "./abi"; import { extractors, SchemaExtractorBuilder } from "./extract"; -import { TypeInfoTransforms, transformTypeInfo } from "./transform"; +import { AbiTransforms, transformAbi } from "./transform"; import { finalizePropertyDef } from "./transform/finalizePropertyDef"; import { validators } from "./validate"; import { SchemaValidatorBuilder } from "./validate"; import { DocumentNode, parse, visit, visitInParallel } from "graphql"; -export * from "./typeInfo"; +export * from "./abi"; export * from "./transform"; export * from "./header"; interface ParserOptions { extractors?: SchemaExtractorBuilder[]; - transforms?: TypeInfoTransforms[]; + transforms?: AbiTransforms[]; validators?: SchemaValidatorBuilder[]; noValidate?: boolean; } -export function parseSchema( - schema: string, - options: ParserOptions = {} -): TypeInfo { +export function parseSchema(schema: string, options: ParserOptions = {}): Abi { const astNode = parse(schema); // Validate GraphQL Schema @@ -30,18 +27,18 @@ export function parseSchema( validate(astNode, validates); } - // Extract & Build TypeInfo - let info = createTypeInfo(); + // Extract & Build Abi + let info = createAbi(); const extracts = options.extractors || extractors; extract(astNode, info, extracts); - // Finalize & Transform TypeInfo - info = transformTypeInfo(info, finalizePropertyDef(info)); + // Finalize & Transform Abi + info = transformAbi(info, finalizePropertyDef(info)); if (options && options.transforms) { for (const transform of options.transforms) { - info = transformTypeInfo(info, transform); + info = transformAbi(info, transform); } } @@ -67,10 +64,10 @@ const validate = ( const extract = ( astNode: DocumentNode, - typeInfo: TypeInfo, + abi: Abi, extractors: SchemaExtractorBuilder[] ) => { - const allVisitors = extractors.map((getVisitor) => getVisitor(typeInfo)); + const allVisitors = extractors.map((getVisitor) => getVisitor(abi)); visit(astNode, visitInParallel(allVisitors)); }; diff --git a/packages/schema/parse/src/transform/addAnnotations.ts b/packages/schema/parse/src/transform/addAnnotations.ts index 7c76957765..49ce397ffd 100644 --- a/packages/schema/parse/src/transform/addAnnotations.ts +++ b/packages/schema/parse/src/transform/addAnnotations.ts @@ -1,7 +1,7 @@ import { toGraphQL } from "."; -import { PropertyDefinition, TypeInfoTransforms } from ".."; +import { PropertyDefinition, AbiTransforms } from ".."; -export const addAnnotations: TypeInfoTransforms = { +export const addAnnotations: AbiTransforms = { enter: { PropertyDefinition: (def: PropertyDefinition): PropertyDefinition => { if (!def.map) return def; diff --git a/packages/schema/parse/src/transform/addFirstLast.ts b/packages/schema/parse/src/transform/addFirstLast.ts index 0e12ffd448..7e69af4f1d 100644 --- a/packages/schema/parse/src/transform/addFirstLast.ts +++ b/packages/schema/parse/src/transform/addFirstLast.ts @@ -1,7 +1,7 @@ -import { TypeInfoTransforms } from "."; -import { TypeInfo, GenericDefinition } from "../typeInfo"; +import { AbiTransforms } from "."; +import { Abi, GenericDefinition } from "../abi"; -export const addFirstLast: TypeInfoTransforms = { +export const addFirstLast: AbiTransforms = { enter: { GenericDefinition: (def: GenericDefinition): GenericDefinition => { const arrays: Record = {}; @@ -19,11 +19,11 @@ export const addFirstLast: TypeInfoTransforms = { ...arrays, }; }, - TypeInfo: (typeInfo: TypeInfo): TypeInfo => ({ - ...typeInfo, - objectTypes: setFirstLast(typeInfo.objectTypes), - importedObjectTypes: setFirstLast(typeInfo.importedObjectTypes), - importedModuleTypes: setFirstLast(typeInfo.importedModuleTypes), + Abi: (abi: Abi): Abi => ({ + ...abi, + objectTypes: setFirstLast(abi.objectTypes), + importedObjectTypes: setFirstLast(abi.importedObjectTypes), + importedModuleTypes: setFirstLast(abi.importedModuleTypes), }), }, }; diff --git a/packages/schema/parse/src/transform/extendType.ts b/packages/schema/parse/src/transform/extendType.ts index 42af13659b..e7ff93bf14 100644 --- a/packages/schema/parse/src/transform/extendType.ts +++ b/packages/schema/parse/src/transform/extendType.ts @@ -1,12 +1,12 @@ -import { TypeInfoTransforms } from "."; -import { GenericDefinition, TypeInfo } from "../typeInfo"; +import { AbiTransforms } from "."; +import { GenericDefinition, Abi } from "../abi"; // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -export function extendType(extension: any): TypeInfoTransforms { +export function extendType(extension: any): AbiTransforms { return { enter: { - TypeInfo: (typeInfo: TypeInfo) => ({ - ...typeInfo, + Abi: (abi: Abi) => ({ + ...abi, extension, }), // eslint-disable-next-line @typescript-eslint/naming-convention diff --git a/packages/schema/parse/src/transform/finalizePropertyDef.ts b/packages/schema/parse/src/transform/finalizePropertyDef.ts index adf93c882d..831cf84cdb 100644 --- a/packages/schema/parse/src/transform/finalizePropertyDef.ts +++ b/packages/schema/parse/src/transform/finalizePropertyDef.ts @@ -1,19 +1,19 @@ -import { TypeInfoTransforms } from "."; +import { AbiTransforms } from "."; import { ArrayDefinition, createEnumRef, createObjectRef, GenericDefinition, PropertyDefinition, - TypeInfo, -} from "../typeInfo"; + Abi, +} from "../abi"; -export const finalizePropertyDef = (typeInfo: TypeInfo): TypeInfoTransforms => { +export const finalizePropertyDef = (abi: Abi): AbiTransforms => { return { enter: { // eslint-disable-next-line @typescript-eslint/naming-convention PropertyDefinition: (def: PropertyDefinition): PropertyDefinition => { - populatePropertyType(def, typeInfo); + populatePropertyType(def, abi); return def; }, }, @@ -22,14 +22,14 @@ export const finalizePropertyDef = (typeInfo: TypeInfo): TypeInfoTransforms => { export function populatePropertyType( property: PropertyDefinition, - typeInfo: TypeInfo + abi: Abi ): void { let propertyType: GenericDefinition | undefined; if (property.array) { - populateArrayType(property.array, typeInfo); + populateArrayType(property.array, abi); propertyType = property.array; } else if (property.unresolvedObjectOrEnum) { - propertyType = resolveObjectOrEnumKind(property, typeInfo); + propertyType = resolveObjectOrEnumKind(property, abi); } else if (property.scalar) { propertyType = property.scalar; } else if (property.object) { @@ -46,14 +46,14 @@ export function populatePropertyType( property.required = propertyType.required; } -function populateArrayType(array: ArrayDefinition, typeInfo: TypeInfo) { +function populateArrayType(array: ArrayDefinition, abi: Abi) { let baseTypeFound = false; let currentArray = array; while (!baseTypeFound) { if (currentArray.array) { currentArray = currentArray.array; - populateArrayType(currentArray, typeInfo); + populateArrayType(currentArray, abi); } else if ( currentArray.scalar || currentArray.object || @@ -75,7 +75,7 @@ function populateArrayType(array: ArrayDefinition, typeInfo: TypeInfo) { if (array.array) { array.item = array.array; } else if (array.unresolvedObjectOrEnum) { - array.item = resolveObjectOrEnumKind(array, typeInfo); + array.item = resolveObjectOrEnumKind(array, abi); } else if (array.scalar) { array.item = array.scalar; } else if (array.enum) { @@ -95,7 +95,7 @@ function populateArrayType(array: ArrayDefinition, typeInfo: TypeInfo) { function resolveObjectOrEnumKind( property: PropertyDefinition, - typeInfo: TypeInfo + abi: Abi ): GenericDefinition { if (!property.unresolvedObjectOrEnum) { throw Error("Type reference is undefined, this should never happen."); @@ -104,17 +104,15 @@ function resolveObjectOrEnumKind( const unresolved = property.unresolvedObjectOrEnum; // Check to see if the type is a part of the custom types defined inside the schema (objects, enums, envs) - let customType: GenericDefinition | undefined = typeInfo.objectTypes.find( + let customType: GenericDefinition | undefined = abi.objectTypes.find( (type) => type.type === unresolved.type ); customType = customType ? customType - : typeInfo.importedObjectTypes.find( - (type) => type.type === unresolved.type - ); + : abi.importedObjectTypes.find((type) => type.type === unresolved.type); - const envType = typeInfo.envType; + const envType = abi.envType; customType = customType ? customType : envType.client?.type === unresolved.type @@ -124,15 +122,11 @@ function resolveObjectOrEnumKind( : undefined; if (!customType) { - customType = typeInfo.enumTypes.find( - (type) => type.type === unresolved.type - ); + customType = abi.enumTypes.find((type) => type.type === unresolved.type); customType = customType ? customType - : typeInfo.importedEnumTypes.find( - (type) => type.type === unresolved.type - ); + : abi.importedEnumTypes.find((type) => type.type === unresolved.type); if (!customType) { throw new Error(`Unsupported type ${unresolved.type}`); diff --git a/packages/schema/parse/src/transform/hasImports.ts b/packages/schema/parse/src/transform/hasImports.ts index 6aa250fce4..7aac34d756 100644 --- a/packages/schema/parse/src/transform/hasImports.ts +++ b/packages/schema/parse/src/transform/hasImports.ts @@ -1,15 +1,15 @@ -import { TypeInfoTransforms } from "."; -import { TypeInfo } from "../typeInfo"; +import { AbiTransforms } from "."; +import { Abi } from "../abi"; -export const hasImports: TypeInfoTransforms = { +export const hasImports: AbiTransforms = { enter: { - TypeInfo: (typeInfo: TypeInfo) => ({ - ...typeInfo, + Abi: (abi: Abi) => ({ + ...abi, hasImports: () => { return ( - typeInfo.importedEnumTypes.length || - typeInfo.importedObjectTypes.length || - typeInfo.importedModuleTypes.length + abi.importedEnumTypes.length || + abi.importedObjectTypes.length || + abi.importedModuleTypes.length ); }, }), diff --git a/packages/schema/parse/src/transform/index.ts b/packages/schema/parse/src/transform/index.ts index 2090dff5a8..3731787176 100644 --- a/packages/schema/parse/src/transform/index.ts +++ b/packages/schema/parse/src/transform/index.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/naming-convention */ import { - TypeInfo, + Abi, GenericDefinition, ObjectDefinition, AnyDefinition, @@ -23,7 +23,7 @@ import { EnvDefinition, WithKind, MapDefinition, -} from "../typeInfo"; +} from "../abi"; export * from "./finalizePropertyDef"; export * from "./extendType"; @@ -35,13 +35,13 @@ export * from "./moduleCapabilities"; export * from "./hasImports"; export * from "./addAnnotations"; -export interface TypeInfoTransforms { - enter?: TypeInfoTransformer; - leave?: TypeInfoTransformer; +export interface AbiTransforms { + enter?: AbiTransformer; + leave?: AbiTransformer; } -export interface TypeInfoTransformer { - TypeInfo?: (typeInfo: TypeInfo) => TypeInfo; +export interface AbiTransformer { + Abi?: (abi: Abi) => Abi; GenericDefinition?: (def: GenericDefinition) => GenericDefinition; ObjectDefinition?: (def: ObjectDefinition) => ObjectDefinition; ObjectRef?: (def: ObjectRef) => ObjectRef; @@ -70,14 +70,11 @@ export interface TypeInfoTransformer { MapDefinition?: (def: MapDefinition) => MapDefinition; } -export function transformTypeInfo( - typeInfo: TypeInfo, - transforms: TypeInfoTransforms -): TypeInfo { - let result = Object.assign({}, typeInfo); +export function transformAbi(abi: Abi, transforms: AbiTransforms): Abi { + let result = Object.assign({}, abi); - if (transforms.enter && transforms.enter.TypeInfo) { - result = transforms.enter.TypeInfo(result); + if (transforms.enter && transforms.enter.Abi) { + result = transforms.enter.Abi(result); } for (let i = 0; i < result.interfaceTypes.length; ++i) { @@ -125,8 +122,8 @@ export function transformTypeInfo( result.envType = visitEnvDefinition(result.envType, transforms); - if (transforms.leave && transforms.leave.TypeInfo) { - result = transforms.leave.TypeInfo(result); + if (transforms.leave && transforms.leave.Abi) { + result = transforms.leave.Abi(result); } return result; @@ -134,7 +131,7 @@ export function transformTypeInfo( export function visitObjectDefinition( def: ObjectDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ObjectDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -158,7 +155,7 @@ export function visitObjectDefinition( export function visitObjectRef( def: ObjectRef, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ObjectRef { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -168,7 +165,7 @@ export function visitObjectRef( export function visitInterfaceImplementedDefinition( def: InterfaceImplementedDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): InterfaceImplementedDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -178,7 +175,7 @@ export function visitInterfaceImplementedDefinition( export function visitAnyDefinition( def: AnyDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): AnyDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -208,7 +205,7 @@ export function visitAnyDefinition( export function visitScalarDefinition( def: ScalarDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ScalarDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -217,17 +214,14 @@ export function visitScalarDefinition( export function visitEnumDefinition( def: EnumDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): EnumDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); return transformType(result, transforms.leave); } -export function visitEnumRef( - def: EnumRef, - transforms: TypeInfoTransforms -): EnumRef { +export function visitEnumRef(def: EnumRef, transforms: AbiTransforms): EnumRef { let result = Object.assign({}, def); result = transformType(result, transforms.enter); return transformType(result, transforms.leave); @@ -235,7 +229,7 @@ export function visitEnumRef( export function visitArrayDefinition( def: ArrayDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ArrayDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -252,7 +246,7 @@ export function visitArrayDefinition( export function visitPropertyDefinition( def: PropertyDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): PropertyDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -264,7 +258,7 @@ export function visitPropertyDefinition( export function visitMethodDefinition( def: MethodDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): MethodDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -285,7 +279,7 @@ export function visitMethodDefinition( export function visitModuleDefinition( def: ModuleDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ModuleDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -299,7 +293,7 @@ export function visitModuleDefinition( export function visitInterfaceDefinition( def: InterfaceDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): InterfaceDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -308,7 +302,7 @@ export function visitInterfaceDefinition( export function visitImportedModuleDefinition( def: ImportedModuleDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ImportedModuleDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -322,21 +316,21 @@ export function visitImportedModuleDefinition( export function visitImportedObjectDefinition( def: ImportedObjectDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ImportedObjectDefinition { return visitObjectDefinition(def, transforms) as ImportedObjectDefinition; } export function visitImportedEnumDefinition( def: ImportedEnumDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): ImportedEnumDefinition { return visitEnumDefinition(def, transforms) as ImportedEnumDefinition; } export function visitEnvDefinition( def: EnvDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): EnvDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -354,7 +348,7 @@ export function visitEnvDefinition( export function visitMapDefinition( def: MapDefinition, - transforms: TypeInfoTransforms + transforms: AbiTransforms ): MapDefinition { let result = Object.assign({}, def); result = transformType(result, transforms.enter); @@ -376,7 +370,7 @@ export function visitMapDefinition( export function transformType( type: TDefinition, - transform?: TypeInfoTransformer + transform?: AbiTransformer ): TDefinition { if (!transform) { return type; diff --git a/packages/schema/parse/src/transform/interfaceUris.ts b/packages/schema/parse/src/transform/interfaceUris.ts index 51f99faeb5..6ccc69064a 100644 --- a/packages/schema/parse/src/transform/interfaceUris.ts +++ b/packages/schema/parse/src/transform/interfaceUris.ts @@ -1,7 +1,7 @@ -import { TypeInfoTransforms } from "."; -import { TypeInfo, ModuleDefinition, ObjectDefinition } from "../typeInfo"; +import { AbiTransforms } from "."; +import { Abi, ModuleDefinition, ObjectDefinition } from "../abi"; -export function interfaceUris(): TypeInfoTransforms { +export function interfaceUris(): AbiTransforms { const uniqueInterfaceUris: Record = {}; const uniqueModuleInterfaceTypes: Record = {}; const uniqueObjectInterfaceTypes: Record = {}; @@ -22,9 +22,9 @@ export function interfaceUris(): TypeInfoTransforms { }, }, leave: { - TypeInfo: (typeInfo: TypeInfo) => { + Abi: (abi: Abi) => { for (const interfaceType of Object.keys(uniqueModuleInterfaceTypes)) { - const importedInterface = typeInfo.importedModuleTypes.find( + const importedInterface = abi.importedModuleTypes.find( (importedModule) => importedModule.type === interfaceType ); @@ -34,7 +34,7 @@ export function interfaceUris(): TypeInfoTransforms { } for (const interfaceType of Object.keys(uniqueObjectInterfaceTypes)) { - const importedInterface = typeInfo.importedObjectTypes.find( + const importedInterface = abi.importedObjectTypes.find( (importedObject) => importedObject.type === interfaceType ); @@ -44,7 +44,7 @@ export function interfaceUris(): TypeInfoTransforms { } return { - ...typeInfo, + ...abi, interfaceUris: Object.keys(uniqueInterfaceUris), }; }, diff --git a/packages/schema/parse/src/transform/methodParentPointers.ts b/packages/schema/parse/src/transform/methodParentPointers.ts index 302278a4c3..105da6cd44 100644 --- a/packages/schema/parse/src/transform/methodParentPointers.ts +++ b/packages/schema/parse/src/transform/methodParentPointers.ts @@ -1,11 +1,11 @@ -import { TypeInfoTransforms } from "."; +import { AbiTransforms } from "."; import { ModuleDefinition, ImportedModuleDefinition, MethodDefinition, -} from "../typeInfo"; +} from "../abi"; -export function methodParentPointers(): TypeInfoTransforms { +export function methodParentPointers(): AbiTransforms { const visitorStack: (ModuleDefinition | ImportedModuleDefinition)[] = []; return { diff --git a/packages/schema/parse/src/transform/moduleCapabilities.ts b/packages/schema/parse/src/transform/moduleCapabilities.ts index 67da840913..531959accb 100644 --- a/packages/schema/parse/src/transform/moduleCapabilities.ts +++ b/packages/schema/parse/src/transform/moduleCapabilities.ts @@ -1,9 +1,5 @@ -import { TypeInfoTransforms } from "."; -import { - InterfaceDefinition, - CapabilityDefinition, - TypeInfo, -} from "../typeInfo"; +import { AbiTransforms } from "."; +import { InterfaceDefinition, CapabilityDefinition, Abi } from "../abi"; export interface ModuleCapability { type: string; @@ -11,7 +7,7 @@ export interface ModuleCapability { namespace: string; } -export function moduleCapabilities(): TypeInfoTransforms { +export function moduleCapabilities(): AbiTransforms { const capabilities: ModuleCapability[] = []; const enabledInterfaces: Set = new Set(); @@ -34,7 +30,7 @@ export function moduleCapabilities(): TypeInfoTransforms { }, }, leave: { - TypeInfo: (info: TypeInfo) => { + Abi: (info: Abi) => { if (info.moduleType) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (info.moduleType as any).capabilities = capabilities; diff --git a/packages/schema/parse/src/transform/toGraphQLType.ts b/packages/schema/parse/src/transform/toGraphQLType.ts index 2ad50fe767..8dc7f9f189 100644 --- a/packages/schema/parse/src/transform/toGraphQLType.ts +++ b/packages/schema/parse/src/transform/toGraphQLType.ts @@ -1,4 +1,4 @@ -import { TypeInfoTransforms } from "."; +import { AbiTransforms } from "."; import { GenericDefinition, AnyDefinition, @@ -6,7 +6,7 @@ import { MethodDefinition, DefinitionKind, MapDefinition, -} from "../typeInfo"; +} from "../abi"; function applyRequired(type: string, required: boolean | null): string { return `${type}${required ? "!" : ""}`; @@ -130,7 +130,7 @@ export function toPrefixedGraphQL(def: GenericDefinition): string { return toGraphQL(def, true); } -export const toPrefixedGraphQLType: TypeInfoTransforms = { +export const toPrefixedGraphQLType: AbiTransforms = { enter: { GenericDefinition: (def: GenericDefinition) => ({ ...def, @@ -139,7 +139,7 @@ export const toPrefixedGraphQLType: TypeInfoTransforms = { }, }; -export const toGraphQLType: TypeInfoTransforms = { +export const toGraphQLType: AbiTransforms = { enter: { GenericDefinition: (def: GenericDefinition) => ({ ...def, diff --git a/packages/schema/parse/src/validate/directives.ts b/packages/schema/parse/src/validate/directives.ts index 9f1a678eef..9461aef96b 100644 --- a/packages/schema/parse/src/validate/directives.ts +++ b/packages/schema/parse/src/validate/directives.ts @@ -1,4 +1,4 @@ -import { ImportedDefinition } from "../typeInfo"; +import { ImportedDefinition } from "../abi"; import { SchemaValidator } from "."; import { DirectiveNode, ASTNode, ObjectTypeDefinitionNode } from "graphql"; diff --git a/packages/schema/parse/src/validate/types.ts b/packages/schema/parse/src/validate/types.ts index cd045980e1..57a10fa661 100644 --- a/packages/schema/parse/src/validate/types.ts +++ b/packages/schema/parse/src/validate/types.ts @@ -1,4 +1,4 @@ -import { isScalarType, scalarTypeNames, isModuleType } from "../typeInfo"; +import { isScalarType, scalarTypeNames, isModuleType } from "../abi"; import { SchemaValidator } from "./"; import { diff --git a/packages/templates/run-tests.ts b/packages/templates/run-tests.ts index bdd38afc7c..01bec3f91e 100644 --- a/packages/templates/run-tests.ts +++ b/packages/templates/run-tests.ts @@ -23,10 +23,9 @@ const languageTestCommands: Record = { // "CI=false yarn build" ], "assemblyscript": [ - // Uncomment when the wasm/as package has been redeployed - // "yarn build", - // "yarn test:e2e" - // "yarn test:workflow" + "yarn build", + "yarn test:e2e", + "yarn test:workflow" ], "interface": [ "yarn build" diff --git a/packages/templates/wasm/assemblyscript/package.json b/packages/templates/wasm/assemblyscript/package.json index 21d4a85f7e..4f0f622c12 100644 --- a/packages/templates/wasm/assemblyscript/package.json +++ b/packages/templates/wasm/assemblyscript/package.json @@ -10,8 +10,9 @@ "test:env:up": "npx polywrap infra up --modules=eth-ens-ipfs", "test:env:down": "npx polywrap infra down --modules=eth-ens-ipfs", "deploy": "npx polywrap deploy", + "test": "yarn test:e2e && yarn test:workflow", "test:e2e": "yarn build && yarn test:e2e:codegen && jest --passWithNoTests --runInBand --verbose", - "test:e2e:codegen": "npx polywrap app codegen -m ./src/__tests__/types/polywrap.app.yaml -c ./src/__tests__/types/wrap", + "test:e2e:codegen": "npx polywrap app codegen -m ./src/__tests__/types/polywrap.app.yaml -g ./src/__tests__/types/wrap", "test:workflow": "yarn build && yarn test:env:up && sleep 5 && npx polywrap run ./workflows/e2e.yaml && yarn test:env:down" }, "devDependencies": { diff --git a/packages/templates/wasm/assemblyscript/workflows/config.ts b/packages/templates/wasm/assemblyscript/workflows/config.ts index 3d5497795c..0f9ada10f7 100644 --- a/packages/templates/wasm/assemblyscript/workflows/config.ts +++ b/packages/templates/wasm/assemblyscript/workflows/config.ts @@ -1,6 +1,7 @@ import { PolywrapClientConfig } from "@polywrap/client-js"; import { ClientConfig, coreInterfaceUris } from "@polywrap/client-js"; -import { ensPlugin } from "@polywrap/ens-plugin-js"; +import { ipfsResolverPlugin } from "@polywrap/ipfs-resolver-plugin-js"; +import { ensResolverPlugin } from "@polywrap/ens-resolver-plugin-js"; import { ethereumPlugin } from "@polywrap/ethereum-plugin-js"; import { ipfsPlugin } from "@polywrap/ipfs-plugin-js"; @@ -34,8 +35,14 @@ function getPlugins( plugin: ipfsPlugin({ provider: ipfs }), }, { - uri: "wrap://ens/ens.polywrap.eth", - plugin: ensPlugin({ addresses: { testnet: ensAddress } }), + uri: "wrap://ens/ipfs-resolver.polywrap.eth", + plugin: ipfsResolverPlugin({ + provider: ipfs, + }), + }, + { + uri: "wrap://ens/ens-resolver.polywrap.eth", + plugin: ensResolverPlugin({ addresses: { testnet: ensAddress } }), }, { uri: "wrap://ens/ethereum.polywrap.eth", @@ -56,8 +63,8 @@ function getPlugins( { interface: coreInterfaceUris.uriResolver.uri, implementations: [ - "wrap://ens/ipfs.polywrap.eth", - "wrap://ens/ens.polywrap.eth", + "wrap://ens/ipfs-resolver.polywrap.eth", + "wrap://ens/ens-resolver.polywrap.eth", ], }, { diff --git a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts index 71e9a4a833..8dcf50fa3f 100644 --- a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts @@ -15,7 +15,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts index 8aed41456a..fae3517706 100644 --- a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/bind/sanity/output/wasm-rs/entry.rs b/packages/test-cases/cases/bind/sanity/output/wasm-rs/entry.rs index 61e182145f..949c996d06 100644 --- a/packages/test-cases/cases/bind/sanity/output/wasm-rs/entry.rs +++ b/packages/test-cases/cases/bind/sanity/output/wasm-rs/entry.rs @@ -8,7 +8,6 @@ use polywrap_wasm_rs::{ InvokeArgs, }; -#[cfg(feature = "wrap-invoke")] #[no_mangle] pub extern "C" fn _wrap_invoke(method_size: u32, args_size: u32) -> bool { // Ensure the abort handler is properly setup diff --git a/packages/test-cases/cases/cli/app/codegen/001-sanity/expected/stdout.json b/packages/test-cases/cases/cli/app/codegen/001-sanity/expected/stdout.json new file mode 100644 index 0000000000..d41100f3b3 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/001-sanity/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.app.yaml", + "Generate types", + "Code was generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/app/codegen/002-with-plugin/expected/stdout.json b/packages/test-cases/cases/cli/app/codegen/002-with-plugin/expected/stdout.json new file mode 100644 index 0000000000..d41100f3b3 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/002-with-plugin/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.app.yaml", + "Generate types", + "Code was generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/app/codegen/003-multi-import/expected/stdout.json b/packages/test-cases/cases/cli/app/codegen/003-multi-import/expected/stdout.json new file mode 100644 index 0000000000..d41100f3b3 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/003-multi-import/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.app.yaml", + "Generate types", + "Code was generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/app/codegen/004-custom-config/cmd.json b/packages/test-cases/cases/cli/app/codegen/004-custom-config/cmd.json new file mode 100644 index 0000000000..aa6170b001 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/004-custom-config/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-c", "./config.ts"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/app/codegen/004-custom-config/config.ts b/packages/test-cases/cases/cli/app/codegen/004-custom-config/config.ts new file mode 100644 index 0000000000..a51cd93907 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/004-custom-config/config.ts @@ -0,0 +1,51 @@ +import { PolywrapClientConfig } from "@polywrap/client-js"; +import { PluginModule } from "@polywrap/core-js"; + +interface Config extends Record { + val: number; +} + +class MockPlugin extends PluginModule { + + getData(_: unknown): number { return this.config.val; } + + setData(args: { value: number }) { + this.config.val = +args.value; + return true; + } + + deployContract(): string { return "0x100"; } +} + +const mockPlugin = () => { + return { + factory: () => new MockPlugin({ val: 0 }), + manifest: { + schema: ` + type Module { + getData: Int! + setData(value: Int!): Boolean! + deployContract: String! + } + `, + implements: [], + }, + }; +}; + +export function getClientConfig(defaultConfigs: Partial) { + if (defaultConfigs.plugins) { + defaultConfigs.plugins.push({ + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }); + } else { + defaultConfigs.plugins = [ + { + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }, + ]; + } + return defaultConfigs; +} diff --git a/packages/test-cases/cases/cli/app/codegen/004-custom-config/expected/stdout.json b/packages/test-cases/cases/cli/app/codegen/004-custom-config/expected/stdout.json new file mode 100644 index 0000000000..d41100f3b3 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/004-custom-config/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.app.yaml", + "Generate types", + "Code was generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/app/codegen/004-custom-config/polywrap.app.yaml b/packages/test-cases/cases/cli/app/codegen/004-custom-config/polywrap.app.yaml new file mode 100644 index 0000000000..bbed2041c9 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/004-custom-config/polywrap.app.yaml @@ -0,0 +1,3 @@ +format: 0.0.1-prealpha.1 +language: app/typescript +schema: ./schema.graphql diff --git a/packages/test-cases/cases/cli/app/codegen/004-custom-config/schema.graphql b/packages/test-cases/cases/cli/app/codegen/004-custom-config/schema.graphql new file mode 100644 index 0000000000..571bb3b5b5 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/004-custom-config/schema.graphql @@ -0,0 +1,2 @@ +#import * into Ethereum from "wrap://ens/ethereum.polywrap.eth" +#import * into Mock from "wrap://ens/mock.eth" diff --git a/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/cmd.json b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/cmd.json new file mode 100644 index 0000000000..7dc74da6e1 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-m", "./polywrap.custom.app.yaml"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/expected/stdout.json b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/expected/stdout.json new file mode 100644 index 0000000000..099897d8fb --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.custom.app.yaml", + "Generate types", + "Code was generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/polywrap.custom.app.yaml b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/polywrap.custom.app.yaml new file mode 100644 index 0000000000..bbed2041c9 --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/polywrap.custom.app.yaml @@ -0,0 +1,3 @@ +format: 0.0.1-prealpha.1 +language: app/typescript +schema: ./schema.graphql diff --git a/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/schema.graphql b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/schema.graphql new file mode 100644 index 0000000000..33edff0f6a --- /dev/null +++ b/packages/test-cases/cases/cli/app/codegen/005-custom-manifest-file/schema.graphql @@ -0,0 +1 @@ +#import * into Ethereum from "wrap://ens/ethereum.polywrap.eth" diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/stdout.json new file mode 100644 index 0000000000..d9b77bbc00 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/index.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/index.ts rename to packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/manifest.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/manifest.ts rename to packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/manifest.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/module.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/module.ts rename to packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/module.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/schema.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/schema.ts rename to packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/schema.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts similarity index 99% rename from packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/types.ts rename to packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts index 796131ef49..bb9273518b 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/src/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/stdout.json new file mode 100644 index 0000000000..d9b77bbc00 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/index.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/index.ts rename to packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/manifest.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/manifest.ts rename to packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/manifest.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/module.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/module.ts rename to packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/module.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/schema.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/schema.ts rename to packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/schema.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts similarity index 99% rename from packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/types.ts rename to packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts index 796131ef49..bb9273518b 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/src/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/stdout.json new file mode 100644 index 0000000000..d9b77bbc00 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/index.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/index.ts rename to packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/manifest.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/manifest.ts rename to packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/manifest.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/module.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/module.ts rename to packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/module.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/schema.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/schema.ts rename to packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/schema.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts similarity index 96% rename from packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/types.ts rename to packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts index 450bfe2967..a02c59511e 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/src/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/stdout.json new file mode 100644 index 0000000000..d9b77bbc00 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/index.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/index.ts rename to packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/manifest.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/manifest.ts rename to packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/manifest.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/module.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/module.ts rename to packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/module.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/schema.ts similarity index 100% rename from packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/schema.ts rename to packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/schema.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts similarity index 96% rename from packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/types.ts rename to packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts index 813097c637..d6e697ee03 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/src/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts @@ -18,7 +18,7 @@ export type Int = number; export type Int8 = number; export type Int16 = number; export type Int32 = number; -export type Bytes = ArrayBuffer; +export type Bytes = Uint8Array; export type BigInt = string; export type BigNumber = string; export type Json = string; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/.gitignore b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/.gitignore new file mode 100644 index 0000000000..3386731da9 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/.gitignore @@ -0,0 +1 @@ +!expected/** diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/cmd.json b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/cmd.json new file mode 100644 index 0000000000..aa6170b001 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-c", "./config.ts"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/config.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/config.ts new file mode 100644 index 0000000000..a51cd93907 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/config.ts @@ -0,0 +1,51 @@ +import { PolywrapClientConfig } from "@polywrap/client-js"; +import { PluginModule } from "@polywrap/core-js"; + +interface Config extends Record { + val: number; +} + +class MockPlugin extends PluginModule { + + getData(_: unknown): number { return this.config.val; } + + setData(args: { value: number }) { + this.config.val = +args.value; + return true; + } + + deployContract(): string { return "0x100"; } +} + +const mockPlugin = () => { + return { + factory: () => new MockPlugin({ val: 0 }), + manifest: { + schema: ` + type Module { + getData: Int! + setData(value: Int!): Boolean! + deployContract: String! + } + `, + implements: [], + }, + }; +}; + +export function getClientConfig(defaultConfigs: Partial) { + if (defaultConfigs.plugins) { + defaultConfigs.plugins.push({ + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }); + } else { + defaultConfigs.plugins = [ + { + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }, + ]; + } + return defaultConfigs; +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/polywrap.plugin.json b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/polywrap.plugin.json new file mode 100644 index 0000000000..438f63f0a1 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/polywrap.plugin.json @@ -0,0 +1,7 @@ +{ + "format": "0.0.1-prealpha.3", + "name": "Test", + "language": "plugin/typescript", + "schema": "./schema.graphql", + "module": "./src/index.ts" +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/schema.graphql b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/schema.graphql new file mode 100644 index 0000000000..cebf63eccd --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/build-artifacts/schema.graphql @@ -0,0 +1,376 @@ +### Polywrap Header START ### +scalar UInt +scalar UInt8 +scalar UInt16 +scalar UInt32 +scalar Int +scalar Int8 +scalar Int16 +scalar Int32 +scalar Bytes +scalar BigInt +scalar BigNumber +scalar JSON +scalar Map + +directive @imported( + uri: String! + namespace: String! + nativeType: String! +) on OBJECT | ENUM + +directive @imports( + types: [String!]! +) on OBJECT + +directive @capability( + type: String! + uri: String! + namespace: String! +) repeatable on OBJECT + +directive @enabled_interface on OBJECT + +directive @annotate(type: String!) on FIELD + +### Polywrap Header END ### + +type Module @imports( + types: [ + "Ethereum_Module", + "Ethereum_Connection", + "Ethereum_TxOverrides", + "Ethereum_StaticTxResult", + "Ethereum_TxRequest", + "Ethereum_TxReceipt", + "Ethereum_Log", + "Ethereum_EventNotification", + "Ethereum_Network", + "Ethereum_TxResponse", + "Ethereum_Access" + ] +) { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Env { + arg1: String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +### Imported Modules START ### + +type Ethereum_Module @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Module" +) { + callContractView( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + callContractStatic( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_StaticTxResult! + + getBalance( + address: String! + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + encodeParams( + types: [String!]! + values: [String!]! + ): String! + + encodeFunction( + method: String! + args: [String!] + ): String! + + solidityPack( + types: [String!]! + values: [String!]! + ): String! + + solidityKeccak256( + types: [String!]! + values: [String!]! + ): String! + + soliditySha256( + types: [String!]! + values: [String!]! + ): String! + + getSignerAddress( + connection: Ethereum_Connection + ): String! + + getSignerBalance( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getSignerTransactionCount( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getGasPrice( + connection: Ethereum_Connection + ): BigInt! + + estimateTransactionGas( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): BigInt! + + estimateContractCallGas( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): BigInt! + + checkAddress( + address: String! + ): Boolean! + + toWei( + eth: String! + ): BigInt! + + toEth( + wei: BigInt! + ): String! + + awaitTransaction( + txHash: String! + confirmations: UInt32! + timeout: UInt32! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + waitForEvent( + address: String! + event: String! + args: [String!] + timeout: UInt32 + connection: Ethereum_Connection + ): Ethereum_EventNotification! + + getNetwork( + connection: Ethereum_Connection + ): Ethereum_Network! + + callContractMethod( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxResponse! + + callContractMethodAndWait( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxReceipt! + + sendTransaction( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxResponse! + + sendTransactionAndWait( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + deployContract( + abi: String! + bytecode: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + signMessage( + message: String! + connection: Ethereum_Connection + ): String! + + sendRPC( + method: String! + params: [String!]! + connection: Ethereum_Connection + ): String +} + +### Imported Modules END ### + +### Imported Objects START ### + +type Ethereum_Connection @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Connection" +) { + node: String + networkNameOrChainId: String +} + +type Ethereum_TxOverrides @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxOverrides" +) { + gasLimit: BigInt + gasPrice: BigInt + value: BigInt +} + +type Ethereum_StaticTxResult @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "StaticTxResult" +) { + result: String! + error: Boolean! +} + +type Ethereum_TxRequest @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxRequest" +) { + to: String + from: String + nonce: UInt32 + gasLimit: BigInt + gasPrice: BigInt + data: String + value: BigInt + chainId: BigInt + type: UInt32 +} + +type Ethereum_TxReceipt @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxReceipt" +) { + to: String! + from: String! + contractAddress: String! + transactionIndex: UInt32! + root: String + gasUsed: BigInt! + logsBloom: String! + transactionHash: String! + logs: [Ethereum_Log!]! + blockNumber: BigInt! + blockHash: String! + confirmations: UInt32! + cumulativeGasUsed: BigInt! + effectiveGasPrice: BigInt! + byzantium: Boolean! + type: UInt32! + status: UInt32 +} + +type Ethereum_Log @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Log" +) { + blockNumber: BigInt! + blockHash: String! + transactionIndex: UInt32! + removed: Boolean! + address: String! + data: String! + topics: [String!]! + transactionHash: String! + logIndex: UInt32! +} + +type Ethereum_EventNotification @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "EventNotification" +) { + data: String! + address: String! + log: Ethereum_Log! +} + +type Ethereum_Network @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Network" +) { + name: String! + chainId: BigInt! + ensAddress: String +} + +type Ethereum_TxResponse @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxResponse" +) { + hash: String! + to: String + from: String! + nonce: UInt32! + gasLimit: BigInt! + gasPrice: BigInt + data: String! + value: BigInt! + chainId: BigInt! + blockNumber: BigInt + blockHash: String + timestamp: UInt32 + confirmations: UInt32! + raw: String + r: String + s: String + v: UInt32 + type: UInt32 + accessList: [Ethereum_Access!] +} + +type Ethereum_Access @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Access" +) { + address: String! + storageKeys: [String!]! +} + +### Imported Objects END ### diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/stdout.json new file mode 100644 index 0000000000..d9b77bbc00 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/index.ts new file mode 100644 index 0000000000..f367d143d9 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/index.ts @@ -0,0 +1,9 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +export * from "./schema"; +export * from "./manifest"; +export * from "./module"; +export * from "./types"; + +export { Client } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/manifest.ts new file mode 100644 index 0000000000..730cf8326f --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/manifest.ts @@ -0,0 +1,15 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +/* eslint-disable @typescript-eslint/no-unused-vars */ + +import { schema } from "./"; + +// @ts-ignore +import { PluginPackageManifest, Uri } from "@polywrap/core-js"; + +export const manifest: PluginPackageManifest = { + schema, + implements: [ + ], +}; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/module.ts new file mode 100644 index 0000000000..5d68d6b00e --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/module.ts @@ -0,0 +1,37 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +import * as Types from "./types"; + +import { + Client, + PluginModule, + MaybeAsync +} from "@polywrap/core-js"; + +export interface Args_methodOne extends Record { + str: Types.String; + optStr?: Types.String | null; +} + +export interface Args_methodTwo extends Record { + arg: Types.UInt32; +} + +export abstract class Module< + TConfig +> extends PluginModule< + TConfig, + Types.Env +> { + + abstract methodOne( + args: Args_methodOne, + client: Client + ): MaybeAsync; + + abstract methodTwo( + args: Args_methodTwo, + client: Client + ): MaybeAsync; +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/schema.ts new file mode 100644 index 0000000000..a16cb34492 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/schema.ts @@ -0,0 +1,380 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +export const schema: string = `### Polywrap Header START ### +scalar UInt +scalar UInt8 +scalar UInt16 +scalar UInt32 +scalar Int +scalar Int8 +scalar Int16 +scalar Int32 +scalar Bytes +scalar BigInt +scalar BigNumber +scalar JSON +scalar Map + +directive @imported( + uri: String! + namespace: String! + nativeType: String! +) on OBJECT | ENUM + +directive @imports( + types: [String!]! +) on OBJECT + +directive @capability( + type: String! + uri: String! + namespace: String! +) repeatable on OBJECT + +directive @enabled_interface on OBJECT + +directive @annotate(type: String!) on FIELD + +### Polywrap Header END ### + +type Module @imports( + types: [ + "Ethereum_Module", + "Ethereum_Connection", + "Ethereum_TxOverrides", + "Ethereum_StaticTxResult", + "Ethereum_TxRequest", + "Ethereum_TxReceipt", + "Ethereum_Log", + "Ethereum_EventNotification", + "Ethereum_Network", + "Ethereum_TxResponse", + "Ethereum_Access" + ] +) { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Env { + arg1: String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +### Imported Modules START ### + +type Ethereum_Module @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Module" +) { + callContractView( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + callContractStatic( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_StaticTxResult! + + getBalance( + address: String! + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + encodeParams( + types: [String!]! + values: [String!]! + ): String! + + encodeFunction( + method: String! + args: [String!] + ): String! + + solidityPack( + types: [String!]! + values: [String!]! + ): String! + + solidityKeccak256( + types: [String!]! + values: [String!]! + ): String! + + soliditySha256( + types: [String!]! + values: [String!]! + ): String! + + getSignerAddress( + connection: Ethereum_Connection + ): String! + + getSignerBalance( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getSignerTransactionCount( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getGasPrice( + connection: Ethereum_Connection + ): BigInt! + + estimateTransactionGas( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): BigInt! + + estimateContractCallGas( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): BigInt! + + checkAddress( + address: String! + ): Boolean! + + toWei( + eth: String! + ): BigInt! + + toEth( + wei: BigInt! + ): String! + + awaitTransaction( + txHash: String! + confirmations: UInt32! + timeout: UInt32! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + waitForEvent( + address: String! + event: String! + args: [String!] + timeout: UInt32 + connection: Ethereum_Connection + ): Ethereum_EventNotification! + + getNetwork( + connection: Ethereum_Connection + ): Ethereum_Network! + + callContractMethod( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxResponse! + + callContractMethodAndWait( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxReceipt! + + sendTransaction( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxResponse! + + sendTransactionAndWait( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + deployContract( + abi: String! + bytecode: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + signMessage( + message: String! + connection: Ethereum_Connection + ): String! + + sendRPC( + method: String! + params: [String!]! + connection: Ethereum_Connection + ): String +} + +### Imported Modules END ### + +### Imported Objects START ### + +type Ethereum_Connection @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Connection" +) { + node: String + networkNameOrChainId: String +} + +type Ethereum_TxOverrides @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxOverrides" +) { + gasLimit: BigInt + gasPrice: BigInt + value: BigInt +} + +type Ethereum_StaticTxResult @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "StaticTxResult" +) { + result: String! + error: Boolean! +} + +type Ethereum_TxRequest @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxRequest" +) { + to: String + from: String + nonce: UInt32 + gasLimit: BigInt + gasPrice: BigInt + data: String + value: BigInt + chainId: BigInt + type: UInt32 +} + +type Ethereum_TxReceipt @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxReceipt" +) { + to: String! + from: String! + contractAddress: String! + transactionIndex: UInt32! + root: String + gasUsed: BigInt! + logsBloom: String! + transactionHash: String! + logs: [Ethereum_Log!]! + blockNumber: BigInt! + blockHash: String! + confirmations: UInt32! + cumulativeGasUsed: BigInt! + effectiveGasPrice: BigInt! + byzantium: Boolean! + type: UInt32! + status: UInt32 +} + +type Ethereum_Log @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Log" +) { + blockNumber: BigInt! + blockHash: String! + transactionIndex: UInt32! + removed: Boolean! + address: String! + data: String! + topics: [String!]! + transactionHash: String! + logIndex: UInt32! +} + +type Ethereum_EventNotification @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "EventNotification" +) { + data: String! + address: String! + log: Ethereum_Log! +} + +type Ethereum_Network @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Network" +) { + name: String! + chainId: BigInt! + ensAddress: String +} + +type Ethereum_TxResponse @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxResponse" +) { + hash: String! + to: String + from: String! + nonce: UInt32! + gasLimit: BigInt! + gasPrice: BigInt + data: String! + value: BigInt! + chainId: BigInt! + blockNumber: BigInt + blockHash: String + timestamp: UInt32 + confirmations: UInt32! + raw: String + r: String + s: String + v: UInt32 + type: UInt32 + accessList: [Ethereum_Access!] +} + +type Ethereum_Access @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Access" +) { + address: String! + storageKeys: [String!]! +} + +### Imported Objects END ### +`; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts new file mode 100644 index 0000000000..bb9273518b --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts @@ -0,0 +1,640 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +// @ts-ignore +import * as Types from "./"; + +// @ts-ignore +import { + Client, + InvokeResult +} from "@polywrap/core-js"; + +export type UInt = number; +export type UInt8 = number; +export type UInt16 = number; +export type UInt32 = number; +export type Int = number; +export type Int8 = number; +export type Int16 = number; +export type Int32 = number; +export type Bytes = Uint8Array; +export type BigInt = string; +export type BigNumber = string; +export type Json = string; +export type String = string; +export type Boolean = boolean; + +/// Envs START /// +export interface Env extends Record { + arg1: Types.String; +} +/// Envs END /// + +/// Objects START /// +export interface Object { + u: Types.UInt; + array: Array; + bytes?: Types.Bytes | null; +} + +/// Objects END /// + +/// Enums START /// +/// Enums END /// + +/// Imported Objects START /// + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Connection { + node?: Types.String | null; + networkNameOrChainId?: Types.String | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxOverrides { + gasLimit?: Types.BigInt | null; + gasPrice?: Types.BigInt | null; + value?: Types.BigInt | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_StaticTxResult { + result: Types.String; + error: Types.Boolean; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxRequest { + to?: Types.String | null; + from?: Types.String | null; + nonce?: Types.UInt32 | null; + gasLimit?: Types.BigInt | null; + gasPrice?: Types.BigInt | null; + data?: Types.String | null; + value?: Types.BigInt | null; + chainId?: Types.BigInt | null; + type?: Types.UInt32 | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxReceipt { + to: Types.String; + from: Types.String; + contractAddress: Types.String; + transactionIndex: Types.UInt32; + root?: Types.String | null; + gasUsed: Types.BigInt; + logsBloom: Types.String; + transactionHash: Types.String; + logs: Array; + blockNumber: Types.BigInt; + blockHash: Types.String; + confirmations: Types.UInt32; + cumulativeGasUsed: Types.BigInt; + effectiveGasPrice: Types.BigInt; + byzantium: Types.Boolean; + type: Types.UInt32; + status?: Types.UInt32 | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Log { + blockNumber: Types.BigInt; + blockHash: Types.String; + transactionIndex: Types.UInt32; + removed: Types.Boolean; + address: Types.String; + data: Types.String; + topics: Array; + transactionHash: Types.String; + logIndex: Types.UInt32; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_EventNotification { + data: Types.String; + address: Types.String; + log: Types.Ethereum_Log; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Network { + name: Types.String; + chainId: Types.BigInt; + ensAddress?: Types.String | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxResponse { + hash: Types.String; + to?: Types.String | null; + from: Types.String; + nonce: Types.UInt32; + gasLimit: Types.BigInt; + gasPrice?: Types.BigInt | null; + data: Types.String; + value: Types.BigInt; + chainId: Types.BigInt; + blockNumber?: Types.BigInt | null; + blockHash?: Types.String | null; + timestamp?: Types.UInt32 | null; + confirmations: Types.UInt32; + raw?: Types.String | null; + r?: Types.String | null; + s?: Types.String | null; + v?: Types.UInt32 | null; + type?: Types.UInt32 | null; + accessList?: Array | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Access { + address: Types.String; + storageKeys: Array; +} + +/// Imported Objects END /// + +/// Imported Modules START /// + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractView extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractStatic extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getBalance extends Record { + address: Types.String; + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_encodeParams extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_encodeFunction extends Record { + method: Types.String; + args?: Array | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_solidityPack extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_solidityKeccak256 extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_soliditySha256 extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerAddress extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerBalance extends Record { + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerTransactionCount extends Record { + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getGasPrice extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_estimateTransactionGas extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_estimateContractCallGas extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_checkAddress extends Record { + address: Types.String; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_toWei extends Record { + eth: Types.String; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_toEth extends Record { + wei: Types.BigInt; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_awaitTransaction extends Record { + txHash: Types.String; + confirmations: Types.UInt32; + timeout: Types.UInt32; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_waitForEvent extends Record { + address: Types.String; + event: Types.String; + args?: Array | null; + timeout?: Types.UInt32 | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getNetwork extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractMethod extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractMethodAndWait extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendTransaction extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendTransactionAndWait extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_deployContract extends Record { + abi: Types.String; + bytecode: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_signMessage extends Record { + message: Types.String; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendRPC extends Record { + method: Types.String; + params: Array; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export const Ethereum_Module = { + callContractView: async ( + args: Ethereum_Module_Args_callContractView, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractView", + args + }); + }, + + callContractStatic: async ( + args: Ethereum_Module_Args_callContractStatic, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractStatic", + args + }); + }, + + getBalance: async ( + args: Ethereum_Module_Args_getBalance, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getBalance", + args + }); + }, + + encodeParams: async ( + args: Ethereum_Module_Args_encodeParams, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "encodeParams", + args + }); + }, + + encodeFunction: async ( + args: Ethereum_Module_Args_encodeFunction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "encodeFunction", + args + }); + }, + + solidityPack: async ( + args: Ethereum_Module_Args_solidityPack, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "solidityPack", + args + }); + }, + + solidityKeccak256: async ( + args: Ethereum_Module_Args_solidityKeccak256, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "solidityKeccak256", + args + }); + }, + + soliditySha256: async ( + args: Ethereum_Module_Args_soliditySha256, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "soliditySha256", + args + }); + }, + + getSignerAddress: async ( + args: Ethereum_Module_Args_getSignerAddress, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerAddress", + args + }); + }, + + getSignerBalance: async ( + args: Ethereum_Module_Args_getSignerBalance, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerBalance", + args + }); + }, + + getSignerTransactionCount: async ( + args: Ethereum_Module_Args_getSignerTransactionCount, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerTransactionCount", + args + }); + }, + + getGasPrice: async ( + args: Ethereum_Module_Args_getGasPrice, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getGasPrice", + args + }); + }, + + estimateTransactionGas: async ( + args: Ethereum_Module_Args_estimateTransactionGas, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "estimateTransactionGas", + args + }); + }, + + estimateContractCallGas: async ( + args: Ethereum_Module_Args_estimateContractCallGas, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "estimateContractCallGas", + args + }); + }, + + checkAddress: async ( + args: Ethereum_Module_Args_checkAddress, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "checkAddress", + args + }); + }, + + toWei: async ( + args: Ethereum_Module_Args_toWei, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "toWei", + args + }); + }, + + toEth: async ( + args: Ethereum_Module_Args_toEth, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "toEth", + args + }); + }, + + awaitTransaction: async ( + args: Ethereum_Module_Args_awaitTransaction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "awaitTransaction", + args + }); + }, + + waitForEvent: async ( + args: Ethereum_Module_Args_waitForEvent, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "waitForEvent", + args + }); + }, + + getNetwork: async ( + args: Ethereum_Module_Args_getNetwork, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getNetwork", + args + }); + }, + + callContractMethod: async ( + args: Ethereum_Module_Args_callContractMethod, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractMethod", + args + }); + }, + + callContractMethodAndWait: async ( + args: Ethereum_Module_Args_callContractMethodAndWait, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractMethodAndWait", + args + }); + }, + + sendTransaction: async ( + args: Ethereum_Module_Args_sendTransaction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendTransaction", + args + }); + }, + + sendTransactionAndWait: async ( + args: Ethereum_Module_Args_sendTransactionAndWait, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendTransactionAndWait", + args + }); + }, + + deployContract: async ( + args: Ethereum_Module_Args_deployContract, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "deployContract", + args + }); + }, + + signMessage: async ( + args: Ethereum_Module_Args_signMessage, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "signMessage", + args + }); + }, + + sendRPC: async ( + args: Ethereum_Module_Args_sendRPC, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendRPC", + args + }); + } +} + +/// Imported Modules END /// diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/polywrap.plugin.yaml b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/polywrap.plugin.yaml new file mode 100644 index 0000000000..ac7abe08e5 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/polywrap.plugin.yaml @@ -0,0 +1,5 @@ +format: 0.0.1-prealpha.3 +name: Test +language: plugin/typescript +schema: ./schema.graphql +module: ./src/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/schema.graphql b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/schema.graphql new file mode 100644 index 0000000000..acad0ae76c --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/schema.graphql @@ -0,0 +1,22 @@ +#import { Module } into Ethereum from "ens/ethereum.polywrap.eth" + +type Module { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +type Env { + arg1: String! +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/src/index.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/src/index.ts new file mode 100644 index 0000000000..5bb85ff3e4 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/src/index.ts @@ -0,0 +1 @@ +export * from "./wrap"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/.gitignore b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/.gitignore new file mode 100644 index 0000000000..3386731da9 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/.gitignore @@ -0,0 +1 @@ +!expected/** diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/cmd.json b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/cmd.json new file mode 100644 index 0000000000..d8aa2a5393 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-m", "./polywrap.custom.plugin.yaml"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/polywrap.plugin.json b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/polywrap.plugin.json new file mode 100644 index 0000000000..438f63f0a1 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/polywrap.plugin.json @@ -0,0 +1,7 @@ +{ + "format": "0.0.1-prealpha.3", + "name": "Test", + "language": "plugin/typescript", + "schema": "./schema.graphql", + "module": "./src/index.ts" +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/schema.graphql b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/schema.graphql new file mode 100644 index 0000000000..cebf63eccd --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/build-artifacts/schema.graphql @@ -0,0 +1,376 @@ +### Polywrap Header START ### +scalar UInt +scalar UInt8 +scalar UInt16 +scalar UInt32 +scalar Int +scalar Int8 +scalar Int16 +scalar Int32 +scalar Bytes +scalar BigInt +scalar BigNumber +scalar JSON +scalar Map + +directive @imported( + uri: String! + namespace: String! + nativeType: String! +) on OBJECT | ENUM + +directive @imports( + types: [String!]! +) on OBJECT + +directive @capability( + type: String! + uri: String! + namespace: String! +) repeatable on OBJECT + +directive @enabled_interface on OBJECT + +directive @annotate(type: String!) on FIELD + +### Polywrap Header END ### + +type Module @imports( + types: [ + "Ethereum_Module", + "Ethereum_Connection", + "Ethereum_TxOverrides", + "Ethereum_StaticTxResult", + "Ethereum_TxRequest", + "Ethereum_TxReceipt", + "Ethereum_Log", + "Ethereum_EventNotification", + "Ethereum_Network", + "Ethereum_TxResponse", + "Ethereum_Access" + ] +) { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Env { + arg1: String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +### Imported Modules START ### + +type Ethereum_Module @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Module" +) { + callContractView( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + callContractStatic( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_StaticTxResult! + + getBalance( + address: String! + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + encodeParams( + types: [String!]! + values: [String!]! + ): String! + + encodeFunction( + method: String! + args: [String!] + ): String! + + solidityPack( + types: [String!]! + values: [String!]! + ): String! + + solidityKeccak256( + types: [String!]! + values: [String!]! + ): String! + + soliditySha256( + types: [String!]! + values: [String!]! + ): String! + + getSignerAddress( + connection: Ethereum_Connection + ): String! + + getSignerBalance( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getSignerTransactionCount( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getGasPrice( + connection: Ethereum_Connection + ): BigInt! + + estimateTransactionGas( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): BigInt! + + estimateContractCallGas( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): BigInt! + + checkAddress( + address: String! + ): Boolean! + + toWei( + eth: String! + ): BigInt! + + toEth( + wei: BigInt! + ): String! + + awaitTransaction( + txHash: String! + confirmations: UInt32! + timeout: UInt32! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + waitForEvent( + address: String! + event: String! + args: [String!] + timeout: UInt32 + connection: Ethereum_Connection + ): Ethereum_EventNotification! + + getNetwork( + connection: Ethereum_Connection + ): Ethereum_Network! + + callContractMethod( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxResponse! + + callContractMethodAndWait( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxReceipt! + + sendTransaction( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxResponse! + + sendTransactionAndWait( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + deployContract( + abi: String! + bytecode: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + signMessage( + message: String! + connection: Ethereum_Connection + ): String! + + sendRPC( + method: String! + params: [String!]! + connection: Ethereum_Connection + ): String +} + +### Imported Modules END ### + +### Imported Objects START ### + +type Ethereum_Connection @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Connection" +) { + node: String + networkNameOrChainId: String +} + +type Ethereum_TxOverrides @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxOverrides" +) { + gasLimit: BigInt + gasPrice: BigInt + value: BigInt +} + +type Ethereum_StaticTxResult @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "StaticTxResult" +) { + result: String! + error: Boolean! +} + +type Ethereum_TxRequest @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxRequest" +) { + to: String + from: String + nonce: UInt32 + gasLimit: BigInt + gasPrice: BigInt + data: String + value: BigInt + chainId: BigInt + type: UInt32 +} + +type Ethereum_TxReceipt @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxReceipt" +) { + to: String! + from: String! + contractAddress: String! + transactionIndex: UInt32! + root: String + gasUsed: BigInt! + logsBloom: String! + transactionHash: String! + logs: [Ethereum_Log!]! + blockNumber: BigInt! + blockHash: String! + confirmations: UInt32! + cumulativeGasUsed: BigInt! + effectiveGasPrice: BigInt! + byzantium: Boolean! + type: UInt32! + status: UInt32 +} + +type Ethereum_Log @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Log" +) { + blockNumber: BigInt! + blockHash: String! + transactionIndex: UInt32! + removed: Boolean! + address: String! + data: String! + topics: [String!]! + transactionHash: String! + logIndex: UInt32! +} + +type Ethereum_EventNotification @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "EventNotification" +) { + data: String! + address: String! + log: Ethereum_Log! +} + +type Ethereum_Network @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Network" +) { + name: String! + chainId: BigInt! + ensAddress: String +} + +type Ethereum_TxResponse @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxResponse" +) { + hash: String! + to: String + from: String! + nonce: UInt32! + gasLimit: BigInt! + gasPrice: BigInt + data: String! + value: BigInt! + chainId: BigInt! + blockNumber: BigInt + blockHash: String + timestamp: UInt32 + confirmations: UInt32! + raw: String + r: String + s: String + v: UInt32 + type: UInt32 + accessList: [Ethereum_Access!] +} + +type Ethereum_Access @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Access" +) { + address: String! + storageKeys: [String!]! +} + +### Imported Objects END ### diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/stdout.json b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/stdout.json new file mode 100644 index 0000000000..acdb608c56 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Manifest loaded from ./polywrap.custom.plugin.yaml", + "Generate types", + "Manifest written to ./build/polywrap.plugin.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/index.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/index.ts new file mode 100644 index 0000000000..f367d143d9 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/index.ts @@ -0,0 +1,9 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +export * from "./schema"; +export * from "./manifest"; +export * from "./module"; +export * from "./types"; + +export { Client } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/manifest.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/manifest.ts new file mode 100644 index 0000000000..730cf8326f --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/manifest.ts @@ -0,0 +1,15 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +/* eslint-disable @typescript-eslint/no-unused-vars */ + +import { schema } from "./"; + +// @ts-ignore +import { PluginPackageManifest, Uri } from "@polywrap/core-js"; + +export const manifest: PluginPackageManifest = { + schema, + implements: [ + ], +}; diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/module.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/module.ts new file mode 100644 index 0000000000..5d68d6b00e --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/module.ts @@ -0,0 +1,37 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +import * as Types from "./types"; + +import { + Client, + PluginModule, + MaybeAsync +} from "@polywrap/core-js"; + +export interface Args_methodOne extends Record { + str: Types.String; + optStr?: Types.String | null; +} + +export interface Args_methodTwo extends Record { + arg: Types.UInt32; +} + +export abstract class Module< + TConfig +> extends PluginModule< + TConfig, + Types.Env +> { + + abstract methodOne( + args: Args_methodOne, + client: Client + ): MaybeAsync; + + abstract methodTwo( + args: Args_methodTwo, + client: Client + ): MaybeAsync; +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/schema.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/schema.ts new file mode 100644 index 0000000000..a16cb34492 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/schema.ts @@ -0,0 +1,380 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +export const schema: string = `### Polywrap Header START ### +scalar UInt +scalar UInt8 +scalar UInt16 +scalar UInt32 +scalar Int +scalar Int8 +scalar Int16 +scalar Int32 +scalar Bytes +scalar BigInt +scalar BigNumber +scalar JSON +scalar Map + +directive @imported( + uri: String! + namespace: String! + nativeType: String! +) on OBJECT | ENUM + +directive @imports( + types: [String!]! +) on OBJECT + +directive @capability( + type: String! + uri: String! + namespace: String! +) repeatable on OBJECT + +directive @enabled_interface on OBJECT + +directive @annotate(type: String!) on FIELD + +### Polywrap Header END ### + +type Module @imports( + types: [ + "Ethereum_Module", + "Ethereum_Connection", + "Ethereum_TxOverrides", + "Ethereum_StaticTxResult", + "Ethereum_TxRequest", + "Ethereum_TxReceipt", + "Ethereum_Log", + "Ethereum_EventNotification", + "Ethereum_Network", + "Ethereum_TxResponse", + "Ethereum_Access" + ] +) { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Env { + arg1: String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +### Imported Modules START ### + +type Ethereum_Module @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Module" +) { + callContractView( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + callContractStatic( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_StaticTxResult! + + getBalance( + address: String! + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + encodeParams( + types: [String!]! + values: [String!]! + ): String! + + encodeFunction( + method: String! + args: [String!] + ): String! + + solidityPack( + types: [String!]! + values: [String!]! + ): String! + + solidityKeccak256( + types: [String!]! + values: [String!]! + ): String! + + soliditySha256( + types: [String!]! + values: [String!]! + ): String! + + getSignerAddress( + connection: Ethereum_Connection + ): String! + + getSignerBalance( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getSignerTransactionCount( + blockTag: BigInt + connection: Ethereum_Connection + ): BigInt! + + getGasPrice( + connection: Ethereum_Connection + ): BigInt! + + estimateTransactionGas( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): BigInt! + + estimateContractCallGas( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): BigInt! + + checkAddress( + address: String! + ): Boolean! + + toWei( + eth: String! + ): BigInt! + + toEth( + wei: BigInt! + ): String! + + awaitTransaction( + txHash: String! + confirmations: UInt32! + timeout: UInt32! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + waitForEvent( + address: String! + event: String! + args: [String!] + timeout: UInt32 + connection: Ethereum_Connection + ): Ethereum_EventNotification! + + getNetwork( + connection: Ethereum_Connection + ): Ethereum_Network! + + callContractMethod( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxResponse! + + callContractMethodAndWait( + address: String! + method: String! + args: [String!] + connection: Ethereum_Connection + txOverrides: Ethereum_TxOverrides + ): Ethereum_TxReceipt! + + sendTransaction( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxResponse! + + sendTransactionAndWait( + tx: Ethereum_TxRequest! + connection: Ethereum_Connection + ): Ethereum_TxReceipt! + + deployContract( + abi: String! + bytecode: String! + args: [String!] + connection: Ethereum_Connection + ): String! + + signMessage( + message: String! + connection: Ethereum_Connection + ): String! + + sendRPC( + method: String! + params: [String!]! + connection: Ethereum_Connection + ): String +} + +### Imported Modules END ### + +### Imported Objects START ### + +type Ethereum_Connection @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Connection" +) { + node: String + networkNameOrChainId: String +} + +type Ethereum_TxOverrides @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxOverrides" +) { + gasLimit: BigInt + gasPrice: BigInt + value: BigInt +} + +type Ethereum_StaticTxResult @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "StaticTxResult" +) { + result: String! + error: Boolean! +} + +type Ethereum_TxRequest @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxRequest" +) { + to: String + from: String + nonce: UInt32 + gasLimit: BigInt + gasPrice: BigInt + data: String + value: BigInt + chainId: BigInt + type: UInt32 +} + +type Ethereum_TxReceipt @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxReceipt" +) { + to: String! + from: String! + contractAddress: String! + transactionIndex: UInt32! + root: String + gasUsed: BigInt! + logsBloom: String! + transactionHash: String! + logs: [Ethereum_Log!]! + blockNumber: BigInt! + blockHash: String! + confirmations: UInt32! + cumulativeGasUsed: BigInt! + effectiveGasPrice: BigInt! + byzantium: Boolean! + type: UInt32! + status: UInt32 +} + +type Ethereum_Log @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Log" +) { + blockNumber: BigInt! + blockHash: String! + transactionIndex: UInt32! + removed: Boolean! + address: String! + data: String! + topics: [String!]! + transactionHash: String! + logIndex: UInt32! +} + +type Ethereum_EventNotification @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "EventNotification" +) { + data: String! + address: String! + log: Ethereum_Log! +} + +type Ethereum_Network @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Network" +) { + name: String! + chainId: BigInt! + ensAddress: String +} + +type Ethereum_TxResponse @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "TxResponse" +) { + hash: String! + to: String + from: String! + nonce: UInt32! + gasLimit: BigInt! + gasPrice: BigInt + data: String! + value: BigInt! + chainId: BigInt! + blockNumber: BigInt + blockHash: String + timestamp: UInt32 + confirmations: UInt32! + raw: String + r: String + s: String + v: UInt32 + type: UInt32 + accessList: [Ethereum_Access!] +} + +type Ethereum_Access @imported( + uri: "ens/ethereum.polywrap.eth", + namespace: "Ethereum", + nativeType: "Access" +) { + address: String! + storageKeys: [String!]! +} + +### Imported Objects END ### +`; diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts new file mode 100644 index 0000000000..bb9273518b --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts @@ -0,0 +1,640 @@ +/// NOTE: This is an auto-generated file. +/// All modifications will be overwritten. + +// @ts-ignore +import * as Types from "./"; + +// @ts-ignore +import { + Client, + InvokeResult +} from "@polywrap/core-js"; + +export type UInt = number; +export type UInt8 = number; +export type UInt16 = number; +export type UInt32 = number; +export type Int = number; +export type Int8 = number; +export type Int16 = number; +export type Int32 = number; +export type Bytes = Uint8Array; +export type BigInt = string; +export type BigNumber = string; +export type Json = string; +export type String = string; +export type Boolean = boolean; + +/// Envs START /// +export interface Env extends Record { + arg1: Types.String; +} +/// Envs END /// + +/// Objects START /// +export interface Object { + u: Types.UInt; + array: Array; + bytes?: Types.Bytes | null; +} + +/// Objects END /// + +/// Enums START /// +/// Enums END /// + +/// Imported Objects START /// + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Connection { + node?: Types.String | null; + networkNameOrChainId?: Types.String | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxOverrides { + gasLimit?: Types.BigInt | null; + gasPrice?: Types.BigInt | null; + value?: Types.BigInt | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_StaticTxResult { + result: Types.String; + error: Types.Boolean; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxRequest { + to?: Types.String | null; + from?: Types.String | null; + nonce?: Types.UInt32 | null; + gasLimit?: Types.BigInt | null; + gasPrice?: Types.BigInt | null; + data?: Types.String | null; + value?: Types.BigInt | null; + chainId?: Types.BigInt | null; + type?: Types.UInt32 | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxReceipt { + to: Types.String; + from: Types.String; + contractAddress: Types.String; + transactionIndex: Types.UInt32; + root?: Types.String | null; + gasUsed: Types.BigInt; + logsBloom: Types.String; + transactionHash: Types.String; + logs: Array; + blockNumber: Types.BigInt; + blockHash: Types.String; + confirmations: Types.UInt32; + cumulativeGasUsed: Types.BigInt; + effectiveGasPrice: Types.BigInt; + byzantium: Types.Boolean; + type: Types.UInt32; + status?: Types.UInt32 | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Log { + blockNumber: Types.BigInt; + blockHash: Types.String; + transactionIndex: Types.UInt32; + removed: Types.Boolean; + address: Types.String; + data: Types.String; + topics: Array; + transactionHash: Types.String; + logIndex: Types.UInt32; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_EventNotification { + data: Types.String; + address: Types.String; + log: Types.Ethereum_Log; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Network { + name: Types.String; + chainId: Types.BigInt; + ensAddress?: Types.String | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_TxResponse { + hash: Types.String; + to?: Types.String | null; + from: Types.String; + nonce: Types.UInt32; + gasLimit: Types.BigInt; + gasPrice?: Types.BigInt | null; + data: Types.String; + value: Types.BigInt; + chainId: Types.BigInt; + blockNumber?: Types.BigInt | null; + blockHash?: Types.String | null; + timestamp?: Types.UInt32 | null; + confirmations: Types.UInt32; + raw?: Types.String | null; + r?: Types.String | null; + s?: Types.String | null; + v?: Types.UInt32 | null; + type?: Types.UInt32 | null; + accessList?: Array | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export interface Ethereum_Access { + address: Types.String; + storageKeys: Array; +} + +/// Imported Objects END /// + +/// Imported Modules START /// + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractView extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractStatic extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getBalance extends Record { + address: Types.String; + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_encodeParams extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_encodeFunction extends Record { + method: Types.String; + args?: Array | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_solidityPack extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_solidityKeccak256 extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_soliditySha256 extends Record { + types: Array; + values: Array; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerAddress extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerBalance extends Record { + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getSignerTransactionCount extends Record { + blockTag?: Types.BigInt | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getGasPrice extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_estimateTransactionGas extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_estimateContractCallGas extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_checkAddress extends Record { + address: Types.String; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_toWei extends Record { + eth: Types.String; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_toEth extends Record { + wei: Types.BigInt; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_awaitTransaction extends Record { + txHash: Types.String; + confirmations: Types.UInt32; + timeout: Types.UInt32; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_waitForEvent extends Record { + address: Types.String; + event: Types.String; + args?: Array | null; + timeout?: Types.UInt32 | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_getNetwork extends Record { + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractMethod extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_callContractMethodAndWait extends Record { + address: Types.String; + method: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; + txOverrides?: Types.Ethereum_TxOverrides | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendTransaction extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendTransactionAndWait extends Record { + tx: Types.Ethereum_TxRequest; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_deployContract extends Record { + abi: Types.String; + bytecode: Types.String; + args?: Array | null; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_signMessage extends Record { + message: Types.String; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +interface Ethereum_Module_Args_sendRPC extends Record { + method: Types.String; + params: Array; + connection?: Types.Ethereum_Connection | null; +} + +/* URI: "ens/ethereum.polywrap.eth" */ +export const Ethereum_Module = { + callContractView: async ( + args: Ethereum_Module_Args_callContractView, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractView", + args + }); + }, + + callContractStatic: async ( + args: Ethereum_Module_Args_callContractStatic, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractStatic", + args + }); + }, + + getBalance: async ( + args: Ethereum_Module_Args_getBalance, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getBalance", + args + }); + }, + + encodeParams: async ( + args: Ethereum_Module_Args_encodeParams, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "encodeParams", + args + }); + }, + + encodeFunction: async ( + args: Ethereum_Module_Args_encodeFunction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "encodeFunction", + args + }); + }, + + solidityPack: async ( + args: Ethereum_Module_Args_solidityPack, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "solidityPack", + args + }); + }, + + solidityKeccak256: async ( + args: Ethereum_Module_Args_solidityKeccak256, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "solidityKeccak256", + args + }); + }, + + soliditySha256: async ( + args: Ethereum_Module_Args_soliditySha256, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "soliditySha256", + args + }); + }, + + getSignerAddress: async ( + args: Ethereum_Module_Args_getSignerAddress, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerAddress", + args + }); + }, + + getSignerBalance: async ( + args: Ethereum_Module_Args_getSignerBalance, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerBalance", + args + }); + }, + + getSignerTransactionCount: async ( + args: Ethereum_Module_Args_getSignerTransactionCount, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getSignerTransactionCount", + args + }); + }, + + getGasPrice: async ( + args: Ethereum_Module_Args_getGasPrice, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getGasPrice", + args + }); + }, + + estimateTransactionGas: async ( + args: Ethereum_Module_Args_estimateTransactionGas, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "estimateTransactionGas", + args + }); + }, + + estimateContractCallGas: async ( + args: Ethereum_Module_Args_estimateContractCallGas, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "estimateContractCallGas", + args + }); + }, + + checkAddress: async ( + args: Ethereum_Module_Args_checkAddress, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "checkAddress", + args + }); + }, + + toWei: async ( + args: Ethereum_Module_Args_toWei, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "toWei", + args + }); + }, + + toEth: async ( + args: Ethereum_Module_Args_toEth, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "toEth", + args + }); + }, + + awaitTransaction: async ( + args: Ethereum_Module_Args_awaitTransaction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "awaitTransaction", + args + }); + }, + + waitForEvent: async ( + args: Ethereum_Module_Args_waitForEvent, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "waitForEvent", + args + }); + }, + + getNetwork: async ( + args: Ethereum_Module_Args_getNetwork, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "getNetwork", + args + }); + }, + + callContractMethod: async ( + args: Ethereum_Module_Args_callContractMethod, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractMethod", + args + }); + }, + + callContractMethodAndWait: async ( + args: Ethereum_Module_Args_callContractMethodAndWait, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "callContractMethodAndWait", + args + }); + }, + + sendTransaction: async ( + args: Ethereum_Module_Args_sendTransaction, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendTransaction", + args + }); + }, + + sendTransactionAndWait: async ( + args: Ethereum_Module_Args_sendTransactionAndWait, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendTransactionAndWait", + args + }); + }, + + deployContract: async ( + args: Ethereum_Module_Args_deployContract, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "deployContract", + args + }); + }, + + signMessage: async ( + args: Ethereum_Module_Args_signMessage, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "signMessage", + args + }); + }, + + sendRPC: async ( + args: Ethereum_Module_Args_sendRPC, + client: Client + ): Promise> => { + return client.invoke({ + uri: "ens/ethereum.polywrap.eth", + method: "sendRPC", + args + }); + } +} + +/// Imported Modules END /// diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/polywrap.custom.plugin.yaml b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/polywrap.custom.plugin.yaml new file mode 100644 index 0000000000..ac7abe08e5 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/polywrap.custom.plugin.yaml @@ -0,0 +1,5 @@ +format: 0.0.1-prealpha.3 +name: Test +language: plugin/typescript +schema: ./schema.graphql +module: ./src/index.ts diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/schema.graphql b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/schema.graphql new file mode 100644 index 0000000000..acad0ae76c --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/schema.graphql @@ -0,0 +1,22 @@ +#import { Module } into Ethereum from "ens/ethereum.polywrap.eth" + +type Module { + methodOne( + str: String! + optStr: String + ): Object! + + methodTwo( + arg: UInt32! + ): String! +} + +type Object { + u: UInt! + array: [Boolean!]! + bytes: Bytes +} + +type Env { + arg1: String! +} diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/src/index.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/src/index.ts new file mode 100644 index 0000000000..5bb85ff3e4 --- /dev/null +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/src/index.ts @@ -0,0 +1 @@ +export * from "./wrap"; diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/output.json index 2f5da39ad0..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/output.json @@ -1,8 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/001-sanity/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/002-invalid-manifest-1/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/002-invalid-manifest-1/expected/stdout.json similarity index 100% rename from packages/test-cases/cases/cli/wasm/build-cmd/002-invalid-manifest-1/expected/output.json rename to packages/test-cases/cases/cli/wasm/build-cmd/002-invalid-manifest-1/expected/stdout.json diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/003-invalid-manifest-2/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/003-invalid-manifest-2/expected/stdout.json similarity index 100% rename from packages/test-cases/cases/cli/wasm/build-cmd/003-invalid-manifest-2/expected/output.json rename to packages/test-cases/cases/cli/wasm/build-cmd/003-invalid-manifest-2/expected/stdout.json diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/output.json index 2f5da39ad0..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/output.json @@ -1,8 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/004-default-build/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/output.json index 2f5da39ad0..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/output.json @@ -1,8 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/005-default-dockerfile/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/output.json index 2f5da39ad0..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/output.json @@ -1,8 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/006-custom-dockerfile/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/output.json index 2f5da39ad0..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/output.json @@ -1,8 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/007-linked-packages/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/output.json index 31c089053b..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/output.json @@ -1,13 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json", - "build/polywrap.meta.json", - "build/meta/queries/test.graphql", - "build/meta/queries/test.json", - "build/meta/links/link.svg", - "build/meta/icon/icon.png" - ], - "exitCode": 0 -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/stdout.json new file mode 100644 index 0000000000..31c089053b --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/008-metadata/expected/stdout.json @@ -0,0 +1,13 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json", + "build/polywrap.meta.json", + "build/meta/queries/test.graphql", + "build/meta/queries/test.json", + "build/meta/links/link.svg", + "build/meta/icon/icon.png" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/output.json index 9d8067dee4..97ca582cee 100644 --- a/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/output.json +++ b/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/output.json @@ -1,14 +1,6 @@ -{ - "stdout": [ - "Artifacts written to ./build from the image `polywrap-build-env-", - "Manifest written to ./build/polywrap.json", - "build/polywrap.json", - "docker rmi polywrap-build-env-", - "docker buildx rm polywrap-build-env-" - ], - "exitCode": 0, - "files": [ - ".polywrap/wasm/build/image/cache/index.json", - ".polywrap/wasm/build/image/cache/blobs/sha256/" - ] -} +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/stdout.json new file mode 100644 index 0000000000..9d8067dee4 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/009-docker-buildx/expected/stdout.json @@ -0,0 +1,14 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json", + "docker rmi polywrap-build-env-", + "docker buildx rm polywrap-build-env-" + ], + "exitCode": 0, + "files": [ + ".polywrap/wasm/build/image/cache/index.json", + ".polywrap/wasm/build/image/cache/blobs/sha256/" + ] +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/cmd.json b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/cmd.json new file mode 100644 index 0000000000..aa6170b001 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-c", "./config.ts"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/config.ts b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/config.ts new file mode 100644 index 0000000000..a51cd93907 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/config.ts @@ -0,0 +1,51 @@ +import { PolywrapClientConfig } from "@polywrap/client-js"; +import { PluginModule } from "@polywrap/core-js"; + +interface Config extends Record { + val: number; +} + +class MockPlugin extends PluginModule { + + getData(_: unknown): number { return this.config.val; } + + setData(args: { value: number }) { + this.config.val = +args.value; + return true; + } + + deployContract(): string { return "0x100"; } +} + +const mockPlugin = () => { + return { + factory: () => new MockPlugin({ val: 0 }), + manifest: { + schema: ` + type Module { + getData: Int! + setData(value: Int!): Boolean! + deployContract: String! + } + `, + implements: [], + }, + }; +}; + +export function getClientConfig(defaultConfigs: Partial) { + if (defaultConfigs.plugins) { + defaultConfigs.plugins.push({ + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }); + } else { + defaultConfigs.plugins = [ + { + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }, + ]; + } + return defaultConfigs; +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/output.json new file mode 100644 index 0000000000..97ca582cee --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/output.json @@ -0,0 +1,6 @@ +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/package.json b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/package.json new file mode 100644 index 0000000000..06c2689137 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/package.json @@ -0,0 +1,15 @@ +{ + "name": "@polywrap/test-project", + "version": "0.0.1-prealpha.72", + "license": "MIT", + "private": true, + "scripts": { + "build": "polywrap build" + }, + "dependencies": { + "@polywrap/wasm-as": "0.0.1-prealpha.72" + }, + "devDependencies": { + "assemblyscript": "0.19.5" + } +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.build.yaml b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.build.yaml new file mode 100644 index 0000000000..9f8b2d1fc6 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.build.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.2 +config: + node_version: "14.16.0" +linked_packages: + - name: "@polywrap/wasm-as" + path: ../../../../../../wasm/as diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.yaml b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.yaml new file mode 100644 index 0000000000..370224c8aa --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/polywrap.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.9 +name: test-project +build: ./polywrap.build.yaml +language: wasm/assemblyscript +module: ./src/index.ts +schema: ./src/schema.graphql diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/index.ts b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/index.ts new file mode 100644 index 0000000000..b7e03abfee --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/index.ts @@ -0,0 +1,9 @@ +import { Args_method, Mock_Module } from "./wrap"; + +export function method(args: Args_method): string { + return args.arg; +} + +export function deployContract(): string { + return Mock_Module.deployContract({}).unwrap(); +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/schema.graphql b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/schema.graphql new file mode 100644 index 0000000000..928ed3bdb9 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/010-custom-config/src/schema.graphql @@ -0,0 +1,9 @@ +#import * into Mock from "wrap://ens/mock.eth" + +type Module { + method( + arg: String! + ): String! + + deployContract: String! +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/cmd.json b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/cmd.json new file mode 100644 index 0000000000..2009d3aa55 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-m", "./polywrap.custom.yaml"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/output.json b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/output.json new file mode 100644 index 0000000000..97ca582cee --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/output.json @@ -0,0 +1,6 @@ +[ + "module.wasm", + "polywrap.json", + "polywrap.build.json", + "schema.graphql" +] \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/stdout.json b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/stdout.json new file mode 100644 index 0000000000..2f5da39ad0 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/expected/stdout.json @@ -0,0 +1,8 @@ +{ + "stdout": [ + "Artifacts written to ./build from the image `polywrap-build-env-", + "Manifest written to ./build/polywrap.json", + "build/polywrap.json" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/package.json b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/package.json new file mode 100644 index 0000000000..06c2689137 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/package.json @@ -0,0 +1,15 @@ +{ + "name": "@polywrap/test-project", + "version": "0.0.1-prealpha.72", + "license": "MIT", + "private": true, + "scripts": { + "build": "polywrap build" + }, + "dependencies": { + "@polywrap/wasm-as": "0.0.1-prealpha.72" + }, + "devDependencies": { + "assemblyscript": "0.19.5" + } +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.build.yaml b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.build.yaml new file mode 100644 index 0000000000..9f8b2d1fc6 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.build.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.2 +config: + node_version: "14.16.0" +linked_packages: + - name: "@polywrap/wasm-as" + path: ../../../../../../wasm/as diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.yaml b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.yaml new file mode 100644 index 0000000000..2c076ed92d --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/polywrap.custom.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.9 +name: test-project +build: ./polywrap.custom.build.yaml +language: wasm/assemblyscript +module: ./src/index.ts +schema: ./src/schema.graphql diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/index.ts b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/index.ts new file mode 100644 index 0000000000..862d4cb226 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/index.ts @@ -0,0 +1,5 @@ +import { Args_method } from "./wrap"; + +export function method(args: Args_method): string { + return args.arg; +} diff --git a/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/schema.graphql b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/schema.graphql new file mode 100644 index 0000000000..325e224971 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/build-cmd/011-custom-config/src/schema.graphql @@ -0,0 +1,5 @@ +type Module { + method( + arg: String! + ): String! +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/001-sanity/expected/output.json b/packages/test-cases/cases/cli/wasm/codegen/001-sanity/expected/stdout.json similarity index 100% rename from packages/test-cases/cases/cli/wasm/codegen/001-sanity/expected/output.json rename to packages/test-cases/cases/cli/wasm/codegen/001-sanity/expected/stdout.json diff --git a/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/expected/output.json b/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/expected/stdout.json similarity index 100% rename from packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/expected/output.json rename to packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/expected/stdout.json diff --git a/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/polywrap-norun.gen.js b/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/polywrap-norun.gen.js index 8fbe5a3942..f874fce4c8 100644 --- a/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/polywrap-norun.gen.js +++ b/packages/test-cases/cases/cli/wasm/codegen/002-invalid-codegen-script/polywrap-norun.gen.js @@ -2,7 +2,7 @@ exports.generate = (output, config) => { output.entries.push({ type: "File", name: "./schema1.ts", - data: config.generate("./templates/schema1.mustache", config.typeInfo), + data: config.generate("./templates/schema1.mustache", config.abi), }); output.entries.push({ @@ -12,7 +12,7 @@ exports.generate = (output, config) => { { type: "File", name: "./schema2.ts", - data: config.generate("./templates/schema2.mustache", config.typeInfo), + data: config.generate("./templates/schema2.mustache", config.abi), }, ], }); diff --git a/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/cmd.json b/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/cmd.json index 64290f576f..41da6c8ed9 100644 --- a/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/cmd.json +++ b/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/cmd.json @@ -1,3 +1,4 @@ { - "args": ["--script", "polywrap.gen.ts"] + "args": ["--script", "polywrap.gen.ts"], + "codegenDir": "./wrap" } \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/expected/output.json b/packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/expected/stdout.json similarity index 100% rename from packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/expected/output.json rename to packages/test-cases/cases/cli/wasm/codegen/003-codegen-script/expected/stdout.json diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/cmd.json b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/cmd.json new file mode 100644 index 0000000000..aa6170b001 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-c", "./config.ts"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/config.ts b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/config.ts new file mode 100644 index 0000000000..a51cd93907 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/config.ts @@ -0,0 +1,51 @@ +import { PolywrapClientConfig } from "@polywrap/client-js"; +import { PluginModule } from "@polywrap/core-js"; + +interface Config extends Record { + val: number; +} + +class MockPlugin extends PluginModule { + + getData(_: unknown): number { return this.config.val; } + + setData(args: { value: number }) { + this.config.val = +args.value; + return true; + } + + deployContract(): string { return "0x100"; } +} + +const mockPlugin = () => { + return { + factory: () => new MockPlugin({ val: 0 }), + manifest: { + schema: ` + type Module { + getData: Int! + setData(value: Int!): Boolean! + deployContract: String! + } + `, + implements: [], + }, + }; +}; + +export function getClientConfig(defaultConfigs: Partial) { + if (defaultConfigs.plugins) { + defaultConfigs.plugins.push({ + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }); + } else { + defaultConfigs.plugins = [ + { + uri: "wrap://ens/mock.eth", + plugin: mockPlugin(), + }, + ]; + } + return defaultConfigs; +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/expected/stdout.json b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/expected/stdout.json new file mode 100644 index 0000000000..3e4855fba4 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/expected/stdout.json @@ -0,0 +1,6 @@ +{ + "stdout": [ + "Types were generated successfully" + ], + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/package.json b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/package.json new file mode 100644 index 0000000000..06c2689137 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/package.json @@ -0,0 +1,15 @@ +{ + "name": "@polywrap/test-project", + "version": "0.0.1-prealpha.72", + "license": "MIT", + "private": true, + "scripts": { + "build": "polywrap build" + }, + "dependencies": { + "@polywrap/wasm-as": "0.0.1-prealpha.72" + }, + "devDependencies": { + "assemblyscript": "0.19.5" + } +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.build.yaml b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.build.yaml new file mode 100644 index 0000000000..9f8b2d1fc6 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.build.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.2 +config: + node_version: "14.16.0" +linked_packages: + - name: "@polywrap/wasm-as" + path: ../../../../../../wasm/as diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.yaml b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.yaml new file mode 100644 index 0000000000..b8a9cd03c9 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/polywrap.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.9 +name: test-project +build: ./polywrap.build.yaml +language: wasm/assemblyscript +schema: ./schema.graphql +module: ./src/index.ts diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/schema.graphql b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/schema.graphql new file mode 100644 index 0000000000..928ed3bdb9 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/schema.graphql @@ -0,0 +1,9 @@ +#import * into Mock from "wrap://ens/mock.eth" + +type Module { + method( + arg: String! + ): String! + + deployContract: String! +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/src/index.ts b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/src/index.ts new file mode 100644 index 0000000000..2c9e567878 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/004-custom-config/src/index.ts @@ -0,0 +1,9 @@ +import { Args_method, Mock_deployContract } from "./wrap"; + +export function method(args: Args_method): string { + return args.arg; +} + +export function deployContract(): string { + return Mock_deployContract({}).unwrap(); +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/cmd.json b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/cmd.json new file mode 100644 index 0000000000..2009d3aa55 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/cmd.json @@ -0,0 +1,3 @@ +{ + "args": ["-m", "./polywrap.custom.yaml"] +} \ No newline at end of file diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/expected/stdout.json b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/expected/stdout.json new file mode 100644 index 0000000000..735a6dca2c --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/expected/stdout.json @@ -0,0 +1,4 @@ +{ + "stdout": "Types were generated successfully", + "exitCode": 0 +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/package.json b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/package.json new file mode 100644 index 0000000000..06c2689137 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/package.json @@ -0,0 +1,15 @@ +{ + "name": "@polywrap/test-project", + "version": "0.0.1-prealpha.72", + "license": "MIT", + "private": true, + "scripts": { + "build": "polywrap build" + }, + "dependencies": { + "@polywrap/wasm-as": "0.0.1-prealpha.72" + }, + "devDependencies": { + "assemblyscript": "0.19.5" + } +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.build.yaml b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.build.yaml new file mode 100644 index 0000000000..9f8b2d1fc6 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.build.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.2 +config: + node_version: "14.16.0" +linked_packages: + - name: "@polywrap/wasm-as" + path: ../../../../../../wasm/as diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.yaml b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.yaml new file mode 100644 index 0000000000..b8a9cd03c9 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/polywrap.custom.yaml @@ -0,0 +1,6 @@ +format: 0.0.1-prealpha.9 +name: test-project +build: ./polywrap.build.yaml +language: wasm/assemblyscript +schema: ./schema.graphql +module: ./src/index.ts diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/schema.graphql b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/schema.graphql new file mode 100644 index 0000000000..325e224971 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/schema.graphql @@ -0,0 +1,5 @@ +type Module { + method( + arg: String! + ): String! +} diff --git a/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/src/index.ts b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/src/index.ts new file mode 100644 index 0000000000..862d4cb226 --- /dev/null +++ b/packages/test-cases/cases/cli/wasm/codegen/005-custom-manifest-file/src/index.ts @@ -0,0 +1,5 @@ +import { Args_method } from "./wrap"; + +export function method(args: Args_method): string { + return args.arg; +} diff --git a/packages/test-cases/cases/cli/wasm/run/workflows/config.ts b/packages/test-cases/cases/cli/wasm/run/workflows/config.ts index 0869b4de1a..8a657de59b 100644 --- a/packages/test-cases/cases/cli/wasm/run/workflows/config.ts +++ b/packages/test-cases/cases/cli/wasm/run/workflows/config.ts @@ -1,6 +1,7 @@ import { PolywrapClientConfig } from "@polywrap/client-js"; import { ClientConfig, coreInterfaceUris } from "@polywrap/client-js"; -import { ensPlugin } from "@polywrap/ens-plugin-js"; +import { ipfsResolverPlugin } from "@polywrap/ipfs-resolver-plugin-js"; +import { ensResolverPlugin } from "@polywrap/ens-resolver-plugin-js"; import { ethereumPlugin } from "@polywrap/ethereum-plugin-js"; import { ipfsPlugin } from "@polywrap/ipfs-plugin-js"; @@ -40,8 +41,14 @@ function getPlugins( plugin: ipfsPlugin({ provider: ipfs }), }, { - uri: "wrap://ens/ens.polywrap.eth", - plugin: ensPlugin({ addresses: { testnet: ensAddress } }), + uri: "wrap://ens/ipfs-resolver.polywrap.eth", + plugin: ipfsResolverPlugin({ + provider: ipfs, + }), + }, + { + uri: "wrap://ens/ens-resolver.polywrap.eth", + plugin: ensResolverPlugin({ addresses: { testnet: ensAddress } }), }, { uri: "wrap://ens/ethereum.polywrap.eth", @@ -62,8 +69,8 @@ function getPlugins( { interface: coreInterfaceUris.uriResolver.uri, implementations: [ - "wrap://ens/ipfs.polywrap.eth", - "wrap://ens/ens.polywrap.eth", + "wrap://ens/ipfs-resolver.polywrap.eth", + "wrap://ens/ens-resolver.polywrap.eth", ], }, { diff --git a/packages/test-cases/cases/compose/001-local-imports/00-sanity/output/module.ts b/packages/test-cases/cases/compose/001-local-imports/00-sanity/output/module.ts index 7e5ffbae7d..b40ef62381 100644 --- a/packages/test-cases/cases/compose/001-local-imports/00-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/001-local-imports/00-sanity/output/module.ts @@ -8,14 +8,14 @@ import { createObjectPropertyDefinition, createObjectDefinition, createEnumDefinition, - TypeInfo, + Abi, createEnumPropertyDefinition, createObjectRef, - createTypeInfo + createAbi } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), moduleType: { ...createModuleDefinition({}), diff --git a/packages/test-cases/cases/compose/001-local-imports/01-nested-objects/output/module.ts b/packages/test-cases/cases/compose/001-local-imports/01-nested-objects/output/module.ts index 15d72042cb..948afdd812 100644 --- a/packages/test-cases/cases/compose/001-local-imports/01-nested-objects/output/module.ts +++ b/packages/test-cases/cases/compose/001-local-imports/01-nested-objects/output/module.ts @@ -4,12 +4,12 @@ import { createScalarPropertyDefinition, createObjectDefinition, createObjectPropertyDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/001-local-imports/02-recursive/output/module.ts b/packages/test-cases/cases/compose/001-local-imports/02-recursive/output/module.ts index 52ab74bc3f..f45a63c554 100644 --- a/packages/test-cases/cases/compose/001-local-imports/02-recursive/output/module.ts +++ b/packages/test-cases/cases/compose/001-local-imports/02-recursive/output/module.ts @@ -4,12 +4,12 @@ import { createScalarPropertyDefinition, createObjectDefinition, createObjectPropertyDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/001-local-imports/03-wild-card/output/module.ts b/packages/test-cases/cases/compose/001-local-imports/03-wild-card/output/module.ts index cde655ddf1..4373d1585e 100644 --- a/packages/test-cases/cases/compose/001-local-imports/03-wild-card/output/module.ts +++ b/packages/test-cases/cases/compose/001-local-imports/03-wild-card/output/module.ts @@ -9,14 +9,14 @@ import { createObjectPropertyDefinition, createObjectDefinition, createEnumDefinition, - TypeInfo, + Abi, createEnumPropertyDefinition, createObjectRef, - createTypeInfo, + createAbi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ type: "CustomModuleType" }), diff --git a/packages/test-cases/cases/compose/002-external-imports/00-sanity/output/module.ts b/packages/test-cases/cases/compose/002-external-imports/00-sanity/output/module.ts index a7785cc6b4..252babedcf 100644 --- a/packages/test-cases/cases/compose/002-external-imports/00-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/002-external-imports/00-sanity/output/module.ts @@ -4,12 +4,12 @@ import { createObjectPropertyDefinition, createImportedObjectDefinition, createScalarPropertyDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ ], moduleType: { diff --git a/packages/test-cases/cases/compose/002-external-imports/01-with-duplicate-local-type/output/module.ts b/packages/test-cases/cases/compose/002-external-imports/01-with-duplicate-local-type/output/module.ts index 9d1aa0b8c6..253c9acc64 100644 --- a/packages/test-cases/cases/compose/002-external-imports/01-with-duplicate-local-type/output/module.ts +++ b/packages/test-cases/cases/compose/002-external-imports/01-with-duplicate-local-type/output/module.ts @@ -5,12 +5,12 @@ import { createObjectPropertyDefinition, createImportedObjectDefinition, createScalarPropertyDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ type: "LocalType" }), diff --git a/packages/test-cases/cases/compose/002-external-imports/02-wild-card/output/module.ts b/packages/test-cases/cases/compose/002-external-imports/02-wild-card/output/module.ts index 801a2c7514..94b778e0ba 100644 --- a/packages/test-cases/cases/compose/002-external-imports/02-wild-card/output/module.ts +++ b/packages/test-cases/cases/compose/002-external-imports/02-wild-card/output/module.ts @@ -4,12 +4,12 @@ import { createObjectPropertyDefinition, createImportedObjectDefinition, createScalarPropertyDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ ], moduleType: diff --git a/packages/test-cases/cases/compose/003-inheritance/01-sanity/output/module.ts b/packages/test-cases/cases/compose/003-inheritance/01-sanity/output/module.ts index 15d11abd62..ff6294782b 100644 --- a/packages/test-cases/cases/compose/003-inheritance/01-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/003-inheritance/01-sanity/output/module.ts @@ -5,12 +5,12 @@ import { createObjectPropertyDefinition, createScalarPropertyDefinition, createInterfaceImplementedDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ type: "BaseType1" }), diff --git a/packages/test-cases/cases/compose/004-empty-types/00-sanity/output/module.ts b/packages/test-cases/cases/compose/004-empty-types/00-sanity/output/module.ts index af9099dcb4..33d9884369 100644 --- a/packages/test-cases/cases/compose/004-empty-types/00-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/004-empty-types/00-sanity/output/module.ts @@ -1,12 +1,12 @@ import { createModuleDefinition, createObjectDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/004-empty-types/01-inherited/output/module.ts b/packages/test-cases/cases/compose/004-empty-types/01-inherited/output/module.ts index b89f1184b6..4459ffc254 100644 --- a/packages/test-cases/cases/compose/004-empty-types/01-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/004-empty-types/01-inherited/output/module.ts @@ -4,12 +4,12 @@ import { createObjectDefinition, createObjectPropertyDefinition, createInterfaceImplementedDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/004-empty-types/02-imported-inherited/output/module.ts b/packages/test-cases/cases/compose/004-empty-types/02-imported-inherited/output/module.ts index a1d703b8c2..41c99b6800 100644 --- a/packages/test-cases/cases/compose/004-empty-types/02-imported-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/004-empty-types/02-imported-inherited/output/module.ts @@ -4,12 +4,12 @@ import { createObjectDefinition, createObjectPropertyDefinition, createInterfaceImplementedDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/004-empty-types/03-external-import/output/module.ts b/packages/test-cases/cases/compose/004-empty-types/03-external-import/output/module.ts index c2ec45c02d..2cbcfc58ff 100644 --- a/packages/test-cases/cases/compose/004-empty-types/03-external-import/output/module.ts +++ b/packages/test-cases/cases/compose/004-empty-types/03-external-import/output/module.ts @@ -2,12 +2,12 @@ import { createModuleDefinition, createInterfaceImplementedDefinition, createImportedModuleDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), moduleType: { ...createModuleDefinition({}), diff --git a/packages/test-cases/cases/compose/004-empty-types/04-external-import-inherited/output/module.ts b/packages/test-cases/cases/compose/004-empty-types/04-external-import-inherited/output/module.ts index 2d0d64bdc8..8f55b26541 100644 --- a/packages/test-cases/cases/compose/004-empty-types/04-external-import-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/004-empty-types/04-external-import-inherited/output/module.ts @@ -5,12 +5,12 @@ import { createObjectPropertyDefinition, createInterfaceImplementedDefinition, createImportedObjectDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/005-map-types/00-sanity/output/module.ts b/packages/test-cases/cases/compose/005-map-types/00-sanity/output/module.ts index 9b4d2e32a0..3c6972ef22 100644 --- a/packages/test-cases/cases/compose/005-map-types/00-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/005-map-types/00-sanity/output/module.ts @@ -7,12 +7,12 @@ import { createModuleDefinition, createObjectDefinition, createScalarDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/005-map-types/01-inherited/output/module.ts b/packages/test-cases/cases/compose/005-map-types/01-inherited/output/module.ts index 4f89f7f026..8ec8ff2a82 100644 --- a/packages/test-cases/cases/compose/005-map-types/01-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/005-map-types/01-inherited/output/module.ts @@ -8,12 +8,12 @@ import { createObjectDefinition, createObjectPropertyDefinition, createScalarDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/005-map-types/02-imported-inherited/output/module.ts b/packages/test-cases/cases/compose/005-map-types/02-imported-inherited/output/module.ts index 27c4e33b67..e75b3b974f 100644 --- a/packages/test-cases/cases/compose/005-map-types/02-imported-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/005-map-types/02-imported-inherited/output/module.ts @@ -8,12 +8,12 @@ import { createObjectDefinition, createObjectPropertyDefinition, createScalarDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/005-map-types/03-external-import/output/module.ts b/packages/test-cases/cases/compose/005-map-types/03-external-import/output/module.ts index db5ee1041c..d0a619d2da 100644 --- a/packages/test-cases/cases/compose/005-map-types/03-external-import/output/module.ts +++ b/packages/test-cases/cases/compose/005-map-types/03-external-import/output/module.ts @@ -2,16 +2,16 @@ import { createModuleDefinition, createInterfaceImplementedDefinition, createImportedModuleDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, createMethodDefinition, createMapPropertyDefinition, createMapKeyDefinition, createScalarDefinition, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), moduleType: { ...createModuleDefinition({}), diff --git a/packages/test-cases/cases/compose/005-map-types/04-external-import-inherited/output/module.ts b/packages/test-cases/cases/compose/005-map-types/04-external-import-inherited/output/module.ts index b540b50ff7..d820973f42 100644 --- a/packages/test-cases/cases/compose/005-map-types/04-external-import-inherited/output/module.ts +++ b/packages/test-cases/cases/compose/005-map-types/04-external-import-inherited/output/module.ts @@ -5,16 +5,16 @@ import { createObjectPropertyDefinition, createInterfaceImplementedDefinition, createImportedObjectDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, createMapPropertyDefinition, createMapKeyDefinition, createScalarDefinition, createArrayDefinition, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/006-env-types/00-sanity/output/module.ts b/packages/test-cases/cases/compose/006-env-types/00-sanity/output/module.ts index dc77a206c6..bd012aee45 100644 --- a/packages/test-cases/cases/compose/006-env-types/00-sanity/output/module.ts +++ b/packages/test-cases/cases/compose/006-env-types/00-sanity/output/module.ts @@ -3,13 +3,13 @@ import { createModuleDefinition, createScalarPropertyDefinition, createObjectDefinition, - createTypeInfo, + createAbi, createEnvDefinition, - TypeInfo, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), envType: createEnvDefinition({ sanitized: { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/006-env-types/01-client-env/output/module.ts b/packages/test-cases/cases/compose/006-env-types/01-client-env/output/module.ts index 9be3133c06..58ecbf82f1 100644 --- a/packages/test-cases/cases/compose/006-env-types/01-client-env/output/module.ts +++ b/packages/test-cases/cases/compose/006-env-types/01-client-env/output/module.ts @@ -3,14 +3,14 @@ import { createModuleDefinition, createScalarPropertyDefinition, createObjectDefinition, - createTypeInfo, + createAbi, createEnvDefinition, - TypeInfo, + Abi, createObjectPropertyDefinition, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), envType: createEnvDefinition({ sanitized: { ...createObjectDefinition({ diff --git a/packages/test-cases/cases/compose/sanity/output/module.ts b/packages/test-cases/cases/compose/sanity/output/module.ts index 357d7c6b61..6a8ba83f1a 100644 --- a/packages/test-cases/cases/compose/sanity/output/module.ts +++ b/packages/test-cases/cases/compose/sanity/output/module.ts @@ -17,12 +17,12 @@ import { createInterfaceImplementedDefinition, createObjectRef, createEnvDefinition, - createTypeInfo, - TypeInfo, + createAbi, + Abi, } from "@polywrap/schema-parse"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), envType: createEnvDefinition({ sanitized: { ...createObjectDefinition({ type: "Env" }), diff --git a/packages/test-cases/cases/parse/recursive-properties/output.ts b/packages/test-cases/cases/parse/recursive-properties/output.ts index ad57e22b8a..0df8d3023e 100644 --- a/packages/test-cases/cases/parse/recursive-properties/output.ts +++ b/packages/test-cases/cases/parse/recursive-properties/output.ts @@ -1,14 +1,14 @@ import { - TypeInfo, - createTypeInfo, + Abi, + createAbi, createObjectDefinition, createObjectPropertyDefinition, createArrayPropertyDefinition, createObjectRef, -} from "../../../../schema/parse/src/typeInfo"; +} from "../../../../schema/parse/src/abi"; -export const typeInfo: TypeInfo = { - ...createTypeInfo(), +export const abi: Abi = { + ...createAbi(), objectTypes: [ { ...createObjectDefinition({ type: "Object" }), diff --git a/packages/test-cases/cases/parse/sanity/output.ts b/packages/test-cases/cases/parse/sanity/output.ts index 84b81ac922..7e45498bde 100644 --- a/packages/test-cases/cases/parse/sanity/output.ts +++ b/packages/test-cases/cases/parse/sanity/output.ts @@ -20,10 +20,10 @@ import { createObjectRef, createScalarDefinition, createScalarPropertyDefinition, - TypeInfo, -} from "../../../../schema/parse/src/typeInfo"; + Abi, +} from "../../../../schema/parse/src/abi"; -export const typeInfo: TypeInfo = { +export const abi: Abi = { interfaceTypes: [ createInterfaceDefinition({ type: "TestImport", diff --git a/packages/wasm/as/assembly/__tests__/msgpack_write.spec.ts b/packages/wasm/as/assembly/__tests__/msgpack_write.spec.ts new file mode 100644 index 0000000000..a24900c449 --- /dev/null +++ b/packages/wasm/as/assembly/__tests__/msgpack_write.spec.ts @@ -0,0 +1,454 @@ +import { Write } from "../msgpack/Write"; +import { WriteSizer } from "../msgpack/WriteSizer"; +import { WriteEncoder } from "../msgpack/WriteEncoder"; +import { BigInt, BigNumber } from "../math"; +import { JSON } from "../json"; + +function fill(arr: Array): ArrayBuffer { + const buffer = new ArrayBuffer(arr.length); + const offset = changetype(buffer); + for (let i: i32 = 0; i < arr.length; ++i) { + store(offset + i, arr[i]); + } + return buffer; +} + +class Case { + name: string; + input: T; + want: Array; + + constructor(name: string, input: T, want: Array) { + this.name = name; + this.input = input; + this.want = want; + } +} + +describe("WriteEncoder", () => { + it("TestWriteNil", () => { + const sizer = new WriteSizer(); + sizer.writeNil(); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeNil(); + + const actual = encoder._view.buffer; + const expected = fill([192]); + expect(actual).toStrictEqual(expected); + }); + + it("TestWriteBool", () => { + const cases = [ + new Case("false", false, [194]), + new Case("true", true, [195]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeBool(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeBool(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteInt8", () => { + const cases = [ + new Case("zero", 0, [0]), + new Case("negative fixed int", -1, [255]), + new Case("negative fixed int", -31, [225]), + new Case("negative fixed int", -32, [224]), + new Case("positive fixed int", 1, [1]), + new Case("positive fixed int", 127, [127]), + new Case("8-bit signed int", -128, [208, 128]), + new Case("8-bit signed int", -100, [208, 156]), + new Case("8-bit signed int", -33, [208, 223]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeInt8(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeInt8(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteInt16", () => { + const cases = [ + new Case("16-bit signed int (negative)", -32768, [209, 128, 0]), + new Case("16-bit signed int (negative)", -32767, [209, 128, 1]), + new Case("16-bit signed int (negative)", -129, [209, 255, 127]), + new Case("16-bit signed int (positive)", 128, [209, 0, 128]), + new Case("16-bit signed int (positive)", 32767, [209, 127, 255]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeInt16(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeInt16(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteInt32", () => { + const cases = [ + new Case("32-bit signed int (negative)", -32769, [210, 255, 255, 127, 255]), + new Case("32-bit signed int (negative)", -2147483648,[210, 128, 0, 0, 0]), + new Case("32-bit signed int (negative)", -2147483647,[210, 128, 0, 0, 1]), + new Case("32-bit signed int (positive)", 32768, [210, 0, 0, 128, 0]), + new Case("32-bit signed int (positive)", 123456, [210, 0, 1, 226, 64]), + new Case("32-bit signed int (positive)", 2147483647, [210, 127, 255, 255, 255]), + ] + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeInt32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeInt32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteUint8", () => { + const cases = [ + new Case("zero", 0, [0]), + new Case("positive fixed int", 1, [1]), + new Case("positive fixed int", 127, [127]), + new Case("8-bit unsigned int", 200, [204, 200]), + new Case("8-bit unsigned int", 255, [204, 255]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeUInt8(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeUInt8(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteUint16", () => { + const cases = [ + new Case("16-bit unsigned int", 256, [205, 1, 0]), + new Case("16-bit unsigned int", 32767, [205, 127, 255]), + new Case("16-bit unsigned int", 32768, [205, 128, 0]), + new Case("16-bit unsigned int", 65535, [205, 255, 255]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeUInt16(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeUInt16(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteUint32", () => { + const cases = [ + new Case("32-bit unsigned int", 65536, [206, 0, 1, 0, 0]), + new Case("32-bit unsigned int", 123456, [206, 0, 1, 226, 64]), + new Case("32-bit unsigned int", 2147483648, [206, 128, 0, 0, 0]), + new Case("32-bit unsigned int", 4294967295, [206, 255, 255, 255, 255]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeUInt32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeUInt32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteFloat32", () => { + const cases = [new Case("32-bit float", 0.5, [202, 63, 0, 0, 0])]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeFloat32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeFloat32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteFloat64", () => { + const cases = [ + new Case("64-bit float", 3.141592653589793, [203, 64, 9, 33, 251, 84, 68, 45, 24]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeFloat64(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeFloat64(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteBytes", () => { + const arr1 = new Uint8Array(1); + arr1.fill(1, 0, 1); + + const cases = [new Case("Bytes", arr1.buffer, [196, 1, 1])]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeBytes(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeBytes(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteString", () => { + const cases = [ + new Case("Empty String", "", [160]), + new Case("5-char String", "hello", [165, 104, 101, 108, 108, 111]), + new Case("11-char String", "hello world", [171, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeString(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeString(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteBigInt", () => { + const cases = [ + new Case("BigInt", BigInt.fromString("3124124512598273468017578125"), + [188, 51, 49, 50, 52, 49, 50, 52, 53, 49, 50, 53, 57, 56, + 50, 55, 51, 52, 54, 56, 48, 49, 55, 53, 55, 56, 49, 50, 53]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeBigInt(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeBigInt(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteBigNumber", () => { + const cases = [ + new Case("BigNumber", BigNumber.fromString("3124124512.598273468017578125"), + [189, 51, 49, 50, 52, 49, 50, 52, 53, 49, 50, 46, 53, 57, 56, + 50, 55, 51, 52, 54, 56, 48, 49, 55, 53, 55, 56, 49, 50, 53]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeBigNumber(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeBigNumber(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteJSON", () => { + const cases = [ + new Case("JSON", JSON.parse(`{"foo": "bar"}`), [173, 123, 34, 102, 111, 111, 34, 58, 34, 98, 97, 114, 34, 125]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeJSON(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeJSON(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteArray", () => { + const cases = [ + new Case>("Array", [10, 20, 30], [147, 10, 20, 30]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeArray(testcase.input, (writer: Write, item: u8) => { + writer.writeUInt8(item); + }); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeArray(testcase.input, (writer: Write, item: u8) => { + writer.writeUInt8(item); + }); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteMap", () => { + const map1 = new Map>(); + map1.set("foo", [1, -1, 42]); + map1.set("baz", [12412, -98987]); + + const cases = [ + new Case>>( + "Map", map1, + [130, 163, 102, 111, 111, 147, 1, 255, 42, 163, 98, + 97, 122, 146, 209, 48, 124, 210, 255, 254, 125, 85]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteExtGenericMap", () => { + const map1 = new Map>(); + map1.set("foo", [1, -1, 42]); + map1.set("baz", [12412, -98987]); + + const cases = [ + new Case>>( + "Map", map1, + [199, 22, 1, 130, 163, 102, 111, 111, 147, 1, 255, 42, 163, 98, + 97, 122, 146, 209, 48, 124, 210, 255, 254, 125, 85]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeExtGenericMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeExtGenericMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); +}); diff --git a/packages/wasm/as/assembly/__tests__/msgpack_write_option.spec.ts b/packages/wasm/as/assembly/__tests__/msgpack_write_option.spec.ts new file mode 100644 index 0000000000..58ac494560 --- /dev/null +++ b/packages/wasm/as/assembly/__tests__/msgpack_write_option.spec.ts @@ -0,0 +1,490 @@ +import { Write } from "../msgpack/Write"; +import { WriteSizer } from "../msgpack/WriteSizer"; +import { WriteEncoder } from "../msgpack/WriteEncoder"; +import { BigInt, BigNumber } from "../math"; +import { JSON } from "../json"; +import { Option } from "../"; + +function fill(arr: Array): ArrayBuffer { + const buffer = new ArrayBuffer(arr.length); + const offset = changetype(buffer); + for (let i: i32 = 0; i < arr.length; ++i) { + store(offset + i, arr[i]); + } + return buffer; +} + +class Case { + name: string; + input: T; + want: Array; + + constructor(name: string, input: T, want: Array) { + this.name = name; + this.input = input; + this.want = want; + } +} + +describe("WriteEncoder Option types", () => { + it("TestWriteOptionalBool", () => { + const cases = [ + new Case>("nil", Option.None(), [192]), + new Case>("nil", Option.Some(false), [194]), + new Case>("nil", Option.Some(true), [195]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalBool(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalBool(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalInt8", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "positive fixed int", + Option.Some(-128), + [208,128] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalInt8(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalInt8(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalInt16", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "16-bit signed int (negative)", + Option.Some(-32768), + [209, 128, 0] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalInt16(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalInt16(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalInt32", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "32-bit signed int (negative)", + Option.Some(-32769), + [210, 255, 255, 127, 255] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalInt32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalInt32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalUint8", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "8-bit unsigned int", + Option.Some(200), + [204,200] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalUInt8(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalUInt8(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalUint16", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "16-bit unsigned int", + Option.Some(256), + [205,1,0] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalUInt16(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalUInt16(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalUint32", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "32-bit unsigned int", + Option.Some(65536), + [206,0,1,0,0] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalUInt32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalUInt32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalFloat32", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "32-bit float", + Option.Some(0.5), + [202,63,0,0,0] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalFloat32(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalFloat32(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalFloat64", () => { + const cases = [ + new Case>("none", Option.None(), [192]), + new Case>( + "64-bit float", + Option.Some(3.141592653589793), + [203, 64, 9, 33, 251, 84, 68, 45, 24] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalFloat64(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalFloat64(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalBytes", () => { + const arr1 = new Uint8Array(1); + arr1.fill(1, 0, 1); + + const cases = [ + new Case("none", null, [192]), + new Case("Bytes", arr1.buffer, [196, 1, 1]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalBytes(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalBytes(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalString", () => { + const cases = [ + new Case("none", null, [192]), + new Case( + "5-char String", + "hello", + [165,104,101,108,108,111]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalString(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalString(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalBigInt", () => { + const cases = [ + new Case("none", null, [192]), + new Case( + "BigInt", + BigInt.fromString("3124124512598273468017578125"), + [188,51,49,50,52,49,50,52,53,49,50,53,57,56, + 50,55,51,52,54,56,48,49,55,53,55,56,49,50,53] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalBigInt(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalBigInt(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalBigNumber", () => { + const cases = [ + new Case("none", null, [192]), + new Case( + "BigNumber", + BigNumber.fromString("3124124512.598273468017578125"), + [189,51,49,50,52,49,50,52,53,49,50,46,53,57,56, + 50,55,51,52,54,56,48,49,55,53,55,56,49,50,53] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalBigNumber(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalBigNumber(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalJSON", () => { + const cases = [ + new Case("none", null, [192]), + new Case( + "JSON", + JSON.parse(`{"foo": "bar"}`), + [173,123,34,102,111,111,34,58,34,98,97,114,34,125] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalJSON(testcase.input); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalJSON(testcase.input); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalArray", () => { + const cases = [ + new Case | null>("none", null, [192]), + new Case | null>("Array", [10, 20, 30], [147, 10, 20, 30]), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalArray( + testcase.input, + (writer: Write, item: u8) => { + writer.writeUInt8(item); + } + ); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalArray( + testcase.input, + (writer: Write, item: u8) => { + writer.writeUInt8(item); + } + ); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalMap", () => { + const map1 = new Map>(); + map1.set("foo", [1, -1, 42]); + map1.set("baz", [12412, -98987]); + + const cases = [ + new Case> | null>("none", null, [192]), + new Case> | null>( + "Map", + map1, + [130,163,102,111,111,147,1,255,42,163,98, + 97,122,146,209,48,124,210,255,254,125,85] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); + + it("TestWriteOptionalExtGenericMap", () => { + const map1 = new Map>(); + map1.set("foo", [1, -1, 42]); + map1.set("baz", [12412, -98987]); + + const cases = [ + new Case> | null>("none", null, [192]), + new Case> | null>( + "Map", + map1, + [199,22,1,130,163,102,111,111,147,1,255,42,163, + 98,97,122,146,209,48,124,210,255,254,125,85] + ), + ]; + + for (let i: i32 = 0; i < cases.length; ++i) { + const testcase = cases[i]; + const sizer = new WriteSizer(); + sizer.writeOptionalExtGenericMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + const buffer = new ArrayBuffer(sizer.length); + const encoder = new WriteEncoder(buffer, sizer); + encoder.writeOptionalExtGenericMap>( + testcase.input, + (writer: Write, key: string): void => { + writer.writeString(key); + }, + (writer: Write, value: Array) => { + writer.writeArray(value, (writer: Write, item: i32) => { + writer.writeInt32(item); + }); + } + ); + + const actual = encoder._view.buffer; + const expected = fill(testcase.want); + expect(actual).toStrictEqual(expected); + } + }); +}); diff --git a/packages/wasm/as/assembly/msgpack/WriteEncoder.ts b/packages/wasm/as/assembly/msgpack/WriteEncoder.ts index 06a561ae00..36b4ff085c 100644 --- a/packages/wasm/as/assembly/msgpack/WriteEncoder.ts +++ b/packages/wasm/as/assembly/msgpack/WriteEncoder.ts @@ -343,7 +343,7 @@ export class WriteEncoder extends Write { this.writeBigInt(value); } - writeOptionalBigNumber(value: BigNumber): void { + writeOptionalBigNumber(value: BigNumber | null): void { if (value === null) { this.writeNil(); return; diff --git a/packages/wasm/as/assembly/msgpack/WriteSizer.ts b/packages/wasm/as/assembly/msgpack/WriteSizer.ts index 05d789c3a5..23cc096090 100644 --- a/packages/wasm/as/assembly/msgpack/WriteSizer.ts +++ b/packages/wasm/as/assembly/msgpack/WriteSizer.ts @@ -303,7 +303,7 @@ export class WriteSizer extends Write { this.writeBigInt(value); } - writeOptionalBigNumber(value: BigNumber): void { + writeOptionalBigNumber(value: BigNumber | null): void { if (value === null) { this.writeNil(); return;