Inject url

This commit is contained in:
Adria Navarro 2024-01-18 13:49:47 +01:00
parent 60574196b9
commit 262dbc7c2b
2 changed files with 35 additions and 13 deletions

View File

@ -4,26 +4,50 @@ import { setJSRunner } from "@budibase/string-templates"
import { context } from "@budibase/backend-core"
import tracer from "dd-trace"
import fs from "fs"
import url from "url"
export function init() {
const helpersSource = fs.readFileSync(
`${require.resolve("@budibase/string-templates/index-helpers")}`,
"utf8"
)
setJSRunner((js: string, ctx: Record<string, any>) => {
return tracer.trace("runJS", {}, span => {
const bbCtx = context.getCurrentContext()!
let { jsContext, jsIsolate } = bbCtx
// if (!jsIsolate) {
jsIsolate = new ivm.Isolate({ memoryLimit: 64 })
jsContext = jsIsolate.createContextSync()
const helpersModule = jsIsolate.compileModuleSync(helpersSource)
const bbCtx = context.getCurrentContext() || {}
let { jsIsolate = new ivm.Isolate({ memoryLimit: 64 }) } = bbCtx
let { jsContext = jsIsolate.createContextSync() } = bbCtx
const injectedRequire = `const require = function(val){
switch (val) {
case "url":
return {
resolve: (...params) => urlResolveCb(...params),
parse: (...params) => urlParseCb(...params),
}
}
};`
const global = jsContext.global
global.setSync(
"urlResolveCb",
new ivm.Callback((...params: Parameters<typeof url.resolve>) =>
url.resolve(...params)
)
)
global.setSync(
"urlParseCb",
new ivm.Callback((...params: Parameters<typeof url.parse>) =>
url.parse(...params)
)
)
const helpersModule = jsIsolate.compileModuleSync(
`${injectedRequire};${helpersSource}`
)
helpersModule.instantiateSync(jsContext, specifier => {
throw new Error(`No imports allowed. Required: ${specifier}`)
})
// }
const perRequestLimit = env.JS_PER_REQUEST_TIME_LIMIT_MS
if (perRequestLimit) {
@ -35,8 +59,6 @@ export function init() {
}
}
const global = jsContext!.global
for (const [key, value] of Object.entries(ctx)) {
if (key === "helpers") {
// Can't copy the native helpers into the isolate. We just ignore them as they are handled properly from the helpersSource
@ -50,7 +72,7 @@ export function init() {
{}
)
script.instantiateSync(jsContext!, specifier => {
script.instantiateSync(jsContext, specifier => {
if (specifier === "compiled_module") {
return helpersModule
}

View File

@ -5,7 +5,7 @@ const externalCollections = {
math: require("@budibase/handlebars-helpers/lib/math"),
array: require("@budibase/handlebars-helpers/lib/array"),
number: require("@budibase/handlebars-helpers/lib/number"),
// url: require("@budibase/handlebars-helpers/lib/url"),
url: require("@budibase/handlebars-helpers/lib/url"),
string: require("@budibase/handlebars-helpers/lib/string"),
comparison: require("@budibase/handlebars-helpers/lib/comparison"),
object: require("@budibase/handlebars-helpers/lib/object"),
@ -37,4 +37,4 @@ const getHelperList = () => {
return helpers
}
export default getHelperList()
module.exports = getHelperList()