# nx-helpers

> A collection of helper functions for nx-intelligence

Latest version **1.5.1** (published 2026-01-04) · ISC license · 0 weekly downloads

## Install

```sh
npm install nx-helpers
pnpm add nx-helpers
yarn add nx-helpers
bun add nx-helpers
```

## Health

**Score 60/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 1.5.1 |
| Published | 2026-01-04 |
| First published | 2025-12-31 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 6 |
| Unpacked size | 125.8 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Maintainers | nx-morpheus |
| Keywords | nx, helpers, merge, deepmerge |

## Links

- npm: https://www.npmjs.com/package/nx-helpers
- npm.io page: https://npm.io/package/nx-helpers

## Dependencies (6)

- [fs](https://npm.io/package/fs.md) ^0.0.1-security
- [path](https://npm.io/package/path.md) ^0.12.7
- [json2md](https://npm.io/package/json2md.md) ^2.0.3
- [talisman](https://npm.io/package/talisman.md) ^1.1.4
- [fast-fuzzy](https://npm.io/package/fast-fuzzy.md) ^1.12.0
- [json-to-markdown-table](https://npm.io/package/json-to-markdown-table.md) ^1.0.0

## Alternatives

- [lodash.assign](https://npm.io/package/lodash.assign.md) — 2.3M weekly downloads
- [lodash.chunk](https://npm.io/package/lodash.chunk.md) — 1.8M weekly downloads
- [react-native-ios-utilities](https://npm.io/package/react-native-ios-utilities.md) — 138.5K weekly downloads
- [@technically/lodash](https://npm.io/package/@technically/lodash.md) — 50.9K weekly downloads
- [@fluid-topics/ft-icon](https://npm.io/package/@fluid-topics/ft-icon.md) — 20.6K weekly downloads

## Recent versions

- 1.5.1 (latest) — 2026-01-04
- 1.5.0 — 2026-01-01
- 1.2.7 — 2025-12-31
- 1.2.6 — 2025-12-31
- 1.2.5 — 2025-12-31
- 1.2.0 — 2025-12-31
- 1.1.0 — 2025-12-31
- 1.0.3 — 2025-12-31
- 1.0.0 — 2025-12-31

## README

# nx-helpers

A collection of high-performance utility functions for deep-merging and object manipulation, specifically designed for Nx Intelligence projects.

## Installation

```bash
npm install nx-helpers
```

## Features

### `mergeNoRedundancy<T>(base: T, override: Partial<T>): T`

Deep-merges a `base` object with an `override` object with the following rules:

- **Plain Objects**: Merged recursively.
- **Arrays**: Merged as a **UNION** (deduplicated) using deep equality comparison.
- **Primitives/Other**: The `override` value always wins.

#### Example

```typescript
import { mergeNoRedundancy } from 'nx-helpers';

const base = {
  id: 1,
  tags: ["typescript", "nx"],
  metadata: {
    version: "1.0.0",
    active: true
  }
};

const override = {
  tags: ["nx", "ai"],
  metadata: {
    active: false
  }
};

const result = mergeNoRedundancy(base, override);

console.log(result);
/*
{
  id: 1,
  tags: ["typescript", "nx", "ai"],
  metadata: {
    version: "1.0.0",
    active: false
  }
}
*/
```

### `loadJson<T>(filePath: string): T`

Loads and parses a JSON file synchronously. Supports both relative and absolute paths.

#### Example

```typescript
import { loadJson } from 'nx-helpers';

const config = loadJson('./config.json');
console.log(config.name);
```

### `mergeMultiple<T>(...objects: Partial<T>[]): T`

Merges multiple objects sequentially. Later objects have higher priority.

```typescript
const result = mergeMultiple(obj1, obj2, obj3);
```

### `mergeWithRoles(items: MergableItem[]): any`

Wraps values in objects keyed by their camelCased role and merges them. Useful for combining different data sources into a single structured object.

```typescript
const items = [
  { role: 'user info', value: { name: 'John' } },
  { role: 'tags', value: ['a', 'b'] }
];
const result = mergeWithRoles(items);
// { userInfo: { name: 'John' }, tags: ['a', 'b'] }
```

### `anyToMarkdownString(input: unknown, opts?: AnyToMarkdownOptions): string`
The primary high-level helper for converting any value into a clean Markdown string. It handles strings, primitives, objects, and arrays with built-in error handling and fallback mechanisms.

- **Strings**: Returned as-is.
- **Primitives**: Converted to strings.
- **Objects/Arrays**: Converted via `json2mdWithTables`.
- **Fallback**: If conversion fails, it defaults to a prettified `JSON.stringify`.

```typescript
import { anyToMarkdownString } from 'nx-helpers';

const data = {
  title: "Project Alpha",
  metadata: { version: 1, tags: ["ai", "nx"] }
};

console.log(anyToMarkdownString(data, { level: 1 }));
/*
# Title
Project Alpha

# Metadata
## Version
1

## Tags
ai, nx
*/
```

### `json2mdWithTables(json: any, level?: number): string`
Recursive JSON-to-Markdown converter that:
- **Title Cases** all keys and headings.
- **Converts Arrays of Objects** into clean Markdown tables.
- **Converts Arrays of Primitives** into bulleted lists.
- **Maintains Hierarchy** by automatically incrementing heading levels (H1, H2, etc.).

### `json2table(rows: any[], columns?: string[]): string`
Converts an array of objects to a Markdown table, with headers automatically transformed to **Title Case**. It uses `json-to-markdown-table` if available, with a robust fallback.

## String Helpers

### `toCamelCase(input: string): string`
Converts strings to camelCase format. Handles spaces, dashes, and underscores.

```typescript
toCamelCase("hello-world"); // "helloWorld"
toCamelCase("User Name");   // "userName"
```

### `fromCamelToTitle(camelCase: string): string`
Converts camelCase strings to readable Title Case.

```typescript
fromCamelToTitle("helloWorld"); // "Hello World"
```

### `toTitleCase(input: string): string`
Converts any string (kebab-case, snake_case, camelCase) to Title Case.

```typescript
toTitleCase("hello-world"); // "Hello World"
toTitleCase("user_profile"); // "User Profile"
```

## Advanced String Matching (`matcher.tunable.ts`)

The package includes a powerful, tunable fuzzy string matcher designed for mapping ambiguous input (like LLM outputs or human typing) to strict schema keys.

### Core Functions
- `scoreStrings(a, b, cfg)`: Computes a similarity score (0..1) using a weighted blend of metrics (Jaro-Winkler, Dice, Levenshtein, Jaccard Tokens, Fast-Fuzzy).
- `bestMatchOneToMany(term, candidates, cfg, kind)`: Finds the single best match above a threshold.
- `bestMatchManyToMany(listA, listB, cfg, options)`: Performs optimal unique assignment between two sets of strings.

### Tunable Configuration
You can customize the matcher behavior via the `MatcherConfig`:
```typescript
const cfg = defaultMatcherConfig();
cfg.weights.jaroWinkler = 0.4; // give more weight to Jaro-Winkler
cfg.thresholds.titleToKey = 0.65; // tighten the requirement for matching
```

### Calibration
Once you have ground-truth examples, you can auto-tune the weights:
```typescript
const examples = [
  { a: "Max Tokens", b: "maxTokens", label: 1, kind: "titleToKey" },
  { a: "Temp", b: "maxTokens", label: 0, kind: "titleToKey" },
];
const { bestConfig } = calibrateMatcher(examples, defaultConfig);
// Use bestConfig for your production matching
```

### Alias Auto-Learning
Propose new aliases by mining successful historical mappings:
```typescript
const mappings = [ { from: "ipaddr", to: "ip" }, { from: "IP Address", to: "ip" } ];
const { proposedAliases } = learnAliasesFromMappings(mappings, cfg);
// proposedAliases = { ip: ["ipaddr", "ip address"] }
```

## JSON Transformation & Schema Validation (`transformers.ts`)

The `JSONTransformer` uses the tunable matcher to "fix" messy/ambiguous JSON data to match a target schema.

### Schema Definitions
```typescript
import { string, number, boolean, array, object } from 'nx-helpers';

const schema = object({
  fullName: string,
  profile: object({
    age: number,
    tags: array(string)
  })
});
```

### Capabilities
- **Fuzzy Key Matching**: Maps `Name` -> `fullName`, `Tags` -> `tags`.
- **Type Casting**: Converts `"30"` to `30`, `"true"` to `true`, `"a,b,c"` to `["a","b","c"]`.
- **Structural Cleanup**: 
    - Wraps single values in arrays: `"ai"` -> `["ai"]`.
    - Converts strings to objects: `"msg"` -> `{ message: "msg" }` (if schema has 1 property).
    - Recover nested keys from root: `{ age: 30 }` -> `{ profile: { age: 30 } }`.

```typescript
const transformer = new JSONTransformer(schema);
const { status, result } = transformer.transform({
  "Name": "Alice",
  "age": "25",
  "tags": "dev,ts"
});

// result = { fullName: "Alice", profile: { age: 25, tags: ["dev", "ts"] } }
// status = "fixed"
```

## Running Examples

You can see all these features in action by running the included examples via `tsx`:

```bash
npx tsx src/verify.ts
```

## Development & Verification

To verify the library logic and run transformation examples:

```bash
npx tsx src/verify.ts
```

## License

ISC

---
_Source: https://npm.io/package/nx-helpers · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
