Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(engine): derive the capability matrix lazily instead of at module load
Yudhi Armyndharisd159fcf7e89a
diff --git a/src/engine/docs-29-counts.spec.ts b/src/engine/docs-29-counts.spec.tsindex c9240eed2..50642cd2a 100644--- a/src/engine/docs-29-counts.spec.ts+++ b/src/engine/docs-29-counts.spec.ts@@ -1,6 +1,6 @@import { readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';-import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';+import { engineCapabilityMatrix } from './engine-capability-matrix';/*** `docs/29` states the same three figures in ten places — the intro, the architecture prose, a@@ -21,7 +21,7 @@ describe('docs/29 counts match the capability matrix', () => {* line-oriented parse could.*/const recount = () => {- const rows = Object.values(ENGINE_CAPABILITY_MATRIX).map(entry => ({+ const rows = Object.values(engineCapabilityMatrix()).map(entry => ({wwjs: entry.wwjs.status,baileys: entry.baileys.status,}));diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex bdc19ad5b..ed7d2e3e4 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -5,8 +5,8 @@** DERIVED — membership and the default. The method list is not hand-maintained: it is read from* `interfaces/whatsapp-engine.interface.ts` with the same member regex the parity gate- * (`engine-parity.spec.ts`) applies, so a method added to the interface appears in- * ENGINE_CAPABILITY_MATRIX the moment it compiles and a removed one drops out. A method with no+ * (`engine-parity.spec.ts`) applies, so a method added to the interface appears in the derived+ * matrix the moment it compiles and a removed one drops out. A method with no* curated entry defaults to `{wwjs: supported, baileys: supported}` — "plainly works on both" is* the common case and costs no line here.*@@ -442,11 +442,12 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {const MEMBER_RE = /^\s{2}([a-zA-Z][a-zA-Z0-9]*)\??\s*\(/;function readInterfaceMethods(): string[] {- // The interface SOURCE is the inventory's source of truth, so it is read from disk at module- // load. Two layouts resolve it: this file among its sources (ts-jest / ts-node), and this file- // compiled into dist inside a checkout (dist/engine → ../../src/engine). A deployment image that- // ships only dist cannot read it — but every consumer of the matrix is a spec or docs gate, none- // runtime, so the read never happens there; if one ever appears, this error names the fix.+ // The interface SOURCE is the inventory's source of truth, so it is read from disk when the+ // matrix is first derived — lazily, on the first engineCapabilityMatrix() call, never at import.+ // Two layouts resolve it: this file among its sources (ts-jest / ts-node), and this file compiled+ // into dist inside a checkout (dist/engine → ../../src/engine). A deployment image that ships+ // only dist cannot read it — a dist-only runtime consumer would still fail at CALL time with the+ // error below; making the matrix a build-time artifact is the fix if such a consumer ever appears.const candidates = [join(__dirname, 'interfaces', 'whatsapp-engine.interface.ts'),join(__dirname, '..', '..', 'src', 'engine', 'interfaces', 'whatsapp-engine.interface.ts'),@@ -454,7 +455,7 @@ function readInterfaceMethods(): string[] {const path = candidates.find(p => existsSync(p));if (!path) {throw new Error(- `Cannot derive ENGINE_CAPABILITY_MATRIX: the interface source was not found (tried ${candidates.join(', ')}). ` ++ `Cannot derive the engine capability matrix: the interface source was not found (tried ${candidates.join(', ')}). ` +'The matrix is derived from src/engine/interfaces/whatsapp-engine.interface.ts, which must be present.',);}@@ -496,4 +497,19 @@ function copyCapability(entry: MethodCapability): MethodCapability {return copy;}-export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = deriveEngineCapabilityMatrix();+/**+ * The derived matrix, produced on FIRST CALL and memoized. Deriving at module load meant importing+ * this module read `whatsapp-engine.interface.ts` from disk at import time — harmless for the spec+ * and docs gates that are its only consumers today, but a runtime import from a dist-only+ * deployment image would have crashed at import. Lazy derivation moves that failure to CALL time,+ * where the loud named error in readInterfaceMethods still names the fix; if a dist-only runtime+ * consumer ever appears for real, making the matrix a build-time artifact is the fix, not this+ * cache. The memoized object is shared across callers exactly like the const it replaced, and+ * derivation copies each row, so no caller can alias CURATED_CAPABILITY_EXCEPTIONS.+ */+let cachedMatrix: Record<string, MethodCapability> | undefined;++export function engineCapabilityMatrix(): Record<string, MethodCapability> {+ cachedMatrix ??= deriveEngineCapabilityMatrix();+ return cachedMatrix;+}diff --git a/src/engine/engine-inventory-parity.spec.ts b/src/engine/engine-inventory-parity.spec.tsindex 72860ca2a..bf79a0193 100644--- a/src/engine/engine-inventory-parity.spec.ts+++ b/src/engine/engine-inventory-parity.spec.ts@@ -1,6 +1,6 @@import { readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';-import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';+import { engineCapabilityMatrix } from './engine-capability-matrix';/*** Drift invariants for the hand-maintained halves of docs/29-engine-capability-matrix.md.@@ -200,11 +200,12 @@ describe('engine inventory (docs/29 §29.5) — drift invariants', () => {});it('every interface method named in a ✅ exposure cell is `supported` for this engine', () => {+ const matrix = engineCapabilityMatrix();const offenders: string[] = [];for (const row of readInventory(engine)) {if (!row.exposure.startsWith('✅')) continue;for (const [, method] of row.exposure.matchAll(/`([a-zA-Z][a-zA-Z0-9]*)`/g)) {- const entry = ENGINE_CAPABILITY_MATRIX[method];+ const entry = matrix[method];if (!entry) continue; // prose backtick, not an interface methodif (entry[engine].status !== 'supported') offenders.push(`${row.symbol} → ${method}`);}diff --git a/src/engine/engine-parity.spec.ts b/src/engine/engine-parity.spec.tsindex 109bcea05..e03fef65a 100644--- a/src/engine/engine-parity.spec.ts+++ b/src/engine/engine-parity.spec.ts@@ -2,7 +2,7 @@ import { readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { BaileysAdapter } from './adapters/baileys.adapter';import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';-import { CURATED_CAPABILITY_EXCEPTIONS, ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';+import { CURATED_CAPABILITY_EXCEPTIONS, engineCapabilityMatrix } from './engine-capability-matrix';/*** Drift invariants for the engine capability matrix. Status and throw behaviour must agree exactly:@@ -149,7 +149,8 @@ function liveThrows(adapter: AdapterCtor, method: string, engine: string): booledescribe('engine capability matrix — drift invariants', () => {const methods = readInterfaceMethods();- const matrixKeys = Object.keys(ENGINE_CAPABILITY_MATRIX).sort();+ const matrix = engineCapabilityMatrix();+ const matrixKeys = Object.keys(matrix).sort();// Guard against a pattern that silently stops matching: an empty registry would make the widened// scan collapse back to the prototype-only one without a single test turning red.@@ -191,7 +192,7 @@ describe('engine capability matrix — drift invariants', () => {// binding between the two readers — if the module's copy drifted from the spec's, the derived// keys and the inventory read here would disagree and this test would fail.it('matrix keys exactly match the interface methods (no missing, no stale)', () => {- const missing = methods.filter(m => !(m in ENGINE_CAPABILITY_MATRIX));+ const missing = methods.filter(m => !(m in matrix));const stale = matrixKeys.filter(k => !methods.includes(k));expect({ missing, stale }).toEqual({ missing: [], stale: [] });});@@ -209,7 +210,7 @@ describe('engine capability matrix — drift invariants', () => {});it.each(methods)('%s: throws ⇔ not-available', method => {- const entry = ENGINE_CAPABILITY_MATRIX[method];+ const entry = matrix[method];for (const [adapter, ctor] of ADAPTERS) {const throws = liveThrows(ctor, method, adapter);const status = entry[adapter].status;diff --git a/src/engine/inventory-mapping-direction.spec.ts b/src/engine/inventory-mapping-direction.spec.tsindex 2a0cfc4e7..d1f459f20 100644--- a/src/engine/inventory-mapping-direction.spec.ts+++ b/src/engine/inventory-mapping-direction.spec.ts@@ -1,7 +1,7 @@import { readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import * as ts from 'typescript';-import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';+import { engineCapabilityMatrix } from './engine-capability-matrix';/*** The DIRECTION of the docs/29 §29.5 inventory: a row saying "`groupMetadata` → `getGroupInfo`,@@ -144,15 +144,14 @@ function reachers(symbol: string, engine: Engine): Set<string> {function inventoryRows(engine: Engine): { symbol: string; listed: string[] }[] {const doc = readFileSync(DOC, 'utf8');+ const matrix = engineCapabilityMatrix();const start = doc.indexOf(engine === 'baileys' ? '### 29.5.1' : '### 29.5.2');const end = doc.indexOf(engine === 'baileys' ? '### 29.5.2' : '### 29.5.3');const rows: { symbol: string; listed: string[] }[] = [];for (const line of doc.slice(start, end).split('\n')) {const m = /^\|\s*`([^`]+)`\s*\|\s*(✅.*?)\s*\|\s*$/.exec(line);if (!m) continue;- const listed = [...m[2].matchAll(/`([a-zA-Z][\w]*)`/g)]- .map(x => x[1])- .filter(name => name in ENGINE_CAPABILITY_MATRIX);+ const listed = [...m[2].matchAll(/`([a-zA-Z][\w]*)`/g)].map(x => x[1]).filter(name => name in matrix);if (listed.length) rows.push({ symbol: m[1], listed });}return rows;