npm package: @kouovo/ph-shared
Description: A TypeScript library providing shared utilities for generating Pug resources manifests and locale files from directory structures.
Latest version: 0.1.46

# @kouovo/ph-shared

A TypeScript library providing shared utilities for generating Pug resources manifests and locale files from directory structures.

## Overview

The `@kouovo/ph-shared` package provides utilities for automatically generating Pug template files from resource directories and locale JSON files. It's designed to streamline the process of managing static assets and internationalization in Pug-based projects.

## Installation

```bash
npm install @kouovo/ph-shared
# or
pnpm add @kouovo/ph-shared
# or
yarn add @kouovo/ph-shared
```

## Features

- **Resource Manifest Generation**: Automatically scan directories for images and media files and generate Pug variable definitions
- **Locale File Generation**: Convert JSON locale files to Pug template files with translation functions
- **TypeScript Support**: Fully typed with comprehensive interfaces
- **Error Handling**: Comprehensive error handling with detailed error messages
- **Flexible Configuration**: Customizable prefix and output paths

## API Reference

### `generatePugResourcesManifest(inputDir, outputPugFile, prefix?)`

Scans a directory for supported media files and generates a Pug file with variable definitions.

#### Parameters

- `inputDir: string` - Path to the directory containing resource files
- `outputPugFile: string` - Path where the generated Pug file should be written
- `prefix: string` - Optional prefix for resource paths (default: `"~"`)

#### Supported File Types

- **Images**: `.png`, `.jpg`, `.jpeg`, `.svg`
- **Videos**: `.mp4`, `.flv`

#### Example

```typescript
import { generatePugResourcesManifest } from '@kouovo/ph-shared';

await generatePugResourcesManifest(
  './src/assets',
  './src/_resources.pug',
  '~assets/'
);
```

#### Generated Output

```pug
//- Auto-generated by script. Do not edit manually.
-
  const $ = {
    "logo": "~assets/logo.png",
    "icons_home": "~assets/icons/home.svg",
    "banner_video": "~assets/videos/banner.mp4"
  }
```

#### Features

- **Recursive Directory Scanning**: Automatically scans subdirectories
- **Path Normalization**: Converts file paths to web-compatible format
- **Duplicate Handling**: Automatically renames duplicate keys with numeric suffixes
- **Clean Variable Names**: Generates clean, camelCase variable names from file paths
- **Directory Structure Preservation**: Maintains directory structure in variable names

### `generatePugLocaleFiles(inputDir, outputDir)`

Converts JSON locale files to Pug template files with translation functions.

#### Parameters

- `inputDir: string` - Path to the directory containing JSON locale files
- `outputDir: string` - Path where the generated Pug files should be written

#### Example

```typescript
import { generatePugLocaleFiles } from '@kouovo/ph-shared';

await generatePugLocaleFiles(
  './locales',
  './src/locales'
);
```

#### Input Structure

```
locales/
├── en.json
├── zh.json
└── ar.json
```

**en.json**:
```json
{
  "welcome": "Welcome",
  "goodbye": "Goodbye",
  "navigation": {
    "home": "Home",
    "about": "About"
  }
}
```

#### Generated Output

**src/locales/en.pug**:
```pug
//- Auto-generated by script. Do not edit manually.
//- Source: locales/en.json
//- Target: src/locales/en.pug

-
  var _en = {
    "welcome": "Welcome",
    "goodbye": "Goodbye",
    "navigation": {
      "home": "Home",
      "about": "About"
    }
  }
```

**src/locales/t.pug**:
```pug
//- Auto-generated by script. Do not edit manually.

- var _translations = {}

if __LANG__ == 'en'
  include ./en.pug
  - _translations = _en
else if __LANG__ == 'zh'
  include ./zh.pug
  - _translations = _zh
else if __LANG__ == 'ar'
  include ./ar.pug
  - _translations = _ar
else
  // No language files found or matched, _translations remains {}

//- Translation function
-
  function $t(key) {
    var value = _translations[key];
    if (typeof value === 'undefined') {
      return `Missing translation for key: ${key}`;
    }
    return value;
  }
mixin pp(key)
  p&attributes(attributes)
    - const v = $t(key)
    - if (Array.isArray(v))
      each val in v
        span !{val}
    - else
      span !{v}
```

#### Features

- **Automatic Default Creation**: Creates default locale files if none exist
- **Parallel Processing**: Processes multiple locale files concurrently
- **Translation Function**: Generates a `$t()` function for easy translation access
- **Pug Mixin**: Includes `pp()` mixin for paragraph elements with translation
- **Fallback Handling**: Provides fallback messages for missing translations
- **Error Recovery**: Continues processing even if individual files fail

## Usage in Pug Templates

### Using Resource Manifest

```pug
include _resources.pug

img(src=$.logo alt="Logo")
video(src=$.banner_video)
```

### Using Locale System

```pug
include locales/t.pug

h1= $t('welcome')
+pp('goodbye')
p= $t('navigation.home')
```

## Error Handling

Both functions include comprehensive error handling for:

- **File System Errors**: Missing directories, permission issues
- **JSON Parsing Errors**: Invalid JSON format in locale files
- **Path Resolution**: Invalid input/output paths
- **Duplicate Resources**: Automatic renaming with warnings

## Default Locale Configuration

When no locale files exist, the system creates default files for:
- `en.json` (English)
- `zh.json` (Chinese)
- `ar.json` (Arabic)

Each with a simple example structure:
```json
{
  "example": "hello world"
}
```

## TypeScript Support

The package is fully typed with interfaces for:
- `TranslationData` - Nested translation object structure
- `ImageData` - Resource path mappings
- All function parameters and return types

## Performance Features

- **Parallel Processing**: Resource scanning and locale processing use parallel execution
- **Efficient File Operations**: Uses async/await with proper error handling
- **Memory Optimization**: Streams file operations where possible
- **Recursive Directory Scanning**: Efficiently handles nested directory structures

## License

MIT