UNPKG

@tririga/tri-bundler

Version:

A tool for bundling Polymer 3 TRIRIGA UX views.

106 lines (85 loc) 2.77 kB
"use strict"; const fs = require("fs"); const path = require("path"); const jsc = require("jscodeshift"); function stripTrailingSlash(dir) { if (!dir) { return null; } return dir.replace(/\\/g, "/").replace(/\/+$/, ""); } module.exports.stripTrailingSlash = stripTrailingSlash; function getComponentUrls(componentSource, componentContext) { var componentPaths = []; let importUrls = getImportUrls(componentSource); if (importUrls.length > 0) { importUrls.forEach((impUrl) => { var relativePath = impUrl; var componentPath = resolvePath(componentContext, relativePath); componentPaths.push(componentPath); }); } return componentPaths; } module.exports.getComponentUrls = getComponentUrls; function getImportUrls(source) { let importUrls = []; jsc(source).find(jsc.ImportDeclaration) .forEach(function(path) { importUrls.push(path.node.source.value); }); jsc(source).find(jsc.Identifier) .forEach(function(path) { if (path.node.name == "loadResource" || path.node.name == "_loadPortalItem") { const parent = path.parent; if (parent.node.type == "MemberExpression" && parent.parent.node.type == "CallExpression" && parent.parent.node.arguments) { let resource; if (path.node.name == "loadResource" && parent.parent.node.arguments[1]) { resource = parent.parent.node.arguments[1].value; } else if (path.node.name == "_loadPortalItem" && parent.parent.node.arguments[2]) { resource = parent.parent.node.arguments[2].value; } if (resource) { importUrls.push(`./${resource}`); } } } }); importUrls = [...new Set(importUrls)]; return importUrls; } module.exports.getImportUrls = getImportUrls; function resolvePath(componentContextUrl, relativePath) { if (!relativePath.startsWith(".")) { return componentContextUrl + relativePath; } if (relativePath.startsWith("./")) { return resolvePath(componentContextUrl, relativePath.slice(2)); } if (relativePath.startsWith("../")) { var fromIndex = componentContextUrl.length - 2; var sliceIndex = componentContextUrl.lastIndexOf("/", fromIndex) + 1; return resolvePath( componentContextUrl.slice(0, sliceIndex), relativePath.slice(3)); } } module.exports.resolvePath = resolvePath; function minifyTemplateStr(src) { return src .replace(/(\r\n|\n|\r)/g, '') .replace(/\s{2,}/g, ' '); } module.exports.minifyTemplateStr = minifyTemplateStr; function getCurrentDir() { var currentDirFullPath = process.cwd(); currentDirFullPath = currentDirFullPath.replace(/\\/g, "/"); var currentDirName = currentDirFullPath.substr(currentDirFullPath.lastIndexOf("/") + 1); return { path: currentDirFullPath, name: currentDirName }; } module.exports.getCurrentDir = getCurrentDir;