Compare commits
5 commits
bfaa68dc35
...
2765fa2eba
| Author | SHA1 | Date | |
|---|---|---|---|
| 2765fa2eba | |||
| a8ed131b3b | |||
| da758206b4 | |||
| 57fcb6fef2 | |||
| 5ed6ee7988 |
5 changed files with 330 additions and 161 deletions
|
|
@ -16,7 +16,7 @@ database = []
|
|||
http-client = ["dep:reqwest"]
|
||||
validation = []
|
||||
resilience = []
|
||||
i18n = []
|
||||
i18n = ["dep:rust-embed"]
|
||||
|
||||
[dependencies]
|
||||
# Core
|
||||
|
|
@ -34,6 +34,9 @@ tokio = { workspace = true, features = ["sync", "time"] }
|
|||
# Optional: HTTP Client
|
||||
reqwest = { workspace = true, features = ["json", "rustls-tls"], optional = true }
|
||||
|
||||
# Optional: i18n
|
||||
rust-embed = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
||||
|
||||
|
|
|
|||
114
PROMPT.md
114
PROMPT.md
|
|
@ -1,114 +0,0 @@
|
|||
# BotLib Development Guide
|
||||
|
||||
**Version:** 6.2.0
|
||||
**Purpose:** Shared library for General Bots workspace
|
||||
|
||||
---
|
||||
|
||||
## ZERO TOLERANCE POLICY
|
||||
|
||||
**EVERY SINGLE WARNING MUST BE FIXED. NO EXCEPTIONS.**
|
||||
|
||||
---
|
||||
|
||||
## ❌ ABSOLUTE PROHIBITIONS
|
||||
|
||||
```
|
||||
❌ NEVER use #![allow()] or #[allow()] in source code
|
||||
❌ NEVER use _ prefix for unused variables - DELETE or USE them
|
||||
❌ NEVER use .unwrap() - use ? or proper error handling
|
||||
❌ NEVER use .expect() - use ? or proper error handling
|
||||
❌ NEVER use panic!() or unreachable!()
|
||||
❌ NEVER use todo!() or unimplemented!()
|
||||
❌ NEVER leave unused imports or dead code
|
||||
❌ NEVER add comments - code must be self-documenting
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ MODULE STRUCTURE
|
||||
|
||||
```
|
||||
src/
|
||||
├── lib.rs # Public exports, feature gates
|
||||
├── error.rs # Error types (thiserror)
|
||||
├── models.rs # Shared data models
|
||||
├── message_types.rs # Message type definitions
|
||||
├── http_client.rs # HTTP client wrapper (feature-gated)
|
||||
├── branding.rs # Version, branding constants
|
||||
└── version.rs # Version information
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ MANDATORY CODE PATTERNS
|
||||
|
||||
### Error Handling
|
||||
|
||||
```rust
|
||||
// ❌ WRONG
|
||||
let value = something.unwrap();
|
||||
|
||||
// ✅ CORRECT
|
||||
let value = something?;
|
||||
let value = something.ok_or_else(|| Error::NotFound)?;
|
||||
```
|
||||
|
||||
### Self Usage
|
||||
|
||||
```rust
|
||||
impl MyStruct {
|
||||
fn new() -> Self { Self { } } // ✅ Not MyStruct
|
||||
}
|
||||
```
|
||||
|
||||
### Format Strings
|
||||
|
||||
```rust
|
||||
format!("Hello {name}") // ✅ Not format!("{}", name)
|
||||
```
|
||||
|
||||
### Display vs ToString
|
||||
|
||||
```rust
|
||||
// ❌ WRONG
|
||||
impl ToString for MyType { }
|
||||
|
||||
// ✅ CORRECT
|
||||
impl std::fmt::Display for MyType { }
|
||||
```
|
||||
|
||||
### Derive Eq with PartialEq
|
||||
|
||||
```rust
|
||||
#[derive(PartialEq, Eq)] // ✅ Always both
|
||||
struct MyStruct { }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 KEY DEPENDENCIES
|
||||
|
||||
| Library | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| anyhow | 1.0 | Error handling |
|
||||
| thiserror | 2.0 | Error derive |
|
||||
| chrono | 0.4 | Date/time |
|
||||
| serde | 1.0 | Serialization |
|
||||
| uuid | 1.11 | UUIDs |
|
||||
| diesel | 2.1 | Database ORM |
|
||||
| reqwest | 0.12 | HTTP client |
|
||||
|
||||
---
|
||||
|
||||
## 🔑 REMEMBER
|
||||
|
||||
- **ZERO WARNINGS** - Every clippy warning must be fixed
|
||||
- **NO ALLOW IN CODE** - Never use #[allow()] in source files
|
||||
- **NO DEAD CODE** - Delete unused code
|
||||
- **NO UNWRAP/EXPECT** - Use ? operator
|
||||
- **INLINE FORMAT ARGS** - `format!("{name}")` not `format!("{}", name)`
|
||||
- **USE SELF** - In impl blocks, use Self not the type name
|
||||
- **DERIVE EQ** - Always derive Eq with PartialEq
|
||||
- **DISPLAY NOT TOSTRING** - Implement Display, not ToString
|
||||
- **Version 6.2.0** - do not change without approval
|
||||
171
README.md
171
README.md
|
|
@ -1,3 +1,170 @@
|
|||
General Bots® base library for building Node.js TypeScript Apps packages (.gbapp).
|
||||
# BotLib - General Bots Shared Library
|
||||
|
||||
See: https://github.com/pragmatismo-io/botserver for main documentation.
|
||||
**Version:** 6.2.0
|
||||
**Purpose:** Shared library for General Bots workspace
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
BotLib is the foundational shared library for the General Bots workspace, providing common types, error handling, HTTP client functionality, and utilities used across all projects. It serves as the core dependency for botserver, botui, botapp, and other workspace members, ensuring consistency and reducing code duplication.
|
||||
|
||||
For comprehensive documentation, see **[docs.pragmatismo.com.br](https://docs.pragmatismo.com.br)** or the **[BotBook](../botbook)** for detailed guides and API references.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Module Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── lib.rs # Public exports, feature gates
|
||||
├── error.rs # Error types (thiserror)
|
||||
├── models.rs # Shared data models
|
||||
├── message_types.rs # Message type definitions
|
||||
├── http_client.rs # HTTP client wrapper (feature-gated)
|
||||
├── branding.rs # Version, branding constants
|
||||
└── version.rs # Version information
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ ZERO TOLERANCE POLICY
|
||||
|
||||
**EVERY SINGLE WARNING MUST BE FIXED. NO EXCEPTIONS.**
|
||||
|
||||
### Absolute Prohibitions
|
||||
|
||||
```
|
||||
❌ NEVER use #![allow()] or #[allow()] in source code
|
||||
❌ NEVER use _ prefix for unused variables - DELETE or USE them
|
||||
❌ NEVER use .unwrap() - use ? or proper error handling
|
||||
❌ NEVER use .expect() - use ? or proper error handling
|
||||
❌ NEVER use panic!() or unreachable!()
|
||||
❌ NEVER use todo!() or unimplemented!()
|
||||
❌ NEVER leave unused imports or dead code
|
||||
❌ NEVER add comments - code must be self-documenting
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 Key Dependencies
|
||||
|
||||
| Library | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| anyhow | 1.0 | Error handling |
|
||||
| thiserror | 2.0 | Error derive |
|
||||
| chrono | 0.4 | Date/time |
|
||||
| serde | 1.0 | Serialization |
|
||||
| uuid | 1.11 | UUIDs |
|
||||
| diesel | 2.1 | Database ORM |
|
||||
| reqwest | 0.12 | HTTP client |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Features
|
||||
|
||||
### Feature Gates
|
||||
|
||||
BotLib uses Cargo features to enable optional functionality:
|
||||
|
||||
```toml
|
||||
[features]
|
||||
default = []
|
||||
http-client = ["reqwest"] # Enable HTTP client
|
||||
# Add more features as needed
|
||||
```
|
||||
|
||||
### Using Features
|
||||
|
||||
```toml
|
||||
# In dependent crate's Cargo.toml
|
||||
[dependencies.botlib]
|
||||
workspace = true
|
||||
features = ["http-client"] # Enable HTTP client
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Mandatory Code Patterns
|
||||
|
||||
### Error Handling
|
||||
|
||||
```rust
|
||||
// ❌ WRONG
|
||||
let value = something.unwrap();
|
||||
|
||||
// ✅ CORRECT
|
||||
let value = something?;
|
||||
let value = something.ok_or_else(|| Error::NotFound)?;
|
||||
```
|
||||
|
||||
### Self Usage
|
||||
|
||||
```rust
|
||||
impl MyStruct {
|
||||
fn new() -> Self { Self { } } // ✅ Not MyStruct
|
||||
}
|
||||
```
|
||||
|
||||
### Format Strings
|
||||
|
||||
```rust
|
||||
format!("Hello {name}") // ✅ Not format!("{}", name)
|
||||
```
|
||||
|
||||
### Display vs ToString
|
||||
|
||||
```rust
|
||||
// ❌ WRONG
|
||||
impl ToString for MyType { }
|
||||
|
||||
// ✅ CORRECT
|
||||
impl std::fmt::Display for MyType { }
|
||||
```
|
||||
|
||||
### Derive Eq with PartialEq
|
||||
|
||||
```rust
|
||||
#[derive(PartialEq, Eq)] // ✅ Always both
|
||||
struct MyStruct { }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
For complete documentation, guides, and API references:
|
||||
|
||||
- **[docs.pragmatismo.com.br](https://docs.pragmatismo.com.br)** - Full online documentation
|
||||
- **[BotBook](../botbook)** - Local comprehensive guide with tutorials and examples
|
||||
- **[General Bots Repository](https://github.com/GeneralBots/BotServer)** - Main project repository
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Related Projects
|
||||
|
||||
- **[botserver](https://github.com/GeneralBots/botserver)** - Main API server
|
||||
- **[botui](https://github.com/GeneralBots/botui)** - Web UI interface
|
||||
- **[botapp](https://github.com/GeneralBots/botapp)** - Desktop application
|
||||
- **[botbook](https://github.com/GeneralBots/botbook)** - Documentation
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Remember
|
||||
|
||||
- **ZERO WARNINGS** - Every clippy warning must be fixed
|
||||
- **NO ALLOW IN CODE** - Never use #[allow()] in source files
|
||||
- **NO DEAD CODE** - Delete unused code
|
||||
- **NO UNWRAP/EXPECT** - Use ? operator
|
||||
- **INLINE FORMAT ARGS** - `format!("{name}")` not `format!("{}", name)`
|
||||
- **USE SELF** - In impl blocks, use Self not the type name
|
||||
- **DERIVE EQ** - Always derive Eq with PartialEq
|
||||
- **DISPLAY NOT TOSTRING** - Implement Display, not ToString
|
||||
- **Version 6.2.0** - Do not change without approval
|
||||
- **GIT WORKFLOW** - ALWAYS push to ALL repositories (github, pragmatismo)
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
AGPL-3.0 - See [LICENSE](LICENSE) for details.
|
||||
|
|
@ -3,8 +3,16 @@ use std::collections::HashMap;
|
|||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(feature = "i18n")]
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
use super::Locale;
|
||||
|
||||
#[cfg(feature = "i18n")]
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "locales"]
|
||||
struct EmbeddedLocales;
|
||||
|
||||
pub type MessageArgs = HashMap<String, String>;
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -87,14 +95,12 @@ impl LocaleBundle {
|
|||
messages: HashMap::new(),
|
||||
};
|
||||
|
||||
let entries = fs::read_dir(locale_dir).map_err(|e| {
|
||||
BotError::config(format!("failed to read locale directory: {e}"))
|
||||
})?;
|
||||
let entries = fs::read_dir(locale_dir)
|
||||
.map_err(|e| BotError::config(format!("failed to read locale directory: {e}")))?;
|
||||
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| {
|
||||
BotError::config(format!("failed to read directory entry: {e}"))
|
||||
})?;
|
||||
let entry = entry
|
||||
.map_err(|e| BotError::config(format!("failed to read directory entry: {e}")))?;
|
||||
|
||||
let path = entry.path();
|
||||
|
||||
|
|
@ -117,6 +123,32 @@ impl LocaleBundle {
|
|||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "i18n")]
|
||||
fn load_embedded(locale_str: &str) -> BotResult<Self> {
|
||||
let locale = Locale::new(locale_str)
|
||||
.ok_or_else(|| BotError::config(format!("invalid locale: {locale_str}")))?;
|
||||
|
||||
let mut translations = TranslationFile {
|
||||
messages: HashMap::new(),
|
||||
};
|
||||
|
||||
for file in EmbeddedLocales::iter() {
|
||||
if file.starts_with(locale_str) && file.ends_with(".ftl") {
|
||||
if let Some(content_bytes) = EmbeddedLocales::get(&file) {
|
||||
if let Ok(content) = std::str::from_utf8(content_bytes.data.as_ref()) {
|
||||
let file_translations = TranslationFile::parse(content);
|
||||
translations.merge(file_translations);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
locale,
|
||||
translations,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_message(&self, key: &str) -> Option<&String> {
|
||||
self.translations.get(key)
|
||||
}
|
||||
|
|
@ -134,6 +166,15 @@ impl I18nBundle {
|
|||
let base = Path::new(base_path);
|
||||
|
||||
if !base.exists() {
|
||||
#[cfg(feature = "i18n")]
|
||||
{
|
||||
log::info!(
|
||||
"Locales directory not found at {}, trying embedded assets",
|
||||
base_path
|
||||
);
|
||||
return Self::load_embedded();
|
||||
}
|
||||
#[cfg(not(feature = "i18n"))]
|
||||
return Err(BotError::config(format!(
|
||||
"locales directory not found: {base_path}"
|
||||
)));
|
||||
|
|
@ -142,14 +183,12 @@ impl I18nBundle {
|
|||
let mut bundles = HashMap::new();
|
||||
let mut available = Vec::new();
|
||||
|
||||
let entries = fs::read_dir(base).map_err(|e| {
|
||||
BotError::config(format!("failed to read locales directory: {e}"))
|
||||
})?;
|
||||
let entries = fs::read_dir(base)
|
||||
.map_err(|e| BotError::config(format!("failed to read locales directory: {e}")))?;
|
||||
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| {
|
||||
BotError::config(format!("failed to read directory entry: {e}"))
|
||||
})?;
|
||||
let entry = entry
|
||||
.map_err(|e| BotError::config(format!("failed to read directory entry: {e}")))?;
|
||||
|
||||
let path = entry.path();
|
||||
|
||||
|
|
@ -175,6 +214,44 @@ impl I18nBundle {
|
|||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "i18n")]
|
||||
fn load_embedded() -> BotResult<Self> {
|
||||
let mut bundles = HashMap::new();
|
||||
let mut available = Vec::new();
|
||||
let mut seen_locales = std::collections::HashSet::new();
|
||||
|
||||
for file in EmbeddedLocales::iter() {
|
||||
// Path structure: locale/file.ftl
|
||||
let parts: Vec<&str> = file.split('/').collect();
|
||||
if let Some(locale_str) = parts.first() {
|
||||
if !seen_locales.contains(*locale_str) {
|
||||
match LocaleBundle::load_embedded(locale_str) {
|
||||
Ok(bundle) => {
|
||||
available.push(bundle.locale.clone());
|
||||
bundles.insert(bundle.locale.to_string(), bundle);
|
||||
seen_locales.insert(locale_str.to_string());
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"failed to load embedded locale bundle {}: {}",
|
||||
locale_str,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fallback = Locale::default();
|
||||
|
||||
Ok(Self {
|
||||
bundles,
|
||||
available,
|
||||
fallback,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_message(&self, locale: &Locale, key: &str, args: Option<&MessageArgs>) -> String {
|
||||
let negotiated = Locale::negotiate(&[locale], &self.available, &self.fallback);
|
||||
|
||||
|
|
@ -258,15 +335,15 @@ impl I18nBundle {
|
|||
let mut result = template.to_string();
|
||||
|
||||
for (key, value) in args {
|
||||
let count: i64 = value.parse().unwrap_or(0);
|
||||
if let Ok(count) = value.parse::<i64>() {
|
||||
let plural_pattern = format!("{{ ${key} ->");
|
||||
|
||||
let plural_pattern = format!("{{ ${key} ->");
|
||||
|
||||
if let Some(start) = result.find(&plural_pattern) {
|
||||
if let Some(end) = result[start..].find('}') {
|
||||
let plural_block = &result[start..start + end + 1];
|
||||
let replacement = Self::select_plural_form(plural_block, count);
|
||||
result = result.replace(plural_block, &replacement);
|
||||
if let Some(start) = result.find(&plural_pattern) {
|
||||
if let Some(end) = result[start..].find('}') {
|
||||
let plural_block = &result[start..start + end + 1];
|
||||
let replacement = Self::select_plural_form(plural_block, count);
|
||||
result = result.replace(plural_block, &replacement);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -330,10 +407,7 @@ world = World
|
|||
greeting = Hello, { $name }!
|
||||
"#;
|
||||
let file = TranslationFile::parse(content);
|
||||
assert_eq!(
|
||||
file.get("greeting"),
|
||||
Some(&"Hello, { $name }!".to_string())
|
||||
);
|
||||
assert_eq!(file.get("greeting"), Some(&"Hello, { $name }!".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -2,20 +2,13 @@ use env_logger::fmt::Formatter;
|
|||
use log::Record;
|
||||
use std::io::Write;
|
||||
|
||||
// ANSI color codes
|
||||
const RED: &str = "\x1b[31m";
|
||||
const YELLOW: &str = "\x1b[33m";
|
||||
const GREEN: &str = "\x1b[32m";
|
||||
const CYAN: &str = "\x1b[36m";
|
||||
const RESET: &str = "\x1b[0m";
|
||||
|
||||
pub fn compact_format(buf: &mut Formatter, record: &Record) -> std::io::Result<()> {
|
||||
let (level, color) = match record.level() {
|
||||
log::Level::Error => ("E", RED),
|
||||
log::Level::Warn => ("W", YELLOW),
|
||||
log::Level::Info => ("I", GREEN),
|
||||
log::Level::Debug => ("D", CYAN),
|
||||
log::Level::Trace => ("T", ""),
|
||||
let level_char = match record.level() {
|
||||
log::Level::Error => 'E',
|
||||
log::Level::Warn => 'I', // Mapping Warn to Info per I/T/E spec
|
||||
log::Level::Info => 'I',
|
||||
log::Level::Debug => 'T', // Mapping Debug to Trace per I/T/E spec
|
||||
log::Level::Trace => 'T',
|
||||
};
|
||||
|
||||
let now = chrono::Local::now();
|
||||
|
|
@ -28,10 +21,58 @@ pub fn compact_format(buf: &mut Formatter, record: &Record) -> std::io::Result<(
|
|||
target
|
||||
};
|
||||
|
||||
if color.is_empty() {
|
||||
writeln!(buf, "{} {} {}:{}", timestamp, level, module, record.args())
|
||||
// Format: "YYYYMMDDHHMMSS.mmm L module:"
|
||||
// Length: 18 + 1 + 1 + 1 + module.len() + 1 = 22 + module.len()
|
||||
let prefix = format!("{} {} {}:", timestamp, level_char, module);
|
||||
|
||||
// Max width 100
|
||||
// If prefix + message fits, print it.
|
||||
// Else, wrap.
|
||||
// Indent for wrapping is 21 spaces (18 timestamp + 1 space + 1 level + 1 space)
|
||||
// Actually, based on spec:
|
||||
// Position: 123456789012345678901234567890...
|
||||
// Format: YYYYMMDDHHMMSS.mmm L module:Message
|
||||
// 1 18 20 22
|
||||
// So indent is 21 spaces.
|
||||
|
||||
let message = record.args().to_string();
|
||||
let indent = " "; // 21 spaces
|
||||
|
||||
if prefix.len() + message.len() <= 100 {
|
||||
writeln!(buf, "{}{}", prefix, message)
|
||||
} else {
|
||||
writeln!(buf, "{} {}{}{} {}:{}", timestamp, color, level, RESET, module, record.args())
|
||||
let available_first_line = if prefix.len() < 100 {
|
||||
100 - prefix.len()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let available_other_lines = 100 - 21; // 99 chars
|
||||
|
||||
let mut current_pos = 0;
|
||||
let chars: Vec<char> = message.chars().collect();
|
||||
let total_chars = chars.len();
|
||||
|
||||
// First line
|
||||
write!(buf, "{}", prefix)?;
|
||||
|
||||
// If prefix is already >= 100, we force a newline immediately?
|
||||
// Or we just print a bit and wrap?
|
||||
// Let's assume typical usage where module name isn't huge.
|
||||
|
||||
let take = std::cmp::min(available_first_line, total_chars);
|
||||
let first_chunk: String = chars[0..take].iter().collect();
|
||||
writeln!(buf, "{}", first_chunk)?;
|
||||
current_pos += take;
|
||||
|
||||
while current_pos < total_chars {
|
||||
write!(buf, "{}", indent)?;
|
||||
let remaining = total_chars - current_pos;
|
||||
let take = std::cmp::min(remaining, available_other_lines);
|
||||
let chunk: String = chars[current_pos..current_pos + take].iter().collect();
|
||||
writeln!(buf, "{}", chunk)?;
|
||||
current_pos += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -42,8 +83,6 @@ pub fn init_compact_logger(default_filter: &str) {
|
|||
}
|
||||
|
||||
pub fn init_compact_logger_with_style(default_filter: &str) {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(default_filter))
|
||||
.format(compact_format)
|
||||
.write_style(env_logger::WriteStyle::Always)
|
||||
.init();
|
||||
// Style ignored to strictly follow text format spec
|
||||
init_compact_logger(default_filter);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue