roboto-js 1.1.10 → 1.1.12

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.
@@ -1,39 +1,20 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports["default"] = void 0;
7
- var _axios = _interopRequireDefault(require("axios"));
8
- var _cryptoJs = _interopRequireDefault(require("crypto-js"));
9
- var _rbt_object = _interopRequireDefault(require("./rbt_object.js"));
10
- var _rbt_user = _interopRequireDefault(require("./rbt_user.js"));
11
- var _rbt_file = _interopRequireDefault(require("./rbt_file.js"));
12
- var _lodash = _interopRequireDefault(require("lodash"));
13
- var _idb = require("idb");
14
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
15
- 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); }
16
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
17
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
18
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
- 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 new 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 new 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 new 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; }
20
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
21
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
22
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
23
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
24
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
25
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
26
- 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); }
27
- var RbtApi = exports["default"] = /*#__PURE__*/function () {
28
- function RbtApi(_ref) {
29
- var apiKey = _ref.apiKey,
30
- baseUrl = _ref.baseUrl,
31
- authtoken = _ref.authtoken,
32
- accesskey = _ref.accesskey;
33
- _classCallCheck(this, RbtApi);
34
- var isClient = typeof window !== 'undefined';
35
- var authTokenToUse = isClient && !authtoken ? localStorage.getItem('authtoken') : authtoken;
36
- this.axios = _axios["default"].create({
1
+ import axios from 'axios';
2
+ import CryptoJS from 'crypto-js';
3
+ import RbtObject from './rbt_object.js';
4
+ import RbtUser from './rbt_user.js';
5
+ import RbtFile from './rbt_file.js';
6
+ import _ from 'lodash';
7
+ import { openDB } from 'idb';
8
+ export default class RbtApi {
9
+ constructor({
10
+ apiKey,
11
+ baseUrl,
12
+ authtoken,
13
+ accesskey
14
+ }) {
15
+ const isClient = typeof window !== 'undefined';
16
+ const authTokenToUse = isClient && !authtoken ? localStorage.getItem('authtoken') : authtoken;
17
+ this.axios = axios.create({
37
18
  baseURL: baseUrl,
38
19
  headers: {
39
20
  'accesskey': accesskey || apiKey,
@@ -45,902 +26,518 @@ var RbtApi = exports["default"] = /*#__PURE__*/function () {
45
26
  this.authtoken = authTokenToUse;
46
27
  this.appServiceHost = null;
47
28
  }
48
- _createClass(RbtApi, [{
49
- key: "initLocalDb",
50
- value: function () {
51
- var _initLocalDb = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
52
- return _regeneratorRuntime().wrap(function _callee$(_context) {
53
- while (1) switch (_context.prev = _context.next) {
54
- case 0:
55
- _context.next = 2;
56
- return (0, _idb.openDB)('RBTFileDatabase', 1, {
57
- upgrade: function upgrade(db) {
58
- if (!db.objectStoreNames.contains('files')) {
59
- db.createObjectStore('files', {
60
- autoIncrement: true
61
- });
62
- }
63
- }
64
- });
65
- case 2:
66
- this.localDb = _context.sent;
67
- case 3:
68
- case "end":
69
- return _context.stop();
70
- }
71
- }, _callee, this);
72
- }));
73
- function initLocalDb() {
74
- return _initLocalDb.apply(this, arguments);
29
+ async initLocalDb() {
30
+ this.localDb = await openDB('RBTFileDatabase', 1, {
31
+ upgrade(db) {
32
+ if (!db.objectStoreNames.contains('files')) {
33
+ db.createObjectStore('files', {
34
+ autoIncrement: true
35
+ });
36
+ }
75
37
  }
76
- return initLocalDb;
77
- }()
78
- }, {
79
- key: "setAppServiceHost",
80
- value: function setAppServiceHost(host) {
81
- this.appServiceHost = host;
82
- this.axios.defaults.baseURL = host;
83
- }
38
+ });
39
+ }
40
+ setAppServiceHost(host) {
41
+ this.appServiceHost = host;
42
+ this.axios.defaults.baseURL = host;
43
+ }
84
44
 
85
- /**
86
- * Logs in a user and stores the authToken.
87
- *
88
- * @param {Object} params - The login parameters.
89
- * @param {string} params.email - The email of the user.
90
- * @param {string} params.password - The password of the user.
91
- * @returns {Promise<Object>} - The response data from the API.
92
- */
93
- }, {
94
- key: "login",
95
- value: (function () {
96
- var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(params) {
97
- var hash_password, response;
98
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
99
- while (1) switch (_context2.prev = _context2.next) {
100
- case 0:
101
- _context2.prev = 0;
102
- // create a md5 hash of the password using crypto-js
103
- hash_password = _cryptoJs["default"].MD5(params.password).toString(_cryptoJs["default"].enc.Hex);
104
- _context2.next = 4;
105
- return this.axios.post('/user_service/loginUser', [{
106
- email: params.email,
107
- password: hash_password
108
- }]);
109
- case 4:
110
- response = _context2.sent;
111
- if (!(response.data.ok === false)) {
112
- _context2.next = 7;
113
- break;
114
- }
115
- return _context2.abrupt("return", this._handleError(response));
116
- case 7:
117
- this.iac_session = response.data;
118
- this.currentUser = this.iac_session ? new _rbt_user["default"](this.iac_session.user, this.axios) : null;
119
- // update axios instance headers with authtoken
120
- this.axios.defaults.headers.common['authtoken'] = response.data.authToken;
121
- if (typeof localStorage != 'undefined') {
122
- localStorage.setItem('authtoken', response.data.authToken);
123
- }
124
- return _context2.abrupt("return", response.data);
125
- case 14:
126
- _context2.prev = 14;
127
- _context2.t0 = _context2["catch"](0);
128
- this._handleError(_context2.t0);
129
- case 17:
130
- case "end":
131
- return _context2.stop();
132
- }
133
- }, _callee2, this, [[0, 14]]);
134
- }));
135
- function login(_x) {
136
- return _login.apply(this, arguments);
45
+ /**
46
+ * Logs in a user and stores the authToken.
47
+ *
48
+ * @param {Object} params - The login parameters.
49
+ * @param {string} params.email - The email of the user.
50
+ * @param {string} params.password - The password of the user.
51
+ * @returns {Promise<Object>} - The response data from the API.
52
+ */
53
+ async login(params) {
54
+ try {
55
+ // create a md5 hash of the password using crypto-js
56
+ const hash_password = CryptoJS.MD5(params.password).toString(CryptoJS.enc.Hex);
57
+ const response = await this.axios.post('/user_service/loginUser', [{
58
+ email: params.email,
59
+ password: hash_password
60
+ }]);
61
+ if (response.data.ok === false) {
62
+ return this._handleError(response);
63
+ }
64
+ this.iac_session = response.data;
65
+ this.currentUser = this.iac_session ? new RbtUser(this.iac_session.user, this.axios) : null;
66
+ // update axios instance headers with authtoken
67
+ this.axios.defaults.headers.common['authtoken'] = response.data.authToken;
68
+ if (typeof localStorage != 'undefined') {
69
+ localStorage.setItem('authtoken', response.data.authToken);
70
+ }
71
+ return response.data;
72
+ } catch (e) {
73
+ this._handleError(e);
74
+ }
75
+ }
76
+ async logout() {
77
+ try {
78
+ // Call logout endpoint if necessary. Here, I assume there's a '/user_service/logoutUser' endpoint.
79
+ // This is optional and depends on how your backend is set up.
80
+ const response = await this.axios.post('/user_service/logoutUser');
81
+ if (response.data.ok === false) {
82
+ return this._handleError(response);
137
83
  }
138
- return login;
139
- }())
140
- }, {
141
- key: "logout",
142
- value: function () {
143
- var _logout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
144
- var response;
145
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
146
- while (1) switch (_context3.prev = _context3.next) {
147
- case 0:
148
- _context3.prev = 0;
149
- _context3.next = 3;
150
- return this.axios.post('/user_service/logoutUser');
151
- case 3:
152
- response = _context3.sent;
153
- if (!(response.data.ok === false)) {
154
- _context3.next = 6;
155
- break;
156
- }
157
- return _context3.abrupt("return", this._handleError(response));
158
- case 6:
159
- // Clear the iac_session and remove the auth token from axios headers
160
- this.iac_session = null;
161
- this.currentUser = null;
162
- if (this.axios.defaults.headers.common['authtoken']) {
163
- delete this.axios.defaults.headers.common['authtoken'];
164
- }
165
-
166
- // Clear localStorage if it's being used
167
- if (typeof localStorage !== 'undefined') {
168
- localStorage.removeItem('authtoken');
169
- }
170
84
 
171
- // Return some kind of success response or the response from the server
172
- return _context3.abrupt("return", response.data);
173
- case 13:
174
- _context3.prev = 13;
175
- _context3.t0 = _context3["catch"](0);
176
- this._handleError(_context3.t0);
177
- case 16:
178
- case "end":
179
- return _context3.stop();
180
- }
181
- }, _callee3, this, [[0, 13]]);
182
- }));
183
- function logout() {
184
- return _logout.apply(this, arguments);
85
+ // Clear the iac_session and remove the auth token from axios headers
86
+ this.iac_session = null;
87
+ this.currentUser = null;
88
+ if (this.axios.defaults.headers.common['authtoken']) {
89
+ delete this.axios.defaults.headers.common['authtoken'];
185
90
  }
186
- return logout;
187
- }()
188
- }, {
189
- key: "loadCurrentUser",
190
- value: function () {
191
- var _loadCurrentUser = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
192
- var response;
193
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
194
- while (1) switch (_context4.prev = _context4.next) {
195
- case 0:
196
- _context4.prev = 0;
197
- if (!this.currentUser) {
198
- _context4.next = 3;
199
- break;
200
- }
201
- return _context4.abrupt("return", this.currentUser);
202
- case 3:
203
- if (!this.authtoken) {
204
- _context4.next = 10;
205
- break;
206
- }
207
- _context4.next = 6;
208
- return this.refreshAuthToken(this.authtoken);
209
- case 6:
210
- response = _context4.sent;
211
- this.currentUser = new _rbt_user["default"]({
212
- id: response.user.id
213
- }, this.axios);
214
- this.currentUser.setData(response.user);
215
- return _context4.abrupt("return", this.currentUser);
216
- case 10:
217
- this.currentUser = null;
218
- return _context4.abrupt("return", null);
219
- case 14:
220
- _context4.prev = 14;
221
- _context4.t0 = _context4["catch"](0);
222
- return _context4.abrupt("return", this._handleError(_context4.t0));
223
- case 17:
224
- case "end":
225
- return _context4.stop();
226
- }
227
- }, _callee4, this, [[0, 14]]);
228
- }));
229
- function loadCurrentUser() {
230
- return _loadCurrentUser.apply(this, arguments);
91
+
92
+ // Clear localStorage if it's being used
93
+ if (typeof localStorage !== 'undefined') {
94
+ localStorage.removeItem('authtoken');
231
95
  }
232
- return loadCurrentUser;
233
- }()
234
- }, {
235
- key: "confirmUserEmail",
236
- value: function () {
237
- var _confirmUserEmail = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(confirmCode) {
238
- var params, response;
239
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
240
- while (1) switch (_context5.prev = _context5.next) {
241
- case 0:
242
- params = {
243
- emailConfirmCode: confirmCode
244
- };
245
- _context5.prev = 1;
246
- _context5.next = 4;
247
- return this.axios.post('/user_service/confirmUserEmail', [params]);
248
- case 4:
249
- response = _context5.sent;
250
- if (!(response.data.ok === false)) {
251
- _context5.next = 7;
252
- break;
253
- }
254
- return _context5.abrupt("return", this._handleError(response));
255
- case 7:
256
- return _context5.abrupt("return", response.data);
257
- case 10:
258
- _context5.prev = 10;
259
- _context5.t0 = _context5["catch"](1);
260
- return _context5.abrupt("return", this._handleError(_context5.t0));
261
- case 13:
262
- case "end":
263
- return _context5.stop();
264
- }
265
- }, _callee5, this, [[1, 10]]);
266
- }));
267
- function confirmUserEmail(_x2) {
268
- return _confirmUserEmail.apply(this, arguments);
96
+
97
+ // Return some kind of success response or the response from the server
98
+ return response.data;
99
+ } catch (e) {
100
+ this._handleError(e);
101
+ }
102
+ }
103
+ async loadCurrentUser() {
104
+ try {
105
+ if (this.currentUser) {
106
+ return this.currentUser;
269
107
  }
270
- return confirmUserEmail;
271
- }()
272
- }, {
273
- key: "loadUser",
274
- value: function () {
275
- var _loadUser = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(userId) {
276
- var params, _response$data, response, userData, User;
277
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
278
- while (1) switch (_context6.prev = _context6.next) {
279
- case 0:
280
- params = {
281
- id: userId
282
- };
283
- _context6.prev = 1;
284
- _context6.next = 4;
285
- return this.axios.post('/user_service/loadUser', [params]);
286
- case 4:
287
- response = _context6.sent;
288
- userData = response === null || response === void 0 || (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.user;
289
- User = new _rbt_user["default"]({
290
- id: userData.id
291
- }, this.axios);
292
- User.setData(userData);
293
- return _context6.abrupt("return", User);
294
- case 11:
295
- _context6.prev = 11;
296
- _context6.t0 = _context6["catch"](1);
297
- return _context6.abrupt("return", this._handleError(_context6.t0));
298
- case 14:
299
- case "end":
300
- return _context6.stop();
301
- }
302
- }, _callee6, this, [[1, 11]]);
303
- }));
304
- function loadUser(_x3) {
305
- return _loadUser.apply(this, arguments);
108
+ if (this.authtoken) {
109
+ let response = await this.refreshAuthToken(this.authtoken);
110
+ this.currentUser = new RbtUser({
111
+ id: response.user.id
112
+ }, this.axios);
113
+ this.currentUser.setData(response.user);
114
+ return this.currentUser;
115
+
116
+ //this.currentOrg = new RbtObject(response.organization, this.axios);
117
+ //this.currentOrg.type = '<@iac.organization>';
306
118
  }
307
- return loadUser;
308
- }()
309
- }, {
310
- key: "refreshAuthToken",
311
- value: function () {
312
- var _refreshAuthToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(authtoken) {
313
- var response;
314
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
315
- while (1) switch (_context7.prev = _context7.next) {
316
- case 0:
317
- _context7.prev = 0;
318
- _context7.next = 3;
319
- return this.axios.post('/user_service/refreshAuthToken', [authtoken]);
320
- case 3:
321
- response = _context7.sent;
322
- debugger;
323
- return _context7.abrupt("return", response.data);
324
- case 8:
325
- _context7.prev = 8;
326
- _context7.t0 = _context7["catch"](0);
327
- this._handleError(_context7.t0);
328
- case 11:
329
- case "end":
330
- return _context7.stop();
331
- }
332
- }, _callee7, this, [[0, 8]]);
333
- }));
334
- function refreshAuthToken(_x4) {
335
- return _refreshAuthToken.apply(this, arguments);
119
+ this.currentUser = null;
120
+ return null;
121
+ } catch (e) {
122
+ return this._handleError(e);
123
+ }
124
+ }
125
+ async confirmUserEmail(confirmCode) {
126
+ let params = {
127
+ emailConfirmCode: confirmCode
128
+ };
129
+ try {
130
+ const response = await this.axios.post('/user_service/confirmUserEmail', [params]);
131
+ if (response.data.ok === false) {
132
+ return this._handleError(response);
336
133
  }
337
- return refreshAuthToken;
338
- }()
339
- /**
340
- * Registers a new user.
341
- *
342
- * @param {Object} dataHash - The data for the new user.
343
- * @returns {Promise<RbtObject>} - The newly created user as an RbtObject.
344
- *
345
- */
346
- }, {
347
- key: "registerUser",
348
- value: (function () {
349
- var _registerUser = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
350
- var dataHash,
351
- response,
352
- record,
353
- _args8 = arguments;
354
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
355
- while (1) switch (_context8.prev = _context8.next) {
356
- case 0:
357
- dataHash = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};
358
- _context8.prev = 1;
359
- _context8.next = 4;
360
- return this.axios.post('/user_service/registerUser', [dataHash]);
361
- case 4:
362
- response = _context8.sent;
363
- record = response.data;
364
- return _context8.abrupt("return", new _rbt_user["default"](record, this.axios));
365
- case 9:
366
- _context8.prev = 9;
367
- _context8.t0 = _context8["catch"](1);
368
- debugger;
369
- return _context8.abrupt("return", this._handleError(_context8.t0));
370
- case 13:
371
- case "end":
372
- return _context8.stop();
373
- }
374
- }, _callee8, this, [[1, 9]]);
375
- }));
376
- function registerUser() {
377
- return _registerUser.apply(this, arguments);
134
+ return response.data;
135
+ } catch (e) {
136
+ return this._handleError(e);
137
+ }
138
+ }
139
+ async loadUser(userId) {
140
+ let params = {
141
+ id: userId
142
+ };
143
+ try {
144
+ const response = await this.axios.post('/user_service/loadUser', [params]);
145
+ let userData = response?.data?.user;
146
+ let User = new RbtUser({
147
+ id: userData.id
148
+ }, this.axios);
149
+ User.setData(userData);
150
+ return User;
151
+ } catch (e) {
152
+ return this._handleError(e);
153
+ }
154
+ }
155
+ async refreshAuthToken(authtoken) {
156
+ try {
157
+ const response = await this.axios.post('/user_service/refreshAuthToken', [authtoken]);
158
+ debugger;
159
+ return response.data;
160
+ } catch (e) {
161
+ this._handleError(e);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Registers a new user.
167
+ *
168
+ * @param {Object} dataHash - The data for the new user.
169
+ * @returns {Promise<RbtObject>} - The newly created user as an RbtObject.
170
+ *
171
+ */
172
+ async registerUser(dataHash = {}) {
173
+ try {
174
+ const response = await this.axios.post('/user_service/registerUser', [dataHash]);
175
+ const record = response.data;
176
+ return new RbtUser(record, this.axios);
177
+ } catch (e) {
178
+ debugger;
179
+ return this._handleError(e);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Creates a new file in the system.
185
+ *
186
+ * @param {Object} dataHash - The data for the new file.
187
+ * @returns {Promise<RbtFile>} - The newly created file as an RbtFile.
188
+ *
189
+ */
190
+ async createFile(dataHash) {
191
+ //return this.create('<@filekit.file>', dataHash);
192
+ try {
193
+ const response = await this.axios.post('/object_service/createObject', ['<@filekit.file>', dataHash]);
194
+ const record = response.data;
195
+ if (dataHash) {
196
+ record.data = dataHash;
378
197
  }
379
- return registerUser;
380
- }()
381
- /**
382
- * Creates a new file in the system.
383
- *
384
- * @param {Object} dataHash - The data for the new file.
385
- * @returns {Promise<RbtFile>} - The newly created file as an RbtFile.
386
- *
387
- */
388
- )
389
- }, {
390
- key: "createFile",
391
- value: (function () {
392
- var _createFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(dataHash) {
393
- var response, record;
394
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
395
- while (1) switch (_context9.prev = _context9.next) {
396
- case 0:
397
- _context9.prev = 0;
398
- _context9.next = 3;
399
- return this.axios.post('/object_service/createObject', ['<@filekit.file>', dataHash]);
400
- case 3:
401
- response = _context9.sent;
402
- record = response.data;
403
- if (dataHash) {
404
- record.data = dataHash;
405
- }
406
- return _context9.abrupt("return", new _rbt_file["default"](record, this.axios, this.localDb));
407
- case 9:
408
- _context9.prev = 9;
409
- _context9.t0 = _context9["catch"](0);
410
- return _context9.abrupt("return", this._handleError(_context9.t0));
411
- case 12:
412
- case "end":
413
- return _context9.stop();
414
- }
415
- }, _callee9, this, [[0, 9]]);
416
- }));
417
- function createFile(_x5) {
418
- return _createFile.apply(this, arguments);
198
+ return new RbtFile(record, this.axios, this.localDb);
199
+ } catch (e) {
200
+ return this._handleError(e);
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Creates a new object of the given type.
206
+ *
207
+ * @param {string} type - The type of object to create.
208
+ * @param {Object} dataHash - The data for the new object.
209
+ * @returns {Promise<RbtObject>} - The newly created object as an RbtObject.
210
+ */
211
+ async create(type, dataHash = {}) {
212
+ try {
213
+ const response = await this.axios.post('/object_service/createObject', [type, dataHash]);
214
+ const record = response.data;
215
+ if (dataHash) {
216
+ record.data = dataHash;
419
217
  }
420
- return createFile;
421
- }()
422
- /**
423
- * Creates a new object of the given type.
424
- *
425
- * @param {string} type - The type of object to create.
426
- * @param {Object} dataHash - The data for the new object.
427
- * @returns {Promise<RbtObject>} - The newly created object as an RbtObject.
428
- */
429
- )
430
- }, {
431
- key: "create",
432
- value: (function () {
433
- var _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(type) {
434
- var dataHash,
435
- response,
436
- record,
437
- _args10 = arguments;
438
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
439
- while (1) switch (_context10.prev = _context10.next) {
440
- case 0:
441
- dataHash = _args10.length > 1 && _args10[1] !== undefined ? _args10[1] : {};
442
- _context10.prev = 1;
443
- _context10.next = 4;
444
- return this.axios.post('/object_service/createObject', [type, dataHash]);
445
- case 4:
446
- response = _context10.sent;
447
- record = response.data;
448
- if (dataHash) {
449
- record.data = dataHash;
450
- }
451
- return _context10.abrupt("return", new _rbt_object["default"](record, this.axios, {
452
- isNew: true
453
- }));
454
- case 10:
455
- _context10.prev = 10;
456
- _context10.t0 = _context10["catch"](1);
457
- return _context10.abrupt("return", this._handleError(_context10.t0));
458
- case 13:
459
- case "end":
460
- return _context10.stop();
461
- }
462
- }, _callee10, this, [[1, 10]]);
463
- }));
464
- function create(_x6) {
465
- return _create.apply(this, arguments);
218
+ return new RbtObject(record, this.axios, {
219
+ isNew: true
220
+ });
221
+ } catch (e) {
222
+ return this._handleError(e);
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Queries objects of a given type based on specified parameters.
228
+ *
229
+ * @param {string} type - The type of object to query, specified as a doctree.typedef.
230
+ * @param {Object} params - The query parameters, including optional filters and configurations.
231
+ * @returns {Promise<Array<RbtObject>>} - An array of queried objects as RbtObjects.
232
+ *
233
+ * The `params` object can include the following properties:
234
+ * - where: A SQL-like where clause string for filtering the results.
235
+ * - orderBy: An object specifying the ordering of the results. It should include:
236
+ * - column: The attribute name to sort by. This must be either a column in the @doctree.model schema or an indexed type attribute.
237
+ * - direction: The sort direction, either 'ASC' for ascending or 'DESC' for descending.
238
+ * - limit: An object to control the pagination of results. It includes:
239
+ * - offset: The starting point from where to fetch the results.
240
+ * - results: The maximum number of results to return.
241
+ * - resolveReferences: An array of attribute names whose references should be resolved in the returned objects.
242
+ * - timeout: A numerical value in milliseconds to set a maximum time limit for the query execution.
243
+ *
244
+ * Example usage:
245
+ * query("<@testuser>", {
246
+ * where: 'email="tom@pospa.com"',
247
+ * orderBy: { column: 'timeCreated', direction: 'DESC' },
248
+ * limit: { offset: 0, results: 50 },
249
+ * resolveReferences: ['translatableContent']
250
+ * });
251
+ *
252
+ * Note: A default orderBy is applied if none is provided, ordering items by 'timeCreated' in descending order.
253
+ */
254
+ async query(type, params = {}) {
255
+ try {
256
+ params.type = type;
257
+
258
+ // Default ordering and pagination
259
+ const defaultOrderBy = {
260
+ orderBy: {
261
+ column: 'timeCreated',
262
+ direction: 'DESC'
263
+ }
264
+ };
265
+ const defaultLimit = {
266
+ limit: {
267
+ offset: 0,
268
+ results: 50
269
+ }
270
+ };
271
+
272
+ // Merge defaults with provided params
273
+ const mergedParams = {
274
+ ...defaultOrderBy,
275
+ ...defaultLimit,
276
+ ...params
277
+ };
278
+ const response = await this.axios.post('/object_service/queryObjects', [mergedParams]);
279
+ if (response.data.ok === false) {
280
+ return this._handleError(response);
466
281
  }
467
- return create;
468
- }()
469
- /**
470
- * Queries objects of a given type based on specified parameters.
471
- *
472
- * @param {string} type - The type of object to query, specified as a doctree.typedef.
473
- * @param {Object} params - The query parameters, including optional filters and configurations.
474
- * @returns {Promise<Array<RbtObject>>} - An array of queried objects as RbtObjects.
475
- *
476
- * The `params` object can include the following properties:
477
- * - where: A SQL-like where clause string for filtering the results.
478
- * - orderBy: An object specifying the ordering of the results. It should include:
479
- * - column: The attribute name to sort by. This must be either a column in the @doctree.model schema or an indexed type attribute.
480
- * - direction: The sort direction, either 'ASC' for ascending or 'DESC' for descending.
481
- * - limit: An object to control the pagination of results. It includes:
482
- * - offset: The starting point from where to fetch the results.
483
- * - results: The maximum number of results to return.
484
- * - resolveReferences: An array of attribute names whose references should be resolved in the returned objects.
485
- * - timeout: A numerical value in milliseconds to set a maximum time limit for the query execution.
486
- *
487
- * Example usage:
488
- * query("<@testuser>", {
489
- * where: 'email="tom@pospa.com"',
490
- * orderBy: { column: 'timeCreated', direction: 'DESC' },
491
- * limit: { offset: 0, results: 50 },
492
- * resolveReferences: ['translatableContent']
493
- * });
494
- *
495
- * Note: A default orderBy is applied if none is provided, ordering items by 'timeCreated' in descending order.
496
- */
497
- )
498
- }, {
499
- key: "query",
500
- value: (function () {
501
- var _query = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(type) {
502
- var _this = this;
503
- var params,
504
- defaultOrderBy,
505
- defaultLimit,
506
- mergedParams,
507
- response,
508
- _args11 = arguments;
509
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
510
- while (1) switch (_context11.prev = _context11.next) {
511
- case 0:
512
- params = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : {};
513
- _context11.prev = 1;
514
- params.type = type;
515
282
 
516
- // Default ordering and pagination
517
- defaultOrderBy = {
518
- orderBy: {
519
- column: 'timeCreated',
520
- direction: 'DESC'
521
- }
522
- };
523
- defaultLimit = {
524
- limit: {
525
- offset: 0,
526
- results: 50
527
- }
528
- }; // Merge defaults with provided params
529
- mergedParams = _objectSpread(_objectSpread(_objectSpread({}, defaultOrderBy), defaultLimit), params);
530
- _context11.next = 8;
531
- return this.axios.post('/object_service/queryObjects', [mergedParams]);
532
- case 8:
533
- response = _context11.sent;
534
- if (!(response.data.ok === false)) {
535
- _context11.next = 11;
536
- break;
537
- }
538
- return _context11.abrupt("return", this._handleError(response));
539
- case 11:
540
- // Process items into RbtObject instances
541
- if (Array.isArray(response.data.items)) {
542
- response.data.items = response.data.items.map(function (record) {
543
- return new _rbt_object["default"](record, _this.axios, {
544
- isNew: true
545
- });
546
- });
547
- }
548
- return _context11.abrupt("return", response.data.items);
549
- case 15:
550
- _context11.prev = 15;
551
- _context11.t0 = _context11["catch"](1);
552
- return _context11.abrupt("return", this._handleError(_context11.t0));
553
- case 18:
554
- case "end":
555
- return _context11.stop();
556
- }
557
- }, _callee11, this, [[1, 15]]);
558
- }));
559
- function query(_x7) {
560
- return _query.apply(this, arguments);
283
+ // Process items into RbtObject instances
284
+ if (Array.isArray(response.data.items)) {
285
+ response.data.items = response.data.items.map(record => new RbtObject(record, this.axios, {
286
+ isNew: true
287
+ }));
561
288
  }
562
- return query;
563
- }()
564
- /**
565
- * Loads one or multiple objects of a given type by their IDs.
566
- *
567
- * @param {string} type - The type of object to load.
568
- * @param {Array<string>|string} ids - The ID(s) of the object(s) to load.
569
- *
570
- * @returns {Promise<RbtObject|RbtObject[]>} - The loaded object(s) as RbtObject(s).
571
- */
572
- )
573
- }, {
574
- key: "load",
575
- value: (function () {
576
- var _load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(type, ids) {
577
- var params,
578
- mergedParams,
579
- res,
580
- _args12 = arguments;
581
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
582
- while (1) switch (_context12.prev = _context12.next) {
583
- case 0:
584
- params = _args12.length > 2 && _args12[2] !== undefined ? _args12[2] : {};
585
- _context12.prev = 1;
586
- if (!Array.isArray(ids)) {
587
- _context12.next = 7;
588
- break;
589
- }
590
- mergedParams = _objectSpread(_objectSpread({}, params), {}, {
591
- where: "id IN (" + ids.join(',') + ")"
592
- });
593
- return _context12.abrupt("return", this.query(type, mergedParams));
594
- case 7:
595
- mergedParams = _objectSpread(_objectSpread({}, params), {}, {
596
- where: "id=" + ids
597
- });
598
- _context12.next = 10;
599
- return this.query(type, mergedParams);
600
- case 10:
601
- res = _context12.sent;
602
- return _context12.abrupt("return", res[0]);
603
- case 12:
604
- _context12.next = 17;
605
- break;
606
- case 14:
607
- _context12.prev = 14;
608
- _context12.t0 = _context12["catch"](1);
609
- return _context12.abrupt("return", this._handleError(_context12.t0));
610
- case 17:
611
- case "end":
612
- return _context12.stop();
613
- }
614
- }, _callee12, this, [[1, 14]]);
615
- }));
616
- function load(_x8, _x9) {
617
- return _load.apply(this, arguments);
289
+ return response.data.items;
290
+ } catch (e) {
291
+ return this._handleError(e);
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Loads one or multiple objects of a given type by their IDs.
297
+ *
298
+ * @param {string} type - The type of object to load.
299
+ * @param {Array<string>|string} ids - The ID(s) of the object(s) to load.
300
+ *
301
+ * @returns {Promise<RbtObject|RbtObject[]>} - The loaded object(s) as RbtObject(s).
302
+ */
303
+ async load(type, ids, params = {}) {
304
+ try {
305
+ let mergedParams;
306
+ if (Array.isArray(ids)) {
307
+ mergedParams = {
308
+ ...params,
309
+ where: "id IN (" + ids.join(',') + ")"
310
+ };
311
+ return this.query(type, mergedParams);
312
+ } else {
313
+ mergedParams = {
314
+ ...params,
315
+ where: "id=" + ids
316
+ };
317
+ let res = await this.query(type, mergedParams);
318
+ return res[0];
618
319
  }
619
- return load;
620
- }()
621
- /**
622
- * Makes a POST request to a specific endpoint to run a task and handle progress updates.
623
- *
624
- * @param {Object} params - The parameters to be sent in the POST request.
625
- * @param {Object} callbacks - An object containing callback functions for progress and error handling.
626
- *
627
- * The function expects a response in the following format:
628
- * {
629
- * ok: boolean, // Indicates if the request was successful or not
630
- * jobId: string, // The job identifier
631
- * status: string // Can be 'RUNNING', 'DONE', or 'ERROR'
632
- * }
633
- */
634
- )
635
- }, {
636
- key: "runTask",
637
- value: (function () {
638
- var _runTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
639
- var params,
640
- callbacks,
641
- onProgress,
642
- onError,
643
- onFinish,
644
- response,
645
- ok,
646
- jobId,
647
- status,
648
- message,
649
- output,
650
- _args13 = arguments;
651
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
652
- while (1) switch (_context13.prev = _context13.next) {
653
- case 0:
654
- params = _args13.length > 0 && _args13[0] !== undefined ? _args13[0] : {};
655
- callbacks = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : {};
656
- onProgress = callbacks.onProgress, onError = callbacks.onError, onFinish = callbacks.onFinish;
657
- _context13.prev = 3;
658
- _context13.next = 6;
659
- return this.post('http://localhost:3004/runChain', params);
660
- case 6:
661
- response = _context13.sent;
662
- if (response) {
663
- _context13.next = 9;
664
- break;
665
- }
666
- throw new Error('Invalid server response');
667
- case 9:
668
- // Validate response structure
669
- ok = response.ok, jobId = response.jobId, status = response.status, message = response.message, output = response.output;
670
- if (!(!ok || typeof jobId !== 'string' || typeof status !== 'string')) {
671
- _context13.next = 12;
672
- break;
673
- }
674
- throw new Error('Invalid response structure');
675
- case 12:
676
- // If the task is still in progress, start polling for updates
677
- if (status === 'RUNNING' || status === 'SCHEDULED' || status === 'QUEUED') {
678
- this.pollTaskProgress(jobId, callbacks);
679
- }
680
- if (status === 'ERROR' && onError) {
681
- // Provide the current progress to the callback function
682
- onError(response);
683
- }
684
- if (status === 'DONE' && onFinish) {
685
- // Provide the current progress to the callback function
686
- console.log('Finish (request) ', response);
687
- onFinish(response);
688
- }
689
- return _context13.abrupt("return", {
690
- ok: ok,
691
- jobId: jobId,
692
- status: status,
693
- message: message,
694
- output: output
695
- });
696
- case 18:
697
- _context13.prev = 18;
698
- _context13.t0 = _context13["catch"](3);
699
- if (typeof onError === 'function') {
700
- onError(_context13.t0);
701
- } else {
702
- console.error('Error in runTask:', _context13.t0);
703
- }
704
- return _context13.abrupt("return", {
705
- ok: false,
706
- jobId: null,
707
- status: 'ERROR',
708
- error: _context13.t0.message
709
- });
710
- case 22:
711
- case "end":
712
- return _context13.stop();
713
- }
714
- }, _callee13, this, [[3, 18]]);
715
- }));
716
- function runTask() {
717
- return _runTask.apply(this, arguments);
320
+ } catch (e) {
321
+ return this._handleError(e);
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Makes a POST request to a specific endpoint to run a task and handle progress updates.
327
+ *
328
+ * @param {Object} params - The parameters to be sent in the POST request.
329
+ * @param {Object} callbacks - An object containing callback functions for progress and error handling.
330
+ *
331
+ * The function expects a response in the following format:
332
+ * {
333
+ * ok: boolean, // Indicates if the request was successful or not
334
+ * jobId: string, // The job identifier
335
+ * status: string // Can be 'RUNNING', 'DONE', or 'ERROR'
336
+ * }
337
+ */
338
+ async runTask(params = {}, callbacks = {}) {
339
+ const {
340
+ onProgress,
341
+ onError,
342
+ onFinish
343
+ } = callbacks;
344
+ try {
345
+ const response = await this.post('/task_service/runChain', params);
346
+ // Check if response and response.data are defined
347
+ if (!response) {
348
+ throw new Error('Invalid server response');
718
349
  }
719
- return runTask;
720
- }()
721
- /**
722
- * Polls the progress of a long-running task.
723
- *
724
- * @param {string} jobId - The ID of the job to poll for progress.
725
- * @param {function} onProgress - Callback function that receives progress updates.
726
- *
727
- * The function periodically sends GET requests to check the task's progress
728
- * and reports back via the provided callback function. The polling stops when
729
- * the task is completed or an error occurs.
730
- */
731
- )
732
- }, {
733
- key: "pollTaskProgress",
734
- value: (function () {
735
- var _pollTaskProgress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(jobId, callbacks) {
736
- var _this2 = this;
737
- var onProgress, onError, onFinish, checkProgress;
738
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
739
- while (1) switch (_context15.prev = _context15.next) {
740
- case 0:
741
- onProgress = callbacks.onProgress, onError = callbacks.onError, onFinish = callbacks.onFinish;
742
- _context15.prev = 1;
743
- checkProgress = /*#__PURE__*/function () {
744
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
745
- var response;
746
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
747
- while (1) switch (_context14.prev = _context14.next) {
748
- case 0:
749
- _context14.next = 2;
750
- return _this2.get("http://localhost:3004/pollChainProgress", {
751
- jobId: jobId
752
- });
753
- case 2:
754
- response = _context14.sent;
755
- // If the task is still in progress, start polling for updates
756
- if (response.status === 'DONE' && onFinish) {
757
- // Provide the current progress to the callback function
758
- console.log('Finish (progress) ', response);
759
- onFinish(response);
760
- }
761
- if (response.status === 'ERROR' && onError) {
762
- // Provide the current progress to the callback function
763
- onError(response);
764
- }
765
350
 
766
- // Provide the current progress to the callback function
767
- if (response.status == 'RUNNING') {
768
- onProgress(response);
769
- }
351
+ // Validate response structure
352
+ const {
353
+ ok,
354
+ jobId,
355
+ status,
356
+ message,
357
+ output
358
+ } = response;
359
+ if (!ok || typeof jobId !== 'string' || typeof status !== 'string') {
360
+ throw new Error('Invalid response structure');
361
+ }
770
362
 
771
- // Continue polling if the status is 'RUNNING'
772
- if (['RUNNING'].includes(response.status)) {
773
- setTimeout(checkProgress, 1000); // Poll every 2 seconds
774
- }
775
- case 7:
776
- case "end":
777
- return _context14.stop();
778
- }
779
- }, _callee14);
780
- }));
781
- return function checkProgress() {
782
- return _ref2.apply(this, arguments);
783
- };
784
- }();
785
- checkProgress();
786
- _context15.next = 9;
787
- break;
788
- case 6:
789
- _context15.prev = 6;
790
- _context15.t0 = _context15["catch"](1);
791
- return _context15.abrupt("return", this._handleError(_context15.t0));
792
- case 9:
793
- case "end":
794
- return _context15.stop();
795
- }
796
- }, _callee15, this, [[1, 6]]);
797
- }));
798
- function pollTaskProgress(_x10, _x11) {
799
- return _pollTaskProgress.apply(this, arguments);
363
+ // If the task is still in progress, start polling for updates
364
+ if (status === 'RUNNING' || status === 'SCHEDULED' || status === 'QUEUED') {
365
+ this.pollTaskProgress(jobId, callbacks);
800
366
  }
801
- return pollTaskProgress;
802
- }()
803
- /**
804
- * Performs a GET request to the specified endpoint.
805
- *
806
- * This method uses the Axios instance to make an authenticated GET request.
807
- * The `authtoken` stored in the class instance is included in the request headers
808
- * for authorization. It handles any errors and returns the response data.
809
- *
810
- * @param {string} endpoint - The endpoint URL to which the GET request is made.
811
- * @param {Object} [params={}] - Optional parameters to be sent with the request.
812
- * @returns {Promise<Object>} - The response data from the API.
813
- */
814
- )
815
- }, {
816
- key: "get",
817
- value: (function () {
818
- var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(endpoint) {
819
- var params,
820
- headers,
821
- response,
822
- _args16 = arguments;
823
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
824
- while (1) switch (_context16.prev = _context16.next) {
825
- case 0:
826
- params = _args16.length > 1 && _args16[1] !== undefined ? _args16[1] : {};
827
- debugger;
828
- _context16.prev = 2;
829
- // Add the authToken to the headers
830
- headers = {
831
- authtoken: this.authtoken
832
- }; // Make the GET request using Axios
833
- _context16.next = 6;
834
- return this.axios.get(endpoint, {
835
- params: params,
836
- headers: headers
837
- });
838
- case 6:
839
- response = _context16.sent;
840
- if (!(response.data.ok === false)) {
841
- _context16.next = 9;
842
- break;
843
- }
844
- return _context16.abrupt("return", this._handleError(response));
845
- case 9:
846
- return _context16.abrupt("return", response.data);
847
- case 12:
848
- _context16.prev = 12;
849
- _context16.t0 = _context16["catch"](2);
850
- return _context16.abrupt("return", this._handleError(_context16.t0));
851
- case 15:
852
- case "end":
853
- return _context16.stop();
854
- }
855
- }, _callee16, this, [[2, 12]]);
856
- }));
857
- function get(_x12) {
858
- return _get.apply(this, arguments);
367
+ if (status === 'ERROR' && onError) {
368
+ // Provide the current progress to the callback function
369
+ onError(response);
859
370
  }
860
- return get;
861
- }()
862
- /**
863
- * Performs a POST request to the specified endpoint.
864
- *
865
- * This method uses the Axios instance to make an authenticated POST request.
866
- * It includes the `authtoken` in the request headers for authorization. The method
867
- * sends the provided data as the request body. It handles any errors and returns
868
- * the response data.
869
- *
870
- * @param {string} endpoint - The endpoint URL to which the POST request is made.
871
- * @param {Object} [data={}] - Data to be sent in the body of the POST request.
872
- * @returns {Promise<Object>} - The response data from the API.
873
- */
874
- )
875
- }, {
876
- key: "post",
877
- value: (function () {
878
- var _post = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(endpoint) {
879
- var data,
880
- headers,
881
- response,
882
- _args17 = arguments;
883
- return _regeneratorRuntime().wrap(function _callee17$(_context17) {
884
- while (1) switch (_context17.prev = _context17.next) {
885
- case 0:
886
- data = _args17.length > 1 && _args17[1] !== undefined ? _args17[1] : {};
887
- _context17.prev = 1;
888
- // Add the authToken to the headers
889
- headers = {
890
- authtoken: this.authtoken
891
- }; // Make the POST request using Axios
892
- _context17.next = 5;
893
- return this.axios.post(endpoint, data, {
894
- headers: headers
895
- });
896
- case 5:
897
- response = _context17.sent;
898
- if (!(response.data.ok === false)) {
899
- _context17.next = 8;
900
- break;
901
- }
902
- return _context17.abrupt("return", this._handleError(response));
903
- case 8:
904
- return _context17.abrupt("return", response.data);
905
- case 11:
906
- _context17.prev = 11;
907
- _context17.t0 = _context17["catch"](1);
908
- return _context17.abrupt("return", this._handleError(_context17.t0));
909
- case 14:
910
- case "end":
911
- return _context17.stop();
912
- }
913
- }, _callee17, this, [[1, 11]]);
914
- }));
915
- function post(_x13) {
916
- return _post.apply(this, arguments);
371
+ if (status === 'DONE' && onFinish) {
372
+ // Provide the current progress to the callback function
373
+ console.log('Finish (request) ', response);
374
+ onFinish(response);
917
375
  }
918
- return post;
919
- }())
920
- }, {
921
- key: "setErrorHandler",
922
- value: function setErrorHandler(customErrorHandler) {
923
- this.customErrorHandler = customErrorHandler;
924
- }
925
- }, {
926
- key: "_handleError",
927
- value: function _handleError(err) {
928
- // Invoke the custom error handler if provided
929
- if (this.customErrorHandler) {
930
- var res = this.customErrorHandler(err);
931
- if (res) return;
376
+ return {
377
+ ok,
378
+ jobId,
379
+ status,
380
+ message,
381
+ output
382
+ };
383
+ } catch (e) {
384
+ if (typeof onError === 'function') {
385
+ onError(e);
386
+ } else {
387
+ console.error('Error in runTask:', e);
932
388
  }
933
- if (_lodash["default"].isObject(err) && _lodash["default"].get(err, 'response')) {
934
- var msg = _lodash["default"].get(err, 'response.data.message', 'Error in API response');
935
- if (msg.key) {
936
- throw new Error(msg.key);
937
- } else {
938
- throw new Error(msg);
389
+ return {
390
+ ok: false,
391
+ jobId: null,
392
+ status: 'ERROR',
393
+ error: e.message
394
+ };
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Polls the progress of a long-running task.
400
+ *
401
+ * @param {string} jobId - The ID of the job to poll for progress.
402
+ * @param {function} onProgress - Callback function that receives progress updates.
403
+ *
404
+ * The function periodically sends GET requests to check the task's progress
405
+ * and reports back via the provided callback function . The polling stops when
406
+ * the task is completed or an error occurs.
407
+ */
408
+ async pollTaskProgress(jobId, callbacks) {
409
+ const {
410
+ onProgress,
411
+ onError,
412
+ onFinish
413
+ } = callbacks;
414
+ try {
415
+ const checkProgress = async () => {
416
+ const response = await this.get(`/task_service/pollChainProgress`, {
417
+ jobId: jobId
418
+ });
419
+
420
+ // If the task is still in progress, start polling for updates
421
+ if (response.status === 'DONE' && onFinish) {
422
+ // Provide the current progress to the callback function
423
+ console.log('Finish (progress) ', response);
424
+ onFinish(response);
425
+ }
426
+ if (response.status === 'ERROR' && onError) {
427
+ // Provide the current progress to the callback function
428
+ onError(response);
429
+ }
430
+
431
+ // Provide the current progress to the callback function
432
+ if (response.status == 'RUNNING') {
433
+ onProgress(response);
939
434
  }
435
+
436
+ // Continue polling if the status is 'RUNNING'
437
+ if (['RUNNING'].includes(response.status)) {
438
+ setTimeout(checkProgress, 1000); // Poll every 2 seconds
439
+ }
440
+ };
441
+ checkProgress();
442
+ } catch (e) {
443
+ // Handle error based on your application's logic
444
+ return this._handleError(e);
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Performs a GET request to the specified endpoint.
450
+ *
451
+ * This method uses the Axios instance to make an authenticated GET request.
452
+ * The `authtoken` stored in the class instance is included in the request headers
453
+ * for authorization. It handles any errors and returns the response data.
454
+ *
455
+ * @param {string} endpoint - The endpoint URL to which the GET request is made.
456
+ * @param {Object} [params={}] - Optional parameters to be sent with the request.
457
+ * @returns {Promise<Object>} - The response data from the API.
458
+ */
459
+ async get(endpoint, params = {}) {
460
+ debugger;
461
+ try {
462
+ // Add the authToken to the headers
463
+ const headers = {
464
+ authtoken: this.authtoken
465
+ };
466
+
467
+ // Make the GET request using Axios
468
+ const response = await this.axios.get(endpoint, {
469
+ params,
470
+ headers
471
+ });
472
+
473
+ // Check if the response is not okay
474
+ if (response.data.ok === false) {
475
+ return this._handleError(response);
476
+ }
477
+
478
+ // Return the response data
479
+ return response.data;
480
+ } catch (e) {
481
+ // Handle any errors
482
+ return this._handleError(e);
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Performs a POST request to the specified endpoint.
488
+ *
489
+ * This method uses the Axios instance to make an authenticated POST request.
490
+ * It includes the `authtoken` in the request headers for authorization. The method
491
+ * sends the provided data as the request body. It handles any errors and returns
492
+ * the response data.
493
+ *
494
+ * @param {string} endpoint - The endpoint URL to which the POST request is made.
495
+ * @param {Object} [data={}] - Data to be sent in the body of the POST request.
496
+ * @returns {Promise<Object>} - The response data from the API.
497
+ */
498
+ async post(endpoint, data = {}) {
499
+ try {
500
+ // Add the authToken to the headers
501
+ const headers = {
502
+ authtoken: this.authtoken
503
+ };
504
+
505
+ // Make the POST request using Axios
506
+ const response = await this.axios.post(endpoint, data, {
507
+ headers
508
+ });
509
+
510
+ // Check if the response is not okay
511
+ if (response.data.ok === false) {
512
+ return this._handleError(response);
513
+ }
514
+
515
+ // Return the response data
516
+ return response.data;
517
+ } catch (e) {
518
+ // Handle any errors
519
+ return this._handleError(e);
520
+ }
521
+ }
522
+ setErrorHandler(customErrorHandler) {
523
+ this.customErrorHandler = customErrorHandler;
524
+ }
525
+ _handleError(err) {
526
+ // Invoke the custom error handler if provided
527
+ if (this.customErrorHandler) {
528
+ let res = this.customErrorHandler(err);
529
+ if (res) return;
530
+ }
531
+ if (_.isObject(err) && _.get(err, 'response')) {
532
+ console.log('RbtAPI handleError', err);
533
+ const msg = _.get(err, 'response.data.message', 'Error in API response');
534
+ if (msg.key) {
535
+ throw new Error(msg.key);
940
536
  } else {
941
- throw new Error(err.message || 'Unknown error');
537
+ throw new Error(msg);
942
538
  }
539
+ } else {
540
+ throw new Error(err.message || 'Unknown error');
943
541
  }
944
- }]);
945
- return RbtApi;
946
- }();
542
+ }
543
+ }