diff --git a/packages/bootstrap-components/dist/index.js.map b/packages/bootstrap-components/dist/index.js.map index fa543197c0..eb9dac7595 100644 --- a/packages/bootstrap-components/dist/index.js.map +++ b/packages/bootstrap-components/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../node_modules/svelte/internal/index.mjs","../src/Button.svelte","../src/Textbox.svelte","../src/Form.svelte","../src/api.js","../src/Login.svelte","../src/buildStyle.js","../src/Grid.svelte","../src/StackPanel.svelte"],"sourcesContent":["function noop() { }\nconst identity = x => x;\nfunction assign(tar, src) {\n // @ts-ignore\n for (const k in src)\n tar[k] = src[k];\n return tar;\n}\nfunction is_promise(value) {\n return value && typeof value === 'object' && typeof value.then === 'function';\n}\nfunction add_location(element, file, line, column, char) {\n element.__svelte_meta = {\n loc: { file, line, column, char }\n };\n}\nfunction run(fn) {\n return fn();\n}\nfunction blank_object() {\n return Object.create(null);\n}\nfunction run_all(fns) {\n fns.forEach(run);\n}\nfunction is_function(thing) {\n return typeof thing === 'function';\n}\nfunction safe_not_equal(a, b) {\n return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');\n}\nfunction not_equal(a, b) {\n return a != a ? b == b : a !== b;\n}\nfunction validate_store(store, name) {\n if (!store || typeof store.subscribe !== 'function') {\n throw new Error(`'${name}' is not a store with a 'subscribe' method`);\n }\n}\nfunction subscribe(store, callback) {\n const unsub = store.subscribe(callback);\n return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\nfunction get_store_value(store) {\n let value;\n subscribe(store, _ => value = _)();\n return value;\n}\nfunction component_subscribe(component, store, callback) {\n component.$$.on_destroy.push(subscribe(store, callback));\n}\nfunction create_slot(definition, ctx, fn) {\n if (definition) {\n const slot_ctx = get_slot_context(definition, ctx, fn);\n return definition[0](slot_ctx);\n }\n}\nfunction get_slot_context(definition, ctx, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.ctx, definition[1](fn ? fn(ctx) : {})))\n : ctx.$$scope.ctx;\n}\nfunction get_slot_changes(definition, ctx, changed, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.changed || {}, definition[1](fn ? fn(changed) : {})))\n : ctx.$$scope.changed || {};\n}\nfunction exclude_internal_props(props) {\n const result = {};\n for (const k in props)\n if (k[0] !== '$')\n result[k] = props[k];\n return result;\n}\nfunction once(fn) {\n let ran = false;\n return function (...args) {\n if (ran)\n return;\n ran = true;\n fn.call(this, ...args);\n };\n}\nfunction null_to_empty(value) {\n return value == null ? '' : value;\n}\nfunction set_store_value(store, ret, value = ret) {\n store.set(value);\n return ret;\n}\n\nconst is_client = typeof window !== 'undefined';\nlet now = is_client\n ? () => window.performance.now()\n : () => Date.now();\nlet raf = is_client ? cb => requestAnimationFrame(cb) : noop;\n// used internally for testing\nfunction set_now(fn) {\n now = fn;\n}\nfunction set_raf(fn) {\n raf = fn;\n}\n\nconst tasks = new Set();\nlet running = false;\nfunction run_tasks() {\n tasks.forEach(task => {\n if (!task[0](now())) {\n tasks.delete(task);\n task[1]();\n }\n });\n running = tasks.size > 0;\n if (running)\n raf(run_tasks);\n}\nfunction clear_loops() {\n // for testing...\n tasks.forEach(task => tasks.delete(task));\n running = false;\n}\nfunction loop(fn) {\n let task;\n if (!running) {\n running = true;\n raf(run_tasks);\n }\n return {\n promise: new Promise(fulfil => {\n tasks.add(task = [fn, fulfil]);\n }),\n abort() {\n tasks.delete(task);\n }\n };\n}\n\nfunction append(target, node) {\n target.appendChild(node);\n}\nfunction insert(target, node, anchor) {\n target.insertBefore(node, anchor || null);\n}\nfunction detach(node) {\n node.parentNode.removeChild(node);\n}\nfunction destroy_each(iterations, detaching) {\n for (let i = 0; i < iterations.length; i += 1) {\n if (iterations[i])\n iterations[i].d(detaching);\n }\n}\nfunction element(name) {\n return document.createElement(name);\n}\nfunction element_is(name, is) {\n return document.createElement(name, { is });\n}\nfunction object_without_properties(obj, exclude) {\n // eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion\n const target = {};\n for (const k in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, k)\n // @ts-ignore\n && exclude.indexOf(k) === -1) {\n // @ts-ignore\n target[k] = obj[k];\n }\n }\n return target;\n}\nfunction svg_element(name) {\n return document.createElementNS('http://www.w3.org/2000/svg', name);\n}\nfunction text(data) {\n return document.createTextNode(data);\n}\nfunction space() {\n return text(' ');\n}\nfunction empty() {\n return text('');\n}\nfunction listen(node, event, handler, options) {\n node.addEventListener(event, handler, options);\n return () => node.removeEventListener(event, handler, options);\n}\nfunction prevent_default(fn) {\n return function (event) {\n event.preventDefault();\n // @ts-ignore\n return fn.call(this, event);\n };\n}\nfunction stop_propagation(fn) {\n return function (event) {\n event.stopPropagation();\n // @ts-ignore\n return fn.call(this, event);\n };\n}\nfunction self(fn) {\n return function (event) {\n // @ts-ignore\n if (event.target === this)\n fn.call(this, event);\n };\n}\nfunction attr(node, attribute, value) {\n if (value == null)\n node.removeAttribute(attribute);\n else\n node.setAttribute(attribute, value);\n}\nfunction set_attributes(node, attributes) {\n for (const key in attributes) {\n if (key === 'style') {\n node.style.cssText = attributes[key];\n }\n else if (key in node) {\n node[key] = attributes[key];\n }\n else {\n attr(node, key, attributes[key]);\n }\n }\n}\nfunction set_svg_attributes(node, attributes) {\n for (const key in attributes) {\n attr(node, key, attributes[key]);\n }\n}\nfunction set_custom_element_data(node, prop, value) {\n if (prop in node) {\n node[prop] = value;\n }\n else {\n attr(node, prop, value);\n }\n}\nfunction xlink_attr(node, attribute, value) {\n node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);\n}\nfunction get_binding_group_value(group) {\n const value = [];\n for (let i = 0; i < group.length; i += 1) {\n if (group[i].checked)\n value.push(group[i].__value);\n }\n return value;\n}\nfunction to_number(value) {\n return value === '' ? undefined : +value;\n}\nfunction time_ranges_to_array(ranges) {\n const array = [];\n for (let i = 0; i < ranges.length; i += 1) {\n array.push({ start: ranges.start(i), end: ranges.end(i) });\n }\n return array;\n}\nfunction children(element) {\n return Array.from(element.childNodes);\n}\nfunction claim_element(nodes, name, attributes, svg) {\n for (let i = 0; i < nodes.length; i += 1) {\n const node = nodes[i];\n if (node.nodeName === name) {\n for (let j = 0; j < node.attributes.length; j += 1) {\n const attribute = node.attributes[j];\n if (!attributes[attribute.name])\n node.removeAttribute(attribute.name);\n }\n return nodes.splice(i, 1)[0]; // TODO strip unwanted attributes\n }\n }\n return svg ? svg_element(name) : element(name);\n}\nfunction claim_text(nodes, data) {\n for (let i = 0; i < nodes.length; i += 1) {\n const node = nodes[i];\n if (node.nodeType === 3) {\n node.data = '' + data;\n return nodes.splice(i, 1)[0];\n }\n }\n return text(data);\n}\nfunction claim_space(nodes) {\n return claim_text(nodes, ' ');\n}\nfunction set_data(text, data) {\n data = '' + data;\n if (text.data !== data)\n text.data = data;\n}\nfunction set_input_value(input, value) {\n if (value != null || input.value) {\n input.value = value;\n }\n}\nfunction set_input_type(input, type) {\n try {\n input.type = type;\n }\n catch (e) {\n // do nothing\n }\n}\nfunction set_style(node, key, value, important) {\n node.style.setProperty(key, value, important ? 'important' : '');\n}\nfunction select_option(select, value) {\n for (let i = 0; i < select.options.length; i += 1) {\n const option = select.options[i];\n if (option.__value === value) {\n option.selected = true;\n return;\n }\n }\n}\nfunction select_options(select, value) {\n for (let i = 0; i < select.options.length; i += 1) {\n const option = select.options[i];\n option.selected = ~value.indexOf(option.__value);\n }\n}\nfunction select_value(select) {\n const selected_option = select.querySelector(':checked') || select.options[0];\n return selected_option && selected_option.__value;\n}\nfunction select_multiple_value(select) {\n return [].map.call(select.querySelectorAll(':checked'), option => option.__value);\n}\nfunction add_resize_listener(element, fn) {\n if (getComputedStyle(element).position === 'static') {\n element.style.position = 'relative';\n }\n const object = document.createElement('object');\n object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');\n object.type = 'text/html';\n object.tabIndex = -1;\n let win;\n object.onload = () => {\n win = object.contentDocument.defaultView;\n win.addEventListener('resize', fn);\n };\n if (/Trident/.test(navigator.userAgent)) {\n element.appendChild(object);\n object.data = 'about:blank';\n }\n else {\n object.data = 'about:blank';\n element.appendChild(object);\n }\n return {\n cancel: () => {\n win && win.removeEventListener && win.removeEventListener('resize', fn);\n element.removeChild(object);\n }\n };\n}\nfunction toggle_class(element, name, toggle) {\n element.classList[toggle ? 'add' : 'remove'](name);\n}\nfunction custom_event(type, detail) {\n const e = document.createEvent('CustomEvent');\n e.initCustomEvent(type, false, false, detail);\n return e;\n}\nclass HtmlTag {\n constructor(html, anchor = null) {\n this.e = element('div');\n this.a = anchor;\n this.u(html);\n }\n m(target, anchor = null) {\n for (let i = 0; i < this.n.length; i += 1) {\n insert(target, this.n[i], anchor);\n }\n this.t = target;\n }\n u(html) {\n this.e.innerHTML = html;\n this.n = Array.from(this.e.childNodes);\n }\n p(html) {\n this.d();\n this.u(html);\n this.m(this.t, this.a);\n }\n d() {\n this.n.forEach(detach);\n }\n}\n\nlet stylesheet;\nlet active = 0;\nlet current_rules = {};\n// https://github.com/darkskyapp/string-hash/blob/master/index.js\nfunction hash(str) {\n let hash = 5381;\n let i = str.length;\n while (i--)\n hash = ((hash << 5) - hash) ^ str.charCodeAt(i);\n return hash >>> 0;\n}\nfunction create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {\n const step = 16.666 / duration;\n let keyframes = '{\\n';\n for (let p = 0; p <= 1; p += step) {\n const t = a + (b - a) * ease(p);\n keyframes += p * 100 + `%{${fn(t, 1 - t)}}\\n`;\n }\n const rule = keyframes + `100% {${fn(b, 1 - b)}}\\n}`;\n const name = `__svelte_${hash(rule)}_${uid}`;\n if (!current_rules[name]) {\n if (!stylesheet) {\n const style = element('style');\n document.head.appendChild(style);\n stylesheet = style.sheet;\n }\n current_rules[name] = true;\n stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);\n }\n const animation = node.style.animation || '';\n node.style.animation = `${animation ? `${animation}, ` : ``}${name} ${duration}ms linear ${delay}ms 1 both`;\n active += 1;\n return name;\n}\nfunction delete_rule(node, name) {\n node.style.animation = (node.style.animation || '')\n .split(', ')\n .filter(name\n ? anim => anim.indexOf(name) < 0 // remove specific animation\n : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations\n )\n .join(', ');\n if (name && !--active)\n clear_rules();\n}\nfunction clear_rules() {\n raf(() => {\n if (active)\n return;\n let i = stylesheet.cssRules.length;\n while (i--)\n stylesheet.deleteRule(i);\n current_rules = {};\n });\n}\n\nfunction create_animation(node, from, fn, params) {\n if (!from)\n return noop;\n const to = node.getBoundingClientRect();\n if (from.left === to.left && from.right === to.right && from.top === to.top && from.bottom === to.bottom)\n return noop;\n const { delay = 0, duration = 300, easing = identity, \n // @ts-ignore todo: should this be separated from destructuring? Or start/end added to public api and documentation?\n start: start_time = now() + delay, \n // @ts-ignore todo:\n end = start_time + duration, tick = noop, css } = fn(node, { from, to }, params);\n let running = true;\n let started = false;\n let name;\n function start() {\n if (css) {\n name = create_rule(node, 0, 1, duration, delay, easing, css);\n }\n if (!delay) {\n started = true;\n }\n }\n function stop() {\n if (css)\n delete_rule(node, name);\n running = false;\n }\n loop(now => {\n if (!started && now >= start_time) {\n started = true;\n }\n if (started && now >= end) {\n tick(1, 0);\n stop();\n }\n if (!running) {\n return false;\n }\n if (started) {\n const p = now - start_time;\n const t = 0 + 1 * easing(p / duration);\n tick(t, 1 - t);\n }\n return true;\n });\n start();\n tick(0, 1);\n return stop;\n}\nfunction fix_position(node) {\n const style = getComputedStyle(node);\n if (style.position !== 'absolute' && style.position !== 'fixed') {\n const { width, height } = style;\n const a = node.getBoundingClientRect();\n node.style.position = 'absolute';\n node.style.width = width;\n node.style.height = height;\n add_transform(node, a);\n }\n}\nfunction add_transform(node, a) {\n const b = node.getBoundingClientRect();\n if (a.left !== b.left || a.top !== b.top) {\n const style = getComputedStyle(node);\n const transform = style.transform === 'none' ? '' : style.transform;\n node.style.transform = `${transform} translate(${a.left - b.left}px, ${a.top - b.top}px)`;\n }\n}\n\nlet current_component;\nfunction set_current_component(component) {\n current_component = component;\n}\nfunction get_current_component() {\n if (!current_component)\n throw new Error(`Function called outside component initialization`);\n return current_component;\n}\nfunction beforeUpdate(fn) {\n get_current_component().$$.before_update.push(fn);\n}\nfunction onMount(fn) {\n get_current_component().$$.on_mount.push(fn);\n}\nfunction afterUpdate(fn) {\n get_current_component().$$.after_update.push(fn);\n}\nfunction onDestroy(fn) {\n get_current_component().$$.on_destroy.push(fn);\n}\nfunction createEventDispatcher() {\n const component = current_component;\n return (type, detail) => {\n const callbacks = component.$$.callbacks[type];\n if (callbacks) {\n // TODO are there situations where events could be dispatched\n // in a server (non-DOM) environment?\n const event = custom_event(type, detail);\n callbacks.slice().forEach(fn => {\n fn.call(component, event);\n });\n }\n };\n}\nfunction setContext(key, context) {\n get_current_component().$$.context.set(key, context);\n}\nfunction getContext(key) {\n return get_current_component().$$.context.get(key);\n}\n// TODO figure out if we still want to support\n// shorthand events, or if we want to implement\n// a real bubbling mechanism\nfunction bubble(component, event) {\n const callbacks = component.$$.callbacks[event.type];\n if (callbacks) {\n callbacks.slice().forEach(fn => fn(event));\n }\n}\n\nconst dirty_components = [];\nconst intros = { enabled: false };\nconst binding_callbacks = [];\nconst render_callbacks = [];\nconst flush_callbacks = [];\nconst resolved_promise = Promise.resolve();\nlet update_scheduled = false;\nfunction schedule_update() {\n if (!update_scheduled) {\n update_scheduled = true;\n resolved_promise.then(flush);\n }\n}\nfunction tick() {\n schedule_update();\n return resolved_promise;\n}\nfunction add_render_callback(fn) {\n render_callbacks.push(fn);\n}\nfunction add_flush_callback(fn) {\n flush_callbacks.push(fn);\n}\nfunction flush() {\n const seen_callbacks = new Set();\n do {\n // first, call beforeUpdate functions\n // and update components\n while (dirty_components.length) {\n const component = dirty_components.shift();\n set_current_component(component);\n update(component.$$);\n }\n while (binding_callbacks.length)\n binding_callbacks.pop()();\n // then, once components are updated, call\n // afterUpdate functions. This may cause\n // subsequent updates...\n for (let i = 0; i < render_callbacks.length; i += 1) {\n const callback = render_callbacks[i];\n if (!seen_callbacks.has(callback)) {\n callback();\n // ...so guard against infinite loops\n seen_callbacks.add(callback);\n }\n }\n render_callbacks.length = 0;\n } while (dirty_components.length);\n while (flush_callbacks.length) {\n flush_callbacks.pop()();\n }\n update_scheduled = false;\n}\nfunction update($$) {\n if ($$.fragment) {\n $$.update($$.dirty);\n run_all($$.before_update);\n $$.fragment.p($$.dirty, $$.ctx);\n $$.dirty = null;\n $$.after_update.forEach(add_render_callback);\n }\n}\n\nlet promise;\nfunction wait() {\n if (!promise) {\n promise = Promise.resolve();\n promise.then(() => {\n promise = null;\n });\n }\n return promise;\n}\nfunction dispatch(node, direction, kind) {\n node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));\n}\nconst outroing = new Set();\nlet outros;\nfunction group_outros() {\n outros = {\n r: 0,\n c: [],\n p: outros // parent group\n };\n}\nfunction check_outros() {\n if (!outros.r) {\n run_all(outros.c);\n }\n outros = outros.p;\n}\nfunction transition_in(block, local) {\n if (block && block.i) {\n outroing.delete(block);\n block.i(local);\n }\n}\nfunction transition_out(block, local, detach, callback) {\n if (block && block.o) {\n if (outroing.has(block))\n return;\n outroing.add(block);\n outros.c.push(() => {\n outroing.delete(block);\n if (callback) {\n if (detach)\n block.d(1);\n callback();\n }\n });\n block.o(local);\n }\n}\nconst null_transition = { duration: 0 };\nfunction create_in_transition(node, fn, params) {\n let config = fn(node, params);\n let running = false;\n let animation_name;\n let task;\n let uid = 0;\n function cleanup() {\n if (animation_name)\n delete_rule(node, animation_name);\n }\n function go() {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n if (css)\n animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);\n tick(0, 1);\n const start_time = now() + delay;\n const end_time = start_time + duration;\n if (task)\n task.abort();\n running = true;\n add_render_callback(() => dispatch(node, true, 'start'));\n task = loop(now => {\n if (running) {\n if (now >= end_time) {\n tick(1, 0);\n dispatch(node, true, 'end');\n cleanup();\n return running = false;\n }\n if (now >= start_time) {\n const t = easing((now - start_time) / duration);\n tick(t, 1 - t);\n }\n }\n return running;\n });\n }\n let started = false;\n return {\n start() {\n if (started)\n return;\n delete_rule(node);\n if (is_function(config)) {\n config = config();\n wait().then(go);\n }\n else {\n go();\n }\n },\n invalidate() {\n started = false;\n },\n end() {\n if (running) {\n cleanup();\n running = false;\n }\n }\n };\n}\nfunction create_out_transition(node, fn, params) {\n let config = fn(node, params);\n let running = true;\n let animation_name;\n const group = outros;\n group.r += 1;\n function go() {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n if (css)\n animation_name = create_rule(node, 1, 0, duration, delay, easing, css);\n const start_time = now() + delay;\n const end_time = start_time + duration;\n add_render_callback(() => dispatch(node, false, 'start'));\n loop(now => {\n if (running) {\n if (now >= end_time) {\n tick(0, 1);\n dispatch(node, false, 'end');\n if (!--group.r) {\n // this will result in `end()` being called,\n // so we don't need to clean up here\n run_all(group.c);\n }\n return false;\n }\n if (now >= start_time) {\n const t = easing((now - start_time) / duration);\n tick(1 - t, t);\n }\n }\n return running;\n });\n }\n if (is_function(config)) {\n wait().then(() => {\n // @ts-ignore\n config = config();\n go();\n });\n }\n else {\n go();\n }\n return {\n end(reset) {\n if (reset && config.tick) {\n config.tick(1, 0);\n }\n if (running) {\n if (animation_name)\n delete_rule(node, animation_name);\n running = false;\n }\n }\n };\n}\nfunction create_bidirectional_transition(node, fn, params, intro) {\n let config = fn(node, params);\n let t = intro ? 0 : 1;\n let running_program = null;\n let pending_program = null;\n let animation_name = null;\n function clear_animation() {\n if (animation_name)\n delete_rule(node, animation_name);\n }\n function init(program, duration) {\n const d = program.b - t;\n duration *= Math.abs(d);\n return {\n a: t,\n b: program.b,\n d,\n duration,\n start: program.start,\n end: program.start + duration,\n group: program.group\n };\n }\n function go(b) {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n const program = {\n start: now() + delay,\n b\n };\n if (!b) {\n // @ts-ignore todo: improve typings\n program.group = outros;\n outros.r += 1;\n }\n if (running_program) {\n pending_program = program;\n }\n else {\n // if this is an intro, and there's a delay, we need to do\n // an initial tick and/or apply CSS animation immediately\n if (css) {\n clear_animation();\n animation_name = create_rule(node, t, b, duration, delay, easing, css);\n }\n if (b)\n tick(0, 1);\n running_program = init(program, duration);\n add_render_callback(() => dispatch(node, b, 'start'));\n loop(now => {\n if (pending_program && now > pending_program.start) {\n running_program = init(pending_program, duration);\n pending_program = null;\n dispatch(node, running_program.b, 'start');\n if (css) {\n clear_animation();\n animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);\n }\n }\n if (running_program) {\n if (now >= running_program.end) {\n tick(t = running_program.b, 1 - t);\n dispatch(node, running_program.b, 'end');\n if (!pending_program) {\n // we're done\n if (running_program.b) {\n // intro — we can tidy up immediately\n clear_animation();\n }\n else {\n // outro — needs to be coordinated\n if (!--running_program.group.r)\n run_all(running_program.group.c);\n }\n }\n running_program = null;\n }\n else if (now >= running_program.start) {\n const p = now - running_program.start;\n t = running_program.a + running_program.d * easing(p / running_program.duration);\n tick(t, 1 - t);\n }\n }\n return !!(running_program || pending_program);\n });\n }\n }\n return {\n run(b) {\n if (is_function(config)) {\n wait().then(() => {\n // @ts-ignore\n config = config();\n go(b);\n });\n }\n else {\n go(b);\n }\n },\n end() {\n clear_animation();\n running_program = pending_program = null;\n }\n };\n}\n\nfunction handle_promise(promise, info) {\n const token = info.token = {};\n function update(type, index, key, value) {\n if (info.token !== token)\n return;\n info.resolved = key && { [key]: value };\n const child_ctx = assign(assign({}, info.ctx), info.resolved);\n const block = type && (info.current = type)(child_ctx);\n if (info.block) {\n if (info.blocks) {\n info.blocks.forEach((block, i) => {\n if (i !== index && block) {\n group_outros();\n transition_out(block, 1, 1, () => {\n info.blocks[i] = null;\n });\n check_outros();\n }\n });\n }\n else {\n info.block.d(1);\n }\n block.c();\n transition_in(block, 1);\n block.m(info.mount(), info.anchor);\n flush();\n }\n info.block = block;\n if (info.blocks)\n info.blocks[index] = block;\n }\n if (is_promise(promise)) {\n const current_component = get_current_component();\n promise.then(value => {\n set_current_component(current_component);\n update(info.then, 1, info.value, value);\n set_current_component(null);\n }, error => {\n set_current_component(current_component);\n update(info.catch, 2, info.error, error);\n set_current_component(null);\n });\n // if we previously had a then/catch block, destroy it\n if (info.current !== info.pending) {\n update(info.pending, 0);\n return true;\n }\n }\n else {\n if (info.current !== info.then) {\n update(info.then, 1, info.value, promise);\n return true;\n }\n info.resolved = { [info.value]: promise };\n }\n}\n\nconst globals = (typeof window !== 'undefined' ? window : global);\n\nfunction destroy_block(block, lookup) {\n block.d(1);\n lookup.delete(block.key);\n}\nfunction outro_and_destroy_block(block, lookup) {\n transition_out(block, 1, 1, () => {\n lookup.delete(block.key);\n });\n}\nfunction fix_and_destroy_block(block, lookup) {\n block.f();\n destroy_block(block, lookup);\n}\nfunction fix_and_outro_and_destroy_block(block, lookup) {\n block.f();\n outro_and_destroy_block(block, lookup);\n}\nfunction update_keyed_each(old_blocks, changed, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block, next, get_context) {\n let o = old_blocks.length;\n let n = list.length;\n let i = o;\n const old_indexes = {};\n while (i--)\n old_indexes[old_blocks[i].key] = i;\n const new_blocks = [];\n const new_lookup = new Map();\n const deltas = new Map();\n i = n;\n while (i--) {\n const child_ctx = get_context(ctx, list, i);\n const key = get_key(child_ctx);\n let block = lookup.get(key);\n if (!block) {\n block = create_each_block(key, child_ctx);\n block.c();\n }\n else if (dynamic) {\n block.p(changed, child_ctx);\n }\n new_lookup.set(key, new_blocks[i] = block);\n if (key in old_indexes)\n deltas.set(key, Math.abs(i - old_indexes[key]));\n }\n const will_move = new Set();\n const did_move = new Set();\n function insert(block) {\n transition_in(block, 1);\n block.m(node, next);\n lookup.set(block.key, block);\n next = block.first;\n n--;\n }\n while (o && n) {\n const new_block = new_blocks[n - 1];\n const old_block = old_blocks[o - 1];\n const new_key = new_block.key;\n const old_key = old_block.key;\n if (new_block === old_block) {\n // do nothing\n next = new_block.first;\n o--;\n n--;\n }\n else if (!new_lookup.has(old_key)) {\n // remove old block\n destroy(old_block, lookup);\n o--;\n }\n else if (!lookup.has(new_key) || will_move.has(new_key)) {\n insert(new_block);\n }\n else if (did_move.has(old_key)) {\n o--;\n }\n else if (deltas.get(new_key) > deltas.get(old_key)) {\n did_move.add(new_key);\n insert(new_block);\n }\n else {\n will_move.add(old_key);\n o--;\n }\n }\n while (o--) {\n const old_block = old_blocks[o];\n if (!new_lookup.has(old_block.key))\n destroy(old_block, lookup);\n }\n while (n)\n insert(new_blocks[n - 1]);\n return new_blocks;\n}\nfunction measure(blocks) {\n const rects = {};\n let i = blocks.length;\n while (i--)\n rects[blocks[i].key] = blocks[i].node.getBoundingClientRect();\n return rects;\n}\n\nfunction get_spread_update(levels, updates) {\n const update = {};\n const to_null_out = {};\n const accounted_for = { $$scope: 1 };\n let i = levels.length;\n while (i--) {\n const o = levels[i];\n const n = updates[i];\n if (n) {\n for (const key in o) {\n if (!(key in n))\n to_null_out[key] = 1;\n }\n for (const key in n) {\n if (!accounted_for[key]) {\n update[key] = n[key];\n accounted_for[key] = 1;\n }\n }\n levels[i] = n;\n }\n else {\n for (const key in o) {\n accounted_for[key] = 1;\n }\n }\n }\n for (const key in to_null_out) {\n if (!(key in update))\n update[key] = undefined;\n }\n return update;\n}\nfunction get_spread_object(spread_props) {\n return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};\n}\n\nconst invalid_attribute_name_character = /[\\s'\">/=\\u{FDD0}-\\u{FDEF}\\u{FFFE}\\u{FFFF}\\u{1FFFE}\\u{1FFFF}\\u{2FFFE}\\u{2FFFF}\\u{3FFFE}\\u{3FFFF}\\u{4FFFE}\\u{4FFFF}\\u{5FFFE}\\u{5FFFF}\\u{6FFFE}\\u{6FFFF}\\u{7FFFE}\\u{7FFFF}\\u{8FFFE}\\u{8FFFF}\\u{9FFFE}\\u{9FFFF}\\u{AFFFE}\\u{AFFFF}\\u{BFFFE}\\u{BFFFF}\\u{CFFFE}\\u{CFFFF}\\u{DFFFE}\\u{DFFFF}\\u{EFFFE}\\u{EFFFF}\\u{FFFFE}\\u{FFFFF}\\u{10FFFE}\\u{10FFFF}]/u;\n// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2\n// https://infra.spec.whatwg.org/#noncharacter\nfunction spread(args) {\n const attributes = Object.assign({}, ...args);\n let str = '';\n Object.keys(attributes).forEach(name => {\n if (invalid_attribute_name_character.test(name))\n return;\n const value = attributes[name];\n if (value === undefined)\n return;\n if (value === true)\n str += \" \" + name;\n const escaped = String(value)\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n str += \" \" + name + \"=\" + JSON.stringify(escaped);\n });\n return str;\n}\nconst escaped = {\n '\"': '"',\n \"'\": ''',\n '&': '&',\n '<': '<',\n '>': '>'\n};\nfunction escape(html) {\n return String(html).replace(/[\"'&<>]/g, match => escaped[match]);\n}\nfunction each(items, fn) {\n let str = '';\n for (let i = 0; i < items.length; i += 1) {\n str += fn(items[i], i);\n }\n return str;\n}\nconst missing_component = {\n $$render: () => ''\n};\nfunction validate_component(component, name) {\n if (!component || !component.$$render) {\n if (name === 'svelte:component')\n name += ' this={...}';\n throw new Error(`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules`);\n }\n return component;\n}\nfunction debug(file, line, column, values) {\n console.log(`{@debug} ${file ? file + ' ' : ''}(${line}:${column})`); // eslint-disable-line no-console\n console.log(values); // eslint-disable-line no-console\n return '';\n}\nlet on_destroy;\nfunction create_ssr_component(fn) {\n function $$render(result, props, bindings, slots) {\n const parent_component = current_component;\n const $$ = {\n on_destroy,\n context: new Map(parent_component ? parent_component.$$.context : []),\n // these will be immediately discarded\n on_mount: [],\n before_update: [],\n after_update: [],\n callbacks: blank_object()\n };\n set_current_component({ $$ });\n const html = fn(result, props, bindings, slots);\n set_current_component(parent_component);\n return html;\n }\n return {\n render: (props = {}, options = {}) => {\n on_destroy = [];\n const result = { head: '', css: new Set() };\n const html = $$render(result, props, {}, options);\n run_all(on_destroy);\n return {\n html,\n css: {\n code: Array.from(result.css).map(css => css.code).join('\\n'),\n map: null // TODO\n },\n head: result.head\n };\n },\n $$render\n };\n}\nfunction add_attribute(name, value, boolean) {\n if (value == null || (boolean && !value))\n return '';\n return ` ${name}${value === true ? '' : `=${typeof value === 'string' ? JSON.stringify(escape(value)) : `\"${value}\"`}`}`;\n}\nfunction add_classes(classes) {\n return classes ? ` class=\"${classes}\"` : ``;\n}\n\nfunction bind(component, name, callback) {\n if (component.$$.props.indexOf(name) === -1)\n return;\n component.$$.bound[name] = callback;\n callback(component.$$.ctx[name]);\n}\nfunction mount_component(component, target, anchor) {\n const { fragment, on_mount, on_destroy, after_update } = component.$$;\n fragment.m(target, anchor);\n // onMount happens before the initial afterUpdate\n add_render_callback(() => {\n const new_on_destroy = on_mount.map(run).filter(is_function);\n if (on_destroy) {\n on_destroy.push(...new_on_destroy);\n }\n else {\n // Edge case - component was destroyed immediately,\n // most likely as a result of a binding initialising\n run_all(new_on_destroy);\n }\n component.$$.on_mount = [];\n });\n after_update.forEach(add_render_callback);\n}\nfunction destroy_component(component, detaching) {\n if (component.$$.fragment) {\n run_all(component.$$.on_destroy);\n component.$$.fragment.d(detaching);\n // TODO null out other refs, including component.$$ (but need to\n // preserve final state?)\n component.$$.on_destroy = component.$$.fragment = null;\n component.$$.ctx = {};\n }\n}\nfunction make_dirty(component, key) {\n if (!component.$$.dirty) {\n dirty_components.push(component);\n schedule_update();\n component.$$.dirty = blank_object();\n }\n component.$$.dirty[key] = true;\n}\nfunction init(component, options, instance, create_fragment, not_equal, prop_names) {\n const parent_component = current_component;\n set_current_component(component);\n const props = options.props || {};\n const $$ = component.$$ = {\n fragment: null,\n ctx: null,\n // state\n props: prop_names,\n update: noop,\n not_equal,\n bound: blank_object(),\n // lifecycle\n on_mount: [],\n on_destroy: [],\n before_update: [],\n after_update: [],\n context: new Map(parent_component ? parent_component.$$.context : []),\n // everything else\n callbacks: blank_object(),\n dirty: null\n };\n let ready = false;\n $$.ctx = instance\n ? instance(component, props, (key, ret, value = ret) => {\n if ($$.ctx && not_equal($$.ctx[key], $$.ctx[key] = value)) {\n if ($$.bound[key])\n $$.bound[key](value);\n if (ready)\n make_dirty(component, key);\n }\n return ret;\n })\n : props;\n $$.update();\n ready = true;\n run_all($$.before_update);\n $$.fragment = create_fragment($$.ctx);\n if (options.target) {\n if (options.hydrate) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n $$.fragment.l(children(options.target));\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n $$.fragment.c();\n }\n if (options.intro)\n transition_in(component.$$.fragment);\n mount_component(component, options.target, options.anchor);\n flush();\n }\n set_current_component(parent_component);\n}\nlet SvelteElement;\nif (typeof HTMLElement !== 'undefined') {\n SvelteElement = class extends HTMLElement {\n constructor() {\n super();\n this.attachShadow({ mode: 'open' });\n }\n connectedCallback() {\n // @ts-ignore todo: improve typings\n for (const key in this.$$.slotted) {\n // @ts-ignore todo: improve typings\n this.appendChild(this.$$.slotted[key]);\n }\n }\n attributeChangedCallback(attr, _oldValue, newValue) {\n this[attr] = newValue;\n }\n $destroy() {\n destroy_component(this, 1);\n this.$destroy = noop;\n }\n $on(type, callback) {\n // TODO should this delegate to addEventListener?\n const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));\n callbacks.push(callback);\n return () => {\n const index = callbacks.indexOf(callback);\n if (index !== -1)\n callbacks.splice(index, 1);\n };\n }\n $set() {\n // overridden by instance, if it has props\n }\n };\n}\nclass SvelteComponent {\n $destroy() {\n destroy_component(this, 1);\n this.$destroy = noop;\n }\n $on(type, callback) {\n const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));\n callbacks.push(callback);\n return () => {\n const index = callbacks.indexOf(callback);\n if (index !== -1)\n callbacks.splice(index, 1);\n };\n }\n $set() {\n // overridden by instance, if it has props\n }\n}\n\nfunction dispatch_dev(type, detail) {\n document.dispatchEvent(custom_event(type, detail));\n}\nfunction append_dev(target, node) {\n dispatch_dev(\"SvelteDOMInsert\", { target, node });\n append(target, node);\n}\nfunction insert_dev(target, node, anchor) {\n dispatch_dev(\"SvelteDOMInsert\", { target, node, anchor });\n insert(target, node, anchor);\n}\nfunction detach_dev(node) {\n dispatch_dev(\"SvelteDOMRemove\", { node });\n detach(node);\n}\nfunction detach_between_dev(before, after) {\n while (before.nextSibling && before.nextSibling !== after) {\n detach_dev(before.nextSibling);\n }\n}\nfunction detach_before_dev(after) {\n while (after.previousSibling) {\n detach_dev(after.previousSibling);\n }\n}\nfunction detach_after_dev(before) {\n while (before.nextSibling) {\n detach_dev(before.nextSibling);\n }\n}\nfunction listen_dev(node, event, handler, options, has_prevent_default, has_stop_propagation) {\n const modifiers = options === true ? [\"capture\"] : options ? Array.from(Object.keys(options)) : [];\n if (has_prevent_default)\n modifiers.push('preventDefault');\n if (has_stop_propagation)\n modifiers.push('stopPropagation');\n dispatch_dev(\"SvelteDOMAddEventListener\", { node, event, handler, modifiers });\n const dispose = listen(node, event, handler, options);\n return () => {\n dispatch_dev(\"SvelteDOMRemoveEventListener\", { node, event, handler, modifiers });\n dispose();\n };\n}\nfunction attr_dev(node, attribute, value) {\n attr(node, attribute, value);\n if (value == null)\n dispatch_dev(\"SvelteDOMRemoveAttribute\", { node, attribute });\n else\n dispatch_dev(\"SvelteDOMSetAttribute\", { node, attribute, value });\n}\nfunction prop_dev(node, property, value) {\n node[property] = value;\n dispatch_dev(\"SvelteDOMSetProperty\", { node, property, value });\n}\nfunction dataset_dev(node, property, value) {\n node.dataset[property] = value;\n dispatch_dev(\"SvelteDOMSetDataset\", { node, property, value });\n}\nfunction set_data_dev(text, data) {\n data = '' + data;\n if (text.data === data)\n return;\n dispatch_dev(\"SvelteDOMSetData\", { node: text, data });\n text.data = data;\n}\nclass SvelteComponentDev extends SvelteComponent {\n constructor(options) {\n if (!options || (!options.target && !options.$$inline)) {\n throw new Error(`'target' is a required option`);\n }\n super();\n }\n $destroy() {\n super.$destroy();\n this.$destroy = () => {\n console.warn(`Component was already destroyed`); // eslint-disable-line no-console\n };\n }\n}\n\nexport { HtmlTag, SvelteComponent, SvelteComponentDev, SvelteElement, add_attribute, add_classes, add_flush_callback, add_location, add_render_callback, add_resize_listener, add_transform, afterUpdate, append, append_dev, assign, attr, attr_dev, beforeUpdate, bind, binding_callbacks, blank_object, bubble, check_outros, children, claim_element, claim_space, claim_text, clear_loops, component_subscribe, createEventDispatcher, create_animation, create_bidirectional_transition, create_in_transition, create_out_transition, create_slot, create_ssr_component, current_component, custom_event, dataset_dev, debug, destroy_block, destroy_component, destroy_each, detach, detach_after_dev, detach_before_dev, detach_between_dev, detach_dev, dirty_components, dispatch_dev, each, element, element_is, empty, escape, escaped, exclude_internal_props, fix_and_destroy_block, fix_and_outro_and_destroy_block, fix_position, flush, getContext, get_binding_group_value, get_current_component, get_slot_changes, get_slot_context, get_spread_object, get_spread_update, get_store_value, globals, group_outros, handle_promise, identity, init, insert, insert_dev, intros, invalid_attribute_name_character, is_client, is_function, is_promise, listen, listen_dev, loop, measure, missing_component, mount_component, noop, not_equal, now, null_to_empty, object_without_properties, onDestroy, onMount, once, outro_and_destroy_block, prevent_default, prop_dev, raf, run, run_all, safe_not_equal, schedule_update, select_multiple_value, select_option, select_options, select_value, self, setContext, set_attributes, set_current_component, set_custom_element_data, set_data, set_data_dev, set_input_type, set_input_value, set_now, set_raf, set_store_value, set_style, set_svg_attributes, space, spread, stop_propagation, subscribe, svg_element, text, tick, time_ranges_to_array, to_number, toggle_class, transition_in, transition_out, update_keyed_each, validate_component, validate_store, xlink_attr };\n","\n\n\n\n\n\n","\n\n{#if hideValue}\n\n{:else}\n\n{/if}\n\n","\n\n
\n {#each formControls as child, index}\n
{labels[index]}
\n
\n
\n {/each}\n
\n\n","\r\nconst apiCall = (method) => (url, body) => \r\n fetch(url, {\r\n method: method,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n body: body && JSON.stringify(body), \r\n });\r\n\r\nexport const post = apiCall(\"POST\");\r\nexport const get = apiCall(\"GET\");\r\nexport const patch = apiCall(\"PATCH\");\r\nexport const del = apiCall(\"DELETE\");\r\n\r\nexport const authenticate = (username, password) => post(\"./api/authenticate\", {\r\n username, password\r\n});\r\n\r\nexport default {\r\npost, get, patch, delete:del\r\n};","\n\n
\n\n
\n\n {#if logo}\n
\n \"logo\"/\n
\n {/if}\n\n
\n
\n {usernameLabel}\n
\n
\n \n
\n
\n {passwordLabel}\n
\n
\n \n
\n
\n\n
\n \n
\n\n {#if incorrect}\n
\n Incorrect username or password\n
\n {/if}\n\n
\n\n
\n\n","export const buildStyle = (styles) => {\r\n let str = \"\";\r\n for(let s in styles) {\r\n if(styles[s]) {\r\n str += `${s}: ${styles[s]}; `\r\n }\r\n }\r\n return str;\r\n}","\r\n\r\n
\r\n {#each children as child, index}\r\n
\r\n
\r\n {/each}\r\n
\r\n\r\n","\n\n
\n {#each children as child, index}\n
\n
\n
\n
\n {/each}\n
\n\n"],"names":[],"mappings":"AAAA,SAAS,IAAI,GAAG,GAAG;AACnB,AACA,SAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE;;IAEtB,KAAK,MAAM,CAAC,IAAI,GAAG;QACf,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,GAAG,CAAC;CACd;AACD,AAQA,SAAS,GAAG,CAAC,EAAE,EAAE;IACb,OAAO,EAAE,EAAE,CAAC;CACf;AACD,SAAS,YAAY,GAAG;IACpB,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC9B;AACD,SAAS,OAAO,CAAC,GAAG,EAAE;IAClB,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;CACpB;AACD,SAAS,WAAW,CAAC,KAAK,EAAE;IACxB,OAAO,OAAO,KAAK,KAAK,UAAU,CAAC;CACtC;AACD,SAAS,cAAc,CAAC,CAAC,EAAE,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AAI,IAAI,EAAE,IAAI,YAAY,EAAE;YACxB,IAAI,CAAC,mBAAmB;gBACpB,QAAQ,CAAC,EAAE,CAAC,CAAC,OAAO;gBACpB,YAAY,CAAC,EAAE,CAAC;aACnB,CAAC;SACL;KACJ;CACJ,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"index.js","sources":["../node_modules/svelte/internal/index.js","../src/Button.svelte","../src/Textbox.svelte","../src/Form.svelte","../src/api.js","../src/Login.svelte","../src/buildStyle.js","../src/Grid.svelte","../src/StackPanel.svelte"],"sourcesContent":["function noop() { }\nconst identity = x => x;\nfunction assign(tar, src) {\n // @ts-ignore\n for (const k in src)\n tar[k] = src[k];\n return tar;\n}\nfunction is_promise(value) {\n return value && typeof value === 'object' && typeof value.then === 'function';\n}\nfunction add_location(element, file, line, column, char) {\n element.__svelte_meta = {\n loc: { file, line, column, char }\n };\n}\nfunction run(fn) {\n return fn();\n}\nfunction blank_object() {\n return Object.create(null);\n}\nfunction run_all(fns) {\n fns.forEach(run);\n}\nfunction is_function(thing) {\n return typeof thing === 'function';\n}\nfunction safe_not_equal(a, b) {\n return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');\n}\nfunction not_equal(a, b) {\n return a != a ? b == b : a !== b;\n}\nfunction validate_store(store, name) {\n if (!store || typeof store.subscribe !== 'function') {\n throw new Error(`'${name}' is not a store with a 'subscribe' method`);\n }\n}\nfunction subscribe(store, callback) {\n const unsub = store.subscribe(callback);\n return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\nfunction get_store_value(store) {\n let value;\n subscribe(store, _ => value = _)();\n return value;\n}\nfunction component_subscribe(component, store, callback) {\n component.$$.on_destroy.push(subscribe(store, callback));\n}\nfunction create_slot(definition, ctx, fn) {\n if (definition) {\n const slot_ctx = get_slot_context(definition, ctx, fn);\n return definition[0](slot_ctx);\n }\n}\nfunction get_slot_context(definition, ctx, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.ctx, definition[1](fn ? fn(ctx) : {})))\n : ctx.$$scope.ctx;\n}\nfunction get_slot_changes(definition, ctx, changed, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.changed || {}, definition[1](fn ? fn(changed) : {})))\n : ctx.$$scope.changed || {};\n}\nfunction exclude_internal_props(props) {\n const result = {};\n for (const k in props)\n if (k[0] !== '$')\n result[k] = props[k];\n return result;\n}\nfunction once(fn) {\n let ran = false;\n return function (...args) {\n if (ran)\n return;\n ran = true;\n fn.call(this, ...args);\n };\n}\nfunction null_to_empty(value) {\n return value == null ? '' : value;\n}\nfunction set_store_value(store, ret, value = ret) {\n store.set(value);\n return ret;\n}\n\nconst is_client = typeof window !== 'undefined';\nlet now = is_client\n ? () => window.performance.now()\n : () => Date.now();\nlet raf = is_client ? cb => requestAnimationFrame(cb) : noop;\n// used internally for testing\nfunction set_now(fn) {\n now = fn;\n}\nfunction set_raf(fn) {\n raf = fn;\n}\n\nconst tasks = new Set();\nlet running = false;\nfunction run_tasks() {\n tasks.forEach(task => {\n if (!task[0](now())) {\n tasks.delete(task);\n task[1]();\n }\n });\n running = tasks.size > 0;\n if (running)\n raf(run_tasks);\n}\nfunction clear_loops() {\n // for testing...\n tasks.forEach(task => tasks.delete(task));\n running = false;\n}\nfunction loop(fn) {\n let task;\n if (!running) {\n running = true;\n raf(run_tasks);\n }\n return {\n promise: new Promise(fulfil => {\n tasks.add(task = [fn, fulfil]);\n }),\n abort() {\n tasks.delete(task);\n }\n };\n}\n\nfunction append(target, node) {\n target.appendChild(node);\n}\nfunction insert(target, node, anchor) {\n target.insertBefore(node, anchor || null);\n}\nfunction detach(node) {\n node.parentNode.removeChild(node);\n}\nfunction destroy_each(iterations, detaching) {\n for (let i = 0; i < iterations.length; i += 1) {\n if (iterations[i])\n iterations[i].d(detaching);\n }\n}\nfunction element(name) {\n return document.createElement(name);\n}\nfunction element_is(name, is) {\n return document.createElement(name, { is });\n}\nfunction object_without_properties(obj, exclude) {\n // eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion\n const target = {};\n for (const k in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, k)\n // @ts-ignore\n && exclude.indexOf(k) === -1) {\n // @ts-ignore\n target[k] = obj[k];\n }\n }\n return target;\n}\nfunction svg_element(name) {\n return document.createElementNS('http://www.w3.org/2000/svg', name);\n}\nfunction text(data) {\n return document.createTextNode(data);\n}\nfunction space() {\n return text(' ');\n}\nfunction empty() {\n return text('');\n}\nfunction listen(node, event, handler, options) {\n node.addEventListener(event, handler, options);\n return () => node.removeEventListener(event, handler, options);\n}\nfunction prevent_default(fn) {\n return function (event) {\n event.preventDefault();\n // @ts-ignore\n return fn.call(this, event);\n };\n}\nfunction stop_propagation(fn) {\n return function (event) {\n event.stopPropagation();\n // @ts-ignore\n return fn.call(this, event);\n };\n}\nfunction self(fn) {\n return function (event) {\n // @ts-ignore\n if (event.target === this)\n fn.call(this, event);\n };\n}\nfunction attr(node, attribute, value) {\n if (value == null)\n node.removeAttribute(attribute);\n else\n node.setAttribute(attribute, value);\n}\nfunction set_attributes(node, attributes) {\n for (const key in attributes) {\n if (key === 'style') {\n node.style.cssText = attributes[key];\n }\n else if (key in node) {\n node[key] = attributes[key];\n }\n else {\n attr(node, key, attributes[key]);\n }\n }\n}\nfunction set_svg_attributes(node, attributes) {\n for (const key in attributes) {\n attr(node, key, attributes[key]);\n }\n}\nfunction set_custom_element_data(node, prop, value) {\n if (prop in node) {\n node[prop] = value;\n }\n else {\n attr(node, prop, value);\n }\n}\nfunction xlink_attr(node, attribute, value) {\n node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);\n}\nfunction get_binding_group_value(group) {\n const value = [];\n for (let i = 0; i < group.length; i += 1) {\n if (group[i].checked)\n value.push(group[i].__value);\n }\n return value;\n}\nfunction to_number(value) {\n return value === '' ? undefined : +value;\n}\nfunction time_ranges_to_array(ranges) {\n const array = [];\n for (let i = 0; i < ranges.length; i += 1) {\n array.push({ start: ranges.start(i), end: ranges.end(i) });\n }\n return array;\n}\nfunction children(element) {\n return Array.from(element.childNodes);\n}\nfunction claim_element(nodes, name, attributes, svg) {\n for (let i = 0; i < nodes.length; i += 1) {\n const node = nodes[i];\n if (node.nodeName === name) {\n for (let j = 0; j < node.attributes.length; j += 1) {\n const attribute = node.attributes[j];\n if (!attributes[attribute.name])\n node.removeAttribute(attribute.name);\n }\n return nodes.splice(i, 1)[0]; // TODO strip unwanted attributes\n }\n }\n return svg ? svg_element(name) : element(name);\n}\nfunction claim_text(nodes, data) {\n for (let i = 0; i < nodes.length; i += 1) {\n const node = nodes[i];\n if (node.nodeType === 3) {\n node.data = '' + data;\n return nodes.splice(i, 1)[0];\n }\n }\n return text(data);\n}\nfunction claim_space(nodes) {\n return claim_text(nodes, ' ');\n}\nfunction set_data(text, data) {\n data = '' + data;\n if (text.data !== data)\n text.data = data;\n}\nfunction set_input_value(input, value) {\n if (value != null || input.value) {\n input.value = value;\n }\n}\nfunction set_input_type(input, type) {\n try {\n input.type = type;\n }\n catch (e) {\n // do nothing\n }\n}\nfunction set_style(node, key, value, important) {\n node.style.setProperty(key, value, important ? 'important' : '');\n}\nfunction select_option(select, value) {\n for (let i = 0; i < select.options.length; i += 1) {\n const option = select.options[i];\n if (option.__value === value) {\n option.selected = true;\n return;\n }\n }\n}\nfunction select_options(select, value) {\n for (let i = 0; i < select.options.length; i += 1) {\n const option = select.options[i];\n option.selected = ~value.indexOf(option.__value);\n }\n}\nfunction select_value(select) {\n const selected_option = select.querySelector(':checked') || select.options[0];\n return selected_option && selected_option.__value;\n}\nfunction select_multiple_value(select) {\n return [].map.call(select.querySelectorAll(':checked'), option => option.__value);\n}\nfunction add_resize_listener(element, fn) {\n if (getComputedStyle(element).position === 'static') {\n element.style.position = 'relative';\n }\n const object = document.createElement('object');\n object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');\n object.type = 'text/html';\n object.tabIndex = -1;\n let win;\n object.onload = () => {\n win = object.contentDocument.defaultView;\n win.addEventListener('resize', fn);\n };\n if (/Trident/.test(navigator.userAgent)) {\n element.appendChild(object);\n object.data = 'about:blank';\n }\n else {\n object.data = 'about:blank';\n element.appendChild(object);\n }\n return {\n cancel: () => {\n win && win.removeEventListener && win.removeEventListener('resize', fn);\n element.removeChild(object);\n }\n };\n}\nfunction toggle_class(element, name, toggle) {\n element.classList[toggle ? 'add' : 'remove'](name);\n}\nfunction custom_event(type, detail) {\n const e = document.createEvent('CustomEvent');\n e.initCustomEvent(type, false, false, detail);\n return e;\n}\nclass HtmlTag {\n constructor(html, anchor = null) {\n this.e = element('div');\n this.a = anchor;\n this.u(html);\n }\n m(target, anchor = null) {\n for (let i = 0; i < this.n.length; i += 1) {\n insert(target, this.n[i], anchor);\n }\n this.t = target;\n }\n u(html) {\n this.e.innerHTML = html;\n this.n = Array.from(this.e.childNodes);\n }\n p(html) {\n this.d();\n this.u(html);\n this.m(this.t, this.a);\n }\n d() {\n this.n.forEach(detach);\n }\n}\n\nlet stylesheet;\nlet active = 0;\nlet current_rules = {};\n// https://github.com/darkskyapp/string-hash/blob/master/index.js\nfunction hash(str) {\n let hash = 5381;\n let i = str.length;\n while (i--)\n hash = ((hash << 5) - hash) ^ str.charCodeAt(i);\n return hash >>> 0;\n}\nfunction create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {\n const step = 16.666 / duration;\n let keyframes = '{\\n';\n for (let p = 0; p <= 1; p += step) {\n const t = a + (b - a) * ease(p);\n keyframes += p * 100 + `%{${fn(t, 1 - t)}}\\n`;\n }\n const rule = keyframes + `100% {${fn(b, 1 - b)}}\\n}`;\n const name = `__svelte_${hash(rule)}_${uid}`;\n if (!current_rules[name]) {\n if (!stylesheet) {\n const style = element('style');\n document.head.appendChild(style);\n stylesheet = style.sheet;\n }\n current_rules[name] = true;\n stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);\n }\n const animation = node.style.animation || '';\n node.style.animation = `${animation ? `${animation}, ` : ``}${name} ${duration}ms linear ${delay}ms 1 both`;\n active += 1;\n return name;\n}\nfunction delete_rule(node, name) {\n node.style.animation = (node.style.animation || '')\n .split(', ')\n .filter(name\n ? anim => anim.indexOf(name) < 0 // remove specific animation\n : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations\n )\n .join(', ');\n if (name && !--active)\n clear_rules();\n}\nfunction clear_rules() {\n raf(() => {\n if (active)\n return;\n let i = stylesheet.cssRules.length;\n while (i--)\n stylesheet.deleteRule(i);\n current_rules = {};\n });\n}\n\nfunction create_animation(node, from, fn, params) {\n if (!from)\n return noop;\n const to = node.getBoundingClientRect();\n if (from.left === to.left && from.right === to.right && from.top === to.top && from.bottom === to.bottom)\n return noop;\n const { delay = 0, duration = 300, easing = identity, \n // @ts-ignore todo: should this be separated from destructuring? Or start/end added to public api and documentation?\n start: start_time = now() + delay, \n // @ts-ignore todo:\n end = start_time + duration, tick = noop, css } = fn(node, { from, to }, params);\n let running = true;\n let started = false;\n let name;\n function start() {\n if (css) {\n name = create_rule(node, 0, 1, duration, delay, easing, css);\n }\n if (!delay) {\n started = true;\n }\n }\n function stop() {\n if (css)\n delete_rule(node, name);\n running = false;\n }\n loop(now => {\n if (!started && now >= start_time) {\n started = true;\n }\n if (started && now >= end) {\n tick(1, 0);\n stop();\n }\n if (!running) {\n return false;\n }\n if (started) {\n const p = now - start_time;\n const t = 0 + 1 * easing(p / duration);\n tick(t, 1 - t);\n }\n return true;\n });\n start();\n tick(0, 1);\n return stop;\n}\nfunction fix_position(node) {\n const style = getComputedStyle(node);\n if (style.position !== 'absolute' && style.position !== 'fixed') {\n const { width, height } = style;\n const a = node.getBoundingClientRect();\n node.style.position = 'absolute';\n node.style.width = width;\n node.style.height = height;\n add_transform(node, a);\n }\n}\nfunction add_transform(node, a) {\n const b = node.getBoundingClientRect();\n if (a.left !== b.left || a.top !== b.top) {\n const style = getComputedStyle(node);\n const transform = style.transform === 'none' ? '' : style.transform;\n node.style.transform = `${transform} translate(${a.left - b.left}px, ${a.top - b.top}px)`;\n }\n}\n\nlet current_component;\nfunction set_current_component(component) {\n current_component = component;\n}\nfunction get_current_component() {\n if (!current_component)\n throw new Error(`Function called outside component initialization`);\n return current_component;\n}\nfunction beforeUpdate(fn) {\n get_current_component().$$.before_update.push(fn);\n}\nfunction onMount(fn) {\n get_current_component().$$.on_mount.push(fn);\n}\nfunction afterUpdate(fn) {\n get_current_component().$$.after_update.push(fn);\n}\nfunction onDestroy(fn) {\n get_current_component().$$.on_destroy.push(fn);\n}\nfunction createEventDispatcher() {\n const component = current_component;\n return (type, detail) => {\n const callbacks = component.$$.callbacks[type];\n if (callbacks) {\n // TODO are there situations where events could be dispatched\n // in a server (non-DOM) environment?\n const event = custom_event(type, detail);\n callbacks.slice().forEach(fn => {\n fn.call(component, event);\n });\n }\n };\n}\nfunction setContext(key, context) {\n get_current_component().$$.context.set(key, context);\n}\nfunction getContext(key) {\n return get_current_component().$$.context.get(key);\n}\n// TODO figure out if we still want to support\n// shorthand events, or if we want to implement\n// a real bubbling mechanism\nfunction bubble(component, event) {\n const callbacks = component.$$.callbacks[event.type];\n if (callbacks) {\n callbacks.slice().forEach(fn => fn(event));\n }\n}\n\nconst dirty_components = [];\nconst intros = { enabled: false };\nconst binding_callbacks = [];\nconst render_callbacks = [];\nconst flush_callbacks = [];\nconst resolved_promise = Promise.resolve();\nlet update_scheduled = false;\nfunction schedule_update() {\n if (!update_scheduled) {\n update_scheduled = true;\n resolved_promise.then(flush);\n }\n}\nfunction tick() {\n schedule_update();\n return resolved_promise;\n}\nfunction add_render_callback(fn) {\n render_callbacks.push(fn);\n}\nfunction add_flush_callback(fn) {\n flush_callbacks.push(fn);\n}\nfunction flush() {\n const seen_callbacks = new Set();\n do {\n // first, call beforeUpdate functions\n // and update components\n while (dirty_components.length) {\n const component = dirty_components.shift();\n set_current_component(component);\n update(component.$$);\n }\n while (binding_callbacks.length)\n binding_callbacks.pop()();\n // then, once components are updated, call\n // afterUpdate functions. This may cause\n // subsequent updates...\n for (let i = 0; i < render_callbacks.length; i += 1) {\n const callback = render_callbacks[i];\n if (!seen_callbacks.has(callback)) {\n callback();\n // ...so guard against infinite loops\n seen_callbacks.add(callback);\n }\n }\n render_callbacks.length = 0;\n } while (dirty_components.length);\n while (flush_callbacks.length) {\n flush_callbacks.pop()();\n }\n update_scheduled = false;\n}\nfunction update($$) {\n if ($$.fragment) {\n $$.update($$.dirty);\n run_all($$.before_update);\n $$.fragment.p($$.dirty, $$.ctx);\n $$.dirty = null;\n $$.after_update.forEach(add_render_callback);\n }\n}\n\nlet promise;\nfunction wait() {\n if (!promise) {\n promise = Promise.resolve();\n promise.then(() => {\n promise = null;\n });\n }\n return promise;\n}\nfunction dispatch(node, direction, kind) {\n node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));\n}\nconst outroing = new Set();\nlet outros;\nfunction group_outros() {\n outros = {\n r: 0,\n c: [],\n p: outros // parent group\n };\n}\nfunction check_outros() {\n if (!outros.r) {\n run_all(outros.c);\n }\n outros = outros.p;\n}\nfunction transition_in(block, local) {\n if (block && block.i) {\n outroing.delete(block);\n block.i(local);\n }\n}\nfunction transition_out(block, local, detach, callback) {\n if (block && block.o) {\n if (outroing.has(block))\n return;\n outroing.add(block);\n outros.c.push(() => {\n outroing.delete(block);\n if (callback) {\n if (detach)\n block.d(1);\n callback();\n }\n });\n block.o(local);\n }\n}\nconst null_transition = { duration: 0 };\nfunction create_in_transition(node, fn, params) {\n let config = fn(node, params);\n let running = false;\n let animation_name;\n let task;\n let uid = 0;\n function cleanup() {\n if (animation_name)\n delete_rule(node, animation_name);\n }\n function go() {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n if (css)\n animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);\n tick(0, 1);\n const start_time = now() + delay;\n const end_time = start_time + duration;\n if (task)\n task.abort();\n running = true;\n add_render_callback(() => dispatch(node, true, 'start'));\n task = loop(now => {\n if (running) {\n if (now >= end_time) {\n tick(1, 0);\n dispatch(node, true, 'end');\n cleanup();\n return running = false;\n }\n if (now >= start_time) {\n const t = easing((now - start_time) / duration);\n tick(t, 1 - t);\n }\n }\n return running;\n });\n }\n let started = false;\n return {\n start() {\n if (started)\n return;\n delete_rule(node);\n if (is_function(config)) {\n config = config();\n wait().then(go);\n }\n else {\n go();\n }\n },\n invalidate() {\n started = false;\n },\n end() {\n if (running) {\n cleanup();\n running = false;\n }\n }\n };\n}\nfunction create_out_transition(node, fn, params) {\n let config = fn(node, params);\n let running = true;\n let animation_name;\n const group = outros;\n group.r += 1;\n function go() {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n if (css)\n animation_name = create_rule(node, 1, 0, duration, delay, easing, css);\n const start_time = now() + delay;\n const end_time = start_time + duration;\n add_render_callback(() => dispatch(node, false, 'start'));\n loop(now => {\n if (running) {\n if (now >= end_time) {\n tick(0, 1);\n dispatch(node, false, 'end');\n if (!--group.r) {\n // this will result in `end()` being called,\n // so we don't need to clean up here\n run_all(group.c);\n }\n return false;\n }\n if (now >= start_time) {\n const t = easing((now - start_time) / duration);\n tick(1 - t, t);\n }\n }\n return running;\n });\n }\n if (is_function(config)) {\n wait().then(() => {\n // @ts-ignore\n config = config();\n go();\n });\n }\n else {\n go();\n }\n return {\n end(reset) {\n if (reset && config.tick) {\n config.tick(1, 0);\n }\n if (running) {\n if (animation_name)\n delete_rule(node, animation_name);\n running = false;\n }\n }\n };\n}\nfunction create_bidirectional_transition(node, fn, params, intro) {\n let config = fn(node, params);\n let t = intro ? 0 : 1;\n let running_program = null;\n let pending_program = null;\n let animation_name = null;\n function clear_animation() {\n if (animation_name)\n delete_rule(node, animation_name);\n }\n function init(program, duration) {\n const d = program.b - t;\n duration *= Math.abs(d);\n return {\n a: t,\n b: program.b,\n d,\n duration,\n start: program.start,\n end: program.start + duration,\n group: program.group\n };\n }\n function go(b) {\n const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;\n const program = {\n start: now() + delay,\n b\n };\n if (!b) {\n // @ts-ignore todo: improve typings\n program.group = outros;\n outros.r += 1;\n }\n if (running_program) {\n pending_program = program;\n }\n else {\n // if this is an intro, and there's a delay, we need to do\n // an initial tick and/or apply CSS animation immediately\n if (css) {\n clear_animation();\n animation_name = create_rule(node, t, b, duration, delay, easing, css);\n }\n if (b)\n tick(0, 1);\n running_program = init(program, duration);\n add_render_callback(() => dispatch(node, b, 'start'));\n loop(now => {\n if (pending_program && now > pending_program.start) {\n running_program = init(pending_program, duration);\n pending_program = null;\n dispatch(node, running_program.b, 'start');\n if (css) {\n clear_animation();\n animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);\n }\n }\n if (running_program) {\n if (now >= running_program.end) {\n tick(t = running_program.b, 1 - t);\n dispatch(node, running_program.b, 'end');\n if (!pending_program) {\n // we're done\n if (running_program.b) {\n // intro — we can tidy up immediately\n clear_animation();\n }\n else {\n // outro — needs to be coordinated\n if (!--running_program.group.r)\n run_all(running_program.group.c);\n }\n }\n running_program = null;\n }\n else if (now >= running_program.start) {\n const p = now - running_program.start;\n t = running_program.a + running_program.d * easing(p / running_program.duration);\n tick(t, 1 - t);\n }\n }\n return !!(running_program || pending_program);\n });\n }\n }\n return {\n run(b) {\n if (is_function(config)) {\n wait().then(() => {\n // @ts-ignore\n config = config();\n go(b);\n });\n }\n else {\n go(b);\n }\n },\n end() {\n clear_animation();\n running_program = pending_program = null;\n }\n };\n}\n\nfunction handle_promise(promise, info) {\n const token = info.token = {};\n function update(type, index, key, value) {\n if (info.token !== token)\n return;\n info.resolved = key && { [key]: value };\n const child_ctx = assign(assign({}, info.ctx), info.resolved);\n const block = type && (info.current = type)(child_ctx);\n if (info.block) {\n if (info.blocks) {\n info.blocks.forEach((block, i) => {\n if (i !== index && block) {\n group_outros();\n transition_out(block, 1, 1, () => {\n info.blocks[i] = null;\n });\n check_outros();\n }\n });\n }\n else {\n info.block.d(1);\n }\n block.c();\n transition_in(block, 1);\n block.m(info.mount(), info.anchor);\n flush();\n }\n info.block = block;\n if (info.blocks)\n info.blocks[index] = block;\n }\n if (is_promise(promise)) {\n const current_component = get_current_component();\n promise.then(value => {\n set_current_component(current_component);\n update(info.then, 1, info.value, value);\n set_current_component(null);\n }, error => {\n set_current_component(current_component);\n update(info.catch, 2, info.error, error);\n set_current_component(null);\n });\n // if we previously had a then/catch block, destroy it\n if (info.current !== info.pending) {\n update(info.pending, 0);\n return true;\n }\n }\n else {\n if (info.current !== info.then) {\n update(info.then, 1, info.value, promise);\n return true;\n }\n info.resolved = { [info.value]: promise };\n }\n}\n\nconst globals = (typeof window !== 'undefined' ? window : global);\n\nfunction destroy_block(block, lookup) {\n block.d(1);\n lookup.delete(block.key);\n}\nfunction outro_and_destroy_block(block, lookup) {\n transition_out(block, 1, 1, () => {\n lookup.delete(block.key);\n });\n}\nfunction fix_and_destroy_block(block, lookup) {\n block.f();\n destroy_block(block, lookup);\n}\nfunction fix_and_outro_and_destroy_block(block, lookup) {\n block.f();\n outro_and_destroy_block(block, lookup);\n}\nfunction update_keyed_each(old_blocks, changed, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block, next, get_context) {\n let o = old_blocks.length;\n let n = list.length;\n let i = o;\n const old_indexes = {};\n while (i--)\n old_indexes[old_blocks[i].key] = i;\n const new_blocks = [];\n const new_lookup = new Map();\n const deltas = new Map();\n i = n;\n while (i--) {\n const child_ctx = get_context(ctx, list, i);\n const key = get_key(child_ctx);\n let block = lookup.get(key);\n if (!block) {\n block = create_each_block(key, child_ctx);\n block.c();\n }\n else if (dynamic) {\n block.p(changed, child_ctx);\n }\n new_lookup.set(key, new_blocks[i] = block);\n if (key in old_indexes)\n deltas.set(key, Math.abs(i - old_indexes[key]));\n }\n const will_move = new Set();\n const did_move = new Set();\n function insert(block) {\n transition_in(block, 1);\n block.m(node, next);\n lookup.set(block.key, block);\n next = block.first;\n n--;\n }\n while (o && n) {\n const new_block = new_blocks[n - 1];\n const old_block = old_blocks[o - 1];\n const new_key = new_block.key;\n const old_key = old_block.key;\n if (new_block === old_block) {\n // do nothing\n next = new_block.first;\n o--;\n n--;\n }\n else if (!new_lookup.has(old_key)) {\n // remove old block\n destroy(old_block, lookup);\n o--;\n }\n else if (!lookup.has(new_key) || will_move.has(new_key)) {\n insert(new_block);\n }\n else if (did_move.has(old_key)) {\n o--;\n }\n else if (deltas.get(new_key) > deltas.get(old_key)) {\n did_move.add(new_key);\n insert(new_block);\n }\n else {\n will_move.add(old_key);\n o--;\n }\n }\n while (o--) {\n const old_block = old_blocks[o];\n if (!new_lookup.has(old_block.key))\n destroy(old_block, lookup);\n }\n while (n)\n insert(new_blocks[n - 1]);\n return new_blocks;\n}\nfunction measure(blocks) {\n const rects = {};\n let i = blocks.length;\n while (i--)\n rects[blocks[i].key] = blocks[i].node.getBoundingClientRect();\n return rects;\n}\n\nfunction get_spread_update(levels, updates) {\n const update = {};\n const to_null_out = {};\n const accounted_for = { $$scope: 1 };\n let i = levels.length;\n while (i--) {\n const o = levels[i];\n const n = updates[i];\n if (n) {\n for (const key in o) {\n if (!(key in n))\n to_null_out[key] = 1;\n }\n for (const key in n) {\n if (!accounted_for[key]) {\n update[key] = n[key];\n accounted_for[key] = 1;\n }\n }\n levels[i] = n;\n }\n else {\n for (const key in o) {\n accounted_for[key] = 1;\n }\n }\n }\n for (const key in to_null_out) {\n if (!(key in update))\n update[key] = undefined;\n }\n return update;\n}\nfunction get_spread_object(spread_props) {\n return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};\n}\n\nconst invalid_attribute_name_character = /[\\s'\">/=\\u{FDD0}-\\u{FDEF}\\u{FFFE}\\u{FFFF}\\u{1FFFE}\\u{1FFFF}\\u{2FFFE}\\u{2FFFF}\\u{3FFFE}\\u{3FFFF}\\u{4FFFE}\\u{4FFFF}\\u{5FFFE}\\u{5FFFF}\\u{6FFFE}\\u{6FFFF}\\u{7FFFE}\\u{7FFFF}\\u{8FFFE}\\u{8FFFF}\\u{9FFFE}\\u{9FFFF}\\u{AFFFE}\\u{AFFFF}\\u{BFFFE}\\u{BFFFF}\\u{CFFFE}\\u{CFFFF}\\u{DFFFE}\\u{DFFFF}\\u{EFFFE}\\u{EFFFF}\\u{FFFFE}\\u{FFFFF}\\u{10FFFE}\\u{10FFFF}]/u;\n// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2\n// https://infra.spec.whatwg.org/#noncharacter\nfunction spread(args) {\n const attributes = Object.assign({}, ...args);\n let str = '';\n Object.keys(attributes).forEach(name => {\n if (invalid_attribute_name_character.test(name))\n return;\n const value = attributes[name];\n if (value === undefined)\n return;\n if (value === true)\n str += \" \" + name;\n const escaped = String(value)\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n str += \" \" + name + \"=\" + JSON.stringify(escaped);\n });\n return str;\n}\nconst escaped = {\n '\"': '"',\n \"'\": ''',\n '&': '&',\n '<': '<',\n '>': '>'\n};\nfunction escape(html) {\n return String(html).replace(/[\"'&<>]/g, match => escaped[match]);\n}\nfunction each(items, fn) {\n let str = '';\n for (let i = 0; i < items.length; i += 1) {\n str += fn(items[i], i);\n }\n return str;\n}\nconst missing_component = {\n $$render: () => ''\n};\nfunction validate_component(component, name) {\n if (!component || !component.$$render) {\n if (name === 'svelte:component')\n name += ' this={...}';\n throw new Error(`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules`);\n }\n return component;\n}\nfunction debug(file, line, column, values) {\n console.log(`{@debug} ${file ? file + ' ' : ''}(${line}:${column})`); // eslint-disable-line no-console\n console.log(values); // eslint-disable-line no-console\n return '';\n}\nlet on_destroy;\nfunction create_ssr_component(fn) {\n function $$render(result, props, bindings, slots) {\n const parent_component = current_component;\n const $$ = {\n on_destroy,\n context: new Map(parent_component ? parent_component.$$.context : []),\n // these will be immediately discarded\n on_mount: [],\n before_update: [],\n after_update: [],\n callbacks: blank_object()\n };\n set_current_component({ $$ });\n const html = fn(result, props, bindings, slots);\n set_current_component(parent_component);\n return html;\n }\n return {\n render: (props = {}, options = {}) => {\n on_destroy = [];\n const result = { head: '', css: new Set() };\n const html = $$render(result, props, {}, options);\n run_all(on_destroy);\n return {\n html,\n css: {\n code: Array.from(result.css).map(css => css.code).join('\\n'),\n map: null // TODO\n },\n head: result.head\n };\n },\n $$render\n };\n}\nfunction add_attribute(name, value, boolean) {\n if (value == null || (boolean && !value))\n return '';\n return ` ${name}${value === true ? '' : `=${typeof value === 'string' ? JSON.stringify(escape(value)) : `\"${value}\"`}`}`;\n}\nfunction add_classes(classes) {\n return classes ? ` class=\"${classes}\"` : ``;\n}\n\nfunction bind(component, name, callback) {\n if (component.$$.props.indexOf(name) === -1)\n return;\n component.$$.bound[name] = callback;\n callback(component.$$.ctx[name]);\n}\nfunction mount_component(component, target, anchor) {\n const { fragment, on_mount, on_destroy, after_update } = component.$$;\n fragment.m(target, anchor);\n // onMount happens before the initial afterUpdate\n add_render_callback(() => {\n const new_on_destroy = on_mount.map(run).filter(is_function);\n if (on_destroy) {\n on_destroy.push(...new_on_destroy);\n }\n else {\n // Edge case - component was destroyed immediately,\n // most likely as a result of a binding initialising\n run_all(new_on_destroy);\n }\n component.$$.on_mount = [];\n });\n after_update.forEach(add_render_callback);\n}\nfunction destroy_component(component, detaching) {\n if (component.$$.fragment) {\n run_all(component.$$.on_destroy);\n component.$$.fragment.d(detaching);\n // TODO null out other refs, including component.$$ (but need to\n // preserve final state?)\n component.$$.on_destroy = component.$$.fragment = null;\n component.$$.ctx = {};\n }\n}\nfunction make_dirty(component, key) {\n if (!component.$$.dirty) {\n dirty_components.push(component);\n schedule_update();\n component.$$.dirty = blank_object();\n }\n component.$$.dirty[key] = true;\n}\nfunction init(component, options, instance, create_fragment, not_equal, prop_names) {\n const parent_component = current_component;\n set_current_component(component);\n const props = options.props || {};\n const $$ = component.$$ = {\n fragment: null,\n ctx: null,\n // state\n props: prop_names,\n update: noop,\n not_equal,\n bound: blank_object(),\n // lifecycle\n on_mount: [],\n on_destroy: [],\n before_update: [],\n after_update: [],\n context: new Map(parent_component ? parent_component.$$.context : []),\n // everything else\n callbacks: blank_object(),\n dirty: null\n };\n let ready = false;\n $$.ctx = instance\n ? instance(component, props, (key, ret, value = ret) => {\n if ($$.ctx && not_equal($$.ctx[key], $$.ctx[key] = value)) {\n if ($$.bound[key])\n $$.bound[key](value);\n if (ready)\n make_dirty(component, key);\n }\n return ret;\n })\n : props;\n $$.update();\n ready = true;\n run_all($$.before_update);\n $$.fragment = create_fragment($$.ctx);\n if (options.target) {\n if (options.hydrate) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n $$.fragment.l(children(options.target));\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n $$.fragment.c();\n }\n if (options.intro)\n transition_in(component.$$.fragment);\n mount_component(component, options.target, options.anchor);\n flush();\n }\n set_current_component(parent_component);\n}\nlet SvelteElement;\nif (typeof HTMLElement !== 'undefined') {\n SvelteElement = class extends HTMLElement {\n constructor() {\n super();\n this.attachShadow({ mode: 'open' });\n }\n connectedCallback() {\n // @ts-ignore todo: improve typings\n for (const key in this.$$.slotted) {\n // @ts-ignore todo: improve typings\n this.appendChild(this.$$.slotted[key]);\n }\n }\n attributeChangedCallback(attr, _oldValue, newValue) {\n this[attr] = newValue;\n }\n $destroy() {\n destroy_component(this, 1);\n this.$destroy = noop;\n }\n $on(type, callback) {\n // TODO should this delegate to addEventListener?\n const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));\n callbacks.push(callback);\n return () => {\n const index = callbacks.indexOf(callback);\n if (index !== -1)\n callbacks.splice(index, 1);\n };\n }\n $set() {\n // overridden by instance, if it has props\n }\n };\n}\nclass SvelteComponent {\n $destroy() {\n destroy_component(this, 1);\n this.$destroy = noop;\n }\n $on(type, callback) {\n const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));\n callbacks.push(callback);\n return () => {\n const index = callbacks.indexOf(callback);\n if (index !== -1)\n callbacks.splice(index, 1);\n };\n }\n $set() {\n // overridden by instance, if it has props\n }\n}\n\nfunction dispatch_dev(type, detail) {\n document.dispatchEvent(custom_event(type, detail));\n}\nfunction append_dev(target, node) {\n dispatch_dev(\"SvelteDOMInsert\", { target, node });\n append(target, node);\n}\nfunction insert_dev(target, node, anchor) {\n dispatch_dev(\"SvelteDOMInsert\", { target, node, anchor });\n insert(target, node, anchor);\n}\nfunction detach_dev(node) {\n dispatch_dev(\"SvelteDOMRemove\", { node });\n detach(node);\n}\nfunction detach_between_dev(before, after) {\n while (before.nextSibling && before.nextSibling !== after) {\n detach_dev(before.nextSibling);\n }\n}\nfunction detach_before_dev(after) {\n while (after.previousSibling) {\n detach_dev(after.previousSibling);\n }\n}\nfunction detach_after_dev(before) {\n while (before.nextSibling) {\n detach_dev(before.nextSibling);\n }\n}\nfunction listen_dev(node, event, handler, options, has_prevent_default, has_stop_propagation) {\n const modifiers = options === true ? [\"capture\"] : options ? Array.from(Object.keys(options)) : [];\n if (has_prevent_default)\n modifiers.push('preventDefault');\n if (has_stop_propagation)\n modifiers.push('stopPropagation');\n dispatch_dev(\"SvelteDOMAddEventListener\", { node, event, handler, modifiers });\n const dispose = listen(node, event, handler, options);\n return () => {\n dispatch_dev(\"SvelteDOMRemoveEventListener\", { node, event, handler, modifiers });\n dispose();\n };\n}\nfunction attr_dev(node, attribute, value) {\n attr(node, attribute, value);\n if (value == null)\n dispatch_dev(\"SvelteDOMRemoveAttribute\", { node, attribute });\n else\n dispatch_dev(\"SvelteDOMSetAttribute\", { node, attribute, value });\n}\nfunction prop_dev(node, property, value) {\n node[property] = value;\n dispatch_dev(\"SvelteDOMSetProperty\", { node, property, value });\n}\nfunction dataset_dev(node, property, value) {\n node.dataset[property] = value;\n dispatch_dev(\"SvelteDOMSetDataset\", { node, property, value });\n}\nfunction set_data_dev(text, data) {\n data = '' + data;\n if (text.data === data)\n return;\n dispatch_dev(\"SvelteDOMSetData\", { node: text, data });\n text.data = data;\n}\nclass SvelteComponentDev extends SvelteComponent {\n constructor(options) {\n if (!options || (!options.target && !options.$$inline)) {\n throw new Error(`'target' is a required option`);\n }\n super();\n }\n $destroy() {\n super.$destroy();\n this.$destroy = () => {\n console.warn(`Component was already destroyed`); // eslint-disable-line no-console\n };\n }\n}\n\nexport { HtmlTag, SvelteComponent, SvelteComponentDev, SvelteElement, add_attribute, add_classes, add_flush_callback, add_location, add_render_callback, add_resize_listener, add_transform, afterUpdate, append, append_dev, assign, attr, attr_dev, beforeUpdate, bind, binding_callbacks, blank_object, bubble, check_outros, children, claim_element, claim_space, claim_text, clear_loops, component_subscribe, createEventDispatcher, create_animation, create_bidirectional_transition, create_in_transition, create_out_transition, create_slot, create_ssr_component, current_component, custom_event, dataset_dev, debug, destroy_block, destroy_component, destroy_each, detach, detach_after_dev, detach_before_dev, detach_between_dev, detach_dev, dirty_components, dispatch_dev, each, element, element_is, empty, escape, escaped, exclude_internal_props, fix_and_destroy_block, fix_and_outro_and_destroy_block, fix_position, flush, getContext, get_binding_group_value, get_current_component, get_slot_changes, get_slot_context, get_spread_object, get_spread_update, get_store_value, globals, group_outros, handle_promise, identity, init, insert, insert_dev, intros, invalid_attribute_name_character, is_client, is_function, is_promise, listen, listen_dev, loop, measure, missing_component, mount_component, noop, not_equal, now, null_to_empty, object_without_properties, onDestroy, onMount, once, outro_and_destroy_block, prevent_default, prop_dev, raf, run, run_all, safe_not_equal, schedule_update, select_multiple_value, select_option, select_options, select_value, self, setContext, set_attributes, set_current_component, set_custom_element_data, set_data, set_data_dev, set_input_type, set_input_value, set_now, set_raf, set_store_value, set_style, set_svg_attributes, space, spread, stop_propagation, subscribe, svg_element, text, tick, time_ranges_to_array, to_number, toggle_class, transition_in, transition_out, update_keyed_each, validate_component, validate_store, xlink_attr };\n","\n\n\n\n\n\n","\n\n{#if hideValue}\n\n{:else}\n\n{/if}\n\n","\n\n
\n {#each formControls as child, index}\n
{labels[index]}
\n
\n
\n {/each}\n
\n\n","\r\nconst apiCall = (method) => (url, body) => \r\n fetch(url, {\r\n method: method,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n body: body && JSON.stringify(body), \r\n });\r\n\r\nexport const post = apiCall(\"POST\");\r\nexport const get = apiCall(\"GET\");\r\nexport const patch = apiCall(\"PATCH\");\r\nexport const del = apiCall(\"DELETE\");\r\n\r\nexport const authenticate = (username, password) => post(\"./api/authenticate\", {\r\n username, password\r\n});\r\n\r\nexport default {\r\npost, get, patch, delete:del\r\n};","\n\n
\n\n
\n\n {#if logo}\n
\n \"logo\"/\n
\n {/if}\n\n
\n
\n {usernameLabel}\n
\n
\n \n
\n
\n {passwordLabel}\n
\n
\n \n
\n
\n\n
\n \n
\n\n {#if incorrect}\n
\n Incorrect username or password\n
\n {/if}\n\n
\n\n
\n\n","export const buildStyle = (styles) => {\r\n let str = \"\";\r\n for(let s in styles) {\r\n if(styles[s]) {\r\n str += `${s}: ${styles[s]}; `\r\n }\r\n }\r\n return str;\r\n}","\r\n\r\n
\r\n {#each children as child, index}\r\n
\r\n
\r\n {/each}\r\n
\r\n\r\n","\n\n
\n {#each children as child, index}\n
\n
\n
\n
\n {/each}\n
\n\n"],"names":[],"mappings":"AAAA,SAAS,IAAI,GAAG,GAAG;AACnB,AACA,SAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE;;IAEtB,KAAK,MAAM,CAAC,IAAI,GAAG;QACf,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,GAAG,CAAC;CACd;AACD,AAQA,SAAS,GAAG,CAAC,EAAE,EAAE;IACb,OAAO,EAAE,EAAE,CAAC;CACf;AACD,SAAS,YAAY,GAAG;IACpB,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC9B;AACD,SAAS,OAAO,CAAC,GAAG,EAAE;IAClB,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;CACpB;AACD,SAAS,WAAW,CAAC,KAAK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AY,GAAG,EAAE,CAAC;;AAEtB,OAAO,CAAC,MAAM;IACV,GAAG,IAAI,IAAI,YAAY,EAAE;QACrB,IAAI,IAAI,EAAE,IAAI,YAAY,EAAE;YACxB,IAAI,CAAC,mBAAmB;gBACpB,QAAQ,CAAC,EAAE,CAAC,CAAC,OAAO;gBACpB,YAAY,CAAC,EAAE,CAAC;aACnB,CAAC;SACL;KACJ;CACJ,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/builder/src/builderStore/store/index.js b/packages/builder/src/builderStore/store/index.js index 8c1538e098..f135ceb070 100644 --- a/packages/builder/src/builderStore/store/index.js +++ b/packages/builder/src/builderStore/store/index.js @@ -1,4 +1,3 @@ -// import { filter, cloneDeep, last, concat, isEmpty, values } from "lodash/fp" import { pipe, getNode, constructHierarchy } from "components/common/core" import * as backendStoreActions from "./backend" @@ -392,13 +391,11 @@ const addComponentLibrary = store => async lib => { } const removeComponentLibrary = store => lib => { - store.update(s => { - s.pages.componentLibraries = filter(l => l !== lib)( - s.pages.componentLibraries - ) - _savePage(s) + store.update(state => { + state.pages.componentLibraries = state.pages.componentLibraries.filter(l => l !== lib); + _savePage(state); - return s + return state; }) } @@ -411,10 +408,10 @@ const addStylesheet = store => stylesheet => { } const removeStylesheet = store => stylesheet => { - store.update(s => { - s.pages.stylesheets = filter(s => s !== stylesheet)(s.pages.stylesheets) - _savePage(s) - return s + store.update(state => { + state.pages.stylesheets = s.pages.stylesheets.filter(s => s !== stylesheet) + _savePage(state) + return state }) } diff --git a/packages/common/lib/common/apiWrapper.js b/packages/common/lib/common/apiWrapper.js new file mode 100644 index 0000000000..49d865fc94 --- /dev/null +++ b/packages/common/lib/common/apiWrapper.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/common/apiWrapper.js.map b/packages/common/lib/common/apiWrapper.js.map new file mode 100644 index 0000000000..a1ed6bc2e7 --- /dev/null +++ b/packages/common/lib/common/apiWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/common/apiWrapper.js"],"names":["apiWrapper","app","eventNamespace","isAuthorized","eventContext","func","pushCallStack","handleNotAuthorized","startDate","Date","now","elapsed","publish","onBegin","params","result","publishComplete","publishError","apiWrapperSync","error","err","UnauthorisedError","seedCallId","callId","createCallStack","threadCallId","stack","calls","push","namespace","popCallStack","pop","length","ctx","onError","endcontext","onComplete"],"mappings":"+ZAAA;AACA;AACA;;AAEO,IAAMA,UAAU,sHAAG;AACxBC,EAAAA,GADwB;AAExBC,EAAAA,cAFwB;AAGxBC,EAAAA,YAHwB;AAIxBC,EAAAA,YAJwB;AAKxBC,EAAAA,IALwB;;;AAQxBC,YAAAA,aAAa,CAACL,GAAD,EAAMC,cAAN,CAAb,CARwB;;AAUnBC,YAAAA,YAAY,CAACF,GAAD,CAVO;AAWtBM,YAAAA,mBAAmB,CAACN,GAAD,EAAMG,YAAN,EAAoBF,cAApB,CAAnB,CAXsB;;;;AAelBM,YAAAA,SAfkB,GAeNC,IAAI,CAACC,GAAL,EAfM;AAgBlBC,YAAAA,OAhBkB,GAgBR,SAAVA,OAAU,WAAMF,IAAI,CAACC,GAAL,KAAaF,SAAnB,EAhBQ;;;AAmBhBP,cAAAA,GAAG,CAACW,OA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ChC,WAAO/B,GAAG,CAAC0B,KAAX;AACD;AACF,CALD;;AAOA,IAAMV,YAAY,uHAAG;AACnBhB,EAAAA,GADmB;AAEnBG,EAAAA,YAFmB;AAGnBF,EAAAA,cAHmB;AAInBS,EAAAA,OAJmB;AAKnBS,EAAAA,GALmB;;AAOba,YAAAA,GAPa,GAOP,mBAAU7B,YAAV,CAPO;AAQnB6B,YAAAA,GAAG,CAACd,KAAJ,GAAYC,GAAZ;AACAa,YAAAA,GAAG,CAACtB,OAAJ,GAAcA,OAAO,EAArB,CATmB;AAUbV,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACgC,OAA3B,EAAoCD,GAApC,CAVa;AAWnBH,YAAAA,YAAY,CAAC7B,GAAD,CAAZ,CAXmB,0DAAH,mBAAZgB,YAAY,qEAAlB;;;AAcA,IAAMD,eAAe,uHAAG;AACtBf,EAAAA,GADsB;AAEtBG,EAAAA,YAFsB;AAGtBF,EAAAA,cAHsB;AAItBS,EAAAA,OAJsB;AAKtBI,EAAAA,MALsB;;AAOhBoB,YAAAA,UAPgB,GAOH,mBAAU/B,YAAV,CAPG;AAQtB+B,YAAAA,UAAU,CAACpB,MAAX,GAAoBA,MAApB;AACAoB,YAAAA,UAAU,CAACxB,OAAX,GAAqBA,OAAO,EAA5B,CATsB;AAUhBV,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACkC,UAA3B,EAAuCD,UAAvC,CAVgB;AAWtBL,YAAAA,YAAY,CAAC7B,GAAD,CAAZ,CAXsB;AAYfc,YAAAA,MAZe,4DAAH,mBAAfC,eAAe,yEAArB,C;;;AAeehB,U","sourcesContent":["import { cloneDeep, isUndefined } from \"lodash/fp\"\nimport { generate } from \"shortid\"\nimport { UnauthorisedError } from \"./errors\"\n\nexport const apiWrapper = async (\n app,\n eventNamespace,\n isAuthorized,\n eventContext,\n func,\n ...params\n) => {\n pushCallStack(app, eventNamespace)\n\n if (!isAuthorized(app)) {\n handleNotAuthorized(app, eventContext, eventNamespace)\n return\n }\n\n const startDate = Date.now()\n const elapsed = () => Date.now() - startDate\n\n try {\n await app.publish(eventNamespace.onBegin, eventContext)\n\n const result = await func(...params)\n\n await publishComplete(app, eventContext, eventNamespace, elapsed, result)\n return result\n } catch (error) {\n await publishError(app, eventContext, eventNamespace, elapsed, error)\n throw error\n }\n}\n\nexport const apiWrapperSync = (\n app,\n eventNamespace,\n isAuthorized,\n eventContext,\n func,\n ...params\n) => {\n pushCallStack(app, eventNamespace)\n\n if (!isAuthorized(app)) {\n handleNotAuthorized(app, eventContext, eventNamespace)\n return\n }\n\n const startDate = Date.now()\n const elapsed = () => Date.now() - startDate\n\n try {\n app.publish(eventNamespace.onBegin, eventContext)\n\n const result = func(...params)\n\n publishComplete(app, eventContext, eventNamespace, elapsed, result)\n return result\n } catch (error) {\n publishError(app, eventContext, eventNamespace, elapsed, error)\n throw error\n }\n}\n\nconst handleNotAuthorized = (app, eventContext, eventNamespace) => {\n const err = new UnauthorisedError(`Unauthorized: ${eventNamespace}`)\n publishError(app, eventContext, eventNamespace, () => 0, err)\n throw err\n}\n\nconst pushCallStack = (app, eventNamespace, seedCallId) => {\n const callId = generate()\n\n const createCallStack = () => ({\n seedCallId: !isUndefined(seedCallId) ? seedCallId : callId,\n threadCallId: callId,\n stack: [],\n })\n\n if (isUndefined(app.calls)) {\n app.calls = createCallStack()\n }\n\n app.calls.stack.push({\n namespace: eventNamespace,\n callId,\n })\n}\n\nconst popCallStack = app => {\n app.calls.stack.pop()\n if (app.calls.stack.length === 0) {\n delete app.calls\n }\n}\n\nconst publishError = async (\n app,\n eventContext,\n eventNamespace,\n elapsed,\n err\n) => {\n const ctx = cloneDeep(eventContext)\n ctx.error = err\n ctx.elapsed = elapsed()\n await app.publish(eventNamespace.onError, ctx)\n popCallStack(app)\n}\n\nconst publishComplete = async (\n app,\n eventContext,\n eventNamespace,\n elapsed,\n result\n) => {\n const endcontext = cloneDeep(eventContext)\n endcontext.result = result\n endcontext.elapsed = elapsed()\n await app.publish(eventNamespace.onComplete, endcontext)\n popCallStack(app)\n return result\n}\n\nexport default apiWrapper\n"],"file":"apiWrapper.js"} \ No newline at end of file diff --git a/packages/common/lib/common/compileCode.js b/packages/common/lib/common/compileCode.js new file mode 100644 index 0000000000..7a8589f51b --- /dev/null +++ b/packages/common/lib/common/compileCode.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/common/compileCode.js.map b/packages/common/lib/common/compileCode.js.map new file mode 100644 index 0000000000..f32cc0ab6c --- /dev/null +++ b/packages/common/lib/common/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"} \ No newline at end of file diff --git a/packages/common/lib/common/errors.js b/packages/common/lib/common/errors.js new file mode 100644 index 0000000000..2087164021 --- /dev/null +++ b/packages/common/lib/common/errors.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 \ No newline at end of file diff --git a/packages/common/lib/common/errors.js.map b/packages/common/lib/common/errors.js.map new file mode 100644 index 0000000000..833284900a --- /dev/null +++ b/packages/common/lib/common/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"} \ No newline at end of file diff --git a/packages/common/lib/common/eventAggregator.js b/packages/common/lib/common/eventAggregator.js new file mode 100644 index 0000000000..cc30849911 --- /dev/null +++ b/packages/common/lib/common/eventAggregator.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 \ No newline at end of file diff --git a/packages/common/lib/common/eventAggregator.js.map b/packages/common/lib/common/eventAggregator.js.map new file mode 100644 index 0000000000..8c8719202d --- /dev/null +++ b/packages/common/lib/common/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"} \ No newline at end of file diff --git a/packages/common/lib/common/events.js b/packages/common/lib/common/events.js new file mode 100644 index 0000000000..59b1e5599a --- /dev/null +++ b/packages/common/lib/common/events.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 \ No newline at end of file diff --git a/packages/common/lib/common/events.js.map b/packages/common/lib/common/events.js.map new file mode 100644 index 0000000000..edf1c04791 --- /dev/null +++ b/packages/common/lib/common/events.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/common/events.js"],"names":["commonPlus","extra","common","_events","recordApi","save","getContext","getNew","load","validate","uploadFile","downloadFile","indexApi","buildIndex","listItems","aggregates","collectionApi","getAllowedRecordTypes","initialise","authApi","authenticate","authenticateTemporaryAccess","createTemporaryAccess","createUser","enableUser","disableUser","loadAccessLevels","getNewAccessLevel","getNewUser","getNewUserAuth","getUsers","saveAccessLevels","isAuthorized","changeMyPassword","setPasswordFromTemporaryCode","scorePassword","isValidPassword","validateUser","validateAccessLevels","setUserAccessLevels","templateApi","saveApplicationHierarchy","saveActionsAndTriggers","actionsApi","execute","_eventsList","makeEvent","area","method","name","areaKey","methodKey","obj","s","push","events","eventsList"],"mappings":"6IAAA;;AAEA,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAAAC,KAAK,UAAI,eAAM,CAAC,SAAD,EAAY,YAAZ,EAA0B,SAA1B,CAAN,EAA4CA,KAA5C,CAAJ,EAAxB;;AAEA,IAAMC,MAAM,GAAG,SAATA,MAAS,WAAMF,UAAU,CAAC,EAAD,CAAhB,EAAf;;AAEA,IAAMG,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,IAAI,EAAEL,UAA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IAAsB/C,OAAtB,EAA+B;AAC7B,OAAK,IAAMgD,SAAX,IAAwBhD,OAAO,CAAC+C,QAAD,CAA/B,EAA0C;AACxC,SAAK,IAAMD,IAAX,IAAmB9C,OAAO,CAAC+C,QAAD,CAAP,CAAiBC,SAAjB,CAAnB,EAAgD;AAC9CN,MAAAA,WAAW,CAACS,IAAZ,CAAiBnD,OAAO,CAAC+C,QAAD,CAAP,CAAiBC,SAAjB,EAA4BF,IAA5B,CAAjB;AACD;AACF;AACF;;AAEM,IAAMM,MAAM,GAAGpD,OAAf,C;;AAEA,IAAMqD,UAAU,GAAGX,WAAnB,C;;AAEQ,EAAEU,MAAM,EAAEpD,OAAV,EAAmBqD,UAAU,EAAEX,WAA/B,E","sourcesContent":["import { union, reduce } from \"lodash/fp\"\n\nconst commonPlus = extra => union([\"onBegin\", \"onComplete\", \"onError\"])(extra)\n\nconst common = () => commonPlus([])\n\nconst _events = {\n recordApi: {\n save: commonPlus([\"onInvalid\", \"onRecordUpdated\", \"onRecordCreated\"]),\n delete: common(),\n getContext: common(),\n getNew: common(),\n load: common(),\n validate: common(),\n uploadFile: common(),\n downloadFile: common(),\n },\n indexApi: {\n buildIndex: common(),\n listItems: common(),\n delete: common(),\n aggregates: common(),\n },\n collectionApi: {\n getAllowedRecordTypes: common(),\n initialise: common(),\n delete: common(),\n },\n authApi: {\n authenticate: common(),\n authenticateTemporaryAccess: common(),\n createTemporaryAccess: common(),\n createUser: common(),\n enableUser: common(),\n disableUser: common(),\n loadAccessLevels: common(),\n getNewAccessLevel: common(),\n getNewUser: common(),\n getNewUserAuth: common(),\n getUsers: common(),\n saveAccessLevels: common(),\n isAuthorized: common(),\n changeMyPassword: common(),\n setPasswordFromTemporaryCode: common(),\n scorePassword: common(),\n isValidPassword: common(),\n validateUser: common(),\n validateAccessLevels: common(),\n setUserAccessLevels: common(),\n },\n templateApi: {\n saveApplicationHierarchy: common(),\n saveActionsAndTriggers: common(),\n },\n actionsApi: {\n execute: common(),\n },\n}\n\nconst _eventsList = []\n\nconst makeEvent = (area, method, name) => `${area}:${method}:${name}`\n\nfor (const areaKey in _events) {\n for (const methodKey in _events[areaKey]) {\n _events[areaKey][methodKey] = reduce((obj, s) => {\n obj[s] = makeEvent(areaKey, methodKey, s)\n return obj\n }, {})(_events[areaKey][methodKey])\n }\n}\n\nfor (const areaKey in _events) {\n for (const methodKey in _events[areaKey]) {\n for (const name in _events[areaKey][methodKey]) {\n _eventsList.push(_events[areaKey][methodKey][name])\n }\n }\n}\n\nexport const events = _events\n\nexport const eventsList = _eventsList\n\nexport default { events: _events, eventsList: _eventsList }\n"],"file":"events.js"} \ No newline at end of file diff --git a/packages/common/lib/common/index.js b/packages/common/lib/common/index.js new file mode 100644 index 0000000000..e31e55402e --- /dev/null +++ b/packages/common/lib/common/index.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/common/index.js.map b/packages/common/lib/common/index.js.map new file mode 100644 index 0000000000..775e613d7a --- /dev/null +++ b/packages/common/lib/common/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/common/index.js"],"names":["$$","funcs","arg","$","keySep","trimKeySep","str","splitByKeySep","safeKey","key","joinKey","strs","paramsOrArray","length","s","toString","splitKey","getDirFomKey","dropRight","p","getFileFromKey","takeRight","head","configFolder","fieldDefinitions","templateDefinitions","appDefinitionFile","dirIndex","folderPath","getIndexKeyFromFileKey","ifExists","val","exists","notExists","getOrDefault","defaultVal","not","func","isDefined","isUndefined","isNonNull","isNull","isNotNaN","isNaN","allTrue","funcArgs","result","conditionFunc","anyTrue","insensitiveEquals","str1","str2","trim","toLowerCase","isSomething","isNothing","isNothingOrEmpty","v","somethingOrGetDefault","getDefaultFunc","somethingOrDefault","mapIfSomethingOrDefault","mapFunc","mapIfSomethingOrBlank","none","predicate","collection","all","isNotEmpty","ob","isAsync","fn","constructor","name","isNonEmptyArray","isArray","isNonEmptyString","isString","tryOr","failFunc","args","apply","_","tryAwaitOr","defineError","errorPrefix","err","message","tryOrIgnore","tryAwaitOrIgnore","causesException","e","executesWithoutException","handleErrorWith","returnValInError","handleErrorWithUndefined","undefined","switchCase","cases","value","nextCase","nextResult","isValue","val1","val2","isOneOf","vals","defaultCase","memberMatches","member","match","obj","StartsWith","searchFor","searchIn","contains","array","getHashCode","hash","i","char","l","charCodeAt","awEx","promise","isSafeInteger","n","Number","MAX_SAFE_INTEGER","toDateOrNull","Date","toBoolOrNull","toNumberOrNull","isArrayOfString","opts","pushAll","target","items","push","pause","duration","Promise","res","setTimeout","retry","retries","delay","then","events","eventsList","toNumber","toDate","toBool"],"mappings":"06DAAA;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;AAkBA,qC;;AAEA;AACO,IAAMA,EAAE,GAAG,SAALA,EAAK,sCAAIC,KAAJ,oDAAIA,KAAJ,iCAAc,UAAAC,GAAG,UAAI,kBAAKD,KAAL,EAAYC,GAAZ,CAAJ,EAAjB,EAAX;;AAEP;gBACO,IAAMC,CAAC,GAAG,SAAJA,CAAI,CAACD,GAAD,EAAMD,KAAN,UAAgBD,EAAE,MAAF,6CAAMC,KAAN,GAAaC,GAAb,CAAhB,EAAV,C;;AAEA,IAAME,MAAM,GAAG,GAAf,C;AACP,IAAMC,UAAU,GAAG,SAAbA,UAAa,CAAAC,GAAG,UAAI,kBAAKA,GAAL,EAAUF,MAAV,CAAJ,EAAtB;AACA,IAAMG,aAAa,GAAG,SAAhBA,aAAgB,CAAAD,GAAG,UAAI,eAAMF,MAAN,EAAcE,GAAd,CAAJ,EAAzB;AACO,IAAME,OAAO,GAAG,SAAVA,OAAU,CAAAC,GAAG;AACxB,mCAAWL,MAAX,SAAoBC,UAAU,CAACI,GAAD,CAA9B,aAA0CL,MAA1C,SAAmDA,MAAnD,GAA6DA,MAA7D,CADwB,GAAnB,C;AAEA,IAAMM,OAAO,GAAG,SAAVA,OAAU,GAAa,oCAATC,IAAS,yDAATA,IAAS;AAClC,MAAMC,aAAa,GAAID,IAAI,CAACE,MAAL,KAAgB,CAAjB,GAAsB,iBAAQF,IAAI,CAAC,CAAD,CAAZ,CAAtB,GAAyCA,IAAI,CAAC,CAAD,CAA7C,GAAmDA,IAAzE;AACA,SAAOR,CAAC,CAACS,aAAD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bC,EAAAA,MAAM,EAAEtB,YAtDK;AAuDbuB,EAAAA,MAAM,EAAErB,YAvDK;AAwDbE,EAAAA,eAAe,EAAfA,eAxDa;AAyDbpF,EAAAA,iBAAiB,EAAjBA,iBAzDa;AA0Db0F,EAAAA,KAAK,EAALA,KA1Da;AA2DbK,EAAAA,KAAK,EAALA,KA3Da;AA4DbT,EAAAA,OAAO,EAAPA,OA5Da,E","sourcesContent":["import {\n head,\n tail,\n findIndex,\n startsWith,\n dropRight,\n flow,\n takeRight,\n trim,\n replace,\n} from \"lodash\"\nimport {\n some,\n reduce,\n isEmpty,\n isArray,\n join,\n isString,\n isInteger,\n isDate,\n toNumber,\n isUndefined,\n isNaN,\n isNull,\n constant,\n split,\n includes,\n filter,\n} from \"lodash/fp\"\nimport { events, eventsList } from \"./events.js\"\n\n// this is the combinator function\nexport const $$ = (...funcs) => arg => flow(funcs)(arg)\n\n// this is the pipe function\nexport const $ = (arg, funcs) => $$(...funcs)(arg)\n\nexport const keySep = \"/\"\nconst trimKeySep = str => trim(str, keySep)\nconst splitByKeySep = str => split(keySep)(str)\nexport const safeKey = key =>\n replace(`${keySep}${trimKeySep(key)}`, `${keySep}${keySep}`, keySep)\nexport const joinKey = (...strs) => {\n const paramsOrArray = (strs.length === 1) & isArray(strs[0]) ? strs[0] : strs\n return $(paramsOrArray, [\n filter(s => !isUndefined(s) && !isNull(s) && s.toString().length > 0),\n join(keySep),\n safeKey,\n ])\n}\nexport const splitKey = $$(trimKeySep, splitByKeySep)\nexport const getDirFomKey = $$(splitKey, dropRight, p => joinKey(...p))\nexport const getFileFromKey = $$(splitKey, takeRight, head)\n\nexport const configFolder = `${keySep}.config`\nexport const fieldDefinitions = joinKey(configFolder, \"fields.json\")\nexport const templateDefinitions = joinKey(configFolder, \"templates.json\")\nexport const appDefinitionFile = joinKey(configFolder, \"appDefinition.json\")\nexport const dirIndex = folderPath =>\n joinKey(configFolder, \"dir\", ...splitKey(folderPath), \"dir.idx\")\nexport const getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex)\n\nexport const ifExists = (val, exists, notExists) =>\n isUndefined(val)\n ? isUndefined(notExists)\n ? (() => {})()\n : notExists()\n : exists()\n\nexport const getOrDefault = (val, defaultVal) =>\n ifExists(\n val,\n () => val,\n () => defaultVal\n )\n\nexport const not = func => val => !func(val)\nexport const isDefined = not(isUndefined)\nexport const isNonNull = not(isNull)\nexport const isNotNaN = not(isNaN)\n\nexport const allTrue = (...funcArgs) => val =>\n reduce(\n (result, conditionFunc) =>\n (isNull(result) || result == true) && conditionFunc(val),\n null\n )(funcArgs)\n\nexport const anyTrue = (...funcArgs) => val =>\n reduce(\n (result, conditionFunc) => result == true || conditionFunc(val),\n null\n )(funcArgs)\n\nexport const insensitiveEquals = (str1, str2) =>\n str1.trim().toLowerCase() === str2.trim().toLowerCase()\n\nexport const isSomething = allTrue(isDefined, isNonNull, isNotNaN)\nexport const isNothing = not(isSomething)\nexport const isNothingOrEmpty = v => isNothing(v) || isEmpty(v)\nexport const somethingOrGetDefault = getDefaultFunc => val =>\n isSomething(val) ? val : getDefaultFunc()\nexport const somethingOrDefault = (val, defaultVal) =>\n somethingOrGetDefault(constant(defaultVal))(val)\n\nexport const mapIfSomethingOrDefault = (mapFunc, defaultVal) => val =>\n isSomething(val) ? mapFunc(val) : defaultVal\n\nexport const mapIfSomethingOrBlank = mapFunc =>\n mapIfSomethingOrDefault(mapFunc, \"\")\n\nexport const none = predicate => collection => !some(predicate)(collection)\n\nexport const all = predicate => collection =>\n none(v => !predicate(v))(collection)\n\nexport const isNotEmpty = ob => !isEmpty(ob)\nexport const isAsync = fn => fn.constructor.name === \"AsyncFunction\"\nexport const isNonEmptyArray = allTrue(isArray, isNotEmpty)\nexport const isNonEmptyString = allTrue(isString, isNotEmpty)\nexport const tryOr = failFunc => (func, ...args) => {\n try {\n return func.apply(null, ...args)\n } catch (_) {\n return failFunc()\n }\n}\n\nexport const tryAwaitOr = failFunc => async (func, ...args) => {\n try {\n return await func.apply(null, ...args)\n } catch (_) {\n return await failFunc()\n }\n}\n\nexport const defineError = (func, errorPrefix) => {\n try {\n return func()\n } catch (err) {\n err.message = `${errorPrefix} : ${err.message}`\n throw err\n }\n}\n\nexport const tryOrIgnore = tryOr(() => {})\nexport const tryAwaitOrIgnore = tryAwaitOr(async () => {})\nexport const causesException = func => {\n try {\n func()\n return false\n } catch (e) {\n return true\n }\n}\n\nexport const executesWithoutException = func => !causesException(func)\n\nexport const handleErrorWith = returnValInError =>\n tryOr(constant(returnValInError))\n\nexport const handleErrorWithUndefined = handleErrorWith(undefined)\n\nexport const switchCase = (...cases) => value => {\n const nextCase = () => head(cases)[0](value)\n const nextResult = () => head(cases)[1](value)\n\n if (isEmpty(cases)) return // undefined\n if (nextCase() === true) return nextResult()\n return switchCase(...tail(cases))(value)\n}\n\nexport const isValue = val1 => val2 => val1 === val2\nexport const isOneOf = (...vals) => val => includes(val)(vals)\nexport const defaultCase = constant(true)\nexport const memberMatches = (member, match) => obj => match(obj[member])\n\nexport const StartsWith = searchFor => searchIn =>\n startsWith(searchIn, searchFor)\n\nexport const contains = val => array => findIndex(array, v => v === val) > -1\n\nexport const getHashCode = s => {\n let hash = 0\n let i\n let char\n let l\n if (s.length == 0) return hash\n for (i = 0, l = s.length; i < l; i++) {\n char = s.charCodeAt(i)\n hash = (hash << 5) - hash + char\n hash |= 0 // Convert to 32bit integer\n }\n\n // converting to string, but dont want a \"-\" prefixed\n if (hash < 0) {\n return `n${(hash * -1).toString()}`\n }\n return hash.toString()\n}\n\n// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/\nexport const awEx = async promise => {\n try {\n const result = await promise\n return [undefined, result]\n } catch (error) {\n return [error, undefined]\n }\n}\n\nexport const isSafeInteger = n =>\n isInteger(n) &&\n n <= Number.MAX_SAFE_INTEGER &&\n n >= 0 - Number.MAX_SAFE_INTEGER\n\nexport const toDateOrNull = s =>\n isNull(s) ? null : isDate(s) ? s : new Date(s)\nexport const toBoolOrNull = s => (isNull(s) ? null : s === \"true\" || s === true)\nexport const toNumberOrNull = s => (isNull(s) ? null : toNumber(s))\n\nexport const isArrayOfString = opts => isArray(opts) && all(isString)(opts)\n\nexport const pushAll = (target, items) => {\n for (let i of items) target.push(i)\n}\n\nexport const pause = async duration =>\n new Promise(res => setTimeout(res, duration))\n\nexport const retry = async (fn, retries, delay, ...args) => {\n try {\n return await fn(...args)\n } catch (err) {\n if (retries > 1) {\n return await pause(delay).then(\n async () => await retry(fn, retries - 1, delay, ...args)\n )\n }\n throw err\n }\n}\n\nexport { events } from \"./events.js\"\n\nexport default {\n ifExists,\n getOrDefault,\n isDefined,\n isNonNull,\n isNotNaN,\n allTrue,\n isSomething,\n mapIfSomethingOrDefault,\n mapIfSomethingOrBlank,\n configFolder,\n fieldDefinitions,\n isNothing,\n not,\n switchCase,\n defaultCase,\n StartsWith,\n contains,\n templateDefinitions,\n handleErrorWith,\n handleErrorWithUndefined,\n tryOr,\n tryOrIgnore,\n tryAwaitOr,\n tryAwaitOrIgnore,\n dirIndex,\n keySep,\n $,\n $$,\n getDirFomKey,\n getFileFromKey,\n splitKey,\n somethingOrDefault,\n getIndexKeyFromFileKey,\n joinKey,\n somethingOrGetDefault,\n appDefinitionFile,\n isValue,\n all,\n isOneOf,\n memberMatches,\n defineError,\n anyTrue,\n isNonEmptyArray,\n causesException,\n executesWithoutException,\n none,\n getHashCode,\n awEx,\n events,\n eventsList,\n isNothingOrEmpty,\n isSafeInteger,\n toNumber,\n toDate: toDateOrNull,\n toBool: toBoolOrNull,\n isArrayOfString,\n insensitiveEquals,\n pause,\n retry,\n pushAll,\n}\n"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/lib/common/validationCommon.js b/packages/common/lib/common/validationCommon.js new file mode 100644 index 0000000000..0bc100e158 --- /dev/null +++ b/packages/common/lib/common/validationCommon.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/common/validationCommon.js.map b/packages/common/lib/common/validationCommon.js.map new file mode 100644 index 0000000000..421ded1c61 --- /dev/null +++ b/packages/common/lib/common/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"} \ No newline at end of file diff --git a/packages/common/lib/index.js b/packages/common/lib/index.js new file mode 100644 index 0000000000..8ffec395ef --- /dev/null +++ b/packages/common/lib/index.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 \ No newline at end of file diff --git a/packages/common/lib/index.js.map b/packages/common/lib/index.js.map new file mode 100644 index 0000000000..c70c44e2d2 --- /dev/null +++ b/packages/common/lib/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"} \ No newline at end of file diff --git a/packages/common/lib/records/getNewRecord.js b/packages/common/lib/records/getNewRecord.js new file mode 100644 index 0000000000..b0634d6264 --- /dev/null +++ b/packages/common/lib/records/getNewRecord.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 \ No newline at end of file diff --git a/packages/common/lib/records/getNewRecord.js.map b/packages/common/lib/records/getNewRecord.js.map new file mode 100644 index 0000000000..5c9a88d2a6 --- /dev/null +++ b/packages/common/lib/records/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"} \ No newline at end of file diff --git a/packages/common/lib/records/recordValidationRules.js b/packages/common/lib/records/recordValidationRules.js new file mode 100644 index 0000000000..b625a44c5b --- /dev/null +++ b/packages/common/lib/records/recordValidationRules.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 \ No newline at end of file diff --git a/packages/common/lib/records/recordValidationRules.js.map b/packages/common/lib/records/recordValidationRules.js.map new file mode 100644 index 0000000000..789f133bc6 --- /dev/null +++ b/packages/common/lib/records/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"} \ No newline at end of file diff --git a/packages/common/lib/records/validateRecord.js b/packages/common/lib/records/validateRecord.js new file mode 100644 index 0000000000..0ab3aa4cde --- /dev/null +++ b/packages/common/lib/records/validateRecord.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 \ No newline at end of file diff --git a/packages/common/lib/records/validateRecord.js.map b/packages/common/lib/records/validateRecord.js.map new file mode 100644 index 0000000000..60bf6c08f7 --- /dev/null +++ b/packages/common/lib/records/validateRecord.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/records/validateRecord.js"],"names":["fieldParseError","fieldName","value","fields","message","validateAllFieldParse","record","model","f","name","parseResult","errors","success","push","validateAllTypeConstraints","field","isNonEmptyString","m","e","runRecordValidationRules","runValidationRule","rule","isValid","expressionWhenValid","expressionContext","valid","invalidFields","messageWhenInvalid","validationRules","flatten","r","validateRecord","schema","findModel","_modelId","fieldParseFails","recordValidationRuleFails","typeContraintFails"],"mappings":"2G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AAO,EAAE,KAAX,EAAkBX,MAAM,EAAEwB,eAA1B,EAAP;AACD;;AAED,MAAMC,yBAAyB,GAAGjB,wBAAwB,CAACb,MAAD,EAASC,KAAT,CAA1D;AACA,MAAM8B,kBAAkB,GAAGvB,0BAA0B,CAACR,MAAD,EAASC,KAAT,CAArD;;AAEA;AACE,mBAAQ4B,eAAR;AACA,mBAAQC,yBAAR,CADA;AAEA,mBAAQC,kBAAR,CAHF;AAIE;AACA,WAAO,EAAEf,OAAO,EAAE,IAAX,EAAiBX,MAAM,EAAE,EAAzB,EAAP;AACD;;AAED,SAAO;AACLW,IAAAA,OAAO,EAAE,KADJ;AAELX,IAAAA,MAAM,EAAE;AACNwB,IAAAA,eADM;AAENE,IAAAA,kBAFM;AAGND,IAAAA,yBAHM,CAFH,EAAP;;;AAQD,CA5BM,C","sourcesContent":["import { map, reduce, filter, isEmpty, flatten, each, union } from \"lodash/fp\";\nimport { compileCode } from \"../common/compileCode\";\nimport {\n validateFieldParse,\n validateTypeConstraints,\n} from \"../schema/types/index.js\"\nimport { $, isNonEmptyString } from \"../common/index.js\"\n\nconst fieldParseError = (fieldName, value) => ({\n fields: [fieldName],\n message: `Could not parse field ${fieldName}:${value}`,\n})\n\nconst validateAllFieldParse = (record, model) =>\n $(model.fields, [\n map(f => ({ name: f.name, parseResult: validateFieldParse(f, record) })),\n reduce((errors, f) => {\n if (f.parseResult.success) return errors\n errors.push(fieldParseError(f.name, f.parseResult.value))\n return errors\n }, []),\n ])\n\nconst validateAllTypeConstraints = (record, model) => {\n const errors = []\n for (const field of model.fields) {\n $(validateTypeConstraints(field, record), [\n filter(isNonEmptyString),\n map(m => ({ message: m, fields: [field.name] })),\n each(e => errors.push(e)),\n ])\n }\n return errors\n}\n\nconst runRecordValidationRules = (record, model) => {\n const runValidationRule = rule => {\n const isValid = compileCode(rule.expressionWhenValid)\n const expressionContext = { record }\n return isValid(expressionContext)\n ? { valid: true }\n : {\n valid: false,\n fields: rule.invalidFields,\n message: rule.messageWhenInvalid,\n }\n }\n\n return $(model.validationRules, [\n map(runValidationRule),\n flatten,\n filter(r => r.valid === false),\n map(r => ({ fields: r.fields, message: r.message })),\n ])\n}\n\nexport const validateRecord = (schema, record) => {\n const model = schema.findModel(record._modelId)\n const fieldParseFails = validateAllFieldParse(record, model)\n\n // non parsing would cause further issues - exit here\n if (!isEmpty(fieldParseFails)) {\n return { isValid: false, errors: fieldParseFails }\n }\n\n const recordValidationRuleFails = runRecordValidationRules(record, model)\n const typeContraintFails = validateAllTypeConstraints(record, model)\n\n if (\n isEmpty(fieldParseFails) &&\n isEmpty(recordValidationRuleFails) &&\n isEmpty(typeContraintFails)\n ) {\n return { isValid: true, errors: [] }\n }\n\n return {\n isValid: false,\n errors: union(\n fieldParseFails,\n typeContraintFails,\n recordValidationRuleFails\n ),\n }\n}\n"],"file":"validateRecord.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/createActions.js b/packages/common/lib/schema/createActions.js new file mode 100644 index 0000000000..4e48aa6dc6 --- /dev/null +++ b/packages/common/lib/schema/createActions.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/schema/createActions.js.map b/packages/common/lib/schema/createActions.js.map new file mode 100644 index 0000000000..2362409748 --- /dev/null +++ b/packages/common/lib/schema/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/fields.js b/packages/common/lib/schema/fields.js new file mode 100644 index 0000000000..ab3e75d48e --- /dev/null +++ b/packages/common/lib/schema/fields.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 \ No newline at end of file diff --git a/packages/common/lib/schema/fields.js.map b/packages/common/lib/schema/fields.js.map new file mode 100644 index 0000000000..db27a134e4 --- /dev/null +++ b/packages/common/lib/schema/fields.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/schema/fields.js"],"names":["fieldErrors","AddFieldValidationFailed","allowedTypes","all","getNewField","type","id","name","typeOptions","label","getInitialValue","getUndefinedValue","fieldRules","allFields","f","t","typeOptionsRules","field","def","optName","optionDefinitions","keys","o","isValid","requirementDescription","validateField","everySingleField","validateAllFields","recordNode","fields","flatten","addField","recordTemplate","validationMessages","length","errors","m","error","BadRequestError","join","push"],"mappings":"uZAAA;AACA;;;;;;;AAOA;AACA;AACA;AACA;;AAEO,IAAMA,WAAW,GAAG;AACzBC,EAAAA,wBAAwB,EAAE,wBADD,EAApB,C;;;AAIA,IAAMC,YA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IAAAA,gBAAgB,CAACC,KAAD,CAFd;AAGJA,IAAAA,KAHI,CAAP;AAID,GARqC,EAA/B,C;;AAUA,IAAMU,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,UAAU;AACzC,mBAAEA,UAAU,CAACC,MAAb,EAAqB,CAAC,aAAIJ,aAAa,CAACG,UAAU,CAACC,MAAZ,CAAjB,CAAD,EAAwCC,WAAxC,CAArB,CADyC,GAApC,C;;AAGA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,cAAD,EAAiBf,KAAjB,EAA2B;AACjD,MAAI,8BAAiBA,KAAK,CAACR,KAAvB,CAAJ,EAAmC;AACjCQ,IAAAA,KAAK,CAACR,KAAN,GAAcQ,KAAK,CAACV,IAApB;AACD;AACD,MAAM0B,kBAAkB,GAAGR,aAAa,+CAAKO,cAAc,CAACH,MAApB,IAA4BZ,KAA5B,GAAb;AACzBA,EAAAA,KADyB,CAA3B;;AAGA,MAAIgB,kBAAkB,CAACC,MAAnB,GAA4B,CAAhC,EAAmC;AACjC,QAAMC,MAAM,GAAG,aAAI,UAAAC,CAAC,UAAIA,CAAC,CAACC,KAAN,EAAL,EAAkBJ,kBAAlB,CAAf;AACA,UAAM,IAAIK,uBAAJ;AACDtC,IAAAA,WAAW,CAACC,wBADX,cACuCkC,MAAM,CAACI,IAAP,CAAY,IAAZ,CADvC,EAAN;;AAGD;AACDP,EAAAA,cAAc,CAACH,MAAf,CAAsBW,IAAtB,CAA2BvB,KAA3B;AACD,CAdM,C","sourcesContent":["import { some, map, filter, keys, includes, countBy, flatten } from \"lodash/fp\"\nimport {\n isSomething,\n $,\n isNonEmptyString,\n isNothingOrEmpty,\n isNothing,\n} from \"../common\"\nimport { all, getDefaultOptions } from \"./types/index.js\"\nimport { applyRuleSet, makerule } from \"../common/validationCommon\"\nimport { BadRequestError } from \"../common/errors\"\nimport { generate } from \"shortid\"\n\nexport const fieldErrors = {\n AddFieldValidationFailed: \"Add field validation: \",\n}\n\nexport const allowedTypes = () => keys(all)\n\nexport const getNewField = type => ({\n id: generate(),\n name: \"\", // how field is referenced internally\n type,\n typeOptions: getDefaultOptions(type),\n label: \"\", // how field is displayed\n getInitialValue: \"default\", // function that gets value when initially created\n getUndefinedValue: \"default\", // function that gets value when field undefined on record\n})\n\nconst fieldRules = allFields => [\n makerule(\"name\", \"field name is not set\", f => isNonEmptyString(f.name)),\n makerule(\"type\", \"field type is not set\", f => isNonEmptyString(f.type)),\n makerule(\"label\", \"field label is not set\", f => isNonEmptyString(f.label)),\n makerule(\"getInitialValue\", \"getInitialValue function is not set\", f =>\n isNonEmptyString(f.getInitialValue)\n ),\n makerule(\"getUndefinedValue\", \"getUndefinedValue function is not set\", f =>\n isNonEmptyString(f.getUndefinedValue)\n ),\n makerule(\n \"name\",\n \"field name is duplicated\",\n f => isNothingOrEmpty(f.name) || countBy(\"name\")(allFields)[f.name] === 1\n ),\n makerule(\n \"type\",\n \"type is unknown\",\n f => isNothingOrEmpty(f.type) || some(t => f.type === t)(allowedTypes())\n ),\n]\n\nconst typeOptionsRules = field => {\n const type = all[field.type]\n if (isNothing(type)) return []\n\n const def = optName => type.optionDefinitions[optName]\n\n return $(field.typeOptions, [\n keys,\n filter(o => isSomething(def(o)) && isSomething(def(o).isValid)),\n map(o =>\n makerule(`typeOptions.${o}`, `${def(o).requirementDescription}`, field =>\n def(o).isValid(field.typeOptions[o])\n )\n ),\n ])\n}\n\nexport const validateField = allFields => field => {\n const everySingleField = includes(field)(allFields)\n ? allFields\n : [...allFields, field]\n return applyRuleSet([\n ...fieldRules(everySingleField),\n ...typeOptionsRules(field),\n ])(field)\n}\n\nexport const validateAllFields = recordNode =>\n $(recordNode.fields, [map(validateField(recordNode.fields)), flatten])\n\nexport const addField = (recordTemplate, field) => {\n if (isNothingOrEmpty(field.label)) {\n field.label = field.name\n }\n const validationMessages = validateField([...recordTemplate.fields, field])(\n field\n )\n if (validationMessages.length > 0) {\n const errors = map(m => m.error)(validationMessages)\n throw new BadRequestError(\n `${fieldErrors.AddFieldValidationFailed} ${errors.join(\", \")}`\n )\n }\n recordTemplate.fields.push(field)\n}\n"],"file":"fields.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/fullSchema.js b/packages/common/lib/schema/fullSchema.js new file mode 100644 index 0000000000..9be170d805 --- /dev/null +++ b/packages/common/lib/schema/fullSchema.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/schema/fullSchema.js.map b/packages/common/lib/schema/fullSchema.js.map new file mode 100644 index 0000000000..5eece533a2 --- /dev/null +++ b/packages/common/lib/schema/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,MAA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ent":["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"} \ No newline at end of file diff --git a/packages/common/lib/schema/models.js b/packages/common/lib/schema/models.js new file mode 100644 index 0000000000..4f39b50c02 --- /dev/null +++ b/packages/common/lib/schema/models.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 \ No newline at end of file diff --git a/packages/common/lib/schema/models.js.map b/packages/common/lib/schema/models.js.map new file mode 100644 index 0000000000..506f0d734f --- /dev/null +++ b/packages/common/lib/schema/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/array.js b/packages/common/lib/schema/types/array.js new file mode 100644 index 0000000000..1377a6e108 --- /dev/null +++ b/packages/common/lib/schema/types/array.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/array.js.map b/packages/common/lib/schema/types/array.js.map new file mode 100644 index 0000000000..056ecd769d --- /dev/null +++ b/packages/common/lib/schema/types/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/bool.js b/packages/common/lib/schema/types/bool.js new file mode 100644 index 0000000000..1736ddf52a --- /dev/null +++ b/packages/common/lib/schema/types/bool.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/bool.js.map b/packages/common/lib/schema/types/bool.js.map new file mode 100644 index 0000000000..749e49a9c1 --- /dev/null +++ b/packages/common/lib/schema/types/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/datetime.js b/packages/common/lib/schema/types/datetime.js new file mode 100644 index 0000000000..5fcaa8f0f7 --- /dev/null +++ b/packages/common/lib/schema/types/datetime.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/datetime.js.map b/packages/common/lib/schema/types/datetime.js.map new file mode 100644 index 0000000000..6559a7758e --- /dev/null +++ b/packages/common/lib/schema/types/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/file.js b/packages/common/lib/schema/types/file.js new file mode 100644 index 0000000000..5626b9c5ea --- /dev/null +++ b/packages/common/lib/schema/types/file.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/file.js.map b/packages/common/lib/schema/types/file.js.map new file mode 100644 index 0000000000..c08e34a911 --- /dev/null +++ b/packages/common/lib/schema/types/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,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,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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/index.js b/packages/common/lib/schema/types/index.js new file mode 100644 index 0000000000..f77aeb3c4f --- /dev/null +++ b/packages/common/lib/schema/types/index.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/index.js.map b/packages/common/lib/schema/types/index.js.map new file mode 100644 index 0000000000..5e1aa0307c --- /dev/null +++ b/packages/common/lib/schema/types/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/schema/types/index.js"],"names":["allTypes","basicTypes","string","number","datetime","bool","link","file","arrays","keys","k","kvType","concreteArray","name","types","assign","all","getType","typeName","BadRequestError","getSampleFieldValue","field","type","sampleValue","getNewFieldValue","getNew","safeParseField","record","validateFieldParse","tryParse","undefined","getDefaultOptions","validateTypeConstraints","detectType","value","JSON","stringify"],"mappings":"+eAAA;AACA;;;;;;;;;;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,IAAMA,QAAQ,GAAG,SAAXA,QAAW,GAAM;AACrB,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,OAAJ,EAAaA,KAAb,CAA5C,EAAiE,OAAO5B,gBAAP;AACjE,MAAI,kBAAS4B,KAAT,KAAmB,aAAI,cAAJ,EAAoBA,KAApB,CAAnB,IAAiD,aAAI,MAAJ,EAAYA,KAAZ,CAArD;AACE,SAAO3B,gBAAP;;AAEF,QAAM,IAAIY,uBAAJ,kCAA8CgB,IAAI,CAACC,SAAL,CAAeF,KAAf,CAA9C,EAAN;AACD,CAXM,C","sourcesContent":["import { assign, merge } from \"lodash\"\nimport {\n map,\n isString,\n isNumber,\n isBoolean,\n isDate,\n keys,\n isObject,\n isArray,\n has,\n} from \"lodash/fp\"\nimport { $ } from \"../../common\"\nimport { parsedSuccess } from \"./typeHelpers\"\nimport string from \"./string\"\nimport bool from \"./bool\"\nimport number from \"./number\"\nimport datetime from \"./datetime\"\nimport array from \"./array\"\nimport link from \"./link\"\nimport file from \"./file\"\nimport { BadRequestError } from \"../../common/errors\"\n\nconst allTypes = () => {\n const basicTypes = {\n string,\n number,\n datetime,\n bool,\n link,\n file,\n }\n\n const arrays = $(basicTypes, [\n keys,\n map(k => {\n const kvType = {}\n const concreteArray = array(basicTypes[k])\n kvType[concreteArray.name] = concreteArray\n return kvType\n }),\n types => assign({}, ...types),\n ])\n\n return merge({}, basicTypes, arrays)\n}\n\nexport const all = allTypes()\n\nexport const getType = typeName => {\n if (!has(typeName)(all))\n throw new BadRequestError(`Do not recognise type ${typeName}`)\n return all[typeName]\n}\n\nexport const getSampleFieldValue = field => getType(field.type).sampleValue\n\nexport const getNewFieldValue = field => getType(field.type).getNew(field)\n\nexport const safeParseField = (field, record) =>\n getType(field.type).safeParseField(field, record)\n\nexport const validateFieldParse = (field, record) =>\n has(field.name)(record)\n ? getType(field.type).tryParse(record[field.name])\n : parsedSuccess(undefined) // fields may be undefined by default\n\nexport const getDefaultOptions = type => getType(type).getDefaultOptions()\n\nexport const validateTypeConstraints = (field, record) =>\n getType(field.type).validateTypeConstraints(field, record)\n\nexport const detectType = value => {\n if (isString(value)) return string\n if (isBoolean(value)) return bool\n if (isNumber(value)) return number\n if (isDate(value)) return datetime\n if (isArray(value)) return array(detectType(value[0]))\n if (isObject(value) && has(\"key\")(value) && has(\"value\")(value)) return link\n if (isObject(value) && has(\"relativePath\")(value) && has(\"size\")(value))\n return file\n\n throw new BadRequestError(`cannot determine type: ${JSON.stringify(value)}`)\n}\n"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/link.js b/packages/common/lib/schema/types/link.js new file mode 100644 index 0000000000..85a4626523 --- /dev/null +++ b/packages/common/lib/schema/types/link.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/link.js.map b/packages/common/lib/schema/types/link.js.map new file mode 100644 index 0000000000..8bd94f4726 --- /dev/null +++ b/packages/common/lib/schema/types/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/number.js b/packages/common/lib/schema/types/number.js new file mode 100644 index 0000000000..2ce66eb376 --- /dev/null +++ b/packages/common/lib/schema/types/number.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/number.js.map b/packages/common/lib/schema/types/number.js.map new file mode 100644 index 0000000000..9d2b7cf610 --- /dev/null +++ b/packages/common/lib/schema/types/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,CAAx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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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/object.js b/packages/common/lib/schema/types/object.js new file mode 100644 index 0000000000..db00a6d243 --- /dev/null +++ b/packages/common/lib/schema/types/object.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/object.js.map b/packages/common/lib/schema/types/object.js.map new file mode 100644 index 0000000000..3ff33f277a --- /dev/null +++ b/packages/common/lib/schema/types/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","typeConstra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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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/string.js b/packages/common/lib/schema/types/string.js new file mode 100644 index 0000000000..3772a9365a --- /dev/null +++ b/packages/common/lib/schema/types/string.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/string.js.map b/packages/common/lib/schema/types/string.js.map new file mode 100644 index 0000000000..12eb59c17c --- /dev/null +++ b/packages/common/lib/schema/types/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"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/typeHelpers.js b/packages/common/lib/schema/types/typeHelpers.js new file mode 100644 index 0000000000..0908fbb298 --- /dev/null +++ b/packages/common/lib/schema/types/typeHelpers.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 \ No newline at end of file diff --git a/packages/common/lib/schema/types/typeHelpers.js.map b/packages/common/lib/schema/types/typeHelpers.js.map new file mode 100644 index 0000000000..5f23995697 --- /dev/null +++ b/packages/common/lib/schema/types/typeHelpers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/schema/types/typeHelpers.js"],"names":["getSafeFieldParser","tryParse","defaultValueFunctions","field","record","name","getSafeValueParser","getUndefinedValue","value","parsed","success","getNewValue","getInitialValue","typeFunctions","specificFunctions","constant","validateTypeConstraints","validationRules","fieldValue","validateRule","r","isValid","typeOptions","getMessage","errors","err","push","getDefaultOptions","v","defaultValue","makerule","parsedFailed","val","parsedSuccess","getDefaultExport","functions","options","sampleValue","stringify","getNew","safeParseField","safeParseValue","optionDefinitions","undefined","getDefaultValue"],"mappings":"yTAAA;AACA;AACA,+C;;AAEO,IAAMA,kBAAkB,GAAG,SAArBA,kBAAqB,CAACC,QAAD,EAAWC,qBAAX,UAAqC;AACrEC,EAAAA,KADqE;AAErEC,EAAAA,MAFqE;AAGlE;AACH,QAAI,aAAID,KAAK,CAACE,IAAV,EAAgBD,MAAhB,CAAJ,EAA6B;AAC3B,aAAOE,kBAAkB;AACvBL,MAAAA,QADuB;AAEvBC,MAAAA,qBAFuB,CAAlB;AAGLE,MAAAA,MAAM,CAACD,KAAK,CAACE,IAAP,CAHD,CAAP;AAID;AACD,WAAOH,qBAAqB,CAACC,KAAK,CAACI,iBAAP,CAArB,EAAP;AACD,GAXiC,EAA3B,C;;AAaA,IAAMD,kBAAkB,GAAG,SAArBA,kBAAqB;AAChCL,QADgC;AAEhCC,qBAFgC;AAG7B,cAAAM,KAAK,EAAI;AACZ,UAAMC,MAAM,GAAGR,QAAQ,CAACO,KAAD,CAAvB;AACA,UAAIC,MAAM,CAACC,OAAX,EAAoB;AAClB,eAAOD,MAAM,CAACD,KAAd;AACD;AACD,aAAON,qBAAqB,WAArB,EAAP;AACD,KATiC,GAA3B,C;;AAWA,IAAMS,WAAW,GAAG,SAAdA,WAAc,CAACV,QAAD,EAAWC,qBAAX,UAAqC,UAAAC,KAAK,EAAI;AACvE,QAAMS,eAAe;AACnB,yBAAYT,KAAZ,KAAsB,qBAAYA,KAAK,CAACS,eAAlB,CAAtB;AACI,aADJ;AAEIT,IAAAA,KAAK,CAACS,eAHZ;;AAKA,WAAO,aAAIA,eAAJ,EAAqBV,qBAArB;AACHA,IAAAA,qBAAqB,CAACU,eAAD,CAArB,EADG;AAEHN,IAAAA,kBAAkB,CAACL,QAAD,EAAWC,qBAAX,CAAl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B,EAAL,EAAxB,C;AACA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAD,GAAG,UAAK,EAAEtB,OAAO,EAAE,IAAX,EAAiBF,KAAK,EAAEwB,GAAxB,EAAL,EAAzB,C;AACA,IAAME,gBAAgB,GAAG,SAAnBA,gBAAmB;AAC9B7B,IAD8B;AAE9BJ,QAF8B;AAG9BkC,SAH8B;AAI9BC,OAJ8B;AAK9BnB,eAL8B;AAM9BoB,WAN8B;AAO9BC,UAP8B;AAQ1B;AACJC,MAAAA,MAAM,EAAE5B,WAAW,CAACV,QAAD,EAAWkC,SAAX,CADf;AAEJK,MAAAA,cAAc,EAAExC,kBAAkB,CAACC,QAAD,EAAWkC,SAAX,CAF9B;AAGJM,MAAAA,cAAc,EAAEnC,kBAAkB,CAACL,QAAD,EAAWkC,SAAX,CAH9B;AAIJlC,MAAAA,QAAQ,EAARA,QAJI;AAKJI,MAAAA,IAAI,EAAJA,IALI;AAMJsB,MAAAA,iBAAiB,EAAE,qCAAMA,kBAAiB,CAAC,mBAAUS,OAAV,CAAD,CAAvB,EANf;AAOJM,MAAAA,iBAAiB,EAAEN,OAPf;AAQJpB,MAAAA,uBAAuB,EAAEA,uBAAuB,CAACC,eAAD,CAR5C;AASJoB,MAAAA,WAAW,EAAXA,WATI;AAUJC,MAAAA,SAAS,EAAE,mBAAAN,GAAG,UAAKA,GAAG,KAAK,IAAR,IAAgBA,GAAG,KAAKW,SAAxB,GAAoC,EAApC,GAAyCL,UAAS,CAACN,GAAD,CAAvD,EAVV;AAWJY,MAAAA,eAAe,EAAET,SAAS,WAXtB,EAR0B,GAAzB,C","sourcesContent":["import { merge } from \"lodash\"\nimport { constant, isUndefined, has, mapValues, cloneDeep } from \"lodash/fp\"\nimport { isNotEmpty } from \"../../common/index.js\"\n\nexport const getSafeFieldParser = (tryParse, defaultValueFunctions) => (\n field,\n record\n) => {\n if (has(field.name)(record)) {\n return getSafeValueParser(\n tryParse,\n defaultValueFunctions\n )(record[field.name])\n }\n return defaultValueFunctions[field.getUndefinedValue]()\n}\n\nexport const getSafeValueParser = (\n tryParse,\n defaultValueFunctions\n) => value => {\n const parsed = tryParse(value)\n if (parsed.success) {\n return parsed.value\n }\n return defaultValueFunctions.default()\n}\n\nexport const getNewValue = (tryParse, defaultValueFunctions) => field => {\n const getInitialValue =\n isUndefined(field) || isUndefined(field.getInitialValue)\n ? \"default\"\n : field.getInitialValue\n\n return has(getInitialValue)(defaultValueFunctions)\n ? defaultValueFunctions[getInitialValue]()\n : getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue)\n}\n\nexport const typeFunctions = specificFunctions =>\n merge(\n {\n value: constant,\n null: constant(null),\n },\n specificFunctions\n )\n\nexport const validateTypeConstraints = validationRules => (field, record) => {\n const fieldValue = record[field.name]\n const validateRule = r =>\n !r.isValid(fieldValue, field.typeOptions)\n ? r.getMessage(fieldValue, field.typeOptions)\n : \"\"\n\n const errors = []\n for (const r of validationRules) {\n const err = validateRule(r)\n if (isNotEmpty(err)) errors.push(err)\n }\n\n return errors\n}\n\nconst getDefaultOptions = mapValues(v => v.defaultValue)\n\nexport const makerule = (isValid, getMessage) => ({ isValid, getMessage })\nexport const parsedFailed = val => ({ success: false, value: val })\nexport const parsedSuccess = val => ({ success: true, value: val })\nexport const getDefaultExport = (\n name,\n tryParse,\n functions,\n options,\n validationRules,\n sampleValue,\n stringify\n) => ({\n getNew: getNewValue(tryParse, functions),\n safeParseField: getSafeFieldParser(tryParse, functions),\n safeParseValue: getSafeValueParser(tryParse, functions),\n tryParse,\n name,\n getDefaultOptions: () => getDefaultOptions(cloneDeep(options)),\n optionDefinitions: options,\n validateTypeConstraints: validateTypeConstraints(validationRules),\n sampleValue,\n stringify: val => (val === null || val === undefined ? \"\" : stringify(val)),\n getDefaultValue: functions.default,\n})\n"],"file":"typeHelpers.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/views.js b/packages/common/lib/schema/views.js new file mode 100644 index 0000000000..5b846c4fa5 --- /dev/null +++ b/packages/common/lib/schema/views.js @@ -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 \ No newline at end of file diff --git a/packages/common/lib/schema/views.js.map b/packages/common/lib/schema/views.js.map new file mode 100644 index 0000000000..07be3044e4 --- /dev/null +++ b/packages/common/lib/schema/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"} \ No newline at end of file diff --git a/packages/common/package.json b/packages/common/package.json index 209c5479b4..4a8f82c16b 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -2,6 +2,7 @@ "name": "@budibase/common", "version": "0.0.32", "description": "core javascript library for budibase", + "main": "lib/index.js", "files": [ "dist/**", "!dist/node_modules" @@ -10,7 +11,8 @@ "test": "test" }, "scripts": { - "test": "jest" + "test": "jest", + "build": "npx babel src --out-dir lib --source-maps" }, "keywords": [ "budibase" diff --git a/packages/common/src/common/apiWrapper.mjs b/packages/common/src/common/apiWrapper.js similarity index 100% rename from packages/common/src/common/apiWrapper.mjs rename to packages/common/src/common/apiWrapper.js diff --git a/packages/common/src/common/compileCode.mjs b/packages/common/src/common/compileCode.js similarity index 100% rename from packages/common/src/common/compileCode.mjs rename to packages/common/src/common/compileCode.js diff --git a/packages/common/src/common/errors.mjs b/packages/common/src/common/errors.js similarity index 100% rename from packages/common/src/common/errors.mjs rename to packages/common/src/common/errors.js diff --git a/packages/common/src/common/eventAggregator.mjs b/packages/common/src/common/eventAggregator.js similarity index 100% rename from packages/common/src/common/eventAggregator.mjs rename to packages/common/src/common/eventAggregator.js diff --git a/packages/common/src/common/events.mjs b/packages/common/src/common/events.js similarity index 100% rename from packages/common/src/common/events.mjs rename to packages/common/src/common/events.js diff --git a/packages/common/src/common/index.mjs b/packages/common/src/common/index.js similarity index 98% rename from packages/common/src/common/index.mjs rename to packages/common/src/common/index.js index 1b7750f9ae..7c91ef9d67 100644 --- a/packages/common/src/common/index.mjs +++ b/packages/common/src/common/index.js @@ -27,7 +27,7 @@ import { includes, filter, } from "lodash/fp" -import { events, eventsList } from "./events.mjs" +import { events, eventsList } from "./events.js" // this is the combinator function 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 { ifExists, diff --git a/packages/common/src/common/validationCommon.mjs b/packages/common/src/common/validationCommon.js similarity index 100% rename from packages/common/src/common/validationCommon.mjs rename to packages/common/src/common/validationCommon.js diff --git a/packages/common/src/index.js b/packages/common/src/index.js index e69de29bb2..b8e96f333c 100644 --- a/packages/common/src/index.js +++ b/packages/common/src/index.js @@ -0,0 +1,3 @@ +export { validateRecord } from "./records/validateRecord"; +export { events } from "./common/events"; +export { safeParseField } from "./schema/types"; \ No newline at end of file diff --git a/packages/common/src/records/getNewRecord.mjs b/packages/common/src/records/getNewRecord.js similarity index 100% rename from packages/common/src/records/getNewRecord.mjs rename to packages/common/src/records/getNewRecord.js diff --git a/packages/common/src/records/recordValidationRules.mjs b/packages/common/src/records/recordValidationRules.js similarity index 100% rename from packages/common/src/records/recordValidationRules.mjs rename to packages/common/src/records/recordValidationRules.js diff --git a/packages/common/src/records/validateRecord.js b/packages/common/src/records/validateRecord.js index 84890c32e0..b6fcf6a0a3 100644 --- a/packages/common/src/records/validateRecord.js +++ b/packages/common/src/records/validateRecord.js @@ -1,11 +1,10 @@ -const { map, reduce, filter, isEmpty, flatten, each, union } = require("lodash/fp"); -const { compileCode } = require("../common/compileCode"); -const { validateFieldParse, validateTypeConstraints } = require("../schema/types"); +import { map, reduce, filter, isEmpty, flatten, each, union } from "lodash/fp"; +import { compileCode } from "../common/compileCode"; import { validateFieldParse, validateTypeConstraints, } from "../schema/types/index.js" -import { $, isNonEmptyString } from "../common/index.mjs" +import { $, isNonEmptyString } from "../common/index.js" const fieldParseError = (fieldName, value) => ({ fields: [fieldName], diff --git a/packages/common/src/records/validateRecord.mjs b/packages/common/src/records/validateRecord.mjs deleted file mode 100644 index 7f9e774a55..0000000000 --- a/packages/common/src/records/validateRecord.mjs +++ /dev/null @@ -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 - ), - } -} diff --git a/packages/common/src/schema/createActions.mjs b/packages/common/src/schema/createActions.js similarity index 100% rename from packages/common/src/schema/createActions.mjs rename to packages/common/src/schema/createActions.js diff --git a/packages/common/src/schema/fields.mjs b/packages/common/src/schema/fields.js similarity index 97% rename from packages/common/src/schema/fields.mjs rename to packages/common/src/schema/fields.js index 5e6c1fcfd0..0a11acf596 100644 --- a/packages/common/src/schema/fields.mjs +++ b/packages/common/src/schema/fields.js @@ -6,7 +6,7 @@ import { isNothingOrEmpty, isNothing, } from "../common" -import { all, getDefaultOptions } from "./types/index.mjs" +import { all, getDefaultOptions } from "./types/index.js" import { applyRuleSet, makerule } from "../common/validationCommon" import { BadRequestError } from "../common/errors" import { generate } from "shortid" diff --git a/packages/common/src/schema/fullSchema.mjs b/packages/common/src/schema/fullSchema.js similarity index 100% rename from packages/common/src/schema/fullSchema.mjs rename to packages/common/src/schema/fullSchema.js diff --git a/packages/common/src/schema/models.mjs b/packages/common/src/schema/models.js similarity index 100% rename from packages/common/src/schema/models.mjs rename to packages/common/src/schema/models.js diff --git a/packages/common/src/schema/types/array.mjs b/packages/common/src/schema/types/array.js similarity index 97% rename from packages/common/src/schema/types/array.mjs rename to packages/common/src/schema/types/array.js index fc0f9158d1..44c820f517 100644 --- a/packages/common/src/schema/types/array.mjs +++ b/packages/common/src/schema/types/array.js @@ -12,7 +12,7 @@ import { toNumberOrNull, $$, isSafeInteger, -} from "../../common/index.mjs" +} from "../../common/index.js" const arrayFunctions = () => typeFunctions({ diff --git a/packages/common/src/schema/types/bool.mjs b/packages/common/src/schema/types/bool.js similarity index 96% rename from packages/common/src/schema/types/bool.mjs rename to packages/common/src/schema/types/bool.js index 9165aca5bd..c1bfa70141 100644 --- a/packages/common/src/schema/types/bool.mjs +++ b/packages/common/src/schema/types/bool.js @@ -11,7 +11,7 @@ import { defaultCase, isOneOf, toBoolOrNull, -} from "../../common/index.mjs" +} from "../../common/index.js" const boolFunctions = typeFunctions({ default: constant(null), diff --git a/packages/common/src/schema/types/datetime.mjs b/packages/common/src/schema/types/datetime.js similarity index 100% rename from packages/common/src/schema/types/datetime.mjs rename to packages/common/src/schema/types/datetime.js diff --git a/packages/common/src/schema/types/file.mjs b/packages/common/src/schema/types/file.js similarity index 97% rename from packages/common/src/schema/types/file.mjs rename to packages/common/src/schema/types/file.js index 4171060f62..d0c08b7785 100644 --- a/packages/common/src/schema/types/file.mjs +++ b/packages/common/src/schema/types/file.js @@ -11,7 +11,7 @@ import { none, $, splitKey, -} from "../../common/index.mjs" +} from "../../common/index.js" const illegalCharacters = "*?\\/:<>|\0\b\f\v" diff --git a/packages/common/src/schema/types/index.mjs b/packages/common/src/schema/types/index.js similarity index 95% rename from packages/common/src/schema/types/index.mjs rename to packages/common/src/schema/types/index.js index 974b83bbf9..aae0dd3cc5 100644 --- a/packages/common/src/schema/types/index.mjs +++ b/packages/common/src/schema/types/index.js @@ -10,7 +10,7 @@ import { isArray, has, } from "lodash/fp" -import { $ } from "../../common/index.mjs" +import { $ } from "../../common" import { parsedSuccess } from "./typeHelpers" import string from "./string" import bool from "./bool" @@ -19,7 +19,7 @@ import datetime from "./datetime" import array from "./array" import link from "./link" import file from "./file" -import { BadRequestError } from "../../common/errors.mjs" +import { BadRequestError } from "../../common/errors" const allTypes = () => { const basicTypes = { diff --git a/packages/common/src/schema/types/link.mjs b/packages/common/src/schema/types/link.js similarity index 96% rename from packages/common/src/schema/types/link.mjs rename to packages/common/src/schema/types/link.js index ada1ef0efb..a2f1b2cf63 100644 --- a/packages/common/src/schema/types/link.mjs +++ b/packages/common/src/schema/types/link.js @@ -4,7 +4,7 @@ import { switchCase, defaultCase, isNonEmptyString, -} from "../../common/index.mjs" +} from "../../common/index.js" const linkNothing = () => "" diff --git a/packages/common/src/schema/types/number.mjs b/packages/common/src/schema/types/number.js similarity index 98% rename from packages/common/src/schema/types/number.mjs rename to packages/common/src/schema/types/number.js index d0dff23287..2fdcf1ac4f 100644 --- a/packages/common/src/schema/types/number.mjs +++ b/packages/common/src/schema/types/number.js @@ -11,7 +11,7 @@ import { defaultCase, toNumberOrNull, isSafeInteger, -} from "../../common/index.mjs" +} from "../../common/index.js" const numberFunctions = typeFunctions({ default: constant(null), diff --git a/packages/common/src/schema/types/object.mjs b/packages/common/src/schema/types/object.js similarity index 95% rename from packages/common/src/schema/types/object.mjs rename to packages/common/src/schema/types/object.js index d5ea57638a..d1429d1af7 100644 --- a/packages/common/src/schema/types/object.mjs +++ b/packages/common/src/schema/types/object.js @@ -5,7 +5,7 @@ import { parsedSuccess, getDefaultExport, } from "./typeHelpers" -import { switchCase, defaultCase, $ } from "../../common/index.mjs" +import { switchCase, defaultCase, $ } from "../../common/index.js" const objectFunctions = (definition, allTypes) => typeFunctions({ diff --git a/packages/common/src/schema/types/string.mjs b/packages/common/src/schema/types/string.js similarity index 98% rename from packages/common/src/schema/types/string.mjs rename to packages/common/src/schema/types/string.js index 077751243f..2c19cb8ce5 100644 --- a/packages/common/src/schema/types/string.mjs +++ b/packages/common/src/schema/types/string.js @@ -12,7 +12,7 @@ import { toNumberOrNull, isSafeInteger, isArrayOfString, -} from "../../common/index.mjs" +} from "../../common/index.js" const stringFunctions = typeFunctions({ default: constant(null), diff --git a/packages/common/src/schema/types/typeHelpers.mjs b/packages/common/src/schema/types/typeHelpers.js similarity index 97% rename from packages/common/src/schema/types/typeHelpers.mjs rename to packages/common/src/schema/types/typeHelpers.js index d584bc6348..0d5e1b07f0 100644 --- a/packages/common/src/schema/types/typeHelpers.mjs +++ b/packages/common/src/schema/types/typeHelpers.js @@ -1,6 +1,6 @@ import { merge } from "lodash" 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) => ( field, diff --git a/packages/common/src/schema/views.mjs b/packages/common/src/schema/views.js similarity index 100% rename from packages/common/src/schema/views.mjs rename to packages/common/src/schema/views.js diff --git a/packages/common/test/testSchema.mjs b/packages/common/test/testSchema.js similarity index 100% rename from packages/common/test/testSchema.mjs rename to packages/common/test/testSchema.js diff --git a/packages/server/middleware/controllers/client.js b/packages/server/middleware/controllers/client.js index 7446c4f03a..27dfdd20ac 100644 --- a/packages/server/middleware/controllers/client.js +++ b/packages/server/middleware/controllers/client.js @@ -13,6 +13,7 @@ exports.create = async function(ctx) { } } }, '_design/client'); + ctx.body = { message: `Client Database ${clientId} successfully provisioned.` } @@ -20,7 +21,9 @@ exports.create = async function(ctx) { exports.destroy = async function(ctx) { const dbId = `client-${ctx.params.clientId}`; + await couchdb.db.destroy(dbId); + ctx.body = { status: 200, message: `Client Database ${dbId} successfully deleted.` diff --git a/packages/server/middleware/controllers/model.js b/packages/server/middleware/controllers/model.js index 35c9b37fe6..bc2cbbde7f 100644 --- a/packages/server/middleware/controllers/model.js +++ b/packages/server/middleware/controllers/model.js @@ -38,6 +38,7 @@ exports.fetch = async function(ctx) { exports.create = async function(ctx) { const db = couchdb.db.use(ctx.params.instanceId); const newModel = await db.insert(ctx.request.body); + const designDoc = await db.get("_design/database"); designDoc.views = { ...designDoc.views, @@ -47,8 +48,8 @@ exports.create = async function(ctx) { } } }; - await db.insert(designDoc, designDoc._id); + ctx.body = { ...newModel, message: `Model ${ctx.request.body.name} created successfully.`, diff --git a/packages/server/middleware/controllers/record.js b/packages/server/middleware/controllers/record.js index bbfc24007a..eac9ea3c90 100644 --- a/packages/server/middleware/controllers/record.js +++ b/packages/server/middleware/controllers/record.js @@ -2,9 +2,9 @@ const couchdb = require("../../db") const { mapValues, keyBy, compose } = require("lodash/fp") const { validateRecord, -} = require("../../../common/src/records/validateRecord") -const { events } = require("../../../common/src/common/events") -const { safeParseField } = require("../../../common/src/schema/types"); + events, + safeParseField +} = require("@budibase/common") exports.save = async function(ctx) { const db = couchdb.use(ctx.databaseId) diff --git a/packages/server/middleware/controllers/static.js b/packages/server/middleware/controllers/static.js new file mode 100644 index 0000000000..554dad401b --- /dev/null +++ b/packages/server/middleware/controllers/static.js @@ -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 }) +} \ No newline at end of file diff --git a/packages/server/middleware/routers.js b/packages/server/middleware/routers.js index 4f640ff549..5a07333c3e 100644 --- a/packages/server/middleware/routers.js +++ b/packages/server/middleware/routers.js @@ -22,6 +22,7 @@ const clientRoutes = require("./routes/neo/client"); const applicationRoutes = require("./routes/neo/application"); const modelsRoutes = require("./routes/neo/model"); const viewsRoutes = require("./routes/neo/view"); +const staticRoutes = require("./routes/neo/static"); const builderPath = resolve(__dirname, "../builder") @@ -29,7 +30,13 @@ module.exports = (config, app) => { const router = new 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) => { // ctx.sessionId = ctx.session._sessCtx.externalKey // ctx.session.accessed = true @@ -96,9 +103,9 @@ module.exports = (config, app) => { // }) router - .get("/_builder", async ctx => { - await send(ctx, "/index.html", { root: builderPath }) - }) + // .get("/_builder", async ctx => { + // await send(ctx, "/index.html", { root: builderPath }) + // }) .get("/_builder/:appname/componentlibrary", async ctx => { const info = await componentLibraryInfo( ctx.config, @@ -107,19 +114,19 @@ module.exports = (config, app) => { ) await send(ctx, info.components._lib || "index.js", { root: info.libDir }) }) - .get("/_builder/*", async (ctx, next) => { - const path = ctx.path.replace("/_builder", "") + // .get("/_builder/*", async (ctx, next) => { + // 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/")) { - await next() - } else if (isFile) { - await send(ctx, path, { root: builderPath }) - } else { - await send(ctx, "/index.html", { root: builderPath }) - } - }) + // if (path.startsWith("/api/") || path.startsWith("/instance/")) { + // await next() + // } else if (isFile) { + // await send(ctx, path, { root: builderPath }) + // } else { + // await send(ctx, "/index.html", { root: builderPath }) + // } + // }) // Neo // error handling middleware @@ -127,6 +134,7 @@ module.exports = (config, app) => { try { await next(); } catch (err) { + console.trace(err); ctx.status = err.status || 500; ctx.body = { 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.allowedMethods()); @@ -156,8 +167,6 @@ module.exports = (config, app) => { router.use(databaseRoutes.routes()); router.use(databaseRoutes.allowedMethods()); - router.use(databaseRoutes.routes()); - router.use(databaseRoutes.allowedMethods()); // end of Neo router.use(userRoutes.routes()); @@ -170,9 +179,9 @@ module.exports = (config, app) => { router.use(pageRoutes.allowedMethods()); // router - // .get("/:appname", async ctx => { - // await send(ctx, "/index.html", { root: ctx.publicPath }) - // }) + // .get("/:appname", async ctx => { + // await send(ctx, "/index.html", { root: ctx.publicPath }) + // }) // .get("/:appname/*", routeHandlers.appDefault) // .get("/_builder/instance/:appname/:instanceid/*", routeHandlers.appDefault) diff --git a/packages/server/middleware/routes/neo/record.js b/packages/server/middleware/routes/neo/record.js index 21b8de7ecf..60589c1d76 100644 --- a/packages/server/middleware/routes/neo/record.js +++ b/packages/server/middleware/routes/neo/record.js @@ -1,12 +1,12 @@ const Router = require("@koa/router"); -// const controller = require("../../controllers/record"); +const controller = require("../../controllers/record"); const router = Router(); -// router -// .get("/api/:databaseId/records/:modelname", controller.fetch) -// .post("/api/:databaseId/record", controller.save) -// .get("/api/:databaseId/record/:recordId", controller.find) -// .delete("/api/:databaseId/record/:recordId", controller.destroy) +router + .get("/api/:databaseId/:modelId/records", controller.fetch) + .get("/api/:databaseId/records/:recordId", controller.find) + .post("/api/:databaseId/records", controller.save) + .delete("/api/:databaseId/records/:recordId", controller.destroy) module.exports = router; \ No newline at end of file diff --git a/packages/server/middleware/routes/neo/static.js b/packages/server/middleware/routes/neo/static.js new file mode 100644 index 0000000000..38f2eab813 --- /dev/null +++ b/packages/server/middleware/routes/neo/static.js @@ -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; \ No newline at end of file diff --git a/packages/server/package.json b/packages/server/package.json index b8507c851d..9406ee741f 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -19,6 +19,7 @@ "license": "AGPL-3.0-or-later", "dependencies": { "@budibase/client": "^0.0.32", + "@budibase/common": "0.0.32", "@budibase/core": "^0.0.32", "@koa/router": "^8.0.0", "fs-extra": "^8.1.0",