UNPKG

tiny-crypto-suite

Version:

Tiny tools, big crypto โ€” seamless encryption and certificate handling for modern web and Node apps.

259 lines (182 loc) โ€ข 9.32 kB
# ๐Ÿ“š TinyCryptoParser Documentation `TinyCryptoParser` is a JavaScript utility class that provides robust serialization and deserialization of complex JavaScript data types into JSON-compatible formats. It ensures data safety for encryption ๐Ÿ”’, transmission ๐Ÿ“ก, or storage ๐Ÿ’พ. --- ## โœจ Features - Converts complex data types like `Map`, `Set`, `Buffer`, `Date`, `BigInt`, `Symbol`, and `HTMLElement`. - Provides strong type validation during deserialization โœ…. - Throws errors for unsupported types like `WeakMap`, `WeakSet`, `Promise`, and `Function` ๐Ÿšซ. - Deep serialization and deserialization support ๐Ÿ”. --- ## ๐Ÿ”ฅ Usage Example ```javascript import { TinyCryptoParser } from 'tiny-crypto-suite'; const parser = new TinyCryptoParser(); // Serialize a Map const serialized = parser.serialize(new Map([['key', 'value']])); // Deserialize it back const { value, type } = parser.deserialize(serialized); console.log(value); // Map { 'key' => 'value' } console.log(type); // 'map' ``` --- ## ๐Ÿ›๏ธ Class: `TinyCryptoParser` ### โžก๏ธ serialize(data) ๐Ÿ”น Serializes a JavaScript value into a JSON-compatible string. | Parameter | Type | Description | |:----------|:-----|:------------| | `data` | `any` | The data to serialize. | | Returns | Type | Description | |:--------|:-----|:------------| | `string` | `string` | The serialized JSON string. | โš ๏ธ Throws an error if the data type is unsupported. --- ### โžก๏ธ deserialize(text, expectedType = null) ๐Ÿ”น Deserializes a JSON string back to its original JavaScript object. | Parameter | Type | Description | |:----------|:-----|:------------| | `text` | `string` | The serialized string. | | `expectedType` | `string \| null` | (Optional) Expected type to validate against. | | Returns | Type | Description | |:--------|:-----|:------------| | `DeserializedData` | `{ value: any; type: string }` | The deserialized object and its type. | โš ๏ธ Throws an error if types mismatch when `expectedType` is provided. --- ### โžก๏ธ serializeDeep(data) ๐Ÿ”น Recursively serializes an entire object or array, converting all nested structures. | Parameter | Type | Description | |:----------|:-----|:------------| | `data` | `any` | Data to deeply serialize. | | Returns | Type | Description | |:--------|:-----|:------------| | `string` | `string` | Deeply serialized data. | --- ### โžก๏ธ deserializeDeep(text, expectedType = null) ๐Ÿ”น Recursively deserializes a deeply structured JSON string. | Parameter | Type | Description | |:----------|:-----|:------------| | `text` | `string` | The deeply serialized string. | | `expectedType` | `string \| null` | (Optional) Expected type for validation. | | Returns | Type | Description | |:--------|:-----|:------------| | `DeserializedData` | `{ value: any; type: string }` | The deeply deserialized object. | --- ## ๐Ÿงฉ Supported Types | Type | Serialization | Deserialization | |:-----|:--------------|:----------------| | `number` | โœ… | โœ… | | `boolean` | โœ… | โœ… | | `string` | โœ… | โœ… | | `null` | โœ… | โœ… | | `undefined` | โœ… | โœ… | | `bigint` | โœ… | โœ… | | `symbol` | โœ… | โœ… | | `map` | โœ… | โœ… | | `set` | โœ… | โœ… | | `regexp` | โœ… | โœ… | | `date` | โœ… | โœ… | | `buffer` | โœ… | โœ… | | `array` | โœ… | โœ… | | `object` | โœ… | โœ… | | `htmlElement` | โœ… (Browser Only) | โœ… (Browser Only) | | `function`, `promise`, `weakmap`, `weakset` | โŒ Throws error ๐Ÿšซ | N/A | --- ## โš™๏ธ Internal Mechanisms ### ๐Ÿ› ๏ธ `#valueConvertTypes` - Map of types โ†’ serialization functions. - Handles type-specific transformations. ### ๐Ÿ› ๏ธ `#valueTypes` - Map of types โ†’ deserialization functions. - Converts JSON-compatible representations back into real JavaScript objects. ### ๐Ÿ›ก๏ธ `#validateDeserializedType(expected, actual)` - Ensures that deserialized data matches the expected type. - Throws an error on mismatch. --- ## ๐Ÿงน Notes - Buffer operations depend on Node.js's `Buffer` or browser polyfills. - Deserialization of `HTMLElement` only works inside browser environments ๐ŸŒ. - Symbol descriptions are used for serialization; uniqueness is not guaranteed during restoration. --- ### โœจ `addValueType` Function Documentation The `addValueType` function allows you to add new types and their corresponding converter functions to your instance. This function ensures that both the type and the converter are validated as proper functions and that a type name does not already exist in the list. ๐Ÿš€ ## Method Signature ```javascript addValueType(typeName, getFunction, convertFunction, serializeDeep, deserializeDeep) ``` ### ๐Ÿ“œ Parameters - **`typeName`** `(string)`: - The name of the new type you wish to add. ๐Ÿท๏ธ - This name must be unique within the list of existing types. โ— - **`getFunction`** `(function(data: any) => any)`: - A function that converts a serialized value back into a value representation. ๐Ÿ”„ - This should be used to transform the data into a readable or usable format when needed. - **`convertFunction`** `(function(data: any) => SerializedData)`: - A function responsible for serializing the value into a specific structured format. ๐Ÿ”ง - The serialized value will usually be returned as an object, ensuring you can store it in a consistent way for future conversion. - **`serializeDeep`** `(function(data: any) => any)` _(optional)_: - A function that deeply serializes a value type into a JSON-compatible format. ๐ŸŒ๐Ÿ” - This function is invoked when the data is serialized deeply, meaning if the type is complex (e.g., objects, arrays, or custom types), it will recursively traverse the structure and serialize each element. - For example, you might use this function to serialize a `Map` or `Set`, ensuring that each key-value pair or set element is serialized deeply. - **`deserializeDeep`** `(function(data: any) => any)` _(optional)_: - A function that deeply deserializes a serialized value back to its original format. ๐Ÿ”„๐Ÿ’ก - This function is used to handle cases where you need to recursively parse complex data types (such as objects, arrays, `Map`, or `Set`) back into their original form. - For example, you might use this function to deserialize a `Map` or `Set`, converting it back into a structure that holds the appropriate data types. ### ๐Ÿ”™ Return - This function does not return anything explicitly. It adds the `typeName`, `getFunction`, `convertFunction`, `serializeDeep`, and `deserializeDeep` to their respective collections (`#valueTypes`, `#valueConvertTypes`, `#deepSerialize`, and `#deepDeserialize`). ๐Ÿ“š ### โš ๏ธ Throws - **`Error`**: If either `getFunction` or `convertFunction` is not a function, an error will be thrown. ๐Ÿ›‘ - **`Error`**: If either `serializeDeep` or `deserializeDeep` is defined but not a function, an error will be thrown. ๐Ÿ›‘ - **`Error`**: If the provided `typeName` already exists in the list, an error will be thrown. โš ๏ธ ## ๐Ÿง‘โ€๐Ÿ’ป Usage ### ๐Ÿ“ Example 1: Adding a Type for Regular Expressions ```javascript myInstance.addValueType( 'regexp', /** * @param {*} value - The serialized regular expression string. * @returns {RegExp} The deserialized RegExp object. */ (value) => { const match = value.match(/^\/(.*)\/([gimsuy]*)$/); return match ? new RegExp(match[1], match[2]) : new RegExp(value); }, // Convert (data) => ({ __type: 'regexp', value: data.toString() }), ); ``` ### ๐ŸŒ Example 2: Adding a Type for Array with serialization ```javascript myInstance.addValueType( 'array', /** * @param {*} value - The serialized representation of the array. * @returns {Array<*>} The deserialized array. */ (value) => value, // Convert (data) => ({ __type: 'array', value: data }), // Serialization (data) => data.map(/** @param {*} item */ (item) => myInstance.serializeDeep(item)), // Deserialization (value) => value.map(/** @param {*} item */ (item) => myInstance.deserializeDeep(item).value), ); ``` ### ๐Ÿšจ Error Handling If you try to add a type with an existing name or if the functions are not provided correctly, the function will throw an error. โ— #### โš ๏ธ Example of Duplicate Type Name ```javascript myInstance.addValueType('regexp'); // Error: Type "regexp" already exists. ๐Ÿšซ ``` #### ๐Ÿ›‘ Example of Invalid Function Type ```javascript myInstance.addValueType('number'); // Error: Both getFunction and convertFunction must be functions. โš ๏ธ ``` ## ๐Ÿ” How It Works Internally - The function first validates whether both `getFunction` and `convertFunction` are indeed functions. โœ… - It then checks if the `typeName` already exists in the `#valueTypes` or `#valueConvertTypes` collections. If it does, it throws an error. ๐Ÿšซ - Finally, it adds the new type and its corresponding conversion function to the collections. ๐Ÿ“š ## ๐Ÿ“Œ Important Notes - **Unique Type Names**: Ensure that the `typeName` you provide does not already exist. If you try to add a type with a name that already exists, an error will be thrown. โš ๏ธ - **Function Format**: Both the `getFunction` and `convertFunction` must follow the specified formats. The `getFunction` should serialize the value, and the `convertFunction` should convert it back to a usable format. ๐Ÿ”ง