npm package: @schematize/util-common
Description: Schematize Common Utility Library
Author: Benjamin Bytheway
Latest version: 0.6.3

# @schematize/util-common

A comprehensive utility library providing common functions and constants for the Schematize ecosystem.

## Overview

The Schematize Common Utility Library provides a collection of essential utility functions, constants, and data structures used across the Schematize platform.  It includes string manipulation, data encoding/decoding, object manipulation, and various helper functions.

## Features

- **String Utilities**: Case conversion, encoding/decoding, and manipulation functions
- **Object Manipulation**: Deep property setting and deletion
- **Data Encoding**: Base64, Base64URL, and custom radix-64 encoding
- **MIME Type Support**: Comprehensive MIME type to file extension mapping
- **BigInt Support**: Large number handling and compatibility checking
- **Constants**: Permission flags, symbols, and common string constants
- **Data Structures**: BigMap for handling large datasets

## Dependencies

- `@schematize/refs`: JavaScript reference implementations
- `@schematize/metamodel`: UML metamodel library

## Installation

```bash
npm install @schematize/util-common
```

## Usage

### Basic Import

```javascript
import {
  // String utilities
  upperFirst,
  lowerFirst,
  
  // Object manipulation
  setDeep,
  deleteDeep,
  
  // Encoding/decoding
  toString64,
  fromString64,
  toBase64WithoutPadding,
  fromBase64WithoutPadding,
  
  // Constants
  CRUD,
  ADMIN,
  
  // Data structures
  BigMap,
  
  // MIME types
  mimeTypeToFileExtension
} from '@schematize/util-common';
```

## API Reference

### String Utilities

#### upperFirst

Capitalizes the first character of a string.

##### Parameters

- `string` (String): The string to capitalize

##### Returns

- **String**: The string with the first character capitalized

##### Usage

```javascript
import { upperFirst } from '@schematize/util-common';

console.log(upperFirst('hello')); // 'Hello'
console.log(upperFirst('world')); // 'World'
console.log(upperFirst('')); // ''
```

#### lowerFirst

Lowercases the first character of a string.

##### Parameters

- `string` (String): The string to lowercase

##### Returns

- **String**: The string with the first character lowercased

##### Usage

```javascript
import { lowerFirst } from '@schematize/util-common';

console.log(lowerFirst('Hello')); // 'hello'
console.log(lowerFirst('World')); // 'world'
console.log(lowerFirst('')); // ''
```

### Object Manipulation

#### setDeep

Sets a value at a deep path in an object, creating intermediate objects as needed.

##### Parameters

- `item` (Object): The object to modify
- `path` (Array): Array of property names representing the path
- `value` (Any): The value to set

##### Returns

- **undefined**: Modifies the object in place

##### Usage

```javascript
import { setDeep } from '@schematize/util-common';

const obj = {};
setDeep(obj, ['user', 'profile', 'name'], 'John Doe');
console.log(obj.user.profile.name); // 'John Doe'

// Creates intermediate objects automatically
setDeep(obj, ['settings', 'theme'], 'dark');
console.log(obj.settings.theme); // 'dark'
```

#### deleteDeep

Deletes a property at a deep path in an object.

##### Parameters

- `item` (Object): The object to modify
- `path` (Array): Array of property names representing the path

##### Returns

- **undefined**: Modifies the object in place

##### Usage

```javascript
import { deleteDeep } from '@schematize/util-common';

const obj = {
  user: {
    profile: {
      name: 'John Doe',
      email: 'john@example.com'
    }
  }
};

deleteDeep(obj, ['user', 'profile', 'email']);
console.log(obj.user.profile.email); // undefined
```

### Data Encoding

#### toString64

Converts a BigInt to a base-64 string representation.

##### Parameters

- `n` (BigInt): The BigInt to convert

##### Returns

- **String**: Base-64 encoded string

##### Usage

```javascript
import { toString64 } from '@schematize/util-common';

const bigNum = 123456789n;
const encoded = toString64(bigNum);
console.log(encoded); // Base-64 string representation
```

#### fromString64

Converts a base-64 string back to a BigInt.

