Add JSON-RPC 2.0 support

This commit is contained in:
Namhyeon Go 2024-04-07 15:48:40 +09:00
parent 9f24bf6384
commit e332682fd2
3 changed files with 70 additions and 54 deletions

View File

@ -126,5 +126,6 @@ exports.createEmulator = function(binPath) {
};
exports.VERSIONINFO = "Android Debug Bridge Interface (adb.js) version 0.2.1";
exports.AUTHOR = "abuse@catswords.net";
exports.global = global;
exports.require = global.require;

View File

@ -1,54 +0,0 @@
////////////////////////////////////////////////////////////////////////
// JSON API
////////////////////////////////////////////////////////////////////////
exports.VERSIONINFO = "JSON Lib (json.js) version 0.1";
exports.global = global;
exports.require = global.require;
exports.stringify = function(obj) {
var items = [];
var isArray = (function(_obj) {
try {
return (_obj instanceof Array);
} catch (e) {
return false;
}
})(obj);
var _toString = function(_obj) {
try {
if (typeof(_obj) == "object") {
return exports.stringify(_obj);
} else {
var s = String(_obj).replace(/"/g, '\\"');
if (typeof(_obj) == "number" || typeof(_obj) == "boolean") {
return s;
} else {
return '"' + s + '"';
}
}
} catch (e) {
return "null";
}
};
for (var k in obj) {
var v = obj[k];
if (!isArray) {
items.push('"' + k + '":' + _toString(v));
} else {
items.push(_toString(v));
}
}
if (!isArray) {
return "{" + items.join(",") + "}";
} else {
return "[" + items.join(",") + "]";
}
};
exports.parse = function(jsonString) {
return (new Function("return " + jsonString)());
};

69
lib/jsonrpc2.js Normal file
View File

@ -0,0 +1,69 @@
var HTTP = require("lib/http");
function encode(method, params, id) {
var data = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": id
};
return JSON.stringify(data);
}
function resultEncode(result, id) {
var data = {
"jsonrpc": "2.0",
"result": result
"id": id
};
return JSON.stringify(data);
}
function errorEncode(error, id) {
var data = {
"jsonrpc": "2.0",
"error": error,
"id": id
}
return JSON.stringify(data);
}
// See also: https://github.com/gnh1201/caterpillar
function JsonRpcObject() {
this.url = "http://localhost:5555";
this.setUrl = function(url) {
this.url = url;
return this;
}
this.call = function(method, params, id) {
var data = HTTP.create("MSXML")
.setContentType("application/json")
.setDataType("json")
.setRequestBody(encode(method, params, id))
.open("POST", this.url)
.send()
.responseBody
;
return data;
}
}
function create() {
return new JsonRpcObject();
}
exports.encode = encode;
exports.resultEncode = resultEncode;
exports.errorEncode = errorEncode;
exports.create = create;
exports.VERSIONINFO = "JSON-RPC 2.0 Interface (jsonrpc2.js) version 0.1";
exports.AUTHOR = "abuse@catswords.net";
exports.global = global;
exports.require = global.require;