This commit is contained in:
lalBi94
2023-03-05 13:23:23 +01:00
commit 7bc56c09b5
14034 changed files with 1834369 additions and 0 deletions

7
node_modules/@riotjs/compiler/src/constants.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export const TAG_LOGIC_PROPERTY = 'exports'
export const TAG_CSS_PROPERTY = 'css'
export const TAG_TEMPLATE_PROPERTY = 'template'
export const TAG_NAME_PROPERTY = 'name'
export const RIOT_MODULE_ID = 'riot'
export const RIOT_INTERFACE_WRAPPER_NAME = 'RiotComponentWrapper'
export const RIOT_TAG_INTERFACE_NAME = 'RiotComponent'

View File

@@ -0,0 +1,124 @@
import {builders, types} from '../../utils/build-types'
import {TAG_CSS_PROPERTY} from '../../constants'
import cssEscape from 'cssesc'
import getPreprocessorTypeByAttribute from '../../utils/get-preprocessor-type-by-attribute'
import preprocess from '../../utils/preprocess-node'
/**
* Matches valid, multiline JavaScript comments in almost all its forms.
* @const {RegExp}
* @static
*/
const R_MLCOMMS = /\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//g
/**
* Source for creating regexes matching valid quoted, single-line JavaScript strings.
* It recognizes escape characters, including nested quotes and line continuation.
* @const {string}
*/
const S_LINESTR = /"[^"\n\\]*(?:\\[\S\s][^"\n\\]*)*"|'[^'\n\\]*(?:\\[\S\s][^'\n\\]*)*'/.source
/**
* Matches CSS selectors, excluding those beginning with '@' and quoted strings.
* @const {RegExp}
*/
const CSS_SELECTOR = RegExp(`([{}]|^)[; ]*((?:[^@ ;{}][^{}]*)?[^@ ;{}:] ?)(?={)|${S_LINESTR}`, 'g')
/**
* Parses styles enclosed in a "scoped" tag
* The "css" string is received without comments or surrounding spaces.
*
* @param {string} tag - Tag name of the root element
* @param {string} css - The CSS code
* @returns {string} CSS with the styles scoped to the root element
*/
function scopedCSS(tag, css) {
const host = ':host'
const selectorsBlacklist = ['from', 'to']
return css.replace(CSS_SELECTOR, function(m, p1, p2) {
// skip quoted strings
if (!p2) return m
// we have a selector list, parse each individually
p2 = p2.replace(/[^,]+/g, function(sel) {
const s = sel.trim()
// skip selectors already using the tag name
if (s.indexOf(tag) === 0) {
return sel
}
// skips the keywords and percents of css animations
if (!s || selectorsBlacklist.indexOf(s) > -1 || s.slice(-1) === '%') {
return sel
}
// replace the `:host` pseudo-selector, where it is, with the root tag name;
// if `:host` was not included, add the tag name as prefix, and mirror all
// `[data-is]`
if (s.indexOf(host) < 0) {
return `${tag} ${s},[is="${tag}"] ${s}`
} else {
return `${s.replace(host, tag)},${
s.replace(host, `[is="${tag}"]`)}`
}
})
// add the danling bracket char and return the processed selector list
return p1 ? `${p1} ${p2}` : p2
})
}
/**
* Remove comments, compact and trim whitespace
* @param { string } code - compiled css code
* @returns { string } css code normalized
*/
function compactCss(code) {
return code.replace(R_MLCOMMS, '').replace(/\s+/g, ' ').trim()
}
const escapeBackslashes = s => s.replace(/\\/g, '\\\\')
const escapeIdentifier = identifier => escapeBackslashes(cssEscape(identifier, {
isIdentifier: true
}))
/**
* Generate the component css
* @param { Object } sourceNode - node generated by the riot compiler
* @param { string } source - original component source code
* @param { Object } meta - compilation meta information
* @param { AST } ast - current AST output
* @returns { AST } the AST generated
*/
export default function css(sourceNode, source, meta, ast) {
const preprocessorName = getPreprocessorTypeByAttribute(sourceNode)
const { options } = meta
const preprocessorOutput = preprocess('css', preprocessorName, meta, sourceNode.text)
const normalizedCssCode = compactCss(preprocessorOutput.code)
const escapedCssIdentifier = escapeIdentifier(meta.tagName)
const cssCode = (options.scopedCss ?
scopedCSS(escapedCssIdentifier, escapeBackslashes(normalizedCssCode)) :
escapeBackslashes(normalizedCssCode)
).trim()
types.visit(ast, {
visitProperty(path) {
if (path.value.key.name === TAG_CSS_PROPERTY) {
path.value.value = builders.templateLiteral(
[builders.templateElement({ raw: cssCode, cooked: '' }, false)],
[]
)
return false
}
this.traverse(path)
}
})
return ast
}

View File

@@ -0,0 +1,73 @@
import {
addComponentInterfaceToExportedObject,
createDefaultExportFromLegacySyntax,
extendTagProperty,
filterNonExportDefaultStatements, findAllExportNamedDeclarations,
findAllImportDeclarations, findComponentInterface,
findExportDefaultStatement,
getProgramBody
} from './utils'
import addLinesOffset from '../../utils/add-lines-offset'
import generateAST from '../../utils/generate-ast'
import getPreprocessorTypeByAttribute from '../../utils/get-preprocessor-type-by-attribute'
import isEmptySourcemap from '../../utils/is-empty-sourcemap'
import {isNil} from '@riotjs/util/checks'
import {isThisExpressionStatement} from '../../utils/ast-nodes-checks'
import preprocess from '../../utils/preprocess-node'
import sourcemapToJSON from '../../utils/sourcemap-as-json'
/**
* Generate the component javascript logic
* @param { Object } sourceNode - node generated by the riot compiler
* @param { string } source - original component source code
* @param { Object } meta - compilation meta information
* @param { AST } ast - current AST output
* @returns { AST } the AST generated
*/
export default function javascript(sourceNode, source, meta, ast) {
const preprocessorName = getPreprocessorTypeByAttribute(sourceNode)
const javascriptNode = addLinesOffset(sourceNode.text.text, source, sourceNode)
const { options } = meta
const preprocessorOutput = preprocess('javascript', preprocessorName, meta, {
...sourceNode,
text: javascriptNode
})
const inputSourceMap = sourcemapToJSON(preprocessorOutput.map)
const generatedAst = generateAST(preprocessorOutput.code, {
sourceFileName: options.file,
inputSourceMap: isEmptySourcemap(inputSourceMap) ? null : inputSourceMap
})
const generatedAstBody = getProgramBody(generatedAst)
const exportDefaultNode = findExportDefaultStatement(generatedAstBody)
const isLegacyRiotSyntax = isNil(exportDefaultNode)
const outputBody = getProgramBody(ast)
const componentInterface = findComponentInterface(generatedAstBody)
// throw in case of mixed component exports
if (exportDefaultNode && generatedAstBody.some(isThisExpressionStatement))
throw new Error('You can\t use "export default {}" and root this statements in the same component')
// add to the ast the "private" javascript content of our tag script node
outputBody.unshift(
...(
// for the legacy riot syntax we need to move all the import and (named) export statements outside of the function body
isLegacyRiotSyntax ?
[...findAllImportDeclarations(generatedAstBody), ...findAllExportNamedDeclarations(generatedAstBody)] :
// modern riot syntax will hoist all the private stuff outside of the export default statement
filterNonExportDefaultStatements(generatedAstBody)
))
// create the public component export properties from the root this statements
if (isLegacyRiotSyntax) extendTagProperty(
ast,
createDefaultExportFromLegacySyntax(generatedAstBody)
)
// convert the export default adding its content to the component property exported
if (exportDefaultNode) extendTagProperty(ast, exportDefaultNode)
return componentInterface ?
// add the component interface to the component object exported
addComponentInterfaceToExportedObject(ast, componentInterface) :
ast
}

View File

@@ -0,0 +1,172 @@
import {RIOT_INTERFACE_WRAPPER_NAME, RIOT_MODULE_ID, RIOT_TAG_INTERFACE_NAME, TAG_LOGIC_PROPERTY} from '../../constants'
import {builders, types} from '../../utils/build-types'
import {
isExportDefaultStatement,
isExportNamedDeclaration,
isImportDeclaration, isInterfaceDeclaration,
isThisExpressionStatement,
isTypeAliasDeclaration
} from '../../utils/ast-nodes-checks'
import compose from 'cumpa'
/**
* Find the export default statement
* @param { Array } body - tree structure containing the program code
* @returns { Object } node containing only the code of the export default statement
*/
export function findExportDefaultStatement(body) {
return body.find(isExportDefaultStatement)
}
/**
* Find all import declarations
* @param { Array } body - tree structure containing the program code
* @returns { Array } array containing all the import declarations detected
*/
export function findAllImportDeclarations(body) {
return body.filter(isImportDeclaration)
}
/**
* Find all the named export declarations
* @param { Array } body - tree structure containing the program code
* @returns { Array } array containing all the named export declarations detected
*/
export function findAllExportNamedDeclarations(body) {
return body.filter(isExportNamedDeclaration)
}
/**
* Filter all the import declarations
* @param { Array } body - tree structure containing the program code
* @returns { Array } array containing all the ast expressions without the import declarations
*/
export function filterOutAllImportDeclarations(body) {
return body.filter(n => !isImportDeclaration(n))
}
/**
* Filter all the export declarations
* @param { Array } body - tree structure containing the program code
* @returns { Array } array containing all the ast expressions without the export declarations
*/
export function filterOutAllExportDeclarations(body) {
return body.filter(n => !isExportNamedDeclaration(n) || isExportDefaultStatement(n))
}
/**
* Find the component interface exported
* @param { Array } body - tree structure containing the program code
* @returns { Object|null } the object referencing the component interface if found
*/
export function findComponentInterface(body) {
const exportNamedDeclarations = body.filter(isExportNamedDeclaration).map(n => n.declaration)
const types = exportNamedDeclarations.filter(isTypeAliasDeclaration)
const interfaces = exportNamedDeclarations.filter(isInterfaceDeclaration)
const isRiotComponentTypeName = ({ typeName }) => typeName && typeName.name ? typeName.name === RIOT_TAG_INTERFACE_NAME : false
const extendsRiotComponent = ({ expression }) => expression.name === RIOT_TAG_INTERFACE_NAME
return types.find(
node => (node.typeAnnotation.types && node.typeAnnotation.types.some(isRiotComponentTypeName)) || isRiotComponentTypeName(node.typeAnnotation)
) || interfaces.find(
node => node.extends && node.extends.some(extendsRiotComponent)
)
}
/**
* Add the component interface to the export declaration
* @param { Object } ast - ast object generated by recast
* @param { Object } componentInterface - the component typescript interface
* @returns { Object } the component object exported combined with the riot typescript interfaces
*/
export function addComponentInterfaceToExportedObject(ast, componentInterface) {
const body = getProgramBody(ast)
const RiotComponentWrapperImportSpecifier = builders.importSpecifier(
builders.identifier(RIOT_INTERFACE_WRAPPER_NAME)
)
const componentInterfaceName = componentInterface.id.name
const riotImportDeclaration = findAllImportDeclarations(body).find(node => node.source.value === RIOT_MODULE_ID)
const exportDefaultStatement = body.find(isExportDefaultStatement)
const objectExport = exportDefaultStatement.declaration
// add the RiotComponentWrapper to this component imports
if (riotImportDeclaration) {
riotImportDeclaration.specifiers.push(RiotComponentWrapperImportSpecifier)
} else {
// otherwise create the whole import statement from riot
body.unshift(0, builders.importDeclaration(
[RiotComponentWrapperImportSpecifier],
builders.stringLiteral(RIOT_MODULE_ID)
))
}
// override the object export adding the types detected
exportDefaultStatement.declaration = builders.tsAsExpression(
objectExport,
builders.tsTypeReference(
builders.identifier(RIOT_INTERFACE_WRAPPER_NAME),
builders.tsTypeParameterInstantiation(
[builders.tsTypeReference(builders.identifier(componentInterfaceName))]
)
)
)
return ast
}
/**
* Create the default export declaration interpreting the old riot syntax relying on "this" statements
* @param { Array } body - tree structure containing the program code
* @returns { Object } ExportDefaultDeclaration
*/
export function createDefaultExportFromLegacySyntax(body) {
return builders.exportDefaultDeclaration(
builders.functionDeclaration(
builders.identifier(TAG_LOGIC_PROPERTY),
[],
builders.blockStatement([
...compose(filterOutAllImportDeclarations, filterOutAllExportDeclarations)(body),
builders.returnStatement(builders.thisExpression())
])
)
)
}
/**
* Find all the code in an ast program except for the export default statements
* @param { Array } body - tree structure containing the program code
* @returns { Array } array containing all the program code except the export default expressions
*/
export function filterNonExportDefaultStatements(body) {
return body.filter(node => !isExportDefaultStatement(node) && !isThisExpressionStatement(node))
}
/**
* Get the body of the AST structure
* @param { Object } ast - ast object generated by recast
* @returns { Array } array containing the program code
*/
export function getProgramBody(ast) {
return ast.body || ast.program.body
}
/**
* Extend the AST adding the new tag method containing our tag sourcecode
* @param { Object } ast - current output ast
* @param { Object } exportDefaultNode - tag export default node
* @returns { Object } the output ast having the "tag" key extended with the content of the export default
*/
export function extendTagProperty(ast, exportDefaultNode) {
types.visit(ast, {
visitProperty(path) {
if (path.value.key.name === TAG_LOGIC_PROPERTY) {
path.value.value = exportDefaultNode.declaration
return false
}
this.traverse(path)
}
})
return ast
}

View File

@@ -0,0 +1,110 @@
import {
BINDING_CONDITION_KEY,
BINDING_EVALUATE_KEY,
BINDING_GET_KEY_KEY,
BINDING_INDEX_NAME_KEY,
BINDING_ITEM_NAME_KEY,
BINDING_TYPES,
BINDING_TYPE_KEY,
EACH_BINDING_TYPE
} from '../constants'
import {
createASTFromExpression,
createSelectorProperties,
createTemplateProperty,
getAttributeExpression,
getName,
toScopedFunction
} from '../utils'
import {findEachAttribute, findIfAttribute, findKeyAttribute} from '../find'
import {isExpressionStatement, isSequenceExpression} from '../../../utils/ast-nodes-checks'
import {nullNode, simplePropertyNode} from '../../../utils/custom-ast-nodes'
import {builders} from '../../../utils/build-types'
import compose from 'cumpa'
import {createNestedBindings} from '../builder'
import generateJavascript from '../../../utils/generate-javascript'
import {panic} from '@riotjs/util/misc'
const getEachItemName = expression => isSequenceExpression(expression.left) ? expression.left.expressions[0] : expression.left
const getEachIndexName = expression => isSequenceExpression(expression.left) ? expression.left.expressions[1] : null
const getEachValue = expression => expression.right
const nameToliteral = compose(builders.literal, getName)
const generateEachItemNameKey = expression => simplePropertyNode(
BINDING_ITEM_NAME_KEY,
compose(nameToliteral, getEachItemName)(expression)
)
const generateEachIndexNameKey = expression => simplePropertyNode(
BINDING_INDEX_NAME_KEY,
compose(nameToliteral, getEachIndexName)(expression)
)
const generateEachEvaluateKey = (expression, eachExpression, sourceFile, sourceCode) => simplePropertyNode(
BINDING_EVALUATE_KEY,
compose(
e => toScopedFunction(e, sourceFile, sourceCode),
e => ({
...eachExpression,
text: generateJavascript(e).code
}),
getEachValue
)(expression)
)
/**
* Get the each expression properties to create properly the template binding
* @param { DomBinding.Expression } eachExpression - original each expression data
* @param { string } sourceFile - original tag file
* @param { string } sourceCode - original tag source code
* @returns { Array } AST nodes that are needed to build an each binding
*/
export function generateEachExpressionProperties(eachExpression, sourceFile, sourceCode) {
const ast = createASTFromExpression(eachExpression, sourceFile, sourceCode)
const body = ast.program.body
const firstNode = body[0]
if (!isExpressionStatement(firstNode)) {
panic(`The each directives supported should be of type "ExpressionStatement",you have provided a "${firstNode.type}"`)
}
const { expression } = firstNode
return [
generateEachItemNameKey(expression),
generateEachIndexNameKey(expression),
generateEachEvaluateKey(expression, eachExpression, sourceFile, sourceCode)
]
}
/**
* Transform a RiotParser.Node.Tag into an each binding
* @param { RiotParser.Node.Tag } sourceNode - tag containing the each attribute
* @param { string } selectorAttribute - attribute needed to select the target node
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns { AST.Node } an each binding node
*/
export default function createEachBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
const [ifAttribute, eachAttribute, keyAttribute] = [
findIfAttribute,
findEachAttribute,
findKeyAttribute
].map(f => f(sourceNode))
const attributeOrNull = attribute => attribute ? toScopedFunction(getAttributeExpression(attribute), sourceFile, sourceCode) : nullNode()
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(BINDING_TYPES),
builders.identifier(EACH_BINDING_TYPE),
false
)
),
simplePropertyNode(BINDING_GET_KEY_KEY, attributeOrNull(keyAttribute)),
simplePropertyNode(BINDING_CONDITION_KEY, attributeOrNull(ifAttribute)),
createTemplateProperty(createNestedBindings(sourceNode, sourceFile, sourceCode, selectorAttribute)),
...createSelectorProperties(selectorAttribute),
...compose(generateEachExpressionProperties, getAttributeExpression)(eachAttribute)
])
}

