1. Architectural Update Overview

We want to extend the meld tool beyond simple @cmd[...] placeholders into @import[...] placeholders that pull in markdown sections or code artifacts. The key challenges are:
	1.	Markdown Imports:
	•	Identify a heading (like # Installation) in a target file.
	•	Grab content until the next heading (ignoring headings in code fences).
	•	Potentially re-level headings (as ###) or rename the heading (as ### My Title).
	•	Fail hard if the heading or file is missing, or if multiple matches exist.
	2.	Code Imports:
	•	Import named exports (e.g. myFunction, or a bracketed list [myFunc, otherFunc]) from TypeScript/JS.
	•	Potentially import entire interface/type definitions.
	•	Fail if the symbol isn’t found, or multiple matches exist.
	3.	Path Aliases:
	•	Instead of direct paths, allow referencing aliases (e.g. @docs/setup.md → ../docs/setup.md).
	•	These aliases come from a meldconfig.json or a global ~/.meldrc.
	4.	Separating Concerns:
	•	The existing meld.ts is already large. We’ll split out logic for command extraction, import resolution, markdown parsing, code parsing, and path alias resolution into distinct modules.

New Modules (High-Level)
	1.	extractPlaceholders.ts
	•	Reads the input file and extracts both @cmd[...] and @import[...] placeholders.
	•	Distinguishes which placeholders are commands vs. imports.
	•	Returns an array of “placeholder” objects containing all relevant data.
	2.	importResolver.ts
	•	Receives an “import” placeholder (with path & optional symbol).
	•	Figures out if it’s a markdown or code import.
	•	Dispatches to either markdownImporter.ts or codeImporter.ts.
	3.	markdownImporter.ts
	•	Locates the heading in the file.
	•	Collects content until the next heading (accounting for code fences).
	•	Performs heading level adjustments.
	•	Optionally renames the heading.
	•	Returns a string to embed.
	4.	codeImporter.ts
	•	Uses a simple TypeScript/AST parse or a regex-based approach (depending on complexity).
	•	Finds the symbol(s) requested.
	•	Returns the relevant code snippet.
	•	Errors if symbols aren’t found or duplicates exist.
	5.	aliasResolver.ts
	•	Loads local config (meldconfig.json) and global config (~/.meldrc) for path aliases.
	•	Rewrites @docs/setup.md → ../docs/setup.md.
	6.	meldCore.ts (Refactor of Meld)
	•	Orchestrates everything:
	•	Loads input file.
	•	Uses extractPlaceholders to parse out placeholders (both @cmd[...] and @import[...]).
	•	For each placeholder, if it’s:
	•	@cmd → run the existing command logic (shell execution).
	•	@import → use aliasResolver → call importResolver.
	•	Replaces each placeholder in the final doc with the result.

2. The Most Challenging, Complex Parts (with Full Implementations)

Below are the three code pieces most likely to trip up less experienced devs:
	1.	extractPlaceholders.ts:
	•	Correctly distinguishing @cmd[...] vs. @import[...].
	•	Handling multiple placeholders on the same line.
	•	Capturing all relevant arguments (e.g., file path, symbol, heading, as ###, etc.).
	2.	markdownImporter.ts:
	•	Matching a heading (like Installation) but ignoring that heading if it’s inside a fenced code block.
	•	Extracting content only until the next heading.
	•	Re-leveling headings if requested.
	•	Overriding the heading text if requested.
	•	Enforcing no duplicates.
	3.	codeImporter.ts:
	•	Locating named exports, or bracket sets of exports, from a TypeScript file.
	•	Handling edge cases like re-exports or default exports.
	•	Returning the correct snippet in a stable format, or raising an error if the symbol can’t be found.

We’ll write out the full implementations for those three. Everything else (boilerplate CLI updates, basic class scaffolding, config, etc.) can be handled by an AI or simpler dev tasks.

2.1 extractPlaceholders.ts

/**
 * extractPlaceholders.ts
 *
 * Scans the input Markdown for both @cmd[...] and @import[...] directives.
 * Returns a unified array of Placeholder objects with a type field:
 *   - type: 'cmd' | 'import'
 *   - raw: entire directive including @cmd[...] or @import[...]
 *   - lineNumber: line number in the input
 *   - details: { filePath, heading, symbolList, headingLevelOverride, headingTextOverride, ... }
 */
 
export interface Placeholder {
  type: 'cmd' | 'import';
  raw: string;
  lineNumber: number;
  // For `@cmd`:
  command?: string;
  // For `@import`:
  importPath?: string;
  importSymbol?: string;           // e.g. "myFunction", or "Endpoints", or "{interface}"
  importSymbolList?: string[];     // For multiple imports: [myFunc, otherFunc]
  heading?: string;                // e.g. "Installation"
  headingLevelOverride?: string;   // e.g. ###
  headingTextOverride?: string;    // e.g. "Quick Start"
}

const CMD_REGEX = /@cmd\[(?<command>[^\]]+)\]/g;
const IMPORT_REGEX = /@import\[(?<importSpec>[^\]]+)\](?:\s+as\s+(?<asSpec>[^\r\n]+))?/g;

/**
 * Extract placeholders from raw doc text.
 */
export function extractPlaceholders(content: string): Placeholder[] {
  const lines = content.split('\n');
  const placeholders: Placeholder[] = [];

  for (let i = 0; i < lines.length; i++) {
    const lineNumber = i + 1;
    let line = lines[i];

    // 1) Check for @cmd[...] placeholders
    let cmdMatch: RegExpExecArray | null;
    while ((cmdMatch = CMD_REGEX.exec(line)) !== null) {
      const cmdStr = cmdMatch.groups?.command.trim() ?? '';
      placeholders.push({
        type: 'cmd',
        raw: cmdMatch[0],
        lineNumber,
        command: cmdStr
      });
    }

    // 2) Check for @import[...] placeholders
    let importMatch: RegExpExecArray | null;
    while ((importMatch = IMPORT_REGEX.exec(line)) !== null) {
      const rawDirective = importMatch[0];
      const importSpec = importMatch.groups?.importSpec.trim() ?? '';
      const asSpec = importMatch.groups?.asSpec?.trim() ?? '';

      // parse something like "../docs/setup.md # Installation"
      // or "src/meld.ts # myFunction"
      // or "src/meld.ts # [myFunction, otherFunction]"
      // or "src/meld.ts # {interface}"

      // We'll do a basic approach: split on `#` to see if there's a heading or symbol
      const [filePathRaw, maybeSymbolRaw] = importSpec.split('#').map(s => s.trim());

      let filePath = filePathRaw;
      let importSymbol: string | undefined;
      let importSymbolList: string[] | undefined;
      let heading: string | undefined;

      if (maybeSymbolRaw) {
        // possible forms: 
        //   "Installation"
        //   "[myFunction, otherFunction]"
        //   "{interface}"
        //   "myFunction"
        // We'll do a quick test for bracket or brace
        if (maybeSymbolRaw.startsWith('[')) {
          // e.g. [myFunction, otherFunction]
          // Strip outer [ ] and split by comma
          const inside = maybeSymbolRaw.replace(/^\[|\]$/g, '');
          importSymbolList = inside.split(',').map(x => x.trim()).filter(Boolean);
        } else if (maybeSymbolRaw.startsWith('{')) {
          // e.g. {interface}
          // We treat that as importSymbol with braces
          importSymbol = maybeSymbolRaw;
        } else {
          // treat it as a heading or single symbol
          importSymbol = maybeSymbolRaw;
        }

        // If it's purely textual with spaces, likely a heading
        // We'll guess: If there's a space, treat it as heading
        // else treat it as code symbol
        if (importSymbol && /\s+/.test(importSymbol) && !importSymbol.startsWith('{')) {
          heading = importSymbol;
          importSymbol = undefined;
        }
      }

      // parse asSpec
      // e.g. "### Quick Start" => headingLevelOverride = "###", headingTextOverride = "Quick Start"
      let headingLevelOverride: string | undefined;
      let headingTextOverride: string | undefined;
      if (asSpec) {
        // We'll split by space for the first chunk that is entirely # 
        // e.g. "### Quick Start"
        // or maybe just "###"
        const parts = asSpec.split(/\s+/, 2);
        const firstPart = parts[0];
        if (/^#+$/.test(firstPart)) {
          headingLevelOverride = firstPart;
          if (parts.length > 1) {
            headingTextOverride = asSpec.replace(firstPart, '').trim();
          }
        } else {
          // the entire thing might be heading text override
          headingTextOverride = asSpec;
        }
      }

      placeholders.push({
        type: 'import',
        raw: rawDirective,
        lineNumber,
        importPath: filePath,
        importSymbol,
        importSymbolList,
        heading,
        headingLevelOverride,
        headingTextOverride
      });
    }
  }

  return placeholders;
}

Key Complexity:
	1.	We have to parse both @cmd[...] and @import[...] from each line (they can coexist on one line).
	2.	@import[...] can contain file paths, headings, or code symbols—some with brackets or braces.
	3.	We handle optional as ### or as ### Some Title.
	4.	We do just enough logic to differentiate heading vs. code symbol—not bulletproof but workable.

2.2 markdownImporter.ts

/**
 * markdownImporter.ts
 * 
 * Extracts a section of a markdown file from a given heading to the next heading.
 * Ignores headings within fenced code blocks.
 * Also supports re-leveling headings (e.g. # -> ##) if requested
 * and renaming the heading if requested.
 */

import { readFileSync, existsSync } from 'fs';

interface MarkdownImportOptions {
  filePath: string;
  heading: string;              // e.g. "Installation"
  headingLevelOverride?: string;  // e.g. ###
  headingTextOverride?: string;   // e.g. "Quick Start"
}

/**
 * Return the substring of the markdown file from the matched heading 
 * to the next heading (or end of file), ignoring headings in code fences.
 */
export function importMarkdownSection(opts: MarkdownImportOptions): string {
  const { filePath, heading, headingLevelOverride, headingTextOverride } = opts;

  if (!existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  const content = readFileSync(filePath, 'utf-8');
  const lines = content.split('\n');

  let inCodeFence = false;
  let matchedStartIndex: number | null = null;

  // We track headings as lines starting with 1-6 #, ignoring code fence sections
  for (let i = 0; i < lines.length; i++) {
    let line = lines[i];

    // Toggle code fence
    if (/^```/.test(line.trim())) {
      inCodeFence = !inCodeFence;
      continue;
    }

    // If in code fence, skip heading detection
    if (inCodeFence) continue;

    // e.g. look for ^#{1,6}\s+Installation
    // but we don't care about how many # exactly, just "some # + some heading text"
    const headingMatch = line.match(/^(\#{1,6})\s+(.*)$/);
    if (headingMatch) {
      // e.g. headingMatch[1] = ###
      // headingMatch[2] = rest of heading text
      const foundHeadingText = headingMatch[2].trim();

      // If we haven't matched yet, check if this heading is the one
      if (matchedStartIndex === null) {
        // "dumb matching": if foundHeadingText === heading, we start
        if (foundHeadingText === heading) {
          matchedStartIndex = i;
        }
      } else {
        // We've already matched the start; we've hit the next heading => stop
        // We'll slice up to i
        const extracted = lines.slice(matchedStartIndex, i).join('\n');
        return adjustHeadingAndTitle(extracted, headingLevelOverride, headingTextOverride);
      }
    }
  }

  // If we found a start heading but never found the next heading
  if (matchedStartIndex !== null) {
    const remainder = lines.slice(matchedStartIndex).join('\n');
    return adjustHeadingAndTitle(remainder, headingLevelOverride, headingTextOverride);
  }

  throw new Error(`Heading not found in ${filePath}: "${heading}"`);
}

/**
 * Utility: If headingLevelOverride is provided (e.g. "###"), 
 * we replace the first line's # level with that. 
 * If headingTextOverride is provided, replace that text as well.
 *
 * For instance, if the extracted text starts with:
 *   ## Installation
 *  and headingLevelOverride = "###", headingTextOverride = "Quick Start"
 *  => "### Quick Start"
 */
function adjustHeadingAndTitle(extracted: string, headingLevel: string | undefined, headingText: string | undefined): string {
  if (!headingLevel && !headingText) {
    return extracted;
  }

  const lines = extracted.split('\n');
  if (lines.length === 0) return extracted;

  // Typically, the first line is the heading
  let firstLine = lines[0];
  const headingMatch = firstLine.match(/^(\#{1,6})\s+(.*)$/);
  if (!headingMatch) {
    // no heading => return as is
    return extracted;
  }

  const originalHashes = headingMatch[1];
  const originalText = headingMatch[2];

  let newHashes = headingLevel ?? originalHashes;
  let newText = headingText ?? originalText;

  lines[0] = `${newHashes} ${newText}`;
  return lines.join('\n');
}

Key Complexity:
	1.	Handling code fences so that headings in code blocks don’t register as real headings.
	2.	“Dumb matching” logic for heading text.
	3.	Stopping at the next heading (or end of file).
	4.	Overriding heading level or heading text.

2.3 codeImporter.ts

/**
 * codeImporter.ts
 *
 * Extracts named exports from a TypeScript or JS file. 
 * We can do this with a simple AST parse if we're comfortable using the TS compiler,
 * or a quick regex approach for minimal overhead. Below is a simplified approach using
 * TypeScript's compiler API for robust symbol matching. 
 */

import * as ts from 'typescript';
import { existsSync, readFileSync } from 'fs';

export interface CodeImportOptions {
  filePath: string;
  // One of:
  //   - importSymbol: "myFunction"
  //   - importSymbolList: ["myFunc", "otherFunc"]
  //   - importSymbol: "{interface}" means "pull entire interface" (or type)
}
 
export function importCodeSnippet(opts: CodeImportOptions): string {
  const { filePath } = opts;
  if (!existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }
  const content = readFileSync(filePath, 'utf-8');

  // We'll parse a source file
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.ESNext, true);

  if (opts.importSymbolList && opts.importSymbolList.length > 0) {
    // multiple named imports
    let results: string[] = [];
    for (const sym of opts.importSymbolList) {
      results.push(extractSymbol(sourceFile, sym));
    }
    return results.join('\n\n');
  } else if (opts.importSymbol) {
    // single
    return extractSymbol(sourceFile, opts.importSymbol);
  }

  throw new Error(`No symbol provided to import from ${filePath}`);
}

/**
 * Attempt to find a top-level export with the given name.
 * If it's {interface} or {type}, we attempt to extract all declared interfaces or types.
 */
function extractSymbol(sourceFile: ts.SourceFile, symbolName: string): string {
  const isInterfaceWildcard = symbolName.startsWith('{interface}');
  const isTypeWildcard = symbolName.startsWith('{type}');

  if (isInterfaceWildcard || isTypeWildcard) {
    // gather all exported interfaces or types
    let snippetParts: string[] = [];
    sourceFile.forEachChild((node) => {
      if (ts.isInterfaceDeclaration(node) && isInterfaceWildcard) {
        if (hasExportModifier(node)) {
          snippetParts.push(node.getText(sourceFile));
        }
      }
      if (ts.isTypeAliasDeclaration(node) && isTypeWildcard) {
        if (hasExportModifier(node)) {
          snippetParts.push(node.getText(sourceFile));
        }
      }
    });
    if (snippetParts.length === 0) {
      throw new Error(`No exported ${isInterfaceWildcard ? 'interface' : 'type'} found.`);
    }
    return snippetParts.join('\n\n');
  }

  // normal single symbol
  // We'll look for: 
  // - function myFunction() export
  // - export function myFunction() ...
  // - export const myFunction = ...
  // - interface myFunction ... (with export)
  // etc.
  let found: string[] = [];

  sourceFile.forEachChild((node) => {
    // check if node is exported with the name symbolName
    if (isExportedNamedDeclaration(node, symbolName, sourceFile)) {
      found.push(node.getText(sourceFile));
    }
  });

  if (found.length === 0) {
    throw new Error(`Symbol not found or not exported: ${symbolName}`);
  }
  if (found.length > 1) {
    throw new Error(`Multiple exports match the symbol: ${symbolName}`);
  }

  return found[0];
}

function hasExportModifier(node: ts.Node): boolean {
  return !!node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);
}

/**
 * Checks if the node is an exported declaration with a matching name.
 */
function isExportedNamedDeclaration(
  node: ts.Node, 
  symbolName: string, 
  sourceFile: ts.SourceFile
): boolean {
  // e.g. "export function myFunction()"
  if (ts.isFunctionDeclaration(node) && node.name?.text === symbolName) {
    return hasExportModifier(node);
  }
  // e.g. "export const myFunction = ..."
  if (ts.isVariableStatement(node) && hasExportModifier(node)) {
    // Could have multiple decls in one statement
    for (const decl of node.declarationList.declarations) {
      if (ts.isIdentifier(decl.name) && decl.name.text === symbolName) {
        return true;
      }
    }
  }
  // e.g. "export interface myFunction { ... }"
  if (ts.isInterfaceDeclaration(node) && node.name.text === symbolName) {
    return hasExportModifier(node);
  }
  // e.g. "export type myFunction = ..."
  if (ts.isTypeAliasDeclaration(node) && node.name.text === symbolName) {
    return hasExportModifier(node);
  }
  // you could add class, enum, etc. as needed

  return false;
}

Key Complexity:
	1.	Using the TypeScript API for robust detection.
	2.	Handling “wildcard” requests like {interface} or {type}.
	3.	Enforcing single match for normal named imports.
	4.	Export checking.

3. Extremely Detailed Plan for the Rest

3.1 Create “aliasResolver.ts”
	1.	Read meldconfig.json in the local project root if present.
	2.	Fallback to ~/.meldrc if local not found or not defining all aliases.
	3.	Return a function resolveAlias(pathOrAlias: string): string that:
	•	If pathOrAlias starts with @, strip the @ prefix, see if it’s a known alias key.
	•	If found, replace with the actual path.
	•	Otherwise, return the original string if no alias is matched.

3.2 Modify the “Meld” Class (now in meldCore.ts or similar)
	1.	Load the raw file (this.options.inputFile).
	2.	Call extractPlaceholders(content) to get a list of placeholders.
	3.	For each placeholder:
	•	If type === 'cmd':
	1.	Use the existing logic to run shell command, capture output.
	•	If type === 'import':
	1.	Pass the file path portion to aliasResolver to expand if needed.
	2.	Decide if it’s markdown or code by extension (.md or .ts / .js).
	3.	If markdown:
	•	Check if we have a heading. If not, error.
	•	Use importMarkdownSection(...).
	4.	If code:
	•	Use importCodeSnippet(...).
	•	Replace the @import[...] token in the final doc with the returned content.
	4.	Write the final replaced content to this.options.outputFile or stdout.

3.3 CLI & Config
	•	Keep the existing meld CLI or rename it.
	•	Add a --config <file> CLI option to specify a custom alias config.
	•	In meldconfig.json or ~/.meldrc, define a schema like:

{
  "aliases": {
    "docs": "../docs",
    "lib": "./src/lib"
  }
}


	•	“aliasResolver.ts” merges the top-level “aliases” object from local and global config.

3.4 Testing
	1.	Unit Tests:
	•	extractPlaceholders.test.ts:
	•	Test lines containing multiple placeholders.
	•	@import[..] as ### MyTitle.
	•	@import[..] # [myFunc, otherFunc].
	•	markdownImporter.test.ts:
	•	Have a fixture markdown with multiple headings, code fences, test partial matches.
	•	Confirm heading rename & re-level.
	•	codeImporter.test.ts:
	•	Mock or real TS fixture with multiple exports (function, interface, type).
	•	Test single symbol import.
	•	Test bracketed list import.
	•	Test wildcard interface/type import.
	•	Verify error if symbol not found or multiple matches.
	2.	Integration Tests:
	•	A test .md with both @cmd and @import references.
	•	A test TS file with multiple exports.
	•	A test local config with an alias.
	•	Confirm final output is as expected.

3.5 Error Handling & Edge Cases
	1.	If no heading is found in the markdown, throw an error.
	2.	If two headings match the exact text in the same doc, also throw an error (the user must fix).
	3.	If symbol is not found in code, throw an error.
	4.	If alias is not recognized, throw an error, or fallback if you prefer.

3.6 Performance Considerations
	•	The code runs once per build, so we can keep it simple.
	•	For code parsing, we do a single parse per file. If multiple symbols come from the same file, we can parse it once, then fetch multiple symbols. (The code above already does one parse per import call; an optimization is to memoize, but not strictly needed.)

Final Summary

By splitting the code into focused modules and carefully implementing the new logic for @import[...], you’ll seamlessly support markdown and code snippet imports, including heading-level overrides, wildcard interface/type imports, multiple symbols, etc. The three implementations above (placeholder extraction, markdown importer, code importer) are the most intricate and have been provided in full detail. Everything else—CLI scaffolding, environment/config merges, unit tests—can be handled by simpler boilerplate or automated tools.