import { describe, expect, it } from 'vitest' import { effectiveScope, formatGrantKey, parseGrantKey } from '@/lib/permissions' import { setScope, scopeAt, isCustomRow, resetRow } from '@/lib/roleForm' import { canCover } from '@/lib/grantLocks' import { baseKey } from '@/lib/permissionNames' describe('parseGrantKey and formatGrantKey', () => { it('parses a bare key without a type', () => { expect(parseGrantKey('content.read')).toEqual({ base: 'content.read' }) }) it('parses a typed key', () => { expect(parseGrantKey('content.read:events')).toEqual({ base: 'content.read', typeKey: 'events', }) }) it('splits on the first colon only so a type key may contain a colon', () => { expect(parseGrantKey('content.update:ns:case-studies')).toEqual({ base: 'content.update', typeKey: 'ns:case-studies', }) }) it('formats and parses back to the same parts', () => { const key = formatGrantKey('content.update', 'ns:case-studies') expect(key).toBe('content.update:ns:case-studies') expect(parseGrantKey(key)).toEqual({ base: 'content.update', typeKey: 'ns:case-studies' }) expect(formatGrantKey('content.update')).toBe('content.update') }) it('keeps a colon type key working through the form, locks and names', () => { const grants = setScope({}, 'content.update', 'own', 'ns:a') expect(grants).toEqual({ 'content.update:ns:a': 'own' }) expect(scopeAt(grants, 'content.update', 'ns:a')).toBe('own') expect( effectiveScope([{ key: 'content.update:ns:a', scope: 'own' }], 'content.update', { typeKey: 'ns:a', }), ).toBe('own') expect(isCustomRow(grants, 'ns:a')).toBe(true) expect(resetRow(grants, 'ns:a')).toEqual({}) expect(baseKey('content.update:ns:a')).toBe('content.update') const held: string[] = [] canCover({ grants: [{ key: 'content.update:ns:a', scope: 'own' }] }, (key, options) => { held.push(`${key}|${options?.typeKey}`) return 'all' }) expect(held).toEqual(['content.update|ns:a']) }) })