View File

@@ -0,0 +1,43 @@
import {
BINDING_EVALUATE_KEY,
BINDING_TYPES,
BINDING_TYPE_KEY,
IF_BINDING_TYPE
} from '../constants'
import {
createSelectorProperties,
createTemplateProperty,
toScopedFunction
} from '../utils'
import {builders} from '../../../utils/build-types'
import {createNestedBindings} from '../builder'
import {findIfAttribute} from '../find'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
/**
* Transform a RiotParser.Node.Tag into an if binding
* @param { RiotParser.Node.Tag } sourceNode - tag containing the if attribute
* @param { string } selectorAttribute - attribute needed to select the target node
* @param { stiring } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns { AST.Node } an if binding node
*/
export default function createIfBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
const ifAttribute = findIfAttribute(sourceNode)
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(BINDING_TYPES),
builders.identifier(IF_BINDING_TYPE),
false
)
),
simplePropertyNode(
BINDING_EVALUATE_KEY,
toScopedFunction(ifAttribute.expressions[0], sourceFile, sourceCode)
),
...createSelectorProperties(selectorAttribute),
createTemplateProperty(createNestedBindings(sourceNode, sourceFile, sourceCode, selectorAttribute))
])
}

View File

@@ -0,0 +1,53 @@
import {createAttributeExpressions, createExpression} from '../expressions/index'
import {
createSelectorProperties,
getChildrenNodes
} from '../utils'
import {hasExpressions, isRemovableNode, isRootNode, isTextNode} from '../checks'
import {BINDING_EXPRESSIONS_KEY} from '../constants'
import {builders} from '../../../utils/build-types'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
/**
* Create the text node expressions
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @returns {Array} array containing all the text node expressions
*/
function createTextNodeExpressions(sourceNode, sourceFile, sourceCode) {
const childrenNodes = getChildrenNodes(sourceNode)
return childrenNodes
.filter(isTextNode)
.filter(hasExpressions)
.map(node => createExpression(
node,
sourceFile,
sourceCode,
childrenNodes.indexOf(node),
sourceNode
))
}
/**
* Add a simple binding to a riot parser node
* @param { RiotParser.Node.Tag } sourceNode - tag containing the if attribute
* @param { string } selectorAttribute - attribute needed to select the target node
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns { AST.Node } an each binding node
*/
export default function createSimpleBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
return builders.objectExpression([
// root or removable nodes do not need selectors
...(isRemovableNode(sourceNode) || isRootNode(sourceNode) ? [] : createSelectorProperties(selectorAttribute)),
simplePropertyNode(
BINDING_EXPRESSIONS_KEY,
builders.arrayExpression([
...createTextNodeExpressions(sourceNode, sourceFile, sourceCode),
...createAttributeExpressions(sourceNode, sourceFile, sourceCode)
])
)
])
}

View File

