You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
262 lines
9.5 KiB
262 lines
9.5 KiB
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
|
|
const projectRoot = process.cwd();
|
|
const srcDir = path.join(projectRoot, 'src');
|
|
const specPath = path.join(projectRoot, 'BACKEND_SPEC.md');
|
|
|
|
console.log('====================================================');
|
|
console.log(' HABIB SHOP - BACKEND SPECIFICATION AUDITOR');
|
|
console.log('====================================================\n');
|
|
|
|
// 1. Check existence of BACKEND_SPEC.md
|
|
if (!fs.existsSync(specPath)) {
|
|
console.error(`FATAL: ${specPath} does not exist!`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const specContent = fs.readFileSync(specPath, 'utf8');
|
|
const specLines = specContent.split('\n');
|
|
console.log(`Loaded BACKEND_SPEC.md: ${specLines.length} lines, ${Buffer.byteLength(specContent, 'utf8')} bytes.\n`);
|
|
|
|
let totalErrors = 0;
|
|
|
|
// 2. Programmatically scan all files in src/ and check 100% citation
|
|
function walkDir(dir) {
|
|
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
const files = [];
|
|
for (const entry of entries) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
files.push(...walkDir(full));
|
|
} else if (entry.isFile()) {
|
|
files.push(full);
|
|
}
|
|
}
|
|
return files;
|
|
}
|
|
|
|
const allSrcFiles = walkDir(srcDir).map((f) => {
|
|
const rel = path.relative(projectRoot, f).replace(/\\/g, '/');
|
|
return rel;
|
|
});
|
|
|
|
console.log(`Found ${allSrcFiles.length} total source/asset files in src/.\nVerifying 100% citation in BACKEND_SPEC.md...`);
|
|
|
|
let missingFileCount = 0;
|
|
for (const relFile of allSrcFiles) {
|
|
if (!specContent.includes(relFile)) {
|
|
console.error(` [MISSING CITATION]: "${relFile}" is not cited in BACKEND_SPEC.md`);
|
|
missingFileCount++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
|
|
if (missingFileCount === 0) {
|
|
console.log(` PASS: All ${allSrcFiles.length} files in src/ are 100% cited and mapped.\n`);
|
|
} else {
|
|
console.error(` FAIL: ${missingFileCount} files are missing citations!\n`);
|
|
}
|
|
|
|
// 3. Check for unresolved placeholders: TODO, TBD, and ellipsis truncations in code blocks
|
|
console.log('Verifying absence of unresolved placeholders (TODO, TBD, ... truncations)...');
|
|
const todoRegex = /\bTODO\b/g;
|
|
const tbdRegex = /\bTBD\b/g;
|
|
|
|
let placeholderMatches = 0;
|
|
let match;
|
|
while ((match = todoRegex.exec(specContent)) !== null) {
|
|
const lineNo = specContent.slice(0, match.index).split('\n').length;
|
|
console.error(` [PLACEHOLDER FOUND]: "TODO" at line ${lineNo}`);
|
|
placeholderMatches++;
|
|
totalErrors++;
|
|
}
|
|
|
|
while ((match = tbdRegex.exec(specContent)) !== null) {
|
|
const lineNo = specContent.slice(0, match.index).split('\n').length;
|
|
console.error(` [PLACEHOLDER FOUND]: "TBD" at line ${lineNo}`);
|
|
placeholderMatches++;
|
|
totalErrors++;
|
|
}
|
|
|
|
// Check for lazy ellipsis truncation in JSON / code blocks
|
|
let inCodeBlock = false;
|
|
let codeBlockEllipsis = 0;
|
|
for (let i = 0; i < specLines.length; i++) {
|
|
const line = specLines[i];
|
|
if (line.trim().startsWith('```')) {
|
|
inCodeBlock = !inCodeBlock;
|
|
continue;
|
|
}
|
|
if (inCodeBlock) {
|
|
const trimmed = line.trim();
|
|
if (trimmed === '...' || trimmed === '...,' || trimmed === '{...}' || trimmed === '[...]') {
|
|
console.error(` [LAZY ELLIPSIS TRUNCATION]: "${trimmed}" at line ${i + 1}`);
|
|
codeBlockEllipsis++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (placeholderMatches === 0 && codeBlockEllipsis === 0) {
|
|
console.log(' PASS: Zero placeholders (TODO, TBD) and zero code-block ellipsis truncations found.\n');
|
|
} else {
|
|
console.error(` FAIL: Found ${placeholderMatches} placeholders and ${codeBlockEllipsis} code-block ellipsis truncations!\n`);
|
|
}
|
|
|
|
// 4. Verify canonical entities (all 20 canonical entities)
|
|
console.log('Verifying presence of 20 canonical entity models and database tables...');
|
|
const requiredEntities = [
|
|
'users',
|
|
'user_addresses',
|
|
'store_booths',
|
|
'categories',
|
|
'products',
|
|
'product_gallery_images',
|
|
'wishlist_bookmarks',
|
|
'shopping_carts',
|
|
'cart_items',
|
|
'orders',
|
|
'order_shipments',
|
|
'order_shipment_items',
|
|
'support_tickets',
|
|
'support_ticket_attachments',
|
|
'chat_conversations',
|
|
'chat_messages',
|
|
'provider_applications',
|
|
'habib_coin_transactions',
|
|
'marketing_banners',
|
|
'donation_campaigns',
|
|
];
|
|
|
|
let missingEntities = 0;
|
|
for (const entity of requiredEntities) {
|
|
const ddlRegex = new RegExp(`CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${entity}\\b`, 'i');
|
|
if (!ddlRegex.test(specContent)) {
|
|
console.error(` [MISSING DDL TABLE]: "CREATE TABLE ${entity}" not found in specification`);
|
|
missingEntities++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
|
|
if (missingEntities === 0) {
|
|
console.log(` PASS: All ${requiredEntities.length} canonical entities have valid CREATE TABLE DDL statements.\n`);
|
|
} else {
|
|
console.error(` FAIL: ${missingEntities} canonical entities missing DDL statements!\n`);
|
|
}
|
|
|
|
// 5. Verify REST endpoints count and schema definitions
|
|
console.log('Verifying REST API endpoints coverage...');
|
|
const endpointRegex = /### Endpoint \d+: `(GET|POST|PUT|PATCH|DELETE) (\/api\/v1\/[a-zA-Z0-9_\-/{}]*)`/g;
|
|
const endpointsFound = [];
|
|
let epMatch;
|
|
while ((epMatch = endpointRegex.exec(specContent)) !== null) {
|
|
endpointsFound.push({ method: epMatch[1], path: epMatch[2] });
|
|
}
|
|
|
|
console.log(`Detected ${endpointsFound.length} fully structured REST endpoint contracts.`);
|
|
if (endpointsFound.length >= 62) {
|
|
console.log(` PASS: Required endpoint threshold met (${endpointsFound.length} >= 62).\n`);
|
|
} else {
|
|
console.error(` FAIL: Found only ${endpointsFound.length} endpoints, expected at least 62!\n`);
|
|
totalErrors++;
|
|
}
|
|
|
|
// 6. Verify Section 3.2.1 Mock Data Field Discard & Presentation Reconciliation Table
|
|
console.log('Verifying Section 3.2.1 Mock Data Field Discard & Presentation Reconciliation Table...');
|
|
const discardTablePresent = specContent.includes('3.2.1 Mock Data Field Discard & Presentation Reconciliation Table');
|
|
const keyTokens = [
|
|
'relX', 'relY', 'labelLeft', 'labelWidth', 'originRelY', 'ratingPillWidth',
|
|
'titleHeight', 'badgeLeft', 'bgColor', 'titleColor', 'subtitleWidth',
|
|
'iconBoxBg', 'badgeCount', 'rightIconType', 'gradientBg', 'figmaNodeId',
|
|
];
|
|
let missingTokens = 0;
|
|
for (const token of keyTokens) {
|
|
if (!specContent.includes(`\`${token}\``)) {
|
|
console.error(` [MISSING DISCARD TOKEN]: "${token}" is not documented in the discard table`);
|
|
missingTokens++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
|
|
if (discardTablePresent && missingTokens === 0) {
|
|
console.log(` PASS: Section 3.2.1 Discard Table is present and documents all ${keyTokens.length} verified layout tokens.\n`);
|
|
} else {
|
|
console.error(' FAIL: Discard table is missing or incomplete!\n');
|
|
totalErrors++;
|
|
}
|
|
|
|
// 7. Verify Section 3.5 Technology-Agnostic JSON Schemas for ALL 20 Canonical Entities
|
|
console.log('Verifying Section 3.5 Draft-07 JSON Schemas for ALL 20 canonical entities...');
|
|
const sec35Match = specContent.match(/###\s*3\.5\s+Technology-Agnostic\s+JSON\s+Schemas[\s\S]*?(?=##\s*4\.\s*REST|$)/);
|
|
if (!sec35Match) {
|
|
console.error(' [FATAL]: Section 3.5 not found in specification!');
|
|
totalErrors++;
|
|
} else {
|
|
const sec35Content = sec35Match[0];
|
|
let missingSchemas = 0;
|
|
for (const entity of requiredEntities) {
|
|
const schemaHeadingRegex = new RegExp(`####\\s*\\d+\\.[^\\n]*\\(${entity}\\)`, 'i');
|
|
if (!schemaHeadingRegex.test(sec35Content)) {
|
|
console.error(` [MISSING JSON SCHEMA]: Dedicated schema heading for "${entity}" not found in Section 3.5`);
|
|
missingSchemas++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
|
|
if (missingSchemas === 0) {
|
|
console.log(` PASS: All ${requiredEntities.length} canonical entities have dedicated Draft-07 JSON Schemas in Section 3.5.\n`);
|
|
} else {
|
|
console.error(` FAIL: ${missingSchemas} entity JSON Schemas are missing from Section 3.5!\n`);
|
|
}
|
|
}
|
|
|
|
// 8. Programmatic Validation of ALL fenced JSON code blocks
|
|
console.log('Validating syntax of ALL fenced JSON code blocks across BACKEND_SPEC.md...');
|
|
const jsonBlockRegex = /```json\s*([\s\S]*?)```/g;
|
|
let jsonBlockMatch;
|
|
let jsonBlockCount = 0;
|
|
let jsonBlockErrors = 0;
|
|
|
|
while ((jsonBlockMatch = jsonBlockRegex.exec(specContent)) !== null) {
|
|
jsonBlockCount++;
|
|
const rawJson = jsonBlockMatch[1];
|
|
try {
|
|
JSON.parse(rawJson);
|
|
} catch (err) {
|
|
console.error(` [INVALID JSON BLOCK #${jsonBlockCount}]: ${err.message}`);
|
|
jsonBlockErrors++;
|
|
totalErrors++;
|
|
}
|
|
}
|
|
|
|
if (jsonBlockErrors === 0) {
|
|
console.log(` PASS: All ${jsonBlockCount} fenced JSON code blocks parsed successfully with 0 syntax errors.\n`);
|
|
} else {
|
|
console.error(` FAIL: Found ${jsonBlockErrors} invalid JSON code blocks!\n`);
|
|
}
|
|
|
|
// 9. Verify PostgreSQL DDL constraints & error envelope
|
|
console.log('Verifying database constraints & error envelopes...');
|
|
const uniqueCartConstraint = specContent.includes('CONSTRAINT uq_shopping_carts_user UNIQUE (user_id)');
|
|
const addressSnapshotPresent = specContent.includes('shipping_address_snapshot');
|
|
const errorEnvelopePresent = specContent.includes('Standard Error Response') && specContent.includes('RESOURCE_NOT_FOUND');
|
|
|
|
if (uniqueCartConstraint && addressSnapshotPresent && errorEnvelopePresent) {
|
|
console.log(' PASS: Unique cart constraint, address snapshotting, and error envelopes are verified.\n');
|
|
} else {
|
|
console.error(' FAIL: Missing critical constraint or error envelope definitions!\n');
|
|
totalErrors++;
|
|
}
|
|
|
|
// Final Summary
|
|
console.log('====================================================');
|
|
if (totalErrors === 0) {
|
|
console.log(' RESULT: ALL QUALITY GATES PASSED (100% COMPLIANT)');
|
|
console.log('====================================================');
|
|
process.exit(0);
|
|
} else {
|
|
console.error(` RESULT: FAILED WITH ${totalErrors} ERROR(S)`);
|
|
console.log('====================================================');
|
|
process.exit(1);
|
|
}
|