import { describe, it, expect } from 'vitest'; import { parseExplicit, parseCompound, parseDocument, isExplicitSyntax, isCompoundSyntax, isDocumentSyntax, } from './explicit-parser'; import type { ParseExplicitOptions, SchemaLookup } from './types'; import { defineCommand, defineRole } from '../schema/command-schema'; import type { CompoundSemanticNode } from '../core/types'; describe('isExplicitSyntax', () => { it('detects bracket syntax', () => { expect(isExplicitSyntax('[toggle patient:.active]')).toBe(true); expect(isExplicitSyntax(' [toggle patient:.active] ')).toBe(true); }); it('rejects non-bracket syntax', () => { expect(isExplicitSyntax('toggle .active')).toBe(false); expect(isExplicitSyntax('[incomplete')).toBe(false); expect(isExplicitSyntax('incomplete]')).toBe(false); expect(isExplicitSyntax('')).toBe(false); }); }); describe('parseExplicit — without schema', () => { it('parses basic command with roles', () => { const node = parseExplicit('[toggle patient:.active destination:#button]'); expect(node.kind).toBe('command'); expect(node.action).toBe('toggle'); expect(node.roles.get('patient')).toEqual({ type: 'selector', value: '.active', selectorKind: 'class', }); expect(node.roles.get('destination')).toEqual({ type: 'selector', value: '#button', selectorKind: 'id', }); }); it('parses selector values', () => { const node = parseExplicit('[add patient:.highlight destination:#output]'); const patient = node.roles.get('patient'); expect(patient?.type).toBe('selector'); expect(patient && 'value' in patient && patient.value).toBe('.highlight'); }); it('parses string literal values', () => { const node = parseExplicit('[put patient:"hello world" destination:#output]'); const patient = node.roles.get('patient'); expect(patient).toEqual({ type: 'literal', value: 'hello world', dataType: 'string' }); }); it('parses boolean values', () => { const node = parseExplicit('[set destination:myVar goal:true]'); expect(node.roles.get('goal')).toEqual({ type: 'literal', value: true, dataType: 'boolean' }); }); it('parses numeric values', () => { const node = parseExplicit('[increment destination:count quantity:5]'); expect(node.roles.get('quantity')).toEqual({ type: 'literal', value: 5, dataType: 'number' }); }); it('parses duration values', () => { const node = parseExplicit('[wait duration:500ms]'); expect(node.roles.get('duration')).toEqual({ type: 'literal', value: '500ms', dataType: 'duration', }); const node2 = parseExplicit('[wait duration:2s]'); expect(node2.roles.get('duration')).toEqual({ type: 'literal', value: '2s', dataType: 'duration', }); }); it('parses reference values', () => { const node = parseExplicit('[add patient:.active destination:me]'); expect(node.roles.get('destination')).toEqual({ type: 'reference', value: 'me' }); }); it('parses plain string values (unquoted, non-special)', () => { const node = parseExplicit('[fetch source:/api/users responseType:json]'); // Unquoted values get no dataType — only explicitly quoted values get dataType: 'string' expect(node.roles.get('source')).toEqual({ type: 'literal', value: '/api/users', }); expect(node.roles.get('responseType')).toEqual({ type: 'literal', value: 'json', }); }); it('parses event handlers with body', () => { const node = parseExplicit('[on event:click body:[toggle patient:.active]]'); expect(node.kind).toBe('event-handler'); expect(node.action).toBe('on'); const eventNode = node as { body: unknown[] }; expect(eventNode.body).toHaveLength(1); expect(eventNode.body[0]).toMatchObject({ kind: 'command', action: 'toggle' }); }); it('accepts any role names without schema', () => { // Custom domain roles should parse fine const node = parseExplicit('[deploy destination:production source:main manner:rolling]'); expect(node.action).toBe('deploy'); expect(node.roles.get('destination')).toEqual({ type: 'literal', value: 'production', }); expect(node.roles.get('source')).toEqual({ type: 'literal', value: 'main', }); expect(node.roles.get('manner')).toEqual({ type: 'literal', value: 'rolling', }); }); it('sets sourceLanguage to explicit', () => { const node = parseExplicit('[toggle patient:.active]'); expect(node.metadata?.sourceLanguage).toBe('explicit'); }); }); describe('parseExplicit — error handling', () => { it('throws on missing brackets', () => { expect(() => parseExplicit('toggle patient:.active')).toThrow('must be wrapped in brackets'); }); it('throws on empty brackets', () => { expect(() => parseExplicit('[]')).toThrow('Empty explicit statement'); expect(() => parseExplicit('[ ]')).toThrow('Empty explicit statement'); }); it('throws on missing colon in role', () => { expect(() => parseExplicit('[toggle active]')).toThrow('Expected role:value'); }); it('throws on missing event role for event handler', () => { expect(() => parseExplicit('[on body:[toggle patient:.active]]')).toThrow( 'requires event role' ); }); }); describe('parseExplicit — with SchemaLookup', () => { const toggleSchema = defineCommand({ action: 'toggle', roles: [ defineRole({ role: 'patient', required: true, expectedTypes: ['selector'] }), defineRole({ role: 'destination', required: false, expectedTypes: ['selector'] }), ], }); const schemaLookup: SchemaLookup = { getSchema(action: string) { if (action === 'toggle') return toggleSchema; return undefined; }, }; const options: ParseExplicitOptions = { schemaLookup }; it('validates roles against schema', () => { // Valid roles pass const node = parseExplicit('[toggle patient:.active]', options); expect(node.action).toBe('toggle'); }); it('rejects unknown roles for known commands', () => { expect(() => parseExplicit('[toggle patient:.active bogus:value]', options)).toThrow( 'Unknown role "bogus"' ); }); it('enforces required roles', () => { expect(() => parseExplicit('[toggle destination:#btn]', options)).toThrow( 'Missing required role "patient"' ); }); it('allows any roles for unknown commands', () => { // 'deploy' has no schema registered const node = parseExplicit('[deploy target:prod]', options); expect(node.action).toBe('deploy'); expect(node.roles.get('target')).toBeDefined(); }); }); describe('parseExplicit — boolean flags', () => { it('parses +flag as enabled FlagValue', () => { const node = parseExplicit('[column name:id +primary-key]'); expect(node.roles.get('primary-key')).toEqual({ type: 'flag', name: 'primary-key', enabled: true, }); }); it('parses ~flag as disabled FlagValue', () => { const node = parseExplicit('[field name:email ~nullable]'); expect(node.roles.get('nullable')).toEqual({ type: 'flag', name: 'nullable', enabled: false, }); }); it('parses flags alongside role:value pairs', () => { const node = parseExplicit('[column name:id type:uuid +primary-key +not-null]'); expect(node.action).toBe('column'); expect(node.roles.get('name')).toEqual({ type: 'literal', value: 'id' }); expect(node.roles.get('type')).toEqual({ type: 'literal', value: 'uuid' }); expect(node.roles.get('primary-key')).toEqual({ type: 'flag', name: 'primary-key', enabled: true, }); expect(node.roles.get('not-null')).toEqual({ type: 'flag', name: 'not-null', enabled: true, }); }); it('parses mixed + and ~ flags', () => { const node = parseExplicit('[field name:email +required ~nullable]'); expect(node.roles.get('required')).toEqual({ type: 'flag', name: 'required', enabled: true, }); expect(node.roles.get('nullable')).toEqual({ type: 'flag', name: 'nullable', enabled: false, }); }); it('throws on empty flag name', () => { expect(() => parseExplicit('[column name:id +]')).toThrow('Empty flag name'); expect(() => parseExplicit('[column name:id ~]')).toThrow('Empty flag name'); }); it('validates flag names against schema', () => { const schema = defineCommand({ action: 'column', roles: [ defineRole({ role: 'name', required: true, expectedTypes: ['literal'] }), defineRole({ role: 'primary-key', required: false, expectedTypes: ['flag'] }), ], }); const schemaLookup: SchemaLookup = { getSchema(action: string) { if (action === 'column') return schema; return undefined; }, }; // Valid flag const node = parseExplicit('[column name:id +primary-key]', { schemaLookup }); expect(node.roles.get('primary-key')).toBeDefined(); // Invalid flag expect(() => parseExplicit('[column name:id +unknown-flag]', { schemaLookup })).toThrow( 'Unknown flag "unknown-flag"' ); }); it('allows any flags for unknown commands (no schema)', () => { const node = parseExplicit('[widget +draggable +resizable]'); expect(node.roles.get('draggable')).toEqual({ type: 'flag', name: 'draggable', enabled: true, }); expect(node.roles.get('resizable')).toEqual({ type: 'flag', name: 'resizable', enabled: true, }); }); }); describe('parseExplicit — custom reference set', () => { it('uses custom references', () => { const options: ParseExplicitOptions = { referenceSet: new Set(['self', 'parent']), }; const node = parseExplicit('[add patient:.active destination:self]', options); expect(node.roles.get('destination')).toEqual({ type: 'reference', value: 'self' }); }); it('does not recognize default references with custom set', () => { const options: ParseExplicitOptions = { referenceSet: new Set(['self']), }; // 'me' is not in the custom set, so it becomes a literal (no dataType for unquoted values) const node = parseExplicit('[add patient:.active destination:me]', options); expect(node.roles.get('destination')).toEqual({ type: 'literal', value: 'me', }); }); }); // =========================================================================== // collectDiagnostics mode (v1.2.1) // =========================================================================== describe('parseExplicit — collectDiagnostics', () => { const toggleSchema = defineCommand({ action: 'toggle', roles: [ defineRole({ role: 'patient', required: true, expectedTypes: ['selector'] }), defineRole({ role: 'destination', required: false, expectedTypes: ['selector'] }), ], }); const schemaLookup: SchemaLookup = { getSchema(action: string) { if (action === 'toggle') return toggleSchema; return undefined; }, }; const collectOpts: ParseExplicitOptions = { schemaLookup, collectDiagnostics: true }; it('returns node with diagnostics for unknown role', () => { const node = parseExplicit('[toggle patient:.active badRole:foo]', collectOpts); expect(node.action).toBe('toggle'); expect(node.diagnostics).toHaveLength(1); expect(node.diagnostics![0].severity).toBe('error'); expect(node.diagnostics![0].code).toBe('UNKNOWN_ROLE'); expect(node.diagnostics![0].message).toContain('badRole'); expect(node.diagnostics![0].source).toBe('schema'); expect(node.diagnostics![0].suggestions).toContain('patient'); }); it('returns node with diagnostics for missing required role', () => { const node = parseExplicit('[toggle destination:.active]', collectOpts); expect(node.action).toBe('toggle'); expect(node.diagnostics).toHaveLength(1); expect(node.diagnostics![0].code).toBe('MISSING_REQUIRED_ROLE'); expect(node.diagnostics![0].message).toContain('patient'); }); it('returns node with diagnostics for unknown flag', () => { const node = parseExplicit('[toggle patient:.active +badFlag]', collectOpts); expect(node.diagnostics).toHaveLength(1); expect(node.diagnostics![0].code).toBe('UNKNOWN_FLAG'); }); it('returns node with diagnostics for invalid role format', () => { const node = parseExplicit('[toggle patient:.active noColonHere]', collectOpts); expect(node.diagnostics).toHaveLength(1); expect(node.diagnostics![0].code).toBe('INVALID_ROLE_FORMAT'); }); it('collects multiple diagnostics', () => { const node = parseExplicit('[toggle badRole:foo +badFlag]', collectOpts); // unknown role + unknown flag + missing required role (patient) expect(node.diagnostics!.length).toBeGreaterThanOrEqual(2); const codes = node.diagnostics!.map(d => d.code); expect(codes).toContain('UNKNOWN_ROLE'); expect(codes).toContain('UNKNOWN_FLAG'); }); it('returns clean node when no errors (no diagnostics field)', () => { const node = parseExplicit('[toggle patient:.active]', collectOpts); expect(node.action).toBe('toggle'); expect(node.diagnostics).toBeUndefined(); }); it('still throws on fatal errors (missing brackets)', () => { expect(() => parseExplicit('toggle patient:.active', collectOpts)).toThrow( 'Explicit syntax must be wrapped in brackets' ); }); it('still throws on empty input', () => { expect(() => parseExplicit('[]', collectOpts)).toThrow('Empty explicit statement'); }); it('returns diagnostics on event handler missing event role', () => { const node = parseExplicit('[on body:[toggle patient:.active]]', collectOpts); expect(node.diagnostics).toHaveLength(1); expect(node.diagnostics![0].code).toBe('MISSING_EVENT_ROLE'); }); }); // ============================================================================= // parseCompound // ============================================================================= describe('parseCompound', () => { it('passes through single bracket command to parseExplicit', () => { const node = parseCompound('[toggle patient:.active]'); expect(node.kind).toBe('command'); expect(node.action).toBe('toggle'); expect(node.roles.get('patient')?.value).toBe('.active'); }); it('parses two commands chained with then', () => { const node = parseCompound('[add patient:.loading] then [fetch source:"/api/data"]'); expect(node.kind).toBe('compound'); const compound = node as CompoundSemanticNode; expect(compound.chainType).toBe('then'); expect(compound.statements).toHaveLength(2); expect(compound.statements[0].action).toBe('add'); expect(compound.statements[1].action).toBe('fetch'); }); it('parses commands chained with and', () => { const node = parseCompound('[add patient:.a] and [add patient:.b]'); expect(node.kind).toBe('compound'); expect((node as CompoundSemanticNode).chainType).toBe('and'); }); it('parses commands chained with async', () => { const node = parseCompound('[fetch source:/api/a] async [fetch source:/api/b]'); expect(node.kind).toBe('compound'); expect((node as CompoundSemanticNode).chainType).toBe('async'); }); it('parses commands chained with sequential', () => { const node = parseCompound('[add patient:.a] sequential [add patient:.b]'); expect(node.kind).toBe('compound'); expect((node as CompoundSemanticNode).chainType).toBe('sequential'); }); it('parses commands chained with |> pipe', () => { const node = parseCompound('[fetch source:/api/users] |> [put destination:#list]'); expect(node.kind).toBe('compound'); const compound = node as CompoundSemanticNode; expect(compound.chainType).toBe('pipe'); expect(compound.statements).toHaveLength(2); expect(compound.statements[0].action).toBe('fetch'); expect(compound.statements[1].action).toBe('put'); }); it('handles three or more chained commands', () => { const node = parseCompound( '[add patient:.loading] then [fetch source:/api/data] then [remove patient:.loading]' ); expect(node.kind).toBe('compound'); const compound = node as CompoundSemanticNode; expect(compound.chainType).toBe('then'); expect(compound.statements).toHaveLength(3); }); it('uses first chain operator for mixed operators', () => { const node = parseCompound('[add patient:.a] then [add patient:.b] and [add patient:.c]'); expect(node.kind).toBe('compound'); expect((node as CompoundSemanticNode).chainType).toBe('then'); }); }); // ============================================================================= // Annotation parsing (via parseCompound) // ============================================================================= describe('parseCompound — annotations', () => { it('parses single annotation with value', () => { const node = parseCompound('@timeout(5s) [fetch source:"/api/users"]'); expect(node.annotations).toHaveLength(1); expect(node.annotations![0]).toEqual({ name: 'timeout', value: '5s' }); expect(node.action).toBe('fetch'); }); it('parses annotation without value (flag-style)', () => { const node = parseCompound('@deprecated [toggle patient:.active]'); expect(node.annotations).toHaveLength(1); expect(node.annotations![0]).toEqual({ name: 'deprecated' }); }); it('parses multiple annotations preserving order', () => { const node = parseCompound('@retry(3) @timeout(10s) @cache(60s) [fetch source:"/api/data"]'); expect(node.annotations).toHaveLength(3); expect(node.annotations![0].name).toBe('retry'); expect(node.annotations![1].name).toBe('timeout'); expect(node.annotations![2].name).toBe('cache'); }); it('handles annotation with path-like value', () => { const node = parseCompound('@source(/api/v2/users) [fetch source:"/api"]'); expect(node.annotations![0]).toEqual({ name: 'source', value: '/api/v2/users' }); }); it('handles annotation with quoted string value', () => { const node = parseCompound('@doc("Toggle active state on click") [toggle patient:.active]'); expect(node.annotations![0]).toEqual({ name: 'doc', value: 'Toggle active state on click', }); }); it('returns no annotations when none present', () => { const node = parseCompound('[toggle patient:.active]'); expect(node.annotations).toBeUndefined(); }); it('attaches annotations to compound nodes', () => { const node = parseCompound( '@permission(admin) [add patient:.loading] then [fetch source:"/api/users"]' ); expect(node.kind).toBe('compound'); expect(node.annotations).toHaveLength(1); expect(node.annotations![0]).toEqual({ name: 'permission', value: 'admin' }); }); }); // ============================================================================= // parseDocument // ============================================================================= describe('parseDocument', () => { it('parses a simple document with version header', () => { const envelope = parseDocument('#!lse 1.2\n[toggle patient:.active]\n[add patient:.highlight]'); expect(envelope.lseVersion).toBe('1.2'); expect(envelope.nodes).toHaveLength(2); expect(envelope.nodes[0].action).toBe('toggle'); expect(envelope.nodes[1].action).toBe('add'); }); it('defaults to version 1.0 when no header present', () => { const envelope = parseDocument('[toggle patient:.active]'); expect(envelope.lseVersion).toBe('1.0'); expect(envelope.nodes).toHaveLength(1); }); it('skips // comments', () => { const envelope = parseDocument( '#!lse 1.2\n// This is a comment\n[toggle patient:.active]\n// Another comment' ); expect(envelope.nodes).toHaveLength(1); }); it('skips # comments', () => { const envelope = parseDocument('#!lse 1.2\n# This is a comment\n[toggle patient:.active]'); expect(envelope.nodes).toHaveLength(1); }); it('skips blank lines', () => { const envelope = parseDocument( '#!lse 1.2\n\n[toggle patient:.active]\n\n\n[add patient:.highlight]\n' ); expect(envelope.nodes).toHaveLength(2); }); it('handles three-part version numbers', () => { const envelope = parseDocument('#!lse 1.2.0\n[toggle patient:.active]'); expect(envelope.lseVersion).toBe('1.2.0'); }); it('handles compound statements in document lines', () => { const envelope = parseDocument( '#!lse 1.2\n[add patient:.loading] then [fetch source:/api/data]' ); expect(envelope.nodes).toHaveLength(1); expect(envelope.nodes[0].kind).toBe('compound'); }); it('handles annotated statements in document lines', () => { const envelope = parseDocument('#!lse 1.2\n@timeout(5s) [fetch source:"/api/users"]'); expect(envelope.nodes).toHaveLength(1); expect(envelope.nodes[0].annotations).toHaveLength(1); }); }); // ============================================================================= // Detection helpers // ============================================================================= describe('isCompoundSyntax', () => { it('detects compound statements', () => { expect(isCompoundSyntax('[a patient:x] then [b patient:y]')).toBe(true); expect(isCompoundSyntax('[a patient:x] |> [b patient:y]')).toBe(true); }); it('rejects single commands', () => { expect(isCompoundSyntax('[toggle patient:.active]')).toBe(false); }); }); describe('isDocumentSyntax', () => { it('detects multi-line input', () => { expect(isDocumentSyntax('[a patient:x]\n[b patient:y]')).toBe(true); }); it('detects version header', () => { expect(isDocumentSyntax('#!lse 1.2')).toBe(true); }); it('detects comment lines', () => { expect(isDocumentSyntax('// a comment')).toBe(true); expect(isDocumentSyntax('# a comment')).toBe(true); }); it('rejects single bracket commands', () => { expect(isDocumentSyntax('[toggle patient:.active]')).toBe(false); }); });