420kit-shared
Version:
Shared library for 247420 and Schwepe projects - eliminating code duplication with common utilities
470 lines (355 loc) โข 12.5 kB
Markdown
# @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
```bash
npm install @420kit/shared
```
## ๐ง Quick Start
### Basic Phrase System Usage
```javascript
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
```javascript
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
```javascript
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
```javascript
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 class
- **`BuildTimePhraseSystem`** - Build-time phrase selection for static sites
#### Example
```html
<!-- 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>
```
```javascript
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
```javascript
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.json
```
### Build 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
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
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
1. **Install the shared library:**
```bash
npm install @420kit/shared
```
2. **Replace phrase system imports:**
```javascript
// Before
import { DynamicPhraseSystem } from './static/phrase-system.js';
// After
import { createPhraseSystem } from '@420kit/shared/phrase-system';
const phraseSystem = createPhraseSystem();
```
3. **Replace media generation:**
```javascript
// Before
import generateMediaList from './generate-media-list.js';
// After
import { generateMediaLists } from '@420kit/shared/media-generator';
```
4. **Replace build process:**
```javascript
// 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:**
```javascript
new DynamicPhraseSystem(options?: PhraseOptions)
```
**Methods:**
- `addPhraseGroup(groupName: string, phrases: PhraseGroup): this`
- `loadPhrasesFromFile(filePath: string): this`
- `loadPhrasesFromDirectory(dirPath: string): this`
- `init(): void`
- `rotatePhrase(group: string, key: string): void`
- `reshuffleAll(): void`
- `getStats(): PhraseStats`
- `validatePhraseGroups(): PhraseValidation`
#### `BuildTimePhraseSystem`
Extends `DynamicPhraseSystem` with build-time features:
**Methods:**
- `generateBuildSelections(): void`
- `getPhrase(group: string, key: string): string`
- `replacePhrasesInHTML(htmlContent: string): string`
### Media Generator
#### `MediaGenerator`
**Constructor:**
```javascript
new MediaGenerator(options?: MediaGeneratorOptions)
```
**Methods:**
- `generateImagesList(): MediaFile[]`
- `generateVideosList(): MediaFile[]`
- `generateAllLists(): Promise<MediaResults>`
- `validateMediaFiles(): MediaValidation`
- `watchDirectories(callback?: Function): any`
### Build Tools
#### `BuildTools`
**Constructor:**
```javascript
new BuildTools(options?: BuildToolsOptions)
```
**Methods:**
- `build(options?: BuildToolsOptions): Promise<BuildResults>`
- `watchMode(): Promise<any>`
- `validate(): PhraseValidation & MediaValidation`
- `clean(): void`
### Configuration Templates
#### `ConfigTemplates`
**Constructor:**
```javascript
new ConfigTemplates(options?: ConfigTemplateOptions)
```
**Methods:**
- `createTemplate(templateName: string, outputPath: string, variables?: object): boolean`
- `createProjectSetup(options?: ProjectSetupOptions): ProjectSetupResults`
- `listTemplates(): void`
- `addTemplate(name: string, template: any, description?: string): void`
## ๐งช Testing
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
```
## ๐๏ธ Building
```bash
# 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
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples in the `/examples` directory
## ๐ Related Projects
- [247420](https://github.com/247420/community) - Original community project
- [Schwepe](https://github.com/schwepe) - Original Schwepe project
- [420kit](https://github.com/420kit) - Main 420kit organization
---
Built with โค๏ธ by the 420kit Collective