├── .gitignore ├── lib ├── or.js ├── get.js └── post.js ├── test └── test.js ├── package.json ├── LICENSE ├── index.d.ts ├── index.js ├── readme.md └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea -------------------------------------------------------------------------------- /lib/or.js: -------------------------------------------------------------------------------- 1 | export const or = (a, b) => (a === undefined ? b : a); 2 | 3 | export default or; 4 | -------------------------------------------------------------------------------- /lib/get.js: -------------------------------------------------------------------------------- 1 | import fetch from "node-fetch"; 2 | 3 | export const get = async (url) => { 4 | try { 5 | const res = await fetch(url); 6 | return await res.json(); 7 | } catch(e) { 8 | return { success: false, error: e }; 9 | } 10 | } 11 | 12 | export default get; -------------------------------------------------------------------------------- /lib/post.js: -------------------------------------------------------------------------------- 1 | import fetch from "node-fetch"; 2 | 3 | export const post = async (url, body) => { 4 | try { 5 | const res = await fetch(url, { 6 | method: 'POST', 7 | body: JSON.stringify(body) 8 | }); 9 | return await res.json(); 10 | } catch(e) { 11 | return { success: false, error: e }; 12 | } 13 | } 14 | 15 | export default post; -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | import piston from "../index.js"; 2 | 3 | (async () => { 4 | const client = piston(); 5 | 6 | // const result = await client.execute({ 7 | // "language": "js", 8 | // "version": "15.10.0", 9 | // "files": [{ 10 | // "name": "my_cool_code.js", 11 | // "content": "console.log('Hello World')" 12 | // }], 13 | // "stdin": "", 14 | // "args": ["1", "2", "3"], 15 | // "compileTimeout": 10000, 16 | // "runTimeout": 3000, 17 | // "compileMemoryLimit": -1, 18 | // "runMemoryLimit": -1 19 | // }); 20 | 21 | //await client.execute("javascript", `console.log('Hello World');`); 22 | 23 | // await client.execute("python", `print("Hello World");`, { 24 | // version: "3.9.4" 25 | // }); 26 | 27 | })(); 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "piston-client", 3 | "type": "module", 4 | "version": "1.0.2", 5 | "description": "Client wrapper for the Piston API.", 6 | "main": "index.js", 7 | "scripts": { 8 | "dev": "nodemon index.js", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "keywords": [ 12 | "piston api client wrapper" 13 | ], 14 | "author": "dthree", 15 | "license": "MIT", 16 | "dependencies": { 17 | "node-fetch": "^2.6.1" 18 | }, 19 | "directories": { 20 | "lib": "lib" 21 | }, 22 | "devDependencies": { 23 | "typescript": "^5.0.4" 24 | }, 25 | "repository": { 26 | "type": "git", 27 | "url": "git+https://github.com/dthree/node-piston.git" 28 | }, 29 | "bugs": { 30 | "url": "https://github.com/dthree/node-piston/issues" 31 | }, 32 | "homepage": "https://github.com/dthree/node-piston#readme" 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2021 DC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | 'Software'), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export default function piston(): PistonClient 2 | 3 | export interface PistonClient { 4 | runtimes(): Promise; 5 | 6 | execute(language: language, code: string, options?: ExecutionOptions): Promise; 7 | } 8 | 9 | export interface ExecutionResult { 10 | language: language; 11 | version: string; 12 | run: { 13 | stdout: string; 14 | stderr: string; 15 | code: number; 16 | signal: any; 17 | output: string 18 | } 19 | } 20 | 21 | export interface ExecutionOptions { 22 | language: language; 23 | version: string; 24 | files: { 25 | name: string; 26 | content: string; 27 | }[] 28 | stdin: string; 29 | args: string[]; 30 | compile_timeout: number; 31 | run_timeout: number; 32 | compile_memory_limit: number; 33 | run_memory_limit: number; 34 | } 35 | 36 | export interface Runtime { 37 | language: language; 38 | version: string; 39 | aliases: string[] 40 | } 41 | 42 | export type Result = any | { error: any, success: boolean } | undefined; 43 | 44 | export type language = "awk" | "bash" | "befunge93" | "brachylog" | "brainfuck" | "bqn" | "c" | "c++" | "cjam" | "clojure" | "cobol" | "coffeescript" | "cow" | "crystal" | "csharp" | "csharp.net" | "d" | "dart" | "dash" | "dragon" | "elixir" | "emacs" | "emojicode" | "erlang" | "file" | "forte" | "forth" | "fortran" | "freebasic" | "fsharp.net" | "fsi" | "go" | "golfscript" | "groovy" | "haskell" | "husk" | "iverilog" | "japt" | "java" | "javascript" | "jelly" | "julia" | "kotlin" | "lisp" | "llvm_ir" | "lolcode" | "lua" | "matl" | "nasm" | "nasm64" | "nim" | "ocaml" | "octave" | "osabie" | "paradoc" | "pascal" | "perl" | "php" | "ponylang" | "powershell" | "prolog" | "pure" | "pyth" | "python" | "python2" | "racket" | "raku" | "retina" | "rockstar" | "rscript" | "ruby" | "rust" | "samarium" | "scala" | "smalltalk" | "sqlite3" | "swift" | "typescript" | "basic" | "basic.net" | "vlang" | "vyxal" | "yeethon" | "zig"; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import get from "./lib/get.js"; 2 | import post from "./lib/post.js"; 3 | import or from "./lib/or.js"; 4 | 5 | const defaultServer = "https://emkc.org"; 6 | 7 | export const piston = (opts = {}) => { 8 | const server = String(opts.server || defaultServer).replace(/\/$/, ''); 9 | const store = {}; 10 | 11 | const api = { 12 | 13 | async runtimes() { 14 | if (store.runtimes) { 15 | return store.runtimes; 16 | } 17 | const suffix = (server === defaultServer) 18 | ? '/api/v2/piston/runtimes' 19 | : '/api/v2/runtimes'; 20 | const url = `${server}${suffix}`; 21 | const runtimes = await get(url); 22 | if (runtimes && runtimes.success !== false) { 23 | store.runtimes = runtimes; 24 | } 25 | return runtimes; 26 | }, 27 | 28 | async execute(argA, argB, argC) { 29 | const runtimes = await api.runtimes(); 30 | if (runtimes.success === false) { 31 | return runtimes; 32 | } 33 | 34 | const config = typeof argA === 'object' ? argA : typeof argB === 'object' ? argB : argC || {}; 35 | let language = (typeof argA === 'string') ? argA : undefined; 36 | language = language || config.language; 37 | const code = typeof argB === 'string' ? argB : undefined; 38 | const latestVersion = (runtimes.filter(n => n.language === language).sort((a, b) => { 39 | return a.version > b.version ? -1 : b.version > a.version ? 1 : 0; 40 | })[0] || {}).version; 41 | 42 | const boilerplate = { 43 | "language": language, 44 | "version": config.version || latestVersion, 45 | "files": or(config.files, [{ 46 | "content": code 47 | }]), 48 | "stdin": or(config.stdin, ""), 49 | "args": or(config.args, ["1", "2", "3"]), 50 | "compile_timeout": or(config.compileTimeout, 10000), 51 | "run_timeout": or(config.runTimeout, 3000), 52 | "compile_memory_limit": or(config.compileMemoryLimit, -1), 53 | "run_memory_limit": or(config.runMemoryLimit, -1) 54 | } 55 | 56 | const suffix = (server === defaultServer) 57 | ? '/api/v2/piston/execute' 58 | : '/api/v2/execute'; 59 | const url = `${server}${suffix}`; 60 | return await post(url, boilerplate); 61 | } 62 | } 63 | 64 | return api; 65 | } 66 | 67 | export default piston; -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Piston Node Client 2 | 3 | A Node.js client wrapper for the [Piston API](https://github.com/engineer-man/piston). 4 | 5 | Piston is a high performance general purpose code execution engine. It excels at running untrusted and possibly malicious code without fear from any harmful effects. 6 | 7 |
8 | 9 | ## Installation 10 | 11 | ```bash 12 | npm install piston-client 13 | ``` 14 | 15 | ### Usage Example 16 | 17 | ```js 18 | import piston from "piston-client"; 19 | 20 | (async () => { 21 | 22 | const client = piston({ server: "https://emkc.org" }); 23 | 24 | const runtimes = await client.runtimes(); 25 | // [{ language: 'python', version: '3.9.4', aliases: ['py'] }, ...] 26 | 27 | const result = await client.execute('python', 'print("Hello World!")'); 28 | // { language: 'python', version: '3.9.4', run: { 29 | // stdout: 'Hello World!\n', 30 | // stderr: '', 31 | // code: 0, 32 | // signal: null, 33 | // output: 'Hello World!\n' 34 | // }} 35 | 36 | })(); 37 | ``` 38 | 39 |
40 | 41 | ## Documentation 42 | 43 | ### `piston(options)` 44 | 45 | ```js 46 | import piston from "piston-client"; 47 | const client = piston({}); 48 | ``` 49 | 50 | Creates a new client. Accepts an `options` object as its first argument. 51 | 52 | ##### Options 53 | 54 | - `server` - The domain name of the Piston server to be used. Defaults to `https://emkc.org`. 55 | 56 | ### `client.runtimes()` 57 | 58 | ```js 59 | import piston from "piston-client"; 60 | (async () => { 61 | const client = piston(); 62 | const runtimes = await client.runtimes(); 63 | })(); 64 | ``` 65 | 66 | Returns an array of available runtimes. [See Piston documentation for the runtimes endpoint](https://github.com/engineer-man/piston#runtimes-endpoint). 67 | 68 | ### `client.execute(language, code, [config])` 69 | 70 | Execute arbitrary code for a given language. Additional, optional config can be passed in the third parameter. 71 | 72 | ```js 73 | import piston from "piston-client"; 74 | (async () => { 75 | const client = piston(); 76 | const result = await client.execute('javascript', 'console.log("Hello world!")', { language: '3.9.4 '}); 77 | })(); 78 | ``` 79 | 80 | ##### Options 81 | 82 | - `language` - Expects a string of the language. 83 | - `code` - Expects a string of the code to execute. 84 | - `config` - Expects an object with additional config. See [Piston documentation](https://github.com/engineer-man/piston#execute-endpoint) for the available config options. 85 | 86 | ### `client.execute(config)` 87 | 88 | To execute Piston with more fine-tuned control, pass in a `config` object as the first and only parameter. 89 | 90 | ```js 91 | import piston from "piston-client"; 92 | (async () => { 93 | const client = piston(); 94 | const result = await client.execute({ 95 | "language": "js", 96 | "version": "15.10.0", 97 | "files": [{ 98 | "name": "my_cool_code.js", 99 | "content": "console.log(process.argv)" 100 | }], 101 | "stdin": "", 102 | "args": ["1", "2", "3"], 103 | "compileTimeout": 10000, 104 | "runTimeout": 3000, 105 | "compileMemoryLimit": -1, 106 | "runMemoryLimit": -1 107 | }); 108 | })(); 109 | ``` 110 | 111 | ##### Options 112 | 113 | See [Piston documentation](https://github.com/engineer-man/piston#execute-endpoint) for the available options. The only difference is that the option are in camelCase as opposed to snake_case. 114 | 115 | ### Error handling 116 | 117 | Any error will return an object with the following signature: 118 | 119 | ```js 120 | { success: false, error: Error } 121 | ``` 122 | 123 | No errors are thrown so wrapping in `try / catch` is unnecessary. 124 | 125 |
126 | 127 | ## License 128 | 129 | MIT © [DC](https://github.com/dthree) 130 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | // "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | --------------------------------------------------------------------------------