##### Parameters

- `s` (String): The base-64 encoded string

##### Returns

- **BigInt**: The decoded BigInt value

##### Usage

```javascript
import { fromString64 } from '@schematize/util-common';

const encoded = 'someBase64String';
const decoded = fromString64(encoded);
console.log(decoded); // BigInt value
```

#### toBase64WithoutPadding

Encodes a string to Base64URL format (RFC 7636) without padding.

##### Parameters

- `str` (String): The string to encode

##### Returns

- **String**: Base64URL encoded string without padding

##### Usage

```javascript
import { toBase64WithoutPadding } from '@schematize/util-common';

const encoded = toBase64WithoutPadding('Hello World');
console.log(encoded); // Base64URL string without padding
```

#### fromBase64WithoutPadding

Decodes a Base64URL string back to the original string.

##### Parameters

- `str` (String): The Base64URL encoded string

##### Returns

- **String**: The decoded string

##### Usage

```javascript
import { fromBase64WithoutPadding } from '@schematize/util-common';

const encoded = 'SGVsbG8gV29ybGQ';
const decoded = fromBase64WithoutPadding(encoded);
console.log(decoded); // 'Hello World'
```

### Data Structures

#### BigMap

A Map-like data structure that can handle very large datasets by using multiple internal Maps.

##### Features

- **Large Capacity**: Can handle datasets larger than single Map limits
- **Map-like API**: Familiar Map interface (has, get, set, entries)
- **Automatic Scaling**: Creates new internal Maps as needed

##### Usage

```javascript
import { BigMap } from '@schematize/util-common';

const bigMap = new BigMap();

// Use like a regular Map
bigMap.set('key1', 'value1');
bigMap.set('key2', 'value2');

console.log(bigMap.has('key1')); // true
console.log(bigMap.get('key1')); // 'value1'
console.log(bigMap.size); // 2

// Iterate over entries
for (const [key, value] of bigMap) {
  console.log(key, value);
}
```

### Utility Functions

#### isCompatibleBigInt

Checks if a value can be safely converted to and from a BigInt without data loss.

##### Parameters

- `v` (Any): The value to check

##### Returns

- **Boolean**: True if the value is BigInt compatible

##### Usage

```javascript
import { isCompatibleBigInt } from '@schematize/util-common';

console.log(isCompatibleBigInt('123')); // true
console.log(isCompatibleBigInt('123.45')); // false
console.log(isCompatibleBigInt('abc')); // false
```

### Constants

#### Permission Flags

Bitwise permission constants for access control:

```javascript
import { NONE, READ, CREATE, UPDATE, DELETE, ADMIN, WRITE, CRUD, FULL } from '@schematize/util-common';

// Individual permissions
const userPermissions = READ | UPDATE; // Can read and update

// Combined permissions
const adminPermissions = FULL; // All permissions
const writePermissions = WRITE; // Create, Update, Delete
const crudPermissions = CRUD; // Create, Read, Update, Delete
```

#### Database Permission Strings

String representations of permissions for database storage:

```javascript
import { DB_NONE, DB_READ, DB_CREATE, DB_UPDATE, DB_DELETE, DB_ADMIN, DB_WRITE, DB_CRUD, DB_FULL } from '@schematize/util-common';

// Store permissions in database
const dbPermissions = DB_CRUD; // 'b'01111''
```

#### String Constants

Common string constants for consistency and also for creating super-minified functions:

```javascript
import { 
  S_call, S_apply, S_click, S_change, S_modify,
  S_touchstart, S_touchmove, S_touchend,
  S_mousedown, S_mouseup, S_mousemove,
  S_pointerdown, S_pointerup, S_pointermove
} from '@schematize/util-common';

// Use for event handling
element.addEventListener(S_click, handler);
element.addEventListener(S_touchstart, handler);
```

### MIME Type Support

#### mimeTypeToFileExtension

A comprehensive mapping of MIME types to file extensions.

##### Usage

