UNPKG

@macalinao/codama-renderers-js-esm

Version:

ESM-native TypeScript renderer for Codama JavaScript code generation

32 lines 1.69 kB
import { getRenderMapVisitor } from "@codama/renderers-js"; import { rootNodeVisitor, visit } from "codama"; import { ESM_DEPENDENCY_MAP } from "./constants.js"; /** * Codama visitor for rendering the code to be TypeScript compatible. * @param path * @returns */ export function renderESMTypeScriptVisitor(path) { return rootNodeVisitor((root) => { // Render the new files. const renderMap = visit(root, getRenderMapVisitor({ dependencyMap: ESM_DEPENDENCY_MAP, })); const index = renderMap.get("index.ts"); renderMap.add("index.ts", index.replace(/(export\s+\*\s+from\s+['"])(\.\/[^'"]+)(['"])/g, (_, prefix, path, quote) => `${prefix}${path}/index.js${quote}`)); renderMap.mapContent((code) => { const updated = code // .replace(/= 0x([\da-f]+), \/\//g, "= 0x$1; //") .replaceAll("process.env.NODE_ENV !== 'production'", "true") .replaceAll(";;", ";") // Add return type annotations for functions that return simple types .replace(/export const (\w+DISCRIMINATOR)\s*=\s*new Uint8Array\(/g, "export const $1: ReadonlyUint8Array = new Uint8Array(") .replace(/export function (get\w+DiscriminatorBytes)\(\)\s*{/g, "export function $1(): ReadonlyUint8Array {") .replace(/(export\s+\*\s+from\s+['"])(\.\/[^'"]+?)(?<!\.(js|ts|mjs|cjs|json))(['"])/g, (_, prefix, path) => `${prefix}${path}.js'`) .replace(/from\s+['"]\.['"]/g, 'from "./index.js"'); return updated; }); renderMap.write(path); }); } //# sourceMappingURL=render-esm-typescript-visitor.js.map