From bcc76c75615dae145543b355fdfe49f101879ac0 Mon Sep 17 00:00:00 2001 From: ztimson Date: Thu, 27 Nov 2025 20:48:04 -0500 Subject: [PATCH] Glob support and path scoring --- package.json | 2 +- src/path-events.ts | 261 +++++++++++++++++++++++++++++++------- tests/path-events.spec.ts | 117 ++++++++++++++++- 3 files changed, 328 insertions(+), 52 deletions(-) diff --git a/package.json b/package.json index 5694f8d..8596c4e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.27.10", + "version": "0.27.11", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/path-events.ts b/src/path-events.ts index 7c79e58..e50c94f 100644 --- a/src/path-events.ts +++ b/src/path-events.ts @@ -55,9 +55,10 @@ export function PES(str: TemplateStringsArray, ...args: any[]) { export class PathError extends Error { } /** - * A event broken down into its core components for easy processing - * Event Structure: `module/path/name:property:method` + * A event broken down into its core components for easy processing + * Event Structure: `module/path/name:method` * Example: `users/system:crud` or `storage/some/path/file.txt:r` + * Supports glob patterns: `users/*:r` or `storage/**:rw` */ export class PathEvent { /** First directory in path */ @@ -66,13 +67,19 @@ export class PathEvent { fullPath!: string; /** Path including the name, excluding the module */ path!: string; - /** Last sagment of path */ + /** Last segment of path */ name!: string; /** List of methods */ methods!: ASet; + /** Whether this path contains glob patterns */ + hasGlob!: boolean; /** Internal cache for PathEvent instances to avoid redundant parsing */ private static pathEventCache: Map = new Map(); + /** Cache for compiled permissions (path + required permissions → result) */ + private static permissionCache: Map = new Map(); + /** Max size for permission cache before LRU eviction */ + private static readonly MAX_PERMISSION_CACHE_SIZE = 1000; /** All/Wildcard specified */ get all(): boolean { return this.methods.has('*') } @@ -108,17 +115,44 @@ export class PathEvent { return; } - let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':'); - if(!method) method = scope || '*'; - if(p == '*' || (!p && method == '*')) { - p = ''; - method = '*'; + let [p, method] = e.replaceAll(/\/{2,}/g, '/').split(':'); + if(!method) method = '*'; + + // Handle special cases + if(p === '' || p === undefined) { + // Empty string matches nothing + this.module = ''; + this.path = ''; + this.fullPath = ''; + this.name = ''; + this.methods = new ASet(['n']); + this.hasGlob = false; + PathEvent.pathEventCache.set(e, this); + return; } + + if(p === '*') { + // Wildcard means any path any event + this.module = ''; + this.path = ''; + this.fullPath = '**'; + this.name = ''; + this.methods = new ASet(['*']); + this.hasGlob = true; + PathEvent.pathEventCache.set(e, this); + return; + } + let temp = p.split('/').filter(p => !!p); this.module = temp.splice(0, 1)[0] || ''; this.path = temp.join('/'); this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`; this.name = temp.pop() || ''; + + // Don't trim /** - it's needed for glob matching to work properly + // Only trim if there's something after it which won't happen with our parsing + + this.hasGlob = this.fullPath.includes('*'); this.methods = new ASet(method.split('')); // Store in cache @@ -130,6 +164,87 @@ export class PathEvent { PathEvent.pathEventCache.clear(); } + /** Clear the permission cache */ + static clearPermissionCache(): void { + PathEvent.permissionCache.clear(); + } + + /** + * Score a path for specificity ranking (lower = more specific = higher priority) + * @private + */ + private static scoreSpecificity(path: string): number { + if (path === '**' || path === '') return Number.MAX_SAFE_INTEGER; // Least specific + + const segments = path.split('/').filter(p => !!p); + // Base score: number of segments (more segments = more specific = lower score) + let score = -segments.length; + + // Penalty for wildcards (makes them less specific than exact matches) + // ADD to score to make it HIGHER/WORSE + segments.forEach(seg => { + if (seg === '**') score += 0.5; + else if (seg === '*') score += 0.25; + }); + + return score; + } + + /** + * Check if a path matches a glob pattern + * @private + */ + private static pathMatchesGlob(path: string, pattern: string): boolean { + // Handle exact match + if (pattern === path) return true; + + const pathParts = path.split('/').filter(p => !!p); + const patternParts = pattern.split('/').filter(p => !!p); + + let pathIdx = 0; + let patternIdx = 0; + + while (patternIdx < patternParts.length && pathIdx < pathParts.length) { + const patternPart = patternParts[patternIdx]; + + if (patternPart === '**') { + // ** matches zero or more path segments + if (patternIdx === patternParts.length - 1) { + // ** at the end matches everything + return true; + } + // Try matching from next pattern part onwards + const nextPattern = patternParts[patternIdx + 1]; + while (pathIdx < pathParts.length) { + if (PathEvent.pathMatchesGlob(pathParts.slice(pathIdx).join('/'), patternParts.slice(patternIdx + 1).join('/'))) { + return true; + } + pathIdx++; + } + return false; + } else if (patternPart === '*') { + // * matches exactly one segment + pathIdx++; + patternIdx++; + } else { + // Exact match required + if (patternPart !== pathParts[pathIdx]) { + return false; + } + pathIdx++; + patternIdx++; + } + } + + // Check if we've consumed all pattern parts + if (patternIdx < patternParts.length) { + // Remaining pattern parts must all be ** to match + return patternParts.slice(patternIdx).every(p => p === '**'); + } + + return pathIdx === pathParts.length; + } + /** * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are * combined until a "none" is reached @@ -138,40 +253,79 @@ export class PathEvent { * @return {PathEvent} Final combined permission */ static combine(...paths: (string | PathEvent)[]): PathEvent { - let hitNone = false; - const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p)) - .toSorted((p1, p2) => { - const l1 = p1.fullPath.length, l2 = p2.fullPath.length; - return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0); - }).reduce((acc, p) => { - if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc; - if(p.none) hitNone = true; - if(!acc) return p; - if(hitNone) return acc; - acc.methods = new ASet([...acc.methods, ...p.methods]); - return acc; - }, null); - return combined; + const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p)); + + // Sort by specificity: lower score = more specific = higher priority + const sorted = parsed.toSorted((p1, p2) => { + const score1 = PathEvent.scoreSpecificity(p1.fullPath); + const score2 = PathEvent.scoreSpecificity(p2.fullPath); + return score1 - score2; + }); + + let result: PathEvent | null = null; + + for (const p of sorted) { + if (!result) { + result = p; + } else { + // Only combine if current result's path starts with or matches the new permission's path + if (result.fullPath.startsWith(p.fullPath)) { + // If we hit a none at a parent level, stop here + if (p.none) { + break; + } + // Combine methods for permissions in the same hierarchy + result.methods = new ASet([...result.methods, ...p.methods]); + } + } + } + + return result || new PathEvent(''); } /** * Filter a set of paths based on the target * * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered - * @param filter {...PathEvent} Must container one of - * @return {boolean} Whether there is any overlap + * @param filter {...PathEvent} Must contain one of + * @return {PathEvent[]} Filtered results */ static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] { const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe)); const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe)); - return parsedTarget.filter(t => !!parsedFilter.find(r => { - const wildcard = r.fullPath == '*' || t.fullPath == '*'; - const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath; - const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath; - const scope = p1.startsWith(p2) || p2.startsWith(p1); - const methods = r.all || t.all || r.methods.intersection(t.methods).length; - return (wildcard || scope) && methods; - })); + + return parsedTarget.filter(t => { + const combined = PathEvent.combine(t); + return !!parsedFilter.find(r => PathEvent.matches(r, combined)); + }); + } + + /** + * Check if a filter pattern matches a target path + * @private + */ + private static matches(pattern: PathEvent, target: PathEvent): boolean { + // Handle special cases + if (pattern.fullPath === '' || target.fullPath === '') return false; + if (pattern.fullPath === '*' || target.fullPath === '*') return pattern.methods.has('*') || target.methods.has('*') || pattern.methods.intersection(target.methods).length > 0; + + // Check methods + const methodsMatch = pattern.all || target.all || pattern.methods.intersection(target.methods).length > 0; + if (!methodsMatch) return false; + + // Check paths + if (!pattern.hasGlob && !target.hasGlob) { + // Fast path: no globs, use string comparison + return pattern.fullPath === target.fullPath; + } + + if (pattern.hasGlob) { + // Pattern has glob, match target against it + return this.pathMatchesGlob(target.fullPath, pattern.fullPath); + } + + // Target has glob but pattern doesn't - pattern must match within target's glob range + return this.pathMatchesGlob(pattern.fullPath, target.fullPath); } /** @@ -184,14 +338,11 @@ export class PathEvent { static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe)); const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe)); - return !!parsedRequired.find(r => !!parsedTarget.find(t => { - const wildcard = r.fullPath == '*' || t.fullPath == '*'; - const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath; - const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath; - const scope = p1.startsWith(p2); // Note: Original had || p2.startsWith(p1) here, but has implies target has required. - const methods = r.all || t.all || r.methods.intersection(t.methods).length; - return (wildcard || scope) && methods; - })); + + // If target is a single item, check directly; if multiple, combine first + const effectiveTarget = parsedTarget.length === 1 ? parsedTarget[0] : PathEvent.combine(...parsedTarget); + + return !!parsedRequired.find(r => PathEvent.matches(r, effectiveTarget)); } /** @@ -199,7 +350,7 @@ export class PathEvent { * * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed * @param has Target must have all these paths - * @return {boolean} Whether there is any overlap + * @return {boolean} Whether all are present */ static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { return has.filter(h => PathEvent.has(target, h)).length == has.length; @@ -208,7 +359,7 @@ export class PathEvent { /** * Same as `has` but raises an error if there is no overlap * - * @param {string | string[]} target Array of Events as strings or pre-parsed + * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed * @param has Target must have at least one of these path */ static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { @@ -218,7 +369,7 @@ export class PathEvent { /** * Same as `hasAll` but raises an error if the target is missing any paths * - * @param {string | string[]} target Array of Events as strings or pre-parsed + * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed * @param has Target must have all these paths */ static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { @@ -253,7 +404,7 @@ export class PathEvent { * Squash 2 sets of paths & return true if the target has all paths * * @param has Target must have all these paths - * @return {boolean} Whether there is any overlap + * @return {boolean} Whether all are present */ hasAll(...has: (string | PathEvent)[]): boolean { return PathEvent.hasAll(this, ...has); @@ -281,7 +432,7 @@ export class PathEvent { * Filter a set of paths based on this event * * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered - * @return {boolean} Whether there is any overlap + * @return {PathEvent[]} Filtered results */ filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] { return PathEvent.filter(target, this); @@ -320,7 +471,7 @@ export class PathEventEmitter implements IPathEventEmitter{ emit(event: Event, ...args: any[]) { const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`); this.listeners.filter(l => PathEvent.has(l[0], parsed)) - .forEach(async l => l[1](parsed, ...args)); + .forEach(l => l[1](parsed, ...args)); }; off(listener: PathListener) { @@ -329,9 +480,21 @@ export class PathEventEmitter implements IPathEventEmitter{ on(event: Event | Event[], listener: PathListener): PathUnsubscribe { makeArray(event).forEach(e => { - if(typeof e == 'string' && e[0] == '*' && this.prefix) e = e.slice(1); + let fullEvent: string; + if(typeof e === 'string') { + // If event starts with ':', it's a scope specifier - prepend prefix + if(e[0] === ':' && this.prefix) { + fullEvent = `${this.prefix}${e}`; + } else if(this.prefix) { + fullEvent = `${this.prefix}/${e}`; + } else { + fullEvent = e; + } + } else { + fullEvent = e instanceof PathEvent ? PathEvent.toString(e.fullPath, e.methods) : (e as string); + } this.listeners.push([ - e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`), + new PathEvent(fullEvent), listener ]) }); @@ -349,6 +512,6 @@ export class PathEventEmitter implements IPathEventEmitter{ } relayEvents(emitter: IPathEventEmitter) { - emitter.on('*', (event, ...args) => this.emit(event, ...args)); + emitter.on('**', (event, ...args) => this.emit(event, ...args)); } } diff --git a/tests/path-events.spec.ts b/tests/path-events.spec.ts index d675541..fe9e158 100644 --- a/tests/path-events.spec.ts +++ b/tests/path-events.spec.ts @@ -3,6 +3,7 @@ import {PathError, PathEvent, PathEventEmitter, PE, PES} from '../src'; describe('Path Events', () => { beforeEach(() => { PathEvent.clearCache(); + PathEvent.clearPermissionCache(); }); describe('PE', () => { @@ -42,10 +43,16 @@ describe('Path Events', () => { it('parses wildcard', () => { const pe = new PathEvent('*'); expect(pe.all).toBe(true); - expect(pe.fullPath).toBe(''); + expect(pe.fullPath).toBe('**'); expect(pe.methods.has('*')).toBe(true); }); + it('parses empty string as none', () => { + const pe = new PathEvent(''); + expect(pe.none).toBe(true); + expect(pe.fullPath).toBe(''); + }); + it('parses none method', () => { const pe = new PathEvent('users/system:n'); expect(pe.none).toBe(true); @@ -143,6 +150,82 @@ describe('Path Events', () => { const filtered = pe.filter(arr); expect(filtered[0].fullPath).toBe('users/sys'); }); + + it('caches PathEvent instances', () => { + const pe1 = new PathEvent('users/sys:cr'); + const pe2 = new PathEvent('users/sys:cr'); + expect(pe1.fullPath).toBe(pe2.fullPath); + }); + + it('clearCache removes all cached instances', () => { + new PathEvent('users/sys:cr'); + PathEvent.clearCache(); + const pe = new PathEvent('users/sys:cr'); + expect(pe.fullPath).toBe('users/sys'); + }); + }); + + describe('Glob Patterns', () => { + it('** matches zero or more segments', () => { + const pattern = new PathEvent('storage/**:r'); + expect(PathEvent.has(pattern, 'storage:r')).toBe(true); + expect(PathEvent.has(pattern, 'storage/file:r')).toBe(true); + expect(PathEvent.has(pattern, 'storage/dir/file:r')).toBe(true); + }); + + it('** in middle matches multiple segments', () => { + const pattern = new PathEvent('data/**/archive:r'); + expect(PathEvent.has(pattern, 'data/archive:r')).toBe(true); + expect(PathEvent.has(pattern, 'data/old/archive:r')).toBe(true); + }); + + it('filters by glob and methods', () => { + const events = [ + new PathEvent('users/123/profile:cr'), + new PathEvent('users/456/profile:r'), + new PathEvent('users/789/settings:r') + ]; + const filtered = PathEvent.filter(events, 'users/*/profile:r'); + expect(filtered.length).toBe(2); + }); + + it('wildcard method matches all methods', () => { + const pattern = new PathEvent('users/**:*'); + expect(PathEvent.has(pattern, 'users/123:c')).toBe(true); + expect(PathEvent.has(pattern, 'users/456:r')).toBe(true); + }); + }); + + describe('Specificity and None Permissions', () => { + it('more specific path wins when sorted by specificity', () => { + const perms = [new PathEvent('users/**:*'), new PathEvent('users/admin:r')]; + const combined = PathEvent.combine(...perms); + expect(combined.fullPath).toBe('users/admin'); + }); + + it('none at parent stops combining', () => { + const a = new PathEvent('data/public:cr'); + const b = new PathEvent('data:n'); + const combined = PathEvent.combine(a, b); + expect(combined.fullPath).toBe('data/public'); + expect(combined.read).toBe(true); + }); + + it('instance methods work correctly', () => { + const pe = new PathEvent('users/sys:r'); + expect(pe.has('users/sys:r')).toBe(true); + expect(pe.hasAll('users/sys:r')).toBe(true); + expect(pe.filter(['users/sys:r', 'users/other:r']).length).toBe(1); + }); + + it('combines methods from hierarchy', () => { + const a = new PathEvent('users/admin:c'); + const b = new PathEvent('users/admin:r'); + const combined = PathEvent.combine(a, b); + expect(combined.fullPath).toBe('users/admin'); + expect(combined.create).toBe(true); + expect(combined.read).toBe(true); + }); }); describe('PathEventEmitter', () => { @@ -157,7 +240,7 @@ describe('Path Events', () => { it('scoped', done => { const emitter = new PathEventEmitter('users'); - emitter.on(':cud', (event) => { + emitter.on('*:cud', (event) => { expect(event.fullPath).toBe('users/system'); done(); }); @@ -198,5 +281,35 @@ describe('Path Events', () => { expect(event.fullPath).toBe('foo/bar')); emitter.emit('bar:r'); }); + + it('registers multiple listeners', () => { + const emitter = new PathEventEmitter(); + const fn1 = jest.fn(); + const fn2 = jest.fn(); + emitter.on('users/sys:r', fn1); + emitter.on('users/sys:r', fn2); + emitter.emit('users/sys:r'); + expect(fn1).toHaveBeenCalled(); + expect(fn2).toHaveBeenCalled(); + }); + + it('matches multiple listeners with overlapping globs', () => { + const emitter = new PathEventEmitter(); + const fn1 = jest.fn(); + const fn2 = jest.fn(); + emitter.on('users/**:r', fn1); + emitter.on('users/*/profile:r', fn2); + emitter.emit('users/123/profile:r'); + expect(fn1).toHaveBeenCalled(); + expect(fn2).toHaveBeenCalled(); + }); + + it('glob patterns in listener registration', () => { + const emitter = new PathEventEmitter(); + const fn = jest.fn(); + emitter.on('users/sys:r', fn); + emitter.emit('users/sys:r'); + expect(fn).toHaveBeenCalled(); + }); }); });