From a780a756ada8267b657c498c36320389a148b279 Mon Sep 17 00:00:00 2001 From: Manfred Zingl Date: Thu, 20 Nov 2025 15:42:29 +0100 Subject: [PATCH 01/22] switch to ESM --- lib/Api.js | 46 +- lib/AsyncApi.js | 83 +-- lib/SyncApi.js | 300 ++++----- lib/index.js | 1641 +++++++++++++++++++++++------------------------ package.json | 7 +- src/Api.js | 6 +- src/AsyncApi.js | 8 +- src/SyncApi.js | 8 +- src/index.js | 10 +- 9 files changed, 989 insertions(+), 1120 deletions(-) diff --git a/lib/Api.js b/lib/Api.js index 1813710..3e5b50a 100644 --- a/lib/Api.js +++ b/lib/Api.js @@ -1,45 +1,35 @@ -"use strict"; - -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); } -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; } -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; } -function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } -function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } -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); } } -function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } -function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } -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); } -var _ = require("lodash"); +import _ from "lodash"; /** * @typedef {object} ApiOptions * @property cookies {object} */ -var Api = /*#__PURE__*/function () { + +class Api { + /** * * @param baseUrl {string} * @param options {ApiOptions} */ - function Api(baseUrl, options) { - _classCallCheck(this, Api); + constructor(baseUrl, options) { if (this.constructor === Api) { throw new Error("Abstract class 'Api' cannot be instantiated!"); } + this.baseUrl = baseUrl; this.cookies = _.get(options, ["cookies"], {}); this.headers = _.get(options, ["headers"], {}); } - return _createClass(Api, [{ - key: "_getRequestHeaders", - value: function _getRequestHeaders() { - return _objectSpread({ - "Cookie": _.map(this.cookies, function (_ref, name) { - var value = _ref.value; - return name + "=" + value || "undefined"; - }).join("; ") - }, this.headers); - } - }]); -}(); -module.exports = Api; \ No newline at end of file + + _getRequestHeaders() { + return { + "Cookie": _.map(this.cookies, ({value}, name) => { + return name + "=" + value || "undefined"; + }).join("; "), + ...this.headers + }; + } +} + +export default Api; diff --git a/lib/AsyncApi.js b/lib/AsyncApi.js index de2faf5..41ef9eb 100644 --- a/lib/AsyncApi.js +++ b/lib/AsyncApi.js @@ -1,37 +1,18 @@ -"use strict"; - -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); } -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; } -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); } -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); }); }; } -function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } -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); } } -function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } -function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } -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); } -function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } -function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } -function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } -function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } -function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } -function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } -function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } -var fetch = require("node-fetch"); -var Api = require("./Api"); +import Api from "./Api.js"; /** * */ -var AsyncApi = /*#__PURE__*/function (_Api) { +class AsyncApi extends Api { + /** * * @param baseUrl {string} * @param options {ApiOptions} */ // eslint-disable-next-line no-useless-constructor - function AsyncApi(baseUrl, options) { - _classCallCheck(this, AsyncApi); - return _callSuper(this, AsyncApi, [baseUrl, options]); + constructor(baseUrl, options) { + super(baseUrl, options); } /** @@ -41,39 +22,21 @@ var AsyncApi = /*#__PURE__*/function (_Api) { * @param [json] {object} * @param [nonce] {string} */ - _inherits(AsyncApi, _Api); - return _createClass(AsyncApi, [{ - key: "doCall", - value: (function () { - var _doCall = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, url, json, nonce) { - var fullUrl, options, response; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - fullUrl = nonce ? this.baseUrl + url + "?" + new URLSearchParams({ - nonce: nonce - }) : this.baseUrl + url; - options = { - method: method, - headers: this._getRequestHeaders(), - body: json ? JSON.stringify(json) : undefined - }; - _context.next = 4; - return fetch(fullUrl, options); - case 4: - response = _context.sent; - return _context.abrupt("return", response.json()); - case 6: - case "end": - return _context.stop(); - } - }, _callee, this); - })); - function doCall(_x, _x2, _x3, _x4) { - return _doCall.apply(this, arguments); - } - return doCall; - }()) - }]); -}(Api); -module.exports = AsyncApi; \ No newline at end of file + async doCall(method, url, json, nonce) { + const fullUrl = nonce + ? this.baseUrl + url + "?" + new URLSearchParams({nonce}) + : this.baseUrl + url; + + const options = { + method: method, + headers: this._getRequestHeaders(), + body: json ? JSON.stringify(json) : undefined + }; + + const response = await fetch(fullUrl, options); + + return response.json(); + } +} + +export default AsyncApi; diff --git a/lib/SyncApi.js b/lib/SyncApi.js index d115a43..ee5f435 100644 --- a/lib/SyncApi.js +++ b/lib/SyncApi.js @@ -1,34 +1,20 @@ -"use strict"; - -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); } -function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } -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); } } -function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } -function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } -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); } -function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } -function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } -function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } -function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } -function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } -function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } -function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } -var request = require("sync-request"); -var Api = require("./Api"); +import request from "sync-request"; + +import Api from "./Api.js"; /** * */ -var SyncApi = /*#__PURE__*/function (_Api) { +class SyncApi extends Api { + /** * * @param baseUrl {string} * @param options {ApiOptions} */ // eslint-disable-next-line no-useless-constructor - function SyncApi(baseUrl, options) { - _classCallCheck(this, SyncApi); - return _callSuper(this, SyncApi, [baseUrl, options]); + constructor(baseUrl, options) { + super(baseUrl, options); } /** @@ -38,154 +24,148 @@ var SyncApi = /*#__PURE__*/function (_Api) { * @param [json] {object} * @param [nonce] {string} */ - _inherits(SyncApi, _Api); - return _createClass(SyncApi, [{ - key: "doCall", - value: function doCall(method, url, json, nonce) { - var fullUrl = this.baseUrl + url; - var options = { - headers: this._getRequestHeaders(), - json: json, - qs: { - nonce: nonce - } - }; - var response = request(method, fullUrl, options).getBody("utf-8"); - return JSON.parse(response); - } - - /** - * - * @param nonce {string} - */ - }, { - key: "resetSchema", - value: function resetSchema(nonce) { - return this.doCall("POST", "/system/reset", undefined, nonce); - } + doCall(method, url, json, nonce) { + const fullUrl = this.baseUrl + url; - /** - * - * @param tableId {number} - * @param [includeRows=false] {boolean} - */ - }, { - key: "fetchTable", - value: function fetchTable(tableId) { - var includeRows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (typeof tableId !== "number") { - throw new Error("parameter 'tableId' should be a number"); - } - var table = this.doCall("GET", "/tables/" + tableId); - delete table["id"]; - delete table["status"]; - var columns = this.doCall("GET", "/tables/" + tableId + "/columns"); - delete columns["status"]; - Object.assign(table, columns); - if (includeRows) { - var rows = this.doCall("GET", "/tables/" + tableId + "/rows"); - delete rows["page"]; - delete rows["status"]; - Object.assign(table, rows); + const options = { + headers: this._getRequestHeaders(), + json: json, + qs: { + nonce: nonce } - return table; - } + }; - /** - * - * @param name {string} - * @param hidden {boolean} - * @param displayName {object} multi-language object - * @param type {string} - * @param group {number} - * @returns {object} - */ - }, { - key: "createTable", - value: function createTable(name, hidden, displayName, type, group) { - var json = { - "name": name, - "hidden": typeof hidden === "boolean" ? hidden : false - }; - if (displayName && _typeof(displayName) === "object") { - json["displayName"] = displayName; - } - if (type && typeof type === "string") { - json["type"] = type; - } - if (group && typeof group === "number") { - json["group"] = group; - } - return this.doCall("POST", "/tables", json); + const response = request(method, fullUrl, options).getBody("utf-8"); + + return JSON.parse(response); + } + + /** + * + * @param nonce {string} + */ + resetSchema(nonce) { + return this.doCall("POST", "/system/reset", undefined, nonce); + } + + /** + * + * @param tableId {number} + * @param [includeRows=false] {boolean} + */ + fetchTable(tableId, includeRows = false) { + if (typeof tableId !== "number") { + throw new Error("parameter 'tableId' should be a number"); } - /** - * - * @param tableId - * @param columnObjArray - */ - }, { - key: "createColumns", - value: function createColumns(tableId, columnObjArray) { - var json = { - "columns": columnObjArray - }; - return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns; + const table = this.doCall("GET", "/tables/" + tableId); + + delete table["id"]; + delete table["status"]; + + const columns = this.doCall("GET", "/tables/" + tableId + "/columns"); + + delete columns["status"]; + + Object.assign(table, columns); + + if (includeRows) { + const rows = this.doCall("GET", "/tables/" + tableId + "/rows"); + + delete rows["page"]; + delete rows["status"]; + + Object.assign(table, rows); } - /** - * - * @param tableId - * @param columnObject - */ - }, { - key: "createColumn", - value: function createColumn(tableId, columnObject) { - var json = { - "columns": [columnObject] - }; - return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns[0]; + return table; + } + + /** + * + * @param name {string} + * @param hidden {boolean} + * @param displayName {object} multi-language object + * @param type {string} + * @param group {number} + * @returns {object} + */ + createTable(name, hidden, displayName, type, group) { + const json = { + "name": name, + "hidden": (typeof hidden === "boolean" ? hidden : false) + }; + + if (displayName && typeof displayName === "object") { + json["displayName"] = displayName; } - /** - * - * @param tableId - * @param columnIds - * @param values - * @returns {*} - */ - }, { - key: "createRow", - value: function createRow(tableId, columnIds, values) { - return this.createRows(tableId, columnIds, [values])[0]; + if (type && typeof type === "string") { + json["type"] = type; } - /** - * - * @param tableId - * @param columnIds - * @param rows - */ - }, { - key: "createRows", - value: function createRows(tableId, columnIds, rows) { - var json = { - "columns": columnIds.map(function (columnId) { - return { - "id": columnId - }; - }), - "rows": rows.map(function (rowValues) { - return { - "values": rowValues - }; - }) - }; - var result = this.doCall("POST", "/tables/" + tableId + "/rows", json); - return result.rows.map(function (row) { - return row.id; - }); + if (group && typeof group === "number") { + json["group"] = group; } - }]); -}(Api); -module.exports = SyncApi; \ No newline at end of file + + return this.doCall("POST", "/tables", json); + } + + /** + * + * @param tableId + * @param columnObjArray + */ + createColumns(tableId, columnObjArray) { + const json = { + "columns": columnObjArray + }; + + return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns; + } + + /** + * + * @param tableId + * @param columnObject + */ + createColumn(tableId, columnObject) { + const json = { + "columns": [ + columnObject + ] + }; + + return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns[0]; + } + + /** + * + * @param tableId + * @param columnIds + * @param values + * @returns {*} + */ + createRow(tableId, columnIds, values) { + return this.createRows(tableId, columnIds, [values])[0]; + } + + /** + * + * @param tableId + * @param columnIds + * @param rows + */ + createRows(tableId, columnIds, rows) { + const json = { + "columns": columnIds.map(columnId => ({"id": columnId})), + "rows": rows.map(rowValues => ({"values": rowValues})) + }; + + const result = this.doCall("POST", "/tables/" + tableId + "/rows", json); + + return result.rows.map(row => row.id); + } +} + +export default SyncApi; diff --git a/lib/index.js b/lib/index.js index 85a2a66..29dbef5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,44 +1,44 @@ -"use strict"; - -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); } -function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } -function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } -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); } } -function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } -function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } -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); } -var _ = require("lodash"); -var AsyncApi = require("./AsyncApi"); -var SyncApi = require("./SyncApi"); +import _ from "lodash"; + +import AsyncApi from "./AsyncApi.js"; +import SyncApi from "./SyncApi.js"; + function argumentsToMultiLanguageObj(argsObj) { - var args = _.toArray(argsObj); - var langtagRegex = /[a-z]{2,3}[-_][A-Z]{2,3}|[a-z]{2,3}/; - var obj = {}; + const args = _.toArray(argsObj); + const langtagRegex = /[a-z]{2,3}[-_][A-Z]{2,3}|[a-z]{2,3}/; + + let obj = {}; + if (args.length === 1 && _.isPlainObject(args[0])) { - var valid = _.every(_.keys(args[0]), function (key) { + let valid = _.every(_.keys(args[0]), function (key) { return langtagRegex.test(key); }); + if (valid) { obj = args[0]; } else { throw new Error("arguments must be either key/value list (e.g. de-DE, Tabelle, en-GB, table) or a plain object"); } } else if (_.isArray(args) && args.length % 2 === 0) { - var object = {}; - for (var i = 0; i < args.length; i += 2) { - var langtag = args[i]; - var value = args[i + 1]; + let object = {}; + + for (let i = 0; i < args.length; i += 2) { + const langtag = args[i]; + const value = args[i + 1]; + if (langtag !== undefined && langtagRegex.test(langtag) && value !== undefined) { object[langtag] = value; } else { throw new Error("Arguments are wrong. undefined or wrong langtag. (" + JSON.stringify(args) + ")"); } } + obj = object; } else { console.log("invalid args", args, _.isArray(args), _.isPlainObject(args), _.toArray(args)); throw new Error("arguments must be either key/value list (e.g. de-DE, Tabelle, en-GB, table) or a plain object"); } + return obj; } @@ -60,21 +60,26 @@ function argumentsToMultiLanguageObj(argsObj) { * @returns {GRUDStructorizer} */ function grudStructorizer(baseUrl, options) { - var syncApi = new SyncApi(baseUrl, options); - var asyncApi = new AsyncApi(baseUrl, options); - var StaticHelpers = { - getLanguages: function getLanguages() { + + const syncApi = new SyncApi(baseUrl, options); + const asyncApi = new AsyncApi(baseUrl, options); + + const StaticHelpers = { + getLanguages: () => { return syncApi.doCall("GET", "/system/settings/langtags").value; }, - checkKindForLanguageConversion: function checkKindForLanguageConversion(kind) { - var ALLOWED_TYPES = ["shorttext", "text"]; + + checkKindForLanguageConversion: (kind) => { + const ALLOWED_TYPES = ["shorttext", "text"]; + if (!_.includes(ALLOWED_TYPES, kind)) { - throw new Error("Column must be of kind '".concat(_.join(ALLOWED_TYPES, "' or '"), "'")); + throw new Error(`Column must be of kind '${_.join(ALLOWED_TYPES, "' or '")}'`); } }, - checkLanguageForLanguageConversion: function checkLanguageForLanguageConversion(languages, targetLanguage) { + + checkLanguageForLanguageConversion: (languages, targetLanguage) => { if (!_.includes(languages, targetLanguage)) { - throw new Error("Language '".concat(targetLanguage, "' not in '/system/settings/langtags'")); + throw new Error(`Language '${targetLanguage}' not in '/system/settings/langtags'`); } } }; @@ -82,12 +87,12 @@ function grudStructorizer(baseUrl, options) { /** * */ - var Tables = /*#__PURE__*/function () { + class Tables { + /** * */ - function Tables() { - _classCallCheck(this, Tables); + constructor() { this.tables = []; } @@ -96,54 +101,51 @@ function grudStructorizer(baseUrl, options) { * * @returns {Tables} */ - return _createClass(Tables, [{ - key: "fetch", - value: function fetch() { - Object.assign(this, syncApi.doCall("GET", "/tables")); - return this; - } + fetch() { + Object.assign(this, syncApi.doCall("GET", "/tables")); + return this; + } - /** - * Searches for a specific table. Fetch tables first - * - * @param tableName {string} - * @returns {Table} - */ - }, { - key: "find", - value: function find(tableName) { - var table = _.find(this.tables, { - name: tableName - }); - if (table) { - return new Table(table.id, table.name); - } + /** + * Searches for a specific table. Fetch tables first + * + * @param tableName {string} + * @returns {Table} + */ + find(tableName) { + const table = _.find(this.tables, { name: tableName }); + + if (table) { + return new Table(table.id, table.name); } - }]); - }(); + } + } + /** * @typedef {object} Column * @property id {number} * @property name {string} * @property kind {string} */ + /** * */ - var Table = /*#__PURE__*/function () { + class Table { /** * * @param tableId {number} * @param tableName {string} */ - function Table(tableId, tableName) { - _classCallCheck(this, Table); + constructor(tableId, tableName) { if (typeof tableId !== "number") { throw new Error("parameter 'tableId' should be a number"); } + if (typeof tableName !== "string") { throw new Error("parameter 'tableName' should be a string"); } + this.tableId = tableId; this.name = tableName; this.columns = []; @@ -155,385 +157,382 @@ function grudStructorizer(baseUrl, options) { * @param includeRows retrieves rows (default: false) {boolean} * @returns {Table} */ - return _createClass(Table, [{ - key: "fetch", - value: function fetch() { - var includeRows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - Object.assign(this, syncApi.fetchTable(this.tableId, includeRows)); - return this; - } + fetch(includeRows = false) { + Object.assign(this, syncApi.fetchTable(this.tableId, includeRows)); + return this; + } - /** - * Returns an array of row objects zipped with column names for this Table. - * - * The `rowId` property represents the row ID (PK) of the database, - * so this value can be reused for updates/deletions/etc. - * - * @returns {Array.} array row objects - */ - }, { - key: "getRows", - value: function getRows() { - var _this = this; - if (!this.columns || !this.rows) { - throw new Error("Fetch table and rows first"); - } - return _.map(this.rows, function (row) { - var obj = _.zipObject(_.map(_this.columns, "name"), row.values); + /** + * Returns an array of row objects zipped with column names for this Table. + * + * The `rowId` property represents the row ID (PK) of the database, + * so this value can be reused for updates/deletions/etc. + * + * @returns {Array.} array row objects + */ + getRows() { + if (!this.columns || !this.rows) { + throw new Error("Fetch table and rows first"); + } + return _.map( + this.rows, + (row) => { + const obj = _.zipObject(_.map(this.columns, "name"), row.values); obj.rowId = row.id; return obj; - }); - } - - /** - * Returns a single row object zipped with column names for this Table. - * - * The `rowId` property represents the row ID (PK) of the database, - * so this value can be reused for updates/deletions/etc. - * - * @param id {number} - * @returns {Object} row object - */ - }, { - key: "getRow", - value: function getRow(id) { - if (!this.columns || !this.rows) { - throw new Error("Fetch table and rows first"); } - if (typeof id !== "number") { - throw new Error("Parameter 'id' should be a number"); - } - var foundRow = _.find(this.rows, function (row) { - return row.id === id; - }); - if (!foundRow) { - throw new Error("No row found for id '" + id + "'"); - } - var obj = _.zipObject(_.map(this.columns, "name"), foundRow.values); - obj.rowId = foundRow.id; - return obj; + ); + } + + /** + * Returns a single row object zipped with column names for this Table. + * + * The `rowId` property represents the row ID (PK) of the database, + * so this value can be reused for updates/deletions/etc. + * + * @param id {number} + * @returns {Object} row object + */ + getRow(id) { + if (!this.columns || !this.rows) { + throw new Error("Fetch table and rows first"); + } + if (typeof id !== "number") { + throw new Error("Parameter 'id' should be a number"); } - /** - * - * @param nameOrId {string|number} - */ - }, { - key: "findColumn", - value: function findColumn(nameOrId) { - if (!this.columns) { - throw new Error("Fetch table first"); - } - return _.find(this.columns, function (column) { - if (_.isInteger(nameOrId)) { - return column.id === nameOrId; - } else { - return column.name === nameOrId; - } - }); + const foundRow = _.find(this.rows, (row) => row.id === id); + + if (!foundRow) { + throw new Error("No row found for id '" + id + "'"); } - /** - * - * @param columnBuilderArray {Array.} - * @returns {Array.} - */ - }, { - key: "createColumns", - value: function createColumns(columnBuilderArray) { - if (typeof this.tableId === "undefined") { - throw new Error("table " + this.name + " should be created first"); - } - var columnObjArray = columnBuilderArray.map(function (columnBuilder) { - return columnBuilder.build(); - }); - var self = this; - columnObjArray.forEach(function (columnObject) { - self.columns.forEach(function (column) { - if (column.name === columnObject.name) { - throw new Error("column " + columnObject.name + " can't be created because its name " + columnObject.name + " is already used"); - } - }); - }); - var newColumns = syncApi.createColumns(this.tableId, columnObjArray); - newColumns.forEach(function (newColumn) { - self.columns.push(newColumn); - }); - return newColumns; + const obj = _.zipObject(_.map(this.columns, "name"), foundRow.values); + obj.rowId = foundRow.id; + + return obj; + } + + /** + * + * @param nameOrId {string|number} + */ + findColumn(nameOrId) { + if (!this.columns) { + throw new Error("Fetch table first"); } - /** - * - * @param nameOrId {string|number} - */ - }, { - key: "deleteColumn", - value: function deleteColumn(nameOrId) { - var column = this.findColumn(nameOrId); - if (!column) { - throw new Error("No column with this name or ID found '" + nameOrId + "'"); - } - var response = syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); - if (response) { - _.remove(this.columns, function (c) { - return c.id === column.id; - }); + return _.find(this.columns, function (column) { + if (_.isInteger(nameOrId)) { + return column.id === nameOrId; + } else { + return column.name === nameOrId; } + }); + } + + /** + * + * @param columnBuilderArray {Array.} + * @returns {Array.} + */ + createColumns(columnBuilderArray) { + if (typeof this.tableId === "undefined") { + throw new Error("table " + this.name + " should be created first"); } - /** - * - * @param columnBuilder {ColumnBuilder} - * @return {number} column id - */ - }, { - key: "createColumn", - value: function createColumn(columnBuilder) { - if (typeof this.tableId === "undefined") { - throw new Error("table " + this.name + " should be created first"); - } - var columnObject = columnBuilder.build(); - this.columns.forEach(function (column) { + const columnObjArray = columnBuilderArray.map(function (columnBuilder) { + return columnBuilder.build(); + }); + + const self = this; + + columnObjArray.forEach(function (columnObject) { + self.columns.forEach(function (column) { if (column.name === columnObject.name) { throw new Error("column " + columnObject.name + " can't be created because its name " + columnObject.name + " is already used"); } }); - var newColumn = syncApi.createColumn(this.tableId, columnBuilder.build()); - this.columns.push(newColumn); - return newColumn.id; + }); + + const newColumns = syncApi.createColumns(this.tableId, columnObjArray); + + newColumns.forEach(function (newColumn) { + self.columns.push(newColumn); + }); + + return newColumns; + } + + /** + * + * @param nameOrId {string|number} + */ + deleteColumn(nameOrId) { + const column = this.findColumn(nameOrId); + + if (!column) { + throw new Error("No column with this name or ID found '" + nameOrId + "'"); } - }, { - key: "getValuesFromCreateRowByObj", - value: function getValuesFromCreateRowByObj(columnNameToValueObject) { - var _this2 = this; - if (!this.columns) { - throw new Error("table needs to be fetched first, columns should be defined"); - } - if (!_.isPlainObject(columnNameToValueObject)) { - throw new Error("columnNameToValueObject should be a simple plain object"); - } - var columnNames = _.keys(columnNameToValueObject); - var columnIdToValueArray = columnNames.map(function (columnName) { - var column = _.find(_this2.columns, ["name", columnName]); - if (!column) { - throw new Error("column '" + columnName + "' is not defined in table '" + _this2.name + "'"); - } - return [column.id, columnNameToValueObject[columnName]]; + + const response = syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); + + if (response) { + _.remove(this.columns, function (c) { + return c.id === column.id; }); - var columnIds = _.map(columnIdToValueArray, _.first); - var values = _.map(columnIdToValueArray, _.last); - return { - columnIds: columnIds, - values: values - }; } + } - /** - * - * @param columnNameToValueObject {object} - * @returns {number} row id - */ - }, { - key: "createRowByObj", - value: function createRowByObj(columnNameToValueObject) { - var _this$getValuesFromCr = this.getValuesFromCreateRowByObj(columnNameToValueObject), - columnIds = _this$getValuesFromCr.columnIds, - values = _this$getValuesFromCr.values; - return this.createRows([values], columnIds)[0]; + /** + * + * @param columnBuilder {ColumnBuilder} + * @return {number} column id + */ + createColumn(columnBuilder) { + if (typeof this.tableId === "undefined") { + throw new Error("table " + this.name + " should be created first"); } - /** - * - * @returns {number} row id - */ - }, { - key: "createRow", - value: function createRow() { - // convert arguments to array and - // hand it over to createRows with just one row - return this.createRows([_.toArray(arguments)])[0]; - } + const columnObject = columnBuilder.build(); - /** - * - * @param rows {Array.>} - * @param columns {Array.} - * @returns {Array.} array of row ids - */ - }, { - key: "createRows", - value: function createRows(rows, columns) { - if (typeof this.tableId === "undefined") { - throw new Error("table should be created first"); - } - var firstRowValues = _.head(rows) || []; - var sameLength = _.every(rows, function (rowValues) { - return rowValues.length === firstRowValues.length; - }); - if (!sameLength) { - throw new Error("all rows need to have same values length"); + this.columns.forEach(function (column) { + if (column.name === columnObject.name) { + throw new Error("column " + columnObject.name + " can't be created because its name " + columnObject.name + " is already used"); } + }); + + const newColumn = syncApi.createColumn(this.tableId, columnBuilder.build()); + + this.columns.push(newColumn); - // generate IDs based on rowValues length - var columnIds = columns || _.range(1, firstRowValues.length + 1); - return syncApi.createRows(this.tableId, columnIds, rows); + return newColumn.id; + } + + getValuesFromCreateRowByObj(columnNameToValueObject) { + if (!this.columns) { + throw new Error("table needs to be fetched first, columns should be defined"); } - }, { - key: "changeColumn", - value: function changeColumn(columnId, changeObj) { - return syncApi.doCall("POST", "/tables/" + this.tableId + "/columns/" + columnId, changeObj); + + if (!_.isPlainObject(columnNameToValueObject)) { + throw new Error("columnNameToValueObject should be a simple plain object"); } - }, { - key: "getColumn", - value: function getColumn(columnName) { - var column = this.findColumn(columnName); + + const columnNames = _.keys(columnNameToValueObject); + const columnIdToValueArray = columnNames.map((columnName) => { + const column = _.find(this.columns, ["name", columnName]); + if (!column) { - throw new Error("Column name '".concat(columnName, "' does not exist")); + throw new Error("column '" + columnName + "' is not defined in table '" + this.name + "'"); } - return column; + return [column.id, columnNameToValueObject[columnName]]; + }); + + const columnIds = _.map(columnIdToValueArray, _.first); + const values = _.map(columnIdToValueArray, _.last); + + return { + columnIds, + values + }; + } + + /** + * + * @param columnNameToValueObject {object} + * @returns {number} row id + */ + createRowByObj(columnNameToValueObject) { + + const { columnIds, values } = this.getValuesFromCreateRowByObj(columnNameToValueObject); + + return this.createRows([values], columnIds)[0]; + } + + /** + * + * @returns {number} row id + */ + createRow() { + // convert arguments to array and + // hand it over to createRows with just one row + return this.createRows([_.toArray(arguments)])[0]; + } + + /** + * + * @param rows {Array.>} + * @param columns {Array.} + * @returns {Array.} array of row ids + */ + createRows(rows, columns) { + if (typeof this.tableId === "undefined") { + throw new Error("table should be created first"); + } + + const firstRowValues = _.head(rows) || []; + const sameLength = _.every(rows, function (rowValues) { + return rowValues.length === firstRowValues.length; + }); + + if (!sameLength) { + throw new Error("all rows need to have same values length"); + } + + // generate IDs based on rowValues length + const columnIds = columns || _.range(1, firstRowValues.length + 1); + + return syncApi.createRows(this.tableId, columnIds, rows); + } + + changeColumn(columnId, changeObj) { + return syncApi.doCall("POST", "/tables/" + this.tableId + "/columns/" + columnId, changeObj); + } + + getColumn(columnName) { + const column = this.findColumn(columnName); + if (!column) { + throw new Error(`Column name '${columnName}' does not exist`); } - }, { - key: "convertColumnToMultilanguage", - value: - /** - * Convenient method to change a single language column to multi language - * - * @param columnName {string} - * @param pickLanguage language in which raw values should be inserted (default: "first language of - * '/system/settings/langtags'") {string} - */ - function convertColumnToMultilanguage(columnName, pickLanguage) { - var _this3 = this; - this.fetch(); - var column = this.getColumn(columnName); - var _$find = _.find(this.columns, { - name: columnName - }), - ordering = _$find.ordering, - kind = _$find.kind, - identifier = _$find.identifier, - displayName = _$find.displayName, - description = _$find.description, - multilanguage = _$find.multilanguage, - maxLength = _$find.maxLength, - minLength = _$find.minLength; - var languages = StaticHelpers.getLanguages(); - var defaultLanguage = _.head(languages); - StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage); - StaticHelpers.checkKindForLanguageConversion(kind); - if (multilanguage) { - throw new Error("Column is already multi language"); + return column; + }; + /** + * Convenient method to change a single language column to multi language + * + * @param columnName {string} + * @param pickLanguage language in which raw values should be inserted (default: "first language of + * '/system/settings/langtags'") {string} + */ + convertColumnToMultilanguage(columnName, pickLanguage) { + this.fetch(); + + const column = this.getColumn(columnName); + + const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(this.columns, { name: columnName }); + + const languages = StaticHelpers.getLanguages(); + const defaultLanguage = _.head(languages); + + StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage); + StaticHelpers.checkKindForLanguageConversion(kind); + + if (multilanguage) { + throw new Error("Column is already multi language"); + } + + const columnIndex = _.findIndex(this.columns, { name: columnName }); + + this.changeColumn(column.id, { name: columnName + "_convert_language" }); + this.fetch(true); + + const newColumnId = this.createColumn( + new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(true), + ); + + _.forEach(this.rows, row => { + const { id: rowId, values } = row; + const value = values[columnIndex]; + const url = "/tables/" + this.tableId + "/columns/" + newColumnId + "/rows/" + rowId; + + if (!value) { + return; } - var columnIndex = _.findIndex(this.columns, { - name: columnName - }); - this.changeColumn(column.id, { - name: columnName + "_convert_language" - }); - this.fetch(true); - var newColumnId = this.createColumn(new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(true)); - _.forEach(this.rows, function (row) { - var rowId = row.id, - values = row.values; - var value = values[columnIndex]; - var url = "/tables/" + _this3.tableId + "/columns/" + newColumnId + "/rows/" + rowId; - if (!value) { - return; - } - var mapValueIntoLanguage = function mapValueIntoLanguage(value, lang) { - return { - value: _defineProperty({}, lang, value) - }; + + const mapValueIntoLanguage = (value, lang) => { + return { + value: { + [lang]: value + } }; - var newValue = mapValueIntoLanguage(value, pickLanguage || defaultLanguage); - syncApi.doCall("PATCH", url, newValue); - syncApi.doCall("POST", "".concat(url, "/annotations"), { - langtags: languages, - type: "flag", - value: "needs_translation" - }); + }; + + const newValue = mapValueIntoLanguage(value, pickLanguage || defaultLanguage); + + syncApi.doCall("PATCH", url, newValue); + + syncApi.doCall("POST", `${url}/annotations`, { + langtags: languages, + type: "flag", + value: "needs_translation" }); - syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); + }); + + syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); + }; + + /** + * Convenient method to change a multi language column to single language + * @param columnName {string} + * @param pickLanguage language from which values are taken as new values (default: first language of + * '/system/settings/langtags') {string} + */ + convertColumnToSinglelanguage(columnName, pickLanguage) { + this.fetch(); + + const column = this.getColumn(columnName); + const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(this.columns, { name: columnName }); + + const languages = StaticHelpers.getLanguages(); + const defaultLanguage = _.head(languages); + + StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage); + StaticHelpers.checkKindForLanguageConversion(kind); + + if (!multilanguage) { + throw new Error("Column is already single language"); } - }, { - key: "convertColumnToSinglelanguage", - value: - /** - * Convenient method to change a multi language column to single language - * @param columnName {string} - * @param pickLanguage language from which values are taken as new values (default: first language of - * '/system/settings/langtags') {string} - */ - function convertColumnToSinglelanguage(columnName, pickLanguage) { - var _this4 = this; - this.fetch(); - var column = this.getColumn(columnName); - var _$find2 = _.find(this.columns, { - name: columnName - }), - ordering = _$find2.ordering, - kind = _$find2.kind, - identifier = _$find2.identifier, - displayName = _$find2.displayName, - description = _$find2.description, - multilanguage = _$find2.multilanguage, - maxLength = _$find2.maxLength, - minLength = _$find2.minLength; - var languages = StaticHelpers.getLanguages(); - var defaultLanguage = _.head(languages); - StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage); - StaticHelpers.checkKindForLanguageConversion(kind); - if (!multilanguage) { - throw new Error("Column is already single language"); + + const columnIndex = _.findIndex(this.columns, { name: columnName }); + + this.changeColumn(column.id, { name: columnName + "_convert_language" }); + this.fetch(true); + + const newColumnId = this.createColumn( + new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(false), + ); + + _.forEach(this.rows, row => { + const { id: rowId, values, annotations } = row; + + const newValue = _.get(values[columnIndex], pickLanguage || defaultLanguage); + const url = "/tables/" + this.tableId + "/columns/" + newColumnId + "/rows/" + rowId; + + if (!newValue) { + return; } - var columnIndex = _.findIndex(this.columns, { - name: columnName - }); - this.changeColumn(column.id, { - name: columnName + "_convert_language" - }); - this.fetch(true); - var newColumnId = this.createColumn(new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(false)); - _.forEach(this.rows, function (row) { - var rowId = row.id, - values = row.values, - annotations = row.annotations; - var newValue = _.get(values[columnIndex], pickLanguage || defaultLanguage); - var url = "/tables/" + _this4.tableId + "/columns/" + newColumnId + "/rows/" + rowId; - if (!newValue) { - return; - } - syncApi.doCall("PATCH", url, { - value: newValue - }); - if (_.includes(annotations, columnIndex)) { - // there schould be not more than one translation flag per cell - var langAnnotation = _.head(_.filter(annotations[columnIndex], { - "value": "needs_translation" - })); - if (langAnnotation) { - syncApi.doCall("DELETE", "".concat(url, "/annotations/").concat(langAnnotation.uuid)); - } + + syncApi.doCall("PATCH", url, { value: newValue }); + + if (_.includes(annotations, columnIndex)) { + // there schould be not more than one translation flag per cell + const langAnnotation = _.head(_.filter(annotations[columnIndex], { "value": "needs_translation" })); + + if (langAnnotation) { + syncApi.doCall("DELETE", `${url}/annotations/${langAnnotation.uuid}`); } - }); - syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); - } - }]); - }(); + } + }); + + syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id); + } + } + /** * */ - var TableBuilder = /*#__PURE__*/function () { + class TableBuilder { + /** * * @param name {string} * @param type {("generic"|"settings")} */ - function TableBuilder(name, type) { - _classCallCheck(this, TableBuilder); - var ALLOWED_TYPES = ["generic", "settings", "taxonomy"]; + constructor(name, type) { + const ALLOWED_TYPES = ["generic", "settings", "taxonomy"]; + this.name = name; this._groupId = null; + if (ALLOWED_TYPES.includes(type)) { this.type = type; } else { @@ -546,66 +545,56 @@ function grudStructorizer(baseUrl, options) { * @param args {Array.} one multi-language object or langtag-value list * @returns {TableBuilder} */ - return _createClass(TableBuilder, [{ - key: "displayName", - value: function displayName() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - this._displayName = argumentsToMultiLanguageObj(args); - return this; - } + displayName(...args) { + this._displayName = argumentsToMultiLanguageObj(args); + return this; + } - /** - * - * @param [hidden=true] {boolean} - * @returns {TableBuilder} - */ - }, { - key: "hidden", - value: function hidden(_hidden) { - this._hidden = typeof _hidden === "boolean" ? _hidden : true; - return this; - } + /** + * + * @param [hidden=true] {boolean} + * @returns {TableBuilder} + */ + hidden(hidden) { + this._hidden = typeof hidden === "boolean" ? hidden : true; + return this; + } - /** - * - * @param groupId {number} - * @returns {TableBuilder} - */ - }, { - key: "group", - value: function group(groupId) { - if (typeof groupId !== "number") { - throw new Error("groupId should be a int"); - } - this._groupId = groupId; - return this; + /** + * + * @param groupId {number} + * @returns {TableBuilder} + */ + group(groupId) { + if (typeof groupId !== "number") { + throw new Error("groupId should be a int"); } - /** - * - * @returns {Table} - */ - }, { - key: "create", - value: function create() { - var tableId = syncApi.createTable(this.name, this._hidden, this._displayName, this.type, this._groupId).id; - return new Table(tableId, this.name); - } - }]); - }(); + this._groupId = groupId; + return this; + } + + /** + * + * @returns {Table} + */ + create() { + const tableId = syncApi.createTable(this.name, this._hidden, this._displayName, this.type, this._groupId).id; + + return new Table(tableId, this.name); + } + } + /** * */ - var ColumnBuilder = /*#__PURE__*/function () { + class ColumnBuilder { /** * * @param name {string} * @param kind {string} */ - function ColumnBuilder(name, kind) { - _classCallCheck(this, ColumnBuilder); + constructor(name, kind) { this.column = { "name": name, "kind": kind @@ -617,479 +606,434 @@ function grudStructorizer(baseUrl, options) { * @param constraint {ConstraintCardinality|ConstraintDeleteCascade} * @returns {ColumnBuilder} */ - return _createClass(ColumnBuilder, [{ - key: "addConstraint", - value: function addConstraint(constraint) { - _.merge(this.column, { - constraint: constraint - }); - return this; - } + addConstraint(constraint) { + _.merge(this.column, { + constraint: constraint + }); - /** - * - * @param args {Array.} one multi-language object or langtag-value list - * @returns {ColumnBuilder} - */ - }, { - key: "displayName", - value: function displayName() { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - this.column.displayName = argumentsToMultiLanguageObj(args); - return this; - } + return this; + } - /** - * - * @param args {Array.} one multi-language object or langtag-value list - * @returns {ColumnBuilder} - */ - }, { - key: "description", - value: function description() { - for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - this.column.description = argumentsToMultiLanguageObj(args); - return this; - } + /** + * + * @param args {Array.} one multi-language object or langtag-value list + * @returns {ColumnBuilder} + */ + displayName(...args) { + this.column.displayName = argumentsToMultiLanguageObj(args); + return this; + } - /** - * - * @param ordering {number} - * @returns {ColumnBuilder} - */ - }, { - key: "ordering", - value: function ordering(_ordering) { - this.column.ordering = _ordering; - return this; - } + /** + * + * @param args {Array.} one multi-language object or langtag-value list + * @returns {ColumnBuilder} + */ + description(...args) { + this.column.description = argumentsToMultiLanguageObj(args); + return this; + } - /** - * - * @param [multilanguage=true] {boolean} - * @returns {ColumnBuilder} - */ - }, { - key: "multilanguage", - value: function multilanguage(_multilanguage) { - if (_multilanguage === true || typeof _multilanguage === "undefined") { - this.languageType("language"); - } else { - this.languageType("neutral"); - } - return this; - } + /** + * + * @param ordering {number} + * @returns {ColumnBuilder} + */ + ordering(ordering) { + this.column.ordering = ordering; + return this; + } - /** - * - * @param languageType {string} - * @param [countryCodes=undefined] {Array.} - * @returns {ColumnBuilder} - */ - }, { - key: "languageType", - value: function languageType(_languageType) { - var countryCodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - switch (_languageType) { - case "country": - if (!_.isEmpty(_languageType) && (!_.isArray(countryCodes) || _.isEmpty(countryCodes))) { - throw new Error("if languageType 'country' argument countryCodes can't be empty", this.column); - } - this.column.languageType = _languageType; - this.column.countryCodes = countryCodes; - break; - case "language": - case "neutral": - this.column.languageType = _languageType; - break; - default: - throw new Error("invalid languageType for column", this.column); - } - return this; + /** + * + * @param [multilanguage=true] {boolean} + * @returns {ColumnBuilder} + */ + multilanguage(multilanguage) { + if (multilanguage === true || typeof multilanguage === "undefined") { + this.languageType("language"); + } else { + this.languageType("neutral"); } - /** - * - * @param [identifier=true] {boolean} - * @returns {ColumnBuilder} - */ - }, { - key: "identifier", - value: function identifier(_identifier) { - this.column.identifier = typeof _identifier === "boolean" ? _identifier : true; - return this; + return this; + } + + /** + * + * @param languageType {string} + * @param [countryCodes=undefined] {Array.} + * @returns {ColumnBuilder} + */ + languageType(languageType, countryCodes = undefined) { + switch (languageType) { + case "country": + if (!_.isEmpty(languageType) && (!_.isArray(countryCodes) || _.isEmpty(countryCodes))) { + throw new Error("if languageType 'country' argument countryCodes can't be empty", this.column); + } + + this.column.languageType = languageType; + this.column.countryCodes = countryCodes; + break; + case "language": + case "neutral": + this.column.languageType = languageType; + break; + default: + throw new Error("invalid languageType for column", this.column); } - /** - * - * @param [separator=true] {boolean} - * @returns {ColumnBuilder} - */ - }, { - key: "separator", - value: function separator(_separator) { - this.column.separator = typeof _separator === "boolean" ? _separator : true; - return this; + return this; + } + + /** + * + * @param [identifier=true] {boolean} + * @returns {ColumnBuilder} + */ + identifier(identifier) { + this.column.identifier = (typeof identifier === "boolean" ? identifier : true); + return this; + } + + /** + * + * @param [separator=true] {boolean} + * @returns {ColumnBuilder} + */ + separator(separator) { + this.column.separator = (typeof separator === "boolean" ? separator : true); + return this; + } + + /** + * + * @param [hidden=true] {boolean} + * @returns {ColumnBuilder} + */ + hidden(hidden) { + this.column.hidden = (typeof hidden === "boolean" ? hidden : true); + return this; + } + + /** + * + * @param maxLength {number} + * @returns {ColumnBuilder} + */ + maxLength(length) { + this.column.maxLength = length; + return this; + } + + /** + * + * @param minLength {number} + * @returns {ColumnBuilder} + */ + minLength(length) { + this.column.minLength = length; + return this; + } + + /** + * + * @param decimalDigits {number} + * @returns {ColumnBuilder} + */ + decimalDigits(decimalDigits) { + if (this.column.kind !== "numeric") { + throw new Error("column " + this.column.name + " should be of type numeric to set 'decimalDigits(...)'"); } - /** - * - * @param [hidden=true] {boolean} - * @returns {ColumnBuilder} - */ - }, { - key: "hidden", - value: function hidden(_hidden2) { - this.column.hidden = typeof _hidden2 === "boolean" ? _hidden2 : true; - return this; + if (!_.isInteger(decimalDigits) || decimalDigits < 0) { + throw new Error("parameter 'decimalDigits' should be a positive integer number"); } - /** - * - * @param maxLength {number} - * @returns {ColumnBuilder} - */ - }, { - key: "maxLength", - value: function maxLength(length) { - this.column.maxLength = length; - return this; + this.column.decimalDigits = decimalDigits; + + return this; + } + + /** + * + * @param toTable {Table|number} + * @returns {ColumnBuilder} + */ + simpleLink(toTable) { + this.link(toTable).singleDirection(); + return this; + } + + /** + * + * @param toTable {Table|number} + * @returns {ColumnBuilder} + */ + link(toTable) { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'link(...)'"); } - /** - * - * @param minLength {number} - * @returns {ColumnBuilder} - */ - }, { - key: "minLength", - value: function minLength(length) { - this.column.minLength = length; - return this; + let tableId; + + if (typeof toTable === "object" && typeof toTable["tableId"] === "number") { + tableId = toTable.tableId; + } else if (typeof toTable === "number") { + tableId = toTable; + } else { + throw new Error("parameter 'toTable' should be an Table object or a number"); } - /** - * - * @param decimalDigits {number} - * @returns {ColumnBuilder} - */ - }, { - key: "decimalDigits", - value: function decimalDigits(_decimalDigits) { - if (this.column.kind !== "numeric") { - throw new Error("column " + this.column.name + " should be of type numeric to set 'decimalDigits(...)'"); - } - if (!_.isInteger(_decimalDigits) || _decimalDigits < 0) { - throw new Error("parameter 'decimalDigits' should be a positive integer number"); - } - this.column.decimalDigits = _decimalDigits; - return this; + this.column.toTable = tableId; + return this; + } + + /** + * + * @param groups {Array.} + * @returns {ColumnBuilder} + */ + groups(groups) { + if (this.column.kind !== "group") { + throw new Error("column " + this.column.name + " should be of type 'group' to set 'groups(...)'"); } - /** - * - * @param toTable {Table|number} - * @returns {ColumnBuilder} - */ - }, { - key: "simpleLink", - value: function simpleLink(toTable) { - this.link(toTable).singleDirection(); - return this; + if (!_.every(groups, _.isInteger)) { + throw new Error("every value of 'groups' parameter should be a positive integer number"); } - /** - * - * @param toTable {Table|number} - * @returns {ColumnBuilder} - */ - }, { - key: "link", - value: function link(toTable) { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'link(...)'"); - } - var tableId; - if (_typeof(toTable) === "object" && typeof toTable["tableId"] === "number") { - tableId = toTable.tableId; - } else if (typeof toTable === "number") { - tableId = toTable; - } else { - throw new Error("parameter 'toTable' should be an Table object or a number"); - } - this.column.toTable = tableId; - return this; + this.column.groups = groups; + + return this; + } + + /** + * + * @param showMemberColumns {boolean} + * @returns {ColumnBuilder} + */ + showMemberColumns(showMemberColumns) { + if (this.column.kind !== "group") { + throw new Error("column " + this.column.name + " should be of type 'group' to set 'showMemberColumns(...)'"); } - /** - * - * @param groups {Array.} - * @returns {ColumnBuilder} - */ - }, { - key: "groups", - value: function groups(_groups) { - if (this.column.kind !== "group") { - throw new Error("column " + this.column.name + " should be of type 'group' to set 'groups(...)'"); - } - if (!_.every(_groups, _.isInteger)) { - throw new Error("every value of 'groups' parameter should be a positive integer number"); - } - this.column.groups = _groups; - return this; + this.column.showMemberColumns = _.isBoolean(showMemberColumns) ? showMemberColumns : true; + + return this; + } + + /** + * + * @param formatPattern {string} + * @returns {ColumnBuilder} + */ + formatPattern(formatPattern) { + if (this.column.kind !== "group") { + throw new Error("column " + this.column.name + " should be of type 'group' to set 'groups(...)'"); } - /** - * - * @param showMemberColumns {boolean} - * @returns {ColumnBuilder} - */ - }, { - key: "showMemberColumns", - value: function showMemberColumns(_showMemberColumns) { - if (this.column.kind !== "group") { - throw new Error("column " + this.column.name + " should be of type 'group' to set 'showMemberColumns(...)'"); - } - this.column.showMemberColumns = _.isBoolean(_showMemberColumns) ? _showMemberColumns : true; - return this; + this.column.formatPattern = formatPattern; + + return this; + } + + /** + * + * @param toName {string} + * @returns {ColumnBuilder} + */ + toName(toName) { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'toName(...)'"); + } else if (typeof this.column.singleDirection !== "undefined") { + throw new Error("column " + this.column.name + " can't have 'toName(...)' and 'singleDirection()'"); } - /** - * - * @param formatPattern {string} - * @returns {ColumnBuilder} - */ - }, { - key: "formatPattern", - value: function formatPattern(_formatPattern) { - if (this.column.kind !== "group") { - throw new Error("column " + this.column.name + " should be of type 'group' to set 'groups(...)'"); - } - this.column.formatPattern = _formatPattern; - return this; + this.column.toName = toName; + return this; + } + + /** + * + * @param args {Array.} one multi-language object or langtag-value list + * @returns {ColumnBuilder} + */ + toDisplayName(...args) { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'toDisplayName(...)'"); + } else if (typeof this.column.singleDirection !== "undefined") { + throw new Error("column " + this.column.name + " can't have 'toDisplayName(...)' and 'singleDirection()'"); } - /** - * - * @param toName {string} - * @returns {ColumnBuilder} - */ - }, { - key: "toName", - value: function toName(_toName) { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'toName(...)'"); - } else if (typeof this.column.singleDirection !== "undefined") { - throw new Error("column " + this.column.name + " can't have 'toName(...)' and 'singleDirection()'"); - } - this.column.toName = _toName; - return this; + if (!this.column.toDisplayInfos) { + this.column.toDisplayInfos = {}; } - /** - * - * @param args {Array.} one multi-language object or langtag-value list - * @returns {ColumnBuilder} - */ - }, { - key: "toDisplayName", - value: function toDisplayName() { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'toDisplayName(...)'"); - } else if (typeof this.column.singleDirection !== "undefined") { - throw new Error("column " + this.column.name + " can't have 'toDisplayName(...)' and 'singleDirection()'"); - } - if (!this.column.toDisplayInfos) { - this.column.toDisplayInfos = {}; - } - for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - this.column.toDisplayInfos.displayName = argumentsToMultiLanguageObj(args); - return this; + this.column.toDisplayInfos.displayName = argumentsToMultiLanguageObj(args); + return this; + } + + /** + * + * @param args {Array.} one multi-language object or langtag-value list + * @returns {ColumnBuilder} + */ + toDescription(...args) { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'toDisplayName(...)'"); + } else if (typeof this.column.singleDirection !== "undefined") { + throw new Error("column " + this.column.name + " can't have 'toDisplayName(...)' and 'singleDirection()'"); } - /** - * - * @param args {Array.} one multi-language object or langtag-value list - * @returns {ColumnBuilder} - */ - }, { - key: "toDescription", - value: function toDescription() { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'toDisplayName(...)'"); - } else if (typeof this.column.singleDirection !== "undefined") { - throw new Error("column " + this.column.name + " can't have 'toDisplayName(...)' and 'singleDirection()'"); - } - if (!this.column.toDisplayInfos) { - this.column.toDisplayInfos = {}; - } - for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { - args[_key5] = arguments[_key5]; - } - this.column.toDisplayInfos.description = argumentsToMultiLanguageObj(args); - return this; + if (!this.column.toDisplayInfos) { + this.column.toDisplayInfos = {}; } - /** - * - * @param toOrdering {number|null} - * @returns {ColumnBuilder} - */ - }, { - key: "toOrdering", - value: function toOrdering(_toOrdering) { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'toOrdering(...)'"); - } else if (typeof this.column.singleDirection !== "undefined") { - throw new Error("column " + this.column.name + " can't have 'toOrdering(...)' and 'singleDirection()'"); - } else if (!_.isNumber(_toOrdering) && _toOrdering !== null) { - throw new Error("toOrdering needs to be called with a number or null", this.column); - } - this.column.toOrdering = _toOrdering; - return this; + this.column.toDisplayInfos.description = argumentsToMultiLanguageObj(args); + return this; + } + + /** + * + * @param toOrdering {number|null} + * @returns {ColumnBuilder} + */ + toOrdering(toOrdering) { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'toOrdering(...)'"); + } else if (typeof this.column.singleDirection !== "undefined") { + throw new Error("column " + this.column.name + " can't have 'toOrdering(...)' and 'singleDirection()'"); + } else if (!_.isNumber(toOrdering) && toOrdering !== null) { + throw new Error("toOrdering needs to be called with a number or null", this.column); } - /** - * - * @returns {ColumnBuilder} - */ - }, { - key: "singleDirection", - value: function singleDirection() { - if (this.column.kind !== "link") { - throw new Error("column " + this.column.name + " should be of type link to set 'singleDirection()'"); - } else if (typeof this.column.toName !== "undefined") { - throw new Error("column " + this.column.name + " can't have 'singleDirection()' and 'toName(...)'"); - } - this.column.singleDirection = true; - return this; + this.column.toOrdering = toOrdering; + + return this; + } + + /** + * + * @returns {ColumnBuilder} + */ + singleDirection() { + if (this.column.kind !== "link") { + throw new Error("column " + this.column.name + " should be of type link to set 'singleDirection()'"); + } else if (typeof this.column.toName !== "undefined") { + throw new Error("column " + this.column.name + " can't have 'singleDirection()' and 'toName(...)'"); } - }, { - key: "build", - value: function build() { - if (typeof this.column.name !== "string" || typeof this.column.kind !== "string") { - throw new Error("at least 'name' (" + this.column.name + ") and 'kind' (" + this.column.kind + ") must be defined"); - } - return this.column; + + this.column.singleDirection = true; + return this; + } + + build() { + if (typeof this.column.name !== "string" || typeof this.column.kind !== "string") { + throw new Error("at least 'name' (" + this.column.name + ") and 'kind' (" + this.column.kind + ") must be defined"); } - }]); - }(); + + return this.column; + } + } + /** * @typedef {{cardinality: {from: number, to: number}}} ConstraintCardinality */ + /** * @typedef {{deleteCascade: boolean}} ConstraintDeleteCascade */ + /** * @typedef {{archiveCascade: boolean}} ConstraintArchiveCascade */ + /** * @typedef {{finalCascade: boolean}} ConstraintFinalCascade */ + /** * */ - var ConstraintBuilder = /*#__PURE__*/function () { - function ConstraintBuilder() { - _classCallCheck(this, ConstraintBuilder); + class ConstraintBuilder { + /** + * + * @returns {ConstraintCardinality} + */ + static cardinalityOneToOne() { + return ConstraintBuilder.cardinality(1, 1); } - return _createClass(ConstraintBuilder, null, [{ - key: "cardinalityOneToOne", - value: - /** - * - * @returns {ConstraintCardinality} - */ - function cardinalityOneToOne() { - return ConstraintBuilder.cardinality(1, 1); - } - /** - * - * @returns {ConstraintCardinality} - */ - }, { - key: "cardinalityOneToMany", - value: function cardinalityOneToMany() { - return ConstraintBuilder.cardinality(1, 0); - } + /** + * + * @returns {ConstraintCardinality} + */ + static cardinalityOneToMany() { + return ConstraintBuilder.cardinality(1, 0); + } - /** - * - * @returns {ConstraintCardinality} - */ - }, { - key: "cardinalityManyToOne", - value: function cardinalityManyToOne() { - return ConstraintBuilder.cardinality(0, 1); - } + /** + * + * @returns {ConstraintCardinality} + */ + static cardinalityManyToOne() { + return ConstraintBuilder.cardinality(0, 1); + } - /** - * - * @param from {number} - * @param to {number} - * @returns {ConstraintCardinality} - */ - }, { - key: "cardinality", - value: function cardinality(from, to) { - return { - cardinality: { - from: from, - to: to - } - }; - } + /** + * + * @param from {number} + * @param to {number} + * @returns {ConstraintCardinality} + */ + static cardinality(from, to) { + return { + cardinality: { + from, + to + } + }; + } - /** - * - * @param deleteCascade {boolean} - * @returns {ConstraintDeleteCascade} - */ - }, { - key: "deleteCascade", - value: function deleteCascade(_deleteCascade) { - return { - deleteCascade: _.isBoolean(_deleteCascade) ? _deleteCascade : true - }; - } + /** + * + * @param deleteCascade {boolean} + * @returns {ConstraintDeleteCascade} + */ + static deleteCascade(deleteCascade) { + return { + deleteCascade: _.isBoolean(deleteCascade) ? deleteCascade : true + }; + } - /** - * - * @param archiveCascade {boolean} - * @returns {ConstraintArchiveCascade} - */ - }, { - key: "archiveCascade", - value: function archiveCascade(_archiveCascade) { - return { - archiveCascade: _.isBoolean(_archiveCascade) ? _archiveCascade : true - }; - } + /** + * + * @param archiveCascade {boolean} + * @returns {ConstraintArchiveCascade} + */ + static archiveCascade(archiveCascade) { + return { + archiveCascade: _.isBoolean(archiveCascade) ? archiveCascade : true + }; + } + + /** + * + * @param finalCascade {boolean} + * @returns {ConstraintFinalCascade} + */ + static finalCascade(finalCascade) { + return { + finalCascade: _.isBoolean(finalCascade) ? finalCascade : true + }; + } + } - /** - * - * @param finalCascade {boolean} - * @returns {ConstraintFinalCascade} - */ - }, { - key: "finalCascade", - value: function finalCascade(_finalCascade) { - return { - finalCascade: _.isBoolean(_finalCascade) ? _finalCascade : true - }; - } - }]); - }(); return { api: syncApi, asyncApi: asyncApi, + Table: Table, Tables: Tables, TableBuilder: TableBuilder, @@ -1098,4 +1042,5 @@ function grudStructorizer(baseUrl, options) { StaticHelpers: StaticHelpers }; } -module.exports = grudStructorizer; \ No newline at end of file + +export default grudStructorizer; diff --git a/package.json b/package.json index 843746e..4385fa2 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,16 @@ { "name": "grud-structorizer", - "version": "2.0.1", + "version": "3.0.0", "description": "Core library for building schemas", + "type": "module", "main": "lib/index.js", "types": "./lib/types.d.ts", "files": [ "lib/" ], "scripts": { - "compile": "babel --ignore '**/*.spec.js' -d ./lib ./src", - "prepublishOnly": "npm run compile -s && npm run lint -s && npm run test -s && npm run jsdoc -s && npm run jsdoc:ts -s", + "build": "cp -r src/* lib/ && rm lib/**/*.spec.js 2>/dev/null || true", + "prepublishOnly": "npm run build -s && npm run lint -s && npm run test -s && npm run jsdoc -s && npm run jsdoc:ts -s", "lint": "eslint ./src", "lint:fix": "npm run lint -- --fix", "test": "jest --testPathPattern='src'", diff --git a/src/Api.js b/src/Api.js index a83c4d7..3e5b50a 100644 --- a/src/Api.js +++ b/src/Api.js @@ -1,6 +1,4 @@ -"use strict"; - -const _ = require("lodash"); +import _ from "lodash"; /** * @typedef {object} ApiOptions @@ -34,4 +32,4 @@ class Api { } } -module.exports = Api; +export default Api; diff --git a/src/AsyncApi.js b/src/AsyncApi.js index d926d1b..41ef9eb 100644 --- a/src/AsyncApi.js +++ b/src/AsyncApi.js @@ -1,8 +1,4 @@ -"use strict"; - -const fetch = require("node-fetch"); - -const Api = require("./Api"); +import Api from "./Api.js"; /** * @@ -43,4 +39,4 @@ class AsyncApi extends Api { } } -module.exports = AsyncApi; +export default AsyncApi; diff --git a/src/SyncApi.js b/src/SyncApi.js index 40ac96d..ee5f435 100644 --- a/src/SyncApi.js +++ b/src/SyncApi.js @@ -1,8 +1,6 @@ -"use strict"; +import request from "sync-request"; -const request = require("sync-request"); - -const Api = require("./Api"); +import Api from "./Api.js"; /** * @@ -170,4 +168,4 @@ class SyncApi extends Api { } } -module.exports = SyncApi; +export default SyncApi; diff --git a/src/index.js b/src/index.js index f8d391a..29dbef5 100644 --- a/src/index.js +++ b/src/index.js @@ -1,9 +1,7 @@ -"use strict"; +import _ from "lodash"; -const _ = require("lodash"); - -const AsyncApi = require("./AsyncApi"); -const SyncApi = require("./SyncApi"); +import AsyncApi from "./AsyncApi.js"; +import SyncApi from "./SyncApi.js"; function argumentsToMultiLanguageObj(argsObj) { const args = _.toArray(argsObj); @@ -1045,4 +1043,4 @@ function grudStructorizer(baseUrl, options) { }; } -module.exports = grudStructorizer; +export default grudStructorizer; From 809e2b3b6c66066bd75ba876f402dec9fe8f1726 Mon Sep 17 00:00:00 2001 From: Manfred Zingl Date: Thu, 20 Nov 2025 16:26:47 +0100 Subject: [PATCH 02/22] refactor: - fix tests - remove babel, jest, node-fetch - add vitest --- .eslintrc.json | 330 +- docs/Api.html | 2 +- docs/Api.js.html | 6 +- docs/AsyncApi.html | 4 +- docs/AsyncApi.js.html | 8 +- docs/ColumnBuilder.html | 46 +- docs/ConstraintBuilder.html | 16 +- docs/SyncApi.html | 18 +- docs/SyncApi.js.html | 8 +- docs/Table.html | 26 +- docs/TableBuilder.html | 10 +- docs/Tables.html | 6 +- docs/global.html | 16 +- docs/index.js.html | 14 +- lib/index.js | 4 +- package-lock.json | 16836 ++++++-------------------- package.json | 17 +- src/__tests__/columnBuilder.spec.js | 4 +- src/__tests__/table.spec.js | 19 +- src/index.js | 4 +- vitest.config.js | 9 + 21 files changed, 4093 insertions(+), 13310 deletions(-) create mode 100644 vitest.config.js diff --git a/.eslintrc.json b/.eslintrc.json index e97a08c..0ff09c5 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,65 +1,130 @@ { "root": true, - "parser": "@babel/eslint-parser", - "parserOptions": { - "ecmaVersion": 7, - "ecmaFeatures": { - "experimentalObjectRestSpread": true, - "jsx": true - }, + "ecmaVersion": 2024, "sourceType": "module" }, - - "ignorePatterns": ["lib/*", "docs/*", "*.spec.js*"], - + "ignorePatterns": [ + "lib/*", + "docs/*", + "*.spec.js*" + ], "env": { "browser": true, - "es6": true, - "mocha": true, - "node": true, - "jest": true + "es2024": true, + "node": true }, - "plugins": [ - "promise", - "jest" + "promise" ], - "globals": { "document": false, "navigator": false, - "window": false, - "jest/globals": true + "window": false }, - "rules": { "accessor-pairs": "error", - "arrow-spacing": ["error", { "before": true, "after": true }], - "block-spacing": ["error", "always"], - "brace-style": ["error", "1tbs", { "allowSingleLine": true }], - "camelcase": ["warn", { "properties": "always" }], - "comma-dangle": ["error", "never"], - "comma-spacing": ["error", { "before": false, "after": true }], - "comma-style": ["error", "last"], + "arrow-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "block-spacing": [ + "error", + "always" + ], + "brace-style": [ + "error", + "1tbs", + { + "allowSingleLine": true + } + ], + "camelcase": [ + "warn", + { + "properties": "always" + } + ], + "comma-dangle": [ + "error", + "never" + ], + "comma-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "comma-style": [ + "error", + "last" + ], "constructor-super": "error", - "curly": ["error", "multi-line"], - "dot-location": ["error", "property"], + "curly": [ + "error", + "multi-line" + ], + "dot-location": [ + "error", + "property" + ], "eol-last": "error", - "eqeqeq": ["error", "allow-null"], - "func-call-spacing": ["error", "never"], - "handle-callback-err": ["error", "^(err|error)$" ], - "indent": ["error", 2, { "SwitchCase": 1 }], - "key-spacing": ["error", { "beforeColon": false, "afterColon": true }], - "keyword-spacing": ["error", { "before": true, "after": true }], - "new-cap": ["error", { "newIsCap": true, "capIsNew": false }], + "eqeqeq": [ + "error", + "allow-null" + ], + "func-call-spacing": [ + "error", + "never" + ], + "handle-callback-err": [ + "error", + "^(err|error)$" + ], + "indent": [ + "error", + 2, + { + "SwitchCase": 1 + } + ], + "key-spacing": [ + "error", + { + "beforeColon": false, + "afterColon": true + } + ], + "keyword-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "new-cap": [ + "error", + { + "newIsCap": true, + "capIsNew": false + } + ], "new-parens": "error", "no-array-constructor": "error", "no-caller": "error", "no-class-assign": "error", "no-cond-assign": "error", "no-const-assign": "error", - "no-constant-condition": ["error", { "checkLoops": false }], + "no-constant-condition": [ + "error", + { + "checkLoops": false + } + ], "no-control-regex": "error", "no-debugger": "error", "no-delete-var": "error", @@ -75,23 +140,40 @@ "no-extend-native": "error", "no-extra-bind": "error", "no-extra-boolean-cast": "error", - "no-extra-parens": ["error", "functions"], + "no-extra-parens": [ + "error", + "functions" + ], "no-fallthrough": "error", "no-floating-decimal": "error", "no-func-assign": "error", "no-global-assign": "error", "no-implied-eval": "error", - "no-inner-declarations": ["error", "functions"], + "no-inner-declarations": [ + "error", + "functions" + ], "no-invalid-regexp": "error", "no-irregular-whitespace": "error", "no-iterator": "error", "no-label-var": "error", - "no-labels": ["error", { "allowLoop": false, "allowSwitch": false }], + "no-labels": [ + "error", + { + "allowLoop": false, + "allowSwitch": false + } + ], "no-lone-blocks": "error", "no-mixed-spaces-and-tabs": "error", "no-multi-spaces": "error", "no-multi-str": "error", - "no-multiple-empty-lines": ["error", { "max": 1 }], + "no-multiple-empty-lines": [ + "error", + { + "max": 1 + } + ], "no-native-reassign": "error", "no-negated-in-lhs": "error", "no-new": "error", @@ -107,7 +189,10 @@ "no-proto": "error", "no-redeclare": "error", "no-regex-spaces": "error", - "no-return-assign": ["error", "except-parens"], + "no-return-assign": [ + "error", + "except-parens" + ], "no-self-assign": "error", "no-self-compare": "error", "no-sequences": "error", @@ -122,11 +207,22 @@ "no-undef-init": "error", "no-unexpected-multiline": "error", "no-unmodified-loop-condition": "error", - "no-unneeded-ternary": ["error", { "defaultAssignment": false }], + "no-unneeded-ternary": [ + "error", + { + "defaultAssignment": false + } + ], "no-unreachable": "error", "no-unsafe-finally": "error", "no-unsafe-negation": "error", - "no-unused-vars": ["warn", { "vars": "all", "args": "none" }], + "no-unused-vars": [ + "warn", + { + "vars": "all", + "args": "none" + } + ], "no-useless-call": "error", "no-useless-computed-key": "error", "no-useless-constructor": "error", @@ -134,33 +230,125 @@ "no-useless-rename": "error", "no-whitespace-before-property": "error", "no-with": "error", - "object-property-newline": ["error", { "allowMultiplePropertiesPerLine": true }], - "one-var": ["error", { "initialized": "never" }], - "operator-linebreak": ["error", "after", { "overrides": { "?": "before", ":": "before", "||": "before", "&&": "before" } }], - "quotes": ["error", "double", { "avoidEscape": true, "allowTemplateLiterals": true }], - "rest-spread-spacing": ["error", "never"], - "semi": ["error", "always"], - "semi-spacing": ["error", { "before": false, "after": true }], - "space-before-blocks": ["error", "always"], - "space-before-function-paren": ["warn", {"anonymous": "always", "named": "never"}], - "space-in-parens": ["error", "never"], + "object-property-newline": [ + "error", + { + "allowMultiplePropertiesPerLine": true + } + ], + "one-var": [ + "error", + { + "initialized": "never" + } + ], + "operator-linebreak": [ + "error", + "after", + { + "overrides": { + "?": "before", + ":": "before", + "||": "before", + "&&": "before" + } + } + ], + "quotes": [ + "error", + "double", + { + "avoidEscape": true, + "allowTemplateLiterals": true + } + ], + "rest-spread-spacing": [ + "error", + "never" + ], + "semi": [ + "error", + "always" + ], + "semi-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "space-before-blocks": [ + "error", + "always" + ], + "space-before-function-paren": [ + "warn", + { + "anonymous": "always", + "named": "never" + } + ], + "space-in-parens": [ + "error", + "never" + ], "space-infix-ops": "error", - "space-unary-ops": ["error", { "words": true, "nonwords": false }], - "spaced-comment": ["warn", "always", { "line": { "markers": ["*package", "!", ","] }, "block": { "balanced": true, "markers": ["*package", "!", ","], "exceptions": ["*"] } }], - "template-curly-spacing": ["error", "never"], - "unicode-bom": ["error", "never"], + "space-unary-ops": [ + "error", + { + "words": true, + "nonwords": false + } + ], + "spaced-comment": [ + "warn", + "always", + { + "line": { + "markers": [ + "*package", + "!", + "," + ] + }, + "block": { + "balanced": true, + "markers": [ + "*package", + "!", + "," + ], + "exceptions": [ + "*" + ] + } + } + ], + "template-curly-spacing": [ + "error", + "never" + ], + "unicode-bom": [ + "error", + "never" + ], "use-isnan": "error", "valid-typeof": "error", - "wrap-iife": ["error", "any", { "functionPrototypeMethods": true }], - "yield-star-spacing": ["error", "both"], - "yoda": ["error", "never"], - - "promise/param-names": "error", - - "jest/no-disabled-tests": "warn", - "jest/no-focused-tests": "error", - "jest/no-identical-title": "error", - "jest/prefer-to-have-length": "warn", - "jest/valid-expect": "error" + "wrap-iife": [ + "error", + "any", + { + "functionPrototypeMethods": true + } + ], + "yield-star-spacing": [ + "error", + "both" + ], + "yoda": [ + "error", + "never" + ], + "promise/param-names": "error" } -} \ No newline at end of file +} diff --git a/docs/Api.html b/docs/Api.html index 359540b..091055a 100644 --- a/docs/Api.html +++ b/docs/Api.html @@ -77,7 +77,7 @@

new ApiSource:
diff --git a/docs/Api.js.html b/docs/Api.js.html index c020d3a..74811c1 100644 --- a/docs/Api.js.html +++ b/docs/Api.js.html @@ -45,9 +45,7 @@

Api.js

-
"use strict";
-
-const _ = require("lodash");
+            
import _ from "lodash";
 
 /**
  * @typedef {object} ApiOptions
@@ -81,7 +79,7 @@ 

Api.js

} } -module.exports = Api; +export default Api;
diff --git a/docs/AsyncApi.html b/docs/AsyncApi.html index fb956ee..15d79bc 100644 --- a/docs/AsyncApi.html +++ b/docs/AsyncApi.html @@ -77,7 +77,7 @@

new AsyncApi<
Source:
@@ -254,7 +254,7 @@

(
Source:
diff --git a/docs/AsyncApi.js.html b/docs/AsyncApi.js.html index c32fc38..31499ef 100644 --- a/docs/AsyncApi.js.html +++ b/docs/AsyncApi.js.html @@ -45,11 +45,7 @@

AsyncApi.js

-
"use strict";
-
-const fetch = require("node-fetch");
-
-const Api = require("./Api");
+            
import Api from "./Api.js";
 
 /**
  *
@@ -90,7 +86,7 @@ 

AsyncApi.js

} } -module.exports = AsyncApi; +export default AsyncApi;
diff --git a/docs/ColumnBuilder.html b/docs/ColumnBuilder.html index a58e7a5..3b7b918 100644 --- a/docs/ColumnBuilder.html +++ b/docs/ColumnBuilder.html @@ -77,7 +77,7 @@

new Colu
Source:
@@ -254,7 +254,7 @@

addConst
Source:
@@ -408,7 +408,7 @@

decimalD
Source:
@@ -559,7 +559,7 @@

descriptio
Source:
@@ -722,7 +722,7 @@

displayNam
Source:
@@ -885,7 +885,7 @@

formatPa
Source:
@@ -1036,7 +1036,7 @@

groupsSource:
@@ -1187,7 +1187,7 @@

hiddenSource:
@@ -1358,7 +1358,7 @@

identifier<
Source:
@@ -1529,7 +1529,7 @@

languageT
Source:
@@ -1724,7 +1724,7 @@