UNPKG

1.93 kBJavaScriptView Raw
1const IMPORT_REGEX = /^import\s/
2const EXPORT_REGEX = /^export\s/
3const EXPORT_DEFAULT_REGEX = /^export default\s/
4const STARTS_WITH_CAPITAL_LETTER_REGEX = /^[A-Z]/
5const EMPTY_NEWLINE = '\n\n'
6const COMMENT_OPEN = '<!--'
7const COMMENT_CLOSE = '-->'
8
9const isImport = text => IMPORT_REGEX.test(text)
10const isExport = text => EXPORT_REGEX.test(text)
11const isExportDefault = text => EXPORT_DEFAULT_REGEX.test(text)
12const isImportOrExport = text => isImport(text) || isExport(text)
13
14const isComment = str =>
15 str.startsWith(COMMENT_OPEN) && str.endsWith(COMMENT_CLOSE)
16
17const getCommentContents = str =>
18 str.slice(COMMENT_OPEN.length, -COMMENT_CLOSE.length)
19
20const startsWithCapitalLetter = str =>
21 STARTS_WITH_CAPITAL_LETTER_REGEX.test(str)
22
23const paramCase = string =>
24 string
25 .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
26 .replace(/([a-z])([0-9])/g, '$1-$2')
27 .toLowerCase()
28
29const toTemplateLiteral = text => {
30 const escaped = text
31 .replace(/\\(?!\$)/g, '\\\\') // Escape all "\" to avoid unwanted escaping in text nodes
32 // and ignore "\$" since it's already escaped and is common
33 // with prettier https://github.com/mdx-js/mdx/issues/606
34 .replace(/`/g, '\\`') // Escape "`"" since
35 .replace(/(\\\$)/g, '\\$1') // Escape \$ so render it as it is
36 .replace(/(\\\$)(\{)/g, '\\$1\\$2') // Escape \${} so render it as it is
37 .replace(/\$\{/g, '\\${') // Escape ${} in text so that it doesn't eval
38
39 return '{`' + escaped + '`}'
40}
41
42module.exports.EMPTY_NEWLINE = EMPTY_NEWLINE
43module.exports.isImport = isImport
44module.exports.isExport = isExport
45module.exports.isExportDefault = isExportDefault
46module.exports.isImportOrExport = isImportOrExport
47module.exports.startsWithCapitalLetter = startsWithCapitalLetter
48module.exports.isComment = isComment
49module.exports.getCommentContents = getCommentContents
50module.exports.paramCase = paramCase
51module.exports.toTemplateLiteral = toTemplateLiteral