```javascript
import { mimeTypeToFileExtension } from '@schematize/util-common';

console.log(mimeTypeToFileExtension['image/jpeg']); // '.jpg'
console.log(mimeTypeToFileExtension['application/pdf']); // '.pdf'
console.log(mimeTypeToFileExtension['text/html']); // '.html'

// Get extension for a MIME type
function getFileExtension(mimeType) {
  return mimeTypeToFileExtension[mimeType] || '.bin';
}
```

### Additional Utilities

#### stringDeclarationShortener

Optimizes string declarations by finding repeated substrings and replacing them with shorter variable names to reduce code size.  This is particularly helpful with JSON strings, and in general is being used to make the interchange json files much smaller.

##### Parameters

- `name` (String): The name of the variable to create
- `string` (String): The string to optimize
- `options` (Object, optional): Configuration options

##### Returns

- **String**: Optimized JavaScript code with shortened variable declarations

##### Usage

```javascript
import { stringDeclarationShortener } from '@schematize/util-common';

const longString = 'This is a very long string with repeated patterns...';
const optimized = stringDeclarationShortener('myString', longString);
console.log(optimized); // Optimized code with shorter variable names
```

#### adjustOpacityHex

Blends two hex colors with a specified opacity to create a new color.

##### Parameters

- `opacity` (Number): Opacity value between 0 and 1
- `foregroundColor` (String): Hex color string (e.g., '#ff0000')
- `backgroundColor` (String): Hex color string (e.g., '#0000ff')

##### Returns

- **String**: Blended hex color string

##### Usage

```javascript
import { adjustOpacityHex } from '@schematize/util-common';

const blended = adjustOpacityHex(0.5, '#ff0000', '#0000ff');
console.log(blended); // Blended color between red and blue
```

#### dataURLToContents

Extracts the content portion from a data URL, handling both regular images and SVG.

##### Parameters

- `dataURL` (String): The data URL to extract content from
- `contents` (String, optional): Default content if extraction fails

##### Returns

- **String**: The extracted content from the data URL

##### Usage

```javascript
import { dataURLToContents } from '@schematize/util-common';

const dataURL = 'data:image/svg+xml;charset=utf-8,<svg>...</svg>';
const content = dataURLToContents(dataURL);
console.log(content); // '<svg>...</svg>'
```

#### imageToDataURL

Converts an image object to a data URL string.

##### Parameters

- `image` (Object): Image object with type, contents, and optional isBase64Encoded properties
- `dataURL` (String, optional): Default data URL if conversion fails

##### Returns

- **String**: Data URL string representation of the image

##### Usage

```javascript
import { imageToDataURL } from '@schematize/util-common';

const image = {
  type: 'image/svg+xml',
  contents: '<svg>...</svg>'
};
const dataURL = imageToDataURL(image);
console.log(dataURL); // 'data:image/svg+xml;charset=utf-8,<svg>...</svg>'
```

#### sanitizeHtml

Sanitizes HTML by escaping special characters to prevent XSS attacks.

##### Parameters

- `string` (String): The string to sanitize

##### Returns

- **String**: HTML-escaped string

##### Usage

```javascript
import { sanitizeHtml } from '@schematize/util-common';

const userInput = '<script>alert("xss")</script>';
const safe = sanitizeHtml(userInput);
console.log(safe); // '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
```

#### svgDecode

Decodes URL-encoded SVG content back to readable SVG markup.

##### Parameters

- `string` (String): URL-encoded SVG string

##### Returns

- **String**: Decoded SVG markup

##### Usage

```javascript
import { svgDecode } from '@schematize/util-common';

const encoded = '%3Csvg%3E%3C/svg%3E';
const decoded = svgDecode(encoded);
console.log(decoded); // '<svg></svg>'
```

#### svgEncode

Encodes SVG markup for safe use in data URLs by URL-encoding special characters.

##### Parameters

- `string` (String): SVG markup string

##### Returns

- **String**: URL-encoded SVG string

##### Usage

```javascript
import { svgEncode } from '@schematize/util-common';

const svg = '<svg><path d="M0,0 L10,10"/></svg>';
const encoded = svgEncode(svg);
console.log(encoded); // URL-encoded SVG string
```

## License

MIT License - see LICENSE file for details.

## Author

Benjamin Bytheway