diff --git a/.eslintrc.json b/.eslintrc.json index 79f7e56712..917443014b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -45,6 +45,16 @@ "no-prototype-builtins": "off", "local-rules/no-budibase-imports": "error" } + }, + { + "files": [ + "packages/builder/**/*", + "packages/client/**/*", + "packages/frontend-core/**/*" + ], + "rules": { + "no-console": ["error", { "allow": ["warn", "error", "debug"] } ] + } } ], "rules": { diff --git a/lerna.json b/lerna.json index f91c51d4bb..0f02995ac0 100644 --- a/lerna.json +++ b/lerna.json @@ -1,5 +1,5 @@ { - "version": "2.16.0", + "version": "2.17.3", "npmClient": "yarn", "packages": [ "packages/*", diff --git a/packages/account-portal b/packages/account-portal index 485ec16a9e..cc12291732 160000 --- a/packages/account-portal +++ b/packages/account-portal @@ -1 +1 @@ -Subproject commit 485ec16a9eed48c548a5f1239772139f3319f028 +Subproject commit cc12291732ee902dc832bc7d93cf2086ffdf0cff diff --git a/packages/backend-core/package.json b/packages/backend-core/package.json index d6325e1de9..85644488f5 100644 --- a/packages/backend-core/package.json +++ b/packages/backend-core/package.json @@ -21,7 +21,7 @@ "test:watch": "jest --watchAll" }, "dependencies": { - "@budibase/nano": "10.1.4", + "@budibase/nano": "10.1.5", "@budibase/pouchdb-replication-stream": "1.2.10", "@budibase/shared-core": "0.0.0", "@budibase/types": "0.0.0", diff --git a/packages/backend-core/src/objectStore/cloudfront.ts b/packages/backend-core/src/objectStore/cloudfront.ts index 866fe9e880..3bca97d11e 100644 --- a/packages/backend-core/src/objectStore/cloudfront.ts +++ b/packages/backend-core/src/objectStore/cloudfront.ts @@ -23,7 +23,7 @@ const getCloudfrontSignParams = () => { return { keypairId: env.CLOUDFRONT_PUBLIC_KEY_ID!, privateKeyString: getPrivateKey(), - expireTime: new Date().getTime() + 1000 * 60 * 60, // 1 hour + expireTime: new Date().getTime() + 1000 * 60 * 60 * 24, // 1 day } } diff --git a/packages/backend-core/src/objectStore/objectStore.ts b/packages/backend-core/src/objectStore/objectStore.ts index 57ead0e809..3a3b9cdaab 100644 --- a/packages/backend-core/src/objectStore/objectStore.ts +++ b/packages/backend-core/src/objectStore/objectStore.ts @@ -7,7 +7,7 @@ import tar from "tar-fs" import zlib from "zlib" import { promisify } from "util" import { join } from "path" -import fs from "fs" +import fs, { ReadStream } from "fs" import env from "../environment" import { budibaseTempDir } from "./utils" import { v4 } from "uuid" @@ -184,7 +184,7 @@ export async function upload({ export async function streamUpload( bucketName: string, filename: string, - stream: any, + stream: ReadStream | ReadableStream, extra = {} ) { const objectStore = ObjectStore(bucketName) diff --git a/packages/builder/src/builderStore/dataBinding.js b/packages/builder/src/builderStore/dataBinding.js index cc3851c318..86aecd466f 100644 --- a/packages/builder/src/builderStore/dataBinding.js +++ b/packages/builder/src/builderStore/dataBinding.js @@ -364,7 +364,6 @@ const getContextBindings = (asset, componentId) => { * Generates a set of bindings for a given component context */ const generateComponentContextBindings = (asset, componentContext) => { - console.log("Hello ") const { component, definition, contexts } = componentContext if (!component || !definition || !contexts?.length) { return [] diff --git a/packages/builder/src/builderStore/store/frontend.js b/packages/builder/src/builderStore/store/frontend.js index 4d43869f8e..55208bb97e 100644 --- a/packages/builder/src/builderStore/store/frontend.js +++ b/packages/builder/src/builderStore/store/frontend.js @@ -158,6 +158,7 @@ export const getFrontendStore = () => { ...INITIAL_FRONTEND_STATE.features, ...application.features, }, + automations: application.automations || {}, icon: application.icon || {}, initialised: true, })) diff --git a/packages/builder/src/builderStore/websocket.js b/packages/builder/src/builderStore/websocket.js index ca3f49e9a3..4482e3ae1e 100644 --- a/packages/builder/src/builderStore/websocket.js +++ b/packages/builder/src/builderStore/websocket.js @@ -21,7 +21,7 @@ export const createBuilderWebsocket = appId => { }) }) socket.on("connect_error", err => { - console.log("Failed to connect to builder websocket:", err.message) + console.error("Failed to connect to builder websocket:", err.message) }) socket.on("disconnect", () => { userStore.actions.reset() diff --git a/packages/builder/src/components/automation/SetupPanel/AutomationBlockSetup.svelte b/packages/builder/src/components/automation/SetupPanel/AutomationBlockSetup.svelte index af54e4d2da..1536d83a82 100644 --- a/packages/builder/src/components/automation/SetupPanel/AutomationBlockSetup.svelte +++ b/packages/builder/src/components/automation/SetupPanel/AutomationBlockSetup.svelte @@ -15,7 +15,6 @@ Icon, Checkbox, DatePicker, - Detail, } from "@budibase/bbui" import CreateWebhookModal from "components/automation/Shared/CreateWebhookModal.svelte" import { automationStore, selectedAutomation } from "builderStore" @@ -33,6 +32,8 @@ import Editor from "components/integration/QueryEditor.svelte" import ModalBindableInput from "components/common/bindings/ModalBindableInput.svelte" import CodeEditor from "components/common/CodeEditor/CodeEditor.svelte" + import BindingPicker from "components/common/bindings/BindingPicker.svelte" + import { BindingHelpers } from "components/common/bindings/utils" import { bindingsToCompletions, hbAutocomplete, @@ -56,7 +57,7 @@ let drawer let fillWidth = true let inputData - let codeBindingOpen = false + let insertAtPos, getCaretPosition $: filters = lookForFilters(schemaProperties) || [] $: tempFilters = filters $: stepId = block.stepId @@ -75,6 +76,10 @@ $: isUpdateRow = stepId === ActionStepID.UPDATE_ROW $: codeMode = stepId === "EXECUTE_BASH" ? EditorModes.Handlebars : EditorModes.JS + $: bindingsHelpers = new BindingHelpers(getCaretPosition, insertAtPos, { + disableWrapping: true, + }) + $: editingJs = codeMode === EditorModes.JS $: stepCompletions = codeMode === EditorModes.Handlebars @@ -157,6 +162,7 @@ let bindings = [] let loopBlockCount = 0 const addBinding = (name, value, icon, idx, isLoopBlock, bindingName) => { + if (!name) return const runtimeBinding = determineRuntimeBinding(name, idx, isLoopBlock) const categoryName = determineCategoryName(idx, isLoopBlock, bindingName) @@ -291,7 +297,6 @@ loopBlockCount++ continue } - Object.entries(schema).forEach(([name, value]) => addBinding(name, value, icon, idx, isLoopBlock, bindingName) ) @@ -539,39 +544,51 @@ /> {:else if value.customType === "code"} - {#if codeMode == EditorModes.JS} - (codeBindingOpen = !codeBindingOpen)} - quiet - icon={codeBindingOpen ? "ChevronDown" : "ChevronRight"} - > - Bindings - - {#if codeBindingOpen} -
{JSON.stringify(bindings, null, 2)}
- {/if} - {/if} - { - // need to pass without the value inside - onChange({ detail: e.detail }, key) - inputData[key] = e.detail - }} - completions={stepCompletions} - mode={codeMode} - autocompleteEnabled={codeMode != EditorModes.JS} - height={500} - /> -
- {#if codeMode == EditorModes.Handlebars} - -
-
- Add available bindings by typing - }} - -
+
+
+ { + // need to pass without the value inside + onChange({ detail: e.detail }, key) + inputData[key] = e.detail + }} + completions={stepCompletions} + mode={codeMode} + autocompleteEnabled={codeMode !== EditorModes.JS} + bind:getCaretPosition + bind:insertAtPos + height={500} + /> +
+ {#if codeMode === EditorModes.Handlebars} + +
+
+ Add available bindings by typing + }} + +
+
+ {/if} +
+
+ {#if editingJs} +
+ + bindingsHelpers.onSelectBinding( + inputData[key], + binding, + { + js: true, + dontDecode: true, + } + )} + mode="javascript" + />
{/if}
@@ -658,4 +675,20 @@ .test :global(.drawer) { width: 10000px !important; } + + .js-editor { + display: flex; + flex-direction: row; + flex-grow: 1; + width: 100%; + } + + .js-code { + flex: 7; + } + + .js-binding-picker { + flex: 3; + margin-top: calc((var(--spacing-xl) * -1) + 1px); + } diff --git a/packages/builder/src/components/common/CodeEditor/CodeEditor.svelte b/packages/builder/src/components/common/CodeEditor/CodeEditor.svelte index a39634f9a3..e906ef445d 100644 --- a/packages/builder/src/components/common/CodeEditor/CodeEditor.svelte +++ b/packages/builder/src/components/common/CodeEditor/CodeEditor.svelte @@ -54,6 +54,7 @@ export let placeholder = null export let autocompleteEnabled = true export let autofocus = false + export let jsBindingWrapping = true // Export a function to expose caret position export const getCaretPosition = () => { @@ -187,7 +188,7 @@ ) complete.push( EditorView.inputHandler.of((view, from, to, insert) => { - if (insert === "$") { + if (jsBindingWrapping && insert === "$") { let { text } = view.state.doc.lineAt(from) const left = from ? text.substring(0, from) : "" diff --git a/packages/builder/src/components/common/CodeEditor/index.js b/packages/builder/src/components/common/CodeEditor/index.js index 7987deff52..38d377b47a 100644 --- a/packages/builder/src/components/common/CodeEditor/index.js +++ b/packages/builder/src/components/common/CodeEditor/index.js @@ -286,13 +286,14 @@ export const hbInsert = (value, from, to, text) => { return parsedInsert } -export function jsInsert(value, from, to, text, { helper } = {}) { +export function jsInsert(value, from, to, text, { helper, disableWrapping }) { let parsedInsert = "" const left = from ? value.substring(0, from) : "" const right = to ? value.substring(to) : "" - - if (helper) { + if (disableWrapping) { + parsedInsert = text + } else if (helper) { parsedInsert = `helpers.${text}()` } else if (!left.includes('$("') || !right.includes('")')) { parsedInsert = `$("${text}")` @@ -312,7 +313,7 @@ export const insertBinding = (view, from, to, text, mode) => { } else if (mode.name == "handlebars") { parsedInsert = hbInsert(view.state.doc?.toString(), from, to, text) } else { - console.log("Unsupported") + console.warn("Unsupported") return } diff --git a/packages/builder/src/components/common/bindings/BindingPanel.svelte b/packages/builder/src/components/common/bindings/BindingPanel.svelte index 548a71b483..0ef34a36ad 100644 --- a/packages/builder/src/components/common/bindings/BindingPanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingPanel.svelte @@ -29,10 +29,9 @@ hbAutocomplete, EditorModes, bindingsToCompletions, - hbInsert, - jsInsert, } from "../CodeEditor" import BindingPicker from "./BindingPicker.svelte" + import { BindingHelpers } from "./utils" const dispatch = createEventDispatcher() @@ -60,8 +59,10 @@ let targetMode = null $: usingJS = mode === "JavaScript" - $: editorMode = mode == "JavaScript" ? EditorModes.JS : EditorModes.Handlebars + $: editorMode = + mode === "JavaScript" ? EditorModes.JS : EditorModes.Handlebars $: bindingCompletions = bindingsToCompletions(bindings, editorMode) + $: bindingHelpers = new BindingHelpers(getCaretPosition, insertAtPos) const updateValue = val => { valid = isValid(readableToRuntimeBinding(bindings, val)) @@ -70,31 +71,13 @@ } } - // Adds a JS/HBS helper to the expression const onSelectHelper = (helper, js) => { - const pos = getCaretPosition() - const { start, end } = pos - if (js) { - let js = decodeJSBinding(jsValue) - const insertVal = jsInsert(js, start, end, helper.text, { helper: true }) - insertAtPos({ start, end, value: insertVal }) - } else { - const insertVal = hbInsert(hbsValue, start, end, helper.text) - insertAtPos({ start, end, value: insertVal }) - } + bindingHelpers.onSelectHelper(js ? jsValue : hbsValue, helper, { js }) } - // Adds a data binding to the expression const onSelectBinding = (binding, { forceJS } = {}) => { - const { start, end } = getCaretPosition() - if (usingJS || forceJS) { - let js = decodeJSBinding(jsValue) - const insertVal = jsInsert(js, start, end, binding.readableBinding) - insertAtPos({ start, end, value: insertVal }) - } else { - const insertVal = hbInsert(hbsValue, start, end, binding.readableBinding) - insertAtPos({ start, end, value: insertVal }) - } + const js = usingJS || forceJS + bindingHelpers.onSelectBinding(js ? jsValue : hbsValue, binding, { js }) } const onChangeMode = e => { diff --git a/packages/builder/src/components/common/bindings/BindingPicker.svelte b/packages/builder/src/components/common/bindings/BindingPicker.svelte index 93d9d62021..9daed00324 100644 --- a/packages/builder/src/components/common/bindings/BindingPicker.svelte +++ b/packages/builder/src/components/common/bindings/BindingPicker.svelte @@ -9,6 +9,7 @@ export let bindings export let mode export let allowHelpers + export let noPaddingTop = false let search = "" let popover @@ -47,9 +48,10 @@ }) $: filteredHelpers = helpers?.filter(helper => { return ( - !search || - helper.label.match(searchRgx) || - helper.description.match(searchRgx) + (!search || + helper.label.match(searchRgx) || + helper.description.match(searchRgx)) && + (mode.name !== "javascript" || helper.allowsJs) ) }) diff --git a/packages/builder/src/components/common/bindings/utils.js b/packages/builder/src/components/common/bindings/utils.js index 8d414ffed3..a086cd0394 100644 --- a/packages/builder/src/components/common/bindings/utils.js +++ b/packages/builder/src/components/common/bindings/utils.js @@ -1,38 +1,41 @@ -export function addHBSBinding(value, caretPos, binding) { - binding = typeof binding === "string" ? binding : binding.path - value = value == null ? "" : value +import { decodeJSBinding } from "@budibase/string-templates" +import { hbInsert, jsInsert } from "components/common/CodeEditor" - const left = caretPos?.start ? value.substring(0, caretPos.start) : "" - const right = caretPos?.end ? value.substring(caretPos.end) : "" - if (!left.includes("{{") || !right.includes("}}")) { - binding = `{{ ${binding} }}` +export class BindingHelpers { + constructor(getCaretPosition, insertAtPos, { disableWrapping } = {}) { + this.getCaretPosition = getCaretPosition + this.insertAtPos = insertAtPos + this.disableWrapping = disableWrapping } - if (caretPos.start) { - value = - value.substring(0, caretPos.start) + - binding + - value.substring(caretPos.end, value.length) - } else { - value += binding - } - return value -} -export function addJSBinding(value, caretPos, binding, { helper } = {}) { - binding = typeof binding === "string" ? binding : binding.path - value = value == null ? "" : value - if (!helper) { - binding = `$("${binding}")` - } else { - binding = `helpers.${binding}()` + // Adds a JS/HBS helper to the expression + onSelectHelper(value, helper, { js, dontDecode }) { + const pos = this.getCaretPosition() + const { start, end } = pos + if (js) { + const jsVal = dontDecode ? value : decodeJSBinding(value) + const insertVal = jsInsert(jsVal, start, end, helper.text, { + helper: true, + }) + this.insertAtPos({ start, end, value: insertVal }) + } else { + const insertVal = hbInsert(value, start, end, helper.text) + this.insertAtPos({ start, end, value: insertVal }) + } } - if (caretPos.start) { - value = - value.substring(0, caretPos.start) + - binding + - value.substring(caretPos.end, value.length) - } else { - value += binding + + // Adds a data binding to the expression + onSelectBinding(value, binding, { js, dontDecode }) { + const { start, end } = this.getCaretPosition() + if (js) { + const jsVal = dontDecode ? value : decodeJSBinding(value) + const insertVal = jsInsert(jsVal, start, end, binding.readableBinding, { + disableWrapping: this.disableWrapping, + }) + this.insertAtPos({ start, end, value: insertVal }) + } else { + const insertVal = hbInsert(value, start, end, binding.readableBinding) + this.insertAtPos({ start, end, value: insertVal }) + } } - return value } diff --git a/packages/builder/src/components/portal/onboarding/TourPopover.svelte b/packages/builder/src/components/portal/onboarding/TourPopover.svelte index d959a6ef95..cc56715284 100644 --- a/packages/builder/src/components/portal/onboarding/TourPopover.svelte +++ b/packages/builder/src/components/portal/onboarding/TourPopover.svelte @@ -67,7 +67,7 @@ })) navigateStep(target) } else { - console.log("Could not retrieve step") + console.warn("Could not retrieve step") } } else { if (typeof tourStep.onComplete === "function") { diff --git a/packages/builder/src/components/portal/onboarding/tourHandler.js b/packages/builder/src/components/portal/onboarding/tourHandler.js index d4a564f23a..5b44bdc96f 100644 --- a/packages/builder/src/components/portal/onboarding/tourHandler.js +++ b/packages/builder/src/components/portal/onboarding/tourHandler.js @@ -3,11 +3,11 @@ import { get } from "svelte/store" const registerNode = async (node, tourStepKey) => { if (!node) { - console.log("Tour Handler - an anchor node is required") + console.warn("Tour Handler - an anchor node is required") } if (!get(store).tourKey) { - console.log("Tour Handler - No active tour ", tourStepKey, node) + console.error("Tour Handler - No active tour ", tourStepKey, node) return } diff --git a/packages/builder/src/components/portal/onboarding/tours.js b/packages/builder/src/components/portal/onboarding/tours.js index e82026da94..55fd4c4a9b 100644 --- a/packages/builder/src/components/portal/onboarding/tours.js +++ b/packages/builder/src/components/portal/onboarding/tours.js @@ -45,7 +45,7 @@ const endUserOnboarding = async ({ skipped = false } = {}) => { onboarding: false, })) } catch (e) { - console.log("Onboarding failed", e) + console.error("Onboarding failed", e) return false } return true diff --git a/packages/builder/src/constants/completions.js b/packages/builder/src/constants/completions.js index 32de934324..e539a8084a 100644 --- a/packages/builder/src/constants/completions.js +++ b/packages/builder/src/constants/completions.js @@ -1,4 +1,4 @@ -import { getManifest } from "@budibase/string-templates" +import { getManifest, helpersToRemoveForJs } from "@budibase/string-templates" export function handlebarsCompletions() { const manifest = getManifest() @@ -11,6 +11,9 @@ export function handlebarsCompletions() { label: helperName, displayText: helperName, description: helperConfig.description, + allowsJs: + !helperConfig.requiresBlock && + !helpersToRemoveForJs.includes(helperName), })) ) } diff --git a/packages/builder/src/helpers/urlStateSync.js b/packages/builder/src/helpers/urlStateSync.js index 2408dde2f1..9337393f06 100644 --- a/packages/builder/src/helpers/urlStateSync.js +++ b/packages/builder/src/helpers/urlStateSync.js @@ -52,7 +52,7 @@ export const syncURLToState = options => { let cachedPage = get(routify.page) let previousParamsHash = null let debug = false - const log = (...params) => debug && console.log(`[${urlParam}]`, ...params) + const log = (...params) => debug && console.debug(`[${urlParam}]`, ...params) // Navigate to a certain URL const gotoUrl = (url, params) => { diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 33116094eb..cd00b36186 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -107,7 +107,7 @@ return } if (!prodAppId) { - console.log("Application id required") + console.error("Application id required") return } await usersFetch.update({ diff --git a/packages/builder/src/pages/builder/app/[application]/design/[screenId]/[componentId]/_components/Screen/GeneralPanel.svelte b/packages/builder/src/pages/builder/app/[application]/design/[screenId]/[componentId]/_components/Screen/GeneralPanel.svelte index fb9ee2c8a5..b2bcd3daa4 100644 --- a/packages/builder/src/pages/builder/app/[application]/design/[screenId]/[componentId]/_components/Screen/GeneralPanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/design/[screenId]/[componentId]/_components/Screen/GeneralPanel.svelte @@ -66,7 +66,7 @@ try { await store.actions.screens.updateSetting(get(selectedScreen), key, value) } catch (error) { - console.log(error) + console.error(error) notifications.error("Error saving screen settings") } } diff --git a/packages/builder/src/pages/builder/app/[application]/design/_components/NewScreen/CreateScreenModal.svelte b/packages/builder/src/pages/builder/app/[application]/design/_components/NewScreen/CreateScreenModal.svelte index a9d64afd19..5e3a7a0f37 100644 --- a/packages/builder/src/pages/builder/app/[application]/design/_components/NewScreen/CreateScreenModal.svelte +++ b/packages/builder/src/pages/builder/app/[application]/design/_components/NewScreen/CreateScreenModal.svelte @@ -71,7 +71,7 @@ $goto(`./${screenId}`) store.actions.screens.select(screenId) } catch (error) { - console.log(error) + console.error(error) notifications.error("Error creating screens") } } diff --git a/packages/builder/src/pages/builder/app/[application]/settings/automations/index.svelte b/packages/builder/src/pages/builder/app/[application]/settings/automations/index.svelte index fde392e31d..9c45eb7eb1 100644 --- a/packages/builder/src/pages/builder/app/[application]/settings/automations/index.svelte +++ b/packages/builder/src/pages/builder/app/[application]/settings/automations/index.svelte @@ -36,15 +36,12 @@ let status = null let timeRange = null let loaded = false - - $: app = $apps.find(app => app.devId === $store.appId?.includes(app.appId)) + $: app = $apps.find(app => $store.appId?.includes(app.appId)) $: licensePlan = $auth.user?.license?.plan $: page = $pageInfo.page $: fetchLogs(automationId, status, page, timeRange) $: isCloud = $admin.cloud - $: chainAutomations = app?.automations?.chainAutomations ?? !isCloud - const timeOptions = [ { value: "90-d", label: "Past 90 days" }, { value: "30-d", label: "Past 30 days" }, diff --git a/packages/builder/src/pages/builder/app/[application]/settings/backups/_components/ActionsRenderer.svelte b/packages/builder/src/pages/builder/app/[application]/settings/backups/_components/ActionsRenderer.svelte index 93f0f518ad..ffdf14fdce 100644 --- a/packages/builder/src/pages/builder/app/[application]/settings/backups/_components/ActionsRenderer.svelte +++ b/packages/builder/src/pages/builder/app/[application]/settings/backups/_components/ActionsRenderer.svelte @@ -13,6 +13,7 @@ import CreateRestoreModal from "./CreateRestoreModal.svelte" import { createEventDispatcher } from "svelte" import { isOnlyUser } from "builderStore" + import { BackupType } from "constants/backend/backups" export let row @@ -42,12 +43,11 @@
- -
- -
- - {#if row.type !== "restore"} + {#if row.type !== BackupType.RESTORE} + +
+ +
Delete Download - {/if} -
+
+ {/if}
diff --git a/packages/builder/src/pages/builder/auth/login.svelte b/packages/builder/src/pages/builder/auth/login.svelte index 0ba7e6448b..7bb2a3ad49 100644 --- a/packages/builder/src/pages/builder/auth/login.svelte +++ b/packages/builder/src/pages/builder/auth/login.svelte @@ -31,7 +31,7 @@ async function login() { form.validate() if (Object.keys(errors).length > 0) { - console.log("errors", errors) + console.error("errors", errors) return } try { diff --git a/packages/client/manifest.json b/packages/client/manifest.json index 5bbf465766..313b679e49 100644 --- a/packages/client/manifest.json +++ b/packages/client/manifest.json @@ -6742,6 +6742,17 @@ "key": "disabled", "defaultValue": false }, + { + "type": "boolean", + "label": "Read only", + "key": "readonly", + "defaultValue": false, + "dependsOn": { + "setting": "disabled", + "value": true, + "invert": true + } + }, { "type": "select", "label": "Layout", diff --git a/packages/client/src/components/app/embedded-map/EmbeddedMap.svelte b/packages/client/src/components/app/embedded-map/EmbeddedMap.svelte index 3bb7d5606d..979cb0e085 100644 --- a/packages/client/src/components/app/embedded-map/EmbeddedMap.svelte +++ b/packages/client/src/components/app/embedded-map/EmbeddedMap.svelte @@ -307,7 +307,7 @@ // Reset view resetView() } catch (e) { - console.log("There was a problem with the map", e) + console.error("There was a problem with the map", e) } } diff --git a/packages/client/src/components/app/forms/CodeScanner.svelte b/packages/client/src/components/app/forms/CodeScanner.svelte index 2a546eb64c..008c0f5727 100644 --- a/packages/client/src/components/app/forms/CodeScanner.svelte +++ b/packages/client/src/components/app/forms/CodeScanner.svelte @@ -61,7 +61,7 @@ resolve({ initialised: true }) }) .catch(err => { - console.log("There was a problem scanning the image", err) + console.error("There was a problem scanning the image", err) resolve({ initialised: false }) }) }) diff --git a/packages/client/src/sdk.js b/packages/client/src/sdk.js index 2b8ba41cbd..536ae93ea0 100644 --- a/packages/client/src/sdk.js +++ b/packages/client/src/sdk.js @@ -28,6 +28,7 @@ import { fetchDatasourceSchema } from "./utils/schema.js" import { getAPIKey } from "./utils/api.js" import { enrichButtonActions } from "./utils/buttonActions.js" import { processStringSync, makePropSafe } from "@budibase/string-templates" +import { fetchData, LuceneUtils } from "@budibase/frontend-core" export default { API, @@ -54,6 +55,8 @@ export default { linkable, getAction, fetchDatasourceSchema, + fetchData, + LuceneUtils, ContextScopes, getAPIKey, enrichButtonActions, diff --git a/packages/client/src/stores/org.js b/packages/client/src/stores/org.js index af0fc955f9..d8a17f7c32 100644 --- a/packages/client/src/stores/org.js +++ b/packages/client/src/stores/org.js @@ -14,7 +14,7 @@ const createOrgStore = () => { const settingsConfigDoc = await API.getTenantConfig(tenantId) set({ logoUrl: settingsConfigDoc.config.logoUrl }) } catch (e) { - console.log("Could not init org ", e) + console.error("Could not init org ", e) } } diff --git a/packages/client/src/utils/buttonActions.js b/packages/client/src/utils/buttonActions.js index 68b7c84878..ef529985b2 100644 --- a/packages/client/src/utils/buttonActions.js +++ b/packages/client/src/utils/buttonActions.js @@ -211,29 +211,27 @@ const deleteRowHandler = async action => { const triggerAutomationHandler = async action => { const { fields, notificationOverride, timeout } = action.parameters - if (fields) { - try { - const result = await API.triggerAutomation({ - automationId: action.parameters.automationId, - fields, - timeout, - }) - - // Value will exist if automation is synchronous, so return it. - if (result.value) { - if (!notificationOverride) { - notificationStore.actions.success("Automation ran successfully") - } - return { result } - } + try { + const result = await API.triggerAutomation({ + automationId: action.parameters.automationId, + fields, + timeout, + }) + // Value will exist if automation is synchronous, so return it. + if (result.value) { if (!notificationOverride) { - notificationStore.actions.success("Automation triggered") + notificationStore.actions.success("Automation ran successfully") } - } catch (error) { - // Abort next actions - return false + return { result } } + + if (!notificationOverride) { + notificationStore.actions.success("Automation triggered") + } + } catch (error) { + // Abort next actions + return false } } const navigationHandler = action => { diff --git a/packages/frontend-core/src/components/grid/lib/websocket.js b/packages/frontend-core/src/components/grid/lib/websocket.js index af34acd530..b0fd236989 100644 --- a/packages/frontend-core/src/components/grid/lib/websocket.js +++ b/packages/frontend-core/src/components/grid/lib/websocket.js @@ -29,7 +29,7 @@ export const createGridWebsocket = context => { connectToDatasource(get(datasource)) }) socket.on("connect_error", err => { - console.log("Failed to connect to grid websocket:", err.message) + console.error("Failed to connect to grid websocket:", err.message) }) // User events diff --git a/packages/pro b/packages/pro index eb9565f568..aaf7101cd1 160000 --- a/packages/pro +++ b/packages/pro @@ -1 +1 @@ -Subproject commit eb9565f568cfef14b336b14eee753119acfdd43b +Subproject commit aaf7101cd1493215155cc8f83124c70d53eb1be4 diff --git a/packages/server/__mocks__/aws-sdk.ts b/packages/server/__mocks__/aws-sdk.ts index fa6d099f56..e6a624c83e 100644 --- a/packages/server/__mocks__/aws-sdk.ts +++ b/packages/server/__mocks__/aws-sdk.ts @@ -1,7 +1,13 @@ +import fs from "fs" +import { join } from "path" + module AwsMock { const aws: any = {} - const response = (body: any) => () => ({ promise: () => body }) + const response = (body: any, extra?: any) => () => ({ + promise: () => body, + ...extra, + }) function DocumentClient() { // @ts-ignore @@ -73,9 +79,18 @@ module AwsMock { // @ts-ignore this.getObject = jest.fn( - response({ - Body: "", - }) + response( + { + Body: "", + }, + { + createReadStream: jest + .fn() + .mockReturnValue( + fs.createReadStream(join(__dirname, "aws-sdk.ts")) + ), + } + ) ) } diff --git a/packages/server/src/api/controllers/application.ts b/packages/server/src/api/controllers/application.ts index 70298c7172..33582cf656 100644 --- a/packages/server/src/api/controllers/application.ts +++ b/packages/server/src/api/controllers/application.ts @@ -445,6 +445,9 @@ export async function update(ctx: UserCtx) { name: app.name, url: app.url, icon: app.icon, + automations: { + chainAutomations: app.automations?.chainAutomations, + }, }) } diff --git a/packages/server/src/sdk/app/backups/imports.ts b/packages/server/src/sdk/app/backups/imports.ts index 7f76945107..4c5c1e659d 100644 --- a/packages/server/src/sdk/app/backups/imports.ts +++ b/packages/server/src/sdk/app/backups/imports.ts @@ -165,8 +165,9 @@ export async function importApp( const isTar = template.file && template?.file?.type?.endsWith("gzip") const isDirectory = template.file && fs.lstatSync(template.file.path).isDirectory() + let tmpPath: string | undefined = undefined if (template.file && (isTar || isDirectory)) { - const tmpPath = isTar ? await untarFile(template.file) : template.file.path + tmpPath = isTar ? await untarFile(template.file) : template.file.path if (isTar && template.file.password) { await decryptFiles(tmpPath, template.file.password) } @@ -208,5 +209,9 @@ export async function importApp( } await updateAttachmentColumns(prodAppId, db) await updateAutomations(prodAppId, db) + // clear up afterward + if (tmpPath) { + fs.rmSync(tmpPath, { recursive: true, force: true }) + } return ok } diff --git a/packages/server/src/utilities/workerRequests.ts b/packages/server/src/utilities/workerRequests.ts index 1604a724d2..69ce58c8a9 100644 --- a/packages/server/src/utilities/workerRequests.ts +++ b/packages/server/src/utilities/workerRequests.ts @@ -1,4 +1,4 @@ -import fetch from "node-fetch" +import { Response, default as fetch } from "node-fetch" import env from "../environment" import { checkSlashesInUrl } from "./index" import { @@ -40,25 +40,21 @@ export function request(ctx?: Ctx, request?: any) { } async function checkResponse( - response: any, + response: Response, errorMsg: string, { ctx }: { ctx?: Ctx } = {} ) { - if (response.status !== 200) { - let error - try { - error = await response.json() - if (!error.message) { - error = JSON.stringify(error) - } - } catch (err) { - error = await response.text() + if (response.status >= 300) { + let responseErrorMessage + if (response.headers.get("content-type")?.includes("json")) { + const error = await response.json() + responseErrorMessage = error.message ?? JSON.stringify(error) + } else { + responseErrorMessage = await response.text() } - const msg = `Unable to ${errorMsg} - ${ - error.message ? error.message : error - }` + const msg = `Unable to ${errorMsg} - ${responseErrorMessage}` if (ctx) { - ctx.throw(400, msg) + ctx.throw(msg, response.status) } else { throw msg } diff --git a/packages/string-templates/manifest.json b/packages/string-templates/manifest.json index 9dd8260350..dce4af8665 100644 --- a/packages/string-templates/manifest.json +++ b/packages/string-templates/manifest.json @@ -6,7 +6,8 @@ ], "numArgs": 1, "example": "{{ abs 12012.1000 }} -> 12012.1", - "description": "

Return the magnitude of a.

\n" + "description": "

Return the magnitude of a.

\n", + "requiresBlock": false }, "add": { "args": [ @@ -15,7 +16,8 @@ ], "numArgs": 2, "example": "{{ add 1 2 }} -> 3", - "description": "

Return the sum of a plus b.

\n" + "description": "

Return the sum of a plus b.

\n", + "requiresBlock": false }, "avg": { "args": [ @@ -23,7 +25,8 @@ ], "numArgs": 1, "example": "{{ avg 1 2 3 4 5 }} -> 3", - "description": "

Returns the average of all numbers in the given array.

\n" + "description": "

Returns the average of all numbers in the given array.

\n", + "requiresBlock": false }, "ceil": { "args": [ @@ -31,7 +34,8 @@ ], "numArgs": 1, "example": "{{ ceil 1.2 }} -> 2", - "description": "

Get the Math.ceil() of the given value.

\n" + "description": "

Get the Math.ceil() of the given value.

\n", + "requiresBlock": false }, "divide": { "args": [ @@ -40,7 +44,8 @@ ], "numArgs": 2, "example": "{{ divide 10 5 }} -> 2", - "description": "

Divide a by b

\n" + "description": "

Divide a by b

\n", + "requiresBlock": false }, "floor": { "args": [ @@ -48,7 +53,8 @@ ], "numArgs": 1, "example": "{{ floor 1.2 }} -> 1", - "description": "

Get the Math.floor() of the given value.

\n" + "description": "

Get the Math.floor() of the given value.

\n", + "requiresBlock": false }, "minus": { "args": [ @@ -57,7 +63,8 @@ ], "numArgs": 2, "example": "{{ subtract 10 5 }} -> 5", - "description": "

Return the product of a minus b.

\n" + "description": "

Return the product of a minus b.

\n", + "requiresBlock": false }, "modulo": { "args": [ @@ -66,7 +73,8 @@ ], "numArgs": 2, "example": "{{ modulo 10 5 }} -> 0", - "description": "

Get the remainder of a division operation.

\n" + "description": "

Get the remainder of a division operation.

\n", + "requiresBlock": false }, "multiply": { "args": [ @@ -75,7 +83,8 @@ ], "numArgs": 2, "example": "{{ multiply 10 5 }} -> 50", - "description": "

Multiply number a by number b.

\n" + "description": "

Multiply number a by number b.

\n", + "requiresBlock": false }, "plus": { "args": [ @@ -84,7 +93,8 @@ ], "numArgs": 2, "example": "{{ plus 10 5 }} -> 15", - "description": "

Add a by b.

\n" + "description": "

Add a by b.

\n", + "requiresBlock": false }, "random": { "args": [ @@ -93,7 +103,8 @@ ], "numArgs": 2, "example": "{{ random 0 20 }} -> 10", - "description": "

Generate a random number between two values

\n" + "description": "

Generate a random number between two values

\n", + "requiresBlock": false }, "remainder": { "args": [ @@ -102,7 +113,8 @@ ], "numArgs": 2, "example": "{{ remainder 10 6 }} -> 4", - "description": "

Get the remainder when a is divided by b.

\n" + "description": "

Get the remainder when a is divided by b.

\n", + "requiresBlock": false }, "round": { "args": [ @@ -110,7 +122,8 @@ ], "numArgs": 1, "example": "{{ round 10.3 }} -> 10", - "description": "

Round the given number.

\n" + "description": "

Round the given number.

\n", + "requiresBlock": false }, "subtract": { "args": [ @@ -119,7 +132,8 @@ ], "numArgs": 2, "example": "{{ subtract 10 5 }} -> 5", - "description": "

Return the product of a minus b.

\n" + "description": "

Return the product of a minus b.

\n", + "requiresBlock": false }, "sum": { "args": [ @@ -127,7 +141,8 @@ ], "numArgs": 1, "example": "{{ sum [1, 2, 3] }} -> 6", - "description": "

Returns the sum of all numbers in the given array.

\n" + "description": "

Returns the sum of all numbers in the given array.

\n", + "requiresBlock": false } }, "array": { @@ -138,7 +153,8 @@ ], "numArgs": 2, "example": "{{ after ['a', 'b', 'c', 'd'] 2}} -> ['c', 'd']", - "description": "

Returns all of the items in an array after the specified index. Opposite of before.

\n" + "description": "

Returns all of the items in an array after the specified index. Opposite of before.

\n", + "requiresBlock": false }, "arrayify": { "args": [ @@ -146,7 +162,8 @@ ], "numArgs": 1, "example": "{{ arrayify 'foo' }} -> ['foo']", - "description": "

Cast the given value to an array.

\n" + "description": "

Cast the given value to an array.

\n", + "requiresBlock": false }, "before": { "args": [ @@ -155,7 +172,8 @@ ], "numArgs": 2, "example": "{{ before ['a', 'b', 'c', 'd'] 3}} -> ['a', 'b']", - "description": "

Return all of the items in the collection before the specified count. Opposite of after.

\n" + "description": "

Return all of the items in the collection before the specified count. Opposite of after.

\n", + "requiresBlock": false }, "eachIndex": { "args": [ @@ -163,8 +181,9 @@ "options" ], "numArgs": 2, - "example": "{{#eachIndex [1, 2, 3]}} {{item}} is {{index}} {{/eachIndex}}", - "description": "

Iterates the array, listing an item and the index of it.

\n" + "example": "{{#eachIndex [1, 2, 3]}} {{item}} is {{index}} {{/eachIndex}} -> ' 1 is 0 2 is 1 3 is 2 '", + "description": "

Iterates the array, listing an item and the index of it.

\n", + "requiresBlock": true }, "filter": { "args": [ @@ -173,8 +192,9 @@ "options" ], "numArgs": 3, - "example": "{{#filter [1, 2, 3] 2}}2 Found{{else}}2 not found{{/filter}}", - "description": "

Block helper that filters the given array and renders the block for values that evaluate to true, otherwise the inverse block is returned.

\n" + "example": "{{#filter [1, 2, 3] 2}}2 Found{{else}}2 not found{{/filter}} -> 2 Found", + "description": "

Block helper that filters the given array and renders the block for values that evaluate to true, otherwise the inverse block is returned.

\n", + "requiresBlock": true }, "first": { "args": [ @@ -183,15 +203,18 @@ ], "numArgs": 2, "example": "{{first [1, 2, 3, 4] 2}} -> 1,2", - "description": "

Returns the first item, or first n items of an array.

\n" + "description": "

Returns the first item, or first n items of an array.

\n", + "requiresBlock": false }, "forEach": { "args": [ - "array" + "array", + "options" ], - "numArgs": 1, - "example": "{{#forEach [{ 'name': 'John' }] }} {{ name }} {{/forEach}}", - "description": "

Iterates over each item in an array and exposes the current item in the array as context to the inner block. In addition to the current array item, the helper exposes the following variables to the inner block: - index - total - isFirst - isLast Also, @index is exposed as a private variable, and additional private variables may be defined as hash arguments.

\n" + "numArgs": 2, + "example": "{{#forEach [{ 'name': 'John' }] }} {{ name }} {{/forEach}} -> ' John '", + "description": "

Iterates over each item in an array and exposes the current item in the array as context to the inner block. In addition to the current array item, the helper exposes the following variables to the inner block: - index - total - isFirst - isLast Also, @index is exposed as a private variable, and additional private variables may be defined as hash arguments.

\n", + "requiresBlock": true }, "inArray": { "args": [ @@ -201,7 +224,8 @@ ], "numArgs": 3, "example": "{{#inArray [1, 2, 3] 2}} 2 exists {{else}} 2 does not exist {{/inArray}} -> ' 2 exists '", - "description": "

Block helper that renders the block if an array has the given value. Optionally specify an inverse block to render when the array does not have the given value.

\n" + "description": "

Block helper that renders the block if an array has the given value. Optionally specify an inverse block to render when the array does not have the given value.

\n", + "requiresBlock": true }, "isArray": { "args": [ @@ -209,7 +233,8 @@ ], "numArgs": 1, "example": "{{isArray [1, 2]}} -> true", - "description": "

Returns true if value is an es5 array.

\n" + "description": "

Returns true if value is an es5 array.

\n", + "requiresBlock": false }, "itemAt": { "args": [ @@ -218,7 +243,8 @@ ], "numArgs": 2, "example": "{{itemAt [1, 2, 3] 1}} -> 2", - "description": "

Returns the item from array at index idx.

\n" + "description": "

Returns the item from array at index idx.

\n", + "requiresBlock": false }, "join": { "args": [ @@ -227,17 +253,18 @@ ], "numArgs": 2, "example": "{{join [1, 2, 3]}} -> 1, 2, 3", - "description": "

Join all elements of array into a string, optionally using a given separator.

\n" + "description": "

Join all elements of array into a string, optionally using a given separator.

\n", + "requiresBlock": false }, "equalsLength": { "args": [ "value", - "length", - "options" + "length" ], - "numArgs": 3, + "numArgs": 2, "example": "{{equalsLength [1, 2, 3] 3}} -> true", - "description": "

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

\n" + "description": "

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

\n", + "requiresBlock": false }, "last": { "args": [ @@ -246,7 +273,8 @@ ], "numArgs": 2, "example": "{{last [1, 2, 3]}} -> 3", - "description": "

Returns the last item, or last n items of an array or string. Opposite of first.

\n" + "description": "

Returns the last item, or last n items of an array or string. Opposite of first.

\n", + "requiresBlock": false }, "length": { "args": [ @@ -254,17 +282,18 @@ ], "numArgs": 1, "example": "{{length [1, 2, 3]}} -> 3", - "description": "

Returns the length of the given string or array.

\n" + "description": "

Returns the length of the given string or array.

\n", + "requiresBlock": false }, "lengthEqual": { "args": [ "value", - "length", - "options" + "length" ], - "numArgs": 3, + "numArgs": 2, "example": "{{equalsLength [1, 2, 3] 3}} -> true", - "description": "

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

\n" + "description": "

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

\n", + "requiresBlock": false }, "map": { "args": [ @@ -273,7 +302,8 @@ ], "numArgs": 2, "example": "{{map [1, 2, 3] double}} -> [2, 4, 6]", - "description": "

Returns a new array, created by calling function on each element of the given array. For example,

\n" + "description": "

Returns a new array, created by calling function on each element of the given array. For example,

\n", + "requiresBlock": false }, "pluck": { "args": [ @@ -282,7 +312,8 @@ ], "numArgs": 2, "example": "{{pluck [{ 'name': 'Bob' }] 'name' }} -> ['Bob']", - "description": "

Map over the given object or array or objects and create an array of values from the given prop. Dot-notation may be used (as a string) to get nested properties.

\n" + "description": "

Map over the given object or array or objects and create an array of values from the given prop. Dot-notation may be used (as a string) to get nested properties.

\n", + "requiresBlock": false }, "reverse": { "args": [ @@ -290,7 +321,8 @@ ], "numArgs": 1, "example": "{{reverse [1, 2, 3]}} -> [3, 2, 1]", - "description": "

Reverse the elements in an array, or the characters in a string.

\n" + "description": "

Reverse the elements in an array, or the characters in a string.

\n", + "requiresBlock": false }, "some": { "args": [ @@ -300,7 +332,8 @@ ], "numArgs": 3, "example": "{{#some [1, \"b\", 3] isString}} string found {{else}} No string found {{/some}} -> ' string found '", - "description": "

Block helper that returns the block if the callback returns true for some value in the given array.

\n" + "description": "

Block helper that returns the block if the callback returns true for some value in the given array.

\n", + "requiresBlock": true }, "sort": { "args": [ @@ -309,7 +342,8 @@ ], "numArgs": 2, "example": "{{ sort ['b', 'a', 'c'] }} -> ['a', 'b', 'c']", - "description": "

Sort the given array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

\n" + "description": "

Sort the given array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

\n", + "requiresBlock": false }, "sortBy": { "args": [ @@ -318,7 +352,8 @@ ], "numArgs": 2, "example": "{{ sortBy [{'a': 'zzz'}, {'a': 'aaa'}] 'a' }} -> [{'a':'aaa'},{'a':'zzz'}]", - "description": "

Sort an array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

\n" + "description": "

Sort an array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

\n", + "requiresBlock": false }, "withAfter": { "args": [ @@ -327,8 +362,9 @@ "options" ], "numArgs": 3, - "example": "{{ withAfter [1, 2, 3] 1 }} {{this}} {{/withAfter}}", - "description": "

Use the items in the array after the specified index as context inside a block. Opposite of withBefore.

\n" + "example": "{{#withAfter [1, 2, 3] 1 }} {{this}} {{/withAfter}} -> ' 2 3 '", + "description": "

Use the items in the array after the specified index as context inside a block. Opposite of withBefore.

\n", + "requiresBlock": true }, "withBefore": { "args": [ @@ -337,8 +373,9 @@ "options" ], "numArgs": 3, - "example": "{{ withBefore [1, 2, 3] 2 }} {{this}} {{/withBefore}}", - "description": "

Use the items in the array before the specified index as context inside a block. Opposite of withAfter.

\n" + "example": "{{#withBefore [1, 2, 3] 2 }} {{this}} {{/withBefore}} -> ' 1 '", + "description": "

Use the items in the array before the specified index as context inside a block. Opposite of withAfter.

\n", + "requiresBlock": true }, "withFirst": { "args": [ @@ -348,7 +385,8 @@ ], "numArgs": 3, "example": "{{#withFirst [1, 2, 3] }}{{this}}{{/withFirst}} -> 1", - "description": "

Use the first item in a collection inside a handlebars block expression. Opposite of withLast.

\n" + "description": "

Use the first item in a collection inside a handlebars block expression. Opposite of withLast.

\n", + "requiresBlock": true }, "withGroup": { "args": [ @@ -358,7 +396,8 @@ ], "numArgs": 3, "example": "{{#withGroup [1, 2, 3, 4] 2}}{{#each this}}{{.}}{{/each}}
{{/withGroup}} -> 12
34
", - "description": "

Block helper that groups array elements by given group size.

\n" + "description": "

Block helper that groups array elements by given group size.

\n", + "requiresBlock": true }, "withLast": { "args": [ @@ -368,7 +407,8 @@ ], "numArgs": 3, "example": "{{#withLast [1, 2, 3, 4]}}{{this}}{{/withLast}} -> 4", - "description": "

Use the last item or n items in an array as context inside a block. Opposite of withFirst.

\n" + "description": "

Use the last item or n items in an array as context inside a block. Opposite of withFirst.

\n", + "requiresBlock": true }, "withSort": { "args": [ @@ -378,7 +418,8 @@ ], "numArgs": 3, "example": "{{#withSort ['b', 'a', 'c']}}{{this}}{{/withSort}} -> abc", - "description": "

Block helper that sorts a collection and exposes the sorted collection as context inside the block.

\n" + "description": "

Block helper that sorts a collection and exposes the sorted collection as context inside the block.

\n", + "requiresBlock": true }, "unique": { "args": [ @@ -387,7 +428,8 @@ ], "numArgs": 2, "example": "{{#each (unique ['a', 'a', 'c', 'b', 'e', 'e']) }}{{.}}{{/each}} -> acbe", - "description": "

Block helper that return an array with all duplicate values removed. Best used along with a each helper.

\n" + "description": "

Block helper that return an array with all duplicate values removed. Best used along with a each helper.

\n", + "requiresBlock": true } }, "number": { @@ -397,7 +439,8 @@ ], "numArgs": 1, "example": "{{ bytes 1386 1 }} -> 1.4 kB", - "description": "

Format a number to it's equivalent in bytes. If a string is passed, it's length will be formatted and returned. Examples: - 'foo' => 3 B - 13661855 => 13.66 MB - 825399 => 825.39 kB - 1396 => 1.4 kB

\n" + "description": "

Format a number to it's equivalent in bytes. If a string is passed, it's length will be formatted and returned. Examples: - 'foo' => 3 B - 13661855 => 13.66 MB - 825399 => 825.39 kB - 1396 => 1.4 kB

\n", + "requiresBlock": false }, "addCommas": { "args": [ @@ -405,7 +448,8 @@ ], "numArgs": 1, "example": "{{ addCommas 1000000 }} -> 1,000,000", - "description": "

Add commas to numbers

\n" + "description": "

Add commas to numbers

\n", + "requiresBlock": false }, "phoneNumber": { "args": [ @@ -413,7 +457,8 @@ ], "numArgs": 1, "example": "{{ phoneNumber 8005551212 }} -> (800) 555-1212", - "description": "

Convert a string or number to a formatted phone number.

\n" + "description": "

Convert a string or number to a formatted phone number.

\n", + "requiresBlock": false }, "toAbbr": { "args": [ @@ -422,7 +467,8 @@ ], "numArgs": 2, "example": "{{ toAbbr 10123 2 }} -> 10.12k", - "description": "

Abbreviate numbers to the given number of precision. This for general numbers, not size in bytes.

\n" + "description": "

Abbreviate numbers to the given number of precision. This for general numbers, not size in bytes.

\n", + "requiresBlock": false }, "toExponential": { "args": [ @@ -431,7 +477,8 @@ ], "numArgs": 2, "example": "{{ toExponential 10123 2 }} -> 1.01e+4", - "description": "

Returns a string representing the given number in exponential notation.

\n" + "description": "

Returns a string representing the given number in exponential notation.

\n", + "requiresBlock": false }, "toFixed": { "args": [ @@ -440,21 +487,24 @@ ], "numArgs": 2, "example": "{{ toFixed 1.1234 2 }} -> 1.12", - "description": "

Formats the given number using fixed-point notation.

\n" + "description": "

Formats the given number using fixed-point notation.

\n", + "requiresBlock": false }, "toFloat": { "args": [ "number" ], "numArgs": 1, - "description": "

Convert input to a float.

\n" + "description": "

Convert input to a float.

\n", + "requiresBlock": false }, "toInt": { "args": [ "number" ], "numArgs": 1, - "description": "

Convert input to an integer.

\n" + "description": "

Convert input to an integer.

\n", + "requiresBlock": false }, "toPrecision": { "args": [ @@ -462,8 +512,9 @@ "precision" ], "numArgs": 2, - "example": "{{toPrecision '1.1234' 2}}", - "description": "

Returns a string representing the Number object to the specified precision.

\n" + "example": "{{toPrecision '1.1234' 2}} -> 1.1", + "description": "

Returns a string representing the Number object to the specified precision.

\n", + "requiresBlock": false } }, "url": { @@ -473,7 +524,8 @@ ], "numArgs": 1, "example": "{{ encodeURI 'https://myurl?Hello There' }} -> https%3A%2F%2Fmyurl%3FHello%20There", - "description": "

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.

\n" + "description": "

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.

\n", + "requiresBlock": false }, "escape": { "args": [ @@ -481,7 +533,8 @@ ], "numArgs": 1, "example": "{{ escape 'https://myurl?Hello+There' }} -> https%3A%2F%2Fmyurl%3FHello%2BThere", - "description": "

Escape the given string by replacing characters with escape sequences. Useful for allowing the string to be used in a URL, etc.

\n" + "description": "

Escape the given string by replacing characters with escape sequences. Useful for allowing the string to be used in a URL, etc.

\n", + "requiresBlock": false }, "decodeURI": { "args": [ @@ -489,7 +542,8 @@ ], "numArgs": 1, "example": "{{ decodeURI 'https://myurl?Hello%20There' }} -> https://myurl?Hello There", - "description": "

Decode a Uniform Resource Identifier (URI) component.

\n" + "description": "

Decode a Uniform Resource Identifier (URI) component.

\n", + "requiresBlock": false }, "urlResolve": { "args": [ @@ -498,7 +552,8 @@ ], "numArgs": 2, "example": "{{ urlResolve 'https://myurl' '/api/test' }} -> https://myurl/api/test", - "description": "

Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

\n" + "description": "

Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

\n", + "requiresBlock": false }, "urlParse": { "args": [ @@ -506,7 +561,8 @@ ], "numArgs": 1, "example": "{{ urlParse 'https://myurl/api/test' }}", - "description": "

Parses a url string into an object.

\n" + "description": "

Parses a url string into an object.

\n", + "requiresBlock": false }, "stripQuerystring": { "args": [ @@ -514,7 +570,8 @@ ], "numArgs": 1, "example": "{{ stripQuerystring 'https://myurl/api/test?foo=bar' }} -> 'https://myurl/api/test'", - "description": "

Strip the query string from the given url.

\n" + "description": "

Strip the query string from the given url.

\n", + "requiresBlock": false }, "stripProtocol": { "args": [ @@ -522,7 +579,8 @@ ], "numArgs": 1, "example": "{{ stripProtocol 'https://myurl/api/test' }} -> '//myurl/api/test'", - "description": "

Strip protocol from a url. Useful for displaying media that may have an 'http' protocol on secure connections.

\n" + "description": "

Strip protocol from a url. Useful for displaying media that may have an 'http' protocol on secure connections.

\n", + "requiresBlock": false } }, "string": { @@ -533,7 +591,8 @@ ], "numArgs": 2, "example": "{{append 'index' '.html'}} -> index.html", - "description": "

Append the specified suffix to the given string.

\n" + "description": "

Append the specified suffix to the given string.

\n", + "requiresBlock": false }, "camelcase": { "args": [ @@ -541,7 +600,8 @@ ], "numArgs": 1, "example": "{{camelcase 'foo bar baz'}} -> fooBarBaz", - "description": "

camelCase the characters in the given string.

\n" + "description": "

camelCase the characters in the given string.

\n", + "requiresBlock": false }, "capitalize": { "args": [ @@ -549,7 +609,8 @@ ], "numArgs": 1, "example": "{{capitalize 'foo bar baz'}} -> Foo bar baz", - "description": "

Capitalize the first word in a sentence.

\n" + "description": "

Capitalize the first word in a sentence.

\n", + "requiresBlock": false }, "capitalizeAll": { "args": [ @@ -557,7 +618,8 @@ ], "numArgs": 1, "example": "{{ capitalizeAll 'foo bar baz'}} -> Foo Bar Baz", - "description": "

Capitalize all words in a string.

\n" + "description": "

Capitalize all words in a string.

\n", + "requiresBlock": false }, "center": { "args": [ @@ -566,7 +628,8 @@ ], "numArgs": 2, "example": "{{ center 'test' 1}} -> ' test '", - "description": "

Center a string using non-breaking spaces

\n" + "description": "

Center a string using non-breaking spaces

\n", + "requiresBlock": false }, "chop": { "args": [ @@ -574,7 +637,8 @@ ], "numArgs": 1, "example": "{{ chop ' ABC '}} -> ABC", - "description": "

Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.

\n" + "description": "

Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.

\n", + "requiresBlock": false }, "dashcase": { "args": [ @@ -582,7 +646,8 @@ ], "numArgs": 1, "example": "{{dashcase 'a-b-c d_e'}} -> a-b-c-d-e", - "description": "

dash-case the characters in string. Replaces non-word characters and periods with hyphens.

\n" + "description": "

dash-case the characters in string. Replaces non-word characters and periods with hyphens.

\n", + "requiresBlock": false }, "dotcase": { "args": [ @@ -590,7 +655,8 @@ ], "numArgs": 1, "example": "{{dotcase 'a-b-c d_e'}} -> a.b.c.d.e", - "description": "

dot.case the characters in string.

\n" + "description": "

dot.case the characters in string.

\n", + "requiresBlock": false }, "downcase": { "args": [ @@ -598,7 +664,8 @@ ], "numArgs": 1, "example": "{{downcase 'aBcDeF'}} -> abcdef", - "description": "

Lowercase all of the characters in the given string. Alias for lowercase.

\n" + "description": "

Lowercase all of the characters in the given string. Alias for lowercase.

\n", + "requiresBlock": false }, "ellipsis": { "args": [ @@ -607,7 +674,8 @@ ], "numArgs": 2, "example": "{{ellipsis 'foo bar baz' 7}} -> foo bar…", - "description": "

Truncates a string to the specified length, and appends it with an elipsis, .

\n" + "description": "

Truncates a string to the specified length, and appends it with an elipsis, .

\n", + "requiresBlock": false }, "hyphenate": { "args": [ @@ -615,7 +683,8 @@ ], "numArgs": 1, "example": "{{hyphenate 'foo bar baz qux'}} -> foo-bar-baz-qux", - "description": "

Replace spaces in a string with hyphens.

\n" + "description": "

Replace spaces in a string with hyphens.

\n", + "requiresBlock": false }, "isString": { "args": [ @@ -623,7 +692,8 @@ ], "numArgs": 1, "example": "{{isString 'foo'}} -> true", - "description": "

Return true if value is a string.

\n" + "description": "

Return true if value is a string.

\n", + "requiresBlock": false }, "lowercase": { "args": [ @@ -631,7 +701,8 @@ ], "numArgs": 1, "example": "{{lowercase 'Foo BAR baZ'}} -> foo bar baz", - "description": "

Lowercase all characters in the given string.

\n" + "description": "

Lowercase all characters in the given string.

\n", + "requiresBlock": false }, "occurrences": { "args": [ @@ -640,7 +711,8 @@ ], "numArgs": 2, "example": "{{occurrences 'foo bar foo bar baz' 'foo'}} -> 2", - "description": "

Return the number of occurrences of substring within the given string.

\n" + "description": "

Return the number of occurrences of substring within the given string.

\n", + "requiresBlock": false }, "pascalcase": { "args": [ @@ -648,7 +720,8 @@ ], "numArgs": 1, "example": "{{pascalcase 'foo bar baz'}} -> FooBarBaz", - "description": "

PascalCase the characters in string.

\n" + "description": "

PascalCase the characters in string.

\n", + "requiresBlock": false }, "pathcase": { "args": [ @@ -656,7 +729,8 @@ ], "numArgs": 1, "example": "{{pathcase 'a-b-c d_e'}} -> a/b/c/d/e", - "description": "

path/case the characters in string.

\n" + "description": "

path/case the characters in string.

\n", + "requiresBlock": false }, "plusify": { "args": [ @@ -664,7 +738,8 @@ ], "numArgs": 1, "example": "{{plusify 'foo bar baz'}} -> foo+bar+baz", - "description": "

Replace spaces in the given string with pluses.

\n" + "description": "

Replace spaces in the given string with pluses.

\n", + "requiresBlock": false }, "prepend": { "args": [ @@ -673,7 +748,8 @@ ], "numArgs": 2, "example": "{{prepend 'bar' 'foo-'}} -> foo-bar", - "description": "

Prepends the given string with the specified prefix.

\n" + "description": "

Prepends the given string with the specified prefix.

\n", + "requiresBlock": false }, "remove": { "args": [ @@ -682,7 +758,8 @@ ], "numArgs": 2, "example": "{{remove 'a b a b a b' 'a '}} -> b b b", - "description": "

Remove all occurrences of substring from the given str.

\n" + "description": "

Remove all occurrences of substring from the given str.

\n", + "requiresBlock": false }, "removeFirst": { "args": [ @@ -691,7 +768,8 @@ ], "numArgs": 2, "example": "{{removeFirst 'a b a b a b' 'a'}} -> ' b a b a b'", - "description": "

Remove the first occurrence of substring from the given str.

\n" + "description": "

Remove the first occurrence of substring from the given str.

\n", + "requiresBlock": false }, "replace": { "args": [ @@ -701,7 +779,8 @@ ], "numArgs": 3, "example": "{{replace 'a b a b a b' 'a' 'z'}} -> z b z b z b", - "description": "

Replace all occurrences of substring a with substring b.

\n" + "description": "

Replace all occurrences of substring a with substring b.

\n", + "requiresBlock": false }, "replaceFirst": { "args": [ @@ -711,7 +790,8 @@ ], "numArgs": 3, "example": "{{replaceFirst 'a b a b a b' 'a' 'z'}} -> z b a b a b", - "description": "

Replace the first occurrence of substring a with substring b.

\n" + "description": "

Replace the first occurrence of substring a with substring b.

\n", + "requiresBlock": false }, "sentence": { "args": [ @@ -719,7 +799,8 @@ ], "numArgs": 1, "example": "{{sentence 'hello world. goodbye world.'}} -> Hello world. Goodbye world.", - "description": "

Sentence case the given string

\n" + "description": "

Sentence case the given string

\n", + "requiresBlock": false }, "snakecase": { "args": [ @@ -727,7 +808,8 @@ ], "numArgs": 1, "example": "{{snakecase 'a-b-c d_e'}} -> a_b_c_d_e", - "description": "

snake_case the characters in the given string.

\n" + "description": "

snake_case the characters in the given string.

\n", + "requiresBlock": false }, "split": { "args": [ @@ -735,7 +817,8 @@ ], "numArgs": 1, "example": "{{split 'a,b,c'}} -> ['a', 'b', 'c']", - "description": "

Split string by the given character.

\n" + "description": "

Split string by the given character.

\n", + "requiresBlock": false }, "startsWith": { "args": [ @@ -745,7 +828,8 @@ ], "numArgs": 3, "example": "{{#startsWith 'Goodbye' 'Hello, world!'}}Yep{{else}}Nope{{/startsWith}} -> Nope", - "description": "

Tests whether a string begins with the given prefix.

\n" + "description": "

Tests whether a string begins with the given prefix.

\n", + "requiresBlock": true }, "titleize": { "args": [ @@ -753,7 +837,8 @@ ], "numArgs": 1, "example": "{{titleize 'this is title case' }} -> This Is Title Case", - "description": "

Title case the given string.

\n" + "description": "

Title case the given string.

\n", + "requiresBlock": false }, "trim": { "args": [ @@ -761,7 +846,8 @@ ], "numArgs": 1, "example": "{{trim ' ABC ' }} -> ABC", - "description": "

Removes extraneous whitespace from the beginning and end of a string.

\n" + "description": "

Removes extraneous whitespace from the beginning and end of a string.

\n", + "requiresBlock": false }, "trimLeft": { "args": [ @@ -769,7 +855,8 @@ ], "numArgs": 1, "example": "{{trimLeft ' ABC ' }} -> 'ABC '", - "description": "

Removes extraneous whitespace from the beginning of a string.

\n" + "description": "

Removes extraneous whitespace from the beginning of a string.

\n", + "requiresBlock": false }, "trimRight": { "args": [ @@ -777,7 +864,8 @@ ], "numArgs": 1, "example": "{{trimRight ' ABC ' }} -> ' ABC'", - "description": "

Removes extraneous whitespace from the end of a string.

\n" + "description": "

Removes extraneous whitespace from the end of a string.

\n", + "requiresBlock": false }, "truncate": { "args": [ @@ -787,7 +875,8 @@ ], "numArgs": 3, "example": "{{truncate 'foo bar baz' 7 }} -> foo bar", - "description": "

Truncate a string to the specified length. Also see ellipsis.

\n" + "description": "

Truncate a string to the specified length. Also see ellipsis.

\n", + "requiresBlock": false }, "truncateWords": { "args": [ @@ -797,7 +886,8 @@ ], "numArgs": 3, "example": "{{truncateWords 'foo bar baz' 1 }} -> foo…", - "description": "

Truncate a string to have the specified number of words. Also see truncate.

\n" + "description": "

Truncate a string to have the specified number of words. Also see truncate.

\n", + "requiresBlock": false }, "upcase": { "args": [ @@ -805,7 +895,8 @@ ], "numArgs": 1, "example": "{{upcase 'aBcDef'}} -> ABCDEF", - "description": "

Uppercase all of the characters in the given string. Alias for uppercase.

\n" + "description": "

Uppercase all of the characters in the given string. Alias for uppercase.

\n", + "requiresBlock": false }, "uppercase": { "args": [ @@ -814,7 +905,8 @@ ], "numArgs": 2, "example": "{{uppercase 'aBcDef'}} -> ABCDEF", - "description": "

Uppercase all of the characters in the given string. If used as a block helper it will uppercase the entire block. This helper does not support inverse blocks.

\n" + "description": "

Uppercase all of the characters in the given string. If used as a block helper it will uppercase the entire block. This helper does not support inverse blocks.

\n", + "requiresBlock": false } }, "comparison": { @@ -825,8 +917,9 @@ "options" ], "numArgs": 3, - "example": "{{#and great magnificent}}both{{else}}no{{/and}}", - "description": "

Helper that renders the block if both of the given values are truthy. If an inverse block is specified it will be rendered when falsy. Works as a block helper, inline helper or subexpression.

\n" + "example": "{{#and great magnificent}}both{{else}}no{{/and}} -> no", + "description": "

Helper that renders the block if both of the given values are truthy. If an inverse block is specified it will be rendered when falsy. Works as a block helper, inline helper or subexpression.

\n", + "requiresBlock": true }, "compare": { "args": [ @@ -837,7 +930,8 @@ ], "numArgs": 4, "example": "{{compare 10 '<' 5 }} -> false", - "description": "

Render a block when a comparison of the first and third arguments returns true. The second argument is the [arithemetic operator][operators] to use. You may also optionally specify an inverse block to render when falsy.

\n" + "description": "

Render a block when a comparison of the first and third arguments returns true. The second argument is the [arithemetic operator][operators] to use. You may also optionally specify an inverse block to render when falsy.

\n", + "requiresBlock": false }, "contains": { "args": [ @@ -847,8 +941,9 @@ "options" ], "numArgs": 4, - "example": "{{#contains ['a', 'b', 'c'] 'd'}} This will not be rendered. {{else}} This will be rendered. {{/contains}}", - "description": "

Block helper that renders the block if collection has the given value, using strict equality (===) for comparison, otherwise the inverse block is rendered (if specified). If a startIndex is specified and is negative, it is used as the offset from the end of the collection.

\n" + "example": "{{#contains ['a', 'b', 'c'] 'd'}} This will not be rendered. {{else}} This will be rendered. {{/contains}} -> ' This will be rendered. '", + "description": "

Block helper that renders the block if collection has the given value, using strict equality (===) for comparison, otherwise the inverse block is rendered (if specified). If a startIndex is specified and is negative, it is used as the offset from the end of the collection.

\n", + "requiresBlock": true }, "default": { "args": [ @@ -857,7 +952,8 @@ ], "numArgs": 2, "example": "{{default null null 'default'}} -> default", - "description": "

Returns the first value that is not undefined, otherwise the 'default' value is returned.

\n" + "description": "

Returns the first value that is not undefined, otherwise the 'default' value is returned.

\n", + "requiresBlock": false }, "eq": { "args": [ @@ -867,7 +963,8 @@ ], "numArgs": 3, "example": "{{#eq 3 3}}equal{{else}}not equal{{/eq}} -> equal", - "description": "

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n" + "description": "

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n", + "requiresBlock": true }, "gt": { "args": [ @@ -877,7 +974,8 @@ ], "numArgs": 3, "example": "{{#gt 4 3}} greater than{{else}} not greater than{{/gt}} -> ' greater than'", - "description": "

Block helper that renders a block if a is greater than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n" + "description": "

Block helper that renders a block if a is greater than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n", + "requiresBlock": true }, "gte": { "args": [ @@ -887,7 +985,8 @@ ], "numArgs": 3, "example": "{{#gte 4 3}} greater than or equal{{else}} not greater than{{/gte}} -> ' greater than or equal'", - "description": "

Block helper that renders a block if a is greater than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n" + "description": "

Block helper that renders a block if a is greater than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n", + "requiresBlock": true }, "has": { "args": [ @@ -897,7 +996,8 @@ ], "numArgs": 3, "example": "{{#has 'foobar' 'foo'}}has it{{else}}doesn't{{/has}} -> has it", - "description": "

Block helper that renders a block if value has pattern. If an inverse block is specified it will be rendered when falsy.

\n" + "description": "

Block helper that renders a block if value has pattern. If an inverse block is specified it will be rendered when falsy.

\n", + "requiresBlock": true }, "isFalsey": { "args": [ @@ -906,7 +1006,8 @@ ], "numArgs": 2, "example": "{{isFalsey '' }} -> true", - "description": "

Returns true if the given value is falsey. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

\n" + "description": "

Returns true if the given value is falsey. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

\n", + "requiresBlock": false }, "isTruthy": { "args": [ @@ -915,7 +1016,8 @@ ], "numArgs": 2, "example": "{{isTruthy '12' }} -> true", - "description": "

Returns true if the given value is truthy. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

\n" + "description": "

Returns true if the given value is truthy. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

\n", + "requiresBlock": false }, "ifEven": { "args": [ @@ -924,7 +1026,8 @@ ], "numArgs": 2, "example": "{{#ifEven 2}} even {{else}} odd {{/ifEven}} -> ' even '", - "description": "

Return true if the given value is an even number.

\n" + "description": "

Return true if the given value is an even number.

\n", + "requiresBlock": true }, "ifNth": { "args": [ @@ -934,7 +1037,8 @@ ], "numArgs": 3, "example": "{{#ifNth 2 10}}remainder{{else}}no remainder{{/ifNth}} -> remainder", - "description": "

Conditionally renders a block if the remainder is zero when b operand is divided by a. If an inverse block is specified it will be rendered when the remainder is not zero.

\n" + "description": "

Conditionally renders a block if the remainder is zero when b operand is divided by a. If an inverse block is specified it will be rendered when the remainder is not zero.

\n", + "requiresBlock": true }, "ifOdd": { "args": [ @@ -943,7 +1047,8 @@ ], "numArgs": 2, "example": "{{#ifOdd 3}}odd{{else}}even{{/ifOdd}} -> odd", - "description": "

Block helper that renders a block if value is an odd number. If an inverse block is specified it will be rendered when falsy.

\n" + "description": "

Block helper that renders a block if value is an odd number. If an inverse block is specified it will be rendered when falsy.

\n", + "requiresBlock": true }, "is": { "args": [ @@ -953,7 +1058,8 @@ ], "numArgs": 3, "example": "{{#is 3 3}} is {{else}} is not {{/is}} -> ' is '", - "description": "

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. Similar to eq but does not do strict equality.

\n" + "description": "

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. Similar to eq but does not do strict equality.

\n", + "requiresBlock": true }, "isnt": { "args": [ @@ -963,7 +1069,8 @@ ], "numArgs": 3, "example": "{{#isnt 3 3}} isnt {{else}} is {{/isnt}} -> ' is '", - "description": "

Block helper that renders a block if a is not equal to b. If an inverse block is specified it will be rendered when falsy. Similar to unlessEq but does not use strict equality for comparisons.

\n" + "description": "

Block helper that renders a block if a is not equal to b. If an inverse block is specified it will be rendered when falsy. Similar to unlessEq but does not use strict equality for comparisons.

\n", + "requiresBlock": true }, "lt": { "args": [ @@ -972,7 +1079,8 @@ ], "numArgs": 2, "example": "{{#lt 2 3}} less than {{else}} more than or equal {{/lt}} -> ' less than '", - "description": "

Block helper that renders a block if a is less than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n" + "description": "

Block helper that renders a block if a is less than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n", + "requiresBlock": true }, "lte": { "args": [ @@ -982,7 +1090,8 @@ ], "numArgs": 3, "example": "{{#lte 2 3}} less than or equal {{else}} more than {{/lte}} -> ' less than or equal '", - "description": "

Block helper that renders a block if a is less than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n" + "description": "

Block helper that renders a block if a is less than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

\n", + "requiresBlock": true }, "neither": { "args": [ @@ -992,7 +1101,8 @@ ], "numArgs": 3, "example": "{{#neither null null}}both falsey{{else}}both not falsey{{/neither}} -> both falsey", - "description": "

Block helper that renders a block if neither of the given values are truthy. If an inverse block is specified it will be rendered when falsy.

\n" + "description": "

Block helper that renders a block if neither of the given values are truthy. If an inverse block is specified it will be rendered when falsy.

\n", + "requiresBlock": true }, "not": { "args": [ @@ -1001,7 +1111,8 @@ ], "numArgs": 2, "example": "{{#not undefined }}falsey{{else}}not falsey{{/not}} -> falsey", - "description": "

Returns true if val is falsey. Works as a block or inline helper.

\n" + "description": "

Returns true if val is falsey. Works as a block or inline helper.

\n", + "requiresBlock": true }, "or": { "args": [ @@ -1010,7 +1121,8 @@ ], "numArgs": 2, "example": "{{#or 1 2 undefined }} at least one truthy {{else}} all falsey {{/or}} -> ' at least one truthy '", - "description": "

Block helper that renders a block if any of the given values is truthy. If an inverse block is specified it will be rendered when falsy.

\n" + "description": "

Block helper that renders a block if any of the given values is truthy. If an inverse block is specified it will be rendered when falsy.

\n", + "requiresBlock": true }, "unlessEq": { "args": [ @@ -1020,7 +1132,8 @@ ], "numArgs": 3, "example": "{{#unlessEq 2 1 }} not equal {{else}} equal {{/unlessEq}} -> ' not equal '", - "description": "

Block helper that always renders the inverse block unless a is equal to b.

\n" + "description": "

Block helper that always renders the inverse block unless a is equal to b.

\n", + "requiresBlock": true }, "unlessGt": { "args": [ @@ -1030,7 +1143,8 @@ ], "numArgs": 3, "example": "{{#unlessGt 20 1 }} not greater than {{else}} greater than {{/unlessGt}} -> ' greater than '", - "description": "

Block helper that always renders the inverse block unless a is greater than b.

\n" + "description": "

Block helper that always renders the inverse block unless a is greater than b.

\n", + "requiresBlock": true }, "unlessLt": { "args": [ @@ -1040,7 +1154,8 @@ ], "numArgs": 3, "example": "{{#unlessLt 20 1 }}greater than or equal{{else}}less than{{/unlessLt}} -> greater than or equal", - "description": "

Block helper that always renders the inverse block unless a is less than b.

\n" + "description": "

Block helper that always renders the inverse block unless a is less than b.

\n", + "requiresBlock": true }, "unlessGteq": { "args": [ @@ -1050,7 +1165,8 @@ ], "numArgs": 3, "example": "{{#unlessGteq 20 1 }} less than {{else}}greater than or equal to{{/unlessGteq}} -> greater than or equal to", - "description": "

Block helper that always renders the inverse block unless a is greater than or equal to b.

\n" + "description": "

Block helper that always renders the inverse block unless a is greater than or equal to b.

\n", + "requiresBlock": true }, "unlessLteq": { "args": [ @@ -1060,7 +1176,8 @@ ], "numArgs": 3, "example": "{{#unlessLteq 20 1 }} greater than {{else}} less than or equal to {{/unlessLteq}} -> ' greater than '", - "description": "

Block helper that always renders the inverse block unless a is less than or equal to b.

\n" + "description": "

Block helper that always renders the inverse block unless a is less than or equal to b.

\n", + "requiresBlock": true } }, "object": { @@ -1069,7 +1186,8 @@ "objects" ], "numArgs": 1, - "description": "

Extend the context with the properties of other objects. A shallow merge is performed to avoid mutating the context.

\n" + "description": "

Extend the context with the properties of other objects. A shallow merge is performed to avoid mutating the context.

\n", + "requiresBlock": false }, "forIn": { "args": [ @@ -1077,7 +1195,8 @@ "options" ], "numArgs": 2, - "description": "

Block helper that iterates over the properties of an object, exposing each key and value on the context.

\n" + "description": "

Block helper that iterates over the properties of an object, exposing each key and value on the context.

\n", + "requiresBlock": true }, "forOwn": { "args": [ @@ -1085,14 +1204,16 @@ "options" ], "numArgs": 2, - "description": "

Block helper that iterates over the own properties of an object, exposing each key and value on the context.

\n" + "description": "

Block helper that iterates over the own properties of an object, exposing each key and value on the context.

\n", + "requiresBlock": true }, "toPath": { "args": [ "prop" ], "numArgs": 1, - "description": "

Take arguments and, if they are string or number, convert them to a dot-delineated object property path.

\n" + "description": "

Take arguments and, if they are string or number, convert them to a dot-delineated object property path.

\n", + "requiresBlock": false }, "get": { "args": [ @@ -1101,7 +1222,8 @@ "options" ], "numArgs": 3, - "description": "

Use property paths (a.b.c) to get a value or nested value from the context. Works as a regular helper or block helper.

\n" + "description": "

Use property paths (a.b.c) to get a value or nested value from the context. Works as a regular helper or block helper.

\n", + "requiresBlock": true }, "getObject": { "args": [ @@ -1109,7 +1231,8 @@ "context" ], "numArgs": 2, - "description": "

Use property paths (a.b.c) to get an object from the context. Differs from the get helper in that this helper will return the actual object, including the given property key. Also, this helper does not work as a block helper.

\n" + "description": "

Use property paths (a.b.c) to get an object from the context. Differs from the get helper in that this helper will return the actual object, including the given property key. Also, this helper does not work as a block helper.

\n", + "requiresBlock": false }, "hasOwn": { "args": [ @@ -1117,28 +1240,32 @@ "context" ], "numArgs": 2, - "description": "

Return true if key is an own, enumerable property of the given context object.

\n" + "description": "

Return true if key is an own, enumerable property of the given context object.

\n", + "requiresBlock": false }, "isObject": { "args": [ "value" ], "numArgs": 1, - "description": "

Return true if value is an object.

\n" + "description": "

Return true if value is an object.

\n", + "requiresBlock": false }, "JSONparse": { "args": [ "string" ], "numArgs": 1, - "description": "

Parses the given string using JSON.parse.

\n" + "description": "

Parses the given string using JSON.parse.

\n", + "requiresBlock": true }, "JSONstringify": { "args": [ "obj" ], "numArgs": 1, - "description": "

Stringify an object using JSON.stringify.

\n" + "description": "

Stringify an object using JSON.stringify.

\n", + "requiresBlock": false }, "merge": { "args": [ @@ -1146,14 +1273,16 @@ "objects" ], "numArgs": 2, - "description": "

Deeply merge the properties of the given objects with the context object.

\n" + "description": "

Deeply merge the properties of the given objects with the context object.

\n", + "requiresBlock": false }, "parseJSON": { "args": [ "string" ], "numArgs": 1, - "description": "

Parses the given string using JSON.parse.

\n" + "description": "

Parses the given string using JSON.parse.

\n", + "requiresBlock": true }, "pick": { "args": [ @@ -1162,14 +1291,16 @@ "options" ], "numArgs": 3, - "description": "

Pick properties from the context object.

\n" + "description": "

Pick properties from the context object.

\n", + "requiresBlock": true }, "stringify": { "args": [ "obj" ], "numArgs": 1, - "description": "

Stringify an object using JSON.stringify.

\n" + "description": "

Stringify an object using JSON.stringify.

\n", + "requiresBlock": false } }, "uuid": { @@ -1177,7 +1308,8 @@ "args": [], "numArgs": 0, "example": "{{ uuid }} -> f34ebc66-93bd-4f7c-b79b-92b5569138bc", - "description": "

Generates a UUID, using the V4 method (identical to the browser crypto.randomUUID function).

\n" + "description": "

Generates a UUID, using the V4 method (identical to the browser crypto.randomUUID function).

\n", + "requiresBlock": false } }, "date": { diff --git a/packages/string-templates/package.json b/packages/string-templates/package.json index dfbff1a24b..36f95060b4 100644 --- a/packages/string-templates/package.json +++ b/packages/string-templates/package.json @@ -25,7 +25,7 @@ "manifest": "node ./scripts/gen-collection-info.js" }, "dependencies": { - "@budibase/handlebars-helpers": "^0.13.0", + "@budibase/handlebars-helpers": "^0.13.1", "dayjs": "^1.10.8", "handlebars": "^4.7.6", "lodash.clonedeep": "^4.5.0", diff --git a/packages/string-templates/scripts/gen-collection-info.js b/packages/string-templates/scripts/gen-collection-info.js index b487c4dde4..ed57fe7fae 100644 --- a/packages/string-templates/scripts/gen-collection-info.js +++ b/packages/string-templates/scripts/gen-collection-info.js @@ -10,8 +10,8 @@ const marked = require("marked") * https://github.com/budibase/handlebars-helpers */ const { join } = require("path") +const path = require("path") -const DIRECTORY = join(__dirname, "..", "..", "..") const COLLECTIONS = [ "math", "array", @@ -115,6 +115,8 @@ function getCommentInfo(file, func) { docs.example = docs.example.replace("product", "multiply") } docs.description = blocks[0].trim() + docs.acceptsBlock = docs.tags.some(el => el.title === "block") + docs.acceptsInline = docs.tags.some(el => el.title === "inline") return docs } @@ -127,7 +129,7 @@ function run() { const foundNames = [] for (let collection of COLLECTIONS) { const collectionFile = fs.readFileSync( - `${DIRECTORY}/node_modules/${HELPER_LIBRARY}/lib/${collection}.js`, + `${path.dirname(require.resolve(HELPER_LIBRARY))}/lib/${collection}.js`, "utf8" ) const collectionInfo = {} @@ -159,6 +161,7 @@ function run() { numArgs: args.length, example: jsDocInfo.example || undefined, description: jsDocInfo.description, + requiresBlock: jsDocInfo.acceptsBlock && !jsDocInfo.acceptsInline, }) } outputJSON[collection] = collectionInfo diff --git a/packages/string-templates/src/conversion/index.js b/packages/string-templates/src/conversion/index.js index 30e2510b55..10aaef0d2f 100644 --- a/packages/string-templates/src/conversion/index.js +++ b/packages/string-templates/src/conversion/index.js @@ -1,4 +1,4 @@ -const { getHelperList } = require("../helpers") +const { getJsHelperList } = require("../helpers") function getLayers(fullBlock) { let layers = [] @@ -109,7 +109,7 @@ module.exports.convertHBSBlock = (block, blockNumber) => { const layers = getLayers(block) let value = null - const list = getHelperList() + const list = getJsHelperList() for (let layer of layers) { const parts = splitBySpace(layer) if (value || parts.length > 1 || list[parts[0]]) { diff --git a/packages/string-templates/src/helpers/date.js b/packages/string-templates/src/helpers/date.js index 27554d1d9e..6fe8b288d6 100644 --- a/packages/string-templates/src/helpers/date.js +++ b/packages/string-templates/src/helpers/date.js @@ -115,7 +115,7 @@ module.exports.duration = (str, pattern, format) => { setLocale(config.str, config.pattern) const duration = dayjs.duration(config.str, config.pattern) - if (!isOptions(format)) { + if (format && !isOptions(format)) { return duration.format(format) } else { return duration.humanize() diff --git a/packages/string-templates/src/helpers/index.js b/packages/string-templates/src/helpers/index.js index bed3d0c3e3..5e6dcbd2b9 100644 --- a/packages/string-templates/src/helpers/index.js +++ b/packages/string-templates/src/helpers/index.js @@ -7,7 +7,7 @@ const { HelperFunctionBuiltin, LITERAL_MARKER, } = require("./constants") -const { getHelperList } = require("./list") +const { getJsHelperList } = require("./list") const HTML_SWAPS = { "<": "<", @@ -97,4 +97,4 @@ module.exports.unregisterAll = handlebars => { externalHandlebars.unregisterAll(handlebars) } -module.exports.getHelperList = getHelperList +module.exports.getJsHelperList = getJsHelperList diff --git a/packages/string-templates/src/helpers/javascript.js b/packages/string-templates/src/helpers/javascript.js index 0b63400deb..eff125dd72 100644 --- a/packages/string-templates/src/helpers/javascript.js +++ b/packages/string-templates/src/helpers/javascript.js @@ -1,7 +1,7 @@ const { atob } = require("../utilities") const cloneDeep = require("lodash.clonedeep") const { LITERAL_MARKER } = require("../helpers/constants") -const { getHelperList } = require("./list") +const { getJsHelperList } = require("./list") // The method of executing JS scripts depends on the bundle being built. // This setter is used in the entrypoint (either index.cjs or index.mjs). @@ -49,7 +49,7 @@ module.exports.processJS = (handlebars, context) => { // app context. const sandboxContext = { $: path => getContextValue(path, cloneDeep(context)), - helpers: getHelperList(), + helpers: getJsHelperList(), } // Create a sandbox with our context and run the JS diff --git a/packages/string-templates/src/helpers/list.js b/packages/string-templates/src/helpers/list.js index b59efb1ef3..e956958865 100644 --- a/packages/string-templates/src/helpers/list.js +++ b/packages/string-templates/src/helpers/list.js @@ -3,7 +3,10 @@ const helperList = require("@budibase/handlebars-helpers") let helpers = undefined -module.exports.getHelperList = () => { +const helpersToRemoveForJs = ["sortBy"] +module.exports.helpersToRemoveForJs = helpersToRemoveForJs + +module.exports.getJsHelperList = () => { if (helpers) { return helpers } @@ -15,12 +18,17 @@ module.exports.getHelperList = () => { } for (let collection of constructed) { for (let [key, func] of Object.entries(collection)) { - helpers[key] = func + // Handlebars injects the hbs options to the helpers by default. We are adding an empty {} as a last parameter to simulate it + helpers[key] = (...props) => func(...props, {}) } } for (let key of Object.keys(externalHandlebars.addedHelpers)) { helpers[key] = externalHandlebars.addedHelpers[key] } + + for (const toRemove of helpersToRemoveForJs) { + delete helpers[toRemove] + } Object.freeze(helpers) return helpers } diff --git a/packages/string-templates/src/index.cjs b/packages/string-templates/src/index.cjs index aedb7fc052..7d3aa02be8 100644 --- a/packages/string-templates/src/index.cjs +++ b/packages/string-templates/src/index.cjs @@ -20,6 +20,7 @@ module.exports.findHBSBlocks = templates.findHBSBlocks module.exports.convertToJS = templates.convertToJS module.exports.setJSRunner = templates.setJSRunner module.exports.FIND_ANY_HBS_REGEX = templates.FIND_ANY_HBS_REGEX +module.exports.helpersToRemoveForJs = templates.helpersToRemoveForJs if (!process.env.NO_JS) { const { VM } = require("vm2") diff --git a/packages/string-templates/src/index.js b/packages/string-templates/src/index.js index 63da7fde4d..eb9a8ac81d 100644 --- a/packages/string-templates/src/index.js +++ b/packages/string-templates/src/index.js @@ -10,6 +10,7 @@ const { } = require("./utilities") const { convertHBSBlock } = require("./conversion") const javascript = require("./helpers/javascript") +const { helpersToRemoveForJs } = require("./helpers/list") const hbsInstance = handlebars.create() registerAll(hbsInstance) @@ -394,3 +395,4 @@ module.exports.convertToJS = hbs => { } module.exports.FIND_ANY_HBS_REGEX = FIND_ANY_HBS_REGEX +module.exports.helpersToRemoveForJs = helpersToRemoveForJs diff --git a/packages/string-templates/src/index.mjs b/packages/string-templates/src/index.mjs index 43cda8183f..ad93a7bed4 100644 --- a/packages/string-templates/src/index.mjs +++ b/packages/string-templates/src/index.mjs @@ -21,6 +21,7 @@ export const findHBSBlocks = templates.findHBSBlocks export const convertToJS = templates.convertToJS export const setJSRunner = templates.setJSRunner export const FIND_ANY_HBS_REGEX = templates.FIND_ANY_HBS_REGEX +export const helpersToRemoveForJs = templates.helpersToRemoveForJs if (process && !process.env.NO_JS) { /** diff --git a/packages/string-templates/test/manifest.spec.js b/packages/string-templates/test/manifest.spec.js index 506f2eb6f7..3e39d775f5 100644 --- a/packages/string-templates/test/manifest.spec.js +++ b/packages/string-templates/test/manifest.spec.js @@ -16,21 +16,55 @@ jest.mock("@budibase/handlebars-helpers/lib/uuid", () => { }) const fs = require("fs") -const { processString } = require("../src/index.cjs") +const { + processString, + convertToJS, + processStringSync, + encodeJSBinding, +} = require("../src/index.cjs") const tk = require("timekeeper") +const { getJsHelperList } = require("../src/helpers") + tk.freeze("2021-01-21T12:00:00") +const processJS = (js, context) => { + return processStringSync(encodeJSBinding(js), context) +} + const manifest = JSON.parse( fs.readFileSync(require.resolve("../manifest.json"), "utf8") ) const collections = Object.keys(manifest) const examples = collections.reduce((acc, collection) => { - const functions = Object.keys(manifest[collection]).filter( - fnc => manifest[collection][fnc].example - ) - if (functions.length) { + const functions = Object.entries(manifest[collection]) + .filter(([_, details]) => details.example) + .map(([name, details]) => { + const example = details.example + let [hbs, js] = example.split("->").map(x => x.trim()) + if (!js) { + // The function has no return value + return + } + + // Trim 's + js = js.replace(/^\'|\'$/g, "") + if ((parsedExpected = tryParseJson(js))) { + if (Array.isArray(parsedExpected)) { + if (typeof parsedExpected[0] === "object") { + js = JSON.stringify(parsedExpected) + } else { + js = parsedExpected.join(",") + } + } + } + const requiresHbsBody = details.requiresBlock + return [name, { hbs, js, requiresHbsBody }] + }) + .filter(x => !!x) + + if (Object.keys(functions).length) { acc[collection] = functions } return acc @@ -55,11 +89,7 @@ function tryParseJson(str) { describe("manifest", () => { describe("examples are valid", () => { describe.each(Object.keys(examples))("%s", collection => { - it.each(examples[collection])("%s", async func => { - const example = manifest[collection][func].example - - let [hbs, js] = example.split("->").map(x => x.trim()) - + it.each(examples[collection])("%s", async (_, { hbs, js }) => { const context = { double: i => i * 2, isString: x => typeof x === "string", @@ -71,23 +101,40 @@ describe("manifest", () => { context[`array${i}`] = JSON.parse(arrayString.replace(/\'/g, '"')) }) - if (js === undefined) { - // The function has no return value - return + let result = await processString(hbs, context) + result = result.replace(/ /g, " ") + expect(result).toEqual(js) + }) + }) + }) + + describe("can be parsed and run as js", () => { + const jsHelpers = getJsHelperList() + const jsExamples = Object.keys(examples).reduce((acc, v) => { + acc[v] = examples[v].filter(([key]) => jsHelpers[key]) + return acc + }, {}) + + describe.each(Object.keys(jsExamples))("%s", collection => { + it.each( + jsExamples[collection].filter( + ([_, { requiresHbsBody }]) => !requiresHbsBody + ) + )("%s", async (_, { hbs, js }) => { + const context = { + double: i => i * 2, + isString: x => typeof x === "string", } - let result = await processString(hbs, context) - // Trim 's - js = js.replace(/^\'|\'$/g, "") - if ((parsedExpected = tryParseJson(js))) { - if (Array.isArray(parsedExpected)) { - if (typeof parsedExpected[0] === "object") { - js = JSON.stringify(parsedExpected) - } else { - js = parsedExpected.join(",") - } - } - } + const arrays = hbs.match(/\[[^/\]]+\]/) + arrays?.forEach((arrayString, i) => { + hbs = hbs.replace(new RegExp(escapeRegExp(arrayString)), `array${i}`) + context[`array${i}`] = JSON.parse(arrayString.replace(/\'/g, '"')) + }) + + let convertedJs = convertToJS(hbs) + + let result = processJS(convertedJs, context) result = result.replace(/ /g, " ") expect(result).toEqual(js) }) diff --git a/packages/types/package.json b/packages/types/package.json index 5111339c7b..ce4fce95fb 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -15,7 +15,7 @@ }, "jest": {}, "devDependencies": { - "@budibase/nano": "10.1.4", + "@budibase/nano": "10.1.5", "@types/koa": "2.13.4", "@types/pouchdb": "6.4.0", "@types/redlock": "4.0.3", diff --git a/packages/worker/package.json b/packages/worker/package.json index 2e3200fda5..6c4cc6fe5b 100644 --- a/packages/worker/package.json +++ b/packages/worker/package.json @@ -63,7 +63,7 @@ "koa-useragent": "^4.1.0", "lodash": "4.17.21", "node-fetch": "2.6.7", - "nodemailer": "6.7.2", + "nodemailer": "6.9.9", "passport-google-oauth": "2.0.0", "passport-local": "1.0.0", "pouchdb": "7.3.0", diff --git a/yarn.lock b/yarn.lock index c310d1d111..0e29b0a00f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2038,10 +2038,10 @@ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== -"@budibase/handlebars-helpers@^0.13.0": - version "0.13.0" - resolved "https://registry.yarnpkg.com/@budibase/handlebars-helpers/-/handlebars-helpers-0.13.0.tgz#224333d14e3900b7dacf48286af1e624a9fd62ea" - integrity sha512-g8+sFrMNxsIDnK+MmdUICTVGr6ReUFtnPp9hJX0VZwz1pN3Ynolpk/Qbu6rEWAvoU1sEqY1mXr9uo/+kEfeGbQ== +"@budibase/handlebars-helpers@^0.13.1": + version "0.13.1" + resolved "https://registry.yarnpkg.com/@budibase/handlebars-helpers/-/handlebars-helpers-0.13.1.tgz#d02e73c0df8305cd675e70dc37f8427eb0842080" + integrity sha512-v4RbXhr3igvK3i2pj5cNltu/4NMxdPIzcUt/o0RoInhesNH1VSLRdweSFr6/Y34fsCR5jHZ6vltdcz2RgrTKgw== dependencies: get-object "^0.2.0" get-value "^3.0.1" @@ -2057,10 +2057,10 @@ to-gfm-code-block "^0.1.1" uuid "^9.0.1" -"@budibase/nano@10.1.4": - version "10.1.4" - resolved "https://registry.yarnpkg.com/@budibase/nano/-/nano-10.1.4.tgz#5c2670d0b4c12d736ddd6581c57d47c0aa45efad" - integrity sha512-J+IVaAljGideDvJss/AUxXA1599HEIUJo5c0LLlmc1KMA3GZWZjyX+w2fxAw3qF7hqFvX+qAStQgdcD3+/GPMA== +"@budibase/nano@10.1.5": + version "10.1.5" + resolved "https://registry.yarnpkg.com/@budibase/nano/-/nano-10.1.5.tgz#eeaded7bfc707ecabf8fde604425b865a90c06ec" + integrity sha512-q1eKIsYKo+iK17zsJYd3VBl+5ufQMPpHYLec0wVsid8wnJVrTQk7RNpBlBUn/EDgXM7t8XNNHlERqHu+CxJu8Q== dependencies: "@types/tough-cookie" "^4.0.2" axios "^1.1.3"