Socket
Socket
Sign inDemoInstall

wandbox-api-updated

Package Overview
Dependencies
106
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.2.5 to 1.0.0

lib/getCompilerList.js

252

lib/file.js
'use strict';
// MODULES //
var debug = require( 'debug' )( 'wandbox-api:file' );
var copy = require( 'utils-copy' );
const { readFile } = require('fs');
var https = require( 'https' );
var cwd = require( 'utils-cwd' );
var readFile = require( 'utils-fs-read-file' );
var writeFile = require( 'fs' ).writeFile;
var https = require( 'https' );
var resolve = require( 'path' ).resolve;
var typeName = require( 'type-name' );
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );
var resolveFile = require( 'path' ).resolve;
// VARIABLES //
var interfaces = {
'string,string,Object,function': [ 0, 1, 2, 3 ],
'string,string,function': [ 0, 1, -1, 2 ],
'string,Object,function': [ -1, 0, 1, 2 ],
'string,function': [ -1, 0, -1, 1 ]
};
// FILE //
/**
* @deprecated Since v0.2.5, will be removed in v0.3.0
*
* FUNCTION: file( [dest,] src[, opts], clbk )
* Execute source file on Wandbox and fetch results.
*
* @param {String} [dest] - output file path
* @param {String} src - file to run on Wandbox
* @param {Object} [opts] - function options
* @param {String} [opts.compiler="gcc-head"] - name of used compiler
* @param {Array} [opts.codes=[]] - additional codes, objects with `file` and `code` keys
* @param {String} [opts.options="boost-1.60,warning,gnu++1y"] - used options for a compiler joined by comma.
* @param {String} [opts.stdin=""] - standard input
* @param {String} [opts.compiler-option-raw=""] - additional compile-time options joined by line-break
* @param {String} [opts.runtime-option-raw=""] - additional run-time options joined by line-break
* @param {Boolean} [opts.save=false] - boolean indicating whether permanent link should be generated
* @param {Function} clbk - callback to invoke after receiving results from Wandbox
* @returns {Void}
*/
function file() {
console.warn("Calling deprecated `file`. Will be removed in v0.3.0.");
var outFile;
var options;
var inputFile;
var types;
var dest;
var opts;
var clbk;
var src;
var err;
var dir;
var idx;
var len;
var i;
* @param {String} srcFile - file to run on Wandbox
* @param {Array} opts - function options
* @returns JSON Result or String
*/
module.exports = function string(srcFile, opts) {
return new Promise((resolve, reject) => {
if (!srcFile) {
reject("No source provided.");
}
len = arguments.length;
types = new Array( len );
for ( i = 0; i < len; i++ ) {
types[ i ] = typeName( arguments[ i ] );
}
types = types.join( ',' );
idx = interfaces[ types ];
if ( idx === void 0 ) {
throw new Error( 'invalid input argument(s). No implementation matching `f('+types+')`.' );
}
if ( idx[ 0 ] >= 0 ) {
dest = arguments[ idx[0] ];
}
src = arguments[ idx[1] ];
if ( idx[ 2 ] >= 0 ) {
options = arguments[ idx[2] ];
}
clbk = arguments[ idx[3] ];
let dir = cwd();
let inputFile = resolveFile( dir, srcFile);
opts = copy( defaults );
if ( options ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
dir = cwd();
debug( 'Current working directory: %s', dir );
readFile( inputFile, {'encoding':'utf-8'}, onFile);
inputFile = resolve( dir, src );
debug( 'Input file: %s', inputFile );
function onFile( error, data ) {
if ( error ) {
reject(`[${error.name}]: ${error.message}`);
}
readFile( inputFile, {'encoding':'utf8'}, onFile );
/**
* FUNCTION: onFile( error, file )
* Callback invoked upon reading a file.
*
* @private
* @param {Error|Null} error - error object
* @param {String} data - file contents
* @returns {Void}
*/
function onFile( error, data ) {
if ( error ) {
debug( 'Error encountered while attempting to read a input file %s: %s', inputFile, error.message );
return done( error );
}
debug( 'Successfully read input file: %s', inputFile );
opts.code = data;
// Add `code` key to options holding the source code to run on Wandbox...
opts.code = data;
require('./getCompilerList')().then(list => {
let found = false;
list.forEach(compiler => {
if (compiler.name.toLowerCase() === opts.compiler.toLowerCase()) {
found = true;
}
});
const post_data = JSON.stringify(opts);
if (!found) {
reject("Invalid compiler supplied.");
} else {
const post_data = JSON.stringify(opts);
const params = {
hostname: 'wandbox.org',
port: 443,
path: '/api/compile.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
}
const params = {
hostname: 'wandbox.org',
port: 443,
path: '/api/compile.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
}
let e = null;
let e = null;
let resdata = "";
let start = Date.now();
let data = "";
let start = Date.now();
const req = https.request(params, (res) => {
res.setEncoding('utf8')
console.log(`statusCode: ${res.statusCode}`);
res.on('data', function(chunk) {
if ((Date.now() - start) > opts.timeout) {
e = new Error('Request Timed out.');
req.destroy();
}
resdata += chunk;
})
const req = https.request(params, (res) => {
res.setEncoding('utf8')
res.on('data', function(chunk) {
if ((Date.now() - start) > opts.timeout) {
e = new Error('Request Timed out.');
req.destroy();
}
data += chunk;
})
res.on('close', function() {
if (e) {
resdata = '{ "response":"Request timed out." }';
}
done(e, res, resdata);
});
}, done)
res.on('close', function() {
if (e) {
data = '{ "response":"Request timed out." }';
reject(`[${e.name}]: ${e.message}`)
} else {
try {
resolve(JSON.parse(data))
} catch (err) {
reject(`[${err.name}]: ${err.message}`)
}
}
});
})
req.on('error', error => {
e = error;
})
req.on('error', error => {
e = error;
})
req.write(post_data);
req.end();
}
/**
* FUNCTION: done( error, message, body )
* Callback invoked after resolving POST request to Wandbox.
*
* @private
* @param {Error|Null} error - error object
* @param {Object} message - an http.IncomingMessage
* @param {Object} body - response body
* @returns {Void}
*/
function done( error, message, body ) {
error = error || null;
body = body || null;
// Save response body if `dest` is supplied:
if ( dest !== void 0 ) {
outFile = resolve( dir, dest );
writeFile( outFile, JSON.stringify( body ), function( err ) {
clbk( err, body );
});
} else {
try {
clbk( error, JSON.parse(body) );
} catch (e) {
if (e instanceof SyntaxError) {
clbk( error, body );
} else {
clbk( error, e.message );
req.write(post_data);
req.end();
}
}
}).catch(e => {
reject("Failed to gather list of compilers.");
})
}
} // end FUNCTION done()
} // end FUNCTION file()
// EXPORTS //
module.exports = file;
});
}

@@ -1,14 +0,11 @@

export function fromStringV2(
opts: Opts,
clbk: (err: Error | null, body: Result) => void,
dest: string | undefined
): void;
export function fromFileV2(
export function fromString( opts: Opts ): Promise<Result>;
export function fromFile(
srcFile: string,
opts: Opts,
clbk: (err: Error | null, body: Result) => void,
dest: string | undefined
): void;
opts: Opts
): Promise<Result>;
export function getCompilers(
lang?: string
): Promise<Compiler[] | string>;
interface Opts {

@@ -34,4 +31,28 @@ compiler: string,

"program_message": string,
"api_output": string,
"api_error": string,
"api_message": string,
permlink?: string,
url?: string
}
interface Switch {
default: boolean;
"display-flags": string;
"display-name": string;
name: string;
type: string;
}
interface Compiler {
"compiler-option-raw": boolean;
"display-compile-command": string;
"display-name": string;
language: string;
name: string;
provider: number;
"runtime-option-raw": boolean;
switches: Array<Switch>;
templates: Array<string>;
version: string;
}

@@ -5,5 +5,4 @@ 'use strict';

module.exports = require( './file.js' );
module.exports.fromFileV2 = require( './file_v2.js');
module.exports.fromFile = require( './file.js' );
module.exports.fromString = require( './string.js' );
module.exports.fromStringV2 = require( './string_v2.js' );
module.exports.getCompilers = require( './getCompilerList.js' );
'use strict';
// MODULES //
var debug = require( 'debug' )( 'wandbox-api-updated:string' );
var copy = require( 'utils-copy' );
var cwd = require( 'utils-cwd' );
var typeName = require( 'type-name' );
var writeFile = require( 'fs' ).writeFile;
var https = require( 'https' );
var resolve = require( 'path' ).resolve;
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );
// VARIABLES //
var interfaces = {
'string,string,Object,function': [ 0, 1, 2, 3 ],
'string,string,function': [ 0, 1, -1, 2 ],
'string,Object,function': [ -1, 0, 1, 2 ],
'string,function': [ -1, 0, -1, 1 ]
};
// STRING //
/**
* @deprecated Since v0.2.5, will be removed in v0.3.0
*
* FUNCTION: string( [dest,] code[, opts], clbk )
* Execute code on Wandbox and fetch results.
*
* @param {String} [dest] - output file path
* @param {String} code - code to run on Wandbox
* @param {Object} [opts] - function options
* @param {String} [opts.compiler="gcc-head"] - name of used compiler
* @param {Array} [opts.codes=[]] - additional codes, objects with `file` and `code` keys
* @param {String} [opts.options="boost-1.60,warning,gnu++1y"] - used options for a compiler joined by comma.
* @param {String} [opts.stdin=""] - standard input
* @param {String} [opts.compiler-option-raw=""] - additional compile-time options joined by line-break
* @param {String} [opts.runtime-option-raw=""] - additional run-time options joined by line-break
* @param {Boolean} [opts.save=false] - boolean indicating whether permanent link should be generated
* @param {Function} clbk - callback to invoke after receiving results from Wandbox
* @returns {Void}
*/
function string() {
console.warn("Calling deprecated `string`. Will be removed in v0.3.0.");
var options;
var outFile;
var types;
var dest;
var opts;
var clbk;
var code;
var err;
var dir;
var idx;
var len;
var i;
* @param {Array} opts - function options
* @returns JSON Result or String
*/
module.exports = function string(opts, dest) {
return new Promise((resolve, reject) => {
if (!opts.code) {
reject("No source provided.");
}
len = arguments.length;
types = new Array( len );
for ( i = 0; i < len; i++ ) {
types[ i ] = typeName( arguments[ i ] );
}
types = types.join( ',' );
idx = interfaces[ types ];
if ( idx === void 0 ) {
throw new Error( 'invalid input argument(s). No implementation matching `f('+types+')`.' );
}
if ( idx[ 0 ] >= 0 ) {
dest = arguments[ idx[0] ];
}
code = arguments[ idx[1] ];
if ( idx[ 2 ] >= 0 ) {
options = arguments[ idx[2] ];
}
clbk = arguments[ idx[3] ];
require('./getCompilerList')().then(list => {
let found = false;
list.forEach(compiler => {
if (compiler.name.toLowerCase() === opts.compiler.toLowerCase()) {
found = true;
}
});
opts = copy( defaults );
if ( options ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
if (!found) {
reject("Invalid compiler supplied.");
} else {
const post_data = JSON.stringify(opts);
dir = cwd();
debug( 'Current working directory: %s', dir );
const params = {
hostname: 'wandbox.org',
port: 443,
path: '/api/compile.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
}
if ( dest !== void 0 ) {
outFile = resolve( dir, dest );
}
debug( 'Output file: %s', outFile );
let e = null;
// Add `code` key to options holding the source code to run on Wandbox...
opts.code = code;
let data = "";
let start = Date.now();
const post_data = JSON.stringify(opts);
const req = https.request(params, (res) => {
res.setEncoding('utf8')
res.on('data', function(chunk) {
if ((Date.now() - start) > opts.timeout) {
e = new Error('Request Timed out.');
req.destroy();
}
data += chunk;
})
const params = {
hostname: 'wandbox.org',
port: 443,
path: '/api/compile.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
}
res.on('close', function() {
if (e) {
data = '{ "response":"Request timed out." }';
reject(`[${e.name}]: ${e.message}`)
} else {
try {
resolve(JSON.parse(data))
} catch (err) {
reject(`[${err.name}]: ${err.message}`)
}
}
});
})
let e = null;
req.on('error', error => {
e = error;
})
let data = "";
let start = Date.now();
const req = https.request(params, (res) => {
res.setEncoding('utf8')
res.on('data', function(chunk) {
if ((Date.now() - start) > opts.timeout) {
e = new Error('Request Timed out.');
req.destroy();
req.write(post_data);
req.end();
}
data += chunk;
}).catch(e => {
reject("Failed to gather list of compilers.");
})
res.on('close', function() {
if (e) {
data = '{ "response":"Request timed out." }';
}
done(e, res, data);
});
}, done)
req.write(post_data);
// req.end();
/**
* FUNCTION: done( error, message, body )
* Callback invoked after resolving POST request to Wandbox.
*
* @private
* @param {Error|Null} error - error object
* @param {Object} message - an http.IncomingMessage
* @param {Object} body - response body
* @returns {Void}
*/
function done( error, message, body ) {
error = error || null;
body = body || null;
// Save response body if `dest` is supplied:
if ( dest !== void 0 ) {
outFile = resolve( dir, dest );
writeFile( outFile, JSON.stringify( body ), function( err ) {
clbk( err, body );
});
} else {
try {
clbk( error, JSON.parse(body) );
} catch (e) {
if (e instanceof SyntaxError) {
clbk( error, body );
} else {
clbk( error, e.message );
}
}
}
} // end FUNCTION done()
} // end FUNCTION string()
// EXPORTS //
module.exports = string;
});
}
{
"name": "wandbox-api-updated",
"version": "0.2.5",
"version": "1.0.0",
"description": "Node.js bindings to the Wandbox API.",

@@ -62,3 +62,3 @@ "author": {

"proxyquire": "^1.7.4",
"tap-spec": "^5.0.0",
"tap-spec": "^2.2.2",
"tape": "4.x.x",

@@ -65,0 +65,0 @@ "utils-fs-exists": "^1.0.1"

@@ -14,2 +14,22 @@ Node Wandbox API

# > v1.0.0 Usage
``` javascript
var { fromString, fromFile, getCompilers } = require('../lib/index');
fromString({
code: "print(\"Hello World!\")",
compiler: "lua-5.4.0",
}).then(console.log).catch(console.error);
fromFile("./test/fixtures/gamma.cpp",
{
compiler: "gcc-head"
}
).then(console.log).catch(console.error);
getCompilers("Lua").then(console.log).catch(console.error);
```
# < v1.0.0 Usage
## V2 Usage

@@ -16,0 +36,0 @@ ``` javascript

const runWandbox = require('../lib/index');
let res = runWandbox.fromStringV2(
{
compiler: "lua-5.4.0",
codes: [],
options: "",
save: true,
timeout: 30000,
code: "print(\"Hello\")"
},
function done(error, res) {
console.log(error);
console.log(res);
}
);
// let res = runWandbox.fromStringV2(
// {
// compiler: "lua-5.4.1",
// codes: [],
// options: "",
// save: true,
// timeout: 30000,
// code: "print(\"Hello\")"
// },
// function done(error, res) {
// console.log(error);
// console.log(res);
// }
// );
// console.log("Looking for compilers for language: Cringe");
// let list = runWandbox.getCompilers("Cringe");
// list.then(console.log).catch(console.error);
// console.log("Looking for compilers for language: Lua");
// list = runWandbox.getCompilers("Lua");
// list.then(console.log).catch(console.error);
// console.log("Promise StringV3");
// let res = runWandbox.fromStringV3(
// {
// compiler: "lua-5.4.0",
// codes: [],
// options: "",
// save: true,
// timeout: 30000,
// code: "print(\"Hello\")"
// },
// );
// res.then(console.log).catch(console.error);
// var copy = require( 'utils-copy' );
// var opts = copy ( require('../lib/defaults.json') );
// const test = runWandbox.fromFileV3( './test/fixtures/gamma.cpp', opts );
// test.then(console.log).catch(console.error);
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc