Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): gate client wire shapes against the OpenAPI contract
Yudhi Armyndharis65b585e6aca1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 53f0d6fa6..4fdb81fc7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -77,6 +77,12 @@ jobs:- name: Check SDK docs cover the shipped client surfacerun: npm run check:sdk-docs+ # The shape half of the client contract gates above: routes/events/methods say WHICH+ # endpoints exist, this says the hand-written SDK/dashboard types mirror the DTO schemas+ # they carry — the verification none of the other gates provide.+ - name: Client wire-shape contract check+ run: npm run check:contract-shapes+# Deliberately its own job rather than a step inside Lint. `npm audit` reports against the# advisory database, not against the diff, so a newly published advisory turns red on unrelated# PRs. While it lived as the first step of Lint, that failure aborted the job before ESLint, thediff --git a/CHANGELOG.md b/CHANGELOG.mdindex e5359fb26..c48a89a42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Weekly scheduled security scan (`.github/workflows/security-scan.yml`): the merge-time audit gates re-run against the current dependency trees, and the release image scan re-runs against the published `latest` image on both architectures — a newly published advisory surfaces within days instead of at the next push or release. Also dispatchable on demand.+- Client wire-shape contract gate (`check:contract-shapes`, in the CI lint job): the JavaScript SDK's and the dashboard's hand-written wire types are now checked field-by-field against the OpenAPI schemas — presence, required-vs-optional, and type drift for simple fields — closing the gap where every existing gate verified which routes exist but none verified the body shapes they carry. 21 pairs conform today; 23 known-drifting pairs are excluded inline with recorded reasons and shrink as each is adjudicated.## [0.19.0] - 2026-08-15diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex cc04ea686..7819a753e 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -236,17 +236,17 @@ on broad integration coverage.Main CI is defined in `.github/workflows/ci.yml`.-| Job | Checks |-| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, .dockerignore context, OpenAPI snapshot, SDK routes and webhook events against the contract, contract coverage per SDK, SDK docs against the shipped client surface |-| `audit` | dependency security audit of BOTH npm trees (root and `dashboard/`) |-| `test` | backend coverage run, script unit tests (node:test), e2e smoke tests, Codecov upload |-| `test-postgres` | real PostgreSQL 16 service, backend build, migration smoke, and PostgreSQL FTS provider spec |-| `dashboard` | dashboard install, lint, formatting, type-check, i18n parity, build, unit tests |-| `scripts-smoke` | shellcheck on `docker-entrypoint.sh` and every `scripts/*.sh`, plus the backup/restore smoke test |-| `chart` | helm lint, helm template with default and fully-toggled values, kubeconform on both renders, the rendered-behaviour check, actionlint on the workflows |-| `build` | backend build after lint/audit/test/dashboard/scripts-smoke/chart jobs pass |-| `docker` | multi-arch Docker build on pushes and pull requests, then `scripts/smoke-test-non-root.sh` against the built image so the entrypoint's root→openwa drop is verified, not assumed; publishes to GHCR only on push, so fork pull requests validate both architectures without publishing |+| Job | Checks |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, .dockerignore context, OpenAPI snapshot, SDK routes and webhook events against the contract, contract coverage per SDK, SDK docs against the shipped client surface, client wire shapes (`check:contract-shapes` — the SDK's and dashboard's hand-written types against the OpenAPI schemas) |+| `audit` | dependency security audit of BOTH npm trees (root and `dashboard/`) |+| `test` | backend coverage run, script unit tests (node:test), e2e smoke tests, Codecov upload |+| `test-postgres` | real PostgreSQL 16 service, backend build, migration smoke, and PostgreSQL FTS provider spec |+| `dashboard` | dashboard install, lint, formatting, type-check, i18n parity, build, unit tests |+| `scripts-smoke` | shellcheck on `docker-entrypoint.sh` and every `scripts/*.sh`, plus the backup/restore smoke test |+| `chart` | helm lint, helm template with default and fully-toggled values, kubeconform on both renders, the rendered-behaviour check, actionlint on the workflows |+| `build` | backend build after lint/audit/test/dashboard/scripts-smoke/chart jobs pass |+| `docker` | multi-arch Docker build on pushes and pull requests, then `scripts/smoke-test-non-root.sh` against the built image so the entrypoint's root→openwa drop is verified, not assumed; publishes to GHCR only on push, so fork pull requests validate both architectures without publishing |SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus servercontract surfaces that SDKs mirror (`src/**/dto/**`, `src/**/*.controller.ts`, `src/**/*.service.ts`, anddiff --git a/package.json b/package.jsonindex c158b1d38..97c2206d7 100644--- a/package.json+++ b/package.json@@ -35,12 +35,13 @@"check:sdk-coverage": "node scripts/check-sdk-coverage.mjs","check:sdk-events": "node scripts/check-sdk-events.mjs","check:sdk-docs": "node scripts/check-sdk-docs.mjs",+ "check:contract-shapes": "node scripts/check-contract-shapes.mjs","openapi:export": "ts-node scripts/export-openapi.ts openapi.json","openapi:check": "ts-node scripts/export-openapi.ts /tmp/openapi.generated.json && diff -u openapi.json /tmp/openapi.generated.json","lint": "eslint \"{src,apps,libs,test}/**/*.ts\"","lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix","test": "jest",- "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs",+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs","test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts --testPathIgnorePatterns=/node_modules/","test:watch": "jest --watch","test:cov": "jest --coverage",diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsnew file mode 100644index 000000000..67e546307--- /dev/null+++ b/scripts/check-contract-shapes.mjs@@ -0,0 +1,353 @@+#!/usr/bin/env node+/**+ * Shape gate: the hand-written wire types of the two HTTP clients (the JavaScript SDK's types.ts+ * and the dashboard's api.ts) against the DTO schemas of the committed openapi.json.+ *+ * This is the contract verification the repo previously had in name only: every existing gate+ * checks WHICH routes/events/methods exist, none checks request/response body SHAPES — the mocks+ * in each client's own suite are a circular oracle. Why a source-parsing script rather than+ * type-level assertions against a generated contract view: deep comparisons through schema trees+ * this large were observed driving the TypeScript 6 checker to composition-dependent verdicts (the+ * same pair failing in one file, silently passing in another — instantiation-budget degradation),+ * which is worse than no gate at all. Comparing parsed declarations against JSON schemas is+ * deterministic, and it is the same mechanism the other check-* gates trust.+ *+ * What one comparison covers, per mapped pair: field-name sets in both directions, required vs+ * optional (hand `?` vs the schema's `required` array), and — for fields whose both sides reduce+ * to a simple token (primitive, enum literal set, array of those, null union) — the token itself,+ * which is what catches `string` widened to `string | number` or a re-ordered enum growing a+ * member. Complex/nested fields are compared by presence and optionality only; that limit is+ * deliberate (the hand parser stays regular), and the exclusions below record what is known to be+ * unpinned. Every mapping entry must resolve on BOTH sides — a renamed hand type or schema fails+ * loudly instead of being skipped (the vacuous-pass failure mode), and the run refuses to gate+ * fewer than 8 pairs per client for the same reason (the dashboard's mappable surface is smaller than the SDK's; exclusions are explicit and counted either way).+ *+ * Pairs that drift today live in EXCLUDED with a one-line reason, mirroring the per-advisory+ * allowlist culture of check-audit: an exclusion is a recorded decision, not a silent skip, and+ * the goal is to shrink it to zero (usually by tightening the hand type; where the CONTRACT+ * under-describes reality, fix the backend DTO decorator, regenerate, and un-exclude).+ */++import { readFileSync } from 'node:fs';++/** hand file -> { handTypeName: schemaName } */+const MAPPINGS = {+ 'sdk/javascript/src/types.ts': {+ AccountRestriction: 'AccountRestrictionDto',+ BatchProgress: 'BatchProgressDto',+ BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMessageContent: 'BulkMessageContentDto',+ BulkMessageItem: 'BulkMessageItemDto',+ CallLinkResponse: 'CallLinkResponseDto',+ ChatHistoryMessage: 'ChatHistoryMessageDto',+ ChatSummary: 'ChatSummaryDto',+ GroupInfo: 'GroupInfoDto',+ GroupJoinInfo: 'GroupJoinInfoDto',+ GroupParticipant: 'GroupParticipantDto',+ GroupSummary: 'GroupSummaryDto',+ MessageListResponse: 'MessageListResponseDto',+ MessageResponse: 'MessageResponseDto',+ PairingCodeResponse: 'PairingCodeResponseDto',+ ParticipantPresence: 'ParticipantPresenceDto',+ ProfilePictureResponse: 'ProfilePictureResponseDto',+ ProfilePicturesResponse: 'ProfilePicturesResponseDto',+ SearchHit: 'SearchHitDto',+ SessionResponse: 'SessionResponseDto',+ StatusResult: 'StatusResultDto',+ WebhookResponse: 'WebhookResponseDto',+ },+ 'dashboard/src/services/api.ts': {+ AccountRestriction: 'AccountRestrictionDto',+ ApiKey: 'ApiKeyResponseDto',+ BatchMessageResult: 'BatchMessageResultDto',+ Chat: 'ChatSummaryDto',+ AuditLog: 'AuditLogDto',+ BatchProgress: 'BatchProgressDto',+ BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMessageItem: 'BulkMessageItemDto',+ Channel: 'ChannelDto',+ ChannelMessage: 'ChannelMessageDto',+ ChatPresence: 'ChatPresenceResponseDto',+ Contact: 'ContactDto',+ EngineHistoryMessage: 'ChatHistoryMessageDto',+ MessageResponse: 'MessageResponseDto',+ ParticipantPresence: 'ParticipantPresenceDto',+ ProfilePictureResponse: 'ProfilePictureResponseDto',+ SearchHit: 'SearchHitDto',+ Session: 'SessionResponseDto',+ SessionConfig: 'SessionConfigResponseDto',+ Webhook: 'WebhookResponseDto',+ },+};++/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */+const EXCLUDED = {+ 'sdk/javascript/src/types.ts': {+ AccountRestriction:+ 'hand types expiresAt as string|null; contract declares string — adjudicate which side reflects the runtime',+ GroupSummary: 'hand types linkedParentJID as string|null; contract declares string — adjudicate',+ ProfilePictureResponse: 'hand types url as string|null; contract declares string — adjudicate',+ BatchMessageResult: 'hand marks chatId/status optional; contract declares them required with a status enum',+ BulkMessageResponse: 'hand requires estimatedCompletionTime; contract declares it optional',+ BatchStatusResponse: 'hand marks results optional; contract requires it',+ ChatHistoryMessage: 'field-level differences across the 20+-field history shape; adjudicate pair-by-pair',+ ChatSummary:+ 'hand marks every field optional and widens timestamp to string|number; contract requires them, timestamp a number',+ GroupInfo: 'nullable-vs-optional and enum differences across 10+ fields; adjudicate pair-by-pair',+ SessionResponse: 'field-level differences; adjudicate pair-by-pair',+ WebhookResponse:+ 'CONTRACT GAP: response schema declares filters as Record<string, never>; fix the backend DTO decorator, then pin',+ },+ 'dashboard/src/services/api.ts': {+ AccountRestriction:+ 'hand types expiresAt as string|null; contract declares string — adjudicate which side reflects the runtime',+ ProfilePictureResponse: 'hand types url as string|null; contract declares string — adjudicate',+ SearchHit: 'hand widens direction to string; contract narrows to enum(incoming,outgoing) — narrow the hand type',+ SessionConfig: 'hand types maxReconnectAttempts as number|null; contract declares number — adjudicate',+ ApiKey:+ 'hand declares an apiKey field the response never carries (the plaintext is shown once at creation); drop it from the type',+ AuditLog:+ 'hand marks apiKeyId/apiKeyName/sessionId/sessionName and the action fields optional; contract requires them, and adds metadata/userAgent',+ BatchStatusResponse: 'hand marks results optional; contract requires it',+ Channel: 'hand lacks createdAt/description/picture the response carries',+ Contact: 'hand marks number optional; contract requires it, and hand lacks isBlocked/isMyContact/profilePicUrl',+ EngineHistoryMessage:+ 'hand models a subset of the history shape (13 contract fields missing, fromMe optional); mirror the full shape',+ Session: 'hand marks engineLoaded optional and lacks connectedAt; contract requires both',+ Webhook: 'hand declares secret (never returned) and lacks lastTriggeredAt/retryCount',+ },+};++// ── hand-type parsing (declarations follow the regular formatting of the two files) ──++export function parseHandTypes(source) {+ const types = {};+ const iface = /export interface (\w+)(?: extends \w+)? \{([\s\S]*?)\n\}/g;+ for (const [, name, body] of source.matchAll(iface)) types[name] = parseMembers(body);+ return types;+}++/** Splits a declaration body into { field: { optional, token } } via brace-depth scanning. */+function parseMembers(body) {+ const members = {};+ let depth = 0;+ let field = null;+ let buffer = '';+ for (const line of body.split('\n')) {+ const cleaned = line+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/\/\/.*$/, '')+ .trim();+ if (!cleaned) continue;+ if (depth === 0) {+ const m = cleaned.match(/^(\w+)(\?)?:\s*(.*)$/);+ if (m) {+ field = m[1];+ members[field] = { optional: m[2] === '?', token: m[3] };+ if (m[3].startsWith('{')) {+ depth = countUnbalanced(m[3]);+ buffer = m[3];+ }+ continue;+ }+ }+ if (depth > 0) {+ buffer += ' ' + cleaned;+ depth += countUnbalanced(cleaned);+ if (depth <= 0) members[field].token = buffer.replace(/\s+/g, ' ');+ }+ }+ return members;+}++function countUnbalanced(s) {+ let n = 0;+ for (const ch of s) {+ if (ch === '{' || ch === '[') n++;+ else if (ch === '}' || ch === ']') n--;+ }+ return n;+}++// ── shape tokens: reduce hand TS text and JSON schema nodes to comparable strings ──++const MAX_DEPTH = 4;++export function handToken(text, types, depth = 0) {+ const t = text.trim().replace(/;$/, '');+ if (t.endsWith('[]')) return `array<${handToken(t.slice(0, -2), types, depth)}>`;+ if (/^(string|number|boolean|unknown|any)$/.test(t)) return t;+ const literals = [...t.matchAll(/'([^']+)'/g)].map(m => m[1]);+ if (literals.length && literals.length === t.split('|').length) return `enum(${literals.slice().sort().join(',')})`;+ if (t.includes('|')) {+ const parts = t+ .split('|')+ .map(p => p.trim())+ .filter(p => p && p !== 'undefined');+ const nullable = parts.includes('null');+ const rest = parts.filter(p => p !== 'null');+ if (nullable && rest.length === 1) return `${handToken(rest[0], types, depth)}|null`;+ return `union(${rest+ .map(p => handToken(p, types, depth))+ .sort()+ .join(',')})`;+ }+ const ref = types[t];+ if (ref && depth < MAX_DEPTH) {+ return `object(${Object.entries(ref)+ .map(([f, v]) => `${f}${v.optional ? '?' : ''}:${handToken(v.token, types, depth + 1)}`)+ .sort()+ .join(',')})`;+ }+ return t; // named type not resolvable in this file (e.g. Jid) — compare by name+}++export function schemaToken(node, schemas, depth = 0) {+ if (!node || typeof node !== 'object') return 'any';+ if (node.$ref) {+ const target = schemas[node.$ref.split('/').pop()];+ return depth < MAX_DEPTH ? schemaToken(target, schemas, depth + 1) : 'object';+ }+ if (node.enum) return `enum(${node.enum.slice().sort().join(',')})`;+ if (node.type === 'array') return `array<${schemaToken(node.items, schemas, depth)}>`;+ if (node.anyOf || node.oneOf) {+ const parts = (node.anyOf ?? node.oneOf).map(n => schemaToken(n, schemas, depth + 1));+ const nullable = parts.includes('null');+ const rest = parts.filter(p => p !== 'null').filter(p => p !== 'any' || !nullable);+ if (nullable && rest.length === 1) return `${rest[0]}|null`;+ return `union(${rest.sort().join(',')})`;+ }+ if (node.type === 'object') {+ if (depth >= MAX_DEPTH) return 'object';+ const required = new Set(node.required ?? []);+ const props = Object.entries(node.properties ?? {}).map(+ ([f, v]) => `${f}${required.has(f) ? '' : '?'}:${schemaToken(v, schemas, depth + 1)}`,+ );+ return `object(${props.sort().join(',')})`;+ }+ const t = node.type ?? 'any';+ if (t === 'integer') return 'number';+ return t;+}++/** Splits an object(...) token back into { field: { optional, token } } for field-level diffing. */+export function parseObjectToken(token) {+ const inner = token.match(/^object\((.*)\)$/)?.[1];+ if (inner === undefined) return {};+ const members = {};+ let depth = 0;+ let buffer = '';+ for (const ch of inner) {+ if (ch === ',' && depth === 0) {+ pushMember();+ continue;+ }+ if (ch === '(' || ch === '<' || ch === '{') depth++;+ if (ch === ')' || ch === '>' || ch === '}') depth--;+ buffer += ch;+ }+ pushMember();+ function pushMember() {+ const m = buffer.match(/^(\w+)(\?)?:(.*)$/s);+ if (m) members[m[1]] = { optional: m[2] === '?', token: m[3] };+ buffer = '';+ }+ return members;+}++/** Fields whose both sides reduce to a primitive/enum/array/null-union get token-level diffing. */+function isSimpleToken(token) {+ return /^(string|number|boolean|unknown|any)(\|null)?$|^enum\([^)]*\)$|^array<(string|number|boolean)(\|null)?>$/.test(+ token,+ );+}++/**+ * Compares one hand type against one schema. Returns an array of human-readable diff lines —+ * empty when the pair conforms. Exported for the spec; the CLI loop below is a thin driver.+ */+export function comparePair(handName, handMembers, schemaName, schema, schemas) {+ const diffs = [];+ const schemaFields = parseObjectToken(schemaToken(schema, schemas));+ for (const [field, handInfo] of Object.entries(handMembers)) {+ const sField = schemaFields[field];+ if (!sField) {+ diffs.push(`hand has "${field}" — contract does not`);+ continue;+ }+ if (handInfo.optional !== sField.optional) {+ diffs.push(+ `"${field}": hand ${handInfo.optional ? 'optional' : 'required'}, contract ${sField.optional ? 'optional' : 'required'}`,+ );+ continue;+ }+ if (isSimpleToken(sField.token)) {+ const hand = handToken(handInfo.token, { [handName]: handMembers });+ if (hand !== sField.token && isSimpleToken(hand))+ diffs.push(`"${field}": hand ${hand}, contract ${sField.token}`);+ }+ }+ for (const field of Object.keys(schemaFields)) {+ if (!(field in handMembers)) diffs.push(`contract has "${field}" — hand does not`);+ }+ return diffs;+}++// ── CLI driver ──++const isDirectRun = process.argv[1] && import.meta.url.endsWith(process.argv[1].split('/').pop());+if (isDirectRun) {+ const openapi = JSON.parse(readFileSync('openapi.json', 'utf8'));+ const schemas = openapi.components.schemas;+ let failures = 0;+ let compared = 0;++ for (const [file, mapping] of Object.entries(MAPPINGS)) {+ const source = readFileSync(file, 'utf8');+ const handTypes = parseHandTypes(source);+ const excluded = EXCLUDED[file] ?? {};+ let fileCompared = 0;+ const fileResults = [];++ for (const [handName, schemaName] of Object.entries(mapping)) {+ if (excluded[handName]) continue;+ const hand = handTypes[handName];+ const schema = schemas[schemaName];+ if (!hand) {+ fileResults.push(` MISSING hand type ${handName} (declared in mapping but not found in ${file})`);+ failures++;+ continue;+ }+ if (!schema) {+ fileResults.push(` MISSING schema ${schemaName} (declared in mapping but not in openapi.json)`);+ failures++;+ continue;+ }+ fileCompared++;+ compared++;+ const diffs = comparePair(handName, hand, schemaName, schema, schemas);+ if (diffs.length) {+ fileResults.push(` ${handName} ↔ ${schemaName}:`, ...diffs.map(d => ` ${d}`));+ failures++;+ }+ }++ if (fileCompared < 8) {+ fileResults.push(` only ${fileCompared} pairs compared for ${file} — vacuous-pass guard`);+ failures++;+ }+ console.log(`${file}: ${fileCompared} pairs compared, ${fileResults.length ? 'FAILURES' : 'all conform'}`);+ for (const line of fileResults) console.log(line);+ const excludedCount = Object.keys(excluded).length;+ if (excludedCount) {+ console.log(` (${excludedCount} excluded pair(s) with recorded reasons — see EXCLUDED in this script)`);+ }+ }++ console.log(+ failures+ ? `\ncheck-contract-shapes: ${failures} failing pair(s) — the contract side wins; tighten the hand type or fix the backend DTO and regenerate.`+ : `\ncheck-contract-shapes: ${compared} pairs conform.`,+ );+ process.exit(failures ? 1 : 0);+}diff --git a/scripts/check-contract-shapes.spec.mjs b/scripts/check-contract-shapes.spec.mjsnew file mode 100644index 000000000..ac3f68215--- /dev/null+++ b/scripts/check-contract-shapes.spec.mjs@@ -0,0 +1,104 @@+#!/usr/bin/env node+/**+ * Spec for check-contract-shapes.mjs — a gate that cannot fail is worse than no gate, so these+ * cases pin the comparator's failure modes against inline fixtures: field presence both ways,+ * optionality flips, token-level drift (widened union, enum mismatch), and the hand parser's+ * regular cases. The `without a ?` case pins a real regression: the member regex once made its+ * literal-`?` group mandatory, so every required field silently failed to parse and the gate+ * compared against a half-empty hand type.+ */++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { parseHandTypes, parseObjectToken, schemaToken, comparePair, handToken } from './check-contract-shapes.mjs';++const handSource = `+export interface Sample {+ id: string;+ name?: string;+ direction: string;+ count: number | null;+}+`;++test('parseHandTypes reads required and optional members (a required field is not silently dropped)', () => {+ const types = parseHandTypes(handSource);+ assert.deepEqual(Object.keys(types.Sample), ['id', 'name', 'direction', 'count']);+ assert.equal(types.Sample.id.optional, false);+ assert.equal(types.Sample.name.optional, true);+});++const schemas = {+ SampleDto: {+ type: 'object',+ required: ['id', 'direction', 'count'],+ properties: {+ id: { type: 'string' },+ name: { type: 'string' },+ direction: { type: 'string', enum: ['incoming', 'outgoing'] },+ count: { type: 'integer' },+ },+ },+ SameDto: {+ type: 'object',+ required: ['id', 'direction', 'count'],+ properties: {+ id: { type: 'string' },+ direction: { type: 'string', enum: ['incoming', 'outgoing'] },+ count: { anyOf: [{ type: 'integer' }, { type: 'null' }] },+ },+ },+};++test('comparePair returns no diffs for a conforming pair', () => {+ const hand = {+ id: { optional: false, token: 'string' },+ direction: { optional: false, token: "'incoming' | 'outgoing'" },+ count: { optional: false, token: 'number | null' },+ };+ assert.deepEqual(comparePair('Same', hand, 'SameDto', schemas.SameDto, schemas), []);+});++test('comparePair flags a field the contract has and the hand lacks, and vice versa', () => {+ const hand = { id: { optional: false, token: 'string' }, extra: { optional: false, token: 'string' } };+ const diffs = comparePair('Sample', hand, 'SampleDto', schemas.SampleDto, schemas);+ assert.ok(diffs.some(d => d.includes('hand has "extra"')));+ assert.ok(+ diffs.some(+ d =>+ d.includes('contract has "name"') ||+ d.includes('contract has "direction"') ||+ d.includes('contract has "count"'),+ ),+ );+});++test('comparePair flags an optionality flip', () => {+ const hand = { id: { optional: true, token: 'string' } };+ const diffs = comparePair('Sample', hand, 'SampleDto', schemas.SampleDto, schemas);+ assert.ok(diffs.some(d => d.includes('"id": hand optional, contract required')));+});++test('comparePair flags a widened union and an enum mismatch at token level', () => {+ const hand = {+ id: { optional: false, token: 'string' },+ direction: { optional: false, token: 'string' },+ count: { optional: false, token: 'number | null' },+ };+ const diffs = comparePair('Sample', hand, 'SampleDto', schemas.SampleDto, schemas);+ assert.ok(diffs.some(d => d.includes('"direction": hand string, contract enum(incoming,outgoing)')));+ assert.ok(diffs.some(d => d.includes('"count": hand number|null, contract number')));+});++test('parseObjectToken splits nested object tokens without losing members', () => {+ const members = parseObjectToken('object(id:string,sub:object(a:number,b?:boolean),tail:string)');+ assert.deepEqual(Object.keys(members), ['id', 'sub', 'tail']);+ assert.equal(members.b?.optional ?? parseObjectToken(members.sub.token).b.optional, true);+});++test('handToken reduces enums, null unions and arrays deterministically', () => {+ const types = {};+ assert.equal(handToken("'b' | 'a'", types), 'enum(a,b)'.replace(',', ','));+ assert.equal(handToken('number | null', types), 'number|null');+ assert.equal(handToken('string[]', types), 'array<string>');+});