@@ -0,0 +1,60 @@
import {
BINDING_ATTRIBUTES_KEY,
BINDING_NAME_KEY,
BINDING_TYPES,
BINDING_TYPE_KEY,
DEFAULT_SLOT_NAME,
NAME_ATTRIBUTE,
SLOT_BINDING_TYPE
} from '../constants'
import {
createBindingAttributes,
createSelectorProperties,
getName,
getNodeAttributes
} from '../utils'
import {builders} from '../../../utils/build-types'
import {findAttribute} from '../find'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
/**
* Transform a RiotParser.Node.Tag of type slot into a slot binding
* @param { RiotParser.Node.Tag } sourceNode - slot node
* @param { string } selectorAttribute - attribute needed to select the target node
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns { AST.Node } a slot binding node
*/
export default function createSlotBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
const slotNameAttribute = findAttribute(NAME_ATTRIBUTE, sourceNode)
const slotName = slotNameAttribute ? slotNameAttribute.value : DEFAULT_SLOT_NAME
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(BINDING_TYPES),
builders.identifier(SLOT_BINDING_TYPE),
false
)
),
simplePropertyNode(
BINDING_ATTRIBUTES_KEY,
createBindingAttributes(
{
...sourceNode,
// filter the name attribute
attributes: getNodeAttributes(sourceNode)
.filter(attribute => getName(attribute) !== NAME_ATTRIBUTE)
},
selectorAttribute,
sourceFile,
sourceCode
)
),
simplePropertyNode(
BINDING_NAME_KEY,
builders.literal(slotName)
),
...createSelectorProperties(selectorAttribute)
])
}

View File

@@ -0,0 +1,129 @@
import {
BINDING_ATTRIBUTES_KEY,
BINDING_BINDINGS_KEY,
BINDING_EVALUATE_KEY,
BINDING_GET_COMPONENT_KEY,
BINDING_HTML_KEY,
BINDING_ID_KEY,
BINDING_SLOTS_KEY,
BINDING_TYPES,
BINDING_TYPE_KEY,
GET_COMPONENT_FN,
SLOT_ATTRIBUTE,
TAG_BINDING_TYPE
} from '../constants'
import {
createBindingAttributes,
createCustomNodeNameEvaluationFunction,
createNestedRootNode,
createSelectorProperties,
getChildrenNodes,
getNodeAttributes
} from '../utils'
import build from '../builder'
import {builders} from '../../../utils/build-types'
import compose from 'cumpa'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
/**
* Find the slots in the current component and group them under the same id
* @param {RiotParser.Node.Tag} sourceNode - the custom tag
* @returns {Object} object containing all the slots grouped by name
*/
function groupSlots(sourceNode) {
return getChildrenNodes(sourceNode).reduce((acc, node) => {
const slotAttribute = findSlotAttribute(node)
if (slotAttribute) {
acc[slotAttribute.value] = node
} else {
acc.default = createNestedRootNode({
nodes: [...getChildrenNodes(acc.default), node]
})
}
return acc
}, {
default: null
})
}
/**
* Create the slot entity to pass to the riot-dom bindings
* @param {string} id - slot id
* @param {RiotParser.Node.Tag} sourceNode - slot root node
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @returns {AST.Node} ast node containing the slot object properties
*/
function buildSlot(id, sourceNode, sourceFile, sourceCode) {
const cloneNode = {
...sourceNode,
attributes: getNodeAttributes(sourceNode)
}
const [html, bindings] = build(cloneNode, sourceFile, sourceCode)
return builders.objectExpression([
simplePropertyNode(BINDING_ID_KEY, builders.literal(id)),
simplePropertyNode(BINDING_HTML_KEY, builders.literal(html)),
simplePropertyNode(BINDING_BINDINGS_KEY, builders.arrayExpression(bindings))
])
}
/**
* Create the AST array containing the slots
* @param { RiotParser.Node.Tag } sourceNode - the custom tag
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns {AST.ArrayExpression} array containing the attributes to bind
*/
export function createSlotsArray(sourceNode, sourceFile, sourceCode) {
return builders.arrayExpression([
...compose(
slots => slots.map(([key, value]) => buildSlot(key, value, sourceFile, sourceCode)),
slots => slots.filter(([, value]) => value),
Object.entries,
groupSlots
)(sourceNode)
])
}
/**
* Find the slot attribute if it exists
* @param {RiotParser.Node.Tag} sourceNode - the custom tag
* @returns {RiotParser.Node.Attr|undefined} the slot attribute found
*/
function findSlotAttribute(sourceNode) {
return getNodeAttributes(sourceNode).find(attribute => attribute.name === SLOT_ATTRIBUTE)
}
/**
* Transform a RiotParser.Node.Tag into a tag binding
* @param { RiotParser.Node.Tag } sourceNode - the custom tag
* @param { string } selectorAttribute - attribute needed to select the target node
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns { AST.Node } tag binding node
*/
export default function createTagBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(BINDING_TYPES),
builders.identifier(TAG_BINDING_TYPE),
false
)
),
simplePropertyNode(BINDING_GET_COMPONENT_KEY, builders.identifier(GET_COMPONENT_FN)),
simplePropertyNode(
BINDING_EVALUATE_KEY,
createCustomNodeNameEvaluationFunction(sourceNode, sourceFile, sourceCode)
),
simplePropertyNode(BINDING_SLOTS_KEY, createSlotsArray(sourceNode, sourceFile, sourceCode)),
simplePropertyNode(
BINDING_ATTRIBUTES_KEY,
createBindingAttributes(sourceNode, selectorAttribute, sourceFile, sourceCode)
),
...createSelectorProperties(selectorAttribute)
])
}

View File

