Compare commits

...

14 Commits

Author SHA1 Message Date
92f36fdb5b Bump 0.30.7
All checks were successful
Build / Publish Docs (push) Successful in 54s
Build / Build NPM Project (push) Successful in 34s
Build / Tag Version (push) Successful in 9s
2026-08-17 14:56:41 -04:00
721fe2dcf8 Patched prototype pollution
Some checks failed
Build / Tag Version (push) Has been cancelled
Build / Build NPM Project (push) Has been cancelled
Build / Publish Docs (push) Has been cancelled
2026-08-17 14:56:18 -04:00
4dfd70f6a7 Added type helpers to isReserved
All checks were successful
Build / Publish Docs (push) Successful in 35s
Build / Build NPM Project (push) Successful in 39s
Build / Tag Version (push) Successful in 9s
2026-08-08 10:51:56 -04:00
af5054192e Added new reserved IP check
All checks were successful
Build / Publish Docs (push) Successful in 38s
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 10s
2026-08-08 10:39:39 -04:00
b7df327cd5 Improved markdown parser
All checks were successful
Build / Publish Docs (push) Successful in 1m35s
Build / Build NPM Project (push) Successful in 1m45s
Build / Tag Version (push) Successful in 10s
2026-07-31 01:42:39 -04:00
aa652bd7e0 Added helpers
All checks were successful
Build / Publish Docs (push) Successful in 1m47s
Build / Build NPM Project (push) Successful in 35s
Build / Tag Version (push) Successful in 8s
2026-07-29 17:51:24 -04:00
e815126807 Added helpers
Some checks failed
Build / Tag Version (push) Has been cancelled
Build / Build NPM Project (push) Has been cancelled
Build / Publish Docs (push) Has been cancelled
2026-07-29 17:51:08 -04:00
6319f810b5 Added safty guardrails to matchAll 2026-07-29 17:42:13 -04:00
91f4abf1f1 Added size getter for cache
All checks were successful
Build / Publish Docs (push) Successful in 38s
Build / Build NPM Project (push) Successful in 44s
Build / Tag Version (push) Successful in 15s
2026-07-24 22:04:45 -04:00
f9971d7ce1 Added size getter for cache
All checks were successful
Build / Build NPM Project (push) Successful in 1m7s
Build / Publish Docs (push) Successful in 1m7s
Build / Tag Version (push) Successful in 13s
2026-07-24 21:56:08 -04:00
fbe46ddb64 Replaced regex search flag with regex operator and added unique/distinct/duplicate functions
All checks were successful
Build / Publish Docs (push) Successful in 1m8s
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 9s
2026-07-22 15:48:02 -04:00
d29d0d5121 PathEvent caching fix
All checks were successful
Build / Publish Docs (push) Successful in 1m47s
Build / Build NPM Project (push) Successful in 34s
Build / Tag Version (push) Successful in 9s
2026-07-14 20:21:05 -04:00
5b3bbdf02c Added node support for uploadWithProgress
All checks were successful
Build / Publish Docs (push) Successful in 54s
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 9s
2026-07-13 22:16:58 -04:00
6b379270a9 Fixed path event dir property
All checks were successful
Build / Publish Docs (push) Successful in 1m3s
Build / Build NPM Project (push) Successful in 36s
Build / Tag Version (push) Successful in 9s
2026-06-15 09:55:38 -04:00
14 changed files with 7824 additions and 595 deletions

1
.gitignore vendored
View File

@@ -10,6 +10,7 @@ uploads
public/momentum*js
junit.xml
/docs/
main.mjs
# Logs
*.log

