Compare commits

..

2 Commits

Author SHA1 Message Date
bcc76c7561 Glob support and path scoring
All checks were successful
Build / Publish Docs (push) Successful in 43s
Build / Build NPM Project (push) Successful in 1m49s
Build / Tag Version (push) Successful in 8s
2025-11-27 20:48:04 -05:00
67c2e8c434 added execute support ot pathed events 2025-11-27 18:32:15 -05:00
3 changed files with 331 additions and 52 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.27.10", "version": "0.27.11",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@@ -55,9 +55,10 @@ export function PES(str: TemplateStringsArray, ...args: any[]) {
export class PathError extends Error { } export class PathError extends Error { }
/** /**
* A event broken down into its core components for easy processing * A event broken down into its core components for easy processing
* Event Structure: `module/path/name:property:method` * Event Structure: `module/path/name:method`
* Example: `users/system:crud` or `storage/some/path/file.txt:r` * Example: `users/system:crud` or `storage/some/path/file.txt:r`
* Supports glob patterns: `users/*:r` or `storage/**:rw`
*/ */
export class PathEvent { export class PathEvent {
/** First directory in path */ /** First directory in path */
@@ -66,13 +67,19 @@ export class PathEvent {
fullPath!: string; fullPath!: string;
/** Path including the name, excluding the module */ /** Path including the name, excluding the module */
path!: string; path!: string;
/** Last sagment of path */ /** Last segment of path */
name!: string; name!: string;
/** List of methods */ /** List of methods */
methods!: ASet<Method>; methods!: ASet<Method>;
/** Whether this path contains glob patterns */
hasGlob!: boolean;
/** Internal cache for PathEvent instances to avoid redundant parsing */ /** Internal cache for PathEvent instances to avoid redundant parsing */
private static pathEventCache: Map<string, PathEvent> = new Map(); private static pathEventCache: Map<string, PathEvent> = new Map();
/** Cache for compiled permissions (path + required permissions → result) */
private static permissionCache: Map<string, PathEvent> = new Map();
/** Max size for permission cache before LRU eviction */
private static readonly MAX_PERMISSION_CACHE_SIZE = 1000;
/** All/Wildcard specified */ /** All/Wildcard specified */
get all(): boolean { return this.methods.has('*') } get all(): boolean { return this.methods.has('*') }
@@ -83,6 +90,9 @@ export class PathEvent {
/** Create method specified */ /** Create method specified */
get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) } get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); } set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
/** Execute method specified */
get execute(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('x')) }
set execute(v: boolean) { v ? this.methods.delete('n').delete('*').add('x') : this.methods.delete('x'); }
/** Read method specified */ /** Read method specified */
get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) } get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); } set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
@@ -105,17 +115,44 @@ export class PathEvent {
return; return;
} }
let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':'); let [p, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
if(!method) method = scope || '*'; if(!method) method = '*';
if(p == '*' || (!p && method == '*')) {
p = ''; // Handle special cases
method = '*'; if(p === '' || p === undefined) {
// Empty string matches nothing
this.module = '';
this.path = '';
this.fullPath = '';
this.name = '';
this.methods = new ASet<Method>(['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<Method>(['*']);
this.hasGlob = true;
PathEvent.pathEventCache.set(e, this);
return;
}
let temp = p.split('/').filter(p => !!p); let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || ''; this.module = temp.splice(0, 1)[0] || '';
this.path = temp.join('/'); this.path = temp.join('/');
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`; this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || ''; 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(<any>method.split('')); this.methods = new ASet(<any>method.split(''));
// Store in cache // Store in cache
@@ -127,6 +164,87 @@ export class PathEvent {
PathEvent.pathEventCache.clear(); 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 * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
* combined until a "none" is reached * combined until a "none" is reached
@@ -135,40 +253,79 @@ export class PathEvent {
* @return {PathEvent} Final combined permission * @return {PathEvent} Final combined permission
*/ */
static combine(...paths: (string | PathEvent)[]): PathEvent { static combine(...paths: (string | PathEvent)[]): PathEvent {
let hitNone = false; const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p));
const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p))
.toSorted((p1, p2) => { // Sort by specificity: lower score = more specific = higher priority
const l1 = p1.fullPath.length, l2 = p2.fullPath.length; const sorted = parsed.toSorted((p1, p2) => {
return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0); const score1 = PathEvent.scoreSpecificity(p1.fullPath);
}).reduce((acc, p) => { const score2 = PathEvent.scoreSpecificity(p2.fullPath);
if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc; return score1 - score2;
if(p.none) hitNone = true; });
if(!acc) return p;
if(hitNone) return acc; let result: PathEvent | null = null;
acc.methods = new ASet([...acc.methods, ...p.methods]);
return acc; for (const p of sorted) {
}, <any>null); if (!result) {
return combined; 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 * Filter a set of paths based on the target
* *
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
* @param filter {...PathEvent} Must container one of * @param filter {...PathEvent} Must contain one of
* @return {boolean} Whether there is any overlap * @return {PathEvent[]} Filtered results
*/ */
static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] { 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 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)); 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 == '*'; return parsedTarget.filter(t => {
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath; const combined = PathEvent.combine(t);
const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath; return !!parsedFilter.find(r => PathEvent.matches(r, combined));
const scope = p1.startsWith(p2) || p2.startsWith(p1); });
const methods = r.all || t.all || r.methods.intersection(t.methods).length; }
return (wildcard || scope) && methods;
})); /**
* 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);
} }
/** /**
@@ -181,14 +338,11 @@ export class PathEvent {
static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { 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 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)); 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 == '*'; // If target is a single item, check directly; if multiple, combine first
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath; const effectiveTarget = parsedTarget.length === 1 ? parsedTarget[0] : PathEvent.combine(...parsedTarget);
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. return !!parsedRequired.find(r => PathEvent.matches(r, effectiveTarget));
const methods = r.all || t.all || r.methods.intersection(t.methods).length;
return (wildcard || scope) && methods;
}));
} }
/** /**
@@ -196,7 +350,7 @@ export class PathEvent {
* *
* @param {string | PathEvent | (string | PathEvent)[]} 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 * @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 { static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
return has.filter(h => PathEvent.has(target, h)).length == has.length; return has.filter(h => PathEvent.has(target, h)).length == has.length;
@@ -205,7 +359,7 @@ export class PathEvent {
/** /**
* Same as `has` but raises an error if there is no overlap * 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 * @param has Target must have at least one of these path
*/ */
static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -215,7 +369,7 @@ export class PathEvent {
/** /**
* Same as `hasAll` but raises an error if the target is missing any paths * 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 * @param has Target must have all these paths
*/ */
static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -250,7 +404,7 @@ export class PathEvent {
* Squash 2 sets of paths & return true if the target has all paths * Squash 2 sets of paths & return true if the target has all paths
* *
* @param has Target must have all these 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 { hasAll(...has: (string | PathEvent)[]): boolean {
return PathEvent.hasAll(this, ...has); return PathEvent.hasAll(this, ...has);
@@ -278,7 +432,7 @@ export class PathEvent {
* Filter a set of paths based on this event * Filter a set of paths based on this event
* *
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered * @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[] { filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] {
return PathEvent.filter(target, this); return PathEvent.filter(target, this);
@@ -317,7 +471,7 @@ export class PathEventEmitter implements IPathEventEmitter{
emit(event: Event, ...args: any[]) { emit(event: Event, ...args: any[]) {
const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`); const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`);
this.listeners.filter(l => PathEvent.has(l[0], parsed)) 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) { off(listener: PathListener) {
@@ -326,9 +480,21 @@ export class PathEventEmitter implements IPathEventEmitter{
on(event: Event | Event[], listener: PathListener): PathUnsubscribe { on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
makeArray(event).forEach(e => { 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([ this.listeners.push([
e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`), new PathEvent(fullEvent),
listener listener
]) ])
}); });
@@ -346,6 +512,6 @@ export class PathEventEmitter implements IPathEventEmitter{
} }
relayEvents(emitter: IPathEventEmitter) { relayEvents(emitter: IPathEventEmitter) {
emitter.on('*', (event, ...args) => this.emit(event, ...args)); emitter.on('**', (event, ...args) => this.emit(event, ...args));
} }
} }