@@ -0,0 +1,180 @@
import {
cloneNodeWithoutSelectorAttribute,
closeTag, createBindingSelector,
createNestedRootNode,
getChildrenNodes,
getNodeAttributes,
nodeToString
} from './utils'
import {
hasEachAttribute, hasIfAttribute,
hasItsOwnTemplate,
isCustomNode, isRemovableNode,
isRootNode,
isSlotNode,
isStaticNode,
isTagNode,
isTextNode,
isVoidNode
} from './checks'
import cloneDeep from '../../utils/clone-deep'
import eachBinding from './bindings/each'
import ifBinding from './bindings/if'
import {panic} from '@riotjs/util/misc'
import simpleBinding from './bindings/simple'
import slotBinding from './bindings/slot'
import tagBinding from './bindings/tag'
const BuildingState = Object.freeze({
html: [],
bindings: [],
parent: null
})
/**
* Nodes having bindings should be cloned and new selector properties should be added to them
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} bindingsSelector - temporary string to identify the current node
* @returns {RiotParser.Node} the original node parsed having the new binding selector attribute
*/
function createBindingsTag(sourceNode, bindingsSelector) {
if (!bindingsSelector) return sourceNode
return {
...sourceNode,
// inject the selector bindings into the node attributes
attributes: [{
name: bindingsSelector,
value: bindingsSelector
}, ...getNodeAttributes(sourceNode)]
}
}
/**
* Create a generic dynamic node (text or tag) and generate its bindings
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @param {BuildingState} state - state representing the current building tree state during the recursion
* @returns {Array} array containing the html output and bindings for the current node
*/
function createDynamicNode(sourceNode, sourceFile, sourceCode, state) {
switch (true) {
case isTextNode(sourceNode):
// text nodes will not have any bindings
return [nodeToString(sourceNode), []]
default:
return createTagWithBindings(sourceNode, sourceFile, sourceCode, state)
}
}
/**
* Create only a dynamic tag node with generating a custom selector and its bindings
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @param {BuildingState} state - state representing the current building tree state during the recursion
* @returns {Array} array containing the html output and bindings for the current node
*/
function createTagWithBindings(sourceNode, sourceFile, sourceCode) {
const bindingsSelector = isRootNode(sourceNode) ? null : createBindingSelector()
const cloneNode = createBindingsTag(sourceNode, bindingsSelector)
const tagOpeningHTML = nodeToString(cloneNode)
switch (true) {
case hasEachAttribute(cloneNode):
// EACH bindings have prio 1
return [tagOpeningHTML, [eachBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
case hasIfAttribute(cloneNode):
// IF bindings have prio 2
return [tagOpeningHTML, [ifBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
case isCustomNode(cloneNode):
// TAG bindings have prio 3
return [tagOpeningHTML, [tagBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
case isSlotNode(cloneNode):
// slot tag
return [tagOpeningHTML, [slotBinding(cloneNode, bindingsSelector)]]
default:
// this node has expressions bound to it
return [tagOpeningHTML, [simpleBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
}
}
/**
* Parse a node trying to extract its template and bindings
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @param {BuildingState} state - state representing the current building tree state during the recursion
* @returns {Array} array containing the html output and bindings for the current node
*/
function parseNode(sourceNode, sourceFile, sourceCode, state) {
// static nodes have no bindings
if (isStaticNode(sourceNode)) return [nodeToString(sourceNode), []]
return createDynamicNode(sourceNode, sourceFile, sourceCode, state)
}
/**
* Create the tag binding
* @param { RiotParser.Node.Tag } sourceNode - tag containing the each attribute
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @param { string } selector - binding selector
* @returns { Array } array with only the tag binding AST
*/
export function createNestedBindings(sourceNode, sourceFile, sourceCode, selector) {
const mightBeARiotComponent = isCustomNode(sourceNode)
const node = cloneNodeWithoutSelectorAttribute(sourceNode, selector)
return mightBeARiotComponent ? [null, [
tagBinding(
node,
null,
sourceFile,
sourceCode
)]
] : build(createNestedRootNode(node), sourceFile, sourceCode)
}
/**
* Build the template and the bindings
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @param {BuildingState} state - state representing the current building tree state during the recursion
* @returns {Array} array containing the html output and the dom bindings
*/
export default function build(
sourceNode,
sourceFile,
sourceCode,
state
) {
if (!sourceNode) panic('Something went wrong with your tag DOM parsing, your tag template can\'t be created')
const [nodeHTML, nodeBindings] = parseNode(sourceNode, sourceFile, sourceCode, state)
const childrenNodes = getChildrenNodes(sourceNode)
const canRenderNodeHTML = isRemovableNode(sourceNode) === false
const currentState = { ...cloneDeep(BuildingState), ...state }
// mutate the original arrays
canRenderNodeHTML && currentState.html.push(...nodeHTML)
currentState.bindings.push(...nodeBindings)
// do recursion if
// this tag has children and it has no special directives bound to it
if (childrenNodes.length && !hasItsOwnTemplate(sourceNode)) {
childrenNodes.forEach(node => build(node, sourceFile, sourceCode, { parent: sourceNode, ...currentState }))
}
// close the tag if it's not a void one
if (canRenderNodeHTML && isTagNode(sourceNode) && !isVoidNode(sourceNode)) {
currentState.html.push(closeTag(sourceNode))
}
return [
currentState.html.join(''),
currentState.bindings
]
}

View File

@@ -0,0 +1,231 @@
import {
IS_CUSTOM_NODE,
IS_SPREAD_ATTRIBUTE,
IS_VOID_NODE,
PROGRESS_TAG_NODE_NAME, SLOT_ATTRIBUTE,
SLOT_TAG_NODE_NAME,
TEMPLATE_TAG_NODE_NAME
} from './constants'
import {findAttribute, findEachAttribute, findIfAttribute, findIsAttribute, findKeyAttribute} from './find'
import {
getName,
getNodeAttributes
} from './utils'
import {isBrowserAPI, isBuiltinAPI, isNewExpression, isRaw} from '../../utils/ast-nodes-checks'
import compose from 'cumpa'
import {isNil} from '@riotjs/util/checks'
import {nodeTypes} from '@riotjs/parser'
import {types} from '../../utils/build-types'
/**
* True if the node has not expression set nor bindings directives
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only if it's a static node that doesn't need bindings or expressions
*/
export function isStaticNode(node) {
return [
hasExpressions,
findEachAttribute,
findIfAttribute,
isCustomNode,
isSlotNode
].every(test => !test(node))
}
/**
* Check if a node should be rendered in the final component HTML
* For example slot <template slot="content"> tags not using `each` or `if` directives can be removed
* see also https://github.com/riot/riot/issues/2888
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true if we can remove this tag from the component rendered HTML
*/
export function isRemovableNode(node) {
return isTemplateNode(node) && !isNil(findAttribute(SLOT_ATTRIBUTE, node)) && !hasEachAttribute(node) && !hasIfAttribute(node)
}
/**
* Check if a node name is part of the browser or builtin javascript api or it belongs to the current scope
* @param { types.NodePath } path - containing the current node visited
* @returns {boolean} true if it's a global api variable
*/
export function isGlobal({ scope, node }) {
// recursively find the identifier of this AST path
if (node.object) {
return isGlobal({ node: node.object, scope })
}
return Boolean(
isRaw(node) ||
isBuiltinAPI(node) ||
isBrowserAPI(node) ||
isNewExpression(node) ||
isNodeInScope(scope, node)
)
}
/**
* Checks if the identifier of a given node exists in a scope
* @param {Scope} scope - scope where to search for the identifier
* @param {types.Node} node - node to search for the identifier
* @returns {boolean} true if the node identifier is defined in the given scope
*/
function isNodeInScope(scope, node) {
const traverse = (isInScope = false) => {
types.visit(node, {
visitIdentifier(path) {
if (scope.lookup(getName(path.node))) {
isInScope = true
}
this.abort()
}
})
return isInScope
}
return traverse()
}
/**
* True if the node has the isCustom attribute set
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true if either it's a riot component or a custom element
*/
export function isCustomNode(node) {
return !!(node[IS_CUSTOM_NODE] || hasIsAttribute(node))
}
/**
* True the node is <slot>
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true if it's a slot node
*/
export function isSlotNode(node) {
return node.name === SLOT_TAG_NODE_NAME
}
/**
* True if the node has the isVoid attribute set
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true if the node is self closing
*/
export function isVoidNode(node) {
return !!node[IS_VOID_NODE]
}
/**
* True if the riot parser did find a tag node
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for the tag nodes
*/
export function isTagNode(node) {
return node.type === nodeTypes.TAG
}
/**
* True if the riot parser did find a text node
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for the text nodes
*/
export function isTextNode(node) {
return node.type === nodeTypes.TEXT
}
/**
* True if the node parsed is the root one
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for the root nodes
*/
export function isRootNode(node) {
return node.isRoot
}
/**
* True if the attribute parsed is of type spread one
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true if the attribute node is of type spread
*/
export function isSpreadAttribute(node) {
return node[IS_SPREAD_ATTRIBUTE]
}
/**
* True if the node is an attribute and its name is "value"
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for value attribute nodes
*/
export function isValueAttribute(node) {
return node.name === 'value'
}
/**
* True if the DOM node is a progress tag
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true for the progress tags
*/
export function isProgressNode(node) {
return node.name === PROGRESS_TAG_NODE_NAME
}
/**
* True if the DOM node is a <template> tag
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true for the progress tags
*/
export function isTemplateNode(node) {
return node.name === TEMPLATE_TAG_NODE_NAME
}
/**
* True if the node is an attribute and a DOM handler
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for dom listener attribute nodes
*/
export const isEventAttribute = (() => {
const EVENT_ATTR_RE = /^on/
return node => EVENT_ATTR_RE.test(node.name)
})()
/**
* Check if a string is an html comment
* @param {string} string - test string
* @returns {boolean} true if html comment
*/
export function isCommentString(string) {
return string.trim().indexOf('<!') === 0
}
/**
* True if the node has expressions or expression attributes
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} ditto
*/
export function hasExpressions(node) {
return !!(
node.expressions ||
// has expression attributes
(getNodeAttributes(node).some(attribute => hasExpressions(attribute))) ||
// has child text nodes with expressions
(node.nodes && node.nodes.some(node => isTextNode(node) && hasExpressions(node)))
)
}
/**
* True if the node is a directive having its own template
* @param {RiotParser.Node} node - riot parser node
* @returns {boolean} true only for the IF EACH and TAG bindings
*/
export function hasItsOwnTemplate(node) {
return [
findEachAttribute,
findIfAttribute,
isCustomNode
].some(test => test(node))
}
export const hasIfAttribute = compose(Boolean, findIfAttribute)
export const hasEachAttribute = compose(Boolean, findEachAttribute)
export const hasIsAttribute = compose(Boolean, findIsAttribute)
export const hasKeyAttribute = compose(Boolean, findKeyAttribute)

View File

@@ -0,0 +1,64 @@
import {constants} from '@riotjs/parser'
export const BINDING_TYPES = 'bindingTypes'
export const EACH_BINDING_TYPE = 'EACH'
export const IF_BINDING_TYPE = 'IF'
export const TAG_BINDING_TYPE = 'TAG'
export const SLOT_BINDING_TYPE = 'SLOT'
export const EXPRESSION_TYPES = 'expressionTypes'
export const ATTRIBUTE_EXPRESSION_TYPE = 'ATTRIBUTE'
export const VALUE_EXPRESSION_TYPE = 'VALUE'
export const TEXT_EXPRESSION_TYPE = 'TEXT'
export const EVENT_EXPRESSION_TYPE = 'EVENT'
export const TEMPLATE_FN = 'template'
export const SCOPE = '_scope'
export const GET_COMPONENT_FN = 'getComponent'
// keys needed to create the DOM bindings
export const BINDING_SELECTOR_KEY = 'selector'
export const BINDING_GET_COMPONENT_KEY = 'getComponent'
export const BINDING_TEMPLATE_KEY = 'template'
export const BINDING_TYPE_KEY = 'type'
export const BINDING_REDUNDANT_ATTRIBUTE_KEY = 'redundantAttribute'
export const BINDING_CONDITION_KEY = 'condition'
export const BINDING_ITEM_NAME_KEY = 'itemName'
export const BINDING_GET_KEY_KEY = 'getKey'
export const BINDING_INDEX_NAME_KEY = 'indexName'
export const BINDING_EVALUATE_KEY = 'evaluate'
export const BINDING_NAME_KEY = 'name'
export const BINDING_SLOTS_KEY = 'slots'
export const BINDING_EXPRESSIONS_KEY = 'expressions'
export const BINDING_CHILD_NODE_INDEX_KEY = 'childNodeIndex'
// slots keys
export const BINDING_BINDINGS_KEY = 'bindings'
export const BINDING_ID_KEY = 'id'
export const BINDING_HTML_KEY = 'html'
export const BINDING_ATTRIBUTES_KEY = 'attributes'
// DOM directives
export const IF_DIRECTIVE = 'if'
export const EACH_DIRECTIVE = 'each'
export const KEY_ATTRIBUTE = 'key'
export const SLOT_ATTRIBUTE = 'slot'
export const NAME_ATTRIBUTE = 'name'
export const IS_DIRECTIVE = 'is'
// Misc
export const DEFAULT_SLOT_NAME = 'default'
export const TEXT_NODE_EXPRESSION_PLACEHOLDER = ' '
export const BINDING_SELECTOR_PREFIX = 'expr'
export const SLOT_TAG_NODE_NAME = 'slot'
export const PROGRESS_TAG_NODE_NAME = 'progress'
export const TEMPLATE_TAG_NODE_NAME = 'template'
// Riot Parser constants
export const IS_RAW_NODE = constants.IS_RAW
export const IS_VOID_NODE = constants.IS_VOID
export const IS_CUSTOM_NODE = constants.IS_CUSTOM
export const IS_BOOLEAN_ATTRIBUTE = constants.IS_BOOLEAN
export const IS_SPREAD_ATTRIBUTE = constants.IS_SPREAD

View File

@@ -0,0 +1,36 @@
import {
ATTRIBUTE_EXPRESSION_TYPE,
BINDING_EVALUATE_KEY,
BINDING_NAME_KEY,
BINDING_TYPE_KEY,
EXPRESSION_TYPES
} from '../constants'
import {nullNode, simplePropertyNode} from '../../../utils/custom-ast-nodes'
import {builders} from '../../../utils/build-types'
import {createAttributeEvaluationFunction} from '../utils'
import {isSpreadAttribute} from '../checks'
/**
* Create a simple attribute expression
* @param {RiotParser.Node.Attr} sourceNode - the custom tag
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @returns {AST.Node} object containing the expression binding keys
*/
export default function createAttributeExpression(sourceNode, sourceFile, sourceCode) {
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(EXPRESSION_TYPES),
builders.identifier(ATTRIBUTE_EXPRESSION_TYPE),
false
)
),
simplePropertyNode(BINDING_NAME_KEY, isSpreadAttribute(sourceNode) ? nullNode() : builders.literal(sourceNode.name)),
simplePropertyNode(
BINDING_EVALUATE_KEY,
createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
)
])
}

View File

@@ -0,0 +1,34 @@
import {
BINDING_EVALUATE_KEY,
BINDING_NAME_KEY,
BINDING_TYPE_KEY,
EVENT_EXPRESSION_TYPE,
EXPRESSION_TYPES
} from '../constants'
import {builders} from '../../../utils/build-types'
import {createAttributeEvaluationFunction} from '../utils'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
/**
* Create a simple event expression
* @param {RiotParser.Node.Attr} sourceNode - attribute containing the event handlers
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @returns {AST.Node} object containing the expression binding keys
*/
export default function createEventExpression(sourceNode, sourceFile, sourceCode) {
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(EXPRESSION_TYPES),
builders.identifier(EVENT_EXPRESSION_TYPE),
false
)
),
simplePropertyNode(BINDING_NAME_KEY, builders.literal(sourceNode.name)),
simplePropertyNode(
BINDING_EVALUATE_KEY,
createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
)
])
}

