npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/ai-prompt-builder

v1.2.0

Published

Reusable prompt templates for common AI tasks (content review, social generation, rewriting) with variable substitution and context building

Readme

@bernierllc/ai-prompt-builder

Reusable prompt templates for common AI tasks (content review, social generation, rewriting) with variable substitution and context building.

Installation

npm install @bernierllc/ai-prompt-builder

Features

  • Pre-built Templates: Ready-to-use prompts for common AI tasks
  • Variable Substitution: Simple {{variable}} syntax for dynamic content
  • Type Safety: Full TypeScript support with strict typing
  • Composition: Combine multiple prompts together
  • Validation: Automatic validation of required variables
  • Sanitization: Built-in escaping for safe variable substitution
  • Conditional Sections: Add sections based on runtime conditions
  • Zero Dependencies: Pure utility with no external dependencies

Quick Start

Using Pre-built Templates

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

// Content review prompt
const reviewPrompt = PromptBuilder.contentReview(blogContent, {
  checkGrammar: true,
  checkSEO: true,
  checkReadability: true,
  targetAudience: 'JavaScript developers'
});

// Social media generation
const twitterPrompt = PromptBuilder.socialGeneration(blogContent, {
  platform: 'twitter',
  tone: 'professional',
  includeHashtags: true,
  includeCTA: true
});

// Commit message rewriting
const commitPrompt = PromptBuilder.commitRewrite('added user auth', {
  type: 'feat',
  scope: 'auth'
});

Using the Builder Pattern

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

const prompt = new PromptBuilder()
  .setTemplate('Analyze this {{type}}: {{content}}')
  .setVariables({
    type: 'code',
    content: 'function hello() { return "world"; }'
  })
  .addSection({
    content: 'Focus on performance',
    condition: true
  })
  .build();

console.log(prompt.content);

Using Named Templates

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

const builder = PromptBuilder.fromTemplate('contentReview');
builder.setVariables({
  content: 'Your blog content here',
  criteria: '- Grammar\n- SEO\n- Readability'
});

const result = builder.build();
if (result.success) {
  console.log(result.content);
} else {
  console.error('Missing variables:', result.missingVariables);
}

API Reference

PromptBuilder

Main class for building AI prompts.

Static Methods

contentReview(content: string, options?: ReviewOptions): string

Generate a content review prompt.

Options:

  • checkGrammar?: boolean - Check grammar and spelling (default: true)
  • checkSEO?: boolean - Check SEO optimization (default: true)
  • checkReadability?: boolean - Check readability metrics (default: true)
  • checkTone?: boolean - Check tone and voice
  • targetAudience?: string - Target audience description
  • focusAreas?: string[] - Additional focus areas

Example:

const prompt = PromptBuilder.contentReview(blogPost, {
  checkGrammar: true,
  checkSEO: true,
  checkReadability: true,
  targetAudience: 'Software developers',
  focusAreas: ['Technical accuracy', 'Code examples']
});
socialGeneration(content: string, options: SocialGenerationOptions): string

Generate a social media post from blog content.

Options:

  • platform: string - Platform (twitter, linkedin, facebook, instagram)
  • tone?: string - Desired tone (default: 'professional')
  • includeHashtags?: boolean - Include hashtags
  • includeCTA?: boolean - Include call-to-action
  • maxLength?: number - Maximum length (platform defaults apply)
  • targetAudience?: string - Target audience

Example:

const prompt = PromptBuilder.socialGeneration(blogContent, {
  platform: 'twitter',
  tone: 'casual',
  includeHashtags: true,
  includeCTA: true,
  targetAudience: 'Web developers'
});
commitRewrite(originalCommit: string, options?: CommitRewriteOptions): string

Rewrite commit messages following conventional commit format.

Options:

  • type?: string - Conventional commit type (default: 'feat')
  • scope?: string - Scope of the change
  • breaking?: boolean - Include breaking change indicator
  • maxSubjectLength?: number - Maximum subject line length (default: 50)

Example:

const prompt = PromptBuilder.commitRewrite('fixed bug in login form', {
  type: 'fix',
  scope: 'auth',
  breaking: false
});
blogPostSuggestions(context: string, count: number, targetAudience: string, category: string): string

Generate blog post topic suggestions.

Example:

const prompt = PromptBuilder.blogPostSuggestions(
  'TypeScript best practices for enterprise applications',
  5,
  'Senior developers',
  'Software Engineering'
);
compose(prompts: string[], separator?: string): string

Compose multiple prompts together.

Example:

const reviewPrompt = PromptBuilder.contentReview(content);
const socialPrompt = PromptBuilder.socialGeneration(content, { platform: 'twitter' });

const combined = PromptBuilder.compose([reviewPrompt, socialPrompt]);
// Prompts are separated by '\n\n---\n\n' by default
fromTemplate(templateName: string): PromptBuilder

Create a builder from a named template.

Example:

const builder = PromptBuilder.fromTemplate('contentReview');
builder.setVariables({ content: '...', criteria: '...' });
const result = builder.build();

Instance Methods

setTemplate(template: string): PromptBuilder

Set the template string. Returns this for chaining.

setVariable(name: string, value: string | number | boolean): PromptBuilder

Set a single variable. Returns this for chaining.

setVariables(variables: Record<string, string | number | boolean>): PromptBuilder

Set multiple variables at once. Returns this for chaining.

addSection(section: TemplateSection): PromptBuilder

Add a conditional section. Returns this for chaining.

Example:

builder.addSection({
  content: 'Additional instructions here',
  condition: shouldInclude
});
build(sanitize?: boolean): SubstitutionResult

Build the final prompt. Sanitizes variables by default.

Returns:

{
  success: boolean;
  content: string;
  missingVariables: string[];
}

VariableSubstitutor

Utility class for variable substitution and validation.

Static Methods

extractVariables(template: string): string[]

Extract all variable names from a template.

Example:

const vars = VariableSubstitutor.extractVariables('Hello {{name}}, you are {{age}}');
// Returns: ['name', 'age']
substitute(template: string, variables: Record<string, any>, required?: string[]): SubstitutionResult

Substitute variables in a template.

Example:

const result = VariableSubstitutor.substitute(
  'Hello {{name}}',
  { name: 'John' },
  ['name']
);
// Returns: { success: true, content: 'Hello John', missingVariables: [] }
escape(value: string): string

Escape special characters in variable values.

Example:

const escaped = VariableSubstitutor.escape('Line 1\nLine 2 "quoted"');
// Returns: 'Line 1\\nLine 2 \\"quoted\\"'
isValidVariableName(name: string): boolean

Validate variable names (alphanumeric, underscore, hyphen only).

Example:

VariableSubstitutor.isValidVariableName('user_name'); // true
VariableSubstitutor.isValidVariableName('user@name'); // false
sanitize(variables: Record<string, any>): Record<string, any>

Sanitize variables object by escaping values and validating names.

Example:

const sanitized = VariableSubstitutor.sanitize({
  name: 'John\nDoe',
  age: 30
});
// Returns: { name: 'John\\nDoe', age: 30 }

Templates

Pre-built template utilities.

Functions

getTemplate(name: string): PromptTemplate | undefined

Get a template by name.

listTemplates(): string[]

List all available template names.

hasTemplate(name: string): boolean

Check if a template exists.

Available Templates

  • contentReview - Review content for quality, grammar, SEO, and readability
  • socialGeneration - Generate social media posts from blog content
  • commitRewrite - Rewrite commit messages following conventional commit format
  • blogPostSuggestions - Generate blog post topic suggestions
  • codeReview - Review code for quality, best practices, and potential issues
  • textSummary - Summarize long text into key points

Example:

import { listTemplates, getTemplate } from '@bernierllc/ai-prompt-builder';

console.log(listTemplates());
// ['contentReview', 'socialGeneration', 'commitRewrite', ...]

const template = getTemplate('contentReview');
console.log(template.requiredVariables);
// ['content', 'criteria']

Advanced Usage

Custom Templates

Create custom templates with variable substitution:

const customTemplate = `
Review this {{contentType}}:

{{content}}

Requirements:
{{requirements}}

Provide {{outputFormat}} format.
`;

const builder = new PromptBuilder(customTemplate);
builder.setVariables({
  contentType: 'blog post',
  content: 'Your content here...',
  requirements: '- Grammar\n- SEO\n- Tone',
  outputFormat: 'JSON'
});

const result = builder.build();

Conditional Sections

Add sections that only appear when certain conditions are met:

const builder = new PromptBuilder('Main prompt content');

builder.addSection({
  content: 'Check for security vulnerabilities',
  condition: options.checkSecurity
});

