budibase/packages/server/utilities/builder/componentLibraryInfo.js

78 lines
2.6 KiB
JavaScript
Raw Normal View History

const { readJSON, exists } = require("fs-extra")
const { resolve, join, dirname } = require("path")
2019-09-06 14:04:23 +02:00
/**
* @param {string} appPath - budibase application name
* @param {string} libname - component library name
2020-02-25 16:21:23 +01:00
* @returns {string} directory name of component definitions for a specific budibase application.
*/
2019-09-07 07:50:35 +02:00
const getLibDir = (appPath, libname) => {
try {
const componentsFile = require.resolve(join(libname, "components.json"), {
paths: [appPath],
})
return dirname(componentsFile)
} catch (e) {
console.log(e)
}
2019-09-07 07:50:35 +02:00
}
2019-09-06 14:04:23 +02:00
const getComponentsFilepath = libPath => resolve(libPath, "components.json")
2019-09-06 14:04:23 +02:00
module.exports.componentsFilepath = (appPath, libname) =>
getComponentsFilepath(getLibDir(appPath, libname))
2019-09-06 14:04:23 +02:00
/**
* @param {string} appPath - the path to a budibase application
* @param {string} libname - the name of the component libary to use for namespacing
2020-02-25 16:21:23 +01:00
* @returns {object} tree of components namespaced by their component library name.
*/
2019-09-06 14:04:23 +02:00
module.exports.componentLibraryInfo = async (appPath, libname) => {
const libDir = getLibDir(appPath, libname)
const componentsPath = getComponentsFilepath(libDir)
2020-02-19 22:38:21 +01:00
const componentDefinitionExists = await exists(componentsPath)
if (!componentDefinitionExists) {
const e = new Error(
`could not find components definition file at ${componentsPath}`
)
e.statusCode = 404
throw e
}
2020-02-19 22:38:21 +01:00
const addNamespace = name => `${libname}/${name}`
try {
const componentDefinitions = await readJSON(componentsPath)
const namespacedComponents = { _lib: componentDefinitions._lib }
for (let componentKey in componentDefinitions) {
2020-02-19 22:38:21 +01:00
if (componentKey === "_lib" || componentKey === "_templates") continue
const namespacedName = addNamespace(componentKey)
componentDefinitions[componentKey].name = namespacedName
namespacedComponents[namespacedName] = componentDefinitions[componentKey]
}
2019-10-07 07:03:41 +02:00
2020-02-19 22:38:21 +01:00
const namespacedTemplates = { _lib: componentDefinitions._lib }
for (let templateKey in componentDefinitions._templates || {}) {
const template = componentDefinitions._templates[templateKey]
if (template.component)
template.component = addNamespace(template.component)
const namespacedName = addNamespace(templateKey)
template.name = namespacedName
namespacedTemplates[namespacedName] =
componentDefinitions._templates[templateKey]
}
return {
components: namespacedComponents,
2020-02-19 22:38:21 +01:00
templates: namespacedTemplates,
libDir,
componentsPath,
2019-09-06 14:04:23 +02:00
}
} catch (e) {
const err = `could not parse JSON - ${componentsPath} : ${e.message}`
throw new Error(err)
}
}