View File

@@ -0,0 +1,34 @@
import {isEventAttribute, isProgressNode, isTextNode, isValueAttribute} from '../checks'
import attributeExpression from './attribute'
import eventExpression from './event'
import {findDynamicAttributes} from '../find'
import {hasValueAttribute} from 'dom-nodes'
import textExpression from './text'
import valueExpression from './value'
export function createExpression(sourceNode, sourceFile, sourceCode, childNodeIndex, parentNode) {
switch (true) {
case isTextNode(sourceNode):
return textExpression(sourceNode, sourceFile, sourceCode, childNodeIndex)
// progress nodes value attributes will be rendered as attributes
// see https://github.com/riot/compiler/issues/122
case isValueAttribute(sourceNode) && hasValueAttribute(parentNode.name) && !isProgressNode(parentNode):
return valueExpression(sourceNode, sourceFile, sourceCode)
case isEventAttribute(sourceNode):
return eventExpression(sourceNode, sourceFile, sourceCode)
default:
return attributeExpression(sourceNode, sourceFile, sourceCode)
}
}
/**
* Create the attribute expressions
* @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @returns {Array} array containing all the attribute expressions
*/
export function createAttributeExpressions(sourceNode, sourceFile, sourceCode) {
return findDynamicAttributes(sourceNode)
.map(attribute => createExpression(attribute, sourceFile, sourceCode, 0, sourceNode))
}

View File

@@ -0,0 +1,105 @@
import {
BINDING_CHILD_NODE_INDEX_KEY,
BINDING_EVALUATE_KEY,
BINDING_TYPE_KEY,
EXPRESSION_TYPES,
TEXT_EXPRESSION_TYPE
} from '../constants'
import {createArrayString, transformExpression, wrapASTInFunctionWithScope} from '../utils'
import {nullNode,simplePropertyNode} from '../../../utils/custom-ast-nodes'
import {builders} from '../../../utils/build-types'
import encodeHTMLEntities from '../../../utils/html-entities/encode'
import {isCommentString} from '../checks'
import {isLiteral} from '../../../utils/ast-nodes-checks'
import trimEnd from '../../../utils/trim-end'
import trimStart from '../../../utils/trim-start'
import unescapeChar from '../../../utils/unescape-char'
/**
* Generate the pure immutable string chunks from a RiotParser.Node.Text
* @param {RiotParser.Node.Text} node - riot parser text node
* @param {string} sourceCode sourceCode - source code
* @returns {Array} array containing the immutable string chunks
*/
function generateLiteralStringChunksFromNode(node, sourceCode) {
return node.expressions.reduce((chunks, expression, index) => {
const start = index ? node.expressions[index - 1].end : node.start
const string = encodeHTMLEntities(
sourceCode.substring(start, expression.start)
)
// trimStart the first string
chunks.push(index === 0 ? trimStart(string) : string)
// add the tail to the string
if (index === node.expressions.length - 1)
chunks.push(
encodeHTMLEntities(
trimEnd(sourceCode.substring(expression.end, node.end))
)
)
return chunks
}, [])
// comments are not supported here
.filter(str => !isCommentString(str))
.map(str => node.unescape ? unescapeChar(str, node.unescape) : str)
}
/**
* Simple bindings might contain multiple expressions like for example: "{foo} and {bar}"
* This helper aims to merge them in a template literal if it's necessary
* @param {RiotParser.Node} node - riot parser node
* @param {string} sourceFile - original tag file
* @param {string} sourceCode - original tag source code
* @returns { Object } a template literal expression object
*/
export function mergeNodeExpressions(node, sourceFile, sourceCode) {
if (node.parts.length === 1)
return transformExpression(node.expressions[0], sourceFile, sourceCode)
const pureStringChunks = generateLiteralStringChunksFromNode(node, sourceCode)
const stringsArray = pureStringChunks.reduce((acc, str, index) => {
const expr = node.expressions[index]
return [
...acc,
builders.literal(str),
expr ? transformExpression(expr, sourceFile, sourceCode) : nullNode()
]
}, [])
// filter the empty literal expressions
.filter(expr => !isLiteral(expr) || expr.value)
return createArrayString(stringsArray)
}
/**
* Create a text expression
* @param {RiotParser.Node.Text} sourceNode - text node to parse
* @param {string} sourceFile - source file path
* @param {string} sourceCode - original source
* @param {number} childNodeIndex - position of the child text node in its parent children nodes
* @returns {AST.Node} object containing the expression binding keys
*/
export default function createTextExpression(sourceNode, sourceFile, sourceCode, childNodeIndex) {
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(EXPRESSION_TYPES),
builders.identifier(TEXT_EXPRESSION_TYPE),
false
)
),
simplePropertyNode(
BINDING_CHILD_NODE_INDEX_KEY,
builders.literal(childNodeIndex)
),
simplePropertyNode(
BINDING_EVALUATE_KEY,
wrapASTInFunctionWithScope(
mergeNodeExpressions(sourceNode, sourceFile, sourceCode)
)
)
])
}

View File

@@ -0,0 +1,25 @@
import {
BINDING_EVALUATE_KEY,
BINDING_TYPE_KEY,
EXPRESSION_TYPES,
VALUE_EXPRESSION_TYPE
} from '../constants'
import {builders} from '../../../utils/build-types'
import {createAttributeEvaluationFunction} from '../utils'
import {simplePropertyNode} from '../../../utils/custom-ast-nodes'
export default function createValueExpression(sourceNode, sourceFile, sourceCode) {
return builders.objectExpression([
simplePropertyNode(BINDING_TYPE_KEY,
builders.memberExpression(
builders.identifier(EXPRESSION_TYPES),
builders.identifier(VALUE_EXPRESSION_TYPE),
false
)
),
simplePropertyNode(
BINDING_EVALUATE_KEY,
createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
)
])
}

View File

@@ -0,0 +1,47 @@
import {EACH_DIRECTIVE, IF_DIRECTIVE, IS_DIRECTIVE, KEY_ATTRIBUTE} from './constants'
import {getName, getNodeAttributes} from './utils'
import {hasExpressions} from './checks'
/**
* Find the attribute node
* @param { string } name - name of the attribute we want to find
* @param { riotParser.nodeTypes.TAG } node - a tag node
* @returns { riotParser.nodeTypes.ATTR } attribute node
*/
export function findAttribute(name, node) {
return node.attributes && node.attributes.find(attr => getName(attr) === name)
}
export function findIfAttribute(node) {
return findAttribute(IF_DIRECTIVE, node)
}
export function findEachAttribute(node) {
return findAttribute(EACH_DIRECTIVE, node)
}
export function findKeyAttribute(node) {
return findAttribute(KEY_ATTRIBUTE, node)
}
export function findIsAttribute(node) {
return findAttribute(IS_DIRECTIVE, node)
}
/**
* Find all the node attributes that are not expressions
* @param {RiotParser.Node} node - riot parser node
* @returns {Array} list of all the static attributes
*/
export function findStaticAttributes(node) {
return getNodeAttributes(node).filter(attribute => !hasExpressions(attribute))
}
/**
* Find all the node attributes that have expressions
* @param {RiotParser.Node} node - riot parser node
* @returns {Array} list of all the dynamic attributes
*/
export function findDynamicAttributes(node) {
return getNodeAttributes(node).filter(hasExpressions)
}

View File

@@ -0,0 +1,61 @@
import {callTemplateFunction, createRootNode, createTemplateDependenciesInjectionWrapper} from './utils'
import {TAG_TEMPLATE_PROPERTY} from '../../constants'
import build from './builder'
import {types} from '../../utils/build-types'
/**
* Create the content of the template function
* @param { RiotParser.Node } sourceNode - node generated by the riot compiler
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @returns {AST.BlockStatement} the content of the template function
*/
function createTemplateFunctionContent(sourceNode, sourceFile, sourceCode) {
return callTemplateFunction(
...build(
createRootNode(sourceNode),
sourceFile,
sourceCode
)
)
}
/**
* Extend the AST adding the new template property containing our template call to render the component
* @param { Object } ast - current output ast
* @param { string } sourceFile - source file path
* @param { string } sourceCode - original source
* @param { RiotParser.Node } sourceNode - node generated by the riot compiler
* @returns { Object } the output ast having the "template" key
*/
function extendTemplateProperty(ast, sourceFile, sourceCode, sourceNode) {
types.visit(ast, {
visitProperty(path) {
if (path.value.key.name === TAG_TEMPLATE_PROPERTY) {
path.value.value = createTemplateDependenciesInjectionWrapper(
createTemplateFunctionContent(sourceNode, sourceFile, sourceCode)
)
return false
}
this.traverse(path)
}
})
return ast
}
/**
* Generate the component template logic
* @param { RiotParser.Node } sourceNode - node generated by the riot compiler
* @param { string } source - original component source code
* @param { Object } meta - compilation meta information
* @param { AST } ast - current AST output
* @returns { AST } the AST generated
*/
export default function template(sourceNode, source, meta, ast) {
const { options } = meta
return extendTemplateProperty(ast, options.file, source, sourceNode)
}

File diff suppressed because it is too large Load Diff

