Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): extend the wire-shape gate to the Python, Go and Java clients
Yudhi Armyndharis168719279813
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bec86a0d6..0f71bd53b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,7 +21,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. 43 pairs conform today; the single remaining exclusion is deliberate (the dashboard's tri-state `engineLoaded` client model, which models client state rather than the wire).+- 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. the gate now spans five clients — the JavaScript SDK, the dashboard, and the Python, Go and Java clients (the PHP client returns untyped arrays and has no types layer to gate) — with 113 pairs conforming; the single remaining exclusion is deliberate (the dashboard's tri-state `engineLoaded` client model, which models client state rather than the wire). The Python, Go and Java clients' wire types were conformed to the contract in the same pass, including two genuine Go wire bugs the measurement surfaced (both fixed): `WebhookResponse.Events` and `ChatHistoryMessage.MentionedIds` were modelled as single strings where the wire carries arrays.## [0.19.0] - 2026-08-15diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 7819a753e..6b4b7b632 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, 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 |+| 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 JavaScript SDK's, dashboard's, Python's, Go's and Java's hand-written types against the OpenAPI schemas; the PHP client returns untyped arrays and has no types layer to gate) |+| `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/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 055a25887..1ea0fbe6a 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -28,7 +28,7 @@* under-describes reality, fix the backend DTO decorator, regenerate, and un-exclude).*/-import { readFileSync } from 'node:fs';+import { readFileSync, readdirSync } from 'node:fs';/** hand file -> { handTypeName: schemaName } */const MAPPINGS = {@@ -91,6 +91,9 @@ const MAPPINGS = {const MINIMUM_MAPPED = {'sdk/javascript/src/types.ts': 24,'dashboard/src/services/api.ts': 20,+ 'sdk/python/openwa/types.py': 22,+ 'sdk/go': 24,+ 'sdk/java': 24,};/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */@@ -101,6 +104,88 @@ const EXCLUDED = {},};+/** Python client pairs (TypedDict classes in openwa/types.py). */+const PYTHON_MAPPING = {+ AccountRestriction: 'AccountRestrictionDto',+ BatchMessageResult: 'BatchMessageResultDto',+ BatchProgress: 'BatchProgressDto',+ BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMessageContent: 'BulkMessageContentDto',+ BulkMessageItem: 'BulkMessageItemDto',+ BulkMessageResponse: 'BulkMessageResponseDto',+ CallLinkResponse: 'CallLinkResponseDto',+ ChatSummary: 'ChatSummaryDto',+ GroupInfo: 'GroupInfoDto',+ GroupJoinInfo: 'GroupJoinInfoDto',+ GroupParticipant: 'GroupParticipantDto',+ GroupSummary: 'GroupSummaryDto',+ MessageListResponse: 'MessageListResponseDto',+ MessageResponse: 'MessageResponseDto',+ PairingCodeResponse: 'PairingCodeResponseDto',+ ParticipantPresence: 'ParticipantPresenceDto',+ ProfilePictureResponse: 'ProfilePictureResponseDto',+ ProfilePicturesResponse: 'ProfilePicturesResponseDto',+ SessionResponse: 'SessionResponseDto',+ StatusResult: 'StatusResultDto',+ WebhookResponse: 'WebhookResponseDto',+};++/** Go client pairs (wire structs across types_*.go). */+const GO_MAPPING = {+ AccountRestriction: 'AccountRestrictionDto',+ BatchMessageResult: 'BatchMessageResultDto',+ BatchProgress: 'BatchProgressDto',+ BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMessageContent: 'BulkMessageContentDto',+ BulkMessageItem: 'BulkMessageItemDto',+ BulkMessageResponse: 'BulkMessageResponseDto',+ 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',+};++/** Java client pairs (record components in model/*.java). */+const JAVA_MAPPING = {+ AccountRestriction: 'AccountRestrictionDto',+ BatchMessageResult: 'BatchMessageResultDto',+ BatchProgress: 'BatchProgressDto',+ BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMessageContent: 'BulkMessageContentDto',+ BulkMessageItem: 'BulkMessageItemDto',+ BulkMessageResponse: 'BulkMessageResponseDto',+ 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',+};+// ── hand-type parsing (declarations follow the regular formatting of the two files) ──export function parseHandTypes(source) {@@ -275,7 +360,7 @@ function isSimpleToken(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) {+export function comparePair(handName, handMembers, schemaName, schema, schemas, compareOptionality = true) {const diffs = [];const schemaFields = parseObjectToken(schemaToken(schema, schemas));for (const [field, handInfo] of Object.entries(handMembers)) {@@ -284,16 +369,27 @@ export function comparePair(handName, handMembers, schemaName, schema, schemas)diffs.push(`hand has "${field}" — contract does not`);continue;}- if (handInfo.optional !== sField.optional) {+ if (compareOptionality && 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}`);+ let hand = isSimpleToken(handInfo.token)+ ? handInfo.token+ : handToken(handInfo.token, { [handName]: handMembers });+ let contract = sField.token;+ if (!compareOptionality) {+ // Java (the only such client) cannot express non-null references — strip null arms on+ // BOTH sides so nullability does not read as drift there; enums and kinds still compare.+ hand = hand.replace(/\|null$/, '');+ contract = contract.replace(/\|null$/, '');+ }+ const absorbs = handInfo.absorbsNull && contract === `${hand}|null`;+ if (hand !== contract && !absorbs && isSimpleToken(hand)) {+ diffs.push(`"${field}": hand ${hand}, contract ${contract}`);+ }}}for (const field of Object.keys(schemaFields)) {@@ -302,28 +398,370 @@ export function comparePair(handName, handMembers, schemaName, schema, schemas)return diffs;}+// ── per-language hand parsers (same member-map contract as parseHandTypes) ──++/**+ * Python (sdk/python/openwa/types.py): TypedDict classes with `total=False` optionality,+ * `Optional[X]`/`X | None` null unions, `List[X]`, inline and aliased `Literal[...]` enums, and+ * TypedDict inheritance (the parent's own total flag governs its members).+ */+export function parsePythonTypes(source) {+ // Join continuation lines inside unclosed brackets so multi-line Literal[...] aliases and+ // annotations parse as one token (a truncated `Literal[` is worse than no token).+ const joined = [];+ let carry = '';+ for (const line of source.split('\n')) {+ carry = carry ? carry + ' ' + line.trim() : line;+ let depth = 0;+ for (const ch of carry) {+ if (ch === '[' || ch === '{' || ch === '(') depth++;+ else if (ch === ']' || ch === '}' || ch === ')') depth--;+ }+ if (depth <= 0) {+ joined.push(carry);+ carry = '';+ }+ }+ if (carry) joined.push(carry);+ source = joined.join('\n');+ const dicts = {};+ const parents = {};+ const optionalAll = new Set();+ const blocks = [...source.matchAll(/class (\w+)\(([^)]*)\):\n([\s\S]*?)(?=\nclass |\n[A-Z]\w+ = |\n*$)/g)];+ // A subclass never re-mentions TypedDict — accept any class whose base chain reaches one+ // (fixpoint: a class is rooted when a base is itself a rooted class).+ const basesOf = Object.fromEntries(+ blocks.map(([, n, b]) => [+ n,+ b+ .split(',')+ .map(x => x.trim())+ .filter(x => x && x !== 'TypedDict' && !x.includes('=')),+ ]),+ );+ let rooted = new Set(blocks.filter(([, , b]) => /(^|\W)TypedDict(\W|$)/.test(b)).map(([, n]) => n));+ let grew = true;+ while (grew) {+ grew = false;+ for (const name of Object.keys(basesOf)) {+ if (rooted.has(name)) continue;+ if (basesOf[name].some(b => rooted.has(b))) {+ rooted.add(name);+ grew = true;+ }+ }+ }+ for (const [, name, bases, body] of blocks) {+ if (!rooted.has(name)) continue;+ if (/total=False/.test(bases)) optionalAll.add(name);+ if (basesOf[name].length) parents[name] = basesOf[name];+ dicts[name] = parsePythonMembers(body);+ }++ const aliases = {};+ for (const [, name, rhs] of source.matchAll(/^([A-Z]\w+) = (.+)$/gm)) aliases[name] = rhs.trim();+ const resolve = (name, depth = 0) => {+ if (depth >= 4) return 'object';+ if (dicts[name]) return pythonObjectToken(dicts[name], resolve, depth);+ if (aliases[name] !== undefined) return pythonToken(aliases[name], resolve, depth);+ return name;+ };+ const merged = {};+ for (const name of Object.keys(dicts)) {+ merged[name] = {};+ for (const base of parents[name] ?? []) Object.assign(merged[name], dicts[base] ?? {});+ Object.assign(merged[name], dicts[name]);+ }+ // total=False marks the class's OWN members optional; inherited members keep the parent's flag.+ for (const [name, members] of Object.entries(merged)) {+ for (const [field, info] of Object.entries(members)) {+ if (dicts[name] && dicts[name][field] && dicts[name][field].__py) {+ if (optionalAll.has(name)) info.optional = true;+ info.token = pythonToken(info.token, resolve);+ }+ }+ }+ return merged;+}++function parsePythonMembers(body) {+ const members = {};+ let inDoc = false;+ for (const rawLine of body.split('\n')) {+ const t = rawLine.trim();+ const quotes = (rawLine.match(/"""/g) ?? []).length;+ if (quotes >= 2 && !inDoc) continue; // one-line docstring+ if (quotes === 1) {+ inDoc = !inDoc;+ continue;+ }+ if (inDoc || !t || t.startsWith('#')) continue;+ const m = t.match(/^(\w+)\s*:\s*(.+)$/);+ if (!m) continue;+ let optional = false;+ let typeText = m[2];+ const notReq = typeText.match(/^NotRequired\[(.+)\]$/s);+ if (notReq) {+ optional = true;+ typeText = notReq[1];+ }+ members[m[1]] = { optional, token: typeText.replace(/,$/, '').trim(), __py: true };+ }+ return members;+}++function pythonObjectToken(members, resolve, depth) {+ const parts = [];+ for (const [f, v] of Object.entries(members)) {+ parts.push(`${f}${v.optional ? '?' : ''}:${pythonToken(v.token, resolve, depth + 1)}`);+ }+ return `object(${parts.sort().join(',')})`;+}++function pythonToken(text, resolve, depth = 0) {+ let t = text.trim();+ if (t.endsWith(',')) t = t.slice(0, -1).trim();+ if (depth >= 4) return 'object';+ let nullable = false;+ if (/\|\s*None$/.test(t) || /^Optional\[/.test(t)) {+ nullable = true;+ t = t+ .replace(/^Optional\[/, '')+ .replace(/\s*\|\s*None$/, '')+ .replace(/\]$/, '')+ .trim();+ }+ const base = (() => {+ if (t === 'str') return 'string';+ if (t === 'int' || t === 'float') return 'number';+ if (t === 'bool') return 'boolean';+ if (t === 'Any') return 'any';+ const lit = t.match(/^Literal\[(.+)\]$/s);+ if (lit) {+ const vals = [...lit[1].matchAll(/["']([^"']+)["']/g)].map(m => m[1]);+ if (vals.length) return `enum(${vals.slice().sort().join(',')})`;+ }+ const lst = t.match(/^(?:List|list)\[(.+)\]$/s);+ if (lst) return `array<${pythonToken(lst[1], resolve, depth + 1)}>`;+ if (/^(?:Dict|dict)\[/.test(t)) return 'dict';+ if (/^(?:Union|union)\[/.test(t)) {+ const inner = t.slice(t.indexOf('[') + 1, -1);+ const parts = inner+ .split(',')+ .map(x => pythonToken(x, resolve, depth + 1))+ .sort();+ return `union(${parts.join(',')})`;+ }+ if (/^[A-Z]\w*$/.test(t)) return resolve ? resolve(t, depth) : t;+ return t;+ })();+ return nullable ? `${base}|null` : base;+}++/**+ * Go (sdk/go/types_*.go): struct fields with json tags — pointer/omitempty/slice ⇒ optional,+ * pointer ⇒ token|null; scalar defined types resolve to their underlying kind, and const blocks+ * grouped per defined type produce enum tokens.+ */+export function parseGoTypes(sources) {+ const structs = {};+ const scalarAliases = {};+ const constGroups = {};+ const kindMap = { string: 'string', int: 'number', int64: 'number', float64: 'number', bool: 'boolean', any: 'any' };++ for (const source of sources) {+ for (const [, name, underlying] of source.matchAll(/^type (\w+) (string|int|int64|float64|bool|any)$/gm)) {+ scalarAliases[name] = kindMap[underlying];+ }+ for (const block of source.matchAll(/type (\w+) struct \{([\s\S]*?)\n\}/g)) {+ const members = {};+ for (const line of block[2].split('\n')) {+ const m = line.match(/^\s*[A-Z]\w*\s+([\w[\]*.]+)\s+`json:"([^"]+)"`/);+ if (!m) continue;+ const json = m[2].split(',');+ const field = json[0];+ if (!field || field === '-') continue;+ const fullType = m[1];+ const omitempty = json.includes('omitempty');+ const ptr = fullType.startsWith('*');+ // omitempty is what drops a key on the wire — THAT is optionality. A bare pointer (no+ // omitempty) serializes null: a REQUIRED nullable field, not an optional one. A bare+ // []T is a required array (slices are nil-able in Go but not absent on the wire).+ members[field] = { optional: omitempty, token: '', __struct: fullType, __ptr: ptr, __omit: omitempty };+ }+ structs[block[1]] = members;+ }+ for (const cblock of source.matchAll(/const \(([\s\S]*?)\n\)/g)) {+ for (const line of cblock[1].split('\n')) {+ // gofmt pads name/type with multiple spaces — \s+ on both sides of the type.+ const m = line.match(/^\s*\w+\s+(\w+)\s+=\s+["']([^"']+)["']/);+ if (m) (constGroups[m[1]] ??= []).push(m[2]);+ }+ }+ }++ // defined scalar types whose consts exist become enums+ for (const [tname, vals] of Object.entries(constGroups)) {+ if (scalarAliases[tname]) scalarAliases[tname] = `enum(${[...new Set(vals)].sort().join(',')})`;+ }++ const expand = (typeText, depth = 0) => {+ if (depth >= 4) return 'object';+ if (typeText.startsWith('map[')) return 'dict';+ if (typeText.startsWith('[]')) return `array<${expand(typeText.slice(2), depth + 1)}>`;+ if (typeText.startsWith('*')) return `${expand(typeText.slice(1), depth + 1)}|null`;+ if (structs[typeText]) {+ const parts = Object.entries(structs[typeText]).map(([f, v]) => `${f}${v.optional ? '?' : ''}:${v.token}`);+ return `object(${parts.sort().join(',')})`;+ }+ return scalarAliases[typeText] ?? kindMap[typeText] ?? typeText;+ };++ for (const members of Object.values(structs)) {+ for (const v of Object.values(members)) {+ v.token = expand(v.__struct);+ // pointer+omitempty is "absent-dominant": JSON null and a missing key are indistinguishable+ // through *T with omitempty, so the null arm is dropped and the field flagged absorbsNull —+ // a nil *T covers both an absent key and an explicit null, so it also conforms to an+ // optional-nullable contract, which Go cannot spell distinctly.+ if (v.__ptr && v.__omit) {+ v.token = v.token.replace(/\|null$/, '');+ v.absorbsNull = true;+ }+ }+ }+ return structs;+}++/**+ * Java (sdk/java/.../model/*.java): record components — the object model cannot express+ * requiredness (every reference is nullable), so these pairs compare presence + type tokens only+ * (the client config sets compareOptionality=false).+ */+export function parseJavaTypes(sources) {+ const records = {};+ const primMap = {+ String: 'string',+ int: 'number',+ long: 'number',+ double: 'number',+ float: 'number',+ boolean: 'boolean',+ Integer: 'number',+ Long: 'number',+ Boolean: 'boolean',+ JsonObject: 'any',+ Object: 'any',+ BigDecimal: 'number',+ Instant: 'string',+ LocalDate: 'string',+ };+ for (const raw of sources) {+ // Javadoc BETWEEN record components breaks comma-splitting — strip comments first.+ const source = raw.replace(/\/\*[\s\S]*?\*\//g, '');+ for (const m of source.matchAll(/record (\w+)\(([^)]*)\)/g)) {+ const members = {};+ for (const comp of m[2].split(',')) {+ const cm = comp.trim().match(/^(?:final\s+)?([\w<>,.\[\]\s]+?)\s+(\w+)$/);+ if (!cm) continue;+ members[cm[2]] = { optional: true, token: cm[1].trim(), __java: cm[1].trim() };+ }+ records[m[1]] = members;+ }+ }+ const expand = (t, depth = 0) => {+ if (depth >= 4) return 'object';+ const lst = t.match(/^List<(.+)>$/);+ if (lst) return `array<${expand(lst[1], depth + 1)}>`;+ if (/^Map</.test(t)) return 'dict';+ if (primMap[t]) return primMap[t];+ const short = t.split('.').pop();+ if (records[short]) {+ const parts = Object.entries(records[short]).map(([f, v]) => `${f}:${expand(v.__java, depth + 1)}`);+ return `object(${parts.sort().join(',')})`;+ }+ return t;+ };+ for (const members of Object.values(records)) {+ for (const v of Object.values(members)) v.token = expand(v.__java);+ }+ return records;+}+// ── 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;++ /**+ * Five HTTP clients, one gate. The two TypeScript trees parse with parseHandTypes; Python, Go+ * and Java each get the parser for their declaration style. PHP is deliberately absent: its+ * client returns untyped array<string,mixed> throughout — there is no types layer to conform+ * (the same reason check-sdk-events exempts it).+ *+ * Java sets compareOptionality=false: record components cannot express requiredness (every+ * reference is nullable), so those pairs verify field presence and type tokens only.+ */+ const goSources = () =>+ readdirSync('sdk/go')+ .filter(f => f.endsWith('.go') && !f.endsWith('_test.go'))+ .map(f => readFileSync(`sdk/go/${f}`, 'utf8'));+ const javaSources = () =>+ readdirSync('sdk/java/src/main/java/com/rmyndharis/openwa/model')+ .filter(f => f.endsWith('.java'))+ .map(f => readFileSync(`sdk/java/src/main/java/com/rmyndharis/openwa/model/${f}`, 'utf8'));++ const CLIENTS = [+ ...Object.entries(MAPPINGS).map(([file, mapping]) => ({+ label: file,+ load: () => parseHandTypes(readFileSync(file, 'utf8')),+ mapping,+ excluded: EXCLUDED[file] ?? {},+ floor: MINIMUM_MAPPED[file],+ compareOptionality: true,+ })),+ {+ label: 'sdk/python/openwa/types.py',+ load: () => parsePythonTypes(readFileSync('sdk/python/openwa/types.py', 'utf8')),+ mapping: PYTHON_MAPPING,+ excluded: EXCLUDED['sdk/python/openwa/types.py'] ?? {},+ floor: MINIMUM_MAPPED['sdk/python/openwa/types.py'],+ compareOptionality: true,+ },+ {+ label: 'sdk/go (types_*.go)',+ load: () => parseGoTypes(goSources()),+ mapping: GO_MAPPING,+ excluded: EXCLUDED['sdk/go'] ?? {},+ floor: MINIMUM_MAPPED['sdk/go'],+ compareOptionality: true,+ },+ {+ label: 'sdk/java (model/*.java)',+ load: () => parseJavaTypes(javaSources()),+ mapping: JAVA_MAPPING,+ excluded: EXCLUDED['sdk/java'] ?? {},+ floor: MINIMUM_MAPPED['sdk/java'],+ compareOptionality: false,+ },+ ];+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] ?? {};+ for (const client of CLIENTS) {+ const handTypes = client.load();let fileCompared = 0;const fileResults = [];- for (const [handName, schemaName] of Object.entries(mapping)) {- if (excluded[handName]) continue;+ for (const [handName, schemaName] of Object.entries(client.mapping)) {+ if (client.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})`);+ fileResults.push(` MISSING hand type ${handName} (declared in mapping but not found in ${client.label})`);failures++;continue;}@@ -334,26 +772,26 @@ if (isDirectRun) {}fileCompared++;compared++;- const diffs = comparePair(handName, hand, schemaName, schema, schemas);+ const diffs = comparePair(handName, hand, schemaName, schema, schemas, client.compareOptionality);if (diffs.length) {fileResults.push(` ${handName} ↔ ${schemaName}:`, ...diffs.map(d => ` ${d}`));failures++;}}- if (Object.keys(mapping).length < MINIMUM_MAPPED[file]) {+ if (Object.keys(client.mapping).length < client.floor) {fileResults.push(- ` only ${Object.keys(mapping).length} mapped pairs for ${file} (floor ${MINIMUM_MAPPED[file]}) — entries were dropped`,+ ` only ${Object.keys(client.mapping).length} mapped pairs for ${client.label} (floor ${client.floor}) — entries were dropped`,);failures++;}if (fileCompared < 8) {- fileResults.push(` only ${fileCompared} pairs compared for ${file} — vacuous-pass guard`);+ fileResults.push(` only ${fileCompared} pairs compared for ${client.label} — vacuous-pass guard`);failures++;}- console.log(`${file}: ${fileCompared} pairs compared, ${fileResults.length ? 'FAILURES' : 'all conform'}`);+ console.log(`${client.label}: ${fileCompared} pairs compared, ${fileResults.length ? 'FAILURES' : 'all conform'}`);for (const line of fileResults) console.log(line);- const excludedCount = Object.keys(excluded).length;+ const excludedCount = Object.keys(client.excluded).length;if (excludedCount) {console.log(` (${excludedCount} excluded pair(s) with recorded reasons — see EXCLUDED in this script)`);}diff --git a/scripts/check-contract-shapes.spec.mjs b/scripts/check-contract-shapes.spec.mjsindex 014391d62..7eb13ffac 100644--- a/scripts/check-contract-shapes.spec.mjs+++ b/scripts/check-contract-shapes.spec.mjs@@ -10,7 +10,16 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { parseHandTypes, parseObjectToken, schemaToken, comparePair, handToken } from './check-contract-shapes.mjs';+import {+ comparePair,+ handToken,+ parseGoTypes,+ parseHandTypes,+ parseJavaTypes,+ parseObjectToken,+ parsePythonTypes,+ schemaToken,+} from './check-contract-shapes.mjs';const handSource = `export interface Sample {@@ -125,3 +134,60 @@ export interface Child extends Base {`);assert.deepEqual(Object.keys(types.Child), ['id', 'apiKey']);});++test('parsePythonTypes: TypedDict totals, NotRequired, aliased Literal enums, inheritance', () => {+ const src = [+ 'SessionStatus = Literal[',+ ' "created",',+ ' "ready",',+ ']',+ '',+ 'class Base(TypedDict, total=False):',+ ' id: str',+ '',+ 'class Session(Base):',+ ' name: str',+ ' status: SessionStatus',+ ' lastError: NotRequired[str | None]',+ ].join('\n');+ const types = parsePythonTypes(src);+ assert.equal(types.Session.id.optional, true, 'inherited total=False member stays optional');+ assert.equal(types.Session.name.optional, false);+ assert.equal(types.Session.status.token, 'enum(created,ready)');+ assert.equal(types.Session.lastError.optional, true);+ assert.equal(types.Session.lastError.token, 'string|null');+});++test('parseGoTypes: omitempty optionality, pointer nullability, const-block enums, required slices', () => {+ const src = [+ 'type Kind string',+ '',+ 'const (',+ '\tKindOne Kind = "one"',+ '\tKindTwo Kind = "two"',+ ')',+ '',+ 'type Sample struct {',+ '\tName string `json:"name,omitempty"`',+ '\tKind Kind `json:"kind"`',+ '\tItems []string `json:"items"`',+ '\tManaged *string `json:"managed"`',+ '}',+ ].join('\n');+ // Member maps key by JSON tag (the wire name), not the Go identifier.+ const s = parseGoTypes([src]).Sample;+ assert.equal(s.name.optional, true);+ assert.equal(s.kind.token, 'enum(one,two)');+ assert.equal(s.kind.optional, false);+ assert.equal(s.items.token, 'array<string>');+ assert.equal(s.items.optional, false, 'bare slice is a REQUIRED array');+ assert.equal(s.managed.optional, false, 'pointer without omitempty is required-nullable');+ assert.equal(s.managed.token, 'string|null');+});++test('parseJavaTypes: javadoc between components must not drop fields', () => {+ const src = 'public record Sample(\n String id,\n /** documented */\n Long count) {}\n';+ const types = parseJavaTypes([src]);+ assert.deepEqual(Object.keys(types.Sample), ['id', 'count']);+ assert.equal(types.Sample.count.token, 'number');+});diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.goindex e62b25c72..69bc3767f 100644--- a/sdk/go/types_chat.go+++ b/sdk/go/types_chat.go@@ -4,13 +4,13 @@ import "net/url"// ChatSummary is a chat-list entry.type ChatSummary struct {- ID string `json:"id"`- Name *string `json:"name,omitempty"`- IsGroup bool `json:"isGroup"`- UnreadCount int `json:"unreadCount"`- LastMessage string `json:"lastMessage,omitempty"`- Timestamp any `json:"timestamp,omitempty"`- Kind string `json:"kind"`+ ID string `json:"id"`+ Name string `json:"name"`+ IsGroup bool `json:"isGroup"`+ UnreadCount int `json:"unreadCount"`+ LastMessage string `json:"lastMessage,omitempty"`+ Timestamp int64 `json:"timestamp"`+ Kind ChatKind `json:"kind"`}// SetOwnPresenceRequest is the body for SessionsService.SetOnlinePresence. Available reportsdiff --git a/sdk/go/types_contact.go b/sdk/go/types_contact.goindex aab7b23ba..dfd8cacb6 100644--- a/sdk/go/types_contact.go+++ b/sdk/go/types_contact.go@@ -26,7 +26,7 @@ type CheckNumberResponse struct {// ProfilePictureResponse carries a contact's profile picture URL.type ProfilePictureResponse struct {- URL *string `json:"url,omitempty"`+ URL *string `json:"url"`}// ProfilePicturesResponse is a batch profile-picture lookup: a map of contactdiff --git a/sdk/go/types_group.go b/sdk/go/types_group.goindex 7218383c2..8429708b2 100644--- a/sdk/go/types_group.go+++ b/sdk/go/types_group.go@@ -5,10 +5,10 @@ import "net/url"// GroupParticipant is a group member.type GroupParticipant struct {ID string `json:"id"`- Number string `json:"number,omitempty"`+ Number string `json:"number"`Name string `json:"name,omitempty"`- IsAdmin bool `json:"isAdmin,omitempty"`- IsSuperAdmin bool `json:"isSuperAdmin,omitempty"`+ IsAdmin bool `json:"isAdmin"`+ IsSuperAdmin bool `json:"isSuperAdmin"`}// GroupSummary is the slim group shape from the list endpoint. Note that@@ -49,16 +49,31 @@ type MembershipRequestActionRequest struct {}// GroupInfo is the full group detail.+// MemberAddMode is who may add participants to a group.+type MemberAddMode string++const (+ MemberAddAll MemberAddMode = "all"+ MemberAddAdmins MemberAddMode = "admins"+)+type GroupInfo struct {- ID string `json:"id"`- Name string `json:"name"`- Description *string `json:"description,omitempty"`- Owner *string `json:"owner,omitempty"`- CreatedAt int64 `json:"createdAt,omitempty"`- Participants []GroupParticipant `json:"participants,omitempty"`- IsReadOnly bool `json:"isReadOnly,omitempty"`- IsAnnounce bool `json:"isAnnounce,omitempty"`- LinkedParentJID *string `json:"linkedParentJID,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Owner string `json:"owner,omitempty"`+ CreatedAt int64 `json:"createdAt,omitempty"`+ Participants []GroupParticipant `json:"participants"`+ // Announce: only admins may send. Locked: only admins may edit info. EphemeralSeconds:+ // disappearing-message timer (0/absent = off). Optional non-null scalars stay pointers — Go+ // cannot omit a false/0 non-pointer without dropping the zero value itself.+ Announce *bool `json:"announce,omitempty"`+ EphemeralSeconds *int `json:"ephemeralSeconds,omitempty"`+ Locked *bool `json:"locked,omitempty"`+ MemberAddMode *MemberAddMode `json:"memberAddMode,omitempty"`+ IsReadOnly bool `json:"isReadOnly,omitempty"`+ IsAnnounce bool `json:"isAnnounce,omitempty"`+ LinkedParentJID *string `json:"linkedParentJID,omitempty"`}// CreateGroupRequest creates a group with initial participants.diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex dbdbfec82..ff79c120d 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -234,13 +234,13 @@ type ChatHistoryMessage struct {From string `json:"from"`To string `json:"to"`ChatID string `json:"chatId"`- Body string `json:"body,omitempty"`- Type string `json:"type"`+ Body string `json:"body"`+ Type MessageType `json:"type"`Timestamp int64 `json:"timestamp"`FromMe bool `json:"fromMe"`IsGroup bool `json:"isGroup"`- IsStatusBroadcast bool `json:"isStatusBroadcast"`- Kind string `json:"kind"`+ IsStatusBroadcast bool `json:"isStatusBroadcast,omitempty"`+ Kind ChatKind `json:"kind"`EphemeralDuration int `json:"ephemeralDuration,omitempty"`Author string `json:"author,omitempty"`MentionedIDs []string `json:"mentionedIds,omitempty"`@@ -326,7 +326,7 @@ type BulkMessageContent struct {// video, audio, document.type BulkMessageItem struct {ChatID string `json:"chatId"`- Type string `json:"type"`+ Type BulkMessageType `json:"type"`Content BulkMessageContent `json:"content"`Variables map[string]string `json:"variables,omitempty"`}@@ -350,7 +350,7 @@ type BulkMessageResponse struct {BatchID string `json:"batchId"`Status string `json:"status"`TotalMessages int `json:"totalMessages"`- EstimatedCompletionTime string `json:"estimatedCompletionTime"`+ EstimatedCompletionTime string `json:"estimatedCompletionTime,omitempty"`StatusURL string `json:"statusUrl"`}@@ -360,13 +360,85 @@ type BatchError struct {Message string `json:"message,omitempty"`}+// BatchMessageStatus is one recipient's send outcome inside a batch.+type BatchMessageStatus string++const (+ BatchPending BatchMessageStatus = "pending"+ BatchSent BatchMessageStatus = "sent"+ BatchFailed BatchMessageStatus = "failed"+ BatchCancelled BatchMessageStatus = "cancelled"+)++// BatchLifecycleStatus is the lifecycle of a whole batch.+type BatchLifecycleStatus string++const (+ BatchLifecyclePending BatchLifecycleStatus = "pending"+ BatchLifecycleProcessing BatchLifecycleStatus = "processing"+ BatchLifecycleCompleted BatchLifecycleStatus = "completed"+ BatchLifecycleFailed BatchLifecycleStatus = "failed"+ BatchLifecycleCancelled BatchLifecycleStatus = "cancelled"+)++// MessageType is the engine-normalized message kind.+type MessageType string++const (+ MsgText MessageType = "text"+ MsgImage MessageType = "image"+ MsgVideo MessageType = "video"+ MsgAudio MessageType = "audio"+ MsgVoice MessageType = "voice"+ MsgDocument MessageType = "document"+ MsgSticker MessageType = "sticker"+ MsgLocation MessageType = "location"+ MsgContact MessageType = "contact"+ MsgPoll MessageType = "poll"+ MsgCall MessageType = "call"+ MsgRevoked MessageType = "revoked"+ MsgMasked MessageType = "masked"+ MsgUnknown MessageType = "unknown"+)++// BulkMessageType is the media kind a bulk item may carry.+type BulkMessageType string++const (+ BulkText BulkMessageType = "text"+ BulkImage BulkMessageType = "image"+ BulkVideo BulkMessageType = "video"+ BulkAudio BulkMessageType = "audio"+ BulkDocument BulkMessageType = "document"+)++// ChatKind is the conversation kind a chat/message belongs to.+type ChatKind string++const (+ KindIndividual ChatKind = "individual"+ KindGroup ChatKind = "group"+ KindChannel ChatKind = "channel"+ KindStatus ChatKind = "status"+ KindBroadcast ChatKind = "broadcast"+ KindUnknown ChatKind = "unknown"+)++// MessageDirection is which way a search hit traveled.+type MessageDirection string++const (+ DirectionIncoming MessageDirection = "incoming"+ DirectionOutgoing MessageDirection = "outgoing"+)+// BatchMessageResult is one message's outcome within a batch.type BatchMessageResult struct {- ChatID string `json:"chatId"`- Status string `json:"status"`- MessageID string `json:"messageId,omitempty"`- SentAt string `json:"sentAt,omitempty"`- Error *BatchError `json:"error,omitempty"`+ ChatID string `json:"chatId"`+ Status BatchMessageStatus `json:"status"`+ MessageID string `json:"messageId,omitempty"`+ SentAt string `json:"sentAt,omitempty"`+ Error *BatchError `json:"error,omitempty"`}// BatchProgress is the aggregate progress of a batch.@@ -381,11 +453,11 @@ type BatchProgress struct {// BatchStatusResponse is the response from the batch status / cancel endpoints.type BatchStatusResponse struct {BatchID string `json:"batchId"`- Status string `json:"status"`+ Status BatchLifecycleStatus `json:"status"`Progress BatchProgress `json:"progress"`- Results []BatchMessageResult `json:"results,omitempty"`- StartedAt string `json:"startedAt,omitempty"`- CompletedAt string `json:"completedAt,omitempty"`+ Results []BatchMessageResult `json:"results"`+ StartedAt *string `json:"startedAt,omitempty"`+ CompletedAt *string `json:"completedAt,omitempty"`}// MessageMedia is a message's stored media: the raw bytes plus the serveddiff --git a/sdk/go/types_search.go b/sdk/go/types_search.goindex 496f48eb1..ddc4628c8 100644--- a/sdk/go/types_search.go+++ b/sdk/go/types_search.go@@ -34,17 +34,17 @@ func (q *SearchQuery) values() url.Values {// SearchHit is one search result.type SearchHit struct {- MessageID string `json:"messageId"`- WaMessageID string `json:"waMessageId"`- SessionID string `json:"sessionId"`- ChatID string `json:"chatId"`- Body string `json:"body"`- Snippet string `json:"snippet"`- Timestamp int64 `json:"timestamp"`- Type string `json:"type"`- Direction string `json:"direction"`- From string `json:"from"`- Score float64 `json:"score,omitempty"`+ MessageID string `json:"messageId"`+ WaMessageID string `json:"waMessageId"`+ SessionID string `json:"sessionId"`+ ChatID string `json:"chatId"`+ Body string `json:"body"`+ Snippet string `json:"snippet"`+ Timestamp int64 `json:"timestamp"`+ Type string `json:"type"`+ Direction MessageDirection `json:"direction"`+ From string `json:"from"`+ Score float64 `json:"score,omitempty"`}// SearchResults is the GET /search payload.diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goindex 780d12049..44565b68d 100644--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -73,11 +73,45 @@ type UpsertLabelRequest struct {}// ParticipantPresence is one participant's presence within a chat.+// SessionStatus is the session lifecycle state reported by the gateway.+type SessionStatus string++const (+ SessionStatusCreated SessionStatus = "created"+ SessionStatusInitializing SessionStatus = "initializing"+ SessionStatusQrReady SessionStatus = "qr_ready"+ SessionStatusAuthenticating SessionStatus = "authenticating"+ SessionStatusReady SessionStatus = "ready"+ SessionStatusDisconnected SessionStatus = "disconnected"+ SessionStatusActionRequired SessionStatus = "action_required"+ SessionStatusFailed SessionStatus = "failed"+)++// AccountRestrictionKind is the class of a WhatsApp-side account restriction.+type AccountRestrictionKind string++const (+ RestrictionReachoutTimelock AccountRestrictionKind = "reachout_timelock"+ RestrictionTosBlock AccountRestrictionKind = "tos_block"+ RestrictionProxyBlock AccountRestrictionKind = "proxy_block"+)++// PresenceState is a subscribed contact's presence.+type PresenceState string++const (+ PresenceAvailable PresenceState = "available"+ PresenceUnavailable PresenceState = "unavailable"+ PresenceComposing PresenceState = "composing"+ PresenceRecording PresenceState = "recording"+ PresencePaused PresenceState = "paused"+)+type ParticipantPresence struct {ID string `json:"id"`// State is one of: available, unavailable, composing, recording, paused. "composing" and// "recording" mean actively typing or recording; "paused" means they stopped.- State string `json:"state"`+ State PresenceState `json:"state"`// LastSeen is Unix SECONDS. Nil whenever the contact's privacy settings hide last-seen — the// common case, not an error.LastSeen *int64 `json:"lastSeen,omitempty"`@@ -100,7 +134,7 @@ type ChatPresence struct {// therefore cannot coexist with a "ready" status.type AccountRestriction struct {// Kind is one of: reachout_timelock, tos_block, proxy_block.- Kind string `json:"kind"`+ Kind AccountRestrictionKind `json:"kind"`// Code is the engine's own token for the cause, verbatim (TOS_BLOCK, BIZ_QUALITY, ...).Code string `json:"code"`// ExpiresAt is an ISO timestamp for the end of enforcement, when WhatsApp states one.@@ -111,16 +145,16 @@ type AccountRestriction struct {// initializing, qr_ready, authenticating, ready, disconnected, action_required,// failed.type SessionResponse struct {- ID string `json:"id"`- Name string `json:"name"`- Status string `json:"status"`- Phone *string `json:"phone,omitempty"`- PushName *string `json:"pushName,omitempty"`- ConnectedAt *string `json:"connectedAt,omitempty"`- LastActive *string `json:"lastActive,omitempty"`- CreatedAt string `json:"createdAt,omitempty"`- UpdatedAt string `json:"updatedAt,omitempty"`- LastError *string `json:"lastError,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Status SessionStatus `json:"status"`+ Phone *string `json:"phone,omitempty"`+ PushName *string `json:"pushName,omitempty"`+ ConnectedAt *string `json:"connectedAt,omitempty"`+ LastActive *string `json:"lastActive,omitempty"`+ CreatedAt string `json:"createdAt"`+ UpdatedAt string `json:"updatedAt"`+ LastError *string `json:"lastError,omitempty"`// Restriction reports a limit WhatsApp itself has placed on the account, or nil when there is// none. Distinct from LastError, which describes a fault on the gateway's side.Restriction *AccountRestriction `json:"restriction,omitempty"`@@ -128,7 +162,7 @@ type SessionResponse struct {// precondition stop/logout/force-kill require and start refuses. Not derivable from Status:// "disconnected" covers both a session mid automatic-reconnect (engine present) and one stopped// with no engine. Nil from a gateway that predates the field.- EngineLoaded *bool `json:"engineLoaded,omitempty"`+ EngineLoaded bool `json:"engineLoaded"`}// CreateSessionRequest is the body for creating a session. ProxyType is one of:@@ -142,8 +176,8 @@ type CreateSessionRequest struct {// QrCodeResponse carries the current QR code for a session awaiting scan.type QrCodeResponse struct {- QrCode string `json:"qrCode"`- Status string `json:"status"`+ QrCode string `json:"qrCode"`+ Status SessionStatus `json:"status"`}// PairingCodeResponse carries a phone-pairing code.diff --git a/sdk/go/types_status.go b/sdk/go/types_status.goindex 79e81a3a9..f9b964aac 100644--- a/sdk/go/types_status.go+++ b/sdk/go/types_status.go@@ -20,8 +20,8 @@ type StatusRecord struct {Font *int `json:"font,omitempty"`// The server types these as Date, which serializes to RFC 3339, so// time.Time decodes them directly. Zero when the server omits the field.- Timestamp time.Time `json:"timestamp,omitempty"`- ExpiresAt time.Time `json:"expiresAt,omitempty"`+ Timestamp time.Time `json:"timestamp"`+ ExpiresAt time.Time `json:"expiresAt"`}// StatusListResponse is the {"statuses": [...]} envelope returned by GET@@ -35,8 +35,8 @@ type StatusListResponse struct {// timing, no contact/media.type StatusResult struct {StatusID string `json:"statusId"`- Timestamp time.Time `json:"timestamp,omitempty"`- ExpiresAt time.Time `json:"expiresAt,omitempty"`+ Timestamp time.Time `json:"timestamp"`+ ExpiresAt time.Time `json:"expiresAt"`}// StatusMedia is the one non-JSON shape on the wire: the raw bytes of a storeddiff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.goindex 991d4e429..944513f6b 100644--- a/sdk/go/types_webhook.go+++ b/sdk/go/types_webhook.go@@ -147,7 +147,7 @@ type WebhookResponse struct {Events []string `json:"events"`Active bool `json:"active"`Filters *WebhookFilters `json:"filters,omitempty"`- RetryCount int `json:"retryCount,omitempty"`+ RetryCount int `json:"retryCount"`LastTriggeredAt *string `json:"lastTriggeredAt,omitempty"`CreatedAt string `json:"createdAt"`UpdatedAt string `json:"updatedAt"`diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.javaindex 685e0586b..e493e3797 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java@@ -11,4 +11,4 @@ package com.rmyndharis.openwa.model;* @param code the engine's own token for the cause, verbatim ({@code TOS_BLOCK}, {@code BIZ_QUALITY}, …)* @param expiresAt ISO timestamp for the end of enforcement, when WhatsApp states one*/-public record AccountRestriction(String kind, String code, String expiresAt) {}+public record AccountRestriction(AccountRestrictionKind kind, String code, String expiresAt) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestrictionKind.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestrictionKind.javanew file mode 100644index 000000000..5e878f401--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestrictionKind.java@@ -0,0 +1,10 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** Class of a WhatsApp-side account restriction. */+public enum AccountRestrictionKind {+ @SerializedName("reachout_timelock") REACHOUT_TIMELOCK,+ @SerializedName("tos_block") TOS_BLOCK,+ @SerializedName("proxy_block") PROXY_BLOCK+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchLifecycleStatus.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchLifecycleStatus.javanew file mode 100644index 000000000..9052d2601--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchLifecycleStatus.java@@ -0,0 +1,12 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** Lifecycle of a whole bulk-send batch. */+public enum BatchLifecycleStatus {+ @SerializedName("pending") PENDING,+ @SerializedName("processing") PROCESSING,+ @SerializedName("completed") COMPLETED,+ @SerializedName("failed") FAILED,+ @SerializedName("cancelled") CANCELLED+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageResult.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageResult.javaindex cf81d4517..e11a38189 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageResult.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageResult.java@@ -3,7 +3,7 @@ package com.rmyndharis.openwa.model;/** Per-message outcome within a batch result list. Optional fields are {@code null} when absent. */public record BatchMessageResult(String chatId,- String status,+ BatchMessageStatus status,String messageId,String sentAt,BatchError error) {diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageStatus.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageStatus.javanew file mode 100644index 000000000..dedf6a551--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchMessageStatus.java@@ -0,0 +1,11 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** One recipient's send outcome inside a batch. */+public enum BatchMessageStatus {+ @SerializedName("pending") PENDING,+ @SerializedName("sent") SENT,+ @SerializedName("failed") FAILED,+ @SerializedName("cancelled") CANCELLED+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchStatusResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchStatusResponse.javaindex 89b000a9a..e50123d4c 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchStatusResponse.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BatchStatusResponse.java@@ -9,7 +9,7 @@ import java.util.List;*/public record BatchStatusResponse(String batchId,- String status,+ BatchLifecycleStatus status,BatchProgress progress,List<BatchMessageResult> results,String startedAt,diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.javaindex 4820f6763..c98c5acc4 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java@@ -13,13 +13,13 @@ public record ChatHistoryMessage(String to,String chatId,String body,- String type,+ MessageType type,/** Unix timestamp in seconds. */long timestamp,boolean fromMe,boolean isGroup,Boolean isStatusBroadcast,- String kind,+ ChatKind kind,/** Disappearing-messages timer on the chat, in seconds; {@code null} when the chat has none. */Integer ephemeralDuration,/** For group messages, the participant who sent it ({@code from} is the group JID). */diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatKind.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatKind.javanew file mode 100644index 000000000..253ed908e--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatKind.java@@ -0,0 +1,13 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** The conversation kind a chat or message belongs to. */+public enum ChatKind {+ @SerializedName("individual") INDIVIDUAL,+ @SerializedName("group") GROUP,+ @SerializedName("channel") CHANNEL,+ @SerializedName("status") STATUS,+ @SerializedName("broadcast") BROADCAST,+ @SerializedName("unknown") UNKNOWN+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.javaindex c2aec5b94..9b79436ba 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatSummary.java@@ -13,5 +13,5 @@ public record ChatSummary(Integer unreadCount,/** Preview text of the last message (the server returns a plain string, not an object). */String lastMessage,- Object timestamp,- String kind) {}+ Long timestamp,+ ChatKind kind) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupInfo.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupInfo.javaindex b1ee17530..3997acc96 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupInfo.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupInfo.java@@ -11,6 +11,10 @@ public record GroupInfo(/** Unix timestamp in seconds. */Long createdAt,List<GroupParticipant> participants,+ Boolean announce,+ Long ephemeralSeconds,+ Boolean locked,+ MemberAddMode memberAddMode,Boolean isReadOnly,Boolean isAnnounce,String linkedParentJID) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MemberAddMode.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MemberAddMode.javanew file mode 100644index 000000000..00c424368--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MemberAddMode.java@@ -0,0 +1,9 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** Who may add participants to a group. */+public enum MemberAddMode {+ @SerializedName("all") ALL,+ @SerializedName("admins") ADMINS+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.javanew file mode 100644index 000000000..f909b7a2c--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MessageType.java@@ -0,0 +1,21 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** The engine-normalized message kind. */+public enum MessageType {+ @SerializedName("text") TEXT,+ @SerializedName("image") IMAGE,+ @SerializedName("video") VIDEO,+ @SerializedName("audio") AUDIO,+ @SerializedName("voice") VOICE,+ @SerializedName("document") DOCUMENT,+ @SerializedName("sticker") STICKER,+ @SerializedName("location") LOCATION,+ @SerializedName("contact") CONTACT,+ @SerializedName("poll") POLL,+ @SerializedName("call") CALL,+ @SerializedName("revoked") REVOKED,+ @SerializedName("masked") MASKED,+ @SerializedName("unknown") UNKNOWN+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.javaindex 7ebee6a98..111db8f8b 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.java@@ -9,4 +9,4 @@ package com.rmyndharis.openwa.model;* @param lastSeen Unix SECONDS; {@code null} whenever the contact's privacy settings hide last-seen,* which is the common case and not an error*/-public record ParticipantPresence(String id, String state, Long lastSeen) {}+public record ParticipantPresence(String id, PresenceState state, Long lastSeen) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/PresenceState.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/PresenceState.javanew file mode 100644index 000000000..f5014a195--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/PresenceState.java@@ -0,0 +1,12 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/** A subscribed contact's presence. */+public enum PresenceState {+ @SerializedName("available") AVAILABLE,+ @SerializedName("unavailable") UNAVAILABLE,+ @SerializedName("composing") COMPOSING,+ @SerializedName("recording") RECORDING,+ @SerializedName("paused") PAUSED+}diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 97092962e..e6fd68b22 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -10,7 +10,13 @@ Field names mirror the backend DTOs exactly (camelCase JSON).from __future__ import annotations-from typing import Any, Literal, Optional, TypedDict+from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict++if TYPE_CHECKING:+ # Annotations are lazy (`from __future__ import annotations`), so NotRequired — which typing+ # only ships from 3.11 — is needed exclusively where type checkers look, never at runtime.+ # typing_extensions rides along with mypy; the runtime dependency set stays httpx-only.+ from typing_extensions import NotRequiredJid = strSessionStatus = Literal[@@ -27,6 +33,9 @@ ChatState = Literal["typing", "recording", "paused"]MessageDirection = Literal["incoming", "outgoing"]DeliveryStatus = Literal["pending", "sent", "delivered", "read", "failed"]BulkMessageType = Literal["text", "image", "video", "audio", "document"]+BatchMessageStatus = Literal["pending", "sent", "failed", "cancelled"]+BatchLifecycleStatus = Literal["pending", "processing", "completed", "failed", "cancelled"]+ChatKind = Literal["individual", "group", "channel", "status", "broadcast", "unknown"]WebhookEvent = Literal["message.received", "message.sent", "message.ack", "message.failed", "message.revoked","message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",@@ -107,14 +116,14 @@ class ParticipantsResult(SuccessResult):results: list[ParticipantResult]-class ParticipantPresence(TypedDict, total=False):+class ParticipantPresence(TypedDict):"""One participant's presence within a chat."""id: str# 'composing'/'recording' mean actively typing or recording; 'paused' means they stopped.state: Literal["available", "unavailable", "composing", "recording", "paused"]# Unix SECONDS. Absent whenever the contact's privacy settings hide last-seen -- the common case.- lastSeen: int+ lastSeen: NotRequired[int]class ChatPresence(TypedDict, total=False):@@ -152,7 +161,7 @@ class MuteChannelRequest(TypedDict):mute: bool-class GroupJoinInfo(TypedDict, total=False):+class GroupJoinInfo(TypedDict):"""What an invite code discloses about a group before joining.Not GroupInfo: a non-member has no participant list, only a count, and only when WhatsApp@@ -161,11 +170,11 @@ class GroupJoinInfo(TypedDict, total=False):id: strname: str- description: str- owner: str+ description: NotRequired[str]+ owner: NotRequired[str]# Unix seconds.- createdAt: int- participantCount: int+ createdAt: NotRequired[int]+ participantCount: NotRequired[int]class CustomLinkPreview(TypedDict, total=False):@@ -180,7 +189,7 @@ class CustomLinkPreview(TypedDict, total=False):# ── Session ───────────────────────────────────────────────────────-class AccountRestriction(TypedDict, total=False):+class AccountRestriction(TypedDict):"""A restriction WhatsApp has in force on a session's account.'reachout_timelock' leaves the session connected and existing chats working -- only starting new@@ -192,23 +201,23 @@ class AccountRestriction(TypedDict, total=False):# The engine's own token for the cause, verbatim (TOS_BLOCK, BIZ_QUALITY, ...).code: str# ISO timestamp when enforcement ends, when WhatsApp states one.- expiresAt: str | None+ expiresAt: NotRequired[str | None]-class SessionResponse(TypedDict, total=False):+class SessionResponse(TypedDict):id: strname: strstatus: SessionStatus- phone: str | None- pushName: str | None- connectedAt: str | None- lastActive: str | None+ phone: NotRequired[str | None]+ pushName: NotRequired[str | None]+ connectedAt: NotRequired[str | None]+ lastActive: NotRequired[str | None]createdAt: strupdatedAt: str- lastError: str | None+ lastError: NotRequired[str | None]# A limit WhatsApp itself has placed on the account, or None when there is none. Distinct from# lastError, which describes a fault on the gateway's side.- restriction: AccountRestriction | None+ restriction: NotRequired[AccountRestriction | None]# Whether the gateway holds a live engine for this session -- the precondition stop/logout/# force-kill require and start refuses. Not derivable from status: 'disconnected' covers both a# session mid automatic-reconnect (engine present) and one stopped with no engine. Absent from a@@ -558,12 +567,12 @@ class BulkMessageContent(TypedDict, total=False):caption: str-class BulkMessageItem(TypedDict, total=False):+class BulkMessageItem(TypedDict):# chatId/type/content required; variables optional.chatId: Jidtype: BulkMessageTypecontent: BulkMessageContent- variables: dict[str, str]+ variables: NotRequired[dict[str, str]]class BulkOptions(TypedDict, total=False):@@ -586,7 +595,7 @@ class BulkMessageResponse(TypedDict):batchId: strstatus: strtotalMessages: int- estimatedCompletionTime: str+ estimatedCompletionTime: NotRequired[str]statusUrl: str@@ -595,15 +604,15 @@ class BatchError(TypedDict, total=False):message: str-class BatchMessageResult(TypedDict, total=False):+class BatchMessageResult(TypedDict):chatId: Jid- status: str- messageId: str- sentAt: str- error: BatchError+ status: BatchMessageStatus+ messageId: NotRequired[str]+ sentAt: NotRequired[str]+ error: NotRequired[BatchError]-class BatchProgress(TypedDict, total=False):+class BatchProgress(TypedDict):total: intsent: intfailed: int@@ -611,18 +620,18 @@ class BatchProgress(TypedDict, total=False):cancelled: int-class BatchStatusResponse(TypedDict, total=False):+class BatchStatusResponse(TypedDict):"""Response from ``GET /messages/batch/:batchId`` and the cancel endpoint.Distinct from :class:`BulkMessageResponse` (the send-bulk acknowledgement)."""batchId: str- status: str+ status: BatchLifecycleStatusprogress: BatchProgressresults: list[BatchMessageResult]- startedAt: str- completedAt: str+ startedAt: NotRequired[str | None]+ completedAt: NotRequired[str | None]# ── Contact ───────────────────────────────────────────────────────@@ -668,22 +677,22 @@ class ContactPhoneResponse(TypedDict):# ── Group ─────────────────────────────────────────────────────────-class GroupParticipant(TypedDict, total=False):+class GroupParticipant(TypedDict):id: Jidnumber: str- name: str+ name: NotRequired[str]isAdmin: boolisSuperAdmin: bool-class GroupSummary(TypedDict, total=False):+class GroupSummary(TypedDict):"""Item returned by ``GET /sessions/:id/groups`` (the slim list shape)."""id: Jidname: str- participantsCount: int- isAdmin: bool- linkedParentJID: str | None+ participantsCount: NotRequired[int]+ isAdmin: NotRequired[bool]+ linkedParentJID: NotRequired[str | None]GroupMembershipRequestMethod = Literal["invite_link", "non_admin_add", "linked_group_join"]@@ -702,20 +711,24 @@ class GroupMembershipRequest(TypedDict, total=False):requestedAt: float-class GroupInfo(TypedDict, total=False):+class GroupInfo(TypedDict):"""Full detail returned by ``GET /sessions/:id/groups/:groupId``."""id: Jidname: str- description: str | None- owner: Jid | None- createdAt: int+ description: NotRequired[str]+ owner: NotRequired[Jid]+ createdAt: NotRequired[int]participants: list[GroupParticipant]- isReadOnly: bool- isAnnounce: bool- linkedParentJID: str | None+ isReadOnly: NotRequired[bool]+ isAnnounce: NotRequired[bool]+ linkedParentJID: NotRequired[str | None]+ announce: NotRequired[bool]+ ephemeralSeconds: NotRequired[int]+ locked: NotRequired[bool]+ memberAddMode: NotRequired[Literal["all", "admins"]]class CreateGroupRequest(TypedDict):name: strparticipants: list[Jid]@@ -803,16 +816,16 @@ class UpdateWebhookRequest(CreateWebhookRequest, total=False):active: bool-class WebhookResponse(TypedDict, total=False):+class WebhookResponse(TypedDict):id: strsessionId: strurl: strevents: list[WebhookEvent]active: bool- filters: WebhookFilters | None+ filters: NotRequired[WebhookFilters | None]retryCount: int# ISO timestamp of the last delivery attempt, or None if never triggered.- lastTriggeredAt: str | None+ lastTriggeredAt: NotRequired[str | None]createdAt: strupdatedAt: str# NOTE: the server deliberately omits ``secret`` and ``headers`` from reads.@@ -827,15 +840,15 @@ class WebhookTestResult(TypedDict, total=False):# ── Chat ──────────────────────────────────────────────────────────-class ChatSummary(TypedDict, total=False):+class ChatSummary(TypedDict):id: Jid- name: str | None+ name: strisGroup: boolunreadCount: int# Server returns a plain preview string, not a message object.- lastMessage: str+ lastMessage: NotRequired[str]timestamp: str | int- kind: str+ kind: ChatKindclass MarkChatRequest(TypedDict):@@ -881,7 +894,7 @@ class StatusRecord(TypedDict, total=False):# Result of a status POST (``send-text``/``send-image``/``send-video``/``send-voice``). Mirrors the backend# ``StatusResult``, which is deliberately NOT ``Status``: the acknowledgement carries the id and# timing only, with no contact or media. ``statusId`` is the handle ``delete()`` takes.-class StatusResult(TypedDict, total=False):+class StatusResult(TypedDict):statusId: str# ISO 8601 timestamp of the post.timestamp: str