Skip to content

Scanner — Content Types

Content-type

Functions

classifyElement

function classifyElement(element: APIElement): ContentClassification
TypeScript

Use classifyElement to determine what kind of documentation an API element needs — reference docs, a conceptual guide, or a tutorial — so skrypt can generate the right content for each piece of your API.

When you're building a custom documentation pipeline or extending skrypt's generation logic, call this before writing docs to ensure each element gets the appropriate treatment. For example, a simple utility function needs a reference entry, while a complex authentication flow might warrant a full tutorial.

classifyElement inspects the element's structure, naming, complexity, and relationships to score it against three content archetypes: API reference, guide, and tutorial. The highest-scoring archetype wins, and the returned classification includes the reasoning so you can audit or override the decision.

Parameters

NameTypeRequiredDescription
elementAPIElementYesThe parsed API element to classify — typically produced by skrypt's scanner. Must include at minimum a name, kind (function, class, etc.), and signature.

Returns

Returns a ContentClassification object containing the winning content type ("api" | "guide" | "tutorial"), confidence scores for each archetype, and an array of reasons explaining the decision. Pass the type field to your doc generator to select the correct template, or inspect reasons to understand why an element was classified a particular way.

Heads up

  • Elements with very little metadata (no docstring, no parameters, no return type) may score low across all archetypes — validate that your scanner is extracting full signatures before classifying.
  • The classification is a recommendation, not a constraint. If your team's standards differ, use the scores to build your own tiebreaker logic rather than treating the result as final.

Example:

type APIElementKind = "function" | "class" | "interface" | "type" | "enum"

interface APIElement {
  name: string
  kind: APIElementKind
  signature: string
  docstring?: string
  parameters?: { name: string; type: string; description?: string }[]
  returnType?: string
  filePath?: string
  complexity?: number
}

type ContentType = "api" | "guide" | "tutorial"

interface ContentClassification {
  type: ContentType
  scores: { api: number; guide: number; tutorial: number }
  reasons: string[]
}

// Inline implementation matching skrypt's classifyElement logic
function classifyElement(element: APIElement): ContentClassification {
  const reasons: string[] = []
  let apiScore = 0
  let guideScore = 0
  let tutorialScore = 0

  // Simple, well-typed functions lean toward API reference
  if (element.kind === "function" && (element.parameters?.length ?? 0) <= 3) {
    apiScore += 3
    reasons.push("Function with few parameters suits a reference entry")
  }

  // Rich docstrings suggest the author intended explanatory content
  if (element.docstring && element.docstring.length > 120) {
    guideScore += 2
    reasons.push("Detailed docstring suggests conceptual explanation needed")
  }

  // High complexity signals a tutorial is warranted
  if ((element.complexity ?? 0) > 10) {
    tutorialScore += 4
    reasons.push("High complexity score — step-by-step tutorial recommended")
  }

  // Classes almost always need a guide to explain lifecycle and usage patterns
  if (element.kind === "class") {
    guideScore += 3
    reasons.push("Classes benefit from a usage guide covering instantiation and lifecycle")
  }

  const scores = { api: apiScore, guide: guideScore, tutorial: tutorialScore }
  const type = (Object.entries(scores).sort(([, a], [, b]) => b - a)[0][0]) as ContentType

  return { type, scores, reasons }
}

// Example: classify a straightforward utility function
const element: APIElement = {
  name: "hashPassword",
  kind: "function",
  signature: "function hashPassword(password: string, saltRounds?: number): Promise<string>",
  docstring: "Hashes a plaintext password using bcrypt.",
  parameters: [
    { name: "password", type: "string", description: "The plaintext password to hash" },
    { name: "saltRounds", type: "number", description: "bcrypt cost factor, defaults to 10" },
  ],
  returnType: "Promise<string>",
  filePath: "src/auth/hash.ts",
  complexity: 2,
}

try {
  const classification = classifyElement(element)

  console.log("Content type:", classification.type)
  // → Content type: api

  console.log("Scores:", classification.scores)
  // → Scores: { api: 3, guide: 0, tutorial: 0 }

  console.log("Reasons:", classification.reasons)
  // → Reasons: [ 'Function with few parameters suits a reference entry' ]
} catch (err) {
  console.error("Classification failed:", err)
}
TypeScript

classifyElements

function classifyElements(elements: APIElement[]): Map<ContentType, APIElement[]>
TypeScript

Use classifyElements to sort a flat list of API elements into content-type buckets — separating reference docs, guides, tutorials, and overviews — so you can render or route each group differently.

Reach for this when you've scanned a codebase and need to organize the extracted elements before writing them to disk. It's the step between collecting raw APIElement objects and generating MDX output, especially when building a --by-topic doc structure.