205
node_modules/@riotjs/compiler/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,205 @@
import {TAG_CSS_PROPERTY, TAG_LOGIC_PROPERTY, TAG_NAME_PROPERTY, TAG_TEMPLATE_PROPERTY} from './constants'
import {callTemplateFunction, createTemplateDependenciesInjectionWrapper} from './generators/template/utils'
import {nullNode, simplePropertyNode} from './utils/custom-ast-nodes'
import {register as registerPostproc, execute as runPostprocessors} from './postprocessors'
import {register as registerPreproc, execute as runPreprocessor} from './preprocessors'
import build from './generators/template/builder'
import {builders} from './utils/build-types'
import compose from 'cumpa'
import {createSlotsArray} from './generators/template/bindings/tag'
import cssGenerator from './generators/css'
import curry from 'curri'
import generateJavascript from './utils/generate-javascript'
import hasHTMLOutsideRootNode from './utils/has-html-outside-root-node'
import isEmptyArray from './utils/is-empty-array'
import isEmptySourcemap from './utils/is-empty-sourcemap'
import javascriptGenerator from './generators/javascript'
import riotParser from '@riotjs/parser'
import sourcemapAsJSON from './utils/sourcemap-as-json'
import templateGenerator from './generators/template'
const DEFAULT_OPTIONS = {
template: 'default',
file: '[unknown-source-file]',
scopedCss: true
}
/**
* Create the initial AST
* @param {string} tagName - the name of the component we have compiled
* @returns { AST } the initial AST
*
* @example
* // the output represents the following string in AST
*/
export function createInitialInput({ tagName }) {
/*
generates
export default {
${TAG_CSS_PROPERTY}: null,
${TAG_LOGIC_PROPERTY}: null,
${TAG_TEMPLATE_PROPERTY}: null
}
*/
return builders.program([
builders.exportDefaultDeclaration(
builders.objectExpression([
simplePropertyNode(TAG_CSS_PROPERTY, nullNode()),
simplePropertyNode(TAG_LOGIC_PROPERTY, nullNode()),
simplePropertyNode(TAG_TEMPLATE_PROPERTY, nullNode()),
simplePropertyNode(TAG_NAME_PROPERTY, builders.literal(tagName))
])
)]
)
}
/**
* Make sure the input sourcemap is valid otherwise we ignore it
* @param {SourceMapGenerator} map - preprocessor source map
* @returns {Object} sourcemap as json or nothing
*/
function normaliseInputSourceMap(map) {
const inputSourceMap = sourcemapAsJSON(map)
return isEmptySourcemap(inputSourceMap) ? null : inputSourceMap
}
/**
* Override the sourcemap content making sure it will always contain the tag source code
* @param {Object} map - sourcemap as json
* @param {string} source - component source code
* @returns {Object} original source map with the "sourcesContent" property overridden
*/
function overrideSourcemapContent(map, source) {
return {
...map,
sourcesContent: [source]
}
}
/**
* Create the compilation meta object
* @param { string } source - source code of the tag we will need to compile
* @param { string } options - compiling options
* @returns {Object} meta object
*/
function createMeta(source, options) {
return {
tagName: null,
fragments: null,
options: {
...DEFAULT_OPTIONS,
...options
},
source
}
}
/**
* Parse a string to simply get its template AST
* @param { string } source - string to parse
* @param { Object } options - parser options
* @returns {Object} riot parser template output
*/
const parseSimpleString = (source, options) => {
const { parse } = riotParser(options)
return parse(source).output.template
}
/**
* Generate the component slots creation function from the root node
* @param { string } source - component outer html
* @param { Object } parserOptions - riot parser options
* @returns { string } content of the function that can be used to crate the slots in runtime
*/
export function generateSlotsFromString(source, parserOptions) {
return compose(
({ code }) => code,
generateJavascript,
createTemplateDependenciesInjectionWrapper,
createSlotsArray
)(parseSimpleString(source, parserOptions), DEFAULT_OPTIONS.file, source)
}
/**
* Generate the Riot.js binding template function from a template string
* @param { string } source - template string
* @param { Object } parserOptions - riot parser options
* @returns { string } Riot.js bindings template function generated
*/
export function generateTemplateFunctionFromString(source, parserOptions) {
return compose(
({ code }) => code,
generateJavascript,
callTemplateFunction
)(
...build(
parseSimpleString(source, parserOptions),
DEFAULT_OPTIONS.file,
source
)
)
}
/**
* Generate the output code source together with the sourcemap
* @param { string } source - source code of the tag we will need to compile
* @param { Object } opts - compiling options
* @returns { Output } object containing output code and source map
*/
export function compile(source, opts = {}) {
const meta = createMeta(source, opts)
const { options } = meta
const { code, map } = runPreprocessor('template', options.template, meta, source)
const { parse } = riotParser(options)
const { template, css, javascript } = parse(code).output
// see also https://github.com/riot/compiler/issues/130
if (hasHTMLOutsideRootNode(template || css || javascript, code, parse)) {
throw new Error('Multiple HTML root nodes are not supported')
}
// extend the meta object with the result of the parsing
Object.assign(meta, {
tagName: template.name,
fragments: { template, css, javascript }
})
return compose(
result => ({ ...result, meta }),
result => runPostprocessors(result, meta),
result => ({
...result,
map: overrideSourcemapContent(result.map, source)
}),
ast => meta.ast = ast && generateJavascript(ast, {
sourceMapName: `${options.file}.map`,
inputSourceMap: normaliseInputSourceMap(map)
}),
hookGenerator(templateGenerator, template, code, meta),
hookGenerator(javascriptGenerator, javascript, code, meta),
hookGenerator(cssGenerator, css, code, meta)
)(createInitialInput(meta))
}
/**
* Prepare the riot parser node transformers
* @param { Function } transformer - transformer function
* @param { Object } sourceNode - riot parser node
* @param { string } source - component source code
* @param { Object } meta - compilation meta information
* @returns { function(): Promise<Output> } Function what resolves to object containing output code and source map
*/
function hookGenerator(transformer, sourceNode, source, meta) {
const hasContent = sourceNode && (sourceNode.text || !isEmptyArray(sourceNode.nodes) || !isEmptyArray(sourceNode.attributes))
return hasContent ? curry(transformer)(sourceNode, source, meta) : result => result
}
// This function can be used to register new preprocessors
// a preprocessor can target either only the css or javascript nodes
// or the complete tag source file ('template')
export const registerPreprocessor = registerPreproc
// This function can allow you to register postprocessors that will parse the output code
// here we can run prettifiers, eslint fixes...
export const registerPostprocessor = registerPostproc

53
node_modules/@riotjs/compiler/src/postprocessors.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import composeSourcemaps from './utils/compose-sourcemaps'
import { createOutput } from './transformer'
import {panic} from '@riotjs/util/misc'
export const postprocessors = new Set()
/**
* Register a postprocessor that will be used after the parsing and compilation of the riot tags
* @param { Function } postprocessor - transformer that will receive the output code ans sourcemap
* @returns { Set } the postprocessors collection
*/
export function register(postprocessor) {
if (postprocessors.has(postprocessor)) {
panic(`This postprocessor "${postprocessor.name || postprocessor.toString()}" was already registered`)
}
postprocessors.add(postprocessor)
return postprocessors
}
/**
* Unregister a postprocessor
* @param { Function } postprocessor - possibly a postprocessor previously registered
* @returns { Set } the postprocessors collection
*/
export function unregister(postprocessor) {
if (!postprocessors.has(postprocessor)) {
panic(`This postprocessor "${postprocessor.name || postprocessor.toString()}" was never registered`)
}
postprocessors.delete(postprocessor)
return postprocessors
}
/**
* Exec all the postprocessors in sequence combining the sourcemaps generated
* @param { Output } compilerOutput - output generated by the compiler
* @param { Object } meta - compiling meta information
* @returns { Output } object containing output code and source map
*/
export function execute(compilerOutput, meta) {
return Array.from(postprocessors).reduce(function(acc, postprocessor) {
const { code, map } = acc
const output = postprocessor(code, meta)
return {
code: output.code,
map: composeSourcemaps(map, output.map)
}
}, createOutput(compilerOutput, meta))
}

72
node_modules/@riotjs/compiler/src/preprocessors.js generated vendored Normal file
View File

@@ -0,0 +1,72 @@
import {panic} from '@riotjs/util/misc'
import { transform } from './transformer'
/**
* Parsers that can be registered by users to preparse components fragments
* @type { Object }
*/
export const preprocessors = Object.freeze({
javascript: new Map(),
css: new Map(),
template: new Map().set('default', code => ({ code }))
})
// throw a processor type error
function preprocessorTypeError(type) {
panic(`No preprocessor of type "${type}" was found, please make sure to use one of these: 'javascript', 'css' or 'template'`)
}
// throw an error if the preprocessor was not registered
function preprocessorNameNotFoundError(name) {
panic(`No preprocessor named "${name}" was found, are you sure you have registered it?'`)
}
/**
* Register a custom preprocessor
* @param { string } type - preprocessor type either 'js', 'css' or 'template'
* @param { string } name - unique preprocessor id
* @param { Function } preprocessor - preprocessor function
* @returns { Map } - the preprocessors map
*/
export function register(type, name, preprocessor) {
if (!type) panic('Please define the type of preprocessor you want to register \'javascript\', \'css\' or \'template\'')
if (!name) panic('Please define a name for your preprocessor')
if (!preprocessor) panic('Please provide a preprocessor function')
if (!preprocessors[type]) preprocessorTypeError(type)
if (preprocessors[type].has(name)) panic(`The preprocessor ${name} was already registered before`)
preprocessors[type].set(name, preprocessor)
return preprocessors
}
/**
* Register a custom preprocessor
* @param { string } type - preprocessor type either 'js', 'css' or 'template'
* @param { string } name - unique preprocessor id
* @returns { Map } - the preprocessors map
*/
export function unregister(type, name) {
if (!type) panic('Please define the type of preprocessor you want to unregister \'javascript\', \'css\' or \'template\'')
if (!name) panic('Please define the name of the preprocessor you want to unregister')
if (!preprocessors[type]) preprocessorTypeError(type)
if (!preprocessors[type].has(name)) preprocessorNameNotFoundError(name)
preprocessors[type].delete(name)
return preprocessors
}
/**
* Exec the compilation of a preprocessor
* @param { string } type - preprocessor type either 'js', 'css' or 'template'
* @param { string } name - unique preprocessor id
* @param { Object } meta - preprocessor meta information
* @param { string } source - source code
* @returns { Output } object containing a sourcemap and a code string
*/
export function execute(type, name, meta, source) {
if (!preprocessors[type]) preprocessorTypeError(type)
if (!preprocessors[type].has(name)) preprocessorNameNotFoundError(name)
return transform(preprocessors[type].get(name), meta, source)
}

