420kit-shared
v1.0.3
Published
Shared library for 247420 and Schwepe projects - eliminating code duplication with common utilities
Maintainers
Readme
@420kit/shared
A comprehensive shared library that eliminates code duplication between 247420 and Schwepe projects, providing unified tools for phrase management, media generation, build processes, and project configuration.
🚀 Features
- 📝 Dynamic Phrase System - SSR-compatible phrase management with multiple variations
- 🖼️ Media Generator - Automated media file processing and JSON list generation
- 🔧 Build Tools - Unified build system with Vite integration and phrase processing
- 📋 Configuration Templates - Ready-to-use project templates and configurations
- 🎯 TypeScript Support - Full type definitions for better developer experience
- ⚡ Zero Dependencies - Lightweight and fast with minimal external dependencies
📦 Installation
npm install @420kit/shared🔧 Quick Start
Basic Phrase System Usage
import { createPhraseSystem } from '@420kit/shared/phrase-system';
// Create and initialize phrase system
const phraseSystem = createPhraseSystem({
enablePersistence: true,
enableSSR: true
});
// Add phrase groups
phraseSystem.addPhraseGroup('pageTitle', {
main: ['Welcome to My Site', 'My Awesome Website', 'Home Sweet Home']
});
phraseSystem.addPhraseGroup('navigation', {
home: ['Home', 'Start', 'Begin'],
about: ['About', 'Info', 'Details']
});
// Initialize and process page
phraseSystem.init();Media Generation
import { generateMediaLists } from '@420kit/shared/media-generator';
// Generate media lists
const results = await generateMediaLists({
baseDir: './my-project',
imageDir: 'assets/images',
videoDir: 'assets/videos'
});
console.log(`Generated ${results.stats.totalImages} images and ${results.stats.totalVideos} videos`);Build System
import { buildProject } from '@420kit/shared/build-tools';
// Build your project
const buildResults = await buildProject({
enablePhraseProcessing: true,
enableMediaGeneration: true,
enableViteBuild: true,
verbose: true
});
if (buildResults.success) {
console.log(`Build completed in ${buildResults.buildTime}ms`);
} else {
console.error('Build failed:', buildResults.error);
}Project Setup
import { createProjectSetup } from '@420kit/shared/config-templates';
// Create a complete project setup
const setupResults = createProjectSetup({
projectName: 'my-awesome-project',
projectDescription: 'An awesome project built with 420kit',
templates: [
'package.json',
'vite.config.js',
'build-process.js',
'.eslintrc.json',
'.gitignore'
]
});
console.log(`Created ${setupResults.created.length} files`);📚 Modules
Phrase System (@420kit/shared/phrase-system)
Manages dynamic content variations with SSR support.
Features
- Multiple phrase variations per content element
- Server-side rendering support
- Client-side phrase rotation
- Persistent selections
- Phrase validation
- CMS integration ready
Classes
DynamicPhraseSystem- Main phrase management classBuildTimePhraseSystem- Build-time phrase selection for static sites
Example
<!-- In your HTML -->
<h1 data-phrase-group="pageTitle" data-phrase-key="main">Default Title</h1>
<nav>
<a href="/" data-phrase-group="navigation" data-phrase-key="home">Home</a>
<a href="/about" data-phrase-group="navigation" data-phrase-key="about">About</a>
</nav>import { createPhraseSystem } from '@420kit/shared/phrase-system';
const phrases = createPhraseSystem();
phrases.addPhraseGroup('pageTitle', {
main: ['Welcome', 'Hello', 'Greetings']
});
phrases.addPhraseGroup('navigation', {
home: ['Home', 'Start', 'Begin'],
about: ['About', 'Info', 'Learn More']
});
phrases.init();Media Generator (@420kit/shared/media-generator)
Automatically generates JSON lists for images and videos with metadata.
Features
- Chronological sorting
- File metadata extraction
- Automatic categorization
- Timestamp extraction from filenames
- Duplicate detection and cleanup
- Watch mode for development
Example
import { MediaGenerator } from '@420kit/shared/media-generator';
const generator = new MediaGenerator({
baseDir: './my-project',
imageExtensions: ['.jpg', '.png', '.gif', '.webp'],
videoExtensions: ['.mp4', '.webm', '.mov'],
sortByDate: true,
sortOrder: 'desc',
includeMetadata: true
});
const results = generator.generateAllLists();
// Creates: saved_images.json, saved_videos.json, saved_media.jsonBuild Tools (@420kit/shared/build-tools)
Unified build system integrating phrase processing and media generation.
Features
- Phrase processing for HTML files
- Media list generation
- Vite integration
- Build validation
- Watch mode for development
- Build manifests
- Error reporting
Example
import { BuildTools } from '@420kit/shared/build-tools';
const buildTools = new BuildTools({
inputDir: 'src',
outputDir: 'dist',
enablePhraseProcessing: true,
enableMediaGeneration: true,
enableViteBuild: true,
enableCMSIntegration: true
});
// Single command build
await buildTools.build();
// Development watch mode
buildTools.watchMode();Configuration Templates (@420kit/shared/config-templates)
Ready-to-use project templates and configurations.
Features
- Package.json templates
- Vite configurations
- Build process templates
- Deployment configurations (Netlify, Firebase, Docker)
- CI/CD pipeline templates
- ESLint configurations
Example
import { ConfigTemplates } from '@420kit/shared/config-templates';
const templates = new ConfigTemplates();
// Create individual template
templates.createTemplate('package.json', 'package.json', {
projectName: 'my-project',
projectDescription: 'My awesome project'
});
// Create complete project setup
templates.createProjectSetup({
projectName: 'my-project',
templates: ['package.json', 'vite.config.js', 'build-process.js']
});🛠️ Configuration
Phrase System Options
const options = {
localStorageKey: 'phraseSelections', // Key for localStorage persistence
enablePersistence: true, // Enable client-side persistence
enableSSR: true, // Enable server-side rendering support
reshuffleKeybind: 'ctrl+shift+r' // Keyboard shortcut for reshuffling
};Media Generator Options
const options = {
baseDir: process.cwd(), // Base directory for media files
imageDir: 'saved_images', // Directory containing images
videoDir: 'saved_videos', // Directory containing videos
outputDir: '.', // Output directory for JSON files
imageExtensions: ['.jpg', '.png'], // Supported image extensions
videoExtensions: ['.mp4', '.webm'], // Supported video extensions
generateTimestamps: true, // Extract timestamps from filenames
sortByDate: true, // Sort files by date
sortOrder: 'desc', // Sort order: 'asc' or 'desc'
includeMetadata: true, // Include file metadata in output
outputFormat: 'json', // Output format
prettyPrint: true // Pretty print JSON output
};Build Tools Options
const options = {
baseDir: process.cwd(), // Base directory
inputDir: '.', // Input directory for source files
outputDir: 'dist', // Output directory for build
staticDir: 'static', // Static files directory
contentDir: 'content', // CMS content directory
enablePhraseProcessing: true, // Enable phrase processing
enableMediaGeneration: true, // Enable media generation
enableViteBuild: true, // Enable Vite build
enableCMSIntegration: true, // Enable CMS integration
enableValidation: true, // Enable build validation
cleanOutput: true, // Clean output directory before build
backupFiles: true, // Backup files during Vite build
verbose: true // Enable verbose logging
};🔄 Migration Guide
From 247420 Project
Install the shared library:
npm install @420kit/sharedReplace phrase system imports:
// Before import { DynamicPhraseSystem } from './static/phrase-system.js'; // After import { createPhraseSystem } from '@420kit/shared/phrase-system'; const phraseSystem = createPhraseSystem();Replace media generation:
// Before import generateMediaList from './generate-media-list.js'; // After import { generateMediaLists } from '@420kit/shared/media-generator';Replace build process:
// Before import PhraseBuildProcess from './build-process.js'; // After import { BuildTools } from '@420kit/shared/build-tools'; const buildTools = new BuildTools();
From Schwepe Project
The migration process is identical. The shared library consolidates all duplicated functionality while maintaining the same API patterns.
📝 API Reference
Phrase System
DynamicPhraseSystem
Constructor:
new DynamicPhraseSystem(options?: PhraseOptions)Methods:
addPhraseGroup(groupName: string, phrases: PhraseGroup): thisloadPhrasesFromFile(filePath: string): thisloadPhrasesFromDirectory(dirPath: string): thisinit(): voidrotatePhrase(group: string, key: string): voidreshuffleAll(): voidgetStats(): PhraseStatsvalidatePhraseGroups(): PhraseValidation
BuildTimePhraseSystem
Extends DynamicPhraseSystem with build-time features:
Methods:
generateBuildSelections(): voidgetPhrase(group: string, key: string): stringreplacePhrasesInHTML(htmlContent: string): string
Media Generator
MediaGenerator
Constructor:
new MediaGenerator(options?: MediaGeneratorOptions)Methods:
generateImagesList(): MediaFile[]generateVideosList(): MediaFile[]generateAllLists(): Promise<MediaResults>validateMediaFiles(): MediaValidationwatchDirectories(callback?: Function): any
Build Tools
BuildTools
Constructor:
new BuildTools(options?: BuildToolsOptions)Methods:
build(options?: BuildToolsOptions): Promise<BuildResults>watchMode(): Promise<any>validate(): PhraseValidation & MediaValidationclean(): void
Configuration Templates
ConfigTemplates
Constructor:
new ConfigTemplates(options?: ConfigTemplateOptions)Methods:
createTemplate(templateName: string, outputPath: string, variables?: object): booleancreateProjectSetup(options?: ProjectSetupOptions): ProjectSetupResultslistTemplates(): voidaddTemplate(name: string, template: any, description?: string): void
🧪 Testing
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage🏗️ Building
# Build the library
npm run build
# Build modules only
npm run build:modules
# Build TypeScript definitions
npm run build:types
# Clean build artifacts
npm run clean📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📞 Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples in the
/examplesdirectory
🔗 Related Projects
- 247420 - Original community project
- Schwepe - Original Schwepe project
- 420kit - Main 420kit organization
Built with ❤️ by the 420kit Collective
