import { ast, type CodeNode, type NodeKind } from '@kubb/ast' /** * What a piece of node text holds, so a fragment such as a type or a parameter list is parsed as one. */ export type InlineTextKind = 'code' | 'type' | 'value' | 'parameters' | 'typeParameters' // The string fields of each node kind and what they hold. `inherit` is the kind of the text around the node. const TEXT_FIELDS: Partial>>> = { Text: { value: 'inherit' }, Jsx: { value: 'inherit' }, Function: { params: 'parameters', generics: 'typeParameters', returnType: 'type' }, ArrowFunction: { params: 'parameters', generics: 'typeParameters', returnType: 'type' }, Const: { type: 'type' }, } // What the nested `nodes` of a node hold: a type's body, a constant's value, or code. const NESTED_KIND: Partial> = { Type: 'type', Const: 'value', Function: 'code', ArrowFunction: 'code' } /** * Rewrites every string field of `nodes`, passing what each one holds. JSDoc stays as written. */ export function rewriteNodes( nodes: Array | undefined, rewrite: (text: string, kind: InlineTextKind) => string, kind: InlineTextKind = 'code', ): Array | undefined { return nodes?.map((node): CodeNode => { // Backward-compat: compiled plugins may still pass bare strings at runtime if (typeof node === 'string') return rewrite(node, kind) as unknown as CodeNode if (node.kind === ast.node.kinds.break) return node const next = { ...node } as unknown as Record for (const [field, fieldKind] of Object.entries(TEXT_FIELDS[node.kind] ?? {})) { next[field] = rewriteField(next[field], (text) => rewrite(text, fieldKind === 'inherit' ? kind : fieldKind)) } if ('nodes' in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite, NESTED_KIND[node.kind] ?? kind) return next as unknown as CodeNode }) } function rewriteField(value: unknown, rewrite: (text: string) => string): unknown { if (Array.isArray(value)) return value.map(rewrite) return typeof value === 'string' && value ? rewrite(value) : value }