Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): align typed record models with the payloads the server returns (#777)

Yudhi Armyndharisfc1975ab96af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39ad074a1..a537ffdd3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
reason to upgrade. No behavior change, and no change to which release carries the fix — it is still
v0.8.18. Refs #753, #757.
+- **Typed SDK response models now match the status, label, and channel payloads the server actually
+ returns.** The status, label, and channel routes hand back the engine-neutral shape from
+ `whatsapp-engine.interface.ts` verbatim — no DTO, no remap — but the record types the typed SDKs
+ declare for them were hand-written and never bound to that contract, so they advertised fields the
+ server never sends while omitting most of the ones it does. `StatusRecord` gains
+ `contact`/`caption`/`expiresAt` (plus the declared-but-not-yet-populated
+ `mediaUrl`/`backgroundColor`/`font`) and drops the never-sent `statusId`/`body`; `LabelRecord`
+ replaces `color`/`colorHex` with the real `hexColor`; `ChannelRecord` gains
+ `inviteCode`/`picture`/`verified`/`createdAt` and drops the never-sent `pictureUrl`/`role`; and
+ channel messages get a dedicated `ChannelMessageRecord` (`id`/`body`/`timestamp`/`hasMedia`/`mediaUrl`)
+ instead of being typed as the persisted `MessageRecord`, which that endpoint never returns — it reads
+ WhatsApp live. This mirrors how `ChatHistoryMessage` already models the live `messages.history()`
+ payload. Status timestamps are typed as the ISO 8601 strings they serialize to rather than
+ `Date`/`Object`. JavaScript, Python, and Java needed all four corrections; Go needed the two channel
+ ones (its status and label models were already right). The PHP SDK is array-based and unaffected.
+ ⚠️ **Breaking (typed SDK consumers):** every field named here was one the server has never sent (always
+ `undefined`/`null`), so the code reading it was already broken at runtime; it now fails to compile.
+ `label.color`/`label.colorHex` → `label.hexColor`; `channel.pictureUrl` → `channel.picture`;
+ `status.statusId` → `status.id`; `status.body` → `status.caption`. `channel.role` has no successor —
+ the server has no such field, so drop the read. Conversely the
+ real fields (`status.contact`, `channel.inviteCode`, `message.hasMedia`, …) were previously compile
+ errors and now resolve. Nothing caught this before: these controllers declare no `@ApiResponse` type,
+ so `openapi.json` carries no response schema for them and `openapi:check` had nothing to diff, while
+ the SDK suites mocked the transport and asserted URLs only. A type-level wire contract
+ (`sdk/javascript/test/wire-contract.test-d.ts`, gated by `tsc` in the JavaScript SDK's `npm test`) plus
+ per-model decode guards in the Java and Go suites now pin the models to the engine shapes. Refs #754.
+
- **Swagger now agrees with the engine capability matrix on status and catalog (docs only).** Eight
operations were describing something other than what they do, and the drift ran in both directions.
The three status-post routes were labelled "(Baileys only)" — stale since #714 wired them on
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 35764c15e..3bcae7b52 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -2,7 +2,7 @@
## 18.1 Overview
-OpenWA ships three official, hand-written client libraries for the REST API. They are not generated from an OpenAPI spec — each is written directly against the real API surface (paths, request DTOs, response shapes) and **unit-tested with a mocked HTTP transport that asserts on the exact request path, method, and body**, so contract drift is caught at test time rather than in production.
+OpenWA ships five official, hand-written client libraries for the REST API. They are not generated from an OpenAPI spec — each is written directly against the real API surface (paths, request DTOs, response shapes) and **unit-tested with a mocked HTTP transport that asserts on the exact request path, method, and body**, so drift in what an SDK *sends* is caught at test time rather than in production. That mechanism says nothing about what an SDK expects *back*; see §18.6 for how response shapes are held to the contract.
| Language | Package | Install | Notes |
| --- | --- | --- | --- |
@@ -519,7 +519,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| --- | --- | --- |
| `list` | `list(session_id) -> list[ChannelRecord]` | List subscribed channels. |
| `get` | `get(session_id, channel_id) -> ChannelRecord` | Get one channel. |
-| `messages` | `messages(session_id, channel_id, query=None) -> list[MessageRecord]` | List channel messages. |
+| `messages` | `messages(session_id, channel_id, query=None) -> list[ChannelMessageRecord]` | List channel messages. |
| `subscribe` | `subscribe(session_id, body) -> ChannelRecord` | Subscribe via invite code. **OPERATOR** |
| `unsubscribe` | `unsubscribe(session_id, channel_id) -> SuccessResult` | Unsubscribe from a channel. **OPERATOR** |
@@ -539,9 +539,9 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| --- | --- | --- |
| `list` | `list(session_id) -> dict[str, list[StatusRecord]]` | List all status updates. |
| `from_contact` | `from_contact(session_id, contact_id) -> dict[str, list[StatusRecord]]` | Status updates from one contact. |
-| `send_text` | `send_text(session_id, body) -> StatusRecord` | Post a text status. **OPERATOR** |
-| `send_image` | `send_image(session_id, body) -> StatusRecord` | Post an image status. **OPERATOR** |
-| `send_video` | `send_video(session_id, body) -> StatusRecord` | Post a video status. **OPERATOR** |
+| `send_text` | `send_text(session_id, body) -> StatusResult` | Post a text status. **OPERATOR** |
+| `send_image` | `send_image(session_id, body) -> StatusResult` | Post an image status. **OPERATOR** |
+| `send_video` | `send_video(session_id, body) -> StatusResult` | Post a video status. **OPERATOR** |
| `delete` | `delete(session_id, status_id) -> None` | Delete a status. **OPERATOR** |
#### `client.templates`
@@ -908,7 +908,11 @@ The three SDKs are versioned **independently of the gateway** and of each other,
### Contract-drift protection
-The wire types live in a dedicated module (`types.ts` / `types.py`) so they can later be regenerated by an OpenAPI codegen pass without touching the hand-written resource methods. Until then, each SDK's test suite mocks the HTTP transport and **asserts on the exact request path, method, and body** — so a drift between an SDK method and the real API (the class of bug that once shipped `messages/text` instead of the real `messages/send-text`) breaks a test rather than reaching users.
+The wire types live in a dedicated module (`types.ts` / `types.py`) so they can later be regenerated by an OpenAPI codegen pass without touching the hand-written resource methods.
+
+**Requests.** Each SDK's test suite mocks the HTTP transport and **asserts on the exact request path, method, and body** — so a drift between an SDK method and the real API (the class of bug that once shipped `messages/text` instead of the real `messages/send-text`) breaks a test rather than reaching users.
+
+**Responses.** That is a different problem, and for a long time nothing covered it — #754 is the proof: the status, label, and channel record types drifted from the engine interface for releases without a single test noticing, because asserting the request says nothing about the reply. It is not covered by `openapi:check` either: those controllers declare no typed `@ApiResponse`, so `openapi.json` carries no response schema for them and there is nothing to diff. The gate is now `sdk/javascript/test/wire-contract.test-d.ts` — a type-level test where `tsc --noEmit` (run by `npm test` ahead of vitest) fails if a record type stops matching the engine-neutral shape as it arrives over JSON. Its `Wire*` types are **maintained by hand**: `sdk-ci.yml` re-runs the job when `whatsapp-engine.interface.ts` changes, but keeping the two in step is a human step, not a generated one.
### Release process
diff --git a/sdk/go/channels.go b/sdk/go/channels.go
index 7d730751f..98a8c68a1 100644
--- a/sdk/go/channels.go
+++ b/sdk/go/channels.go
@@ -28,8 +28,8 @@ func (s *ChannelsService) Get(ctx context.Context, sessionID, channelID string)
}
// Messages returns recent messages from a channel.
-func (s *ChannelsService) Messages(ctx context.Context, sessionID, channelID string, query *ChannelMessageQuery) ([]MessageRecord, error) {
- var out []MessageRecord
+func (s *ChannelsService) Messages(ctx context.Context, sessionID, channelID string, query *ChannelMessageQuery) ([]ChannelMessageRecord, error) {
+ var out []ChannelMessageRecord
err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(channelID)+"/messages", valuesOf(query), nil, &out)
return out, err
}
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 817bb7a8c..8011c76f5 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -660,3 +660,62 @@ func TestContextCancel(t *testing.T) {
t.Fatal("expected context cancellation error")
}
}
+
+// The channel routes return the engine-neutral Channel verbatim (no DTO), so the record must carry
+// inviteCode/picture/verified/createdAt and must not invent pictureUrl/role (#754).
+func TestChannelListDecodesWireShape(t *testing.T) {
+ rt := &recordTransport{
+ status: 200,
+ body: `[{"id":"123@newsletter","name":"News","description":"d","inviteCode":"abc123",` +
+ `"subscriberCount":7,"picture":"https://x/p.jpg","verified":true,"createdAt":1700000000}]`,
+ }
+ c := newTestClient(t, rt)
+
+ got, err := c.Channels.List(context.Background(), "s1")
+ if err != nil {
+ t.Fatalf("Channels.List: %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("want 1 channel, got %d", len(got))
+ }
+ ch := got[0]
+ if ch.InviteCode == nil || *ch.InviteCode != "abc123" {
+ t.Errorf("InviteCode: %+v", ch.InviteCode)
+ }
+ if ch.Picture == nil || *ch.Picture != "https://x/p.jpg" {
+ t.Errorf("Picture: %+v", ch.Picture)
+ }
+ if ch.Verified == nil || !*ch.Verified {
+ t.Errorf("Verified: %+v", ch.Verified)
+ }
+ if ch.CreatedAt == nil || *ch.CreatedAt != 1700000000 {
+ t.Errorf("CreatedAt: %+v", ch.CreatedAt)
+ }
+}
+
+// Channel messages are the live engine payload, not the persisted MessageRecord (#754).
+func TestChannelMessagesDecodeEngineShape(t *testing.T) {
+ rt := &recordTransport{
+ status: 200,
+ body: `[{"id":"m1","body":"hi","timestamp":1700000000,"hasMedia":true,"mediaUrl":"https://x/m.jpg"}]`,
+ }
+ c := newTestClient(t, rt)
+
+ got, err := c.Channels.Messages(context.Background(), "s1", "123@newsletter", nil)
+ if err != nil {
+ t.Fatalf("Channels.Messages: %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("want 1 message, got %d", len(got))
+ }
+ msg := got[0]
+ if msg.ID != "m1" || msg.Body != "hi" || msg.Timestamp != 1700000000 {
+ t.Errorf("scalar decode: %+v", msg)
+ }
+ if !msg.HasMedia {
+ t.Errorf("HasMedia: %+v", msg.HasMedia)
+ }
+ if msg.MediaURL != "https://x/m.jpg" {
+ t.Errorf("MediaURL: %q", msg.MediaURL)
+ }
+}
diff --git a/sdk/go/types_channel.go b/sdk/go/types_channel.go
index 75e9caab1..548011fa3 100644
--- a/sdk/go/types_channel.go
+++ b/sdk/go/types_channel.go
@@ -2,14 +2,33 @@ package openwa
import "net/url"
-// ChannelRecord is a WhatsApp Channel / Newsletter.
+// ChannelRecord is a WhatsApp Channel / Newsletter. Mirrors the backend Channel — the engine
+// payload is returned as-is, with no DTO in between.
type ChannelRecord struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Description *string `json:"description,omitempty"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description *string `json:"description,omitempty"`
+ // InviteCode is the invite code from the channel link.
+ InviteCode *string `json:"inviteCode,omitempty"`
SubscriberCount int `json:"subscriberCount,omitempty"`
- PictureURL *string `json:"pictureUrl,omitempty"`
- Role string `json:"role,omitempty"`
+ // Picture is the channel picture URL. Populated by Baileys; whatsapp-web.js omits it.
+ Picture *string `json:"picture,omitempty"`
+ Verified *bool `json:"verified,omitempty"`
+ // CreatedAt is the channel creation time as reported by the engine. Populated by Baileys;
+ // whatsapp-web.js omits it.
+ CreatedAt *int64 `json:"createdAt,omitempty"`
+}
+
+// ChannelMessageRecord is a message read live from a channel by Channels.Messages. This is the
+// engine payload (backend ChannelMessage), NOT the persisted MessageRecord — that endpoint reads
+// WhatsApp directly and never touches the message store.
+type ChannelMessageRecord struct {
+ ID string `json:"id"`
+ Body string `json:"body"`
+ // Timestamp is a Unix timestamp in seconds.
+ Timestamp int64 `json:"timestamp"`
+ HasMedia bool `json:"hasMedia"`
+ MediaURL string `json:"mediaUrl,omitempty"`
}
// ChannelMessageQuery limits the channel message read (default 50).
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelMessageRecord.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelMessageRecord.java
new file mode 100644
index 000000000..19a11b368
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelMessageRecord.java
@@ -0,0 +1,15 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * A message read live from a channel by {@code channels.messages()}. This is the engine payload
+ * (backend {@code ChannelMessage}), NOT the persisted {@link MessageRecord} — that endpoint reads
+ * WhatsApp directly and never touches the message store. Optional fields are {@code null} when
+ * absent.
+ */
+public record ChannelMessageRecord(
+ String id,
+ String body,
+ /** Unix timestamp in seconds. */
+ Long timestamp,
+ Boolean hasMedia,
+ String mediaUrl) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelRecord.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelRecord.java
index fc42b6eff..7558c49fc 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelRecord.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChannelRecord.java
@@ -1,10 +1,18 @@
package com.rmyndharis.openwa.model;
-/** A WhatsApp Channel / Newsletter. Optional fields are {@code null} when absent. */
+/**
+ * A WhatsApp Channel / Newsletter. Mirrors the backend {@code Channel} — returned by the engine
+ * as-is, with no DTO in between. Optional fields are {@code null} when absent.
+ */
public record ChannelRecord(
String id,
String name,
String description,
+ /** Invite code from the channel link. */
+ String inviteCode,
Integer subscriberCount,
- String pictureUrl,
- String role) {}
+ /** Channel picture URL. Populated by Baileys; whatsapp-web.js omits it. */
+ String picture,
+ Boolean verified,
+ /** Channel creation time as reported by the engine. Populated by Baileys; whatsapp-web.js omits it. */
+ Long createdAt) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/LabelRecord.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/LabelRecord.java
index 82a0492f0..e1689dcb5 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/LabelRecord.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/LabelRecord.java
@@ -1,4 +1,7 @@
package com.rmyndharis.openwa.model;
-/** A WhatsApp Business chat label. Optional fields are {@code null} when absent. */
-public record LabelRecord(String id, String name, String color, String colorHex) {}
+/**
+ * A WhatsApp Business chat label. Mirrors the backend {@code Label} — returned by the engine
+ * as-is, with no DTO in between. {@code hexColor} is the label colour, e.g. {@code #25D366}.
+ */
+public record LabelRecord(String id, String name, String hexColor) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusContact.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusContact.java
new file mode 100644
index 000000000..69b36193c
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusContact.java
@@ -0,0 +1,4 @@
+package com.rmyndharis.openwa.model;
+
+/** Whose story a {@link StatusRecord} belongs to. Optional fields are {@code null} when absent. */
+public record StatusContact(String id, String name, String pushName) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusRecord.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusRecord.java
index 6d3b738fa..264a6b458 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusRecord.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusRecord.java
@@ -1,13 +1,26 @@
package com.rmyndharis.openwa.model;
/**
- * Weak shape returned by the GET status endpoints ({@code list}/{@code fromContact}).
- * The server payload there is loose/different; every field is optional and may be {@code null}.
+ * One status/story from the GET status endpoints ({@code list}/{@code fromContact}), which answer a
+ * {@link StatusListResult} envelope. Mirrors the backend {@code Status} — the engine payload is
+ * returned as-is, with no DTO in between. Optional fields are {@code null} when absent.
+ *
+ * <p>{@code mediaUrl}, {@code backgroundColor} and {@code font} are declared by the backend but no
+ * engine populates them on a read yet: whatsapp-web.js maps none of them, and Baileys cannot read
+ * statuses at all. They are here for forward compatibility — do not expect them on a response today.
*/
public record StatusRecord(
String id,
- String statusId,
+ /** Whose story this is. */
+ StatusContact contact,
+ /** One of {@code text}, {@code image} or {@code video}. */
String type,
- String body,
- /** ISO 8601 timestamp string or an epoch number, depending on the engine. */
- Object timestamp) {}
+ /** Text body for a text status, caption for an image/video one. */
+ String caption,
+ String mediaUrl,
+ String backgroundColor,
+ Integer font,
+ /** ISO 8601 timestamp of the post. */
+ String timestamp,
+ /** ISO 8601 expiry — 24h after {@code timestamp}. */
+ String expiresAt) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChannelsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChannelsResource.java
index e9249c35c..6893b5cc7 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChannelsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChannelsResource.java
@@ -5,8 +5,8 @@ import static com.rmyndharis.openwa.http.Http.encodeSegment;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.ChannelMessageQuery;
+import com.rmyndharis.openwa.model.ChannelMessageRecord;
import com.rmyndharis.openwa.model.ChannelRecord;
-import com.rmyndharis.openwa.model.MessageRecord;
import com.rmyndharis.openwa.model.SubscribeChannelRequest;
import com.rmyndharis.openwa.model.SuccessResult;
import java.util.List;
@@ -40,13 +40,13 @@ public final class ChannelsResource {
}
/** Get recent messages from a channel. */
- public List<MessageRecord> messages(String sessionId, String channelId, ChannelMessageQuery query) {
+ public List<ChannelMessageRecord> messages(String sessionId, String channelId, ChannelMessageQuery query) {
return client.requestList(
HttpMethod.GET,
"/api/sessions/" + encodeSegment(sessionId) + "/channels/" + encodeSegment(channelId) + "/messages",
query,
null,
- MessageRecord.class);
+ ChannelMessageRecord.class);
}
/** Subscribe to a channel using its invite code. Requires an OPERATOR-level key. */
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChannelsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChannelsResourceTest.java
index aff487957..a84c6f69d 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChannelsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChannelsResourceTest.java
@@ -7,6 +7,8 @@ import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.ChannelMessageQuery;
+import com.rmyndharis.openwa.model.ChannelMessageRecord;
+import com.rmyndharis.openwa.model.ChannelRecord;
import com.rmyndharis.openwa.model.SubscribeChannelRequest;
import com.rmyndharis.openwa.support.MockTransport;
import org.junit.jupiter.api.Test;
@@ -32,6 +34,38 @@ class ChannelsResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ /** Guards the wire contract: the backend `Channel` carries inviteCode/picture/verified/createdAt (#754). */
+ @Test
+ void listDeserializesTheChannelWireShape() {
+ tx.respond(
+ 200,
+ "[{\"id\":\"123@newsletter\",\"name\":\"News\",\"description\":\"d\",\"inviteCode\":\"abc123\","
+ + "\"subscriberCount\":7,\"picture\":\"https://x/p.jpg\",\"verified\":true,"
+ + "\"createdAt\":1700000000}]");
+ ChannelRecord channel = client.channels.list("s").get(0);
+ assertEquals("123@newsletter", channel.id());
+ assertEquals("abc123", channel.inviteCode());
+ assertEquals(7, channel.subscriberCount());
+ assertEquals("https://x/p.jpg", channel.picture());
+ assertTrue(channel.verified());
+ assertEquals(1700000000L, channel.createdAt());
+ }
+
+ /** Guards the wire contract: channel messages are the engine payload, not a persisted MessageRecord (#754). */
+ @Test
+ void messagesDeserializesTheEngineChannelMessageShape() {
+ tx.respond(
+ 200,
+ "[{\"id\":\"m1\",\"body\":\"hi\",\"timestamp\":1700000000,\"hasMedia\":true,"
+ + "\"mediaUrl\":\"https://x/m.jpg\"}]");
+ ChannelMessageRecord message = client.channels.messages("s", "123@newsletter", null).get(0);
+ assertEquals("m1", message.id());
+ assertEquals("hi", message.body());
+ assertEquals(1700000000L, message.timestamp());
+ assertTrue(message.hasMedia());
+ assertEquals("https://x/m.jpg", message.mediaUrl());
+ }
+
@Test
void messagesSerializesQueryIntoUrl() {
tx.respond(200, "[]");
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/LabelsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/LabelsResourceTest.java
index 1ee210919..412a2557c 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/LabelsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/LabelsResourceTest.java
@@ -7,6 +7,7 @@ import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.AddLabelRequest;
+import com.rmyndharis.openwa.model.LabelRecord;
import com.rmyndharis.openwa.support.MockTransport;
import org.junit.jupiter.api.Test;
@@ -23,6 +24,16 @@ class LabelsResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ /** Guards the wire contract: the backend `Label` carries `hexColor`, never `color`/`colorHex` (#754). */
+ @Test
+ void listDeserializesTheLabelWireShape() {
+ tx.respond(200, "[{\"id\":\"l1\",\"name\":\"VIP\",\"hexColor\":\"#25D366\"}]");
+ LabelRecord label = client.labels.list("s").get(0);
+ assertEquals("l1", label.id());
+ assertEquals("VIP", label.name());
+ assertEquals("#25D366", label.hexColor());
+ }
+
@Test
void getEncodesIds() {
tx.respond(200, "{\"id\":\"a/b\",\"name\":\"VIP\"}");
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
index 4b0667fc1..b4a89b8ec 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
@@ -10,6 +10,7 @@ import com.rmyndharis.openwa.model.SendImageStatusRequest;
import com.rmyndharis.openwa.model.SendTextStatusRequest;
import com.rmyndharis.openwa.model.SendVideoStatusRequest;
import com.rmyndharis.openwa.model.StatusMediaInput;
+import com.rmyndharis.openwa.model.StatusRecord;
import com.rmyndharis.openwa.support.MockTransport;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -29,6 +30,24 @@ class StatusResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ /** Guards the wire contract: the backend `Status` carries contact/caption/expiresAt, never statusId/body (#754). */
+ @Test
+ void listDeserializesTheStatusWireShape() {
+ tx.respond(
+ 200,
+ "{\"statuses\":[{\"id\":\"s1\",\"contact\":{\"id\":\"[email protected]\",\"pushName\":\"Ana\"},"
+ + "\"type\":\"image\",\"caption\":\"hi\",\"timestamp\":\"2026-01-01T00:00:00.000Z\","
+ + "\"expiresAt\":\"2026-01-02T00:00:00.000Z\"}]}");
+ StatusRecord record = status.list("s").statuses().get(0);
+ assertEquals("s1", record.id());
+ assertEquals("[email protected]", record.contact().id());
+ assertEquals("Ana", record.contact().pushName());
+ assertEquals("image", record.type());
+ assertEquals("hi", record.caption());
+ assertEquals("2026-01-01T00:00:00.000Z", record.timestamp());
+ assertEquals("2026-01-02T00:00:00.000Z", record.expiresAt());
+ }
+
@Test
void listEncodesSessionId() {
tx.respond(200, "{\"statuses\":[{\"id\":\"x\",\"type\":\"text\",\"timestamp\":\"2026-01-01\"}]}");
diff --git a/sdk/javascript/package.json b/sdk/javascript/package.json
index 903e88a96..319a74041 100644
--- a/sdk/javascript/package.json
+++ b/sdk/javascript/package.json
@@ -22,7 +22,7 @@
"build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json',JSON.stringify({type:'commonjs'}))\"",
"prepublishOnly": "npm run build",
"dev": "tsc -p tsconfig.esm.json --watch",
- "test": "vitest run",
+ "test": "tsc --noEmit && vitest run",
"test:watch": "vitest",
"smoke": "node scripts/smoke.mjs",
"typecheck": "tsc --noEmit"
diff --git a/sdk/javascript/src/resources/channels.ts b/sdk/javascript/src/resources/channels.ts
index 7c23202a0..20af165b6 100644
--- a/sdk/javascript/src/resources/channels.ts
+++ b/sdk/javascript/src/resources/channels.ts
@@ -9,8 +9,8 @@ import { encodeSegment } from '../http.js';
import type { OpenWAClient } from '../client.js';
import type {
ChannelMessageQuery,
+ ChannelMessageRecord,
ChannelRecord,
- MessageRecord,
SubscribeChannelRequest,
SuccessResult,
} from '../types.js';
@@ -35,8 +35,8 @@ export class ChannelsResource {
}
/** Get recent messages from a channel. */
- messages(sessionId: string, channelId: string, query?: ChannelMessageQuery): Promise<MessageRecord[]> {
- return this.client.request<MessageRecord[]>({
+ messages(sessionId: string, channelId: string, query?: ChannelMessageQuery): Promise<ChannelMessageRecord[]> {
+ return this.client.request<ChannelMessageRecord[]>({
method: 'GET',
path: `/api/sessions/${encodeSegment(sessionId)}/channels/${encodeSegment(channelId)}/messages`,
query,
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 1be5b7f08..224f57978 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -503,15 +503,31 @@ export interface DeleteChatRequest {
// ── Status / Stories ──────────────────────────────────────────────
/**
- * Weak shape returned by the GET status endpoints (`list`/`fromContact`).
- * The server payload there is loose/different; fields are all optional.
+ * One status/story from the GET status endpoints (`list`/`fromContact`), which answer a
+ * `{ statuses: [...] }` envelope. Mirrors the backend `Status` — the engine payload is returned
+ * as-is, with no DTO in between.
*/
export interface StatusRecord {
- id?: string;
- statusId?: string;
- type?: string;
- body?: string | null;
- timestamp?: string | number;
+ id: string;
+ /** Whose story this is. */
+ contact: {
+ id: Jid;
+ name?: string;
+ pushName?: string;
+ };
+ type: 'text' | 'image' | 'video';
+ /** Text body for a text status, caption for an image/video one. */
+ caption?: string;
+ // Declared by the backend `Status`, but no engine populates them on a read yet: whatsapp-web.js
+ // maps neither, and Baileys does not support reading statuses at all. Present for forward
+ // compatibility — do not expect them on a response today.
+ mediaUrl?: string;
+ backgroundColor?: string;
+ font?: number;
+ /** ISO 8601 timestamp of the post. */
+ timestamp: string;
+ /** ISO 8601 expiry — 24h after `timestamp`. */
+ expiresAt: string;
}
/**
@@ -611,11 +627,12 @@ export type UpdateTemplateRequest = Partial<CreateTemplateRequest>;
// ── Label (WhatsApp Business) ─────────────────────────────────────
+/** Mirrors the backend `Label` — returned by the engine as-is, with no DTO in between. */
export interface LabelRecord {
id: string;
name: string;
- color?: string;
- colorHex?: string;
+ /** Label colour as a hex string, e.g. `#25D366`. */
+ hexColor: string;
}
export interface AddLabelRequest {
@@ -624,13 +641,33 @@ export interface AddLabelRequest {
// ── Channel / Newsletter ──────────────────────────────────────────
+/** Mirrors the backend `Channel` — returned by the engine as-is, with no DTO in between. */
export interface ChannelRecord {
id: Jid;
- name?: string;
- description?: string | null;
+ name: string;
+ description?: string;
+ /** Invite code from the channel link. */
+ inviteCode?: string;
subscriberCount?: number;
- pictureUrl?: string | null;
- role?: string;
+ /** Channel picture URL. Populated by Baileys; whatsapp-web.js omits it. */
+ picture?: string;
+ verified?: boolean;
+ /** Channel creation time as reported by the engine. Populated by Baileys; whatsapp-web.js omits it. */
+ createdAt?: number;
+}
+
+/**
+ * A message read live from a channel by `channels.messages()`. This is the engine payload
+ * (backend `ChannelMessage`), NOT the persisted {@link MessageRecord} — that endpoint reads
+ * WhatsApp directly and never touches the message store.
+ */
+export interface ChannelMessageRecord {
+ id: string;
+ body: string;
+ /** Unix timestamp in seconds. */
+ timestamp: number;
+ hasMedia: boolean;
+ mediaUrl?: string;
}
export interface ChannelMessageQuery {
diff --git a/sdk/javascript/test/wire-contract.test-d.ts b/sdk/javascript/test/wire-contract.test-d.ts
new file mode 100644
index 000000000..c87f238cb
--- /dev/null
+++ b/sdk/javascript/test/wire-contract.test-d.ts
@@ -0,0 +1,96 @@
+/**
+ * Type-level contract test for the engine-resource endpoints — `tsc` is the gate, which `npm test`
+ * runs ahead of vitest (`.test-d.ts` sits outside vitest's `test/**\/*.test.ts` include, so there is
+ * no suite to run here; the build tsconfigs exclude `test/`, so nothing else would check it).
+ *
+ * The status/label/channel routes hand the engine-neutral shapes from
+ * `src/engine/interfaces/whatsapp-engine.interface.ts` straight to the client — no DTO, no remap —
+ * so the record types below must mirror those shapes as JSON. Nothing else enforces that: the
+ * controllers declare no `@ApiResponse` type, so `openapi.json` carries no schema for these routes
+ * and `openapi:check` has nothing to diff, and the resource tests mock the transport and assert
+ * URLs only (#754).
+ *
+ * The `Wire*` types are the server interfaces as they arrive over JSON — `Date` fields serialize to
+ * ISO strings, everything else is verbatim. Keep them in sync with the engine interface by hand;
+ * `sdk-ci.yml` re-runs this job when that file changes.
+ * @packageDocumentation
+ */
+
+import type { CatalogInfo, ChannelMessageRecord, ChannelRecord, LabelRecord, StatusRecord } from '../src/types.js';
+
+/** `Label` — `hexColor` is the only colour field the wire shape carries. */
+interface WireLabel {
+ id: string;
+ name: string;
+ hexColor: string;
+}
+
+/**
+ * `Status` — `timestamp`/`expiresAt` are `Date` on the server and ISO strings once serialized.
+ * `mediaUrl`/`backgroundColor`/`font` are declared by the engine interface but no adapter populates
+ * them yet (wwjs `collectStatuses()` sets neither; Baileys throws `unsupported`), so they are
+ * optional here for forward-compatibility rather than because a response carries them today.
+ */
+interface WireStatus {
+ id: string;
+ contact: { id: string; name?: string; pushName?: string };
+ type: 'text' | 'image' | 'video';
+ caption?: string;
+ mediaUrl?: string;
+ backgroundColor?: string;
+ font?: number;
+ timestamp: string;
+ expiresAt: string;
+}
+
+/** `Channel` — `picture`/`createdAt` come from the Baileys `toChannel()` path; wwjs omits both. */
+interface WireChannel {
+ id: string;
+ name: string;
+ description?: string;
+ inviteCode?: string;
+ subscriberCount?: number;
+ picture?: string;
+ verified?: boolean;
+ createdAt?: number;
+}
+
+/** `ChannelMessage` — the live engine payload, NOT the persisted `MessageRecord`. */
+interface WireChannelMessage {
+ id: string;
+ body: string;
+ timestamp: number;
+ hasMedia: boolean;
+ mediaUrl?: string;
+}
+
+/** `Catalog` — the control: this pair already agreed before #754 and must stay agreeing. */
+interface WireCatalog {
+ id: string;
+ name: string;
+ description?: string;
+ productCount: number;
+ url: string;
+}
+
+/**
+ * Resolves to `true` only when `Rec` is an honest view of `Wire`: it can hold every real response
+ * (so no field access that the server answers is a compile error), and it declares no field the
+ * server never sends (so no access silently evaluates to `undefined`). A mismatch resolves to a
+ * message tuple, which fails to accept `true` at the assertion site.
+ */
+type Mirrors<Wire, Rec> = Wire extends Rec
+ ? [Exclude<keyof Wire, keyof Rec>] extends [never]
+ ? [Exclude<keyof Rec, keyof Wire>] extends [never]
+ ? true
+ : ['sdk declares fields the server never sends:', Exclude<keyof Rec, keyof Wire>]
+ : ['sdk omits fields the server sends:', Exclude<keyof Wire, keyof Rec>]
+ : ['sdk type cannot hold a real response:', Wire];
+
+const label: Mirrors<WireLabel, LabelRecord> = true;
+const status: Mirrors<WireStatus, StatusRecord> = true;
+const channel: Mirrors<WireChannel, ChannelRecord> = true;
+const channelMessage: Mirrors<WireChannelMessage, ChannelMessageRecord> = true;
+const catalog: Mirrors<WireCatalog, CatalogInfo> = true;
+
+export const contract = [label, status, channel, channelMessage, catalog];
diff --git a/sdk/python/openwa/resources/channels.py b/sdk/python/openwa/resources/channels.py
index a0d440424..07c07adbf 100644
--- a/sdk/python/openwa/resources/channels.py
+++ b/sdk/python/openwa/resources/channels.py
@@ -9,7 +9,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from .._http import quote_segment
-from ..types import ChannelMessageQuery, ChannelRecord, MessageRecord, SubscribeChannelRequest, SuccessResult
+from ..types import (
+ ChannelMessageQuery,
+ ChannelMessageRecord,
+ ChannelRecord,
+ SubscribeChannelRequest,
+ SuccessResult,
+)
if TYPE_CHECKING:
from .._http import HttpExecutor
@@ -27,7 +33,7 @@ class ChannelsResource:
def messages(
self, session_id: str, channel_id: str, query: ChannelMessageQuery | None = None
- ) -> list[MessageRecord]:
+ ) -> list[ChannelMessageRecord]:
return self._http.request(
"GET", f"/api/sessions/{quote_segment(session_id)}/channels/{quote_segment(channel_id)}/messages", query=query
)
diff --git a/sdk/python/openwa/resources/status.py b/sdk/python/openwa/resources/status.py
index 0ded81b24..e02eacf40 100644
--- a/sdk/python/openwa/resources/status.py
+++ b/sdk/python/openwa/resources/status.py
@@ -9,7 +9,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from .._http import quote_segment
-from ..types import SendImageStatusRequest, SendTextStatusRequest, SendVideoStatusRequest, StatusRecord
+from ..types import (
+ SendImageStatusRequest,
+ SendTextStatusRequest,
+ SendVideoStatusRequest,
+ StatusRecord,
+ StatusResult,
+)
if TYPE_CHECKING:
from .._http import HttpExecutor
@@ -25,13 +31,13 @@ class StatusResource:
def from_contact(self, session_id: str, contact_id: str) -> dict[str, list[StatusRecord]]:
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/status/{quote_segment(contact_id)}")
- def send_text(self, session_id: str, body: SendTextStatusRequest) -> StatusRecord:
+ def send_text(self, session_id: str, body: SendTextStatusRequest) -> StatusResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-text", body=body)
- def send_image(self, session_id: str, body: SendImageStatusRequest) -> StatusRecord:
+ def send_image(self, session_id: str, body: SendImageStatusRequest) -> StatusResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-image", body=body)
- def send_video(self, session_id: str, body: SendVideoStatusRequest) -> StatusRecord:
+ def send_video(self, session_id: str, body: SendVideoStatusRequest) -> StatusResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-video", body=body)
def delete(self, session_id: str, status_id: str) -> None:
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 923e72d25..a015c6e44 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -493,12 +493,41 @@ class DeleteChatRequest(TypedDict):
# ── Status / Stories ──────────────────────────────────────────────
+class StatusContact(TypedDict, total=False):
+ """Whose story a :class:`StatusRecord` belongs to."""
+
+ id: Jid
+ name: str
+ pushName: str
+
+
+# One status/story from the GET status endpoints (``list``/``from_contact``), which
+# answer a ``{"statuses": [...]}`` envelope. Mirrors the backend ``Status`` — the engine
+# payload is returned as-is, with no DTO in between. ``timestamp``/``expiresAt`` are
+# ISO 8601 strings (``Date`` on the server, serialized). ``mediaUrl``/``backgroundColor``/
+# ``font`` are declared by the backend but no engine populates them on a read yet
+# (whatsapp-web.js maps none of them; Baileys cannot read statuses at all).
class StatusRecord(TypedDict, total=False):
id: str
- statusId: str
+ contact: StatusContact
type: str
- body: str | None
- timestamp: str | int
+ caption: str
+ mediaUrl: str
+ backgroundColor: str
+ font: int
+ timestamp: str
+ expiresAt: str
+
+
+# Result of a status POST (``send-text``/``send-image``/``send-video``). 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):
+ statusId: str
+ # ISO 8601 timestamp of the post.
+ timestamp: str
+ # ISO 8601 expiry timestamp.
+ expiresAt: str
class SendTextStatusRequest(TypedDict, total=False):
@@ -591,11 +620,12 @@ class UpdateTemplateRequest(TypedDict, total=False):
# ── Label (WhatsApp Business) ─────────────────────────────────────
+# Mirrors the backend ``Label`` — returned by the engine as-is, with no DTO in between.
+# ``hexColor`` is the only colour field the wire shape carries, e.g. ``#25D366``.
class LabelRecord(TypedDict, total=False):
id: str
name: str
- color: str
- colorHex: str
+ hexColor: str
class AddLabelRequest(TypedDict):
@@ -605,13 +635,28 @@ class AddLabelRequest(TypedDict):
# ── Channel / Newsletter ──────────────────────────────────────────
+# Mirrors the backend ``Channel`` — returned by the engine as-is, with no DTO in between.
+# ``picture``/``createdAt`` are populated by Baileys; whatsapp-web.js omits both.
class ChannelRecord(TypedDict, total=False):
id: Jid
name: str
- description: str | None
+ description: str
+ inviteCode: str
subscriberCount: int
- pictureUrl: str | None
- role: str
+ picture: str
+ verified: bool
+ createdAt: int
+
+
+# A message read live from a channel by ``channels.messages()`` — the engine payload
+# (backend ``ChannelMessage``), NOT the persisted MessageRecord. ``timestamp`` is a Unix
+# timestamp in seconds.
+class ChannelMessageRecord(TypedDict, total=False):
+ id: str
+ body: str
+ timestamp: int
+ hasMedia: bool
+ mediaUrl: str
class ChannelMessageQuery(TypedDict, total=False):