wao 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+
3
+ var _express = _interopRequireDefault(require("express"));
4
+ var _cors = _interopRequireDefault(require("cors"));
5
+ var _bodyParser = _interopRequireDefault(require("body-parser"));
6
+ var _ramda = require("ramda");
7
+ var _utils = require("./utils.js");
8
+ var _bundler = _interopRequireDefault(require("./bundler.js"));
9
+ var _cu = _interopRequireDefault(require("./cu.js"));
10
+ var _ws = _interopRequireDefault(require("ws"));
11
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
12
+ var ws_server = new _ws["default"].Server({
13
+ port: 8080
14
+ });
15
+ var sus = {};
16
+ var cbs = {};
17
+ var hbs = {
18
+ O74OhzD1O_zE0uaKbaTQD1rfgTZEGMeXQ6M6M60TW_o: {
19
+ update: Date.now()
20
+ }
21
+ };
22
+ (0, _bundler["default"])(sus, cbs, hbs);
23
+ (0, _cu["default"])(sus, cbs, hbs);
24
+ ws_server.on("connection", function (socket) {
25
+ var clientId = (0, _utils.generateId)();
26
+ console.log("new ws:", clientId);
27
+ sus[clientId] = {
28
+ socket: socket,
29
+ su: false,
30
+ connections: {},
31
+ address: null,
32
+ accept: {
33
+ pid: {},
34
+ hb: {}
35
+ }
36
+ };
37
+ socket.send(JSON.stringify({
38
+ type: "registered",
39
+ id: clientId
40
+ }));
41
+ socket.on("message", function (message) {
42
+ var data = JSON.parse(message);
43
+ if (data.type === "list") {
44
+ if (data.target === "hb") {
45
+ var hb = [];
46
+ for (var k in hbs) {
47
+ hb.push({
48
+ address: k,
49
+ update: hbs[k].update
50
+ });
51
+ }
52
+ socket.send(JSON.stringify({
53
+ hb: hb,
54
+ type: "list"
55
+ }));
56
+ } else {
57
+ socket.send(JSON.stringify({
58
+ error: "unknown target"
59
+ }));
60
+ }
61
+ } else if (data.type === "subscribe") {
62
+ sus[clientId].accept = (0, _ramda.mergeLeft)(data.accept, sus[clientId].accept);
63
+ socket.send(JSON.stringify({
64
+ type: "subscribe",
65
+ accept: sus[clientId].accept
66
+ }));
67
+ } else if (data.type === "msg") {
68
+ if (cbs[data.id]) {
69
+ cbs[data.id].status(data.status).send(data.msg);
70
+ delete cbs[data.id];
71
+ }
72
+ } else if (data.type === "register") {
73
+ sus[clientId].su = true;
74
+ } else if (data.type === "sus") {
75
+ var _keys = [];
76
+ for (var _k in sus) if (sus[_k].su) _keys.push(_k);
77
+ socket.send(JSON.stringify({
78
+ type: "sus",
79
+ ids: _keys
80
+ }));
81
+ } else if (data.type === "offer") {
82
+ sus[data.su].socket.send(JSON.stringify({
83
+ type: "offer",
84
+ id: clientId,
85
+ offer: data.offer
86
+ }));
87
+ } else if (data.type === "answer") {
88
+ sus[data.client].socket.send(JSON.stringify({
89
+ type: "answer",
90
+ id: data.clientId,
91
+ answer: data.answer
92
+ }));
93
+ }
94
+ });
95
+ socket.on("close", function () {
96
+ console.log("ws disconnected", clientId);
97
+ delete sus[clientId];
98
+ });
99
+ });
100
+ console.log("WAO hub running on port 8080");
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateId = generateId;
7
+ exports.parseSignatureInput = parseSignatureInput;
8
+ exports.toANS104Request = toANS104Request;
9
+ var _ramda = require("ramda");
10
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
11
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
12
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
13
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
14
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
15
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
16
+ function generateId() {
17
+ return Math.random().toString(36).substring(2, 15);
18
+ }
19
+ function toANS104Request(fields) {
20
+ var _fields$anchor, _fields$Type, _fields$Variant;
21
+ var dataItem = {
22
+ target: fields.target,
23
+ anchor: (_fields$anchor = fields.anchor) !== null && _fields$anchor !== void 0 ? _fields$anchor : "",
24
+ tags: (0, _ramda.keys)((0, _ramda.omit)(["Target", "target", "Anchor", "anchor", "Data", "data", "data-protocol", "Data-Protocol", "variant", "Variant", "dryrun", "Dryrun", "Type", "type", "path", "method"], fields)).map(function (key) {
25
+ return {
26
+ name: key,
27
+ value: fields[key]
28
+ };
29
+ }, fields).concat([{
30
+ name: "Data-Protocol",
31
+ value: "ao"
32
+ }, {
33
+ name: "Type",
34
+ value: (_fields$Type = fields.Type) !== null && _fields$Type !== void 0 ? _fields$Type : "Message"
35
+ }, {
36
+ name: "Variant",
37
+ value: (_fields$Variant = fields.Variant) !== null && _fields$Variant !== void 0 ? _fields$Variant : "ao.N.1"
38
+ }]),
39
+ data: (fields === null || fields === void 0 ? void 0 : fields.data) || ""
40
+ };
41
+ return {
42
+ headers: {
43
+ "Content-Type": "application/ans104",
44
+ "codec-device": "ans104@1.0"
45
+ },
46
+ item: dataItem
47
+ };
48
+ }
49
+ function parseSignatureInput(input) {
50
+ var match = input.match(/^([^=]+)=\(([^)]+)\);alg="([^"]+)";keyid="([^"]+)"$/);
51
+ if (!match) throw new Error("Invalid signature-input format");
52
+ var _match = _slicedToArray(match, 5),
53
+ label = _match[1],
54
+ fieldsStr = _match[2],
55
+ alg = _match[3],
56
+ keyid = _match[4];
57
+ var fields = fieldsStr.split('" "').map(function (f) {
58
+ return f.replace(/"/g, "");
59
+ });
60
+ return {
61
+ label: label,
62
+ fields: fields,
63
+ alg: alg,
64
+ keyid: keyid
65
+ };
66
+ }
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ var _yargs = _interopRequireDefault(require("yargs"));
4
+ var _test = require("../test.js");
5
+ var _utils = require("./utils.js");
6
+ var _ws = _interopRequireDefault(require("ws"));
7
+ var _ramda = require("ramda");
8
+ var _path = require("path");
9
+ var _fs = require("fs");
10
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
11
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
12
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
13
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
14
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
15
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
16
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
17
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
18
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
19
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
20
+ var _yargs$argv$port = (0, _yargs["default"])(process.argv.slice(2)).argv.port,
21
+ port = _yargs$argv$port === void 0 ? 7000 : _yargs$argv$port;
22
+ var ws_server = new _ws["default"].Server({
23
+ port: 7070
24
+ });
25
+ var sus = {};
26
+ var cbs = {};
27
+ var _socket = null;
28
+ ws_server.on("connection", function (socket) {
29
+ _socket = socket;
30
+ var clientId = (0, _utils.generateId)();
31
+ console.log("new ws:", clientId);
32
+ sus[clientId] = {
33
+ socket: socket,
34
+ su: false,
35
+ connections: {},
36
+ address: null
37
+ };
38
+ socket.send(JSON.stringify({
39
+ type: "registered",
40
+ id: clientId
41
+ }));
42
+ socket.on("message", function (message) {
43
+ var data = JSON.parse(message);
44
+ if (data.type === "msg") {
45
+ if (cbs[data.id]) {
46
+ cbs[data.id](data.res);
47
+ delete cbs[data.id];
48
+ }
49
+ }
50
+ });
51
+ socket.on("close", function () {
52
+ console.log("ws disconnected", clientId);
53
+ delete sus[clientId];
54
+ });
55
+ });
56
+ console.log("WAO FS running on port 7070");
57
+ var Adaptor = /*#__PURE__*/function () {
58
+ function Adaptor() {
59
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
60
+ hb_url = _ref.hb_url,
61
+ aoconnect = _ref.aoconnect,
62
+ _ref$log = _ref.log,
63
+ log = _ref$log === void 0 ? false : _ref$log,
64
+ db = _ref.db;
65
+ _classCallCheck(this, Adaptor);
66
+ }
67
+ return _createClass(Adaptor, [{
68
+ key: "get",
69
+ value: function () {
70
+ var _get = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res) {
71
+ var id;
72
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
73
+ while (1) switch (_context.prev = _context.next) {
74
+ case 0:
75
+ try {
76
+ if (_socket) {
77
+ id = (0, _utils.generateId)();
78
+ cbs[id] = res;
79
+ _socket.send(JSON.stringify({
80
+ type: "msg",
81
+ req: req,
82
+ id: id
83
+ }));
84
+ setTimeout(function () {
85
+ if (cbs[id]) {
86
+ res({
87
+ status: 404,
88
+ error: "error"
89
+ });
90
+ delete cbs[id];
91
+ }
92
+ }, 3000);
93
+ } else {
94
+ res({
95
+ status: 404,
96
+ error: "connection not found"
97
+ });
98
+ }
99
+ } catch (e) {
100
+ res({
101
+ status: 404,
102
+ error: "connection not found"
103
+ });
104
+ }
105
+ case 1:
106
+ case "end":
107
+ return _context.stop();
108
+ }
109
+ }, _callee);
110
+ }));
111
+ function get(_x, _x2) {
112
+ return _get.apply(this, arguments);
113
+ }
114
+ return get;
115
+ }()
116
+ }]);
117
+ }();
118
+ var main = /*#__PURE__*/function () {
119
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
120
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
121
+ while (1) switch (_context2.prev = _context2.next) {
122
+ case 0:
123
+ return _context2.abrupt("return", new _test.Server({
124
+ log: true,
125
+ port: port,
126
+ adaptor: new Adaptor()
127
+ }));
128
+ case 1:
129
+ case "end":
130
+ return _context2.stop();
131
+ }
132
+ }, _callee2);
133
+ }));
134
+ return function main() {
135
+ return _ref2.apply(this, arguments);
136
+ };
137
+ }();
138
+ main();
package/esm/cli.js CHANGED
@@ -4,6 +4,21 @@ import { dirname } from "./utils.js"
4
4
  import { resolve } from "path"