45
node_modules/@riotjs/compiler/src/transformer.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import createSourcemap from './utils/create-sourcemap'
export const Output = Object.freeze({
code: '',
ast: [],
meta: {},
map: null
})
/**
* Create the right output data result of a parsing
* @param { Object } data - output data
* @param { string } data.code - code generated
* @param { AST } data.ast - ast representing the code
* @param { SourceMapGenerator } data.map - source map generated along with the code
* @param { Object } meta - compilation meta infomration
* @returns { Output } output container object
*/
export function createOutput(data, meta) {
const output = {
...Output,
...data,
meta
}
if (!output.map && meta && meta.options && meta.options.file)
return {
...output,
map: createSourcemap({ file: meta.options.file })
}
return output
}
/**
* Transform the source code received via a compiler function
* @param { Function } compiler - function needed to generate the output code
* @param { Object } meta - compilation meta information
* @param { string } source - source code
* @returns { Output } output - the result of the compiler
*/
export function transform(compiler, meta, source) {
const result = (compiler ? compiler(source, meta) : { code: source })
return createOutput(result, meta)
}

View File

@@ -0,0 +1,13 @@
import getLineAndColumnByPosition from './get-line-and-column-by-position'
/**
* Add the offset to the code that must be parsed in order to generate properly the sourcemaps
* @param {string} input - input string
* @param {string} source - original source code
* @param {RiotParser.Node} node - node that we are going to transform
* @return {string} the input string with the offset properly set
*/
export default function addLineOffset(input, source, node) {
const {column, line} = getLineAndColumnByPosition(source, node.start)
return `${'\n'.repeat(line - 1)}${' '.repeat(column + 1)}${input}`
}

View File

@@ -0,0 +1,27 @@
import {builtin} from 'globals/globals.json'
import {namedTypes} from './build-types'
const browserAPIs = ['window', 'document', 'console']
const builtinAPIs = Object.keys(builtin)
export const isIdentifier = n => namedTypes.Identifier.check(n)
export const isLiteral = n => namedTypes.Literal.check(n)
export const isExpressionStatement = n => namedTypes.ExpressionStatement.check(n)
export const isThisExpression = n => namedTypes.ThisExpression.check(n)
export const isObjectExpression = n => namedTypes.ObjectExpression.check(n)
export const isThisExpressionStatement = n =>
isExpressionStatement(n) &&
isMemberExpression(n.expression.left) &&
isThisExpression(n.expression.left.object)
export const isNewExpression = n => namedTypes.NewExpression.check(n)
export const isSequenceExpression = n => namedTypes.SequenceExpression.check(n)
export const isExportDefaultStatement = n => namedTypes.ExportDefaultDeclaration.check(n)
export const isMemberExpression = n => namedTypes.MemberExpression.check(n)
export const isImportDeclaration = n => namedTypes.ImportDeclaration.check(n)
export const isTypeAliasDeclaration = n => namedTypes.TSTypeAliasDeclaration.check(n)
export const isInterfaceDeclaration = n => namedTypes.TSInterfaceDeclaration.check(n)
export const isExportNamedDeclaration = n => namedTypes.ExportNamedDeclaration.check(n)
export const isBrowserAPI = ({name}) => browserAPIs.includes(name)
export const isBuiltinAPI = ({name}) => builtinAPIs.includes(name)
export const isRaw = n => n && n.raw

View File

@@ -0,0 +1,5 @@
import {types as astTypes} from 'recast'
export const types = astTypes
export const builders = astTypes.builders
export const namedTypes = astTypes.namedTypes

View File

@@ -0,0 +1,8 @@
/**
* Simple clone deep function, do not use it for classes or recursive objects!
* @param {*} source - possibily an object to clone
* @returns {*} the object we wanted to clone
*/
export default function cloneDeep(source) {
return JSON.parse(JSON.stringify(source))
}

View File

@@ -0,0 +1,22 @@
import asJSON from './sourcemap-as-json'
import {composeSourceMaps} from 'recast/lib/util'
import {isNode} from '@riotjs/util/checks'
/**
* Compose two sourcemaps
* @param { SourceMapGenerator } formerMap - original sourcemap
* @param { SourceMapGenerator } latterMap - target sourcemap
* @returns { Object } sourcemap json
*/
export default function composeSourcemaps(formerMap, latterMap) {
if (
isNode() &&
formerMap && latterMap && latterMap.mappings
) {
return composeSourceMaps(asJSON(formerMap), asJSON(latterMap))
} else if (isNode() && formerMap) {
return asJSON(formerMap)
}
return {}
}

View File

@@ -0,0 +1,10 @@
import { SourceMapGenerator } from 'source-map'
/**
* Create a new sourcemap generator
* @param { Object } options - sourcemap options
* @returns { SourceMapGenerator } SourceMapGenerator instance
*/
export default function createSourcemap(options) {
return new SourceMapGenerator(options)
}

View File

@@ -0,0 +1,12 @@
import {builders} from './build-types'
export function nullNode() {
return builders.literal(null)
}
export function simplePropertyNode(key, value) {
const property = builders.property('init', builders.identifier(key), value, false)
property.sho
return property
}

View File

@@ -0,0 +1,19 @@
import {parse as customParser} from 'recast/parsers/typescript'
import {parse} from 'recast'
/**
* Parse a js source to generate the AST
* @param {string} source - javascript source
* @param {Object} options - parser options
* @returns {AST} AST tree
*/
export default function generateAST(source, options) {
return parse(source, {
parser: {
parse: (source, opts) => customParser(source, {
...opts,
ecmaVersion: 'latest'
})
},
...options
})
}

View File

@@ -0,0 +1,22 @@
import {parse as customParser} from 'recast/parsers/typescript'
import {print} from 'recast'
/**
* Generate the javascript from an ast source
* @param {AST} ast - ast object
* @param {Object} options - printer options
* @returns {Object} code + map
*/
export default function generateJavascript(ast, options) {
return print(ast, {
...options,
parser: {
parse: (source, opts) => customParser(source, {
...opts,
ecmaVersion: 'latest'
})
},
tabWidth: 2,
wrapColumn: 0,
quote: 'single'
})
}

View File

@@ -0,0 +1,16 @@
import splitStringByEOL from './split-string-by-EOL'
/**
* Get the line and the column of a source text based on its position in the string
* @param { string } string - target string
* @param { number } position - target position
* @returns { Object } object containing the source text line and column
*/
export default function getLineAndColumnByPosition(string, position) {
const lines = splitStringByEOL(string.slice(0, position))
return {
line: lines.length,
column: lines[lines.length - 1].length
}
}

View File

@@ -0,0 +1,24 @@
const ATTRIBUTE_TYPE_NAME = 'type'
/**
* Get the type attribute from a node generated by the riot parser
* @param { Object} sourceNode - riot parser node
* @returns { string|null } a valid type to identify the preprocessor to use or nothing
*/
export default function getPreprocessorTypeByAttribute(sourceNode) {
const typeAttribute = sourceNode.attributes ?
sourceNode.attributes.find(attribute => attribute.name === ATTRIBUTE_TYPE_NAME) :
null
return typeAttribute ? normalize(typeAttribute.value) : null
}
/**
* Remove the noise in case a user has defined the preprocessor type='text/scss'
* @param { string } value - input string
* @returns { string } normalized string
*/
function normalize(value) {
return value.replace('text/', '')
}

View File

@@ -0,0 +1,30 @@
import {isObject} from '@riotjs/util/checks'
/**
* Find whether there is html code outside of the root node
* @param {RiotParser.Node} root - node generated by the riot compiler
* @param {string} code - riot tag source code
* @param {Function} parse - riot parser function
* @returns {boolean} true if extra markup is detected
*/
export default function hasHTMLOutsideRootNode(root, code, parse) {
const additionalCode = root ? [
// head
code.substr(0, root.start),
// tail
code.substr(root.end, code.length)
].join('').trim() : ''
if (additionalCode) {
// if there are parsing errors we assume that there are no html
// tags outside of the root node
try {
const { template, javascript, css } = parse(additionalCode).output
return [template, javascript, css].some(isObject)
} catch (error) {
return false
}
}
return false
}

View File

@@ -0,0 +1,50 @@
import entities from './entities.json'
const HTMLEntityRe = /&(\S+);/g
const HEX_NUMBER = /^[\da-fA-F]+$/
const DECIMAL_NUMBER = /^\d+$/
/**
* Encode unicode hex html entities like for example &#x222;
* @param {string} string - input string
* @returns {string} encoded string
*/
export function encodeHex(string) {
const hex = string.substr(2)
return HEX_NUMBER.test(hex) ?
String.fromCodePoint(parseInt(hex, 16)) :
string
}
/**
* Encode unicode decimal html entities like for example &#222;
* @param {string} string - input string
* @returns {string} encoded string
*/
export function encodeDecimal(string) {
const nr = string.substr(1)
return DECIMAL_NUMBER.test(nr) ?
String.fromCodePoint(parseInt(nr, 10))
: string
}
/**
* Encode html entities in strings like &nbsp;
* @param {string} string - input string
* @returns {string} encoded string
*/
export default function encodeHTMLEntities(string) {
return string.replace(HTMLEntityRe, (match, entity) => {
const [firstChar, secondChar] = entity
if (firstChar === '#') {
return secondChar === 'x' ?
encodeHex(entity) :
encodeDecimal(entity)
} else {
return entities[entity] || entity
}
})
}

View File

