feat(core): Introduce native implementations for Base64, random generation and normalization; remove runtime plugin dependencies; update tests, docs and package metadata

This commit is contained in:
2025-09-12 18:57:31 +00:00
parent 6a7570de7b
commit 1f3e170a88
17 changed files with 7585 additions and 4795 deletions

362
readme.md
View File

@@ -1,135 +1,363 @@
# @push.rocks/smartstring
handle strings in smart ways. TypeScript ready.
# @push.rocks/smartstring
🎯 **Smart string manipulation for TypeScript** - Your comprehensive toolkit for handling strings, domains, Git URLs, and encodings with elegance and precision.
## Why smartstring?
When working with strings in modern JavaScript/TypeScript applications, you often need more than just basic manipulation. You need to:
- Parse and validate domains and URLs
- Handle Git repository URLs across different formats
- Encode/decode Base64 for data transmission
- Normalize indentation in code generators
- Create cryptographically secure random strings
- Validate string encodings
- Parse Docker environment variables
**smartstring** unifies all these capabilities in a single, tree-shakeable, TypeScript-native package with zero setup overhead.
## Install
To install `@push.rocks/smartstring`, use the following npm command:
```bash
npm install @push.rocks/smartstring --save
```
This will add it to your project's dependencies.
Or using pnpm (recommended):
```bash
pnpm add @push.rocks/smartstring
```
## Features at a Glance
**Domain parsing** - Extract protocols, subdomains, domains, and TLDs
**Git URL handling** - Parse and convert between SSH and HTTPS formats
**Base64 encoding** - Standard and URL-safe Base64 operations
**Smart indentation** - Indent, outdent, and normalize multi-line strings
**Random strings** - Pattern-based and cryptographically secure generation
**String normalization** - Clean and standardize whitespace
**Type checking** - Validate UTF-8 and Base64 encodings
**Docker env parsing** - Transform Docker environment arrays to objects
## Usage
The `@push.rocks/smartstring` package provides a powerful set of utilities to handle and manipulate strings in various ways, ready for TypeScript usage. Here's an exhaustive guide to using this package.
### 🌐 Domain Parsing
### Working with Domain Strings
The `Domain` class helps in parsing and extracting information from domain URLs.
Extract detailed information from any URL or domain string:
```typescript
import { Domain } from '@push.rocks/smartstring';
// Parse a domain URL
const myDomain = new Domain('https://sub.example.com');
console.log(myDomain.level1); // Output: "com"
console.log(myDomain.level2); // Output: "example"
console.log(myDomain.zoneName); // Output: "example.com"
console.log(myDomain.protocol); // Output: "https"
const domain = new Domain('https://subdomain.example.com:3000/path');
console.log(domain.protocol); // 'https'
console.log(domain.hostname); // 'subdomain.example.com'
console.log(domain.port); // '3000'
console.log(domain.pathname); // '/path'
console.log(domain.fullUrl); // 'https://subdomain.example.com:3000/path'
// Domain level extraction
console.log(domain.level1); // 'com' - TLD
console.log(domain.level2); // 'example' - Domain
console.log(domain.level3); // 'subdomain' - Subdomain
console.log(domain.zoneName); // 'example.com' - Full domain without subdomain
console.log(domain.subdomain); // 'subdomain'
```
### Handling Git Repositories
### 🔧 Git Repository URLs
The `GitRepo` class is designed for extracting information from Git repository URLs.
Parse and convert Git repository URLs between SSH and HTTPS formats:
```typescript
import { GitRepo } from '@push.rocks/smartstring';
// Parse a Git repository URL
const myGitRepo = new GitRepo('git@github.com:user/repo.git');
console.log(myGitRepo.host); // Output: "github.com"
console.log(myGitRepo.user); // Output: "user"
console.log(myGitRepo.repo); // Output: "repo"
console.log(myGitRepo.sshUrl); // Output: "git@github.com:user/repo.git"
console.log(myGitRepo.httpsUrl); // Output: "https://github.com/user/repo.git"
// Parse SSH format
const repo = new GitRepo('git@github.com:user/awesome-project.git');
console.log(repo.host); // 'github.com'
console.log(repo.user); // 'user'
console.log(repo.repo); // 'awesome-project'
console.log(repo.httpsUrl); // 'https://github.com/user/awesome-project.git'
// Parse HTTPS format
const httpsRepo = new GitRepo('https://gitlab.com/team/project.git');
console.log(httpsRepo.sshUrl); // 'git@gitlab.com:team/project.git'
console.log(httpsRepo.httpsUrl); // 'https://gitlab.com/team/project.git'
```
### Encoding and Decoding Base64 Strings
### 🔐 Base64 Encoding
`@push.rocks/smartstring` offers base64 encoding and decoding through the `Base64` class and utility functions.
Handle Base64 encoding with both standard and URL-safe variants:
```typescript
import { Base64, base64 } from '@push.rocks/smartstring';
// Using the Base64 class
const myBase64 = new Base64('hello world', 'string');
console.log(myBase64.base64String); // Encoded string
console.log(myBase64.base64UriString); // Encoded URI compatible string
const encoded = new Base64('Hello World! 👋', 'string');
console.log(encoded.base64String); // Standard Base64
console.log(encoded.base64UriString); // URL-safe Base64
console.log(encoded.simpleString); // Decoded string
// Using utility functions
const encoded = base64.encode('hello world');
const decoded = base64.decode(encoded);
console.log(encoded); // Encoded string
console.log(decoded); // "hello world"
const quickEncode = base64.encode('Secret message');
const quickDecode = base64.decode(quickEncode);
// Validate Base64 strings
console.log(base64.isBase64('SGVsbG8=')); // true
console.log(base64.isBase64('Not Base64!')); // false
// URL-safe Base64 operations
const urlSafeEncoded = base64.encodeUri('https://example.com/path?param=value');
const urlSafeDecoded = base64.decodeUri(urlSafeEncoded);
```
### Applying Indentation
### 📐 Smart Indentation
SmartString allows you to easily indent strings or normalize indentation across a multi-line string.
Manage indentation in multi-line strings with precision:
```typescript
import { indent } from '@push.rocks/smartstring';
// Indent a string by 4 spaces
const indentedString = indent.indent('Some text\nAnother line', 4);
console.log(indentedString);
// Indent with spaces
const indented = indent.indent('Line 1\nLine 2\nLine 3', 4);
// Result:
// Line 1
// Line 2
// Line 3
// Indent using a prefix
const prefixedString = indent.indentWithPrefix('Line 1\nLine 2', '> ');
console.log(prefixedString);
// Indent with custom prefix
const prefixed = indent.indentWithPrefix('Item 1\nItem 2', '> ');
// Result:
// > Item 1
// > Item 2
// Normalize indentation
const normalizedString = indent.normalize(' Some indented text\n Another line');
console.log(normalizedString);
// Add prefix to first line only
const firstLinePrefixed = indent.addPrefix('Chapter\nContent here', '# ');
// Result:
// # Chapter
// Content here
// Normalize irregular indentation
const messy = `
function hello() {
console.log('Hi');
return true;
}
`;
const clean = indent.normalize(messy);
// Result: Properly aligned with minimum indentation preserved
```
### Creating Random or Encrypted Strings
### 🎲 Random String Generation
Create random strings based on patterns or generate cryptographically strong random strings.
Create random strings with specific patterns or cryptographic security:
```typescript
import { create } from '@push.rocks/smartstring';
// Create a random string
const randomString = create.createRandomString('aA0', 10);
console.log(randomString); // Example output: "a9mB8v2Dq1"
// Pattern-based random strings
// A = uppercase, a = lowercase, 0 = number, ! = special, * = any
const password = create.createRandomString('Aa0!', 16);
// Example: "Kg7$Lp2@Qm9#Xn4!"
// Create a crypto-random string
const cryptoString = create.createCryptoRandomString(10);
console.log(cryptoString); // Example output: "f28Bb90aCc"
const alphanumeric = create.createRandomString('Aa0', 10);
// Example: "K7gLp2Qm9X"
const numbers = create.createRandomString('0', 6);
// Example: "472819"
// Cryptographically secure random strings
const cryptoId = create.createCryptoRandomString();
// Example: "f7b2d8e0-3c4a-4b9c-8d2e-1f0a7b9c8d7e"
```
### Normalizing Strings
### 🧹 String Normalization
Normalize strings by removing leading/trailing whitespace, fixing indentation, and more.
Clean and standardize strings for consistent formatting:
```typescript
import { normalize } from '@push.rocks/smartstring';
// Normalize a multi-line string
const exampleString = `
This is an example.
The indentation will be fixed.
const messyString = `
This text has
inconsistent indentation
and too much whitespace
between lines...
`;
const normalized = normalize.standard(exampleString);
console.log(normalized);
const cleaned = normalize.standard(messyString);
// Result: Properly formatted with consistent spacing
// Custom normalization
const customNormalized = normalize.normal(messyString);
```
### Working with Docker Environment Variables
### 🔍 String Type Validation
Transform an array of Docker environment variables into an object for easy access.
Check string encodings and types:
```typescript
import { type } from '@push.rocks/smartstring';
// Check if string is valid UTF-8
const isValidUtf8 = type.isUtf8('Hello 世界');
console.log(isValidUtf8); // true
// Check if string is Base64
const isBase64String = type.isBase64('SGVsbG8gV29ybGQ=');
console.log(isBase64String); // true
```
### 🐳 Docker Environment Variables
Parse Docker-style environment variable arrays:
```typescript
import { docker } from '@push.rocks/smartstring';
const envVars = ['NODE_ENV=production', 'PORT=3000'];
const envObject = docker.makeEnvObject(envVars);
console.log(envObject.NODE_ENV); // Output: "production"
console.log(envObject.PORT); // Output: "3000"
const envArray = [
'NODE_ENV=production',
'PORT=3000',
'DATABASE_URL=postgresql://localhost:5432/mydb',
'API_KEY=secret123'
];
const envObject = docker.makeEnvObject(envArray);
console.log(envObject.NODE_ENV); // 'production'
console.log(envObject.PORT); // '3000'
console.log(envObject.DATABASE_URL); // 'postgresql://localhost:5432/mydb'
console.log(envObject.API_KEY); // 'secret123'
// Use in Docker-related configurations
// Perfect for parsing process.env or Docker Compose outputs
```
This guide covers the primary features of `@push.rocks/smartstring`, making string manipulation and information extraction simple and efficient in your TypeScript projects.
## API Reference
### Classes
- **`Domain`** - URL/domain parser with component extraction
- **`GitRepo`** - Git repository URL parser and converter
- **`Base64`** - Base64 encoder/decoder with multiple formats
### Modules
- **`create`** - Random string generation
- `createRandomString(pattern, length, options)` - Pattern-based generation
- `createCryptoRandomString()` - Cryptographically secure strings
- **`indent`** - Indentation management
- `indent(text, spaces)` - Add spaces to each line
- `indentWithPrefix(text, prefix)` - Add custom prefix to each line
- `normalize(text)` - Fix inconsistent indentation
- `addPrefix(text, prefix)` - Add prefix to first line only
- **`normalize`** - String normalization
- `standard(text)` - Apply standard normalization
- `normal(text)` - Basic normalization
- **`type`** - String type checking
- `isUtf8(text)` - Validate UTF-8 encoding
- `isBase64(text)` - Validate Base64 format
- **`base64`** - Base64 utilities
- `encode(text)` - Standard Base64 encoding
- `decode(text)` - Standard Base64 decoding
- `encodeUri(text)` - URL-safe Base64 encoding
- `decodeUri(text)` - URL-safe Base64 decoding
- `isBase64(text)` - Check if string is valid Base64
- **`docker`** - Docker utilities
- `makeEnvObject(envArray)` - Convert env array to object
## Real-World Examples
### Building a URL Shortener
```typescript
import { Domain, create, base64 } from '@push.rocks/smartstring';
function createShortUrl(longUrl: string): string {
const domain = new Domain(longUrl);
const shortCode = create.createRandomString('Aa0', 6);
const encoded = base64.encodeUri(`${domain.hostname}${domain.pathname}`);
return `short.ly/${shortCode}`;
}
```
### Processing Code Templates
```typescript
import { indent, normalize } from '@push.rocks/smartstring';
function generateComponent(name: string, props: string[]): string {
const propsSection = props
.map(prop => `${prop}: string;`)
.join('\n');
const template = `
export interface ${name}Props {
${indent.indent(propsSection, 2)}
}
export function ${name}(props: ${name}Props) {
${indent.indent('// Component implementation', 2)}
}
`;
return normalize.standard(template);
}
```
### Git Repository Manager
```typescript
import { GitRepo } from '@push.rocks/smartstring';
class RepoManager {
repos: Map<string, GitRepo> = new Map();
addRepo(url: string): void {
const repo = new GitRepo(url);
this.repos.set(repo.repo, repo);
}
getCloneCommand(name: string, useSSH = false): string {
const repo = this.repos.get(name);
if (!repo) throw new Error('Repository not found');
const url = useSSH ? repo.sshUrl : repo.httpsUrl;
return `git clone ${url}`;
}
}
```
## Browser Support
This package is built for modern environments and includes:
- ✅ Full ES Module support
- ✅ Tree-shaking ready
- ✅ TypeScript definitions
- ✅ Browser-compatible (via bundlers)
- ✅ Node.js 14+ support
## Development
```bash
# Clone the repository
git clone https://code.foss.global/push.rocks/smartstring.git
# Install dependencies
pnpm install
# Run tests
pnpm test
# Build the project
pnpm build
```
## License and Legal Information
@@ -148,4 +376,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.