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/publishing-rules

v1.0.5

Published

Publishing rule engine with conditional logic and platform-specific configurations

Readme

@bernierllc/publishing-rules

Publishing rule engine with conditional logic and platform-specific configurations for content management systems.

Installation

npm install @bernierllc/publishing-rules

Usage

Basic Setup

import { createRulesEngine, commonRules, ConditionType, ActionType } from '@bernierllc/publishing-rules';

// Create a rules engine
const engine = createRulesEngine({
  maxRules: 100,
  timeout: 5000,
  continueOnError: true,
  enableLogging: true
});

// Add a common rule
const businessHoursRule = commonRules.businessHours('09:00', '17:00');
engine.addRule(businessHoursRule);

// Evaluate content against rules
const context = {
  content: {
    id: 'post-123',
    type: 'blog-post',
    title: 'My Blog Post',
    content: 'This is the content of my blog post...',
    author: 'john-doe',
    status: 'approved',
    tags: ['tech', 'javascript'],
    createdAt: new Date()
  },
  user: {
    id: 'user-456',
    roles: ['editor'],
    permissions: ['publish']
  }
};

const result = await engine.evaluateRules(context);

if (result.shouldProceed) {
  console.log('Content can be published');
  console.log('Actions to take:', result.actions);
} else {
  console.log('Content publishing blocked');
  console.log('Errors:', result.errors);
}

Custom Rules

import { ConditionType, ConditionOperator, ActionType } from '@bernierllc/publishing-rules';

// Create a custom rule
const customRule = {
  id: 'weekend-hold',
  name: 'Weekend Publishing Hold',
  description: 'Hold content publishing during weekends',
  enabled: true,
  priority: 300,
  conditions: [
    {
      type: ConditionType.DAY_OF_WEEK,
      field: 'current-time',
      operator: ConditionOperator.IN,
      value: [0, 6] // Sunday and Saturday
    }
  ],
  actions: [
    {
      type: ActionType.HOLD,
      parameters: {
        reason: 'Weekend publishing policy',
        resumeOn: 'next-business-day'
      }
    },
    {
      type: ActionType.NOTIFY,
      parameters: {
        recipients: ['[email protected]'],
        subject: 'Content held for weekend policy',
        message: 'Content will be published on the next business day'
      }
    }
  ],
  createdAt: new Date(),
  updatedAt: new Date()
};

engine.addRule(customRule);

Rule Templates

import { RuleTemplateLibrary, getBuiltinTemplates, createRuleFromTemplate } from '@bernierllc/publishing-rules';

// Use built-in templates
const templates = getBuiltinTemplates();
const approvalTemplate = templates.find(t => t.id === 'content-approval-required');

if (approvalTemplate) {
  const approvalRule = createRuleFromTemplate(
    approvalTemplate,
    'my-approval-rule',
    {
      requiredStatus: 'approved',
      notificationEmail: '[email protected]'
    }
  );
  
  engine.addRule(approvalRule);
}

// Create custom template library
const library = new RuleTemplateLibrary();

const customTemplate = {
  id: 'tag-based-scheduling',
  name: 'Tag-Based Scheduling',
  description: 'Schedule content based on tags',
  category: 'SCHEDULING_RULES',
  parameters: [
    {
      name: 'requiredTag',
      type: 'string',
      description: 'Tag that triggers scheduling',
      required: true
    },
    {
      name: 'scheduleDelay',
      type: 'number',
      description: 'Hours to delay publishing',
      required: false,
      defaultValue: 24
    }
  ],
  conditions: [
    {
      type: ConditionType.TAG_EXISTS,
      field: 'tags',
      operator: ConditionOperator.CONTAINS,
      value: '{{requiredTag}}'
    }
  ],
  actions: [
    {
      type: ActionType.SCHEDULE,
      parameters: {
        delay: '{{scheduleDelay}}h'
      }
    }
  ],
  examples: []
};

library.registerTemplate(customTemplate);

Common Rules

The package provides several built-in common rules:

// Business hours only
const businessRule = commonRules.businessHours('08:00', '18:00');

// Content approval required
const approvalRule = commonRules.approvalRequired();

// Weekend delay
const weekendRule = commonRules.weekendDelay('09:00');

// Content length validation
const lengthRule = commonRules.contentLengthValidation(100, 5000);

// Rate limiting
const rateLimitRule = commonRules.rateLimit(10); // max 10 posts per hour

// Emergency stop
const emergencyRule = commonRules.emergencyStop(['[email protected]']);

Advanced Features

Custom Condition Evaluators