@@ -0,0 +1,255 @@
{
"quot": "\u0022",
"amp": "&",
"apos": "\u0027",
"lt": "<",
"gt": ">",
"nbsp": "\u00A0",
"iexcl": "\u00A1",
"cent": "\u00A2",
"pound": "\u00A3",
"curren": "\u00A4",
"yen": "\u00A5",
"brvbar": "\u00A6",
"sect": "\u00A7",
"uml": "\u00A8",
"copy": "\u00A9",
"ordf": "\u00AA",
"laquo": "\u00AB",
"not": "\u00AC",
"shy": "\u00AD",
"reg": "\u00AE",
"macr": "\u00AF",
"deg": "\u00B0",
"plusmn": "\u00B1",
"sup2": "\u00B2",
"sup3": "\u00B3",
"acute": "\u00B4",
"micro": "\u00B5",
"para": "\u00B6",
"middot": "\u00B7",
"cedil": "\u00B8",
"sup1": "\u00B9",
"ordm": "\u00BA",
"raquo": "\u00BB",
"frac14": "\u00BC",
"frac12": "\u00BD",
"frac34": "\u00BE",
"iquest": "\u00BF",
"Agrave": "\u00C0",
"Aacute": "\u00C1",
"Acirc": "\u00C2",
"Atilde": "\u00C3",
"Auml": "\u00C4",
"Aring": "\u00C5",
"AElig": "\u00C6",
"Ccedil": "\u00C7",
"Egrave": "\u00C8",
"Eacute": "\u00C9",
"Ecirc": "\u00CA",
"Euml": "\u00CB",
"Igrave": "\u00CC",
"Iacute": "\u00CD",
"Icirc": "\u00CE",
"Iuml": "\u00CF",
"ETH": "\u00D0",
"Ntilde": "\u00D1",
"Ograve": "\u00D2",
"Oacute": "\u00D3",
"Ocirc": "\u00D4",
"Otilde": "\u00D5",
"Ouml": "\u00D6",
"times": "\u00D7",
"Oslash": "\u00D8",
"Ugrave": "\u00D9",
"Uacute": "\u00DA",
"Ucirc": "\u00DB",
"Uuml": "\u00DC",
"Yacute": "\u00DD",
"THORN": "\u00DE",
"szlig": "\u00DF",
"agrave": "\u00E0",
"aacute": "\u00E1",
"acirc": "\u00E2",
"atilde": "\u00E3",
"auml": "\u00E4",
"aring": "\u00E5",
"aelig": "\u00E6",
"ccedil": "\u00E7",
"egrave": "\u00E8",
"eacute": "\u00E9",
"ecirc": "\u00EA",
"euml": "\u00EB",
"igrave": "\u00EC",
"iacute": "\u00ED",
"icirc": "\u00EE",
"iuml": "\u00EF",
"eth": "\u00F0",
"ntilde": "\u00F1",
"ograve": "\u00F2",
"oacute": "\u00F3",
"ocirc": "\u00F4",
"otilde": "\u00F5",
"ouml": "\u00F6",
"divide": "\u00F7",
"oslash": "\u00F8",
"ugrave": "\u00F9",
"uacute": "\u00FA",
"ucirc": "\u00FB",
"uuml": "\u00FC",
"yacute": "\u00FD",
"thorn": "\u00FE",
"yuml": "\u00FF",
"OElig": "\u0152",
"oelig": "\u0153",
"Scaron": "\u0160",
"scaron": "\u0161",
"Yuml": "\u0178",
"fnof": "\u0192",
"circ": "\u02C6",
"tilde": "\u02DC",
"Alpha": "\u0391",
"Beta": "\u0392",
"Gamma": "\u0393",
"Delta": "\u0394",
"Epsilon": "\u0395",
"Zeta": "\u0396",
"Eta": "\u0397",
"Theta": "\u0398",
"Iota": "\u0399",
"Kappa": "\u039A",
"Lambda": "\u039B",
"Mu": "\u039C",
"Nu": "\u039D",
"Xi": "\u039E",
"Omicron": "\u039F",
"Pi": "\u03A0",
"Rho": "\u03A1",
"Sigma": "\u03A3",
"Tau": "\u03A4",
"Upsilon": "\u03A5",
"Phi": "\u03A6",
"Chi": "\u03A7",
"Psi": "\u03A8",
"Omega": "\u03A9",
"alpha": "\u03B1",
"beta": "\u03B2",
"gamma": "\u03B3",
"delta": "\u03B4",
"epsilon": "\u03B5",
"zeta": "\u03B6",
"eta": "\u03B7",
"theta": "\u03B8",
"iota": "\u03B9",
"kappa": "\u03BA",
"lambda": "\u03BB",
"mu": "\u03BC",
"nu": "\u03BD",
"xi": "\u03BE",
"omicron": "\u03BF",
"pi": "\u03C0",
"rho": "\u03C1",
"sigmaf": "\u03C2",
"sigma": "\u03C3",
"tau": "\u03C4",
"upsilon": "\u03C5",
"phi": "\u03C6",
"chi": "\u03C7",
"psi": "\u03C8",
"omega": "\u03C9",
"thetasym": "\u03D1",
"upsih": "\u03D2",
"piv": "\u03D6",
"ensp": "\u2002",
"emsp": "\u2003",
"thinsp": "\u2009",
"zwnj": "\u200C",
"zwj": "\u200D",
"lrm": "\u200E",
"rlm": "\u200F",
"ndash": "\u2013",
"mdash": "\u2014",
"lsquo": "\u2018",
"rsquo": "\u2019",
"sbquo": "\u201A",
"ldquo": "\u201C",
"rdquo": "\u201D",
"bdquo": "\u201E",
"dagger": "\u2020",
"Dagger": "\u2021",
"bull": "\u2022",
"hellip": "\u2026",
"permil": "\u2030",
"prime": "\u2032",
"Prime": "\u2033",
"lsaquo": "\u2039",
"rsaquo": "\u203A",
"oline": "\u203E",
"frasl": "\u2044",
"euro": "\u20AC",
"image": "\u2111",
"weierp": "\u2118",
"real": "\u211C",
"trade": "\u2122",
"alefsym": "\u2135",
"larr": "\u2190",
"uarr": "\u2191",
"rarr": "\u2192",
"darr": "\u2193",
"harr": "\u2194",
"crarr": "\u21B5",
"lArr": "\u21D0",
"uArr": "\u21D1",
"rArr": "\u21D2",
"dArr": "\u21D3",
"hArr": "\u21D4",
"forall": "\u2200",
"part": "\u2202",
"exist": "\u2203",
"empty": "\u2205",
"nabla": "\u2207",
"isin": "\u2208",
"notin": "\u2209",
"ni": "\u220B",
"prod": "\u220F",
"sum": "\u2211",
"minus": "\u2212",
"lowast": "\u2217",
"radic": "\u221A",
"prop": "\u221D",
"infin": "\u221E",
"ang": "\u2220",
"and": "\u2227",
"or": "\u2228",
"cap": "\u2229",
"cup": "\u222A",
"int": "\u222B",
"there4": "\u2234",
"sim": "\u223C",
"cong": "\u2245",
"asymp": "\u2248",
"ne": "\u2260",
"equiv": "\u2261",
"le": "\u2264",
"ge": "\u2265",
"sub": "\u2282",
"sup": "\u2283",
"nsub": "\u2284",
"sube": "\u2286",
"supe": "\u2287",
"oplus": "\u2295",
"otimes": "\u2297",
"perp": "\u22A5",
"sdot": "\u22C5",
"lceil": "\u2308",
"rceil": "\u2309",
"lfloor": "\u230A",
"rfloor": "\u230B",
"lang": "\u2329",
"rang": "\u232A",
"loz": "\u25CA",
"spades": "\u2660",
"clubs": "\u2663",
"hearts": "\u2665",
"diams": "\u2666"
}

View File

@@ -0,0 +1,8 @@
/**
* Ckeck if an Array-like object has empty length
* @param {Array} target - Array-like object
* @returns {boolean} target is empty or null
*/
export default function isEmptyArray(target) {
return !target || !target.length
}

View File

@@ -0,0 +1,10 @@
import isEmptyArray from './is-empty-array'
/**
* True if the sourcemap has no mappings, it is empty
* @param {Object} map - sourcemap json
* @returns {boolean} true if empty
*/
export default function isEmptySourcemap(map) {
return !map || isEmptyArray(map.mappings)
}

View File

@@ -0,0 +1,7 @@
const assert = {
ok: () => true,
strictEqual: () => true,
deepEqual: () => true
}
export default assert

View File

@@ -0,0 +1 @@
export const EOL = '\n'

View File

@@ -0,0 +1,19 @@
// mock the sourcemaps api for the browser bundle
// we do not need sourcemaps with the in browser compilation
const noop = function() {}
export const SourceMapGenerator = function() {
return {
addMapping: noop,
setSourceContent: noop,
toJSON: () => ({})
}
}
export const SourceMapConsumer = function() {}
export const SourceNode = function() {}
export default {
SourceNode,
SourceMapConsumer,
SourceMapGenerator
}

View File

@@ -0,0 +1,18 @@
import {execute as runPreprocessor} from '../preprocessors'
/**
* Preprocess a riot parser node
* @param { string } preprocessorType - either css, js
* @param { string } preprocessorName - preprocessor id
* @param { Object } meta - compilation meta information
* @param { RiotParser.nodeTypes } node - css node detected by the parser
* @returns { Output } code and sourcemap generated by the preprocessor
*/
export default function preprocess(preprocessorType, preprocessorName, meta, node) {
const code = node.text
return (preprocessorName ?
runPreprocessor(preprocessorType, preprocessorName, meta, code) :
{ code }
)
}

View File

@@ -0,0 +1,10 @@
/**
* Return a source map as JSON, it it has not the toJSON method it means it can
* be used right the way
* @param { SourceMapGenerator|Object } map - a sourcemap generator or simply an json object
* @returns { Object } the source map as JSON
*/
export default function sourcemapAsJSON(map) {
if (map && map.toJSON) return map.toJSON()
return map
}

View File

@@ -0,0 +1,10 @@
const LINES_RE = /\r\n?|\n/g
/**
* Split a string into a rows array generated from its EOL matches
* @param { string } string [description]
* @returns { Array } array containing all the string rows
*/
export default function splitStringByEOL(string) {
return string.split(LINES_RE)
}

9
node_modules/@riotjs/compiler/src/utils/trim-end.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/**
* Native String.prototype.trimEnd method with fallback to String.prototype.trimRight
* Edge doesn't support the first one
* @param {string} string - input string
* @returns {string} trimmed output
*/
export default function trimEnd(string) {
return (string.trimEnd || string.trimRight).apply(string)
}

View File

@@ -0,0 +1,9 @@
/**
* Native String.prototype.trimStart method with fallback to String.prototype.trimLeft
* Edge doesn't support the first one
* @param {string} string - input string
* @returns {string} trimmed output
*/
export default function trimStart(string) {
return (string.trimStart || string.trimLeft).apply(string)
}

View File

@@ -0,0 +1,9 @@
/**
* Unescape the user escaped chars
* @param {string} string - input string
* @param {string} char - probably a '{' or anything the user want's to escape
* @returns {string} cleaned up string
*/
export default function unescapeChar(string, char) {
return string.replace(RegExp(`\\\\${char}`, 'gm'), char)
}