5
5
  const args = process.argv.slice(2)
6
6
 
7
+ const cmds = {
8
+ wao: { script: "run.js" },
9
+ hub: { script: "hub/index.js" },
10
+ fs: { script: "hub/fs.js" },
11
+ proxy: { script: "hub/ws-proxy.js" },
12
+ }
13
+
14
+ const cmd = cmds[args[0]] ?? cmds["wao"]
15
+ if (cmds[args[0]]) args.shift()
16
+
17
+ if (!cmd) {
18
+ console.log("The wrong command")
19
+ process.exit()
20
+ }
21
+
7
22
  pm2.connect(false, async err => {
8
23
  if (err) {
9
24
  console.error("Error connecting to PM2:", err)
@@ -12,7 +27,7 @@ pm2.connect(false, async err => {
12
27
 
13
28
  pm2.start(
14
29
  {
15
- script: resolve(await dirname(), "run.js"),
30
+ script: resolve(await dirname(), cmd.script),
16
31
  nodeArgs: "--experimental-wasm-memory64",
17
32
  instances: 1,
18
33
  force: true,
@@ -0,0 +1,123 @@
1
+ import express from "express"
2
+ import cors from "cors"
3
+ import bodyParser from "body-parser"
4
+ import _Arweave from "arweave"
5
+ const Arweave = _Arweave.default ?? _Arweave
6
+ const arweave = Arweave.init()
7
+ import { generateId, toANS104Request, parseSignatureInput } from "./utils.js"
8
+
9
+ // todo: bundler is unusable due to incorrect ids and signature
10
+ const bundler = (sus, cbs, hbs) => {
11
+ const app = express()
12
+ app.use(cors())
13
+ app.use("/tx", bodyParser.raw({ type: "*/*", limit: "100mb" }))
14
+ app.post("/tx", async (req, res) => {
15
+ if (!Buffer.isBuffer(req.body)) {
16
+ console.log("BD: Invalid body | expected raw Buffer")
17
+ return res.status(400).send("Invalid body: expected raw Buffer")
18
+ }
19
+ const lines = req.body.toString("utf8").split(/\r?\n/)
20
+ const sigs = {}
21
+ let currentKey = null
22
+ for (let line of lines) {
23
+ const trimmed = line.trim()
24
+ if (/^--[a-zA-Z0-9_\-=]+/.test(trimmed)) {
25
+ currentKey = null
26
+ continue
27
+ }
28
+ const headerMatch = trimmed.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/)
29
+ if (headerMatch && !headerMatch[2].includes(": ")) {
30
+ const key = headerMatch[1]
31
+ const value = headerMatch[2]
32
+ sigs[key] = value
33
+ currentKey = key
34
+ } else if (currentKey) sigs[currentKey] += "\n" + line
35
+ }
36
+ sigs.target = req.headers.process
37
+ sigs.slot = req.headers.slot
38
+
39
+ const input = parseSignatureInput(req.headers["signature-input"])
40
+ const key = { kty: "RSA", n: input.keyid, e: "AQAB" }
41
+ const address = await arweave.wallets.jwkToAddress(key)
42
+ hbs[address] ??= {}
43
+ hbs[address].update = Date.now()
44
+ /*
45
+ const verifier = createVerifier(
46
+ createPublicKey({ key, format: "jwk" }),
47
+ "rsa-pss-sha512"
48
+ )*/
49
+ try {
50
+ /*const isValid = await verifyMessage(
51
+ { keyLookup: params => ({ verify: verifier }) },
52
+ {
53
+ method: req.method,
54
+ headers: req.headers,
55
+ url: `http://ao.com${req.headers.path}`,
56
+ }
57
+ )*/
58
+ const item = toANS104Request(sigs).item
59
+ if ((sigs.slot === "0" || sigs.type === "Process") && sigs.module) {
60
+ for (let v of item.tags) if (v.name === "Type") v.value = "Process"
61
+ await message(
62
+ {
63
+ http_msg: item,
64
+ module: sigs.module,
65
+ scheduler: sigs.scheduler,
66
+ address,
67
+ },
68
+ res
69
+ )
70
+ } else if (sigs.type === "Message") {
71
+ for (let v of item.tags) if (v.name === "id") item.target = v.value
72
+ await message(
73
+ {
74
+ slot: sigs.slot,
75
+ http_msg: item,
76
+ process: sigs.target,
77
+ address,
78
+ },
79
+ res
80
+ )
81
+ } else {
82
+ return res.status(500).send("unknown error")
83
+ }
84
+ } catch (e) {
85
+ return res.status(500).send("unknown error")
86
+ }
87
+ })
88
+
89
+ async function message(opt, res) {
90
+ const id = generateId()
91
+ cbs[id] = res
92
+ let exists = false
93
+ for (let k in sus) {
94
+ let hb = sus[k].accept.hb[opt.address]
95
+ let pid = opt.process
96
+ let p = sus[k].accept.pid[pid]
97
+ if (hb?.["*"] || hb?.[pid] || p?.["*"] || p?.[opt.address]) {
98
+ const socket = sus[k].socket
99
+ /*exists = true
100
+ socket.send(
101
+ JSON.stringify({ type: "msg", subtype: "message", id, message: opt })
102
+ )*/
103
+ }
104
+ }
105
+ res.status(200).send("success")
106
+ delete cbs[id]
107
+ /*
108
+ if (!exists) {
109
+ res.status(200).send("success")
110
+ delete cbs[id]
111
+ } else {
112
+ setTimeout(() => {
113
+ if (cbs[id]) {
114
+ res.status(200).send("success")
115
+ delete cbs[id]
116
+ }
117
+ }, 10000)
118
+ }*/
119
+ }
120
+
121
+ const server = app.listen(4001, () => console.log(`BD on port 4001`))
122
+ }
123
+ export default bundler
package/esm/hub/cu.js ADDED
@@ -0,0 +1,74 @@
1
+ import express from "express"
2
+ import cors from "cors"
3
+ import bodyParser from "body-parser"
4
+ const app2 = express()
5
+ import { generateId, toANS104Request, parseSignatureInput } from "./utils.js"
6
+
7
+ const cu = (sus, cbs) => {
8
+ app2.use(cors())
9
+ app2.use(bodyParser.json())
10
+ app2.post("/result/:mid", result)
11
+ app2.get("/result/:mid", result)
12
+
13
+ app2.post("/dry-run", async (req, res) => {
14
+ const process = req.query["process-id"]
15
+ const { Id: id, Owner: owner, Tags: tags, Data: data } = req.body
16
+ dryrun({ id, owner, tags, data, process }, res)
17
+ })
18
+
19
+ const server2 = app2.listen(4004, () => console.log(`CU on port 4004`))
20
+
21
+ // todo: request doesn't contain any info about hb node, how to handle it?
22
+ async function result(req, res) {
23
+ const id = generateId()
24
+ cbs[id] = res
25
+ let message = req.params.mid
26
+ let exists = false
27
+ const process = req.query["process-id"]
28
+ for (let k in sus) {
29
+ const socket = sus[k].socket
30
+ exists = true
31
+ socket.send(
32
+ JSON.stringify({ type: "msg", subtype: "result", message, process, id })
33
+ )
34
+ }
35
+ if (!exists) {
36
+ res.status(404).send("success")
37
+ delete cbs[id]
38
+ } else {
39
+ setTimeout(() => {
40
+ if (cbs[id]) {
41
+ res.status(404).send("success")
42
+ delete cbs[id]
43
+ }
44
+ }, 10000)
45
+ }
46
+ }
47
+
48
+ // todo: request doesn't contain any info about hb node, how to handle it?
49
+ async function dryrun(opt, res) {
50
+ const id = generateId()
51
+ cbs[id] = res
52
+ let exists = false
53
+ for (let k in sus) {
54
+ const socket = sus[k].socket
55
+ exists = true
56
+ socket.send(
57
+ JSON.stringify({ type: "msg", subtype: "dryrun", message: opt, id })
58
+ )
59
+ }
60
+ if (!exists) {
61
+ res.status(404).send("success")
62
+ delete cbs[id]
63
+ } else {
64
+ setTimeout(() => {
65
+ if (cbs[id]) {
66
+ res.status(404).send("success")
67
+ delete cbs[id]
68
+ }
69
+ }, 3000)
70
+ }
71
+ }
72
+ }
73
+
74
+ export default cu