import type { Plugin, SourceDescription } from "rollup"; import type { FilterPattern } from "@rollup/pluginutils"; import { createFilter } from "@rollup/pluginutils"; import { getSwc } from "../swc/loadSwc"; import path from "path"; import { buildSourceLoc } from "../utils/source-loc"; export interface LitTemplateInjectionOptions { include?: FilterPattern; exclude?: FilterPattern; /** Attribute name to inject. Default: "data-source-loc" */ attributeName?: string; /** Tag names to skip injection on. */ skipTags?: string[]; /** Project root directory. Defaults to `process.cwd()`. */ rootDir?: string; } /** * Check that `html` is imported from the `lit` package. * Returns false if `html` is not imported or comes from a different package. */ function hasLitHtmlImport(ast: any): boolean { for (const item of ast.body) { if (item.type !== "ImportDeclaration") continue; for (const spec of item.specifiers) { if (spec.type !== "ImportSpecifier") continue; if (spec.local.value !== "html") continue; // `imported` is the exported name; when absent the local name equals the export const exportedName = spec.imported?.value ?? spec.local.value; if (exportedName === "html") { return item.source.value === "lit"; } } } return false; } function isHtmlTag(tag: any): boolean { return tag.type === "Identifier" && tag.value === "html"; } /** * Compute 1-based line and column from a 0-based character offset in source code. */ function offsetToLineCol( code: string, offset: number, ): { line: number; col: number } { let line = 1; let col = 1; for (let i = 0; i < offset && i < code.length; i++) { if (code[i] === "\n") { line++; col = 1; } else { col++; } } return { line, col }; } /** * Recursively walk an SWC AST node, calling `visitor` on every object with a `type` property. */ function walkSwcAst(node: any, visitor: (node: any) => void): void { if (!node || typeof node !== "object") return; if (node.type) visitor(node); for (const key of Object.keys(node)) { if (key === "span") continue; const child = node[key]; if (Array.isArray(child)) { for (const item of child) { walkSwcAst(item, visitor); } } else if (child && typeof child === "object") { walkSwcAst(child, visitor); } } } /** * Find the index of the first unquoted `>` in `str`, starting from index 0. * Returns -1 if no unquoted `>` is found. */ function findUnquotedClose(str: string): number { let quote: string | null = null; for (let i = 0; i < str.length; i++) { const ch = str[i]; if (quote) { if (ch === quote) quote = null; } else if (ch === '"' || ch === "'") { quote = ch; } else if (ch === ">") { return i; } } return -1; } /** * Inject attributes into HTML opening tags found in a quasi string. * Returns the modified string, or the original if no changes were made. */ function injectIntoQuasi( raw: string, quasiStart0: number, code: string, id: string, attributeName: string, skipTagSet: Set, ): { result: string; injected: boolean } { const OPENING_TAG_RE = /<([a-zA-Z][a-zA-Z0-9-]*)/g; // Collect insertions in reverse order so earlier indices stay valid const insertions: { index: number; text: string }[] = []; let match; while ((match = OPENING_TAG_RE.exec(raw)) !== null) { const tagName = match[1]; if (skipTagSet.has(tagName.toLowerCase())) continue; // Check if attribute already exists in remaining tag content const afterTag = raw.slice(match.index + match[0].length); const closingIdx = findUnquotedClose(afterTag); const tagAttrs = closingIdx >= 0 ? afterTag.slice(0, closingIdx) : afterTag; if (tagAttrs.includes(attributeName)) continue; // Position of the `<` that opens this tag (0-based in source) const tagOpenOffset = quasiStart0 + match.index; const { line, col } = offsetToLineCol(code, tagOpenOffset); const locationId = buildSourceLoc(id, line, col); insertions.push({ index: match.index + match[0].length, text: ` ${attributeName}="${locationId}"`, }); } if (insertions.length === 0) return { result: raw, injected: false }; // Apply insertions from end to start to preserve indices let result = raw; for (let i = insertions.length - 1; i >= 0; i--) { const { index, text } = insertions[i]; result = result.slice(0, index) + text + result.slice(index); } return { result, injected: true }; } export default function litTemplateInjection( options: LitTemplateInjectionOptions = {}, ): Plugin { const { include = ["**/*.{ts,js,mjs,cjs,tsx,jsx}"], exclude, attributeName = "data-source-loc", skipTags = [], rootDir = process.cwd(), } = options; const filter = createFilter(include, exclude); const skipTagSet = new Set(skipTags.map((t) => t.toLowerCase())); return { name: "lit-template-injection", async transform( code: string, id: string, ): Promise { if (!filter(id)) return null; if (!code.includes("from 'lit'") && !code.includes('from "lit"')) return null; // Fast fail to avoid parsing using trivial heuristic const swc = await getSwc(); const ast = await swc.parse(code, { syntax: "typescript", decorators: true, }); // SWC accumulates byte offsets across parse calls; normalize // all spans relative to the module's start so they become 0-based // source positions. const baseOffset = ast.span.start; if (!hasLitHtmlImport(ast)) return null; // Bail before we walk if this isn't a Lit file const relativeId = path.relative(rootDir, id).replace(/\\/g, "/"); let modified = false; walkSwcAst(ast, (node: any) => { if (node.type === "TaggedTemplateExpression" && isHtmlTag(node.tag)) { for (const quasi of node.template.quasis) { const quasiStart0 = quasi.span.start - baseOffset; const { result, injected } = injectIntoQuasi( quasi.raw, quasiStart0, code, relativeId, attributeName, skipTagSet, ); if (injected) { quasi.raw = result; quasi.cooked = result; modified = true; } } } }); if (!modified) return null; // Don't pay to serialize if we didn't modified anything const printed = await swc.print(ast, { sourceMaps: true, inputSourceMap: true, }); return { code: printed.code, map: printed.map ? JSON.parse(printed.map) : undefined, }; }, } as Plugin; }