builder.addSection({
  content: 'Target audience: ' + audience,
  condition: audience !== undefined
});

const result = builder.build();

Variable Validation

Validate required variables before building:

const builder = PromptBuilder.fromTemplate('contentReview');
builder.setVariables({
  content: blogContent,
  criteria: '- Grammar\n- SEO'
});

const result = builder.build();
if (!result.success) {
  console.error('Missing variables:', result.missingVariables);
  // Handle error
} else {
  // Use result.content
}

Composition

Combine multiple prompts for complex workflows:

// Create individual prompts
const reviewPrompt = PromptBuilder.contentReview(content, {
  checkGrammar: true,
  checkSEO: true
});

const socialPrompt = PromptBuilder.socialGeneration(content, {
  platform: 'twitter',
  includeHashtags: true
});

const commitPrompt = PromptBuilder.commitRewrite('initial draft');

// Compose them together
const workflow = PromptBuilder.compose([
  reviewPrompt,
  socialPrompt,
  commitPrompt
], '\n\n=== NEXT STEP ===\n\n');

// Send to AI model

Integration Status

Logger Integration

Status: Not applicable

Justification: This is a pure utility package with no runtime state, side effects, or error conditions that require logging. The PromptBuilder class is stateless and deterministic - it simply constructs prompt strings from templates and variables. All errors are thrown as exceptions that calling code can handle, and there are no background operations, network calls, or state changes that would benefit from structured logging.

Pattern: Pure functional utility - no logger integration needed.

NeverHub Integration

Status: Not applicable

Justification: This is a core utility package that provides prompt building functionality. It does not participate in service discovery, event publishing, or service mesh operations. It's a stateless utility that can be used by any service or application without requiring service registration or discovery.

Pattern: Core utility - no service mesh integration needed.

Docs-Suite Integration

Status: Ready

Format: TypeDoc-compatible JSDoc comments are included throughout the source code. All public APIs are documented with examples and type information.

TypeScript Support

This package is written in TypeScript with strict mode enabled and includes complete type definitions.

import type {
  ReviewOptions,
  SocialGenerationOptions,
  CommitRewriteOptions,
  PromptTemplate,
  SubstitutionResult
} from '@bernierllc/ai-prompt-builder';

Use Cases

AI Content Review Service

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

class ContentReviewService {
  async reviewBlogPost(content: string): Promise<ReviewResult> {
    const prompt = PromptBuilder.contentReview(content, {
      checkGrammar: true,
      checkSEO: true,
      checkReadability: true,
      targetAudience: 'Developers'
    });

    const aiResponse = await this.sendToAI(prompt);
    return this.parseReviewResult(aiResponse);
  }
}

Social Media Automation

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

class SocialMediaAutomation {
  async generatePosts(blogContent: string): Promise<SocialPosts> {
    const platforms = ['twitter', 'linkedin', 'facebook'];
    const posts: Record<string, string> = {};

    for (const platform of platforms) {
      const prompt = PromptBuilder.socialGeneration(blogContent, {
        platform,
        includeHashtags: platform === 'twitter',
        includeCTA: true
      });

      posts[platform] = await this.sendToAI(prompt);
    }

    return posts;
  }
}

Git Commit Assistant

import { PromptBuilder } from '@bernierllc/ai-prompt-builder';

class CommitAssistant {
  async improveCommitMessage(rawCommit: string): Promise<string> {
    const prompt = PromptBuilder.commitRewrite(rawCommit, {
      type: this.detectCommitType(rawCommit),
      scope: this.detectScope(rawCommit)
    });

    return await this.sendToAI(prompt);
  }
}

Performance

  • Zero Runtime Dependencies: Minimal bundle size
  • Pure Functions: No side effects, easy to test and cache
  • Lazy Evaluation: Templates are only processed when build() is called
  • Memory Efficient: No large data structures or caching

Error Handling

The package uses structured error responses:

const result = builder.build();

if (!result.success) {
  console.error('Build failed:', result.missingVariables);
  // Handle missing variables
} else {
  // Use result.content
}

Exceptions are only thrown for invalid inputs:

  • Invalid template names
  • Invalid variable names (sanitize mode)

Testing

# Run tests
npm test

# Run tests without watch mode
npm run test:run

# Run tests with coverage
npm run test:coverage

Test Coverage: 90%+ (branches, functions, lines, statements)

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.

See Also