const customRule = {
  id: 'advanced-rule',
  name: 'Advanced Rule',
  description: 'Rule with custom evaluator',
  enabled: true,
  priority: 100,
  conditions: [
    {
      type: ConditionType.CUSTOM_FIELD,
      field: 'metadata.sentiment',
      operator: ConditionOperator.EQUALS,
      value: 'positive',
      customEvaluator: async (context, condition) => {
        // Custom sentiment analysis logic
        const sentiment = await analyzeSentiment(context.content.content);
        return {
          passed: sentiment.score > 0.7,
          details: `Sentiment score: ${sentiment.score}`
        };
      }
    }
  ],
  actions: [
    {
      type: ActionType.PUBLISH,
      parameters: {}
    }
  ],
  createdAt: new Date(),
  updatedAt: new Date()
};

Event Handling

engine.on('rule-evaluated', (event) => {
  console.log(`Rule ${event.ruleId} evaluated:`, event.result);
});

engine.on('action-executed', (event) => {
  console.log(`Action ${event.actionType} executed:`, event.result);
});

engine.on('error', (event) => {
  console.error('Rule engine error:', event.error);
});

Statistics and Monitoring

// Get engine statistics
const stats = engine.getStatistics();
console.log('Total evaluations:', stats.totalEvaluations);
console.log('Rule executions:', stats.ruleExecutions);
console.log('Average evaluation time:', stats.averageEvaluationTime);

// Reset statistics
engine.resetStatistics();

API Reference

PublishingRulesEngine

Main rule engine class for managing and evaluating publishing rules.

Constructor

  • new PublishingRulesEngine(config?: RuleEngineConfig)

Methods

  • addRule(rule: PublishingRule): void
  • removeRule(id: string): boolean
  • updateRule(id: string, updates: Partial<PublishingRule>): PublishingRule | null
  • getRule(id: string): PublishingRule | undefined
  • getRules(): PublishingRule[]
  • enableRule(id: string): void
  • disableRule(id: string): void
  • clearAllRules(): void
  • evaluateRules(context: RuleEvaluationContext): Promise<RuleEvaluationResult>
  • getStatistics(): RuleEngineStatistics
  • resetStatistics(): void

RuleTemplateLibrary

Template system for creating reusable rule patterns.

Methods

  • registerTemplate(template: RuleTemplate): void
  • getTemplate(id: string): RuleTemplate | undefined
  • listTemplates(): RuleTemplate[]
  • getTemplatesByCategory(category: RuleCategory): RuleTemplate[]
  • removeTemplate(id: string): boolean
  • validateTemplate(template: RuleTemplate): string[]

Common Functions

  • createRulesEngine(config?: Partial<RuleEngineConfig>): PublishingRulesEngine
  • getBuiltinTemplates(): RuleTemplate[]
  • createRuleFromTemplate(template: RuleTemplate, ruleId: string, parameters: Record<string, any>): PublishingRule

Configuration

interface RuleEngineConfig {
  maxRules: number;              // Maximum number of rules (default: 100)
  timeout: number;               // Rule evaluation timeout in ms (default: 5000)
  continueOnError: boolean;      // Continue evaluation on rule errors (default: true)
  enableCaching: boolean;        // Enable result caching (default: true)
  cacheTTL: number;             // Cache TTL in ms (default: 300000)
  enableLogging: boolean;        // Enable logging (default: true)
  logLevel: LogLevel;           // Log level (default: INFO)
  parallelEvaluation: boolean;   // Evaluate rules in parallel (default: true)
  maxConcurrency: number;        // Max parallel evaluations (default: 10)
}

Condition Types

  • CONTENT_TYPE - Match content type
  • CONTENT_LENGTH - Validate content length
  • WORD_COUNT - Validate word count
  • TAG_EXISTS - Check for specific tags
  • TITLE_MATCHES - Match title patterns
  • AUTHOR_IS - Match content author
  • CATEGORY_IS - Match content category
  • STATUS_IS - Match content status
  • TIME_OF_DAY - Time-based conditions
  • DAY_OF_WEEK - Day-based conditions
  • DATE_RANGE - Date range conditions
  • CUSTOM_FIELD - Custom field evaluation
  • USER_ROLE - User role checks
  • USER_PERMISSION - User permission checks
  • RATE_LIMIT - Publishing rate limits

Action Types

  • PUBLISH - Proceed with publishing
  • HOLD - Hold content for review
  • SCHEDULE - Schedule for later publishing
  • NOTIFY - Send notifications
  • REJECT - Reject content
  • REQUIRE_APPROVAL - Require additional approval
  • ADD_TAG - Add tags to content
  • REMOVE_TAG - Remove tags from content
  • UPDATE_METADATA - Update content metadata

Error Handling

try {
  const result = await engine.evaluateRules(context);
  if (result.errors.length > 0) {
    console.warn('Rule evaluation warnings:', result.errors);
  }
} catch (error) {
  console.error('Rule engine failed:', error);
  // Handle critical failure
}

License

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