6927
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +1,46 @@
{
"name": "@ztimson/utils",
"version": "0.29.4",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",
"private": false,
"repository": {
"type": "git",
"url": "https://git.zakscode.com/ztimson/js-utilities"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"scripts": {
"build": "npx tsc && npx vite build",
"docs": "typedoc --cleanOutputDir false --out ./docs --entryPoints src/**/*.ts --readme none",
"test": "npx jest",
"test:coverage": "npx jest --coverage",
"watch": "npx vite build --watch"
},
"dependencies": {
"var-persist": "^1.0.1"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"fake-indexeddb": "^6.2.5",
"jest": "^30.2.0",
"jest-junit": "^16.0.0",
"ts-jest": "^29.4.5",
"typedoc": "^0.28.15",
"typescript": "^5.9.3",
"vite": "^7.2.4",
"vite-plugin-dts": "^4.5.4"
},
"files": [
"dist"
]
}
{
"name": "@ztimson/utils",
"version": "0.30.7",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",
"private": false,
"repository": {
"type": "git",
"url": "https://git.zakscode.com/ztimson/js-utilities"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"scripts": {
"build": "npx tsc && npx vite build",
"docs": "typedoc --cleanOutputDir false --out ./docs --entryPoints src/**/*.ts --readme none",
"test": "npx jest",
"test:coverage": "npx jest --coverage",
"watch": "npx vite build --watch"
},
"dependencies": {
"var-persist": "^1.0.1"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"fake-indexeddb": "^6.2.5",
"jest": "^30.2.0",
"jest-junit": "^16.0.0",
"ts-jest": "^29.4.5",
"typedoc": "^0.28.15",
"typescript": "^5.9.3",
"vite": "^7.2.4",
"vite-plugin-dts": "^4.5.4"
},
"files": [
"dist"
]
}

View File

@@ -31,6 +31,8 @@ export class Cache<K extends string | number | symbol, T> {
/** Await initial loading */
loading = new Promise<void>(r => this._loading = r);
get size() { return this.store.keys().toArray().length }
/**
* Create new cache
* @param {keyof T} key Default property to use as primary key

View File

@@ -83,6 +83,7 @@ export function timestampFilename(name?: string, date: Date | number | string =
/**
* Upload file to URL with progress callback using PromiseProgress
* Works in both browser (with progress) and Node.js (fallback without progress)
*
* @param {{url: string, files: File[], headers?: {[p: string]: string}, withCredentials?: boolean}} options
* @return {PromiseProgress<T>} Promise of request with `onProgress` callback
@@ -93,19 +94,40 @@ export function uploadWithProgress<T>(options: {
headers?: {[key: string]: string};
withCredentials?: boolean;
}): PromiseProgress<T> {
return new PromiseProgress<T>((res, rej, prog) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
options.files.forEach(f => formData.append('file', f));
// Browser environment - use XMLHttpRequest for progress
if (typeof XMLHttpRequest !== 'undefined') {
return new PromiseProgress<T>((res, rej, prog) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
options.files.forEach(f => formData.append('files', f));
xhr.withCredentials = !!options.withCredentials;
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.addEventListener('loadend', () => res(<T>JSONAttemptParse(xhr.responseText)));
xhr.addEventListener('error', () => rej(JSONAttemptParse(xhr.responseText)));
xhr.addEventListener('timeout', () => rej({error: 'Request timed out'}));
xhr.withCredentials = !!options.withCredentials;
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.addEventListener('loadend', () => res(<T>JSONAttemptParse(xhr.responseText)));
xhr.addEventListener('error', () => rej(JSONAttemptParse(xhr.responseText)));
xhr.addEventListener('timeout', () => rej({error: 'Request timed out'}));
xhr.open('POST', options.url);
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.send(formData);
xhr.open('POST', options.url);
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.send(formData);
});
}
// Node.js environment - fallback to fetch without progress
return new PromiseProgress<T>(async (res, rej) => {
try {
const formData = new FormData();
options.files.forEach(f => formData.append('files', f));
const response = await fetch(options.url, {method: 'POST', headers: options.headers || {}, body: formData});
if(!response.ok) {
const error = await response.text();
rej(JSONAttemptParse(error));
} else {
const result = await response.text();
res(<T>JSONAttemptParse(result));
}
} catch (error) {
rej(error);
}
});
}

65
src/html.ts Normal file
View File

@@ -0,0 +1,65 @@
/**
* Decode HTML escaped characters
* @param html HTML to clean up
* @returns {any}
*/
export function decodeHtml(html: string) {
return html
.replace(/&nbsp;/g, '\u00A0')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&cent;/g, '¢')
.replace(/&pound;/g, '£')
.replace(/&yen;/g, '¥')
.replace(/&euro;/g, '€')
.replace(/&copy;/g, '©')
.replace(/&reg;/g, '®')
.replace(/&trade;/g, '™')
.replace(/&times;/g, '×')
.replace(/&divide;/g, '÷')
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
.replace(/&amp;/g, '&'); // Always last!
}
/**
* Parse markdown headers
*
* **NOTE: frontmatter parsing only works 2 layers deep**
*
* @param {string} content
* @returns {{meta: any, content: string} | {meta: {}, content: string}}
*/
export function parseMarkdown(content: string) {
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
if (!match) return {meta: {}, content};
const meta: any = {};
let currentParent: string | null = null;
for (const rawLine of match[1].split('\n')) {
if (!rawLine.trim()) continue;
const indented = /^\s+/.test(rawLine);
const line = rawLine.trim();
const colonIdx = line.indexOf(':');
if (colonIdx === -1) continue;
const key = line.slice(0, colonIdx).trim();
const value = line.slice(colonIdx + 1).trim();
let parsed: any = value;
try { parsed = JSON.parse(value); } catch {}
if (!indented) {
currentParent = value === '' ? key : null;
if (value === '') meta[key] = {};
else meta[key] = parsed;
} else if (currentParent) {
meta[currentParent][key] = parsed;
}
}
return {meta, content: match[2].trim()};
}

View File

@@ -7,10 +7,12 @@ export * from './cache';
export * from './color';
export * from './csv';
export * from './database';
export * from './files';
export * from './emitter';
export * from './errors';
export * from './files';
export * from './html';
export * from './http';
export * from './ip';
export * from './json';
export * from './jwt';
export * from './logger';

77
src/ip.ts Normal file
View File

@@ -0,0 +1,77 @@
/**
* Check if IP address falls within any of the given CIDR ranges
* @param {string} ip IPV4 to check (192.168.0.12)
* @param {...string} cidrs IP ranges to check against (example: 192.168.0.0/24)
* @returns {boolean} Whether IP address is within any range
*/
export function matchesCidr(ip: string, ...cidrs: string[]): boolean {
if (!ip) return false;
if (!cidrs.length) return true;
const ipToInt = (str: string) => str.split('.')
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
return cidrs.some(cidr => {
if (!cidr) return true;
if (!cidr.includes('/')) return ip === cidr; // Single IP
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
});
}
/**
* Convert IPv6 to v4 because who uses that, NAT4Life
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
*/
export function ipV6ToV4(ip: string) {
if(!ip) return null;
const ipv4 = ip.split(':').splice(-1)[0];
if(ipv4 == '1') return '127.0.0.1';
return ipv4;
}
/**
* @deprecated Use isReserved
*
* Check if IP is reserved, e.g. localhost, private IPs, etc.
* @param {string} ip
* @returns {boolean}
*/
export function reservedIp(ip: string): boolean {
if(ip == 'localhost' || ip == '127.0.0.1') return true;
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
}
/**
* Check if IP is within a reserved range
* @param {string} ip
* @returns {null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)'} null if public, class name if reserved
*/
export function isReserved(ip: string): null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)' {
const ipToNumber = (ip: string) => {
return ip.split('.').reduce((acc: number, octet: string) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
};
const ipNum = ipToNumber(ip);
if (ipNum === null) return 'Invalid';
const reserved = [
{ name: "Host", start: ipToNumber("0.0.0.0"), end: ipToNumber("0.255.255.255") },
{ name: "Loopback", start: ipToNumber("127.0.0.0"), end: ipToNumber("127.255.255.255") },
{ name: "Private (Class A)", start: ipToNumber("10.0.0.0"), end: ipToNumber("10.255.255.255") },
{ name: "CGNAT", start: ipToNumber("100.64.0.0"), end: ipToNumber("100.127.255.255") },
{ name: "Private (Class B)", start: ipToNumber("172.16.0.0"), end: ipToNumber("172.31.255.255") },
{ name: "Private (Class C)", start: ipToNumber("192.168.0.0"), end: ipToNumber("192.168.255.255") },
{ name: "Link-Local", start: ipToNumber("169.254.0.0"), end: ipToNumber("169.254.255.255") },
{ name: "IETF Protocol Assignments", start: ipToNumber("192.0.0.0"), end: ipToNumber("192.0.0.255") },
{ name: "Documentation (TEST-NET-1)", start: ipToNumber("192.0.2.0"), end: ipToNumber("192.0.2.255") },
{ name: "Benchmarking", start: ipToNumber("198.18.0.0"), end: ipToNumber("198.19.255.255") },
{ name: "Documentation (TEST-NET-2)", start: ipToNumber("198.51.100.0"), end: ipToNumber("198.51.100.255") },
{ name: "Documentation (TEST-NET-3)", start: ipToNumber("203.0.113.0"), end: ipToNumber("203.0.113.255") },
{ name: "Multicast", start: ipToNumber("224.0.0.0"), end: ipToNumber("239.255.255.255") },
{ name: "Reserved (Class E)", start: ipToNumber("240.0.0.0"), end: ipToNumber("255.255.255.255") }
];
const match = reserved.find(r => ipNum >= r.start && ipNum <= r.end);
return match ? <any>match.name : null;
}

View File

@@ -76,46 +76,6 @@ export function gravatar(email: string, def='mp') {
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
}
/**
* Check if IP address falls within CIDR range
* @param {string} ip IPV4 to check (192.168.0.12)
* @param {string} cidr IP range to check against (example: 192.168.0.0/24)
* @returns {boolean} Whether IP address is within range
*/
export function matchesCidr(ip: string, cidr: string): boolean {
if(!cidr) return true;
if(!ip) return false;
if(!cidr?.includes('/')) return ip === cidr; // Single IP
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
const ipToInt = (str: string) => str.split('.')
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
}
/**
* Convert IPv6 to v4 because who uses that, NAT4Life
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
*/
export function ipV6ToV4(ip: string) {
if(!ip) return null;
const ipv4 = ip.split(':').splice(-1)[0];
if(ipv4 == '1') return '127.0.0.1';
return ipv4;
}
/**
* Check if IP is reserved, e.g. localhost, private IPs, etc.
* @param {string} ip
* @returns {boolean}
*/
export function reservedIp(ip: string): boolean {
if(ip == 'localhost' || ip == '127.0.0.1') return true;
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
}
/**
* Represents a function that listens for events and handles them accordingly.
*

View File

@@ -1,309 +1,311 @@
import {JSONSanitize} from './json.ts';
export type Delta = { [key: string]: any | Delta | null };
/**
* Applies deltas to `target`.
* @param base starting point
* @param deltas List of deltas to apply
* @returns Mutated target
*/
export function applyDeltas(base: any, ...deltas: any[]): any {
function applyDelta(base: any, delta: any): any {
if(delta === null) return null;
if(typeof base !== 'object' || base === null) return delta === undefined ? base : delta;
const result = Array.isArray(base) ? [...base] : { ...base };
for(const key in delta) {
const val = delta[key];
if(val === undefined) delete result[key];
else if(typeof val === 'object' && val !== null && !Array.isArray(val)) result[key] = applyDelta(result[key], val);
else result[key] = val;
}
return result;
}
for(const d of deltas.flat()) base = applyDelta(base, d?.delta ?? d);
return base;
}
/**
* Creates a nested delta that reverts `target` back to `old`.
* @param old - Original object
* @param updated - Modified object
* @returns New changes
*/
export function calcDelta(old: any, updated: any): any {
if(updated == null) return null; // full delete
const delta: any = {};
const isObj = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
for (const key of new Set([...(old ? Object.keys(old) : []), ...(updated ? Object.keys(updated) : [])])) {
const oldVal = old?.[key];
const newVal = updated?.[key];
if(isObj(oldVal) && isObj(newVal)) {
const nested = calcDelta(oldVal, newVal);
if(nested !== null && Object.keys(nested).length > 0) delta[key] = nested;
} else if(JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
delta[key] = newVal;
}
}
return Object.keys(delta).length === 0 ? {} : delta;
}
/**
* Removes any null values from an object in-place
*
* @example
* ```ts
* let test = {a: 0, b: false, c: null, d: 'abc'}
* console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
* ```
*
* @param {T} obj Object reference that will be cleaned
* @param undefinedOnly Ignore null values
* @returns {Partial<T>} Cleaned object
*/
export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
if(obj == null) throw new Error("Cannot clean a NULL value");
if(Array.isArray(obj)) {
obj = <any>obj.filter(o => undefinedOnly ? o !== undefined : o != null);
} else {
Object.entries(obj).forEach(([key, value]) => {
if((undefinedOnly && value === undefined) || (!undefinedOnly && value == null)) delete (<any>obj)[key];
});
}
return <any>obj;
}
/**
* Create a deep copy of an object (vs. a shallow copy of references)
*
* Should be replaced by `structuredClone` once released.
* @param {T} value Object to copy
* @returns {T} Type
*/
export function deepCopy<T>(value: T): T {
if(value == null) return value;
const t = typeof value;
if(t === 'string' || t === 'number' || t === 'boolean' || t === 'function') return value;
try {return structuredClone(value); }
catch { return JSON.parse(JSONSanitize(value)); }
}
/**
* Merge any number of objects into the target
*
* @param target Destination of all properties
* @param sources Objects that will copied into target
* @return {any} The des
*/
export function deepMerge<T>(target: any, ...sources: any[]): T {
sources.forEach(s => {
for(const key in s) {
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
if(!target[key]) target[key] = {};
deepMerge(target[key], s[key]);
} else {
target[key] = s[key];
}
}
});
return target;
}
/**
* Get/set a property of an object using dot notation
*
* @example
* ```ts
* // Get a value
* const name = dotNotation<string>(person, 'firstName');
* const familyCarMake = dotNotation(family, 'cars[0].make');
* // Set a value
* dotNotation(family, 'cars[0].make', 'toyota');
* ```
*
* @type T Return type
* @param {Object} obj source object to search
* @param {string} prop property name (Dot notation & indexing allowed)
* @param {any} set Set object property to value, omit to fetch value instead
* @return {T} property value
*/
export function dotNotation<T>(obj: any, prop: string, set: T): T;
export function dotNotation<T>(obj: any, prop: string): T | undefined;
export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
if(obj == null || !prop) return undefined;
// Split property string by '.' or [index]
return <T>prop.split(/[.[\]]/g).filter(prop => prop.length).reduce((obj, prop, i, arr) => {
if(prop[0] == '"' || prop[0] == "'") prop = prop.slice(1, -1); // Take quotes out
if(!obj?.hasOwnProperty(prop)) {
if(set == undefined) return undefined;
obj[prop] = {};
}
if(set !== undefined && i == arr.length - 1)
return obj[prop] = set;
return obj[prop];
}, obj);
}
/**
* Convert object into URL encoded query string
*
* @example
* ```js
* const query = encodeQuery({page: 1, size: 20});
* console.log(query); // Output: "page=1&size=20"
* ```
*
* @param {any} data - data to convert
* @returns {string} - Encoded form data
*/
export function encodeQuery(data: any): string {
return Object.entries(data).map(([key, value]) =>
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
).join('&');
}
/**
* Recursively flatten a nested object, while maintaining key structure
*
* @example
* ```ts
* const car = {honda: {model: "Civic"}};
* console.log(flattenObj(car)); //Output {honda.model: "Civic"}
* ```
*
* @param obj - Object to flatten
* @param parent - Recursively check if key is a parent key or not
* @param result - Result
* @returns {object} - Flattened object
*/
export function flattenObj(obj: any, parent?: any, result: any = {}) {
if(typeof obj === "object" && !Array.isArray(obj)) {
for(const key of Object.keys(obj)) {
const propName = parent ? `${parent}.${key}` : key;
if(typeof obj[key] === 'object' && obj[key] != null && !Array.isArray(obj[key])) {
flattenObj(obj[key], propName, result);
} else {
result[propName] = obj[key];
}
}
return result;
}
}
/**
* Convert object to FormData
*
* @param target - Object to convert
* @return {FormData} - Form object
*/
export function formData(target: any): FormData {
const data = new FormData();
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
return data;
}
/**
* Check that an object has the following values
*
* @example
* ```ts
* const test = {a: 2, b: 2};
* includes(test, {a: 1}); // true
* includes(test, {b: 1, c: 3}); // false
* ```
*
* @param target Object to search
* @param values Criteria to check against
* @param allowMissing Only check the keys that are available on the target
* @returns {boolean} Does target include all the values
*/
export function includes(target: any, values: any, allowMissing = false): boolean {
if(target == undefined) return allowMissing;
if(Array.isArray(values)) return values.findIndex((e: any, i: number) => !includes(target[i], values[i], allowMissing)) == -1;
const type = typeof values;
if(type != typeof target) return false;
if(type == 'object') {
return Object.keys(values).find(key => !includes(target[key], values[key], allowMissing)) == null;
}
if(type == 'function') return target.toString() == values.toString();
return target == values;
}
/**
* Deep check if two items are equal.
* Handles primitives, objects, arrays, functions, Date, RegExp, and circular references.
*
* @param {any} a - first item to compare
* @param {any} b - second item to compare
* @param {WeakMap<object, object>} [seen] - Internal parameter to track circular references
* @returns {boolean} True if they match
*/
export function isEqual(a: any, b: any, seen = new WeakMap<object, object>()): boolean {
// Simple cases
if(a === b) return true;
if(a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if(a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
// Null checks
if(typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
if(Number.isNaN(a) && Number.isNaN(b)) return true;
if(typeof a === 'function' && typeof b === 'function') return a.toString() === b.toString()
return false;
}
// Circular references
if(seen.has(a)) return seen.get(a) === b;
seen.set(a, b);
const isArrayA = Array.isArray(a);
const isArrayB = Array.isArray(b);
// Array checks
if(isArrayA && isArrayB) {
if(a.length !== b.length) return false;
for(let i = 0; i < a.length; i++) {
if(!isEqual(a[i], b[i], seen)) return false;
}
return true;
}
if(isArrayA !== isArrayB) return false;
// Key & value deep comparison
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if(keysA.length !== keysB.length) return false;
for(const key of keysA) {
if(!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key], seen)) return false;
}
return true;
}
/**
* Experimental: Combine multiple object prototypes into one
*
* @param target Object that will have prototypes added
* @param {any[]} constructors Additionally prototypes that should be merged into target
*/
export function mixin(target: any, constructors: any[]) {
constructors.forEach(c => {
Object.getOwnPropertyNames(c.prototype).forEach((name) => {
Object.defineProperty(
target.prototype,
name,
Object.getOwnPropertyDescriptor(c.prototype, name) ||
Object.create(null)
);
});
});
}
/**
* Run a map function on each property
* @param obj Object that will be iterated
* @param {(key: string, value: any) => any} fn Transformer function - receives key & value
* @returns {{}}
*/
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}
import {JSONSanitize} from './json.ts';
export type Delta = { [key: string]: any | Delta | null };
/**
* Applies deltas to `target`.
* @param base starting point
* @param deltas List of deltas to apply
* @returns Mutated target
*/
export function applyDeltas(base: any, ...deltas: any[]): any {
function applyDelta(base: any, delta: any): any {
if(delta === null) return null;
if(typeof base !== 'object' || base === null) return delta === undefined ? base : delta;
const result = Array.isArray(base) ? [...base] : { ...base };
for(const key in delta) {
const val = delta[key];
if(val === undefined) delete result[key];
else if(typeof val === 'object' && val !== null && !Array.isArray(val)) result[key] = applyDelta(result[key], val);
else result[key] = val;
}
return result;
}
for(const d of deltas.flat()) base = applyDelta(base, d?.delta ?? d);
return base;
}
/**
* Creates a nested delta that reverts `target` back to `old`.
* @param old - Original object
* @param updated - Modified object
* @returns New changes
*/
export function calcDelta(old: any, updated: any): any {
if(updated == null) return null; // full delete
const delta: any = {};
const isObj = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
for (const key of new Set([...(old ? Object.keys(old) : []), ...(updated ? Object.keys(updated) : [])])) {
const oldVal = old?.[key];
const newVal = updated?.[key];
if(isObj(oldVal) && isObj(newVal)) {
const nested = calcDelta(oldVal, newVal);
if(nested !== null && Object.keys(nested).length > 0) delta[key] = nested;
} else if(JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
delta[key] = newVal;
}
}
return Object.keys(delta).length === 0 ? {} : delta;
}
/**
* Removes any null values from an object in-place
*
* @example
* ```ts
* let test = {a: 0, b: false, c: null, d: 'abc'}
* console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
* ```
*
* @param {T} obj Object reference that will be cleaned
* @param undefinedOnly Ignore null values
* @returns {Partial<T>} Cleaned object
*/
export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
if(obj == null) throw new Error("Cannot clean a NULL value");
if(Array.isArray(obj)) {
obj = <any>obj.filter(o => undefinedOnly ? o !== undefined : o != null);
} else {
Object.entries(obj).forEach(([key, value]) => {
if((undefinedOnly && value === undefined) || (!undefinedOnly && value == null)) delete (<any>obj)[key];
});
}
return <any>obj;
}
/**
* Create a deep copy of an object (vs. a shallow copy of references)
*
* Should be replaced by `structuredClone` once released.
* @param {T} value Object to copy
* @returns {T} Type
*/
export function deepCopy<T>(value: T): T {
if(value == null) return value;
const t = typeof value;
if(t === 'string' || t === 'number' || t === 'boolean' || t === 'function') return value;
try {return structuredClone(value); }
catch { return JSON.parse(JSONSanitize(value)); }
}
/**
* Merge any number of objects into the target
*
* @param target Destination of all properties
* @param sources Objects that will copied into target
* @return {any} The des
*/
export function deepMerge<T>(target: any, ...sources: any[]): T {
const BLOCKED = new Set(['__proto__', 'constructor', 'prototype']);
sources.forEach(s => {
for(const key in s) {
if(BLOCKED.has(key) || !Object.prototype.hasOwnProperty.call(s, key)) continue;
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
if(!target[key]) target[key] = {};
deepMerge(target[key], s[key]);
} else {
target[key] = s[key];
}
}
});
return target;
}
/**
* Get/set a property of an object using dot notation
*
* @example
* ```ts
* // Get a value
* const name = dotNotation<string>(person, 'firstName');
* const familyCarMake = dotNotation(family, 'cars[0].make');
* // Set a value
* dotNotation(family, 'cars[0].make', 'toyota');
* ```
*
* @type T Return type
* @param {Object} obj source object to search
* @param {string} prop property name (Dot notation & indexing allowed)
* @param {any} set Set object property to value, omit to fetch value instead
* @return {T} property value
*/
export function dotNotation<T>(obj: any, prop: string, set: T): T;
export function dotNotation<T>(obj: any, prop: string): T | undefined;
export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
if(obj == null || !prop) return undefined;
// Split property string by '.' or [index]
return <T>prop.split(/[.[\]]/g).filter(prop => prop.length).reduce((obj, prop, i, arr) => {
if(prop[0] == '"' || prop[0] == "'") prop = prop.slice(1, -1); // Take quotes out
if(!obj?.hasOwnProperty(prop)) {
if(set == undefined) return undefined;
obj[prop] = {};
}
if(set !== undefined && i == arr.length - 1)
return obj[prop] = set;
return obj[prop];
}, obj);
}
/**
* Convert object into URL encoded query string
*
* @example
* ```js
* const query = encodeQuery({page: 1, size: 20});
* console.log(query); // Output: "page=1&size=20"
* ```
*
* @param {any} data - data to convert
* @returns {string} - Encoded form data
*/
export function encodeQuery(data: any): string {
return Object.entries(data).map(([key, value]) =>
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
).join('&');
}
/**
* Recursively flatten a nested object, while maintaining key structure
*
* @example
* ```ts
* const car = {honda: {model: "Civic"}};
* console.log(flattenObj(car)); //Output {honda.model: "Civic"}
* ```
*
* @param obj - Object to flatten
* @param parent - Recursively check if key is a parent key or not
* @param result - Result
* @returns {object} - Flattened object
*/
export function flattenObj(obj: any, parent?: any, result: any = {}) {
if(typeof obj === "object" && !Array.isArray(obj)) {
for(const key of Object.keys(obj)) {
const propName = parent ? `${parent}.${key}` : key;
if(typeof obj[key] === 'object' && obj[key] != null && !Array.isArray(obj[key])) {
flattenObj(obj[key], propName, result);
} else {
result[propName] = obj[key];
}
}
return result;
}
}
/**
* Convert object to FormData
*
* @param target - Object to convert
* @return {FormData} - Form object
*/
export function formData(target: any): FormData {
const data = new FormData();
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
return data;
}
/**
* Check that an object has the following values
*
* @example
* ```ts
* const test = {a: 2, b: 2};
* includes(test, {a: 1}); // true
* includes(test, {b: 1, c: 3}); // false
* ```
*
* @param target Object to search
* @param values Criteria to check against
* @param allowMissing Only check the keys that are available on the target
* @returns {boolean} Does target include all the values
*/
export function includes(target: any, values: any, allowMissing = false): boolean {
if(target == undefined) return allowMissing;
if(Array.isArray(values)) return values.findIndex((e: any, i: number) => !includes(target[i], values[i], allowMissing)) == -1;
const type = typeof values;
if(type != typeof target) return false;
if(type == 'object') {
return Object.keys(values).find(key => !includes(target[key], values[key], allowMissing)) == null;
}
if(type == 'function') return target.toString() == values.toString();
return target == values;
}
/**
* Deep check if two items are equal.
* Handles primitives, objects, arrays, functions, Date, RegExp, and circular references.
*
* @param {any} a - first item to compare
* @param {any} b - second item to compare
* @param {WeakMap<object, object>} [seen] - Internal parameter to track circular references
* @returns {boolean} True if they match
*/
export function isEqual(a: any, b: any, seen = new WeakMap<object, object>()): boolean {
// Simple cases
if(a === b) return true;
if(a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if(a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
// Null checks
if(typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
if(Number.isNaN(a) && Number.isNaN(b)) return true;
if(typeof a === 'function' && typeof b === 'function') return a.toString() === b.toString()
return false;
}
// Circular references
if(seen.has(a)) return seen.get(a) === b;
seen.set(a, b);
const isArrayA = Array.isArray(a);
const isArrayB = Array.isArray(b);
// Array checks
if(isArrayA && isArrayB) {
if(a.length !== b.length) return false;
for(let i = 0; i < a.length; i++) {
if(!isEqual(a[i], b[i], seen)) return false;
}
return true;
}
if(isArrayA !== isArrayB) return false;
// Key & value deep comparison
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if(keysA.length !== keysB.length) return false;
for(const key of keysA) {
if(!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key], seen)) return false;
}
return true;
}
/**
* Experimental: Combine multiple object prototypes into one
*
* @param target Object that will have prototypes added
* @param {any[]} constructors Additionally prototypes that should be merged into target
*/
export function mixin(target: any, constructors: any[]) {
constructors.forEach(c => {
Object.getOwnPropertyNames(c.prototype).forEach((name) => {
Object.defineProperty(
target.prototype,
name,
Object.getOwnPropertyDescriptor(c.prototype, name) ||
Object.create(null)
);
});
});
}
/**
* Run a map function on each property
* @param obj Object that will be iterated
* @param {(key: string, value: any) => any} fn Transformer function - receives key & value
* @returns {{}}
*/
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}

