set up common to use babel, static file serving middleware
This commit is contained in:
parent
8c922f5d08
commit
65fd38e205
File diff suppressed because one or more lines are too long
|
@ -1,4 +1,3 @@
|
||||||
//
|
|
||||||
import { filter, cloneDeep, last, concat, isEmpty, values } from "lodash/fp"
|
import { filter, cloneDeep, last, concat, isEmpty, values } from "lodash/fp"
|
||||||
import { pipe, getNode, constructHierarchy } from "components/common/core"
|
import { pipe, getNode, constructHierarchy } from "components/common/core"
|
||||||
import * as backendStoreActions from "./backend"
|
import * as backendStoreActions from "./backend"
|
||||||
|
@ -392,13 +391,11 @@ const addComponentLibrary = store => async lib => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeComponentLibrary = store => lib => {
|
const removeComponentLibrary = store => lib => {
|
||||||
store.update(s => {
|
store.update(state => {
|
||||||
s.pages.componentLibraries = filter(l => l !== lib)(
|
state.pages.componentLibraries = state.pages.componentLibraries.filter(l => l !== lib);
|
||||||
s.pages.componentLibraries
|
_savePage(state);
|
||||||
)
|
|
||||||
_savePage(s)
|
|
||||||
|
|
||||||
return s
|
return state;
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -411,10 +408,10 @@ const addStylesheet = store => stylesheet => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeStylesheet = store => stylesheet => {
|
const removeStylesheet = store => stylesheet => {
|
||||||
store.update(s => {
|
store.update(state => {
|
||||||
s.pages.stylesheets = filter(s => s !== stylesheet)(s.pages.stylesheets)
|
state.pages.stylesheets = s.pages.stylesheets.filter(s => s !== stylesheet)
|
||||||
_savePage(s)
|
_savePage(state)
|
||||||
return s
|
return state
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,129 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.apiWrapperSync = exports.apiWrapper = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _fp = require("lodash/fp");
|
||||||
|
var _shortid = require("shortid");
|
||||||
|
var _errors = require("./errors");
|
||||||
|
|
||||||
|
var apiWrapper = /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(
|
||||||
|
app,
|
||||||
|
eventNamespace,
|
||||||
|
isAuthorized,
|
||||||
|
eventContext,
|
||||||
|
func) {var startDate,elapsed,_len,params,_key,result,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
|
||||||
|
|
||||||
|
|
||||||
|
pushCallStack(app, eventNamespace);if (
|
||||||
|
|
||||||
|
isAuthorized(app)) {_context.next = 4;break;}
|
||||||
|
handleNotAuthorized(app, eventContext, eventNamespace);return _context.abrupt("return");case 4:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
startDate = Date.now();
|
||||||
|
elapsed = function elapsed() {return Date.now() - startDate;};_context.prev = 6;_context.next = 9;return (
|
||||||
|
|
||||||
|
|
||||||
|
app.publish(eventNamespace.onBegin, eventContext));case 9:for (_len = _args.length, params = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {params[_key - 5] = _args[_key];}_context.next = 12;return (
|
||||||
|
|
||||||
|
func.apply(void 0, params));case 12:result = _context.sent;_context.next = 15;return (
|
||||||
|
|
||||||
|
publishComplete(app, eventContext, eventNamespace, elapsed, result));case 15:return _context.abrupt("return",
|
||||||
|
result);case 18:_context.prev = 18;_context.t0 = _context["catch"](6);_context.next = 22;return (
|
||||||
|
|
||||||
|
publishError(app, eventContext, eventNamespace, elapsed, _context.t0));case 22:throw _context.t0;case 23:case "end":return _context.stop();}}}, _callee, null, [[6, 18]]);}));return function apiWrapper(_x, _x2, _x3, _x4, _x5) {return _ref.apply(this, arguments);};}();exports.apiWrapper = apiWrapper;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var apiWrapperSync = function apiWrapperSync(
|
||||||
|
app,
|
||||||
|
eventNamespace,
|
||||||
|
isAuthorized,
|
||||||
|
eventContext,
|
||||||
|
func)
|
||||||
|
|
||||||
|
{
|
||||||
|
pushCallStack(app, eventNamespace);
|
||||||
|
|
||||||
|
if (!isAuthorized(app)) {
|
||||||
|
handleNotAuthorized(app, eventContext, eventNamespace);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var startDate = Date.now();
|
||||||
|
var elapsed = function elapsed() {return Date.now() - startDate;};
|
||||||
|
|
||||||
|
try {
|
||||||
|
app.publish(eventNamespace.onBegin, eventContext);for (var _len2 = arguments.length, params = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {params[_key2 - 5] = arguments[_key2];}
|
||||||
|
|
||||||
|
var result = func.apply(void 0, params);
|
||||||
|
|
||||||
|
publishComplete(app, eventContext, eventNamespace, elapsed, result);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
publishError(app, eventContext, eventNamespace, elapsed, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};exports.apiWrapperSync = apiWrapperSync;
|
||||||
|
|
||||||
|
var handleNotAuthorized = function handleNotAuthorized(app, eventContext, eventNamespace) {
|
||||||
|
var err = new _errors.UnauthorisedError("Unauthorized: ".concat(eventNamespace));
|
||||||
|
publishError(app, eventContext, eventNamespace, function () {return 0;}, err);
|
||||||
|
throw err;
|
||||||
|
};
|
||||||
|
|
||||||
|
var pushCallStack = function pushCallStack(app, eventNamespace, seedCallId) {
|
||||||
|
var callId = (0, _shortid.generate)();
|
||||||
|
|
||||||
|
var createCallStack = function createCallStack() {return {
|
||||||
|
seedCallId: !(0, _fp.isUndefined)(seedCallId) ? seedCallId : callId,
|
||||||
|
threadCallId: callId,
|
||||||
|
stack: [] };};
|
||||||
|
|
||||||
|
|
||||||
|
if ((0, _fp.isUndefined)(app.calls)) {
|
||||||
|
app.calls = createCallStack();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.calls.stack.push({
|
||||||
|
namespace: eventNamespace,
|
||||||
|
callId: callId });
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
var popCallStack = function popCallStack(app) {
|
||||||
|
app.calls.stack.pop();
|
||||||
|
if (app.calls.stack.length === 0) {
|
||||||
|
delete app.calls;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var publishError = /*#__PURE__*/function () {var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(
|
||||||
|
app,
|
||||||
|
eventContext,
|
||||||
|
eventNamespace,
|
||||||
|
elapsed,
|
||||||
|
err) {var ctx;return _regenerator["default"].wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
|
||||||
|
|
||||||
|
ctx = (0, _fp.cloneDeep)(eventContext);
|
||||||
|
ctx.error = err;
|
||||||
|
ctx.elapsed = elapsed();_context2.next = 5;return (
|
||||||
|
app.publish(eventNamespace.onError, ctx));case 5:
|
||||||
|
popCallStack(app);case 6:case "end":return _context2.stop();}}}, _callee2);}));return function publishError(_x6, _x7, _x8, _x9, _x10) {return _ref2.apply(this, arguments);};}();
|
||||||
|
|
||||||
|
|
||||||
|
var publishComplete = /*#__PURE__*/function () {var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(
|
||||||
|
app,
|
||||||
|
eventContext,
|
||||||
|
eventNamespace,
|
||||||
|
elapsed,
|
||||||
|
result) {var endcontext;return _regenerator["default"].wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
|
||||||
|
|
||||||
|
endcontext = (0, _fp.cloneDeep)(eventContext);
|
||||||
|
endcontext.result = result;
|
||||||
|
endcontext.elapsed = elapsed();_context3.next = 5;return (
|
||||||
|
app.publish(eventNamespace.onComplete, endcontext));case 5:
|
||||||
|
popCallStack(app);return _context3.abrupt("return",
|
||||||
|
result);case 7:case "end":return _context3.stop();}}}, _callee3);}));return function publishComplete(_x11, _x12, _x13, _x14, _x15) {return _ref3.apply(this, arguments);};}();var _default =
|
||||||
|
|
||||||
|
|
||||||
|
apiWrapper;exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=apiWrapper.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,27 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.compileCode = void 0;var _compilerUtil = require("@nx-js/compiler-util");
|
||||||
|
var _fp = require("lodash/fp");
|
||||||
|
|
||||||
|
var compileCode = function compileCode(code) {
|
||||||
|
var func;
|
||||||
|
var safeCode;
|
||||||
|
|
||||||
|
if ((0, _fp.includes)("return ")(code)) {
|
||||||
|
safeCode = code;
|
||||||
|
} else {
|
||||||
|
var trimmed = code.trim();
|
||||||
|
trimmed = trimmed.endsWith(";") ?
|
||||||
|
trimmed.substring(0, trimmed.length - 1) :
|
||||||
|
trimmed;
|
||||||
|
safeCode = "return (".concat(trimmed, ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
func = (0, _compilerUtil.compileCode)(safeCode);
|
||||||
|
} catch (e) {
|
||||||
|
e.message = "Error compiling code : ".concat(code, " : ").concat(e.message);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return func;
|
||||||
|
};exports.compileCode = compileCode;
|
||||||
|
//# sourceMappingURL=compileCode.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/common/compileCode.js"],"names":["compileCode","code","func","safeCode","trimmed","trim","endsWith","substring","length","e","message"],"mappings":"wGAAA;AACA;;AAEO,IAAMA,WAAW,GAAG,SAAdA,WAAc,CAAAC,IAAI,EAAI;AACjC,MAAIC,IAAJ;AACA,MAAIC,QAAJ;;AAEA,MAAI,kBAAS,SAAT,EAAoBF,IAApB,CAAJ,EAA+B;AAC7BE,IAAAA,QAAQ,GAAGF,IAAX;AACD,GAFD,MAEO;AACL,QAAIG,OAAO,GAAGH,IAAI,CAACI,IAAL,EAAd;AACAD,IAAAA,OAAO,GAAGA,OAAO,CAACE,QAAR,CAAiB,GAAjB;AACNF,IAAAA,OAAO,CAACG,SAAR,CAAkB,CAAlB,EAAqBH,OAAO,CAACI,MAAR,GAAiB,CAAtC,CADM;AAENJ,IAAAA,OAFJ;AAGAD,IAAAA,QAAQ,qBAAcC,OAAd,MAAR;AACD;;AAED,MAAI;AACFF,IAAAA,IAAI,GAAG,+BAAMC,QAAN,CAAP;AACD,GAFD,CAEE,OAAOM,CAAP,EAAU;AACVA,IAAAA,CAAC,CAACC,OAAF,oCAAsCT,IAAtC,gBAAgDQ,CAAC,CAACC,OAAlD;AACA,UAAMD,CAAN;AACD;;AAED,SAAOP,IAAP;AACD,CAtBM,C","sourcesContent":["import { compileCode as cCode } from \"@nx-js/compiler-util\"\nimport { includes } from \"lodash/fp\"\n\nexport const compileCode = code => {\n let func\n let safeCode\n\n if (includes(\"return \")(code)) {\n safeCode = code\n } else {\n let trimmed = code.trim()\n trimmed = trimmed.endsWith(\";\")\n ? trimmed.substring(0, trimmed.length - 1)\n : trimmed\n safeCode = `return (${trimmed})`\n }\n\n try {\n func = cCode(safeCode)\n } catch (e) {\n e.message = `Error compiling code : ${code} : ${e.message}`\n throw e\n }\n\n return func\n}\n"],"file":"compileCode.js"}
|
|
@ -0,0 +1,34 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorisedError = exports.BadRequestError = void 0;var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));function _createSuper(Derived) {return function () {var Super = (0, _getPrototypeOf2["default"])(Derived),result;if (_isNativeReflectConstruct()) {var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor;result = Reflect.construct(Super, arguments, NewTarget);} else {result = Super.apply(this, arguments);}return (0, _possibleConstructorReturn2["default"])(this, result);};}function _isNativeReflectConstruct() {if (typeof Reflect === "undefined" || !Reflect.construct) return false;if (Reflect.construct.sham) return false;if (typeof Proxy === "function") return true;try {Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));return true;} catch (e) {return false;}}var BadRequestError = /*#__PURE__*/function (_Error) {(0, _inherits2["default"])(BadRequestError, _Error);var _super = _createSuper(BadRequestError);
|
||||||
|
function BadRequestError(message) {var _this;(0, _classCallCheck2["default"])(this, BadRequestError);
|
||||||
|
_this = _super.call(this, message);
|
||||||
|
_this.httpStatusCode = 400;return _this;
|
||||||
|
}return BadRequestError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.BadRequestError = BadRequestError;var
|
||||||
|
|
||||||
|
|
||||||
|
UnauthorisedError = /*#__PURE__*/function (_Error2) {(0, _inherits2["default"])(UnauthorisedError, _Error2);var _super2 = _createSuper(UnauthorisedError);
|
||||||
|
function UnauthorisedError(message) {var _this2;(0, _classCallCheck2["default"])(this, UnauthorisedError);
|
||||||
|
_this2 = _super2.call(this, message);
|
||||||
|
_this2.httpStatusCode = 401;return _this2;
|
||||||
|
}return UnauthorisedError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.UnauthorisedError = UnauthorisedError;var
|
||||||
|
|
||||||
|
|
||||||
|
ForbiddenError = /*#__PURE__*/function (_Error3) {(0, _inherits2["default"])(ForbiddenError, _Error3);var _super3 = _createSuper(ForbiddenError);
|
||||||
|
function ForbiddenError(message) {var _this3;(0, _classCallCheck2["default"])(this, ForbiddenError);
|
||||||
|
_this3 = _super3.call(this, message);
|
||||||
|
_this3.httpStatusCode = 403;return _this3;
|
||||||
|
}return ForbiddenError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.ForbiddenError = ForbiddenError;var
|
||||||
|
|
||||||
|
|
||||||
|
NotFoundError = /*#__PURE__*/function (_Error4) {(0, _inherits2["default"])(NotFoundError, _Error4);var _super4 = _createSuper(NotFoundError);
|
||||||
|
function NotFoundError(message) {var _this4;(0, _classCallCheck2["default"])(this, NotFoundError);
|
||||||
|
_this4 = _super4.call(this, message);
|
||||||
|
_this4.httpStatusCode = 404;return _this4;
|
||||||
|
}return NotFoundError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.NotFoundError = NotFoundError;var
|
||||||
|
|
||||||
|
|
||||||
|
ConflictError = /*#__PURE__*/function (_Error5) {(0, _inherits2["default"])(ConflictError, _Error5);var _super5 = _createSuper(ConflictError);
|
||||||
|
function ConflictError(message) {var _this5;(0, _classCallCheck2["default"])(this, ConflictError);
|
||||||
|
_this5 = _super5.call(this, message);
|
||||||
|
_this5.httpStatusCode = 409;return _this5;
|
||||||
|
}return ConflictError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.ConflictError = ConflictError;
|
||||||
|
//# sourceMappingURL=errors.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/common/errors.js"],"names":["BadRequestError","message","httpStatusCode","Error","UnauthorisedError","ForbiddenError","NotFoundError","ConflictError"],"mappings":"i9CAAaA,e;AACX,2BAAYC,OAAZ,EAAqB;AACnB,8BAAMA,OAAN;AACA,UAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,yEAJkCC,K;;;AAOxBC,iB;AACX,6BAAYH,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,2EAJoCC,K;;;AAO1BE,c;AACX,0BAAYJ,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,wEAJiCC,K;;;AAOvBG,a;AACX,yBAAYL,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K;;;AAOtBI,a;AACX,yBAAYN,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K","sourcesContent":["export class BadRequestError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 400\n }\n}\n\nexport class UnauthorisedError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 401\n }\n}\n\nexport class ForbiddenError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 403\n }\n}\n\nexport class NotFoundError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 404\n }\n}\n\nexport class ConflictError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 409\n }\n}\n"],"file":"errors.js"}
|
|
@ -0,0 +1,28 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.createEventAggregator = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _fp = require("lodash/fp");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
var publish = function publish(handlers) {return /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(eventName) {var context,_iterator,_step,handler,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:context = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};if (
|
||||||
|
(0, _fp.has)(eventName)(handlers)) {_context.next = 3;break;}return _context.abrupt("return");case 3:_iterator = _createForOfIteratorHelper(
|
||||||
|
|
||||||
|
handlers[eventName]);_context.prev = 4;_iterator.s();case 6:if ((_step = _iterator.n()).done) {_context.next = 12;break;}handler = _step.value;_context.next = 10;return (
|
||||||
|
handler(eventName, context));case 10:_context.next = 6;break;case 12:_context.next = 17;break;case 14:_context.prev = 14;_context.t0 = _context["catch"](4);_iterator.e(_context.t0);case 17:_context.prev = 17;_iterator.f();return _context.finish(17);case 20:case "end":return _context.stop();}}}, _callee, null, [[4, 14, 17, 20]]);}));return function (_x) {return _ref.apply(this, arguments);};}();};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var subscribe = function subscribe(handlers) {return function (eventName, handler) {
|
||||||
|
if (!(0, _fp.has)(eventName)(handlers)) {
|
||||||
|
handlers[eventName] = [];
|
||||||
|
}
|
||||||
|
handlers[eventName].push(handler);
|
||||||
|
};};
|
||||||
|
|
||||||
|
var createEventAggregator = function createEventAggregator() {
|
||||||
|
var handlers = {};
|
||||||
|
var eventAggregator = {
|
||||||
|
publish: publish(handlers),
|
||||||
|
subscribe: subscribe(handlers) };
|
||||||
|
|
||||||
|
return eventAggregator;
|
||||||
|
};exports.createEventAggregator = createEventAggregator;var _default =
|
||||||
|
|
||||||
|
createEventAggregator;exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=eventAggregator.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/common/eventAggregator.js"],"names":["publish","handlers","eventName","context","handler","subscribe","push","createEventAggregator","eventAggregator"],"mappings":"iZAAA,+B;;AAEA,IAAMA,OAAO,GAAG,SAAVA,OAAU,CAAAC,QAAQ,6HAAI,iBAAOC,SAAP,oLAAkBC,OAAlB,2DAA4B,EAA5B;AACrB,2BAAID,SAAJ,EAAeD,QAAf,CADqB;;AAGJA,cAAAA,QAAQ,CAACC,SAAD,CAHJ,sGAGfE,OAHe;AAIlBA,gBAAAA,OAAO,CAACF,SAAD,EAAYC,OAAZ,CAJW,gTAAJ,mEAAxB;;;;AAQA,IAAME,SAAS,GAAG,SAAZA,SAAY,CAAAJ,QAAQ,UAAI,UAACC,SAAD,EAAYE,OAAZ,EAAwB;AACpD,QAAI,CAAC,aAAIF,SAAJ,EAAeD,QAAf,CAAL,EAA+B;AAC7BA,MAAAA,QAAQ,CAACC,SAAD,CAAR,GAAsB,EAAtB;AACD;AACDD,IAAAA,QAAQ,CAACC,SAAD,CAAR,CAAoBI,IAApB,CAAyBF,OAAzB;AACD,GALyB,EAA1B;;AAOO,IAAMG,qBAAqB,GAAG,SAAxBA,qBAAwB,GAAM;AACzC,MAAMN,QAAQ,GAAG,EAAjB;AACA,MAAMO,eAAe,GAAG;AACtBR,IAAAA,OAAO,EAAEA,OAAO,CAACC,QAAD,CADM;AAEtBI,IAAAA,SAAS,EAAEA,SAAS,CAACJ,QAAD,CAFE,EAAxB;;AAIA,SAAOO,eAAP;AACD,CAPM,C;;AASQD,qB","sourcesContent":["import { has } from \"lodash/fp\"\n\nconst publish = handlers => async (eventName, context = {}) => {\n if (!has(eventName)(handlers)) return\n\n for (const handler of handlers[eventName]) {\n await handler(eventName, context)\n }\n}\n\nconst subscribe = handlers => (eventName, handler) => {\n if (!has(eventName)(handlers)) {\n handlers[eventName] = []\n }\n handlers[eventName].push(handler)\n}\n\nexport const createEventAggregator = () => {\n const handlers = {}\n const eventAggregator = {\n publish: publish(handlers),\n subscribe: subscribe(handlers),\n }\n return eventAggregator\n}\n\nexport default createEventAggregator\n"],"file":"eventAggregator.js"}
|
|
@ -0,0 +1,86 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.eventsList = exports.events = void 0;var _fp = require("lodash/fp");
|
||||||
|
|
||||||
|
var commonPlus = function commonPlus(extra) {return (0, _fp.union)(["onBegin", "onComplete", "onError"])(extra);};
|
||||||
|
|
||||||
|
var common = function common() {return commonPlus([]);};
|
||||||
|
|
||||||
|
var _events = {
|
||||||
|
recordApi: {
|
||||||
|
save: commonPlus(["onInvalid", "onRecordUpdated", "onRecordCreated"]),
|
||||||
|
"delete": common(),
|
||||||
|
getContext: common(),
|
||||||
|
getNew: common(),
|
||||||
|
load: common(),
|
||||||
|
validate: common(),
|
||||||
|
uploadFile: common(),
|
||||||
|
downloadFile: common() },
|
||||||
|
|
||||||
|
indexApi: {
|
||||||
|
buildIndex: common(),
|
||||||
|
listItems: common(),
|
||||||
|
"delete": common(),
|
||||||
|
aggregates: common() },
|
||||||
|
|
||||||
|
collectionApi: {
|
||||||
|
getAllowedRecordTypes: common(),
|
||||||
|
initialise: common(),
|
||||||
|
"delete": common() },
|
||||||
|
|
||||||
|
authApi: {
|
||||||
|
authenticate: common(),
|
||||||
|
authenticateTemporaryAccess: common(),
|
||||||
|
createTemporaryAccess: common(),
|
||||||
|
createUser: common(),
|
||||||
|
enableUser: common(),
|
||||||
|
disableUser: common(),
|
||||||
|
loadAccessLevels: common(),
|
||||||
|
getNewAccessLevel: common(),
|
||||||
|
getNewUser: common(),
|
||||||
|
getNewUserAuth: common(),
|
||||||
|
getUsers: common(),
|
||||||
|
saveAccessLevels: common(),
|
||||||
|
isAuthorized: common(),
|
||||||
|
changeMyPassword: common(),
|
||||||
|
setPasswordFromTemporaryCode: common(),
|
||||||
|
scorePassword: common(),
|
||||||
|
isValidPassword: common(),
|
||||||
|
validateUser: common(),
|
||||||
|
validateAccessLevels: common(),
|
||||||
|
setUserAccessLevels: common() },
|
||||||
|
|
||||||
|
templateApi: {
|
||||||
|
saveApplicationHierarchy: common(),
|
||||||
|
saveActionsAndTriggers: common() },
|
||||||
|
|
||||||
|
actionsApi: {
|
||||||
|
execute: common() } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _eventsList = [];
|
||||||
|
|
||||||
|
var makeEvent = function makeEvent(area, method, name) {return "".concat(area, ":").concat(method, ":").concat(name);};var _loop = function _loop(
|
||||||
|
|
||||||
|
areaKey) {var _loop2 = function _loop2(
|
||||||
|
_methodKey) {
|
||||||
|
_events[areaKey][_methodKey] = (0, _fp.reduce)(function (obj, s) {
|
||||||
|
obj[s] = makeEvent(areaKey, _methodKey, s);
|
||||||
|
return obj;
|
||||||
|
}, {})(_events[areaKey][_methodKey]);};for (var _methodKey in _events[areaKey]) {_loop2(_methodKey);
|
||||||
|
}};for (var areaKey in _events) {_loop(areaKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var _areaKey in _events) {
|
||||||
|
for (var methodKey in _events[_areaKey]) {
|
||||||
|
for (var name in _events[_areaKey][methodKey]) {
|
||||||
|
_eventsList.push(_events[_areaKey][methodKey][name]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var events = _events;exports.events = events;
|
||||||
|
|
||||||
|
var eventsList = _eventsList;exports.eventsList = eventsList;var _default =
|
||||||
|
|
||||||
|
{ events: _events, eventsList: _eventsList };exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=events.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,307 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "events", { enumerable: true, get: function get() {return _events.events;} });exports["default"] = exports.retry = exports.pause = exports.pushAll = exports.isArrayOfString = exports.toNumberOrNull = exports.toBoolOrNull = exports.toDateOrNull = exports.isSafeInteger = exports.awEx = exports.getHashCode = exports.contains = exports.StartsWith = exports.memberMatches = exports.defaultCase = exports.isOneOf = exports.isValue = exports.switchCase = exports.handleErrorWithUndefined = exports.handleErrorWith = exports.executesWithoutException = exports.causesException = exports.tryAwaitOrIgnore = exports.tryOrIgnore = exports.defineError = exports.tryAwaitOr = exports.tryOr = exports.isNonEmptyString = exports.isNonEmptyArray = exports.isAsync = exports.isNotEmpty = exports.all = exports.none = exports.mapIfSomethingOrBlank = exports.mapIfSomethingOrDefault = exports.somethingOrDefault = exports.somethingOrGetDefault = exports.isNothingOrEmpty = exports.isNothing = exports.isSomething = exports.insensitiveEquals = exports.anyTrue = exports.allTrue = exports.isNotNaN = exports.isNonNull = exports.isDefined = exports.not = exports.getOrDefault = exports.ifExists = exports.getIndexKeyFromFileKey = exports.dirIndex = exports.appDefinitionFile = exports.templateDefinitions = exports.fieldDefinitions = exports.configFolder = exports.getFileFromKey = exports.getDirFomKey = exports.splitKey = exports.joinKey = exports.safeKey = exports.keySep = exports.$ = exports.$$ = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _lodash = require("lodash");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _fp = require("lodash/fp");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _events = require("./events.js");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
// this is the combinator function
|
||||||
|
var $$ = function $$() {for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {funcs[_key] = arguments[_key];}return function (arg) {return (0, _lodash.flow)(funcs)(arg);};};
|
||||||
|
|
||||||
|
// this is the pipe function
|
||||||
|
exports.$$ = $$;var $ = function $(arg, funcs) {return $$.apply(void 0, (0, _toConsumableArray2["default"])(funcs))(arg);};exports.$ = $;
|
||||||
|
|
||||||
|
var keySep = "/";exports.keySep = keySep;
|
||||||
|
var trimKeySep = function trimKeySep(str) {return (0, _lodash.trim)(str, keySep);};
|
||||||
|
var splitByKeySep = function splitByKeySep(str) {return (0, _fp.split)(keySep)(str);};
|
||||||
|
var safeKey = function safeKey(key) {return (
|
||||||
|
(0, _lodash.replace)("".concat(keySep).concat(trimKeySep(key)), "".concat(keySep).concat(keySep), keySep));};exports.safeKey = safeKey;
|
||||||
|
var joinKey = function joinKey() {for (var _len2 = arguments.length, strs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {strs[_key2] = arguments[_key2];}
|
||||||
|
var paramsOrArray = strs.length === 1 & (0, _fp.isArray)(strs[0]) ? strs[0] : strs;
|
||||||
|
return $(paramsOrArray, [
|
||||||
|
(0, _fp.filter)(function (s) {return !(0, _fp.isUndefined)(s) && !(0, _fp.isNull)(s) && s.toString().length > 0;}),
|
||||||
|
(0, _fp.join)(keySep),
|
||||||
|
safeKey]);
|
||||||
|
|
||||||
|
};exports.joinKey = joinKey;
|
||||||
|
var splitKey = $$(trimKeySep, splitByKeySep);exports.splitKey = splitKey;
|
||||||
|
var getDirFomKey = $$(splitKey, _lodash.dropRight, function (p) {return joinKey.apply(void 0, (0, _toConsumableArray2["default"])(p));});exports.getDirFomKey = getDirFomKey;
|
||||||
|
var getFileFromKey = $$(splitKey, _lodash.takeRight, _lodash.head);exports.getFileFromKey = getFileFromKey;
|
||||||
|
|
||||||
|
var configFolder = "".concat(keySep, ".config");exports.configFolder = configFolder;
|
||||||
|
var fieldDefinitions = joinKey(configFolder, "fields.json");exports.fieldDefinitions = fieldDefinitions;
|
||||||
|
var templateDefinitions = joinKey(configFolder, "templates.json");exports.templateDefinitions = templateDefinitions;
|
||||||
|
var appDefinitionFile = joinKey(configFolder, "appDefinition.json");exports.appDefinitionFile = appDefinitionFile;
|
||||||
|
var dirIndex = function dirIndex(folderPath) {return (
|
||||||
|
joinKey.apply(void 0, [configFolder, "dir"].concat((0, _toConsumableArray2["default"])(splitKey(folderPath)), ["dir.idx"])));};exports.dirIndex = dirIndex;
|
||||||
|
var getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex);exports.getIndexKeyFromFileKey = getIndexKeyFromFileKey;
|
||||||
|
|
||||||
|
var ifExists = function ifExists(val, exists, notExists) {return (
|
||||||
|
(0, _fp.isUndefined)(val) ?
|
||||||
|
(0, _fp.isUndefined)(notExists) ?
|
||||||
|
function () {}() :
|
||||||
|
notExists() :
|
||||||
|
exists());};exports.ifExists = ifExists;
|
||||||
|
|
||||||
|
var getOrDefault = function getOrDefault(val, defaultVal) {return (
|
||||||
|
ifExists(
|
||||||
|
val,
|
||||||
|
function () {return val;},
|
||||||
|
function () {return defaultVal;}));};exports.getOrDefault = getOrDefault;
|
||||||
|
|
||||||
|
|
||||||
|
var not = function not(func) {return function (val) {return !func(val);};};exports.not = not;
|
||||||
|
var isDefined = not(_fp.isUndefined);exports.isDefined = isDefined;
|
||||||
|
var isNonNull = not(_fp.isNull);exports.isNonNull = isNonNull;
|
||||||
|
var isNotNaN = not(_fp.isNaN);exports.isNotNaN = isNotNaN;
|
||||||
|
|
||||||
|
var allTrue = function allTrue() {for (var _len3 = arguments.length, funcArgs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {funcArgs[_key3] = arguments[_key3];}return function (val) {return (
|
||||||
|
(0, _fp.reduce)(
|
||||||
|
function (result, conditionFunc) {return (
|
||||||
|
((0, _fp.isNull)(result) || result == true) && conditionFunc(val));},
|
||||||
|
null)(
|
||||||
|
funcArgs));};};exports.allTrue = allTrue;
|
||||||
|
|
||||||
|
var anyTrue = function anyTrue() {for (var _len4 = arguments.length, funcArgs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {funcArgs[_key4] = arguments[_key4];}return function (val) {return (
|
||||||
|
(0, _fp.reduce)(
|
||||||
|
function (result, conditionFunc) {return result == true || conditionFunc(val);},
|
||||||
|
null)(
|
||||||
|
funcArgs));};};exports.anyTrue = anyTrue;
|
||||||
|
|
||||||
|
var insensitiveEquals = function insensitiveEquals(str1, str2) {return (
|
||||||
|
str1.trim().toLowerCase() === str2.trim().toLowerCase());};exports.insensitiveEquals = insensitiveEquals;
|
||||||
|
|
||||||
|
var isSomething = allTrue(isDefined, isNonNull, isNotNaN);exports.isSomething = isSomething;
|
||||||
|
var isNothing = not(isSomething);exports.isNothing = isNothing;
|
||||||
|
var isNothingOrEmpty = function isNothingOrEmpty(v) {return isNothing(v) || (0, _fp.isEmpty)(v);};exports.isNothingOrEmpty = isNothingOrEmpty;
|
||||||
|
var somethingOrGetDefault = function somethingOrGetDefault(getDefaultFunc) {return function (val) {return (
|
||||||
|
isSomething(val) ? val : getDefaultFunc());};};exports.somethingOrGetDefault = somethingOrGetDefault;
|
||||||
|
var somethingOrDefault = function somethingOrDefault(val, defaultVal) {return (
|
||||||
|
somethingOrGetDefault((0, _fp.constant)(defaultVal))(val));};exports.somethingOrDefault = somethingOrDefault;
|
||||||
|
|
||||||
|
var mapIfSomethingOrDefault = function mapIfSomethingOrDefault(mapFunc, defaultVal) {return function (val) {return (
|
||||||
|
isSomething(val) ? mapFunc(val) : defaultVal);};};exports.mapIfSomethingOrDefault = mapIfSomethingOrDefault;
|
||||||
|
|
||||||
|
var mapIfSomethingOrBlank = function mapIfSomethingOrBlank(mapFunc) {return (
|
||||||
|
mapIfSomethingOrDefault(mapFunc, ""));};exports.mapIfSomethingOrBlank = mapIfSomethingOrBlank;
|
||||||
|
|
||||||
|
var none = function none(predicate) {return function (collection) {return !(0, _fp.some)(predicate)(collection);};};exports.none = none;
|
||||||
|
|
||||||
|
var all = function all(predicate) {return function (collection) {return (
|
||||||
|
none(function (v) {return !predicate(v);})(collection));};};exports.all = all;
|
||||||
|
|
||||||
|
var isNotEmpty = function isNotEmpty(ob) {return !(0, _fp.isEmpty)(ob);};exports.isNotEmpty = isNotEmpty;
|
||||||
|
var isAsync = function isAsync(fn) {return fn.constructor.name === "AsyncFunction";};exports.isAsync = isAsync;
|
||||||
|
var isNonEmptyArray = allTrue(_fp.isArray, isNotEmpty);exports.isNonEmptyArray = isNonEmptyArray;
|
||||||
|
var isNonEmptyString = allTrue(_fp.isString, isNotEmpty);exports.isNonEmptyString = isNonEmptyString;
|
||||||
|
var tryOr = function tryOr(failFunc) {return function (func) {
|
||||||
|
try {for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {args[_key5 - 1] = arguments[_key5];}
|
||||||
|
return func.apply.apply(func, [null].concat(args));
|
||||||
|
} catch (_) {
|
||||||
|
return failFunc();
|
||||||
|
}
|
||||||
|
};};exports.tryOr = tryOr;
|
||||||
|
|
||||||
|
var tryAwaitOr = function tryAwaitOr(failFunc) {return /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(func) {var _len6,args,_key6,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.prev = 0;for (_len6 = _args.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {args[_key6 - 1] = _args[_key6];}_context.next = 4;return (
|
||||||
|
|
||||||
|
func.apply.apply(func, [null].concat(args)));case 4:return _context.abrupt("return", _context.sent);case 7:_context.prev = 7;_context.t0 = _context["catch"](0);_context.next = 11;return (
|
||||||
|
|
||||||
|
failFunc());case 11:return _context.abrupt("return", _context.sent);case 12:case "end":return _context.stop();}}}, _callee, null, [[0, 7]]);}));return function (_x) {return _ref.apply(this, arguments);};}();};exports.tryAwaitOr = tryAwaitOr;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var defineError = function defineError(func, errorPrefix) {
|
||||||
|
try {
|
||||||
|
return func();
|
||||||
|
} catch (err) {
|
||||||
|
err.message = "".concat(errorPrefix, " : ").concat(err.message);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};exports.defineError = defineError;
|
||||||
|
|
||||||
|
var tryOrIgnore = tryOr(function () {});exports.tryOrIgnore = tryOrIgnore;
|
||||||
|
var tryAwaitOrIgnore = tryAwaitOr( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {return _regenerator["default"].wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:case "end":return _context2.stop();}}}, _callee2);})));exports.tryAwaitOrIgnore = tryAwaitOrIgnore;
|
||||||
|
var causesException = function causesException(func) {
|
||||||
|
try {
|
||||||
|
func();
|
||||||
|
return false;
|
||||||
|
} catch (e) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};exports.causesException = causesException;
|
||||||
|
|
||||||
|
var executesWithoutException = function executesWithoutException(func) {return !causesException(func);};exports.executesWithoutException = executesWithoutException;
|
||||||
|
|
||||||
|
var handleErrorWith = function handleErrorWith(returnValInError) {return (
|
||||||
|
tryOr((0, _fp.constant)(returnValInError)));};exports.handleErrorWith = handleErrorWith;
|
||||||
|
|
||||||
|
var handleErrorWithUndefined = handleErrorWith(undefined);exports.handleErrorWithUndefined = handleErrorWithUndefined;
|
||||||
|
|
||||||
|
var switchCase = function switchCase() {for (var _len7 = arguments.length, cases = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {cases[_key7] = arguments[_key7];}return function (value) {
|
||||||
|
var nextCase = function nextCase() {return (0, _lodash.head)(cases)[0](value);};
|
||||||
|
var nextResult = function nextResult() {return (0, _lodash.head)(cases)[1](value);};
|
||||||
|
|
||||||
|
if ((0, _fp.isEmpty)(cases)) return; // undefined
|
||||||
|
if (nextCase() === true) return nextResult();
|
||||||
|
return switchCase.apply(void 0, (0, _toConsumableArray2["default"])((0, _lodash.tail)(cases)))(value);
|
||||||
|
};};exports.switchCase = switchCase;
|
||||||
|
|
||||||
|
var isValue = function isValue(val1) {return function (val2) {return val1 === val2;};};exports.isValue = isValue;
|
||||||
|
var isOneOf = function isOneOf() {for (var _len8 = arguments.length, vals = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {vals[_key8] = arguments[_key8];}return function (val) {return (0, _fp.includes)(val)(vals);};};exports.isOneOf = isOneOf;
|
||||||
|
var defaultCase = (0, _fp.constant)(true);exports.defaultCase = defaultCase;
|
||||||
|
var memberMatches = function memberMatches(member, match) {return function (obj) {return match(obj[member]);};};exports.memberMatches = memberMatches;
|
||||||
|
|
||||||
|
var StartsWith = function StartsWith(searchFor) {return function (searchIn) {return (
|
||||||
|
(0, _lodash.startsWith)(searchIn, searchFor));};};exports.StartsWith = StartsWith;
|
||||||
|
|
||||||
|
var contains = function contains(val) {return function (array) {return (0, _lodash.findIndex)(array, function (v) {return v === val;}) > -1;};};exports.contains = contains;
|
||||||
|
|
||||||
|
var getHashCode = function getHashCode(s) {
|
||||||
|
var hash = 0;
|
||||||
|
var i;
|
||||||
|
var _char;
|
||||||
|
var l;
|
||||||
|
if (s.length == 0) return hash;
|
||||||
|
for (i = 0, l = s.length; i < l; i++) {
|
||||||
|
_char = s.charCodeAt(i);
|
||||||
|
hash = (hash << 5) - hash + _char;
|
||||||
|
hash |= 0; // Convert to 32bit integer
|
||||||
|
}
|
||||||
|
|
||||||
|
// converting to string, but dont want a "-" prefixed
|
||||||
|
if (hash < 0) {
|
||||||
|
return "n".concat((hash * -1).toString());
|
||||||
|
}
|
||||||
|
return hash.toString();
|
||||||
|
};
|
||||||
|
|
||||||
|
// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
|
||||||
|
exports.getHashCode = getHashCode;var awEx = /*#__PURE__*/function () {var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(promise) {var result;return _regenerator["default"].wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:_context3.prev = 0;_context3.next = 3;return (
|
||||||
|
|
||||||
|
promise);case 3:result = _context3.sent;return _context3.abrupt("return",
|
||||||
|
[undefined, result]);case 7:_context3.prev = 7;_context3.t0 = _context3["catch"](0);return _context3.abrupt("return",
|
||||||
|
|
||||||
|
[_context3.t0, undefined]);case 10:case "end":return _context3.stop();}}}, _callee3, null, [[0, 7]]);}));return function awEx(_x2) {return _ref3.apply(this, arguments);};}();exports.awEx = awEx;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var isSafeInteger = function isSafeInteger(n) {return (
|
||||||
|
(0, _fp.isInteger)(n) &&
|
||||||
|
n <= Number.MAX_SAFE_INTEGER &&
|
||||||
|
n >= 0 - Number.MAX_SAFE_INTEGER);};exports.isSafeInteger = isSafeInteger;
|
||||||
|
|
||||||
|
var toDateOrNull = function toDateOrNull(s) {return (
|
||||||
|
(0, _fp.isNull)(s) ? null : (0, _fp.isDate)(s) ? s : new Date(s));};exports.toDateOrNull = toDateOrNull;
|
||||||
|
var toBoolOrNull = function toBoolOrNull(s) {return (0, _fp.isNull)(s) ? null : s === "true" || s === true;};exports.toBoolOrNull = toBoolOrNull;
|
||||||
|
var toNumberOrNull = function toNumberOrNull(s) {return (0, _fp.isNull)(s) ? null : (0, _fp.toNumber)(s);};exports.toNumberOrNull = toNumberOrNull;
|
||||||
|
|
||||||
|
var isArrayOfString = function isArrayOfString(opts) {return (0, _fp.isArray)(opts) && all(_fp.isString)(opts);};exports.isArrayOfString = isArrayOfString;
|
||||||
|
|
||||||
|
var pushAll = function pushAll(target, items) {var _iterator = _createForOfIteratorHelper(
|
||||||
|
items),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var i = _step.value;target.push(i);}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
|
||||||
|
};exports.pushAll = pushAll;
|
||||||
|
|
||||||
|
var pause = /*#__PURE__*/function () {var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(duration) {return _regenerator["default"].wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:return _context4.abrupt("return",
|
||||||
|
new Promise(function (res) {return setTimeout(res, duration);}));case 1:case "end":return _context4.stop();}}}, _callee4);}));return function pause(_x3) {return _ref4.apply(this, arguments);};}();exports.pause = pause;
|
||||||
|
|
||||||
|
var retry = /*#__PURE__*/function () {var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(fn, retries, delay) {var _len9,args,_key9,_args6 = arguments;return _regenerator["default"].wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:for (_len9 = _args6.length, args = new Array(_len9 > 3 ? _len9 - 3 : 0), _key9 = 3; _key9 < _len9; _key9++) {args[_key9 - 3] = _args6[_key9];}_context6.prev = 1;_context6.next = 4;return (
|
||||||
|
|
||||||
|
fn.apply(void 0, args));case 4:return _context6.abrupt("return", _context6.sent);case 7:_context6.prev = 7;_context6.t0 = _context6["catch"](1);if (!(
|
||||||
|
|
||||||
|
retries > 1)) {_context6.next = 13;break;}_context6.next = 12;return (
|
||||||
|
pause(delay).then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(
|
||||||
|
function _callee5() {return _regenerator["default"].wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:_context5.next = 2;return retry.apply(void 0, [fn, retries - 1, delay].concat(args));case 2:return _context5.abrupt("return", _context5.sent);case 3:case "end":return _context5.stop();}}}, _callee5);}))));case 12:return _context6.abrupt("return", _context6.sent);case 13:throw _context6.t0;case 14:case "end":return _context6.stop();}}}, _callee6, null, [[1, 7]]);}));return function retry(_x4, _x5, _x6) {return _ref5.apply(this, arguments);};}();exports.retry = retry;var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
ifExists: ifExists,
|
||||||
|
getOrDefault: getOrDefault,
|
||||||
|
isDefined: isDefined,
|
||||||
|
isNonNull: isNonNull,
|
||||||
|
isNotNaN: isNotNaN,
|
||||||
|
allTrue: allTrue,
|
||||||
|
isSomething: isSomething,
|
||||||
|
mapIfSomethingOrDefault: mapIfSomethingOrDefault,
|
||||||
|
mapIfSomethingOrBlank: mapIfSomethingOrBlank,
|
||||||
|
configFolder: configFolder,
|
||||||
|
fieldDefinitions: fieldDefinitions,
|
||||||
|
isNothing: isNothing,
|
||||||
|
not: not,
|
||||||
|
switchCase: switchCase,
|
||||||
|
defaultCase: defaultCase,
|
||||||
|
StartsWith: StartsWith,
|
||||||
|
contains: contains,
|
||||||
|
templateDefinitions: templateDefinitions,
|
||||||
|
handleErrorWith: handleErrorWith,
|
||||||
|
handleErrorWithUndefined: handleErrorWithUndefined,
|
||||||
|
tryOr: tryOr,
|
||||||
|
tryOrIgnore: tryOrIgnore,
|
||||||
|
tryAwaitOr: tryAwaitOr,
|
||||||
|
tryAwaitOrIgnore: tryAwaitOrIgnore,
|
||||||
|
dirIndex: dirIndex,
|
||||||
|
keySep: keySep,
|
||||||
|
$: $,
|
||||||
|
$$: $$,
|
||||||
|
getDirFomKey: getDirFomKey,
|
||||||
|
getFileFromKey: getFileFromKey,
|
||||||
|
splitKey: splitKey,
|
||||||
|
somethingOrDefault: somethingOrDefault,
|
||||||
|
getIndexKeyFromFileKey: getIndexKeyFromFileKey,
|
||||||
|
joinKey: joinKey,
|
||||||
|
somethingOrGetDefault: somethingOrGetDefault,
|
||||||
|
appDefinitionFile: appDefinitionFile,
|
||||||
|
isValue: isValue,
|
||||||
|
all: all,
|
||||||
|
isOneOf: isOneOf,
|
||||||
|
memberMatches: memberMatches,
|
||||||
|
defineError: defineError,
|
||||||
|
anyTrue: anyTrue,
|
||||||
|
isNonEmptyArray: isNonEmptyArray,
|
||||||
|
causesException: causesException,
|
||||||
|
executesWithoutException: executesWithoutException,
|
||||||
|
none: none,
|
||||||
|
getHashCode: getHashCode,
|
||||||
|
awEx: awEx,
|
||||||
|
events: _events.events,
|
||||||
|
eventsList: _events.eventsList,
|
||||||
|
isNothingOrEmpty: isNothingOrEmpty,
|
||||||
|
isSafeInteger: isSafeInteger,
|
||||||
|
toNumber: _fp.toNumber,
|
||||||
|
toDate: toDateOrNull,
|
||||||
|
toBool: toBoolOrNull,
|
||||||
|
isArrayOfString: isArrayOfString,
|
||||||
|
insensitiveEquals: insensitiveEquals,
|
||||||
|
pause: pause,
|
||||||
|
retry: retry,
|
||||||
|
pushAll: pushAll };exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=index.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,15 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.applyRule = exports.applyRuleSet = exports.validationError = exports.makerule = exports.stringNotEmpty = void 0;var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _fp = require("lodash/fp");
|
||||||
|
var _index = require("./index");function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;});keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(Object(source), true).forEach(function (key) {(0, _defineProperty2["default"])(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}
|
||||||
|
|
||||||
|
var stringNotEmpty = function stringNotEmpty(s) {return (0, _index.isSomething)(s) && s.trim().length > 0;};exports.stringNotEmpty = stringNotEmpty;
|
||||||
|
|
||||||
|
var makerule = function makerule(field, error, isValid) {return { field: field, error: error, isValid: isValid };};exports.makerule = makerule;
|
||||||
|
|
||||||
|
var validationError = function validationError(rule, item) {return _objectSpread({}, rule, { item: item });};exports.validationError = validationError;
|
||||||
|
|
||||||
|
var applyRuleSet = function applyRuleSet(ruleSet) {return function (itemToValidate) {return (
|
||||||
|
(0, _index.$)(ruleSet, [(0, _fp.map)(applyRule(itemToValidate)), (0, _fp.filter)(_index.isSomething)]));};};exports.applyRuleSet = applyRuleSet;
|
||||||
|
|
||||||
|
var applyRule = function applyRule(itemTovalidate) {return function (rule) {return (
|
||||||
|
rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate));};};exports.applyRule = applyRule;
|
||||||
|
//# sourceMappingURL=validationCommon.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/common/validationCommon.js"],"names":["stringNotEmpty","s","trim","length","makerule","field","error","isValid","validationError","rule","item","applyRuleSet","ruleSet","itemToValidate","applyRule","isSomething","itemTovalidate"],"mappings":"wXAAA;AACA,gC;;AAEO,IAAMA,cAAc,GAAG,SAAjBA,cAAiB,CAAAC,CAAC,UAAI,wBAAYA,CAAZ,KAAkBA,CAAC,CAACC,IAAF,GAASC,MAAT,GAAkB,CAAxC,EAAxB,C;;AAEA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,KAAD,EAAQC,KAAR,EAAeC,OAAf,UAA4B,EAAEF,KAAK,EAALA,KAAF,EAASC,KAAK,EAALA,KAAT,EAAgBC,OAAO,EAAPA,OAAhB,EAA5B,EAAjB,C;;AAEA,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAACC,IAAD,EAAOC,IAAP,4BAAsBD,IAAtB,IAA4BC,IAAI,EAAJA,IAA5B,KAAxB,C;;AAEA,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAAAC,OAAO,UAAI,UAAAC,cAAc;AACnD,oBAAED,OAAF,EAAW,CAAC,aAAIE,SAAS,CAACD,cAAD,CAAb,CAAD,EAAiC,gBAAOE,kBAAP,CAAjC,CAAX,CADmD,GAAlB,EAA5B,C;;AAGA,IAAMD,SAAS,GAAG,SAAZA,SAAY,CAAAE,cAAc,UAAI,UAAAP,IAAI;AAC7CA,MAAAA,IAAI,CAACF,OAAL,CAAaS,cAAb,IAA+B,IAA/B,GAAsCR,eAAe,CAACC,IAAD,EAAOO,cAAP,CADR,GAAR,EAAhC,C","sourcesContent":["import { filter, map } from \"lodash/fp\"\nimport { $, isSomething } from \"./index\"\n\nexport const stringNotEmpty = s => isSomething(s) && s.trim().length > 0\n\nexport const makerule = (field, error, isValid) => ({ field, error, isValid })\n\nexport const validationError = (rule, item) => ({ ...rule, item })\n\nexport const applyRuleSet = ruleSet => itemToValidate =>\n $(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])\n\nexport const applyRule = itemTovalidate => rule =>\n rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)\n"],"file":"validationCommon.js"}
|
|
@ -0,0 +1,4 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "validateRecord", { enumerable: true, get: function get() {return _validateRecord.validateRecord;} });Object.defineProperty(exports, "events", { enumerable: true, get: function get() {return _events.events;} });Object.defineProperty(exports, "safeParseField", { enumerable: true, get: function get() {return _types.safeParseField;} });var _validateRecord = require("./records/validateRecord");
|
||||||
|
var _events = require("./common/events");
|
||||||
|
var _types = require("./schema/types");
|
||||||
|
//# sourceMappingURL=index.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"ybAAA;AACA;AACA","sourcesContent":["export { validateRecord } from \"./records/validateRecord\";\nexport { events } from \"./common/events\";\nexport { safeParseField } from \"./schema/types\";"],"file":"index.js"}
|
|
@ -0,0 +1,18 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.getNewRecord = void 0;var _shortid = require("shortid");
|
||||||
|
var _types = require("../schema/types");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
var getNewRecord = function getNewRecord(schema, modelName) {
|
||||||
|
var model = schema.findModel(modelName);
|
||||||
|
|
||||||
|
var record = {
|
||||||
|
_id: (0, _shortid.generate)(),
|
||||||
|
_modelId: model.id };var _iterator = _createForOfIteratorHelper(
|
||||||
|
|
||||||
|
|
||||||
|
model.fields),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var field = _step.value;
|
||||||
|
record[field.name] = (0, _types.getNewFieldValue)(field);
|
||||||
|
}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
|
||||||
|
|
||||||
|
return record;
|
||||||
|
};exports.getNewRecord = getNewRecord;
|
||||||
|
//# sourceMappingURL=getNewRecord.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/records/getNewRecord.js"],"names":["getNewRecord","schema","modelName","model","findModel","record","_id","_modelId","id","fields","field","name"],"mappings":"yGAAA;AACA,wC;;AAEO,IAAMA,YAAY,GAAG,SAAfA,YAAe,CAACC,MAAD,EAASC,SAAT,EAAuB;AACjD,MAAMC,KAAK,GAAGF,MAAM,CAACG,SAAP,CAAiBF,SAAjB,CAAd;;AAEA,MAAMG,MAAM,GAAG;AACbC,IAAAA,GAAG,EAAE,wBADQ;AAEbC,IAAAA,QAAQ,EAAEJ,KAAK,CAACK,EAFH,EAAf,CAHiD;;;AAQ/BL,EAAAA,KAAK,CAACM,MARyB,aAQjD,oDAAgC,KAAvBC,KAAuB;AAC9BL,MAAAA,MAAM,CAACK,KAAK,CAACC,IAAP,CAAN,GAAqB,6BAAiBD,KAAjB,CAArB;AACD,KAVgD;;AAYjD,SAAOL,MAAP;AACD,CAbM,C","sourcesContent":["import { generate } from \"shortid\"\nimport { getNewFieldValue } from \"../schema/types\"\n\nexport const getNewRecord = (schema, modelName) => {\n const model = schema.findModel(modelName)\n\n const record = {\n _id: generate(),\n _modelId: model.id,\n }\n\n for (let field of model.fields) {\n record[field.name] = getNewFieldValue(field)\n }\n\n return record\n}\n"],"file":"getNewRecord.js"}
|
|
@ -0,0 +1,31 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.commonRecordValidationRules = exports.getNewRecordValidationRule = void 0;var getNewRecordValidationRule = function getNewRecordValidationRule(
|
||||||
|
invalidField,
|
||||||
|
messageWhenInvalid,
|
||||||
|
expressionWhenValid) {return (
|
||||||
|
{
|
||||||
|
invalidField: invalidField,
|
||||||
|
messageWhenInvalid: messageWhenInvalid,
|
||||||
|
expressionWhenValid: expressionWhenValid });};exports.getNewRecordValidationRule = getNewRecordValidationRule;
|
||||||
|
|
||||||
|
|
||||||
|
var commonRecordValidationRules = {
|
||||||
|
fieldNotEmpty: function fieldNotEmpty(fieldName) {return (
|
||||||
|
getNewRecordValidationRule(
|
||||||
|
fieldName, "".concat(
|
||||||
|
fieldName, " is empty"), "record['".concat(
|
||||||
|
fieldName, "'] && record['").concat(fieldName, "'].length > 0")));},
|
||||||
|
|
||||||
|
|
||||||
|
fieldBetween: function fieldBetween(fieldName, min, max) {return (
|
||||||
|
getNewRecordValidationRule(
|
||||||
|
fieldName, "".concat(
|
||||||
|
fieldName, " must be between ").concat(min.toString(), " and ").concat(max.toString()), "record['".concat(
|
||||||
|
fieldName, "'] >= ").concat(min, " && record['").concat(fieldName, "'] <= ").concat(max, " ")));},
|
||||||
|
|
||||||
|
|
||||||
|
fieldGreaterThan: function fieldGreaterThan(fieldName, min, max) {return (
|
||||||
|
getNewRecordValidationRule(
|
||||||
|
fieldName, "".concat(
|
||||||
|
fieldName, " must be greater than ").concat(min.toString(), " and ").concat(max.toString()), "record['".concat(
|
||||||
|
fieldName, "'] >= ").concat(min, " ")));} };exports.commonRecordValidationRules = commonRecordValidationRules;
|
||||||
|
//# sourceMappingURL=recordValidationRules.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/records/recordValidationRules.js"],"names":["getNewRecordValidationRule","invalidField","messageWhenInvalid","expressionWhenValid","commonRecordValidationRules","fieldNotEmpty","fieldName","fieldBetween","min","max","toString","fieldGreaterThan"],"mappings":"6JAAO,IAAMA,0BAA0B,GAAG,SAA7BA,0BAA6B;AACxCC,YADwC;AAExCC,kBAFwC;AAGxCC,mBAHwC;AAIpC;AACJF,MAAAA,YAAY,EAAZA,YADI;AAEJC,MAAAA,kBAAkB,EAAlBA,kBAFI;AAGJC,MAAAA,mBAAmB,EAAnBA,mBAHI,EAJoC,GAAnC,C;;;AAUA,IAAMC,2BAA2B,GAAG;AACzCC,EAAAA,aAAa,EAAE,uBAAAC,SAAS;AACtBN,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB;AAGbA,MAAAA,SAHa,2BAGaA,SAHb,mBADJ,GADiB;;;AAQzCC,EAAAA,YAAY,EAAE,sBAACD,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AACZT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,8BAEQE,GAAG,CAACE,QAAJ,EAFR,kBAE8BD,GAAG,CAACC,QAAJ,EAF9B;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,0BAGwBF,SAHxB,mBAG0CG,GAH1C,OADd,GAR2B;;;AAezCE,EAAAA,gBAAgB,EAAE,0BAACL,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AAChBT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,mCAEaE,GAAG,CAACE,QAAJ,EAFb,kBAEmCD,GAAG,CAACC,QAAJ,EAFnC;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,QADV,GAfuB,EAApC,C","sourcesContent":["export const getNewRecordValidationRule = (\n invalidField,\n messageWhenInvalid,\n expressionWhenValid\n) => ({\n invalidField,\n messageWhenInvalid,\n expressionWhenValid,\n})\n\nexport const commonRecordValidationRules = {\n fieldNotEmpty: fieldName =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} is empty`,\n `record['${fieldName}'] && record['${fieldName}'].length > 0`\n ),\n\n fieldBetween: (fieldName, min, max) =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} must be between ${min.toString()} and ${max.toString()}`,\n `record['${fieldName}'] >= ${min} && record['${fieldName}'] <= ${max} `\n ),\n\n fieldGreaterThan: (fieldName, min, max) =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} must be greater than ${min.toString()} and ${max.toString()}`,\n `record['${fieldName}'] >= ${min} `\n ),\n}\n"],"file":"recordValidationRules.js"}
|
|
@ -0,0 +1,86 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.validateRecord = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _compileCode = require("../common/compileCode");
|
||||||
|
var _index = require("../schema/types/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index2 = require("../common/index.js");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
var fieldParseError = function fieldParseError(fieldName, value) {return {
|
||||||
|
fields: [fieldName],
|
||||||
|
message: "Could not parse field ".concat(fieldName, ":").concat(value) };};
|
||||||
|
|
||||||
|
|
||||||
|
var validateAllFieldParse = function validateAllFieldParse(record, model) {return (
|
||||||
|
(0, _index2.$)(model.fields, [
|
||||||
|
(0, _fp.map)(function (f) {return { name: f.name, parseResult: (0, _index.validateFieldParse)(f, record) };}),
|
||||||
|
(0, _fp.reduce)(function (errors, f) {
|
||||||
|
if (f.parseResult.success) return errors;
|
||||||
|
errors.push(fieldParseError(f.name, f.parseResult.value));
|
||||||
|
return errors;
|
||||||
|
}, [])]));};
|
||||||
|
|
||||||
|
|
||||||
|
var validateAllTypeConstraints = function validateAllTypeConstraints(record, model) {
|
||||||
|
var errors = [];var _iterator = _createForOfIteratorHelper(
|
||||||
|
model.fields),_step;try {var _loop = function _loop() {var field = _step.value;
|
||||||
|
(0, _index2.$)((0, _index.validateTypeConstraints)(field, record), [
|
||||||
|
(0, _fp.filter)(_index2.isNonEmptyString),
|
||||||
|
(0, _fp.map)(function (m) {return { message: m, fields: [field.name] };}),
|
||||||
|
(0, _fp.each)(function (e) {return errors.push(e);})]);};for (_iterator.s(); !(_step = _iterator.n()).done;) {_loop();
|
||||||
|
|
||||||
|
}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
|
||||||
|
return errors;
|
||||||
|
};
|
||||||
|
|
||||||
|
var runRecordValidationRules = function runRecordValidationRules(record, model) {
|
||||||
|
var runValidationRule = function runValidationRule(rule) {
|
||||||
|
var isValid = (0, _compileCode.compileCode)(rule.expressionWhenValid);
|
||||||
|
var expressionContext = { record: record };
|
||||||
|
return isValid(expressionContext) ?
|
||||||
|
{ valid: true } :
|
||||||
|
{
|
||||||
|
valid: false,
|
||||||
|
fields: rule.invalidFields,
|
||||||
|
message: rule.messageWhenInvalid };
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
return (0, _index2.$)(model.validationRules, [
|
||||||
|
(0, _fp.map)(runValidationRule),
|
||||||
|
_fp.flatten,
|
||||||
|
(0, _fp.filter)(function (r) {return r.valid === false;}),
|
||||||
|
(0, _fp.map)(function (r) {return { fields: r.fields, message: r.message };})]);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
var validateRecord = function validateRecord(schema, record) {
|
||||||
|
var model = schema.findModel(record._modelId);
|
||||||
|
var fieldParseFails = validateAllFieldParse(record, model);
|
||||||
|
|
||||||
|
// non parsing would cause further issues - exit here
|
||||||
|
if (!(0, _fp.isEmpty)(fieldParseFails)) {
|
||||||
|
return { isValid: false, errors: fieldParseFails };
|
||||||
|
}
|
||||||
|
|
||||||
|
var recordValidationRuleFails = runRecordValidationRules(record, model);
|
||||||
|
var typeContraintFails = validateAllTypeConstraints(record, model);
|
||||||
|
|
||||||
|
if (
|
||||||
|
(0, _fp.isEmpty)(fieldParseFails) &&
|
||||||
|
(0, _fp.isEmpty)(recordValidationRuleFails) &&
|
||||||
|
(0, _fp.isEmpty)(typeContraintFails))
|
||||||
|
{
|
||||||
|
return { isValid: true, errors: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
errors: (0, _fp.union)(
|
||||||
|
fieldParseFails,
|
||||||
|
typeContraintFails,
|
||||||
|
recordValidationRuleFails) };
|
||||||
|
|
||||||
|
|
||||||
|
};exports.validateRecord = validateRecord;
|
||||||
|
//# sourceMappingURL=validateRecord.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,22 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.createAction = exports.createTrigger = void 0;var createTrigger = function createTrigger() {return {
|
||||||
|
actionName: "",
|
||||||
|
eventName: "",
|
||||||
|
// function, has access to event context,
|
||||||
|
// returns object that is used as parameter to action
|
||||||
|
// only used if triggered by event
|
||||||
|
optionsCreator: "",
|
||||||
|
// action runs if true,
|
||||||
|
// has access to event context
|
||||||
|
condition: "" };};exports.createTrigger = createTrigger;
|
||||||
|
|
||||||
|
|
||||||
|
var createAction = function createAction() {return {
|
||||||
|
name: "",
|
||||||
|
behaviourSource: "",
|
||||||
|
// name of function in actionSource
|
||||||
|
behaviourName: "",
|
||||||
|
// parameter passed into behaviour.
|
||||||
|
// any other parms passed at runtime e.g.
|
||||||
|
// by trigger, or manually, will be merged into this
|
||||||
|
initialOptions: {} };};exports.createAction = createAction;
|
||||||
|
//# sourceMappingURL=createActions.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/schema/createActions.js"],"names":["createTrigger","actionName","eventName","optionsCreator","condition","createAction","name","behaviourSource","behaviourName","initialOptions"],"mappings":"iIAAO,IAAMA,aAAa,GAAG,SAAhBA,aAAgB,WAAO;AAClCC,IAAAA,UAAU,EAAE,EADsB;AAElCC,IAAAA,SAAS,EAAE,EAFuB;AAGlC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EANkB;AAOlC;AACA;AACAC,IAAAA,SAAS,EAAE,EATuB,EAAP,EAAtB,C;;;AAYA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAO;AACjCC,IAAAA,IAAI,EAAE,EAD2B;AAEjCC,IAAAA,eAAe,EAAE,EAFgB;AAGjC;AACAC,IAAAA,aAAa,EAAE,EAJkB;AAKjC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EARiB,EAAP,EAArB,C","sourcesContent":["export const createTrigger = () => ({\n actionName: \"\",\n eventName: \"\",\n // function, has access to event context,\n // returns object that is used as parameter to action\n // only used if triggered by event\n optionsCreator: \"\",\n // action runs if true,\n // has access to event context\n condition: \"\",\n})\n\nexport const createAction = () => ({\n name: \"\",\n behaviourSource: \"\",\n // name of function in actionSource\n behaviourName: \"\",\n // parameter passed into behaviour.\n // any other parms passed at runtime e.g.\n // by trigger, or manually, will be merged into this\n initialOptions: {},\n})\n"],"file":"createActions.js"}
|
|
@ -0,0 +1,97 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.addField = exports.validateAllFields = exports.validateField = exports.getNewField = exports.allowedTypes = exports.fieldErrors = void 0;var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _fp = require("lodash/fp");
|
||||||
|
var _common = require("../common");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("./types/index.js");
|
||||||
|
var _validationCommon = require("../common/validationCommon");
|
||||||
|
var _errors = require("../common/errors");
|
||||||
|
var _shortid = require("shortid");
|
||||||
|
|
||||||
|
var fieldErrors = {
|
||||||
|
AddFieldValidationFailed: "Add field validation: " };exports.fieldErrors = fieldErrors;
|
||||||
|
|
||||||
|
|
||||||
|
var allowedTypes = function allowedTypes() {return (0, _fp.keys)(_index.all);};exports.allowedTypes = allowedTypes;
|
||||||
|
|
||||||
|
var getNewField = function getNewField(type) {return {
|
||||||
|
id: (0, _shortid.generate)(),
|
||||||
|
name: "", // how field is referenced internally
|
||||||
|
type: type,
|
||||||
|
typeOptions: (0, _index.getDefaultOptions)(type),
|
||||||
|
label: "", // how field is displayed
|
||||||
|
getInitialValue: "default", // function that gets value when initially created
|
||||||
|
getUndefinedValue: "default" // function that gets value when field undefined on record
|
||||||
|
};};exports.getNewField = getNewField;
|
||||||
|
|
||||||
|
var fieldRules = function fieldRules(allFields) {return [
|
||||||
|
(0, _validationCommon.makerule)("name", "field name is not set", function (f) {return (0, _common.isNonEmptyString)(f.name);}),
|
||||||
|
(0, _validationCommon.makerule)("type", "field type is not set", function (f) {return (0, _common.isNonEmptyString)(f.type);}),
|
||||||
|
(0, _validationCommon.makerule)("label", "field label is not set", function (f) {return (0, _common.isNonEmptyString)(f.label);}),
|
||||||
|
(0, _validationCommon.makerule)("getInitialValue", "getInitialValue function is not set", function (f) {return (
|
||||||
|
(0, _common.isNonEmptyString)(f.getInitialValue));}),
|
||||||
|
|
||||||
|
(0, _validationCommon.makerule)("getUndefinedValue", "getUndefinedValue function is not set", function (f) {return (
|
||||||
|
(0, _common.isNonEmptyString)(f.getUndefinedValue));}),
|
||||||
|
|
||||||
|
(0, _validationCommon.makerule)(
|
||||||
|
"name",
|
||||||
|
"field name is duplicated",
|
||||||
|
function (f) {return (0, _common.isNothingOrEmpty)(f.name) || (0, _fp.countBy)("name")(allFields)[f.name] === 1;}),
|
||||||
|
|
||||||
|
(0, _validationCommon.makerule)(
|
||||||
|
"type",
|
||||||
|
"type is unknown",
|
||||||
|
function (f) {return (0, _common.isNothingOrEmpty)(f.type) || (0, _fp.some)(function (t) {return f.type === t;})(allowedTypes());})];};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeOptionsRules = function typeOptionsRules(field) {
|
||||||
|
var type = _index.all[field.type];
|
||||||
|
if ((0, _common.isNothing)(type)) return [];
|
||||||
|
|
||||||
|
var def = function def(optName) {return type.optionDefinitions[optName];};
|
||||||
|
|
||||||
|
return (0, _common.$)(field.typeOptions, [
|
||||||
|
_fp.keys,
|
||||||
|
(0, _fp.filter)(function (o) {return (0, _common.isSomething)(def(o)) && (0, _common.isSomething)(def(o).isValid);}),
|
||||||
|
(0, _fp.map)(function (o) {return (
|
||||||
|
(0, _validationCommon.makerule)("typeOptions.".concat(o), "".concat(def(o).requirementDescription), function (field) {return (
|
||||||
|
def(o).isValid(field.typeOptions[o]));}));})]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
var validateField = function validateField(allFields) {return function (field) {
|
||||||
|
var everySingleField = (0, _fp.includes)(field)(allFields) ?
|
||||||
|
allFields : [].concat((0, _toConsumableArray2["default"])(
|
||||||
|
allFields), [field]);
|
||||||
|
return (0, _validationCommon.applyRuleSet)([].concat((0, _toConsumableArray2["default"])(
|
||||||
|
fieldRules(everySingleField)), (0, _toConsumableArray2["default"])(
|
||||||
|
typeOptionsRules(field))))(
|
||||||
|
field);
|
||||||
|
};};exports.validateField = validateField;
|
||||||
|
|
||||||
|
var validateAllFields = function validateAllFields(recordNode) {return (
|
||||||
|
(0, _common.$)(recordNode.fields, [(0, _fp.map)(validateField(recordNode.fields)), _fp.flatten]));};exports.validateAllFields = validateAllFields;
|
||||||
|
|
||||||
|
var addField = function addField(recordTemplate, field) {
|
||||||
|
if ((0, _common.isNothingOrEmpty)(field.label)) {
|
||||||
|
field.label = field.name;
|
||||||
|
}
|
||||||
|
var validationMessages = validateField([].concat((0, _toConsumableArray2["default"])(recordTemplate.fields), [field]))(
|
||||||
|
field);
|
||||||
|
|
||||||
|
if (validationMessages.length > 0) {
|
||||||
|
var errors = (0, _fp.map)(function (m) {return m.error;})(validationMessages);
|
||||||
|
throw new _errors.BadRequestError("".concat(
|
||||||
|
fieldErrors.AddFieldValidationFailed, " ").concat(errors.join(", ")));
|
||||||
|
|
||||||
|
}
|
||||||
|
recordTemplate.fields.push(field);
|
||||||
|
};exports.addField = addField;
|
||||||
|
//# sourceMappingURL=fields.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,34 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.fullSchema = void 0;var fullSchema = function fullSchema(models, views) {
|
||||||
|
var findModel = function findModel(idOrName) {return (
|
||||||
|
models.find(
|
||||||
|
function (m) {return m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase();}));};
|
||||||
|
|
||||||
|
|
||||||
|
var findView = function findView(idOrName) {return (
|
||||||
|
views.find(
|
||||||
|
function (m) {return m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase();}));};
|
||||||
|
|
||||||
|
|
||||||
|
var findField = function findField(modelIdOrName, fieldName) {
|
||||||
|
var model = models.find(
|
||||||
|
function (m) {return (
|
||||||
|
m.id === modelIdOrName ||
|
||||||
|
m.name.toLowerCase() === modelIdOrName.toLowerCase());});
|
||||||
|
|
||||||
|
return model.fields.find(
|
||||||
|
function (f) {return f.name.toLowerCase() === fieldName.toLowerCase();});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
var viewsForModel = function viewsForModel(modelId) {return views.filter(function (v) {return v.modelId === modelId;});};
|
||||||
|
|
||||||
|
return {
|
||||||
|
models: models,
|
||||||
|
views: views,
|
||||||
|
findModel: findModel,
|
||||||
|
findField: findField,
|
||||||
|
findView: findView,
|
||||||
|
viewsForModel: viewsForModel };
|
||||||
|
|
||||||
|
};exports.fullSchema = fullSchema;
|
||||||
|
//# sourceMappingURL=fullSchema.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/schema/fullSchema.js"],"names":["fullSchema","models","views","findModel","idOrName","find","m","id","name","toLowerCase","findView","findField","modelIdOrName","fieldName","model","fields","f","viewsForModel","modelId","filter","v"],"mappings":"uGAAO,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAACC,MAAD,EAASC,KAAT,EAAmB;AAC3C,MAAMC,SAAS,GAAG,SAAZA,SAAY,CAAAC,QAAQ;AACxBH,MAAAA,MAAM,CAACI,IAAP;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADwB,GAA1B;;;AAKA,MAAMC,QAAQ,GAAG,SAAXA,QAAW,CAAAN,QAAQ;AACvBF,MAAAA,KAAK,CAACG,IAAN;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADuB,GAAzB;;;AAKA,MAAME,SAAS,GAAG,SAAZA,SAAY,CAACC,aAAD,EAAgBC,SAAhB,EAA8B;AAC9C,QAAMC,KAAK,GAAGb,MAAM,CAACI,IAAP;AACZ,cAAAC,CAAC;AACCA,QAAAA,CAAC,CAACC,EAAF,KAASK,aAAT;AACAN,QAAAA,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBG,aAAa,CAACH,WAAd,EAF1B,GADW,CAAd;;AAKA,WAAOK,KAAK,CAACC,MAAN,CAAaV,IAAb;AACL,cAAAW,CAAC,UAAIA,CAAC,CAACR,IAAF,CAAOC,WAAP,OAAyBI,SAAS,CAACJ,WAAV,EAA7B,EADI,CAAP;;AAGD,GATD;;AAWA,MAAMQ,aAAa,GAAG,SAAhBA,aAAgB,CAAAC,OAAO,UAAIhB,KAAK,CAACiB,MAAN,CAAa,UAAAC,CAAC,UAAIA,CAAC,CAACF,OAAF,KAAcA,OAAlB,EAAd,CAAJ,EAA7B;;AAEA,SAAO;AACLjB,IAAAA,MAAM,EAANA,MADK;AAELC,IAAAA,KAAK,EAALA,KAFK;AAGLC,IAAAA,SAAS,EAATA,SAHK;AAILQ,IAAAA,SAAS,EAATA,SAJK;AAKLD,IAAAA,QAAQ,EAARA,QALK;AAMLO,IAAAA,aAAa,EAAbA,aANK,EAAP;;AAQD,CAhCM,C","sourcesContent":["export const fullSchema = (models, views) => {\n const findModel = idOrName =>\n models.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findView = idOrName =>\n views.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findField = (modelIdOrName, fieldName) => {\n const model = models.find(\n m =>\n m.id === modelIdOrName ||\n m.name.toLowerCase() === modelIdOrName.toLowerCase()\n )\n return model.fields.find(\n f => f.name.toLowerCase() === fieldName.toLowerCase()\n )\n }\n\n const viewsForModel = modelId => views.filter(v => v.modelId === modelId)\n\n return {\n models,\n views,\n findModel,\n findField,\n findView,\n viewsForModel,\n }\n}\n"],"file":"fullSchema.js"}
|
|
@ -0,0 +1,38 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.canDeleteModel = exports.newModel = void 0;var _shortid = require("shortid");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
var newModel = function newModel() {return {
|
||||||
|
id: (0, _shortid.generate)(),
|
||||||
|
name: "",
|
||||||
|
fields: [],
|
||||||
|
validationRules: [],
|
||||||
|
primaryField: "",
|
||||||
|
views: [] };};
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {Array} models
|
||||||
|
* @param {string} modelId
|
||||||
|
* @returns {}
|
||||||
|
*/exports.newModel = newModel;
|
||||||
|
var canDeleteModel = function canDeleteModel(models, modelId) {
|
||||||
|
var errors = [];var _iterator = _createForOfIteratorHelper(
|
||||||
|
|
||||||
|
models),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var model = _step.value;
|
||||||
|
var links = model.fields.filter(
|
||||||
|
function (f) {return f.type === "link" && f.typeOptions.modelId === modelId;});var _iterator2 = _createForOfIteratorHelper(
|
||||||
|
|
||||||
|
|
||||||
|
links),_step2;try {for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {var link = _step2.value;
|
||||||
|
errors.push("The \"".concat(
|
||||||
|
model.name, "\" model links to this model, via field \"").concat(link.name, "\""));
|
||||||
|
|
||||||
|
}} catch (err) {_iterator2.e(err);} finally {_iterator2.f();}
|
||||||
|
}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
|
||||||
|
|
||||||
|
return {
|
||||||
|
errors: errors,
|
||||||
|
canDelete: errors.length > 0 };
|
||||||
|
|
||||||
|
};exports.canDeleteModel = canDeleteModel;
|
||||||
|
//# sourceMappingURL=models.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/schema/models.js"],"names":["newModel","id","name","fields","validationRules","primaryField","views","canDeleteModel","models","modelId","errors","model","links","filter","f","type","typeOptions","link","push","canDelete","length"],"mappings":"8HAAA,kC;;AAEO,IAAMA,QAAQ,GAAG,SAAXA,QAAW,WAAO;AAC7BC,IAAAA,EAAE,EAAE,wBADyB;AAE7BC,IAAAA,IAAI,EAAE,EAFuB;AAG7BC,IAAAA,MAAM,EAAE,EAHqB;AAI7BC,IAAAA,eAAe,EAAE,EAJY;AAK7BC,IAAAA,YAAY,EAAE,EALe;AAM7BC,IAAAA,KAAK,EAAE,EANsB,EAAP,EAAjB;;;AASP;;;;;;AAMO,IAAMC,cAAc,GAAG,SAAjBA,cAAiB,CAACC,MAAD,EAASC,OAAT,EAAqB;AACjD,MAAMC,MAAM,GAAG,EAAf,CADiD;;AAG/BF,EAAAA,MAH+B,aAGjD,oDAA0B,KAAjBG,KAAiB;AACxB,UAAMC,KAAK,GAAGD,KAAK,CAACR,MAAN,CAAaU,MAAb;AACZ,gBAAAC,CAAC,UAAIA,CAAC,CAACC,IAAF,KAAW,MAAX,IAAqBD,CAAC,CAACE,WAAF,CAAcP,OAAd,KAA0BA,OAAnD,EADW,CAAd,CADwB;;;AAKPG,MAAAA,KALO,cAKxB,uDAAwB,KAAfK,IAAe;AACtBP,UAAAA,MAAM,CAACQ,IAAP;AACUP,UAAAA,KAAK,CAACT,IADhB,uDAC+De,IAAI,CAACf,IADpE;;AAGD,SATuB;AAUzB,KAbgD;;AAejD,SAAO;AACLQ,IAAAA,MAAM,EAANA,MADK;AAELS,IAAAA,SAAS,EAAET,MAAM,CAACU,MAAP,GAAgB,CAFtB,EAAP;;AAID,CAnBM,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newModel = () => ({\n id: generate(),\n name: \"\",\n fields: [],\n validationRules: [],\n primaryField: \"\",\n views: [],\n})\n\n/**\n *\n * @param {Array} models\n * @param {string} modelId\n * @returns {}\n */\nexport const canDeleteModel = (models, modelId) => {\n const errors = []\n\n for (let model of models) {\n const links = model.fields.filter(\n f => f.type === \"link\" && f.typeOptions.modelId === modelId\n )\n\n for (let link of links) {\n errors.push(\n `The \"${model.name}\" model links to this model, via field \"${link.name}\"`\n )\n }\n }\n\n return {\n errors,\n canDelete: errors.length > 0,\n }\n}\n"],"file":"models.js"}
|
|
@ -0,0 +1,68 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var arrayFunctions = function arrayFunctions() {return (
|
||||||
|
(0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _fp.constant)([]) }));};
|
||||||
|
|
||||||
|
|
||||||
|
var mapToParsedArrary = function mapToParsedArrary(type) {return (
|
||||||
|
(0, _index.$$)(
|
||||||
|
(0, _fp.map)(function (i) {return type.safeParseValue(i);}),
|
||||||
|
_typeHelpers.parsedSuccess));};
|
||||||
|
|
||||||
|
|
||||||
|
var arrayTryParse = function arrayTryParse(type) {return (
|
||||||
|
(0, _index.switchCase)([_fp.isArray, mapToParsedArrary(type)], [_index.defaultCase, _typeHelpers.parsedFailed]));};
|
||||||
|
|
||||||
|
var typeName = function typeName(type) {return "array<".concat(type, ">");};
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
maxLength: {
|
||||||
|
defaultValue: 10000,
|
||||||
|
isValid: _index.isSafeInteger,
|
||||||
|
requirementDescription: "must be a positive integer",
|
||||||
|
parse: _index.toNumberOrNull },
|
||||||
|
|
||||||
|
minLength: {
|
||||||
|
defaultValue: 0,
|
||||||
|
isValid: function isValid(n) {return (0, _index.isSafeInteger)(n) && n >= 0;},
|
||||||
|
requirementDescription: "must be a positive integer",
|
||||||
|
parse: _index.toNumberOrNull } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeConstraints = [
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return val === null || val.length >= opts.minLength;},
|
||||||
|
function (val, opts) {return "must choose ".concat(opts.minLength, " or more options");}),
|
||||||
|
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return val === null || val.length <= opts.maxLength;},
|
||||||
|
function (val, opts) {return "cannot choose more than ".concat(opts.maxLength, " options");})];var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
function _default(type) {return (
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
typeName(type.name),
|
||||||
|
arrayTryParse(type),
|
||||||
|
arrayFunctions(type),
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
[type.sampleValue],
|
||||||
|
JSON.stringify));};exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=array.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/array.js"],"names":["arrayFunctions","mapToParsedArrary","type","i","safeParseValue","parsedSuccess","arrayTryParse","isArray","defaultCase","parsedFailed","typeName","options","maxLength","defaultValue","isValid","isSafeInteger","requirementDescription","parse","toNumberOrNull","minLength","n","typeConstraints","val","opts","length","name","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;;AAQA,IAAMA,cAAc,GAAG,SAAjBA,cAAiB;AACrB,oCAAc;AACZ,iBAAS,kBAAS,EAAT,CADG,EAAd,CADqB,GAAvB;;;AAKA,IAAMC,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,IAAI;AAC5B;AACE,iBAAI,UAAAC,CAAC,UAAID,IAAI,CAACE,cAAL,CAAoBD,CAApB,CAAJ,EAAL,CADF;AAEEE,8BAFF,CAD4B,GAA9B;;;AAMA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAJ,IAAI;AACxB,2BAAW,CAACK,WAAD,EAAUN,iBAAiB,CAACC,IAAD,CAA3B,CAAX,EAA+C,CAACM,kBAAD,EAAcC,yBAAd,CAA/C,CADwB,GAA1B;;AAGA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAAAR,IAAI,0BAAaA,IAAb,QAArB;;AAEA,IAAMS,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,YAAY,EAAE,KADL;AAETC,IAAAA,OAAO,EAAEC,oBAFA;AAGTC,IAAAA,sBAAsB,EAAE,4BAHf;AAITC,IAAAA,KAAK,EAAEC,qBAJE,EADG;;AAOdC,EAAAA,SAAS,EAAE;AACTN,IAAAA,YAAY,EAAE,CADL;AAETC,IAAAA,OAAO,EAAE,iBAAAM,CAAC,UAAI,0BAAcA,CAAd,KAAoBA,CAAC,IAAI,CAA7B,EAFD;AAGTJ,IAAAA,sBAAsB,EAAE,4BAHf;AAITC,IAAAA,KAAK,EAAEC,qBAJE,EAPG,EAAhB;;;;AAeA,IAAMG,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN,UAAeD,GAAG,KAAK,IAAR,IAAgBA,GAAG,CAACE,MAAJ,IAAcD,IAAI,CAACJ,SAAlD,EADF;AAEE,UAACG,GAAD,EAAMC,IAAN,gCAA8BA,IAAI,CAACJ,SAAnC,uBAFF,CADsB;;AAKtB;AACE,UAACG,GAAD,EAAMC,IAAN,UAAeD,GAAG,KAAK,IAAR,IAAgBA,GAAG,CAACE,MAAJ,IAAcD,IAAI,CAACX,SAAlD,EADF;AAEE,UAACU,GAAD,EAAMC,IAAN,4CAA0CA,IAAI,CAACX,SAA/C,eAFF,CALsB,CAAxB,C;;;;AAWe,kBAAAV,IAAI;AACjB;AACEQ,IAAAA,QAAQ,CAACR,IAAI,CAACuB,IAAN,CADV;AAEEnB,IAAAA,aAAa,CAACJ,IAAD,CAFf;AAGEF,IAAAA,cAAc,CAACE,IAAD,CAHhB;AAIES,IAAAA,OAJF;AAKEU,IAAAA,eALF;AAME,KAACnB,IAAI,CAACwB,WAAN,CANF;AAOEC,IAAAA,IAAI,CAACC,SAPP,CADiB,G","sourcesContent":["import { map, constant, isArray } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedFailed,\n getDefaultExport,\n parsedSuccess,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toNumberOrNull,\n $$,\n isSafeInteger,\n} from \"../../common/index.js\"\n\nconst arrayFunctions = () =>\n typeFunctions({\n default: constant([]),\n })\n\nconst mapToParsedArrary = type =>\n $$(\n map(i => type.safeParseValue(i)),\n parsedSuccess\n )\n\nconst arrayTryParse = type =>\n switchCase([isArray, mapToParsedArrary(type)], [defaultCase, parsedFailed])\n\nconst typeName = type => `array<${type}>`\n\nconst options = {\n maxLength: {\n defaultValue: 10000,\n isValid: isSafeInteger,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n minLength: {\n defaultValue: 0,\n isValid: n => isSafeInteger(n) && n >= 0,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) => val === null || val.length >= opts.minLength,\n (val, opts) => `must choose ${opts.minLength} or more options`\n ),\n makerule(\n (val, opts) => val === null || val.length <= opts.maxLength,\n (val, opts) => `cannot choose more than ${opts.maxLength} options`\n ),\n]\n\nexport default type =>\n getDefaultExport(\n typeName(type.name),\n arrayTryParse(type),\n arrayFunctions(type),\n options,\n typeConstraints,\n [type.sampleValue],\n JSON.stringify\n )\n"],"file":"array.js"}
|
|
@ -0,0 +1,52 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var boolFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _fp.constant)(null) });
|
||||||
|
|
||||||
|
|
||||||
|
var boolTryParse = (0, _index.switchCase)(
|
||||||
|
[_fp.isBoolean, _typeHelpers.parsedSuccess],
|
||||||
|
[_fp.isNull, _typeHelpers.parsedSuccess],
|
||||||
|
[(0, _index.isOneOf)("true", "1", "yes", "on"), function () {return (0, _typeHelpers.parsedSuccess)(true);}],
|
||||||
|
[(0, _index.isOneOf)("false", "0", "no", "off"), function () {return (0, _typeHelpers.parsedSuccess)(false);}],
|
||||||
|
[_index.defaultCase, _typeHelpers.parsedFailed]);
|
||||||
|
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
allowNulls: {
|
||||||
|
defaultValue: true,
|
||||||
|
isValid: _fp.isBoolean,
|
||||||
|
requirementDescription: "must be a true or false",
|
||||||
|
parse: _index.toBoolOrNull } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeConstraints = [
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return opts.allowNulls === true || val !== null;},
|
||||||
|
function () {return "field cannot be null";})];var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"bool",
|
||||||
|
boolTryParse,
|
||||||
|
boolFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
true,
|
||||||
|
JSON.stringify);exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=bool.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/bool.js"],"names":["boolFunctions","boolTryParse","isBoolean","parsedSuccess","isNull","defaultCase","parsedFailed","options","allowNulls","defaultValue","isValid","requirementDescription","parse","toBoolOrNull","typeConstraints","val","opts","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;AAOA,IAAMA,aAAa,GAAG,gCAAc;AAClC,aAAS,kBAAS,IAAT,CADyB,EAAd,CAAtB;;;AAIA,IAAMC,YAAY,GAAG;AACnB,CAACC,aAAD,EAAYC,0BAAZ,CADmB;AAEnB,CAACC,UAAD,EAASD,0BAAT,CAFmB;AAGnB,CAAC,oBAAQ,MAAR,EAAgB,GAAhB,EAAqB,KAArB,EAA4B,IAA5B,CAAD,EAAoC,oBAAM,gCAAc,IAAd,CAAN,EAApC,CAHmB;AAInB,CAAC,oBAAQ,OAAR,EAAiB,GAAjB,EAAsB,IAAtB,EAA4B,KAA5B,CAAD,EAAqC,oBAAM,gCAAc,KAAd,CAAN,EAArC,CAJmB;AAKnB,CAACE,kBAAD,EAAcC,yBAAd,CALmB,CAArB;;;AAQA,IAAMC,OAAO,GAAG;AACdC,EAAAA,UAAU,EAAE;AACVC,IAAAA,YAAY,EAAE,IADJ;AAEVC,IAAAA,OAAO,EAAER,aAFC;AAGVS,IAAAA,sBAAsB,EAAE,yBAHd;AAIVC,IAAAA,KAAK,EAAEC,mBAJG,EADE,EAAhB;;;;AASA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN,UAAeA,IAAI,CAACR,UAAL,KAAoB,IAApB,IAA4BO,GAAG,KAAK,IAAnD,EADF;AAEE,oBAAM,sBAAN,EAFF,CADsB,CAAxB,C;;;;AAOe;AACb,MADa;AAEbd,YAFa;AAGbD,aAHa;AAIbO,OAJa;AAKbO,eALa;AAMb,IANa;AAObG,IAAI,CAACC,SAPQ,C","sourcesContent":["import { constant, isBoolean, isNull } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n isOneOf,\n toBoolOrNull,\n} from \"../../common/index.js\"\n\nconst boolFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst boolTryParse = switchCase(\n [isBoolean, parsedSuccess],\n [isNull, parsedSuccess],\n [isOneOf(\"true\", \"1\", \"yes\", \"on\"), () => parsedSuccess(true)],\n [isOneOf(\"false\", \"0\", \"no\", \"off\"), () => parsedSuccess(false)],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n allowNulls: {\n defaultValue: true,\n isValid: isBoolean,\n requirementDescription: \"must be a true or false\",\n parse: toBoolOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) => opts.allowNulls === true || val !== null,\n () => \"field cannot be null\"\n ),\n]\n\nexport default getDefaultExport(\n \"bool\",\n boolTryParse,\n boolFunctions,\n options,\n typeConstraints,\n true,\n JSON.stringify\n)\n"],"file":"bool.js"}
|
|
@ -0,0 +1,78 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _common = require("../../common");
|
||||||
|
|
||||||
|
var dateFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _fp.constant)(null),
|
||||||
|
now: function now() {return new Date();} });
|
||||||
|
|
||||||
|
|
||||||
|
var isValidDate = function isValidDate(d) {return d instanceof Date && !isNaN(d);};
|
||||||
|
|
||||||
|
var parseStringToDate = function parseStringToDate(s) {return (
|
||||||
|
(0, _common.switchCase)(
|
||||||
|
[isValidDate, _typeHelpers.parsedSuccess],
|
||||||
|
[_common.defaultCase, _typeHelpers.parsedFailed])(
|
||||||
|
new Date(s)));};
|
||||||
|
|
||||||
|
var isNullOrEmpty = function isNullOrEmpty(d) {return (0, _fp.isNull)(d) || (d || "").toString() === "";};
|
||||||
|
|
||||||
|
var isDateOrEmpty = function isDateOrEmpty(d) {return (0, _fp.isDate)(d) || isNullOrEmpty(d);};
|
||||||
|
|
||||||
|
var dateTryParse = (0, _common.switchCase)(
|
||||||
|
[isDateOrEmpty, _typeHelpers.parsedSuccess],
|
||||||
|
[_fp.isString, parseStringToDate],
|
||||||
|
[_common.defaultCase, _typeHelpers.parsedFailed]);
|
||||||
|
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
maxValue: {
|
||||||
|
defaultValue: null,
|
||||||
|
//defaultValue: new Date(32503680000000),
|
||||||
|
isValid: isDateOrEmpty,
|
||||||
|
requirementDescription: "must be a valid date",
|
||||||
|
parse: _common.toDateOrNull },
|
||||||
|
|
||||||
|
minValue: {
|
||||||
|
defaultValue: null,
|
||||||
|
//defaultValue: new Date(-8520336000000),
|
||||||
|
isValid: isDateOrEmpty,
|
||||||
|
requirementDescription: "must be a valid date",
|
||||||
|
parse: _common.toDateOrNull } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeConstraints = [
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || isNullOrEmpty(opts.minValue) || val >= opts.minValue);},
|
||||||
|
function (val, opts) {return "value (".concat(
|
||||||
|
val.toString(), ") must be greater than or equal to ").concat(
|
||||||
|
opts.minValue);}),
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || isNullOrEmpty(opts.maxValue) || val <= opts.maxValue);},
|
||||||
|
function (val, opts) {return "value (".concat(
|
||||||
|
val.toString(), ") must be less than or equal to ").concat(
|
||||||
|
opts.minValue, " options");})];var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"datetime",
|
||||||
|
dateTryParse,
|
||||||
|
dateFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
new Date(1984, 4, 1),
|
||||||
|
function (date) {return JSON.stringify(date).replace(new RegExp('"', "g"), "");});exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=datetime.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/datetime.js"],"names":["dateFunctions","now","Date","isValidDate","d","isNaN","parseStringToDate","s","parsedSuccess","defaultCase","parsedFailed","isNullOrEmpty","toString","isDateOrEmpty","dateTryParse","isString","options","maxValue","defaultValue","isValid","requirementDescription","parse","toDateOrNull","minValue","typeConstraints","val","opts","date","JSON","stringify","replace","RegExp"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;AAEA,IAAMA,aAAa,GAAG,gCAAc;AAClC,aAAS,kBAAS,IAAT,CADyB;AAElCC,EAAAA,GAAG,EAAE,uBAAM,IAAIC,IAAJ,EAAN,EAF6B,EAAd,CAAtB;;;AAKA,IAAMC,WAAW,GAAG,SAAdA,WAAc,CAAAC,CAAC,UAAIA,CAAC,YAAYF,IAAb,IAAqB,CAACG,KAAK,CAACD,CAAD,CAA/B,EAArB;;AAEA,IAAME,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,CAAC;AACzB;AACE,KAACJ,WAAD,EAAcK,0BAAd,CADF;AAEE,KAACC,mBAAD,EAAcC,yBAAd,CAFF;AAGE,QAAIR,IAAJ,CAASK,CAAT,CAHF,CADyB,GAA3B;;AAMA,IAAMI,aAAa,GAAG,SAAhBA,aAAgB,CAAAP,CAAC,UAAI,gBAAOA,CAAP,KAAa,CAACA,CAAC,IAAI,EAAN,EAAUQ,QAAV,OAAyB,EAA1C,EAAvB;;AAEA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAT,CAAC,UAAI,gBAAOA,CAAP,KAAaO,aAAa,CAACP,CAAD,CAA9B,EAAvB;;AAEA,IAAMU,YAAY,GAAG;AACnB,CAACD,aAAD,EAAgBL,0BAAhB,CADmB;AAEnB,CAACO,YAAD,EAAWT,iBAAX,CAFmB;AAGnB,CAACG,mBAAD,EAAcC,yBAAd,CAHmB,CAArB;;;AAMA,IAAMM,OAAO,GAAG;AACdC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,YAAY,EAAE,IADN;AAER;AACAC,IAAAA,OAAO,EAAEN,aAHD;AAIRO,IAAAA,sBAAsB,EAAE,sBAJhB;AAKRC,IAAAA,KAAK,EAAEC,oBALC,EADI;;AAQdC,EAAAA,QAAQ,EAAE;AACRL,IAAAA,YAAY,EAAE,IADN;AAER;AACAC,IAAAA,OAAO,EAAEN,aAHD;AAIRO,IAAAA,sBAAsB,EAAE,sBAJhB;AAKRC,IAAAA,KAAK,EAAEC,oBALC,EARI,EAAhB;;;;AAiBA,IAAME,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBd,aAAa,CAACe,IAAI,CAACH,QAAN,CAA7B,IAAgDE,GAAG,IAAIC,IAAI,CAACH,QAD9D,GADF;AAGE,UAACE,GAAD,EAAMC,IAAN;AACYD,EAAAA,GAAG,CAACb,QAAJ,EADZ;AAEIc,EAAAA,IAAI,CAACH,QAFT,GAHF,CADsB;;;AAStB;AACE,UAACE,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBd,aAAa,CAACe,IAAI,CAACT,QAAN,CAA7B,IAAgDQ,GAAG,IAAIC,IAAI,CAACT,QAD9D,GADF;AAGE,UAACQ,GAAD,EAAMC,IAAN;AACYD,EAAAA,GAAG,CAACb,QAAJ,EADZ;AAEIc,EAAAA,IAAI,CAACH,QAFT,eAHF,CATsB,CAAxB,C;;;;;AAmBe;AACb,UADa;AAEbT,YAFa;AAGbd,aAHa;AAIbgB,OAJa;AAKbQ,eALa;AAMb,IAAItB,IAAJ,CAAS,IAAT,EAAe,CAAf,EAAkB,CAAlB,CANa;AAOb,UAAAyB,IAAI,UAAIC,IAAI,CAACC,SAAL,CAAeF,IAAf,EAAqBG,OAArB,CAA6B,IAAIC,MAAJ,CAAW,GAAX,EAAgB,GAAhB,CAA7B,EAAmD,EAAnD,CAAJ,EAPS,C","sourcesContent":["import { constant, isDate, isString, isNull } from \"lodash/fp\"\nimport {\n makerule,\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport { switchCase, defaultCase, toDateOrNull } from \"../../common\"\n\nconst dateFunctions = typeFunctions({\n default: constant(null),\n now: () => new Date(),\n})\n\nconst isValidDate = d => d instanceof Date && !isNaN(d)\n\nconst parseStringToDate = s =>\n switchCase(\n [isValidDate, parsedSuccess],\n [defaultCase, parsedFailed]\n )(new Date(s))\n\nconst isNullOrEmpty = d => isNull(d) || (d || \"\").toString() === \"\"\n\nconst isDateOrEmpty = d => isDate(d) || isNullOrEmpty(d)\n\nconst dateTryParse = switchCase(\n [isDateOrEmpty, parsedSuccess],\n [isString, parseStringToDate],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n maxValue: {\n defaultValue: null,\n //defaultValue: new Date(32503680000000),\n isValid: isDateOrEmpty,\n requirementDescription: \"must be a valid date\",\n parse: toDateOrNull,\n },\n minValue: {\n defaultValue: null,\n //defaultValue: new Date(-8520336000000),\n isValid: isDateOrEmpty,\n requirementDescription: \"must be a valid date\",\n parse: toDateOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || isNullOrEmpty(opts.minValue) || val >= opts.minValue,\n (val, opts) =>\n `value (${val.toString()}) must be greater than or equal to ${\n opts.minValue\n }`\n ),\n makerule(\n (val, opts) =>\n val === null || isNullOrEmpty(opts.maxValue) || val <= opts.maxValue,\n (val, opts) =>\n `value (${val.toString()}) must be less than or equal to ${\n opts.minValue\n } options`\n ),\n]\n\nexport default getDefaultExport(\n \"datetime\",\n dateTryParse,\n dateFunctions,\n options,\n typeConstraints,\n new Date(1984, 4, 1),\n date => JSON.stringify(date).replace(new RegExp('\"', \"g\"), \"\")\n)\n"],"file":"datetime.js"}
|
|
@ -0,0 +1,62 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.isLegalFilename = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var illegalCharacters = "*?\\/:<>|\0\b\f\v";
|
||||||
|
|
||||||
|
var isLegalFilename = function isLegalFilename(filePath) {
|
||||||
|
var fn = fileName(filePath);
|
||||||
|
return (
|
||||||
|
fn.length <= 255 &&
|
||||||
|
(0, _fp.intersection)(fn.split(""))(illegalCharacters.split("")).length === 0 &&
|
||||||
|
(0, _index.none)(function (f) {return f === "..";})((0, _index.splitKey)(filePath)));
|
||||||
|
|
||||||
|
};exports.isLegalFilename = isLegalFilename;
|
||||||
|
|
||||||
|
var fileNothing = function fileNothing() {return { relativePath: "", size: 0 };};
|
||||||
|
|
||||||
|
var fileFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": fileNothing });
|
||||||
|
|
||||||
|
|
||||||
|
var fileTryParse = function fileTryParse(v) {return (
|
||||||
|
(0, _index.switchCase)(
|
||||||
|
[isValidFile, _typeHelpers.parsedSuccess],
|
||||||
|
[_fp.isNull, function () {return (0, _typeHelpers.parsedSuccess)(fileNothing());}],
|
||||||
|
[_index.defaultCase, _typeHelpers.parsedFailed])(
|
||||||
|
v));};
|
||||||
|
|
||||||
|
var fileName = function fileName(filePath) {return (0, _index.$)(filePath, [_index.splitKey, _fp.last]);};
|
||||||
|
|
||||||
|
var isValidFile = function isValidFile(f) {return (
|
||||||
|
!(0, _fp.isNull)(f) &&
|
||||||
|
(0, _fp.has)("relativePath")(f) &&
|
||||||
|
(0, _fp.has)("size")(f) &&
|
||||||
|
(0, _fp.isNumber)(f.size) &&
|
||||||
|
(0, _fp.isString)(f.relativePath) &&
|
||||||
|
isLegalFilename(f.relativePath));};
|
||||||
|
|
||||||
|
var options = {};
|
||||||
|
|
||||||
|
var typeConstraints = [];var _default =
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"file",
|
||||||
|
fileTryParse,
|
||||||
|
fileFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
{ relativePath: "some_file.jpg", size: 1000 },
|
||||||
|
JSON.stringify);exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=file.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/file.js"],"names":["illegalCharacters","isLegalFilename","filePath","fn","fileName","length","split","f","fileNothing","relativePath","size","fileFunctions","fileTryParse","v","isValidFile","parsedSuccess","isNull","defaultCase","parsedFailed","splitKey","last","options","typeConstraints","JSON","stringify"],"mappings":"iIAAA;AACA;;;;;;AAMA;;;;;;;;AAQA,IAAMA,iBAAiB,GAAG,mBAA1B;;AAEO,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAAAC,QAAQ,EAAI;AACzC,MAAMC,EAAE,GAAGC,QAAQ,CAACF,QAAD,CAAnB;AACA;AACEC,IAAAA,EAAE,CAACE,MAAH,IAAa,GAAb;AACA,0BAAaF,EAAE,CAACG,KAAH,CAAS,EAAT,CAAb,EAA2BN,iBAAiB,CAACM,KAAlB,CAAwB,EAAxB,CAA3B,EAAwDD,MAAxD,KAAmE,CADnE;AAEA,qBAAK,UAAAE,CAAC,UAAIA,CAAC,KAAK,IAAV,EAAN,EAAsB,qBAASL,QAAT,CAAtB,CAHF;;AAKD,CAPM,C;;AASP,IAAMM,WAAW,GAAG,SAAdA,WAAc,WAAO,EAAEC,YAAY,EAAE,EAAhB,EAAoBC,IAAI,EAAE,CAA1B,EAAP,EAApB;;AAEA,IAAMC,aAAa,GAAG,gCAAc;AAClC,aAASH,WADyB,EAAd,CAAtB;;;AAIA,IAAMI,YAAY,GAAG,SAAfA,YAAe,CAAAC,CAAC;AACpB;AACE,KAACC,WAAD,EAAcC,0BAAd,CADF;AAEE,KAACC,UAAD,EAAS,oBAAM,gCAAcR,WAAW,EAAzB,CAAN,EAAT,CAFF;AAGE,KAACS,kBAAD,EAAcC,yBAAd,CAHF;AAIEL,IAAAA,CAJF,CADoB,GAAtB;;AAOA,IAAMT,QAAQ,GAAG,SAAXA,QAAW,CAAAF,QAAQ,UAAI,cAAEA,QAAF,EAAY,CAACiB,eAAD,EAAWC,QAAX,CAAZ,CAAJ,EAAzB;;AAEA,IAAMN,WAAW,GAAG,SAAdA,WAAc,CAAAP,CAAC;AACnB,KAAC,gBAAOA,CAAP,CAAD;AACA,iBAAI,cAAJ,EAAoBA,CAApB,CADA;AAEA,iBAAI,MAAJ,EAAYA,CAAZ,CAFA;AAGA,sBAASA,CAAC,CAACG,IAAX,CAHA;AAIA,sBAASH,CAAC,CAACE,YAAX,CAJA;AAKAR,IAAAA,eAAe,CAACM,CAAC,CAACE,YAAH,CANI,GAArB;;AAQA,IAAMY,OAAO,GAAG,EAAhB;;AAEA,IAAMC,eAAe,GAAG,EAAxB,C;;AAEe;AACb,MADa;AAEbV,YAFa;AAGbD,aAHa;AAIbU,OAJa;AAKbC,eALa;AAMb,EAAEb,YAAY,EAAE,eAAhB,EAAiCC,IAAI,EAAE,IAAvC,EANa;AAOba,IAAI,CAACC,SAPQ,C","sourcesContent":["import { last, has, isString, intersection, isNull, isNumber } from \"lodash/fp\"\nimport {\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n none,\n $,\n splitKey,\n} from \"../../common/index.js\"\n\nconst illegalCharacters = \"*?\\\\/:<>|\\0\\b\\f\\v\"\n\nexport const isLegalFilename = filePath => {\n const fn = fileName(filePath)\n return (\n fn.length <= 255 &&\n intersection(fn.split(\"\"))(illegalCharacters.split(\"\")).length === 0 &&\n none(f => f === \"..\")(splitKey(filePath))\n )\n}\n\nconst fileNothing = () => ({ relativePath: \"\", size: 0 })\n\nconst fileFunctions = typeFunctions({\n default: fileNothing,\n})\n\nconst fileTryParse = v =>\n switchCase(\n [isValidFile, parsedSuccess],\n [isNull, () => parsedSuccess(fileNothing())],\n [defaultCase, parsedFailed]\n )(v)\n\nconst fileName = filePath => $(filePath, [splitKey, last])\n\nconst isValidFile = f =>\n !isNull(f) &&\n has(\"relativePath\")(f) &&\n has(\"size\")(f) &&\n isNumber(f.size) &&\n isString(f.relativePath) &&\n isLegalFilename(f.relativePath)\n\nconst options = {}\n\nconst typeConstraints = []\n\nexport default getDefaultExport(\n \"file\",\n fileTryParse,\n fileFunctions,\n options,\n typeConstraints,\n { relativePath: \"some_file.jpg\", size: 1000 },\n JSON.stringify\n)\n"],"file":"file.js"}
|
|
@ -0,0 +1,85 @@
|
||||||
|
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.detectType = exports.validateTypeConstraints = exports.getDefaultOptions = exports.validateFieldParse = exports.safeParseField = exports.getNewFieldValue = exports.getSampleFieldValue = exports.getType = exports.all = void 0;var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _lodash = require("lodash");
|
||||||
|
var _fp = require("lodash/fp");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _common = require("../../common");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
var _string = _interopRequireDefault(require("./string"));
|
||||||
|
var _bool = _interopRequireDefault(require("./bool"));
|
||||||
|
var _number = _interopRequireDefault(require("./number"));
|
||||||
|
var _datetime = _interopRequireDefault(require("./datetime"));
|
||||||
|
var _array = _interopRequireDefault(require("./array"));
|
||||||
|
var _link = _interopRequireDefault(require("./link"));
|
||||||
|
var _file = _interopRequireDefault(require("./file"));
|
||||||
|
var _errors = require("../../common/errors");
|
||||||
|
|
||||||
|
var allTypes = function allTypes() {
|
||||||
|
var basicTypes = {
|
||||||
|
string: _string["default"],
|
||||||
|
number: _number["default"],
|
||||||
|
datetime: _datetime["default"],
|
||||||
|
bool: _bool["default"],
|
||||||
|
link: _link["default"],
|
||||||
|
file: _file["default"] };
|
||||||
|
|
||||||
|
|
||||||
|
var arrays = (0, _common.$)(basicTypes, [
|
||||||
|
_fp.keys,
|
||||||
|
(0, _fp.map)(function (k) {
|
||||||
|
var kvType = {};
|
||||||
|
var concreteArray = (0, _array["default"])(basicTypes[k]);
|
||||||
|
kvType[concreteArray.name] = concreteArray;
|
||||||
|
return kvType;
|
||||||
|
}),
|
||||||
|
function (types) {return _lodash.assign.apply(void 0, [{}].concat((0, _toConsumableArray2["default"])(types)));}]);
|
||||||
|
|
||||||
|
|
||||||
|
return (0, _lodash.merge)({}, basicTypes, arrays);
|
||||||
|
};
|
||||||
|
|
||||||
|
var all = allTypes();exports.all = all;
|
||||||
|
|
||||||
|
var getType = function getType(typeName) {
|
||||||
|
if (!(0, _fp.has)(typeName)(all))
|
||||||
|
throw new _errors.BadRequestError("Do not recognise type ".concat(typeName));
|
||||||
|
return all[typeName];
|
||||||
|
};exports.getType = getType;
|
||||||
|
|
||||||
|
var getSampleFieldValue = function getSampleFieldValue(field) {return getType(field.type).sampleValue;};exports.getSampleFieldValue = getSampleFieldValue;
|
||||||
|
|
||||||
|
var getNewFieldValue = function getNewFieldValue(field) {return getType(field.type).getNew(field);};exports.getNewFieldValue = getNewFieldValue;
|
||||||
|
|
||||||
|
var safeParseField = function safeParseField(field, record) {return (
|
||||||
|
getType(field.type).safeParseField(field, record));};exports.safeParseField = safeParseField;
|
||||||
|
|
||||||
|
var validateFieldParse = function validateFieldParse(field, record) {return (
|
||||||
|
(0, _fp.has)(field.name)(record) ?
|
||||||
|
getType(field.type).tryParse(record[field.name]) :
|
||||||
|
(0, _typeHelpers.parsedSuccess)(undefined));}; // fields may be undefined by default
|
||||||
|
exports.validateFieldParse = validateFieldParse;
|
||||||
|
var getDefaultOptions = function getDefaultOptions(type) {return getType(type).getDefaultOptions();};exports.getDefaultOptions = getDefaultOptions;
|
||||||
|
|
||||||
|
var validateTypeConstraints = function validateTypeConstraints(field, record) {return (
|
||||||
|
getType(field.type).validateTypeConstraints(field, record));};exports.validateTypeConstraints = validateTypeConstraints;
|
||||||
|
|
||||||
|
var detectType = function detectType(value) {
|
||||||
|
if ((0, _fp.isString)(value)) return _string["default"];
|
||||||
|
if ((0, _fp.isBoolean)(value)) return _bool["default"];
|
||||||
|
if ((0, _fp.isNumber)(value)) return _number["default"];
|
||||||
|
if ((0, _fp.isDate)(value)) return _datetime["default"];
|
||||||
|
if ((0, _fp.isArray)(value)) return (0, _array["default"])(detectType(value[0]));
|
||||||
|
if ((0, _fp.isObject)(value) && (0, _fp.has)("key")(value) && (0, _fp.has)("value")(value)) return _link["default"];
|
||||||
|
if ((0, _fp.isObject)(value) && (0, _fp.has)("relativePath")(value) && (0, _fp.has)("size")(value))
|
||||||
|
return _file["default"];
|
||||||
|
|
||||||
|
throw new _errors.BadRequestError("cannot determine type: ".concat(JSON.stringify(value)));
|
||||||
|
};exports.detectType = detectType;
|
||||||
|
//# sourceMappingURL=index.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,42 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var linkNothing = function linkNothing() {return "";};
|
||||||
|
|
||||||
|
var linkFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": linkNothing });
|
||||||
|
|
||||||
|
|
||||||
|
var linkTryParse = function linkTryParse(v) {return (
|
||||||
|
(0, _index.switchCase)(
|
||||||
|
[_fp.isString, function (s) {return (0, _typeHelpers.parsedSuccess)(s);}],
|
||||||
|
[_fp.isNull, function () {return (0, _typeHelpers.parsedSuccess)(linkNothing());}],
|
||||||
|
[_fp.isUndefined, function () {return (0, _typeHelpers.parsedSuccess)(linkNothing());}],
|
||||||
|
[_index.defaultCase, function (s) {return (0, _typeHelpers.parsedSuccess)(s.toString());}])(
|
||||||
|
v));};
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
modelId: {
|
||||||
|
defaultValue: "",
|
||||||
|
isValid: _index.isNonEmptyString,
|
||||||
|
requirementDescription: "must choose a model",
|
||||||
|
parse: function parse(s) {return s;} } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeConstraints = [];var _default =
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"link",
|
||||||
|
linkTryParse,
|
||||||
|
linkFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
"abcd1234",
|
||||||
|
JSON.stringify);exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=link.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/link.js"],"names":["linkNothing","linkFunctions","linkTryParse","v","isString","s","isNull","isUndefined","defaultCase","toString","options","modelId","defaultValue","isValid","isNonEmptyString","requirementDescription","parse","typeConstraints","JSON","stringify"],"mappings":"uGAAA;AACA;AACA;;;;;;AAMA,IAAMA,WAAW,GAAG,SAAdA,WAAc,WAAM,EAAN,EAApB;;AAEA,IAAMC,aAAa,GAAG,gCAAc;AAClC,aAASD,WADyB,EAAd,CAAtB;;;AAIA,IAAME,YAAY,GAAG,SAAfA,YAAe,CAAAC,CAAC;AACpB;AACE,KAACC,YAAD,EAAW,UAAAC,CAAC,UAAI,gCAAcA,CAAd,CAAJ,EAAZ,CADF;AAEE,KAACC,UAAD,EAAS,oBAAM,gCAAcN,WAAW,EAAzB,CAAN,EAAT,CAFF;AAGE,KAACO,eAAD,EAAc,oBAAM,gCAAcP,WAAW,EAAzB,CAAN,EAAd,CAHF;AAIE,KAACQ,kBAAD,EAAc,UAAAH,CAAC,UAAI,gCAAcA,CAAC,CAACI,QAAF,EAAd,CAAJ,EAAf,CAJF;AAKEN,IAAAA,CALF,CADoB,GAAtB;;AAQA,IAAMO,OAAO,GAAG;AACdC,EAAAA,OAAO,EAAE;AACPC,IAAAA,YAAY,EAAE,EADP;AAEPC,IAAAA,OAAO,EAAEC,uBAFF;AAGPC,IAAAA,sBAAsB,EAAE,qBAHjB;AAIPC,IAAAA,KAAK,EAAE,eAAAX,CAAC,UAAIA,CAAJ,EAJD,EADK,EAAhB;;;;AASA,IAAMY,eAAe,GAAG,EAAxB,C;;AAEe;AACb,MADa;AAEbf,YAFa;AAGbD,aAHa;AAIbS,OAJa;AAKbO,eALa;AAMb,UANa;AAObC,IAAI,CAACC,SAPQ,C","sourcesContent":["import { isString, isUndefined, isNull } from \"lodash/fp\"\nimport { typeFunctions, parsedSuccess, getDefaultExport } from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n isNonEmptyString,\n} from \"../../common/index.js\"\n\nconst linkNothing = () => \"\"\n\nconst linkFunctions = typeFunctions({\n default: linkNothing,\n})\n\nconst linkTryParse = v =>\n switchCase(\n [isString, s => parsedSuccess(s)],\n [isNull, () => parsedSuccess(linkNothing())],\n [isUndefined, () => parsedSuccess(linkNothing())],\n [defaultCase, s => parsedSuccess(s.toString())]\n )(v)\n\nconst options = {\n modelId: {\n defaultValue: \"\",\n isValid: isNonEmptyString,\n requirementDescription: \"must choose a model\",\n parse: s => s,\n },\n}\n\nconst typeConstraints = []\n\nexport default getDefaultExport(\n \"link\",\n linkTryParse,\n linkFunctions,\n options,\n typeConstraints,\n \"abcd1234\",\n JSON.stringify\n)\n"],"file":"link.js"}
|
|
@ -0,0 +1,94 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var numberFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _fp.constant)(null) });
|
||||||
|
|
||||||
|
|
||||||
|
var parseStringtoNumberOrNull = function parseStringtoNumberOrNull(s) {
|
||||||
|
var num = Number(s);
|
||||||
|
return isNaN(num) ? (0, _typeHelpers.parsedFailed)(s) : (0, _typeHelpers.parsedSuccess)(num);
|
||||||
|
};
|
||||||
|
|
||||||
|
var numberTryParse = (0, _index.switchCase)(
|
||||||
|
[_fp.isNumber, _typeHelpers.parsedSuccess],
|
||||||
|
[_fp.isString, parseStringtoNumberOrNull],
|
||||||
|
[_fp.isNull, _typeHelpers.parsedSuccess],
|
||||||
|
[_index.defaultCase, _typeHelpers.parsedFailed]);
|
||||||
|
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
maxValue: {
|
||||||
|
defaultValue: Number.MAX_SAFE_INTEGER,
|
||||||
|
isValid: _index.isSafeInteger,
|
||||||
|
requirementDescription: "must be a valid integer",
|
||||||
|
parse: _index.toNumberOrNull },
|
||||||
|
|
||||||
|
minValue: {
|
||||||
|
defaultValue: 0 - Number.MAX_SAFE_INTEGER,
|
||||||
|
isValid: _index.isSafeInteger,
|
||||||
|
requirementDescription: "must be a valid integer",
|
||||||
|
parse: _index.toNumberOrNull },
|
||||||
|
|
||||||
|
decimalPlaces: {
|
||||||
|
defaultValue: 0,
|
||||||
|
isValid: function isValid(n) {return (0, _index.isSafeInteger)(n) && n >= 0;},
|
||||||
|
requirementDescription: "must be a positive integer",
|
||||||
|
parse: _index.toNumberOrNull } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var getDecimalPlaces = function getDecimalPlaces(val) {
|
||||||
|
var splitDecimal = val.toString().split(".");
|
||||||
|
if (splitDecimal.length === 1) return 0;
|
||||||
|
return splitDecimal[1].length;
|
||||||
|
};
|
||||||
|
|
||||||
|
var typeConstraints = [
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || opts.minValue === null || val >= opts.minValue);},
|
||||||
|
function (val, opts) {return "value (".concat(
|
||||||
|
val.toString(), ") must be greater than or equal to ").concat(
|
||||||
|
opts.minValue);}),
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || opts.maxValue === null || val <= opts.maxValue);},
|
||||||
|
function (val, opts) {return "value (".concat(
|
||||||
|
val.toString(), ") must be less than or equal to ").concat(
|
||||||
|
opts.minValue, " options");}),
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || opts.decimalPlaces >= getDecimalPlaces(val));},
|
||||||
|
function (val, opts) {return "value (".concat(
|
||||||
|
val.toString(), ") must have ").concat(
|
||||||
|
opts.decimalPlaces, " decimal places or less");})];var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"number",
|
||||||
|
numberTryParse,
|
||||||
|
numberFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
1,
|
||||||
|
function (num) {return num.toString();});exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=number.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/number.js"],"names":["numberFunctions","parseStringtoNumberOrNull","s","num","Number","isNaN","numberTryParse","isNumber","parsedSuccess","isString","isNull","defaultCase","parsedFailed","options","maxValue","defaultValue","MAX_SAFE_INTEGER","isValid","isSafeInteger","requirementDescription","parse","toNumberOrNull","minValue","decimalPlaces","n","getDecimalPlaces","val","splitDecimal","toString","split","length","typeConstraints","opts"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;AAOA,IAAMA,eAAe,GAAG,gCAAc;AACpC,aAAS,kBAAS,IAAT,CAD2B,EAAd,CAAxB;;;AAIA,IAAMC,yBAAyB,GAAG,SAA5BA,yBAA4B,CAAAC,CAAC,EAAI;AACrC,MAAMC,GAAG,GAAGC,MAAM,CAACF,CAAD,CAAlB;AACA,SAAOG,KAAK,CAACF,GAAD,CAAL,GAAa,+BAAaD,CAAb,CAAb,GAA+B,gCAAcC,GAAd,CAAtC;AACD,CAHD;;AAKA,IAAMG,cAAc,GAAG;AACrB,CAACC,YAAD,EAAWC,0BAAX,CADqB;AAErB,CAACC,YAAD,EAAWR,yBAAX,CAFqB;AAGrB,CAACS,UAAD,EAASF,0BAAT,CAHqB;AAIrB,CAACG,kBAAD,EAAcC,yBAAd,CAJqB,CAAvB;;;AAOA,IAAMC,OAAO,GAAG;AACdC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,YAAY,EAAEX,MAAM,CAACY,gBADb;AAERC,IAAAA,OAAO,EAAEC,oBAFD;AAGRC,IAAAA,sBAAsB,EAAE,yBAHhB;AAIRC,IAAAA,KAAK,EAAEC,qBAJC,EADI;;AAOdC,EAAAA,QAAQ,EAAE;AACRP,IAAAA,YAAY,EAAE,IAAIX,MAAM,CAACY,gBADjB;AAERC,IAAAA,OAAO,EAAEC,oBAFD;AAGRC,IAAAA,sBAAsB,EAAE,yBAHhB;AAIRC,IAAAA,KAAK,EAAEC,qBAJC,EAPI;;AAadE,EAAAA,aAAa,EAAE;AACbR,IAAAA,YAAY,EAAE,CADD;AAEbE,IAAAA,OAAO,EAAE,iBAAAO,CAAC,UAAI,0BAAcA,CAAd,KAAoBA,CAAC,IAAI,CAA7B,EAFG;AAGbL,IAAAA,sBAAsB,EAAE,4BAHX;AAIbC,IAAAA,KAAK,EAAEC,qBAJM,EAbD,EAAhB;;;;AAqBA,IAAMI,gBAAgB,GAAG,SAAnBA,gBAAmB,CAAAC,GAAG,EAAI;AAC9B,MAAMC,YAAY,GAAGD,GAAG,CAACE,QAAJ,GAAeC,KAAf,CAAqB,GAArB,CAArB;AACA,MAAIF,YAAY,CAACG,MAAb,KAAwB,CAA5B,EAA+B,OAAO,CAAP;AAC/B,SAAOH,YAAY,CAAC,CAAD,CAAZ,CAAgBG,MAAvB;AACD,CAJD;;AAMA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACL,GAAD,EAAMM,IAAN;AACEN,IAAAA,GAAG,KAAK,IAAR,IAAgBM,IAAI,CAACV,QAAL,KAAkB,IAAlC,IAA0CI,GAAG,IAAIM,IAAI,CAACV,QADxD,GADF;AAGE,UAACI,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACV,QAFT,GAHF,CADsB;;;AAStB;AACE,UAACI,GAAD,EAAMM,IAAN;AACEN,IAAAA,GAAG,KAAK,IAAR,IAAgBM,IAAI,CAAClB,QAAL,KAAkB,IAAlC,IAA0CY,GAAG,IAAIM,IAAI,CAAClB,QADxD,GADF;AAGE,UAACY,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACV,QAFT,eAHF,CATsB;;;AAiBtB;AACE,UAACI,GAAD,EAAMM,IAAN;AACEN,IAAAA,GAAG,KAAK,IAAR,IAAgBM,IAAI,CAACT,aAAL,IAAsBE,gBAAgB,CAACC,GAAD,CADxD,GADF;AAGE,UAACA,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACT,aAFT,8BAHF,CAjBsB,CAAxB,C;;;;;AA2Be;AACb,QADa;AAEbjB,cAFa;AAGbN,eAHa;AAIba,OAJa;AAKbkB,eALa;AAMb,CANa;AAOb,UAAA5B,GAAG,UAAIA,GAAG,CAACyB,QAAJ,EAAJ,EAPU,C","sourcesContent":["import { constant, isNumber, isString, isNull } from \"lodash/fp\"\nimport {\n makerule,\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toNumberOrNull,\n isSafeInteger,\n} from \"../../common/index.js\"\n\nconst numberFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst parseStringtoNumberOrNull = s => {\n const num = Number(s)\n return isNaN(num) ? parsedFailed(s) : parsedSuccess(num)\n}\n\nconst numberTryParse = switchCase(\n [isNumber, parsedSuccess],\n [isString, parseStringtoNumberOrNull],\n [isNull, parsedSuccess],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n maxValue: {\n defaultValue: Number.MAX_SAFE_INTEGER,\n isValid: isSafeInteger,\n requirementDescription: \"must be a valid integer\",\n parse: toNumberOrNull,\n },\n minValue: {\n defaultValue: 0 - Number.MAX_SAFE_INTEGER,\n isValid: isSafeInteger,\n requirementDescription: \"must be a valid integer\",\n parse: toNumberOrNull,\n },\n decimalPlaces: {\n defaultValue: 0,\n isValid: n => isSafeInteger(n) && n >= 0,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n}\n\nconst getDecimalPlaces = val => {\n const splitDecimal = val.toString().split(\".\")\n if (splitDecimal.length === 1) return 0\n return splitDecimal[1].length\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || opts.minValue === null || val >= opts.minValue,\n (val, opts) =>\n `value (${val.toString()}) must be greater than or equal to ${\n opts.minValue\n }`\n ),\n makerule(\n (val, opts) =>\n val === null || opts.maxValue === null || val <= opts.maxValue,\n (val, opts) =>\n `value (${val.toString()}) must be less than or equal to ${\n opts.minValue\n } options`\n ),\n makerule(\n (val, opts) =>\n val === null || opts.decimalPlaces >= getDecimalPlaces(val),\n (val, opts) =>\n `value (${val.toString()}) must have ${\n opts.decimalPlaces\n } decimal places or less`\n ),\n]\n\nexport default getDefaultExport(\n \"number\",\n numberTryParse,\n numberFunctions,\n options,\n typeConstraints,\n 1,\n num => num.toString()\n)\n"],"file":"number.js"}
|
|
@ -0,0 +1,59 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _lodash = require("lodash");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
var objectFunctions = function objectFunctions(definition, allTypes) {return (
|
||||||
|
(0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _lodash.constant)(null),
|
||||||
|
initialise: function initialise() {return (
|
||||||
|
(0, _index.$)((0, _lodash.keys)(definition), [
|
||||||
|
(0, _lodash.map)(function () {
|
||||||
|
var defClone = (0, _lodash.clone)(definition);
|
||||||
|
for (var k in defClone) {
|
||||||
|
defClone[k] = allTypes[k].getNew();
|
||||||
|
}
|
||||||
|
return defClone;
|
||||||
|
})]));} }));};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var parseObject = function parseObject(definition, allTypes) {return function (record) {
|
||||||
|
var defClone = (0, _lodash.clone)(definition);
|
||||||
|
for (var k in defClone) {
|
||||||
|
var type = allTypes[defClone[k]];
|
||||||
|
defClone[k] = (0, _lodash.has)(record, k) ?
|
||||||
|
type.safeParseValue(record[k]) :
|
||||||
|
type.getNew();
|
||||||
|
}
|
||||||
|
return (0, _typeHelpers.parsedSuccess)(defClone);
|
||||||
|
};};
|
||||||
|
|
||||||
|
var objectTryParse = function objectTryParse(definition, allTypes) {return (
|
||||||
|
(0, _index.switchCase)(
|
||||||
|
[_lodash.isNull, _typeHelpers.parsedSuccess],
|
||||||
|
[_lodash.isObject, parseObject(definition, allTypes)],
|
||||||
|
[_index.defaultCase, _typeHelpers.parsedFailed]));};var _default =
|
||||||
|
|
||||||
|
|
||||||
|
function _default(
|
||||||
|
typeName,
|
||||||
|
definition,
|
||||||
|
allTypes,
|
||||||
|
defaultOptions,
|
||||||
|
typeConstraints,
|
||||||
|
sampleValue) {return (
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
typeName,
|
||||||
|
objectTryParse(definition, allTypes),
|
||||||
|
objectFunctions(definition, allTypes),
|
||||||
|
defaultOptions,
|
||||||
|
typeConstraints,
|
||||||
|
sampleValue,
|
||||||
|
JSON.stringify));};exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=object.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/object.js"],"names":["objectFunctions","definition","allTypes","initialise","defClone","k","getNew","parseObject","record","type","safeParseValue","objectTryParse","isNull","parsedSuccess","isObject","defaultCase","parsedFailed","typeName","defaultOptions","typeConstraints","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;AAMA;;AAEA,IAAMA,eAAe,GAAG,SAAlBA,eAAkB,CAACC,UAAD,EAAaC,QAAb;AACtB,oCAAc;AACZ,iBAAS,sBAAS,IAAT,CADG;AAEZC,MAAAA,UAAU,EAAE;AACV,wBAAE,kBAAKF,UAAL,CAAF,EAAoB;AAClB,2BAAI,YAAM;AACR,gBAAMG,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,iBAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxBA,cAAAA,QAAQ,CAACC,CAAD,CAAR,GAAcH,QAAQ,CAACG,CAAD,CAAR,CAAYC,MAAZ,EAAd;AACD;AACD,mBAAOF,QAAP;AACD,WAND,CADkB,CAApB,CADU,GAFA,EAAd,CADsB,GAAxB;;;;AAeA,IAAMG,WAAW,GAAG,SAAdA,WAAc,CAACN,UAAD,EAAaC,QAAb,UAA0B,UAAAM,MAAM,EAAI;AACtD,QAAMJ,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,SAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxB,UAAMK,IAAI,GAAGP,QAAQ,CAACE,QAAQ,CAACC,CAAD,CAAT,CAArB;AACAD,MAAAA,QAAQ,CAACC,CAAD,CAAR,GAAc,iBAAIG,MAAJ,EAAYH,CAAZ;AACVI,MAAAA,IAAI,CAACC,cAAL,CAAoBF,MAAM,CAACH,CAAD,CAA1B,CADU;AAEVI,MAAAA,IAAI,CAACH,MAAL,EAFJ;AAGD;AACD,WAAO,gCAAcF,QAAd,CAAP;AACD,GATmB,EAApB;;AAWA,IAAMO,cAAc,GAAG,SAAjBA,cAAiB,CAACV,UAAD,EAAaC,QAAb;AACrB;AACE,KAACU,cAAD,EAASC,0BAAT,CADF;AAEE,KAACC,gBAAD,EAAWP,WAAW,CAACN,UAAD,EAAaC,QAAb,CAAtB,CAFF;AAGE,KAACa,kBAAD,EAAcC,yBAAd,CAHF,CADqB,GAAvB,C;;;AAOe;AACbC,QADa;AAEbhB,UAFa;AAGbC,QAHa;AAIbgB,cAJa;AAKbC,eALa;AAMbC,WANa;;AAQb;AACEH,IAAAA,QADF;AAEEN,IAAAA,cAAc,CAACV,UAAD,EAAaC,QAAb,CAFhB;AAGEF,IAAAA,eAAe,CAACC,UAAD,EAAaC,QAAb,CAHjB;AAIEgB,IAAAA,cAJF;AAKEC,IAAAA,eALF;AAMEC,IAAAA,WANF;AAOEC,IAAAA,IAAI,CAACC,SAPP,CARa,G","sourcesContent":["import { keys, isObject, has, clone, map, isNull, constant } from \"lodash\"\nimport {\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport { switchCase, defaultCase, $ } from \"../../common/index.js\"\n\nconst objectFunctions = (definition, allTypes) =>\n typeFunctions({\n default: constant(null),\n initialise: () =>\n $(keys(definition), [\n map(() => {\n const defClone = clone(definition)\n for (const k in defClone) {\n defClone[k] = allTypes[k].getNew()\n }\n return defClone\n }),\n ]),\n })\n\nconst parseObject = (definition, allTypes) => record => {\n const defClone = clone(definition)\n for (const k in defClone) {\n const type = allTypes[defClone[k]]\n defClone[k] = has(record, k)\n ? type.safeParseValue(record[k])\n : type.getNew()\n }\n return parsedSuccess(defClone)\n}\n\nconst objectTryParse = (definition, allTypes) =>\n switchCase(\n [isNull, parsedSuccess],\n [isObject, parseObject(definition, allTypes)],\n [defaultCase, parsedFailed]\n )\n\nexport default (\n typeName,\n definition,\n allTypes,\n defaultOptions,\n typeConstraints,\n sampleValue\n) =>\n getDefaultExport(\n typeName,\n objectTryParse(definition, allTypes),\n objectFunctions(definition, allTypes),\n defaultOptions,\n typeConstraints,\n sampleValue,\n JSON.stringify\n )\n"],"file":"object.js"}
|
|
@ -0,0 +1,74 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp");
|
||||||
|
var _typeHelpers = require("./typeHelpers");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var _index = require("../../common/index.js");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var stringFunctions = (0, _typeHelpers.typeFunctions)({
|
||||||
|
"default": (0, _fp.constant)(null) });
|
||||||
|
|
||||||
|
|
||||||
|
var stringTryParse = (0, _index.switchCase)(
|
||||||
|
[_fp.isString, _typeHelpers.parsedSuccess],
|
||||||
|
[_fp.isNull, _typeHelpers.parsedSuccess],
|
||||||
|
[_index.defaultCase, function (v) {return (0, _typeHelpers.parsedSuccess)(v.toString());}]);
|
||||||
|
|
||||||
|
|
||||||
|
var options = {
|
||||||
|
maxLength: {
|
||||||
|
defaultValue: null,
|
||||||
|
isValid: function isValid(n) {return n === null || (0, _index.isSafeInteger)(n) && n > 0;},
|
||||||
|
requirementDescription:
|
||||||
|
"max length must be null (no limit) or a greater than zero integer",
|
||||||
|
parse: _index.toNumberOrNull },
|
||||||
|
|
||||||
|
values: {
|
||||||
|
defaultValue: null,
|
||||||
|
isValid: function isValid(v) {return (
|
||||||
|
v === null || (0, _index.isArrayOfString)(v) && v.length > 0 && v.length < 10000);},
|
||||||
|
requirementDescription:
|
||||||
|
"'values' must be null (no values) or an array of at least one string",
|
||||||
|
parse: function parse(s) {return s;} },
|
||||||
|
|
||||||
|
allowDeclaredValuesOnly: {
|
||||||
|
defaultValue: false,
|
||||||
|
isValid: _fp.isBoolean,
|
||||||
|
requirementDescription: "allowDeclaredValuesOnly must be true or false",
|
||||||
|
parse: _index.toBoolOrNull } };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var typeConstraints = [
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null || opts.maxLength === null || val.length <= opts.maxLength);},
|
||||||
|
function (val, opts) {return "value exceeds maximum length of ".concat(opts.maxLength);}),
|
||||||
|
|
||||||
|
(0, _typeHelpers.makerule)(
|
||||||
|
function (val, opts) {return (
|
||||||
|
val === null ||
|
||||||
|
opts.allowDeclaredValuesOnly === false ||
|
||||||
|
(0, _fp.includes)(val)(opts.values));},
|
||||||
|
function (val) {return "\"".concat(val, "\" does not exist in the list of allowed values");})];var _default =
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(0, _typeHelpers.getDefaultExport)(
|
||||||
|
"string",
|
||||||
|
stringTryParse,
|
||||||
|
stringFunctions,
|
||||||
|
options,
|
||||||
|
typeConstraints,
|
||||||
|
"abcde",
|
||||||
|
function (str) {return str;});exports["default"] = _default;
|
||||||
|
//# sourceMappingURL=string.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../../src/schema/types/string.js"],"names":["stringFunctions","stringTryParse","isString","parsedSuccess","isNull","defaultCase","v","toString","options","maxLength","defaultValue","isValid","n","requirementDescription","parse","toNumberOrNull","values","length","s","allowDeclaredValuesOnly","isBoolean","toBoolOrNull","typeConstraints","val","opts","str"],"mappings":"uGAAA;AACA;;;;;;AAMA;;;;;;;;;AASA,IAAMA,eAAe,GAAG,gCAAc;AACpC,aAAS,kBAAS,IAAT,CAD2B,EAAd,CAAxB;;;AAIA,IAAMC,cAAc,GAAG;AACrB,CAACC,YAAD,EAAWC,0BAAX,CADqB;AAErB,CAACC,UAAD,EAASD,0BAAT,CAFqB;AAGrB,CAACE,kBAAD,EAAc,UAAAC,CAAC,UAAI,gCAAcA,CAAC,CAACC,QAAF,EAAd,CAAJ,EAAf,CAHqB,CAAvB;;;AAMA,IAAMC,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,YAAY,EAAE,IADL;AAETC,IAAAA,OAAO,EAAE,iBAAAC,CAAC,UAAIA,CAAC,KAAK,IAAN,IAAe,0BAAcA,CAAd,KAAoBA,CAAC,GAAG,CAA3C,EAFD;AAGTC,IAAAA,sBAAsB;AACpB,uEAJO;AAKTC,IAAAA,KAAK,EAAEC,qBALE,EADG;;AAQdC,EAAAA,MAAM,EAAE;AACNN,IAAAA,YAAY,EAAE,IADR;AAENC,IAAAA,OAAO,EAAE,iBAAAL,CAAC;AACRA,QAAAA,CAAC,KAAK,IAAN,IAAe,4BAAgBA,CAAhB,KAAsBA,CAAC,CAACW,MAAF,GAAW,CAAjC,IAAsCX,CAAC,CAACW,MAAF,GAAW,KADxD,GAFJ;AAINJ,IAAAA,sBAAsB;AACpB,0EALI;AAMNC,IAAAA,KAAK,EAAE,eAAAI,CAAC,UAAIA,CAAJ,EANF,EARM;;AAgBdC,EAAAA,uBAAuB,EAAE;AACvBT,IAAAA,YAAY,EAAE,KADS;AAEvBC,IAAAA,OAAO,EAAES,aAFc;AAGvBP,IAAAA,sBAAsB,EAAE,+CAHD;AAIvBC,IAAAA,KAAK,EAAEO,mBAJgB,EAhBX,EAAhB;;;;AAwBA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBC,IAAI,CAACf,SAAL,KAAmB,IAAnC,IAA2Cc,GAAG,CAACN,MAAJ,IAAcO,IAAI,CAACf,SADhE,GADF;AAGE,UAACc,GAAD,EAAMC,IAAN,oDAAkDA,IAAI,CAACf,SAAvD,GAHF,CADsB;;AAMtB;AACE,UAACc,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR;AACAC,IAAAA,IAAI,CAACL,uBAAL,KAAiC,KADjC;AAEA,sBAASI,GAAT,EAAcC,IAAI,CAACR,MAAnB,CAHF,GADF;AAKE,UAAAO,GAAG,sBAAQA,GAAR,sDALL,CANsB,CAAxB,C;;;;AAee;AACb,QADa;AAEbtB,cAFa;AAGbD,eAHa;AAIbQ,OAJa;AAKbc,eALa;AAMb,OANa;AAOb,UAAAG,GAAG,UAAIA,GAAJ,EAPU,C","sourcesContent":["import { constant, isString, isNull, includes, isBoolean } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toBoolOrNull,\n toNumberOrNull,\n isSafeInteger,\n isArrayOfString,\n} from \"../../common/index.js\"\n\nconst stringFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst stringTryParse = switchCase(\n [isString, parsedSuccess],\n [isNull, parsedSuccess],\n [defaultCase, v => parsedSuccess(v.toString())]\n)\n\nconst options = {\n maxLength: {\n defaultValue: null,\n isValid: n => n === null || (isSafeInteger(n) && n > 0),\n requirementDescription:\n \"max length must be null (no limit) or a greater than zero integer\",\n parse: toNumberOrNull,\n },\n values: {\n defaultValue: null,\n isValid: v =>\n v === null || (isArrayOfString(v) && v.length > 0 && v.length < 10000),\n requirementDescription:\n \"'values' must be null (no values) or an array of at least one string\",\n parse: s => s,\n },\n allowDeclaredValuesOnly: {\n defaultValue: false,\n isValid: isBoolean,\n requirementDescription: \"allowDeclaredValuesOnly must be true or false\",\n parse: toBoolOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || opts.maxLength === null || val.length <= opts.maxLength,\n (val, opts) => `value exceeds maximum length of ${opts.maxLength}`\n ),\n makerule(\n (val, opts) =>\n val === null ||\n opts.allowDeclaredValuesOnly === false ||\n includes(val)(opts.values),\n val => `\"${val}\" does not exist in the list of allowed values`\n ),\n]\n\nexport default getDefaultExport(\n \"string\",\n stringTryParse,\n stringFunctions,\n options,\n typeConstraints,\n \"abcde\",\n str => str\n)\n"],"file":"string.js"}
|
|
@ -0,0 +1,90 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.getDefaultExport = exports.parsedSuccess = exports.parsedFailed = exports.makerule = exports.validateTypeConstraints = exports.typeFunctions = exports.getNewValue = exports.getSafeValueParser = exports.getSafeFieldParser = void 0;var _lodash = require("lodash");
|
||||||
|
var _fp = require("lodash/fp");
|
||||||
|
var _index = require("../../common/index.js");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
|
||||||
|
|
||||||
|
var getSafeFieldParser = function getSafeFieldParser(tryParse, defaultValueFunctions) {return function (
|
||||||
|
field,
|
||||||
|
record)
|
||||||
|
{
|
||||||
|
if ((0, _fp.has)(field.name)(record)) {
|
||||||
|
return getSafeValueParser(
|
||||||
|
tryParse,
|
||||||
|
defaultValueFunctions)(
|
||||||
|
record[field.name]);
|
||||||
|
}
|
||||||
|
return defaultValueFunctions[field.getUndefinedValue]();
|
||||||
|
};};exports.getSafeFieldParser = getSafeFieldParser;
|
||||||
|
|
||||||
|
var getSafeValueParser = function getSafeValueParser(
|
||||||
|
tryParse,
|
||||||
|
defaultValueFunctions) {return (
|
||||||
|
function (value) {
|
||||||
|
var parsed = tryParse(value);
|
||||||
|
if (parsed.success) {
|
||||||
|
return parsed.value;
|
||||||
|
}
|
||||||
|
return defaultValueFunctions["default"]();
|
||||||
|
});};exports.getSafeValueParser = getSafeValueParser;
|
||||||
|
|
||||||
|
var getNewValue = function getNewValue(tryParse, defaultValueFunctions) {return function (field) {
|
||||||
|
var getInitialValue =
|
||||||
|
(0, _fp.isUndefined)(field) || (0, _fp.isUndefined)(field.getInitialValue) ?
|
||||||
|
"default" :
|
||||||
|
field.getInitialValue;
|
||||||
|
|
||||||
|
return (0, _fp.has)(getInitialValue)(defaultValueFunctions) ?
|
||||||
|
defaultValueFunctions[getInitialValue]() :
|
||||||
|
getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue);
|
||||||
|
};};exports.getNewValue = getNewValue;
|
||||||
|
|
||||||
|
var typeFunctions = function typeFunctions(specificFunctions) {return (
|
||||||
|
(0, _lodash.merge)(
|
||||||
|
{
|
||||||
|
value: _fp.constant,
|
||||||
|
"null": (0, _fp.constant)(null) },
|
||||||
|
|
||||||
|
specificFunctions));};exports.typeFunctions = typeFunctions;
|
||||||
|
|
||||||
|
|
||||||
|
var validateTypeConstraints = function validateTypeConstraints(validationRules) {return function (field, record) {
|
||||||
|
var fieldValue = record[field.name];
|
||||||
|
var validateRule = function validateRule(r) {return (
|
||||||
|
!r.isValid(fieldValue, field.typeOptions) ?
|
||||||
|
r.getMessage(fieldValue, field.typeOptions) :
|
||||||
|
"");};
|
||||||
|
|
||||||
|
var errors = [];var _iterator = _createForOfIteratorHelper(
|
||||||
|
validationRules),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var r = _step.value;
|
||||||
|
var err = validateRule(r);
|
||||||
|
if ((0, _index.isNotEmpty)(err)) errors.push(err);
|
||||||
|
}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
|
||||||
|
|
||||||
|
return errors;
|
||||||
|
};};exports.validateTypeConstraints = validateTypeConstraints;
|
||||||
|
|
||||||
|
var _getDefaultOptions = (0, _fp.mapValues)(function (v) {return v.defaultValue;});
|
||||||
|
|
||||||
|
var makerule = function makerule(isValid, getMessage) {return { isValid: isValid, getMessage: getMessage };};exports.makerule = makerule;
|
||||||
|
var parsedFailed = function parsedFailed(val) {return { success: false, value: val };};exports.parsedFailed = parsedFailed;
|
||||||
|
var parsedSuccess = function parsedSuccess(val) {return { success: true, value: val };};exports.parsedSuccess = parsedSuccess;
|
||||||
|
var getDefaultExport = function getDefaultExport(
|
||||||
|
name,
|
||||||
|
tryParse,
|
||||||
|
functions,
|
||||||
|
options,
|
||||||
|
validationRules,
|
||||||
|
sampleValue,
|
||||||
|
_stringify) {return (
|
||||||
|
{
|
||||||
|
getNew: getNewValue(tryParse, functions),
|
||||||
|
safeParseField: getSafeFieldParser(tryParse, functions),
|
||||||
|
safeParseValue: getSafeValueParser(tryParse, functions),
|
||||||
|
tryParse: tryParse,
|
||||||
|
name: name,
|
||||||
|
getDefaultOptions: function getDefaultOptions() {return _getDefaultOptions((0, _fp.cloneDeep)(options));},
|
||||||
|
optionDefinitions: options,
|
||||||
|
validateTypeConstraints: validateTypeConstraints(validationRules),
|
||||||
|
sampleValue: sampleValue,
|
||||||
|
stringify: function stringify(val) {return val === null || val === undefined ? "" : _stringify(val);},
|
||||||
|
getDefaultValue: functions["default"] });};exports.getDefaultExport = getDefaultExport;
|
||||||
|
//# sourceMappingURL=typeHelpers.js.map
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,7 @@
|
||||||
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.newView = void 0;var _shortid = require("shortid");
|
||||||
|
|
||||||
|
var newView = function newView() {var modelId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;return {
|
||||||
|
id: (0, _shortid.generate)(),
|
||||||
|
name: "",
|
||||||
|
modelId: modelId };};exports.newView = newView;
|
||||||
|
//# sourceMappingURL=views.js.map
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":3,"sources":["../../src/schema/views.js"],"names":["newView","modelId","id","name"],"mappings":"oGAAA;;AAEO,IAAMA,OAAO,GAAG,SAAVA,OAAU,QAACC,OAAD,uEAAW,IAAX,QAAqB;AAC1CC,IAAAA,EAAE,EAAE,wBADsC;AAE1CC,IAAAA,IAAI,EAAE,EAFoC;AAG1CF,IAAAA,OAAO,EAAPA,OAH0C,EAArB,EAAhB,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newView = (modelId = null) => ({\n id: generate(),\n name: \"\",\n modelId,\n})\n"],"file":"views.js"}
|
|
@ -2,6 +2,7 @@
|
||||||
"name": "@budibase/common",
|
"name": "@budibase/common",
|
||||||
"version": "0.0.32",
|
"version": "0.0.32",
|
||||||
"description": "core javascript library for budibase",
|
"description": "core javascript library for budibase",
|
||||||
|
"main": "lib/index.js",
|
||||||
"files": [
|
"files": [
|
||||||
"dist/**",
|
"dist/**",
|
||||||
"!dist/node_modules"
|
"!dist/node_modules"
|
||||||
|
@ -10,7 +11,8 @@
|
||||||
"test": "test"
|
"test": "test"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "jest"
|
"test": "jest",
|
||||||
|
"build": "npx babel src --out-dir lib --source-maps"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"budibase"
|
"budibase"
|
||||||
|
|
|
@ -27,7 +27,7 @@ import {
|
||||||
includes,
|
includes,
|
||||||
filter,
|
filter,
|
||||||
} from "lodash/fp"
|
} from "lodash/fp"
|
||||||
import { events, eventsList } from "./events.mjs"
|
import { events, eventsList } from "./events.js"
|
||||||
|
|
||||||
// this is the combinator function
|
// this is the combinator function
|
||||||
export const $$ = (...funcs) => arg => flow(funcs)(arg)
|
export const $$ = (...funcs) => arg => flow(funcs)(arg)
|
||||||
|
@ -241,7 +241,7 @@ export const retry = async (fn, retries, delay, ...args) => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export { events } from "./events.mjs"
|
export { events } from "./events.js"
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
ifExists,
|
ifExists,
|
|
@ -0,0 +1,3 @@
|
||||||
|
export { validateRecord } from "./records/validateRecord";
|
||||||
|
export { events } from "./common/events";
|
||||||
|
export { safeParseField } from "./schema/types";
|
|
@ -1,11 +1,10 @@
|
||||||
const { map, reduce, filter, isEmpty, flatten, each, union } = require("lodash/fp");
|
import { map, reduce, filter, isEmpty, flatten, each, union } from "lodash/fp";
|
||||||
const { compileCode } = require("../common/compileCode");
|
import { compileCode } from "../common/compileCode";
|
||||||
const { validateFieldParse, validateTypeConstraints } = require("../schema/types");
|
|
||||||
import {
|
import {
|
||||||
validateFieldParse,
|
validateFieldParse,
|
||||||
validateTypeConstraints,
|
validateTypeConstraints,
|
||||||
} from "../schema/types/index.js"
|
} from "../schema/types/index.js"
|
||||||
import { $, isNonEmptyString } from "../common/index.mjs"
|
import { $, isNonEmptyString } from "../common/index.js"
|
||||||
|
|
||||||
const fieldParseError = (fieldName, value) => ({
|
const fieldParseError = (fieldName, value) => ({
|
||||||
fields: [fieldName],
|
fields: [fieldName],
|
||||||
|
|
|
@ -1,86 +0,0 @@
|
||||||
import { map, reduce, filter, isEmpty, flatten, each } from "lodash/fp"
|
|
||||||
import { compileCode } from "../common/compileCode.mjs"
|
|
||||||
import _ from "lodash"
|
|
||||||
import {
|
|
||||||
validateFieldParse,
|
|
||||||
validateTypeConstraints,
|
|
||||||
} from "../schema/types/index.mjs"
|
|
||||||
import { $, isNonEmptyString } from "../common/index.mjs"
|
|
||||||
|
|
||||||
const fieldParseError = (fieldName, value) => ({
|
|
||||||
fields: [fieldName],
|
|
||||||
message: `Could not parse field ${fieldName}:${value}`,
|
|
||||||
})
|
|
||||||
|
|
||||||
const validateAllFieldParse = (record, model) =>
|
|
||||||
$(model.fields, [
|
|
||||||
map(f => ({ name: f.name, parseResult: validateFieldParse(f, record) })),
|
|
||||||
reduce((errors, f) => {
|
|
||||||
if (f.parseResult.success) return errors
|
|
||||||
errors.push(fieldParseError(f.name, f.parseResult.value))
|
|
||||||
return errors
|
|
||||||
}, []),
|
|
||||||
])
|
|
||||||
|
|
||||||
const validateAllTypeConstraints = (record, model) => {
|
|
||||||
const errors = []
|
|
||||||
for (const field of model.fields) {
|
|
||||||
$(validateTypeConstraints(field, record), [
|
|
||||||
filter(isNonEmptyString),
|
|
||||||
map(m => ({ message: m, fields: [field.name] })),
|
|
||||||
each(e => errors.push(e)),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
return errors
|
|
||||||
}
|
|
||||||
|
|
||||||
const runRecordValidationRules = (record, model) => {
|
|
||||||
const runValidationRule = rule => {
|
|
||||||
const isValid = compileCode(rule.expressionWhenValid)
|
|
||||||
const expressionContext = { record }
|
|
||||||
return isValid(expressionContext)
|
|
||||||
? { valid: true }
|
|
||||||
: {
|
|
||||||
valid: false,
|
|
||||||
fields: rule.invalidFields,
|
|
||||||
message: rule.messageWhenInvalid,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $(model.validationRules, [
|
|
||||||
map(runValidationRule),
|
|
||||||
flatten,
|
|
||||||
filter(r => r.valid === false),
|
|
||||||
map(r => ({ fields: r.fields, message: r.message })),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
export const validateRecord = (schema, record) => {
|
|
||||||
const model = schema.findModel(record._modelId)
|
|
||||||
const fieldParseFails = validateAllFieldParse(record, model)
|
|
||||||
|
|
||||||
// non parsing would cause further issues - exit here
|
|
||||||
if (!isEmpty(fieldParseFails)) {
|
|
||||||
return { isValid: false, errors: fieldParseFails }
|
|
||||||
}
|
|
||||||
|
|
||||||
const recordValidationRuleFails = runRecordValidationRules(record, model)
|
|
||||||
const typeContraintFails = validateAllTypeConstraints(record, model)
|
|
||||||
|
|
||||||
if (
|
|
||||||
isEmpty(fieldParseFails) &&
|
|
||||||
isEmpty(recordValidationRuleFails) &&
|
|
||||||
isEmpty(typeContraintFails)
|
|
||||||
) {
|
|
||||||
return { isValid: true, errors: [] }
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
isValid: false,
|
|
||||||
errors: _.union(
|
|
||||||
fieldParseFails,
|
|
||||||
typeContraintFails,
|
|
||||||
recordValidationRuleFails
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -6,7 +6,7 @@ import {
|
||||||
isNothingOrEmpty,
|
isNothingOrEmpty,
|
||||||
isNothing,
|
isNothing,
|
||||||
} from "../common"
|
} from "../common"
|
||||||
import { all, getDefaultOptions } from "./types/index.mjs"
|
import { all, getDefaultOptions } from "./types/index.js"
|
||||||
import { applyRuleSet, makerule } from "../common/validationCommon"
|
import { applyRuleSet, makerule } from "../common/validationCommon"
|
||||||
import { BadRequestError } from "../common/errors"
|
import { BadRequestError } from "../common/errors"
|
||||||
import { generate } from "shortid"
|
import { generate } from "shortid"
|
|
@ -12,7 +12,7 @@ import {
|
||||||
toNumberOrNull,
|
toNumberOrNull,
|
||||||
$$,
|
$$,
|
||||||
isSafeInteger,
|
isSafeInteger,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const arrayFunctions = () =>
|
const arrayFunctions = () =>
|
||||||
typeFunctions({
|
typeFunctions({
|
|
@ -11,7 +11,7 @@ import {
|
||||||
defaultCase,
|
defaultCase,
|
||||||
isOneOf,
|
isOneOf,
|
||||||
toBoolOrNull,
|
toBoolOrNull,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const boolFunctions = typeFunctions({
|
const boolFunctions = typeFunctions({
|
||||||
default: constant(null),
|
default: constant(null),
|
|
@ -11,7 +11,7 @@ import {
|
||||||
none,
|
none,
|
||||||
$,
|
$,
|
||||||
splitKey,
|
splitKey,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const illegalCharacters = "*?\\/:<>|\0\b\f\v"
|
const illegalCharacters = "*?\\/:<>|\0\b\f\v"
|
||||||
|
|
|
@ -10,7 +10,7 @@ import {
|
||||||
isArray,
|
isArray,
|
||||||
has,
|
has,
|
||||||
} from "lodash/fp"
|
} from "lodash/fp"
|
||||||
import { $ } from "../../common/index.mjs"
|
import { $ } from "../../common"
|
||||||
import { parsedSuccess } from "./typeHelpers"
|
import { parsedSuccess } from "./typeHelpers"
|
||||||
import string from "./string"
|
import string from "./string"
|
||||||
import bool from "./bool"
|
import bool from "./bool"
|
||||||
|
@ -19,7 +19,7 @@ import datetime from "./datetime"
|
||||||
import array from "./array"
|
import array from "./array"
|
||||||
import link from "./link"
|
import link from "./link"
|
||||||
import file from "./file"
|
import file from "./file"
|
||||||
import { BadRequestError } from "../../common/errors.mjs"
|
import { BadRequestError } from "../../common/errors"
|
||||||
|
|
||||||
const allTypes = () => {
|
const allTypes = () => {
|
||||||
const basicTypes = {
|
const basicTypes = {
|
|
@ -4,7 +4,7 @@ import {
|
||||||
switchCase,
|
switchCase,
|
||||||
defaultCase,
|
defaultCase,
|
||||||
isNonEmptyString,
|
isNonEmptyString,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const linkNothing = () => ""
|
const linkNothing = () => ""
|
||||||
|
|
|
@ -11,7 +11,7 @@ import {
|
||||||
defaultCase,
|
defaultCase,
|
||||||
toNumberOrNull,
|
toNumberOrNull,
|
||||||
isSafeInteger,
|
isSafeInteger,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const numberFunctions = typeFunctions({
|
const numberFunctions = typeFunctions({
|
||||||
default: constant(null),
|
default: constant(null),
|
|
@ -5,7 +5,7 @@ import {
|
||||||
parsedSuccess,
|
parsedSuccess,
|
||||||
getDefaultExport,
|
getDefaultExport,
|
||||||
} from "./typeHelpers"
|
} from "./typeHelpers"
|
||||||
import { switchCase, defaultCase, $ } from "../../common/index.mjs"
|
import { switchCase, defaultCase, $ } from "../../common/index.js"
|
||||||
|
|
||||||
const objectFunctions = (definition, allTypes) =>
|
const objectFunctions = (definition, allTypes) =>
|
||||||
typeFunctions({
|
typeFunctions({
|
|
@ -12,7 +12,7 @@ import {
|
||||||
toNumberOrNull,
|
toNumberOrNull,
|
||||||
isSafeInteger,
|
isSafeInteger,
|
||||||
isArrayOfString,
|
isArrayOfString,
|
||||||
} from "../../common/index.mjs"
|
} from "../../common/index.js"
|
||||||
|
|
||||||
const stringFunctions = typeFunctions({
|
const stringFunctions = typeFunctions({
|
||||||
default: constant(null),
|
default: constant(null),
|
|
@ -1,6 +1,6 @@
|
||||||
import { merge } from "lodash"
|
import { merge } from "lodash"
|
||||||
import { constant, isUndefined, has, mapValues, cloneDeep } from "lodash/fp"
|
import { constant, isUndefined, has, mapValues, cloneDeep } from "lodash/fp"
|
||||||
import { isNotEmpty } from "../../common/index.mjs"
|
import { isNotEmpty } from "../../common/index.js"
|
||||||
|
|
||||||
export const getSafeFieldParser = (tryParse, defaultValueFunctions) => (
|
export const getSafeFieldParser = (tryParse, defaultValueFunctions) => (
|
||||||
field,
|
field,
|
|
@ -13,6 +13,7 @@ exports.create = async function(ctx) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, '_design/client');
|
}, '_design/client');
|
||||||
|
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
message: `Client Database ${clientId} successfully provisioned.`
|
message: `Client Database ${clientId} successfully provisioned.`
|
||||||
}
|
}
|
||||||
|
@ -20,7 +21,9 @@ exports.create = async function(ctx) {
|
||||||
|
|
||||||
exports.destroy = async function(ctx) {
|
exports.destroy = async function(ctx) {
|
||||||
const dbId = `client-${ctx.params.clientId}`;
|
const dbId = `client-${ctx.params.clientId}`;
|
||||||
|
|
||||||
await couchdb.db.destroy(dbId);
|
await couchdb.db.destroy(dbId);
|
||||||
|
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
status: 200,
|
status: 200,
|
||||||
message: `Client Database ${dbId} successfully deleted.`
|
message: `Client Database ${dbId} successfully deleted.`
|
||||||
|
|
|
@ -38,6 +38,7 @@ exports.fetch = async function(ctx) {
|
||||||
exports.create = async function(ctx) {
|
exports.create = async function(ctx) {
|
||||||
const db = couchdb.db.use(ctx.params.instanceId);
|
const db = couchdb.db.use(ctx.params.instanceId);
|
||||||
const newModel = await db.insert(ctx.request.body);
|
const newModel = await db.insert(ctx.request.body);
|
||||||
|
|
||||||
const designDoc = await db.get("_design/database");
|
const designDoc = await db.get("_design/database");
|
||||||
designDoc.views = {
|
designDoc.views = {
|
||||||
...designDoc.views,
|
...designDoc.views,
|
||||||
|
@ -47,8 +48,8 @@ exports.create = async function(ctx) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
await db.insert(designDoc, designDoc._id);
|
await db.insert(designDoc, designDoc._id);
|
||||||
|
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
...newModel,
|
...newModel,
|
||||||
message: `Model ${ctx.request.body.name} created successfully.`,
|
message: `Model ${ctx.request.body.name} created successfully.`,
|
||||||
|
|
|
@ -2,9 +2,9 @@ const couchdb = require("../../db")
|
||||||
const { mapValues, keyBy, compose } = require("lodash/fp")
|
const { mapValues, keyBy, compose } = require("lodash/fp")
|
||||||
const {
|
const {
|
||||||
validateRecord,
|
validateRecord,
|
||||||
} = require("../../../common/src/records/validateRecord")
|
events,
|
||||||
const { events } = require("../../../common/src/common/events")
|
safeParseField
|
||||||
const { safeParseField } = require("../../../common/src/schema/types");
|
} = require("@budibase/common")
|
||||||
|
|
||||||
exports.save = async function(ctx) {
|
exports.save = async function(ctx) {
|
||||||
const db = couchdb.use(ctx.databaseId)
|
const db = couchdb.use(ctx.databaseId)
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
const send = require("koa-send");
|
||||||
|
const { resolve } = require("path")
|
||||||
|
|
||||||
|
// either serve the builder or serve the actual app index.html
|
||||||
|
const builderPath = resolve(process.cwd(), "builder")
|
||||||
|
|
||||||
|
exports.serveBuilder = async function(ctx) {
|
||||||
|
await send(ctx, ctx.file, { root: builderPath })
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.serveApp = async function(ctx) {
|
||||||
|
// resolve unauthenticated page if so
|
||||||
|
await send(ctx, "/index.html", { root: ctx.publicPath })
|
||||||
|
// resolve main page if user authenticated
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.serveComponentLibrary = async function(ctx) {
|
||||||
|
await send(ctx, "/index.html", { root: builderPath })
|
||||||
|
}
|
|
@ -22,6 +22,7 @@ const clientRoutes = require("./routes/neo/client");
|
||||||
const applicationRoutes = require("./routes/neo/application");
|
const applicationRoutes = require("./routes/neo/application");
|
||||||
const modelsRoutes = require("./routes/neo/model");
|
const modelsRoutes = require("./routes/neo/model");
|
||||||
const viewsRoutes = require("./routes/neo/view");
|
const viewsRoutes = require("./routes/neo/view");
|
||||||
|
const staticRoutes = require("./routes/neo/static");
|
||||||
|
|
||||||
const builderPath = resolve(__dirname, "../builder")
|
const builderPath = resolve(__dirname, "../builder")
|
||||||
|
|
||||||
|
@ -29,7 +30,13 @@ module.exports = (config, app) => {
|
||||||
const router = new Router()
|
const router = new Router()
|
||||||
|
|
||||||
router
|
router
|
||||||
.use(session(config, app));
|
.use(session(config, app))
|
||||||
|
.use(async (ctx, next) => {
|
||||||
|
// TODO: temp dev middleware
|
||||||
|
ctx.config = config;
|
||||||
|
ctx.isAuthenticated = true;
|
||||||
|
await next();
|
||||||
|
});
|
||||||
// .use(async (ctx, next) => {
|
// .use(async (ctx, next) => {
|
||||||
// ctx.sessionId = ctx.session._sessCtx.externalKey
|
// ctx.sessionId = ctx.session._sessCtx.externalKey
|
||||||
// ctx.session.accessed = true
|
// ctx.session.accessed = true
|
||||||
|
@ -96,9 +103,9 @@ module.exports = (config, app) => {
|
||||||
// })
|
// })
|
||||||
|
|
||||||
router
|
router
|
||||||
.get("/_builder", async ctx => {
|
// .get("/_builder", async ctx => {
|
||||||
await send(ctx, "/index.html", { root: builderPath })
|
// await send(ctx, "/index.html", { root: builderPath })
|
||||||
})
|
// })
|
||||||
.get("/_builder/:appname/componentlibrary", async ctx => {
|
.get("/_builder/:appname/componentlibrary", async ctx => {
|
||||||
const info = await componentLibraryInfo(
|
const info = await componentLibraryInfo(
|
||||||
ctx.config,
|
ctx.config,
|
||||||
|
@ -107,19 +114,19 @@ module.exports = (config, app) => {
|
||||||
)
|
)
|
||||||
await send(ctx, info.components._lib || "index.js", { root: info.libDir })
|
await send(ctx, info.components._lib || "index.js", { root: info.libDir })
|
||||||
})
|
})
|
||||||
.get("/_builder/*", async (ctx, next) => {
|
// .get("/_builder/*", async (ctx, next) => {
|
||||||
const path = ctx.path.replace("/_builder", "")
|
// const path = ctx.path.replace("/_builder", "")
|
||||||
|
|
||||||
const isFile = new RegExp(/(.+\..{1,5})/g).test(path)
|
// const isFile = new RegExp(/(.+\..{1,5})/g).test(path)
|
||||||
|
|
||||||
if (path.startsWith("/api/") || path.startsWith("/instance/")) {
|
// if (path.startsWith("/api/") || path.startsWith("/instance/")) {
|
||||||
await next()
|
// await next()
|
||||||
} else if (isFile) {
|
// } else if (isFile) {
|
||||||
await send(ctx, path, { root: builderPath })
|
// await send(ctx, path, { root: builderPath })
|
||||||
} else {
|
// } else {
|
||||||
await send(ctx, "/index.html", { root: builderPath })
|
// await send(ctx, "/index.html", { root: builderPath })
|
||||||
}
|
// }
|
||||||
})
|
// })
|
||||||
|
|
||||||
// Neo
|
// Neo
|
||||||
// error handling middleware
|
// error handling middleware
|
||||||
|
@ -127,6 +134,7 @@ module.exports = (config, app) => {
|
||||||
try {
|
try {
|
||||||
await next();
|
await next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.trace(err);
|
||||||
ctx.status = err.status || 500;
|
ctx.status = err.status || 500;
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
message: err.message,
|
message: err.message,
|
||||||
|
@ -135,6 +143,9 @@ module.exports = (config, app) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.use(staticRoutes.routes());
|
||||||
|
router.use(staticRoutes.allowedMethods());
|
||||||
|
|
||||||
router.use(viewsRoutes.routes());
|
router.use(viewsRoutes.routes());
|
||||||
router.use(viewsRoutes.allowedMethods());
|
router.use(viewsRoutes.allowedMethods());
|
||||||
|
|
||||||
|
@ -156,8 +167,6 @@ module.exports = (config, app) => {
|
||||||
router.use(databaseRoutes.routes());
|
router.use(databaseRoutes.routes());
|
||||||
router.use(databaseRoutes.allowedMethods());
|
router.use(databaseRoutes.allowedMethods());
|
||||||
|
|
||||||
router.use(databaseRoutes.routes());
|
|
||||||
router.use(databaseRoutes.allowedMethods());
|
|
||||||
// end of Neo
|
// end of Neo
|
||||||
|
|
||||||
router.use(userRoutes.routes());
|
router.use(userRoutes.routes());
|
||||||
|
@ -170,9 +179,9 @@ module.exports = (config, app) => {
|
||||||
router.use(pageRoutes.allowedMethods());
|
router.use(pageRoutes.allowedMethods());
|
||||||
|
|
||||||
// router
|
// router
|
||||||
// .get("/:appname", async ctx => {
|
// .get("/:appname", async ctx => {
|
||||||
// await send(ctx, "/index.html", { root: ctx.publicPath })
|
// await send(ctx, "/index.html", { root: ctx.publicPath })
|
||||||
// })
|
// })
|
||||||
// .get("/:appname/*", routeHandlers.appDefault)
|
// .get("/:appname/*", routeHandlers.appDefault)
|
||||||
// .get("/_builder/instance/:appname/:instanceid/*", routeHandlers.appDefault)
|
// .get("/_builder/instance/:appname/:instanceid/*", routeHandlers.appDefault)
|
||||||
|
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
const Router = require("@koa/router");
|
const Router = require("@koa/router");
|
||||||
// const controller = require("../../controllers/record");
|
const controller = require("../../controllers/record");
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
// router
|
router
|
||||||
// .get("/api/:databaseId/records/:modelname", controller.fetch)
|
.get("/api/:databaseId/:modelId/records", controller.fetch)
|
||||||
// .post("/api/:databaseId/record", controller.save)
|
.get("/api/:databaseId/records/:recordId", controller.find)
|
||||||
// .get("/api/:databaseId/record/:recordId", controller.find)
|
.post("/api/:databaseId/records", controller.save)
|
||||||
// .delete("/api/:databaseId/record/:recordId", controller.destroy)
|
.delete("/api/:databaseId/records/:recordId", controller.destroy)
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
|
@ -0,0 +1,14 @@
|
||||||
|
const Router = require("@koa/router");
|
||||||
|
const controller = require("../../controllers/static");
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router
|
||||||
|
.param("file", async (file, ctx, next) => {
|
||||||
|
ctx.file = file || "index.html";
|
||||||
|
await next();
|
||||||
|
})
|
||||||
|
.get("/_builder/:file*", controller.serveBuilder)
|
||||||
|
.get("/:appName", controller.serveApp);
|
||||||
|
|
||||||
|
module.exports = router;
|
|
@ -19,6 +19,7 @@
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@budibase/client": "^0.0.32",
|
"@budibase/client": "^0.0.32",
|
||||||
|
"@budibase/common": "0.0.32",
|
||||||
"@budibase/core": "^0.0.32",
|
"@budibase/core": "^0.0.32",
|
||||||
"@koa/router": "^8.0.0",
|
"@koa/router": "^8.0.0",
|
||||||
"fs-extra": "^8.1.0",
|
"fs-extra": "^8.1.0",
|
||||||
|
|
Loading…
Reference in New Issue