@diullei/codeguardian
Version:
Open-source developer tool to validate and enforce architectural rules, especially for AI-generated code
103 lines • 3.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssertMatchRule = void 0;
const core_1 = require("../core");
class AssertMatchRule extends core_1.AssertionRule {
pattern;
shouldMatch;
suggestion;
documentation;
constructor(id, pattern, shouldMatch = true, suggestion, documentation) {
super(id);
this.pattern = pattern;
this.shouldMatch = shouldMatch;
this.suggestion = suggestion;
this.documentation = documentation;
}
async assert(item, _context) {
const text = this.extractText(item);
const matches = this.pattern.test(text);
return this.shouldMatch ? matches : !matches;
}
async assertWithDetails(item, _context) {
if (item && typeof item === 'object' && 'status' in item && item.status === 'deleted' && !item.content) {
if (this.shouldMatch) {
return {
passed: false,
message: `Cannot match pattern against deleted file`,
context: {
suggestion: 'Deleted files have no content to match against. Use assert_property to check file status instead.',
documentation: this.documentation,
},
};
}
else {
return { passed: true };
}
}
const text = this.extractText(item);
const matches = this.pattern.test(text);
const passed = this.shouldMatch ? matches : !matches;
if (!passed) {
const itemType = this.getItemType(item);
const patternStr = this.pattern.source;
let codeSnippet;
if (text && text.length < 200) {
codeSnippet = text;
}
else if (text) {
const match = text.match(this.pattern);
if (match && match.index !== undefined) {
const start = Math.max(0, match.index - 50);
const end = Math.min(text.length, match.index + match[0].length + 50);
codeSnippet = '...' + text.substring(start, end) + '...';
}
else {
codeSnippet = text.substring(0, 150) + '...';
}
}
return {
passed: false,
message: this.shouldMatch
? `Expected ${itemType} to match pattern '${patternStr}' but it didn't`
: `Expected ${itemType} NOT to match pattern '${patternStr}' but it did`,
context: {
code: codeSnippet,
suggestion: this.suggestion,
documentation: this.documentation,
},
};
}
return { passed: true };
}
extractText(item) {
if (typeof item === 'string')
return item;
if (item && typeof item === 'object') {
if ('content' in item)
return String(item.content);
if ('text' in item)
return String(item.text);
if ('path' in item)
return String(item.path);
}
return String(item);
}
getItemType(item) {
if (typeof item === 'string')
return 'text';
if (item && typeof item === 'object') {
if ('content' in item && 'path' in item)
return 'file content';
if ('lineNumber' in item)
return 'line';
if ('type' in item && item.type)
return 'AST node';
if ('path' in item)
return 'file path';
}
return 'item';
}
}
exports.AssertMatchRule = AssertMatchRule;
//# sourceMappingURL=AssertMatchRule.js.map