View File

@@ -3,6 +3,7 @@ import {PathError, PathEvent, PathEventEmitter, PE, PES} from '../src';
describe('Path Events', () => { describe('Path Events', () => {
beforeEach(() => { beforeEach(() => {
PathEvent.clearCache(); PathEvent.clearCache();
PathEvent.clearPermissionCache();
}); });
describe('PE', () => { describe('PE', () => {
@@ -42,10 +43,16 @@ describe('Path Events', () => {
it('parses wildcard', () => { it('parses wildcard', () => {
const pe = new PathEvent('*'); const pe = new PathEvent('*');
expect(pe.all).toBe(true); expect(pe.all).toBe(true);
expect(pe.fullPath).toBe(''); expect(pe.fullPath).toBe('**');
expect(pe.methods.has('*')).toBe(true); 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', () => { it('parses none method', () => {
const pe = new PathEvent('users/system:n'); const pe = new PathEvent('users/system:n');
expect(pe.none).toBe(true); expect(pe.none).toBe(true);
@@ -143,6 +150,82 @@ describe('Path Events', () => {
const filtered = pe.filter(arr); const filtered = pe.filter(arr);
expect(filtered[0].fullPath).toBe('users/sys'); 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', () => { describe('PathEventEmitter', () => {
@@ -157,7 +240,7 @@ describe('Path Events', () => {
it('scoped', done => { it('scoped', done => {
const emitter = new PathEventEmitter('users'); const emitter = new PathEventEmitter('users');
emitter.on(':cud', (event) => { emitter.on('*:cud', (event) => {
expect(event.fullPath).toBe('users/system'); expect(event.fullPath).toBe('users/system');
done(); done();
}); });
@@ -198,5 +281,35 @@ describe('Path Events', () => {
expect(event.fullPath).toBe('foo/bar')); expect(event.fullPath).toBe('foo/bar'));
emitter.emit('bar:r'); 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();
});
}); });
}); });