View File

@@ -76,8 +76,18 @@ export class PathEvent {
/** Whether this path contains glob patterns */
hasGlob!: boolean;
/** Internal cache for PathEvent instances to avoid redundant parsing */
private static pathEventCache: Map<string, PathEvent> = new Map();
/** Internal cache for parsed path data (plain objects, not instances) */
private static pathEventCache: Map<string, {
module: string;
fullPath: string;
dir: string;
path: string;
name: string;
methods: Method[];
hasGlob: boolean;
}> = new Map();
/** Max size for path cache before LRU eviction */
private static readonly MAX_PATH_CACHE_SIZE = 1000;
/** Cache for compiled permissions (path + required permissions → result) */
private static permissionCache: Map<string, PathEvent> = new Map();
/** Max size for permission cache before LRU eviction */
@@ -111,8 +121,20 @@ export class PathEvent {
return;
}
// Check cache and reconstruct from plain object
if(PathEvent.pathEventCache.has(e)) {
Object.assign(this, PathEvent.pathEventCache.get(e)!);
const cached = PathEvent.pathEventCache.get(e)!;
// Move to end (LRU - most recently used)
PathEvent.pathEventCache.delete(e);
PathEvent.pathEventCache.set(e, cached);
this.module = cached.module;
this.fullPath = cached.fullPath;
this.dir = cached.dir;
this.path = cached.path;
this.name = cached.name;
this.methods = new ASet(cached.methods);
this.hasGlob = cached.hasGlob;
return;
}
@@ -128,19 +150,49 @@ export class PathEvent {
this.name = '';
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
this.hasGlob = true;
PathEvent.pathEventCache.set(e, this);
// LRU eviction
if(PathEvent.pathEventCache.size >= PathEvent.MAX_PATH_CACHE_SIZE) {
const firstKey = PathEvent.pathEventCache.keys().next().value;
if(firstKey) PathEvent.pathEventCache.delete(firstKey);
}
PathEvent.pathEventCache.set(e, {
module: this.module,
fullPath: this.fullPath,
dir: this.dir,
path: this.path,
name: this.name,
methods: [...this.methods],
hasGlob: this.hasGlob
});
return;
}
let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || '';
this.path = temp.join('/');
this.dir = temp.length > 2 ? temp.slice(0, -1).join('/') : '';
this.dir = temp.length > 1 ? temp.slice(0, -1).join('/') : '';
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || '';
this.hasGlob = this.fullPath.includes('*');
this.methods = new ASet(<any>method.split(''));
PathEvent.pathEventCache.set(e, this);
// LRU eviction
if(PathEvent.pathEventCache.size >= PathEvent.MAX_PATH_CACHE_SIZE) {
const firstKey = PathEvent.pathEventCache.keys().next().value;
if(firstKey) PathEvent.pathEventCache.delete(firstKey);
}
PathEvent.pathEventCache.set(e, {
module: this.module,
fullPath: this.fullPath,
dir: this.dir,
path: this.path,
name: this.name,
methods: [...this.methods],
hasGlob: this.hasGlob
});
}
/**

View File

@@ -1,44 +1,122 @@
import {JSONAttemptParse, JSONSerialize} from './json.ts';
import {dotNotation} from './objects.ts';
/**
* Filters an array of objects based on a search term and optional regex checking.
*
* @param {Array} rows Array of objects to filter
* @param {string} search The logic string or regext to filter on
* @param {boolean} [regex=false] Treat search expression as regex
* @param {Function} [transform=(r) => r] - Transform rows before filtering
* @return {Array} The filtered array of objects that matched search
*/
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
if(!rows) return [];
return rows.filter(r => {
// Empty search
if(!search) return true;
const value = transform(r);
// Regex search
if(regex) {
return !!Object.values(value).filter((v: any) => {
try { return RegExp(search, 'gm').test(v.toString()); }
catch { return false; }
}).length
} else {
return logicTest(value, search);
}
});
const VALID_FLAGS = new Set([...'dgimsuvy']);
function toRegex(pattern: string, defaultFlags = 'gm'): RegExp | null {
const lit = /^\/(.+)\/([a-zA-Z]*)$/.exec(pattern);
try { return lit ? new RegExp(lit[1], lit[2]) : new RegExp(pattern, defaultFlags); }
catch { return null; }
}
/**
* Test an object against a logic condition. By default values are checked
* @param {string} condition
* @param {object} target
* @return {boolean}
* Filters an array of objects based on a query string.
*
* Supports plain text, regex, boolean/logical operators, and dataset helpers.
*
* **Examples**
* ```js
* search(rows: T[], 'alice'): T[] // Case-Insensitive
* search(rows: T[], 'Alice'): T[] // Case-Sensitive
*
* search(rows: T[], 'name = Alice'): T[] // loose equality
* search(rows: T[], 'name != Alice'): T[] // loose inequality
* search(rows: T[], 'role += admin'): T[] // Contains
* search(rows: T[], 'status -= archived'): T[] // Not Contain
* search(rows: T[], 'age > 18'): T[] // Greater Than
* search(rows: T[], 'age >= 18'): T[] // Greater Than or Equal
* search(rows: T[], 'age < 18'): T[] // Less Than
* search(rows: T[], 'age <= 18'): T[] // Less Than or Equal
*
* search(rows: T[], '/^alice/gi'): T[] // Global Regex
* search(rows: T[], 'name =~ ^Al'): T[] // Regex Match (shorthand)
* search(rows: T[], 'name =~ /^al/i'): T[] // Regex Match (with flags)
* search(rows: T[], 'email !~ /@test\.com$/i'): T[] // Regex Not Match
*
* search(rows: T[], 'unique(email)'): T[] // Unique property values
* search(rows: T[], 'duplicate(email)'): T[] // Duplicate property values
* search(rows: T[], 'distinct(type)'): T[] // Distinct property values
*
* search(rows: T[], 'active && role != admin'): T[] // ANDs
* search(rows: T[], 'email != null || distinct(email)'): T[] // ORs
* ```
*
* @param rows - Array of objects to filter
* @param query - Query string; see supported syntax above
* @param transform - Optional transform applied to each row before matching
* @returns The filtered array of rows
*/
export function search(rows: any[], query: string, transform: (r: any) => any = r => r): any[] {
if (!rows || !query?.trim()) return rows ?? [];
const q = query.trim();
// Global regex: /pattern/flags — strict, whole string, at least one valid flag
const globalRegex = /^\/(.+)\/([a-zA-Z]+)$/.exec(q);
if (globalRegex && [...globalRegex[2]].every(f => VALID_FLAGS.has(f))) {
const re = toRegex(q);
return rows.filter(r => re && Object.values(transform(r)).some((v: any) => {
try { return re.test(v?.toString() ?? ''); } catch { return false; }
}));
}
// Split top-level && into predicates and dataset helpers
const parts = q.split('&&').map(p => p.trim());
const helpers = parts.filter(p => /^(unique|duplicate|distinct)\(\w+\)$/.test(p));
const predicate = parts.filter(p => !helpers.includes(p)).join(' && ');
let filtered = predicate
? rows.filter(r => logicTest(transform(r), predicate))
: [...rows];
for (const h of helpers) {
const [, fn, field] = /^(\w+)\((\w+)\)$/.exec(h)!;
if (fn === 'distinct') continue; // run last
const freq = new Map<any, number>();
filtered.forEach(r => { const v = dotNotation(transform(r), field); freq.set(v, (freq.get(v) ?? 0) + 1); });
filtered = filtered.filter(r => fn === 'unique' ? freq.get(dotNotation(transform(r), field)) === 1 : (freq.get(dotNotation(transform(r), field)) ?? 0) > 1);
}
for (const h of helpers.filter(h => h.startsWith('distinct'))) {
const field = /\((\w+)\)/.exec(h)![1];
const seen = new Set();
filtered = filtered.filter(r => { const v = dotNotation(transform(r), field); return seen.has(v) ? false : !!seen.add(v); });
}
return filtered;
}
/**
* Tests object against a logic string.
*
* **Property operators**
* ```
* 'alice' // case-insensitive
* 'Alice' // case-sensitive
* 'name = Alice' // loose equality (==)
* 'name == Alice' // loose equality
* 'name != Alice' // loose inequality
* 'role += admin' // field contains value
* 'status -= archived' // field does not contain value
* 'age > 21' // greater than
* 'age >= 21' // greater than or equal
* 'age < 21' // less than
* 'age <= 21' // less than or equal
* 'name =~ ^Al' // regex match (shorthand)
* 'name =~ /^al/i' // regex match (with flags)
* 'email !~ /@test\.com$/i' // regex not match
* 'status = active && role != admin' // ANDs
* 'status = active || status = pending' // ORs
* ```
*
* @param target - The object to test
* @param condition - The condition string; see supported syntax above
* @returns Whether the object satisfies the condition
*/
export function logicTest(target: object, condition: string): boolean {
const evalBoolean = (a: any, op: string, b: any): boolean => {
switch(op) {
case '=':
case '==': return a == b;
switch (op) {
case '=': case '==': return a == b;
case '!=': return a != b;
case '+=': return a?.toString().includes(b);
case '-=': return !a?.toString().includes(b);
@@ -46,26 +124,23 @@ export function logicTest(target: object, condition: string): boolean {
case '>=': return a >= b;
case '<': return a < b;
case '<=': return a <= b;
case '~=': try { return !!toRegex(b)?.test(a?.toString() ?? ''); } catch { return false; }
case '!~': try { return !toRegex(b)?.test(a?.toString() ?? ''); } catch { return false; }
default: return false;
}
}
};
const or = condition.split('||').map(p => p.trim()).filter(p => !!p);
return -1 != or.findIndex(p => {
// Make sure all ANDs pass
const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
return and.filter(p => {
// Boolean operator
const prop = /(\S+)\s*(==?|!=|\+=|-=|>=|>|<=|<)\s*(\S+)/g.exec(p);
if(prop) {
const key = Object.keys(target).find(k => k.toLowerCase() == prop[1].toLowerCase());
return evalBoolean(dotNotation<any>(target, key || prop[1]), prop[2], JSONAttemptParse(prop[3]));
}
// Case-sensitive
const v = Object.values(target).map(JSONSerialize).join('');
if(/[A-Z]/g.test(condition)) return v.includes(p);
// Case-insensitive
return v.toLowerCase().includes(p);
}).length == and.length;
});
const resolve = (key: string) => dotNotation<any>(target, Object.keys(target).find(k => k.toLowerCase() === key.toLowerCase()) ?? key);
const evalExpr = (expr: string): boolean => {
const e = expr.trim();
const prop = /^(\S+)\s*(==?|!=|~=|!~|\+=|-=|>=|>|<=|<)\s*(.+)$/.exec(e);
if (prop) return evalBoolean(resolve(prop[1]), prop[2], JSONAttemptParse(prop[3].trim()));
const v = Object.values(target).map(JSONSerialize).join('');
return /[A-Z]/.test(e) ? v.includes(e) : v.toLowerCase().includes(e.toLowerCase());
};
return condition.split('||').map(p => p.trim()).filter(Boolean).some(group =>
group.split('&&').map(p => p.trim()).filter(Boolean).every(evalExpr)
);
}

View File

@@ -27,32 +27,6 @@ export function camelCase(str?: string): string {
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
/**
* Decode HTML escaped characters
* @param html HTML to clean up
* @returns {any}
*/
export function decodeHtml(html: string) {
return html
.replace(/&nbsp;/g, '\u00A0')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&cent;/g, '¢')
.replace(/&pound;/g, '£')
.replace(/&yen;/g, '¥')
.replace(/&euro;/g, '€')
.replace(/&copy;/g, '©')
.replace(/&reg;/g, '®')
.replace(/&trade;/g, '™')
.replace(/&times;/g, '×')
.replace(/&divide;/g, '÷')
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
.replace(/&amp;/g, '&'); // Always last!
}
/**
* Convert number of bytes into a human-readable size
*
@@ -125,7 +99,6 @@ export function kebabCase(str?: string): string {
return wordSegments(str).map(w => w.toLowerCase()).join("-");
}
/**
* Add padding to string
*
@@ -256,18 +229,14 @@ export function strSplice(str: string, start: number, deleteCount: number, inser
return before + insert + after;
}
function titleCase(str: string) {
// Normalize separators: replace underscores and hyphens with spaces
let normalizedStr = str.replace(/(_|-)/g, ' ');
// Handle CamelCase/PascalCase boundaries: insert a space before capital letters
normalizedStr = normalizedStr.replace(/([a-z])([A-Z])/g, '$1 $2');
// Lowercase the whole string, split by any whitespace, and capitalize each word
let words = normalizedStr.toLowerCase().split(/\s+/).filter(Boolean);
const titledWords = words.map(word => {
if (word.length === 0) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
return titledWords.join(' ');
/**
* Converts text to Title Case
*/
export function titleCase(str?: string): string {
if(!str) return '';
return wordSegments(str)
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join(' ');
}
/**
@@ -280,19 +249,16 @@ function titleCase(str: string) {
* @return {RegExpExecArray[]} Found matches.
*/
export function matchAll(value: string, regex: RegExp | string): RegExpExecArray[] {
if(typeof regex === 'string') {
regex = new RegExp(regex, 'g');
}
// https://stackoverflow.com/a/60290199
if(!regex.global) {
throw new TypeError('Regular expression must be global.');
}
if(typeof regex === 'string') regex = new RegExp(regex, 'g');
if(!regex.global) throw new TypeError('Regular expression must be global.');
let ret: RegExpExecArray[] = [];
let match: RegExpExecArray | null;
while((match = regex.exec(value)) !== null) {
ret.push(match);
if(match[0].length === 0) {
regex.lastIndex++;
}
}
return ret;

View File

@@ -17,55 +17,130 @@ describe('Search Utilities', () => {
expect(search(rows, '')).toEqual(rows);
});
it('filters based on a simple property string', () => {
expect(search(rows, 'Alice')).toEqual([rows[0]]);
});
it('filters using regex when regex=true', () => {
expect(search(rows, '^B', true)).toEqual([rows[1]]);
});
it('applies the transform function before filtering', () => {
const transform = (r: any) => ({...r, name: r.name.toLowerCase()});
expect(search(rows, 'alice', false, transform)).toEqual([rows[0]]);
});
it('uses logicTest for non-regex search', () => {
expect(search(rows, 'age == 30')).toEqual([rows[0], rows[2]]);
expect(search(rows, 'id = 2')).toEqual([rows[1]]);
});
it('returns all if search is falsy and regex enabled', () => {
expect(search(rows, '', true)).toEqual(rows);
});
it('handles regex search with special characters', () => {
expect(search(rows, '^[AC]', true)).toEqual([rows[0], rows[2]]);
});
it('ignores case when regex is applied', () => {
expect(search(rows, 'ALICE', true)).toEqual([]);
});
it('performs partial matches for properties when regex=false', () => {
expect(search(rows, 'Da')).toEqual([rows[3]]);
});
it('handles empty array input gracefully', () => {
expect(search([], 'test')).toEqual([]);
});
it('handles numeric values with comparison logic in strings', () => {
expect(search(rows, 'age < 31')).toEqual([rows[0], rows[1], rows[2]]);
it('applies transform before filtering', () => {
const transform = (r: any) => ({...r, name: r.name.toLowerCase()});
expect(search(rows, 'alice', transform)).toEqual([rows[0]]);
});
// New test cases for `+` and `-` operators
it('filters rows using the + operator', () => {
expect(search(rows, 'name += Al')).toEqual([rows[0]]);
describe('plain text', () => {
it('matches case-insensitively when lowercase', () => {
expect(search(rows, 'alice')).toEqual([rows[0]]);
});
it('matches case-sensitively when uppercase present', () => {
expect(search(rows, 'Alice')).toEqual([rows[0]]);
expect(search(rows, 'ALICE')).toEqual([]);
});
it('performs partial matches', () => {
expect(search(rows, 'Da')).toEqual([rows[3]]);
});
});
it('filters rows using the - operator', () => {
expect(search(rows, 'name -= Al')).toEqual([rows[1], rows[2], rows[3]]);
describe('global regex', () => {
it('matches with valid /pattern/flags syntax', () => {
expect(search(rows, '/^B/g')).toEqual([rows[1]]);
});
it('matches multiple rows', () => {
expect(search(rows, '/^[AC]/g')).toEqual([rows[0], rows[2]]);
});
it('respects flags', () => {
expect(search(rows, '/alice/i')).toEqual([rows[0]]);
expect(search(rows, '/alice/g')).toEqual([]);
});
it('does not treat /pattern/ without flags as regex', () => {
expect(search(rows, '/Alice/')).toEqual([]);
});
it('does not treat paths as regex', () => {
const pathRows = [{url: 'users/alice'}];
expect(search(pathRows, 'users/alice')).toEqual(pathRows);
});
});
describe('property operators', () => {
it('filters with equality', () => {
expect(search(rows, 'age == 30')).toEqual([rows[0], rows[2]]);
expect(search(rows, 'id = 2')).toEqual([rows[1]]);
});
it('filters with inequality', () => {
expect(search(rows, 'name != Alice')).toEqual([rows[1], rows[2], rows[3]]);
});
it('filters with contains', () => {
expect(search(rows, 'name += Al')).toEqual([rows[0]]);
});
it('filters with not-contains', () => {
expect(search(rows, 'name -= Al')).toEqual([rows[1], rows[2], rows[3]]);
});
it('filters with numeric comparisons', () => {
expect(search(rows, 'age < 31')).toEqual([rows[0], rows[1], rows[2]]);
expect(search(rows, 'age > 30')).toEqual([rows[3]]);
expect(search(rows, 'age >= 30')).toEqual([rows[0], rows[2], rows[3]]);
});
});
describe('property regex', () => {
it('matches with ~= shorthand', () => {
expect(search(rows, 'name ~= ^Al')).toEqual([rows[0]]);
});
it('matches with ~= /pattern/flags', () => {
expect(search(rows, 'name ~= /^al/i')).toEqual([rows[0]]);
});
it('excludes with !~', () => {
expect(search(rows, 'name !~ ^[AB]')).toEqual([rows[2], rows[3]]);
});
});
describe('logical operators', () => {
it('supports &&', () => {
expect(search(rows, 'age == 30 && name != Alice')).toEqual([rows[2]]);
});
it('supports ||', () => {
expect(search(rows, 'name = Alice || name = Bob')).toEqual([rows[0], rows[1]]);
});
});
describe('dataset helpers', () => {
const dupeRows = [
{id: 1, email: 'a@a.com', type: 'admin'},
{id: 2, email: 'b@b.com', type: 'user'},
{id: 3, email: 'a@a.com', type: 'user'},
{id: 4, email: 'c@c.com', type: 'admin'},
];
it('unique() returns rows where field appears once', () => {
expect(search(dupeRows, 'unique(email)')).toEqual([dupeRows[1], dupeRows[3]]);
});
it('duplicate() returns rows where field appears more than once', () => {
expect(search(dupeRows, 'duplicate(email)')).toEqual([dupeRows[0], dupeRows[2]]);
});
it('distinct() returns one row per field value', () => {
expect(search(dupeRows, 'distinct(type)')).toEqual([dupeRows[0], dupeRows[1]]);
});
it('composes helpers with predicates', () => {
expect(search(dupeRows, 'type = user && duplicate(email)')).toEqual([]);
});
it('applies distinct last', () => {
expect(search(dupeRows, 'duplicate(email) && distinct(type)')).toEqual([dupeRows[0], dupeRows[2]]);
});
});
});
@@ -83,60 +158,63 @@ describe('Search Utilities', () => {
expect(logicTest(obj, 'x < 5')).toBe(false);
});
it('supports case insensitive property search', () => {
expect(logicTest(obj, 'alpha')).toBeTruthy();
expect(logicTest(obj, 'ALPHA')).toBeFalsy();
it('handles contains and not-contains', () => {
expect(logicTest(obj, 'name += Alpha')).toBe(true);
expect(logicTest(obj, 'name += Alp')).toBe(true);
expect(logicTest(obj, 'name += Bet')).toBe(false);
expect(logicTest(obj, 'name -= Alpha')).toBe(false);
expect(logicTest(obj, 'name -= Bet')).toBe(true);
expect(logicTest(obj, 'name += lph')).toBe(true);
expect(logicTest(obj, 'name -= lph')).toBe(false);
});
it('handles logical AND/OR expressions', () => {
it('handles property regex ~=', () => {
expect(logicTest(obj, 'name ~= ^Alp')).toBe(true);
expect(logicTest(obj, 'name ~= /^alp/i')).toBe(true);
expect(logicTest(obj, 'name ~= ^Bet')).toBe(false);
});
it('handles property regex !~', () => {
expect(logicTest(obj, 'name !~ ^Bet')).toBe(true);
expect(logicTest(obj, 'name !~ ^Alp')).toBe(false);
});
it('handles invalid regex gracefully', () => {
expect(logicTest(obj, 'name ~= [invalid')).toBe(false);
});
it('supports plain text case-insensitive search', () => {
expect(logicTest(obj, 'alpha')).toBe(true);
});
it('supports plain text case-sensitive search', () => {
expect(logicTest(obj, 'Alpha')).toBe(true);
expect(logicTest(obj, 'ALPHA')).toBe(false);
});
it('handles logical AND/OR', () => {
expect(logicTest(obj, 'x == 10 && y == 5')).toBe(true);
expect(logicTest(obj, 'x == 10 || y == 100')).toBe(true);
expect(logicTest(obj, 'x == 1 && y == 5')).toBe(false);
});
it('handles numeric ranges', () => {
expect(logicTest(obj, 'x > 5 && x < 15')).toBe(true);
expect(logicTest(obj, 'x > 15')).toBe(false);
});
it('matches keys case-insensitively', () => {
const mixedCaseObj = {TestKey: 123};
expect(logicTest(mixedCaseObj, 'TestKey == 123')).toBe(true);
expect(logicTest(mixedCaseObj, 'testkey == 123')).toBe(true);
});
it('returns false for unsupported operators', () => {
expect(logicTest(obj, 'x === 10')).toBe(false);
});
it('handles invalid condition strings gracefully', () => {
expect(logicTest(obj, 'invalid condition')).toBe(false);
});
it('supports numeric operations with ranges', () => {
expect(logicTest(obj, 'x > 5 && x < 15')).toBe(true);
expect(logicTest(obj, 'x > 15')).toBe(false);
});
it('handles mixed case keys gracefully', () => {
const mixedCaseObj = {TestKey: 123};
expect(logicTest(mixedCaseObj, 'TestKey == 123')).toBe(true);
expect(logicTest(mixedCaseObj, 'testkey == 123')).toBe(true);
});
it('returns false if condition operators are missing', () => {
it('returns false for missing operators', () => {
expect(logicTest(obj, 'x 10')).toBe(false);
});
// New test cases for `+` and `-` operators
it('handles the + operator for inclusion', () => {
expect(logicTest(obj, 'name += Alpha')).toBe(true);
expect(logicTest(obj, 'name += Alp')).toBe(true);
expect(logicTest(obj, 'name += Bet')).toBe(false);
});
it('handles the - operator for exclusion', () => {
expect(logicTest(obj, 'name -= Alpha')).toBe(false);
expect(logicTest(obj, 'name -= Alp')).toBe(false);
expect(logicTest(obj, 'name -= Bet')).toBe(true);
});
it('includes partial matches correctly with +', () => {
expect(logicTest(obj, 'name += lph')).toBe(true);
});
it('excludes partial matches correctly with -', () => {
expect(logicTest(obj, 'name -= lph')).toBe(false);
expect(logicTest(obj, 'name -= xyz')).toBe(true);
});
});
});