It iterates over every element and groups them into a Map keyed by ContentType. Every possible content type ('api', 'guide', 'tutorial', 'overview') is guaranteed to exist as a key in the returned map, even if the corresponding array is empty — so you can safely iterate without checking for undefined.

Parameters

NameTypeRequiredDescription
elementsAPIElement[]YesThe raw API elements extracted from a source scan. Pass the full flat list — the function handles all classification internally.

Returns

A Map<ContentType, APIElement[]> where each key is a content type and each value is the subset of elements that belong to it. Use the map to drive per-type output logic — for example, write everything under 'api' to a reference/ directory and everything under 'guide' to a guides/ directory.

Heads up

  • All four keys ('api', 'guide', 'tutorial', 'overview') are always present in the returned map. Calling .get('tutorial') will return [], not undefined, even if no tutorials were found.
  • Classification is determined by the element's own metadata, not its file path — renaming source files won't change how elements are grouped.

Example:

type ContentType = 'api' | 'guide' | 'tutorial' | 'overview';

interface APIElement {
  name: string;
  kind: string;
  contentType: ContentType;
  description: string;
  filePath: string;
}

function classifyElements(elements: APIElement[]): Map<ContentType, APIElement[]> {
  const groups = new Map<ContentType, APIElement[]>([
    ['api', []],
    ['guide', []],
    ['tutorial', []],
    ['overview', []],
  ]);

  for (const element of elements) {
    const bucket = groups.get(element.contentType);
    if (bucket) {
      bucket.push(element);
    }
  }

  return groups;
}

const scannedElements: APIElement[] = [
  { name: 'createUser', kind: 'function', contentType: 'api', description: 'Creates a new user record', filePath: 'src/users.ts' },
  { name: 'deleteUser', kind: 'function', contentType: 'api', description: 'Deletes a user by ID', filePath: 'src/users.ts' },
  { name: 'Getting Started', kind: 'module', contentType: 'guide', description: 'How to authenticate with the API', filePath: 'src/auth.ts' },
  { name: 'Build a Dashboard', kind: 'module', contentType: 'tutorial', description: 'Step-by-step dashboard tutorial', filePath: 'src/examples/dashboard.ts' },
  { name: 'Architecture Overview', kind: 'module', contentType: 'overview', description: 'High-level system design', filePath: 'src/index.ts' },
];

const classified = classifyElements(scannedElements);

for (const [contentType, elements] of classified) {
  console.log(`${contentType}: ${elements.length} element(s)`);
  for (const el of elements) {
    console.log(`  - ${el.name} (${el.filePath})`);
  }
}

// Expected output:
// api: 2 element(s)
//   - createUser (src/users.ts)
//   - deleteUser (src/users.ts)
// guide: 1 element(s)
//   - Getting Started (src/auth.ts)
// tutorial: 1 element(s)
//   - Build a Dashboard (src/examples/dashboard.ts)
// overview: 1 element(s)
//   - Architecture Overview (src/index.ts)
TypeScript

getRecommendedStructure

function getRecommendedStructure(elements: APIElement[]): {
  sections: { name: string; type: ContentType; elements: APIElement[] }[]
  stats: { api: number; guide: number; tutorial: number; overview: number }
}
TypeScript

Use getRecommendedStructure to automatically organize your scanned API elements into a logical documentation layout before writing MDX files.

Reach for this when you've collected APIElement objects from skrypt generate and need to decide how to structure the output — which elements become API reference pages, which become guides, and which become tutorials or overviews. It's the planning step between scanning and writing.

The function classifies each element by its characteristics (exported functions, types, classes, etc.) and groups them into named sections, each tagged with a ContentType. The returned stats object gives you a quick count of how many elements landed in each category.

Parameters

NameTypeRequiredDescription
elementsAPIElement[]YesThe API elements extracted from your source scan. Pass the full array — the function handles classification internally and works best with the complete set so it can infer relationships between elements.

Returns

Returns an object with two keys. sections is an array of groups, each with a name, a ContentType tag ("api", "guide", "tutorial", or "overview"), and the APIElement[] that belong there — use these to drive your MDX file generation loop. stats gives you a flat count per content type, useful for logging or validating that the structure looks reasonable before committing to disk.

Heads up

  • Elements that don't fit a clear category may be grouped into an "overview" section rather than dropped — check stats.overview if the count seems higher than expected.
  • The structure is a recommendation, not a constraint. You can remap or merge sections before passing them to your output writer.

Example:

type ContentType = "api" | "guide" | "tutorial" | "overview"

interface APIElement {
  name: string
  kind: "function" | "class" | "type" | "interface" | "constant"
  description?: string
  filePath: string
  isExported: boolean
}

interface RecommendedStructure {
  sections: { name: string; type: ContentType; elements: APIElement[] }[]
  stats: { api: number; guide: number; tutorial: number; overview: number }
}

