@mintlify/common
Version:
Commonly shared code within Mintlify
90 lines (89 loc) • 3.6 kB
JavaScript
import { visit } from 'unist-util-visit';
const dedent = (text) => {
const lines = text.split('\n');
const indents = lines
.filter((line) => line.trim().length > 0)
.map((line) => { var _a, _b, _c; return (_c = (_b = (_a = line.match(/^(\s*)/)) === null || _a === void 0 ? void 0 : _a[1]) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0; });
const minIndent = indents.length > 0 ? Math.min(...indents) : 0;
if (minIndent === 0)
return text;
return lines.map((line) => line.slice(minIndent)).join('\n');
};
export const remarkPrompt = () => {
return (tree, file) => {
const source = String(file.value);
visit(tree, 'mdxJsxFlowElement', (node) => {
if (node.name !== 'Prompt')
return;
if (!node.position)
return;
if (node.children.length === 0)
return;
const startOffset = node.position.start.offset;
const endOffset = node.position.end.offset;
if (startOffset === undefined || endOffset === undefined)
return;
const nodeSource = source.slice(startOffset, endOffset);
let inString = false;
let braceDepth = 0;
let openTagEnd = -1;
for (let i = 1; i < nodeSource.length; i++) {
const ch = nodeSource[i];
if (inString) {
if (ch === inString && nodeSource[i - 1] !== '\\')
inString = false;
continue;
}
if (ch === '"' || ch === "'") {
inString = ch;
continue;
}
if (ch === '{') {
braceDepth++;
continue;
}
if (ch === '}') {
braceDepth--;
continue;
}
if (ch === '>' && braceDepth === 0) {
openTagEnd = i + 1;
break;
}
}
if (openTagEnd === -1)
return;
const closingTagMatch = nodeSource.match(/<\/\s*Prompt\s*>$/);
if (!closingTagMatch)
return;
const closeTagStart = nodeSource.length - closingTagMatch[0].length;
const rawContent = nodeSource.slice(openTagEnd, closeTagStart);
const trimmedContent = dedent(rawContent.replace(/^\n/, '').replace(/\n$/, ''));
node.attributes.push({
type: 'mdxJsxAttribute',
name: 'children',
value: {
type: 'mdxJsxAttributeValueExpression',
value: JSON.stringify(trimmedContent),
data: {
estree: {
type: 'Program',
sourceType: 'module',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'Literal',
value: trimmedContent,
raw: JSON.stringify(trimmedContent),
},
},
],
},
},
},
});
node.children = [];
});
};
};