Skip to content

refresh — splicer

Splicer

Functions

spliceDocSection

function spliceDocSection(docFilePath: string, elementName: string, newContent: string): boolean
TypeScript

Use spliceDocSection to surgically update a single element's documentation in an existing markdown file without touching the rest of the content.

Reach for this when you've regenerated docs for one function or class and need to sync it back into a doc file that already exists — for example, after a signature change or when iterating on AI-generated descriptions for a specific API element.

It locates the heading matching elementName, then replaces everything from that heading to the next heading of equal or higher level with newContent. The rest of the file is left untouched.

NameTypeRequiredDescription
docFilePathstringYesPath to the .md or .mdx file to update. The file must already exist — spliceDocSection won't create it.
elementNamestringYesThe exact name of the element whose section should be replaced (e.g., "createUser"). Must match the heading text in the file.
newContentstringYesThe full replacement content for the section, including the heading itself. Everything from the matched heading to the next same-or-higher-level heading will be overwritten with this.

Returns true if the section was found and replaced, false if the element heading wasn't found in the file or the file doesn't exist. Check the return value before assuming the update succeeded — a false result means the file is unchanged.

Heads up:

  • newContent should include the heading line itself (e.g., ## createUser\n\n...). If you omit it, the old heading will be removed and nothing will replace it.
  • Matching is against the heading text only — if two elements share a name across different files, make sure you're targeting the right docFilePath.

Example:

const { readFileSync, writeFileSync, existsSync } = require('fs')
const { join } = require('path')
const os = require('os')
const path = require('path')

// Inline implementation — do not import from autodocs
function spliceDocSection(docFilePath, elementName, newContent) {
  if (!existsSync(docFilePath)) return false

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

  // Find the heading line for this element
  let headingIndex = -1
  let headingLevel = 0

  for (let i = 0; i < lines.length; i++) {
    const match = lines[i].match(/^(#{1,6})\s+(.+)/)
    if (match && match[2].trim() === elementName) {
      headingIndex = i
      headingLevel = match[1].length
      break
    }
  }

  if (headingIndex === -1) return false

  // Find the next heading of same or higher level
  let endIndex = lines.length
  for (let i = headingIndex + 1; i < lines.length; i++) {
    const match = lines[i].match(/^(#{1,6})\s+/)
    if (match && match[1].length <= headingLevel) {
      endIndex = i
      break
    }
  }

  const before = lines.slice(0, headingIndex).join('\n')
  const after = lines.slice(endIndex).join('\n')
  const updated = [before, newContent.trimEnd(), after].filter(Boolean).join('\n') + '\n'

  writeFileSync(docFilePath, updated, 'utf-8')
  return true
}

// --- Example: update docs for a single function after a signature change ---

const tmpDir = os.tmpdir()
const docFile = path.join(tmpDir, 'api-reference.md')

// Simulate an existing doc file with multiple sections
const existingDocs = `# API Reference

## createUser

Creates a new user. Takes a name and email.

**Parameters:** name, email

## deleteUser

Deletes a user by ID.

**Parameters:** id
`

writeFileSync(docFile, existingDocs, 'utf-8')

// New content generated after the createUser signature was updated
const updatedSection = `## createUser

Creates a new user account and returns the created user object.

**Parameters:**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| \`name\` | \`string\` | Yes | Full display name for the user. |
| \`email\` | \`string\` | Yes | Primary email address — must be unique. |
| \`role\` | \`string\` | No | Assigned role. Defaults to \`"viewer"\`. |

**Returns:** \`User\` — pass \`user.id\` to subsequent calls to act on behalf of this user.
`

try {
  const success = spliceDocSection(docFile, 'createUser', updatedSection)

  if (success) {
    console.log('Section updated successfully.\n')
    console.log('--- Updated file contents ---\n')
    console.log(readFileSync(docFile, 'utf-8'))
  } else {
    console.log('Element not found in doc file — no changes made.')
  }
} catch (err) {
  console.error('Failed to update doc section:', err.message)
}

// Expected output:
// Section updated successfully.
//
// --- Updated file contents ---
//
// # API Reference
//
// ## createUser
//
// Creates a new user account and returns the created user object.
// ... (updated content) ...
//
// ## deleteUser
//
// Deletes a user by ID.
// ...
TypeScript

removeDocSection

function removeDocSection(docFilePath: string, elementName: string): boolean
TypeScript

Use removeDocSection to delete a specific API element's documentation block from a generated MDX file when that element has been removed from your source code.

Reach for this when your codebase changes — a function gets deleted, a class is renamed, or an endpoint is deprecated — and you need to keep your generated docs in sync without regenerating the entire file. It surgically removes just the named section, leaving the rest of the doc file intact.

It finds the section matching elementName within the MDX file at docFilePath and splices it out, then writes the result back to disk.

Parameters

NameTypeRequiredDescription
docFilePathstringYesAbsolute or relative path to the .mdx doc file containing the section to remove.
elementNamestringYesThe exact name of the API element (function, class, method) whose section should be deleted — must match the name used when the section was generated.

Returns

Returns true if the section was found and successfully removed, false if the element name wasn't found in the file or the file doesn't exist. Check the return value before assuming the doc file was modified.

Heads up

  • elementName is matched exactly as written — if the generated section used getUserById but you pass getUser, nothing will be removed and the function returns false.
  • The file is written back to disk in place. Make sure the doc file isn't open in a write-locked process before calling this.

Example:

import { readFileSync, writeFileSync, existsSync } from 'fs'
import { join } from 'path'
import * as os from 'os'
import * as fs from 'fs'

// Inline implementation — do not import from autodocs
function spliceDocSection(filePath: string, elementName: string, replacement: string): boolean {
  if (!existsSync(filePath)) return false

  const content = readFileSync(filePath, 'utf-8')
  const sectionRegex = new RegExp(
    `(^|\n)## ${elementName}\\b[\\s\\S]*?(?=\n## |$)`,
    'g'
  )

  if (!sectionRegex.test(content)) return false

  const updated = content.replace(
    new RegExp(`(^|\n)## ${elementName}\\b[\\s\\S]*?(?=\n## |$)`, 'g'),
    replacement
  )

  writeFileSync(filePath, updated, 'utf-8')
  return true
}

function removeDocSection(docFilePath: string, elementName: string): boolean {
  return spliceDocSection(docFilePath, elementName, '')
}

// Simulate a generated MDX doc file with multiple sections
const tmpDir = os.tmpdir()
const docFilePath = join(tmpDir, 'payments-api.mdx')

const initialContent = `# Payments API

## createPayment
Use \`createPayment\` to charge a customer.

## refundPayment
Use \`refundPayment\` to issue a refund.

## deletePayment
Use \`deletePayment\` to void a pending charge.
`

fs.writeFileSync(docFilePath, initialContent, 'utf-8')
console.log('Before removal:')
console.log(fs.readFileSync(docFilePath, 'utf-8'))

// deletePayment was removed from source — clean it from the docs
const removed = removeDocSection(docFilePath, 'deletePayment')

console.log('Removal succeeded:', removed)
// => Removal succeeded: true

console.log('After removal:')
console.log(fs.readFileSync(docFilePath, 'utf-8'))
// => deletePayment section is gone; createPayment and refundPayment remain

const notFound = removeDocSection(docFilePath, 'archivePayment')
console.log('Element not found result:', notFound)
// => Element not found result: false
TypeScript
Was this helpful?