// Inline mock — replace with real getRecommendedStructure from autodocs
function getRecommendedStructure(elements: APIElement[]): RecommendedStructure {
  const api = elements.filter((e) => e.kind === "function" || e.kind === "class")
  const overview = elements.filter((e) => e.kind === "type" || e.kind === "interface")
  const constants = elements.filter((e) => e.kind === "constant")

  const sections: RecommendedStructure["sections"] = []
  if (api.length) sections.push({ name: "API Reference", type: "api", elements: api })
  if (overview.length) sections.push({ name: "Types & Interfaces", type: "overview", elements: overview })
  if (constants.length) sections.push({ name: "Constants", type: "guide", elements: constants })

  return {
    sections,
    stats: {
      api: api.length,
      guide: constants.length,
      tutorial: 0,
      overview: overview.length,
    },
  }
}

const scannedElements: APIElement[] = [
  { name: "createPayment", kind: "function", description: "Initiates a payment", filePath: "src/payments.ts", isExported: true },
  { name: "refundPayment", kind: "function", description: "Refunds a charge", filePath: "src/payments.ts", isExported: true },
  { name: "PaymentClient", kind: "class", description: "Main client class", filePath: "src/client.ts", isExported: true },
  { name: "PaymentOptions", kind: "interface", description: "Options for payment creation", filePath: "src/types.ts", isExported: true },
  { name: "Currency", kind: "type", description: "Supported currency codes", filePath: "src/types.ts", isExported: true },
  { name: "DEFAULT_TIMEOUT", kind: "constant", description: "Default request timeout in ms", filePath: "src/config.ts", isExported: true },
]

try {
  const structure = getRecommendedStructure(scannedElements)

  console.log("Documentation structure:")
  for (const section of structure.sections) {
    console.log(`\n[${section.type.toUpperCase()}] ${section.name}`)
    for (const el of section.elements) {
      console.log(`  - ${el.name} (${el.kind})`)
    }
  }

  console.log("\nStats:", structure.stats)
  // Stats: { api: 3, guide: 1, tutorial: 0, overview: 2 }
} catch (err) {
  console.error("Failed to build structure:", err)
}
TypeScript

getPromptForContentType

function getPromptForContentType(type: ContentType): string
TypeScript

Use getPromptForContentType to retrieve the AI prompt template that drives documentation generation for a given content category.

When building a custom documentation pipeline with skrypt, call this before invoking the AI provider so you can inspect, extend, or override the prompt for a specific content type — for example, to append project-specific conventions to the default API reference prompt.

The function maps each ContentType value to a tailored prompt string optimized for that kind of content. Different content types (like 'api', 'guide', or 'example') produce structurally different documentation, so each gets its own prompt rather than a one-size-fits-all template.

Parameters

NameTypeRequiredDescription
typeContentTypeYesThe category of content being documented — determines which prompt template is returned. Use 'api' for function/class reference docs, other values for guides or examples.

Returns

Returns a prompt string ready to send to your AI provider. Pass it directly as the system or user message when calling your LLM, or concatenate your own instructions onto it before sending.

Heads up

  • The returned string is a complete, opinionated prompt — if you need to customize tone or add project-specific rules, append to the string rather than replacing it, so you keep the structured output format skrypt expects.

Example:

type ContentType = 'api' | 'guide' | 'example';

function getPromptForContentType(type: ContentType): string {
  switch (type) {
    case 'api':
      return `Generate detailed API reference documentation. Include:
- Clear parameter descriptions with types
- Return value documentation
- Usage examples`;
    case 'guide':
      return `Generate a conceptual guide. Include:
- Overview of the feature
- Step-by-step instructions
- Common pitfalls`;
    case 'example':
      return `Generate a focused code example. Include:
- Minimal working code
- Inline comments explaining key lines
- Expected output`;
  }
}

async function generateDocs(type: ContentType, signature: string): Promise<string> {
  const basePrompt = getPromptForContentType(type);

  // Extend the prompt with project-specific conventions before sending to your LLM
  const finalPrompt = `${basePrompt}\n\nAdditional rules:\n- Use TypeScript in all examples\n- Prefer async/await over callbacks`;

  // Simulate an AI provider call
  const response = await Promise.resolve(
    `[AI-generated docs for: ${signature} using prompt type "${type}"]`
  );

  return response;
}

try {
  const prompt = getPromptForContentType('api');
  console.log('Base prompt for API docs:\n', prompt);
  // Base prompt for API docs:
  //  Generate detailed API reference documentation. Include:
  // - Clear parameter descriptions with types
  // - Return value documentation
  // - Usage examples

  const result = await generateDocs('api', 'function createUser(email: string): Promise<User>');
  console.log('\nGenerated:', result);
  // Generated: [AI-generated docs for: function createUser(email: string): Promise<User> using prompt type "api"]
} catch (err) {
  console.error('Failed to generate docs:', err);
}
TypeScript
Was this helpful?