ziphjs 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # ziphjs
2
2
 
3
- Lightweight server-side JavaScript and TypeScript client for sending WhatsApp and
4
- SMS messages with [Ziph](https://ziph.dev). Requires Node.js 20 or later. ESM only;
5
- TypeScript declarations are included. No runtime dependencies.
3
+ Lightweight JavaScript and TypeScript client for sending WhatsApp and
4
+ SMS messages with [Ziph](https://ziph.dev). No runtime dependencies.
5
+
6
+ The client covers sending messages; it does not list messages or look up message
7
+ details. Incoming webhook types support handling replies to your messages.
6
8
 
7
9
  ## Installation
8
10
 
@@ -12,16 +14,16 @@ npm install ziphjs
12
14
 
13
15
  ## Quick start
14
16
 
15
- Keep your API key on the server, outside source control. Set `ZIPH_API_KEY` in your
16
- environment, then send a message:
17
+ Set `ZIPH_API_KEY` in your server environment. Keep it out of source control and
18
+ browser code.
17
19
 
18
20
  ```js
19
21
  import { ZiphClient } from "ziphjs";
20
22
 
21
23
  const client = new ZiphClient({ apiKey: process.env.ZIPH_API_KEY });
22
24
 
23
- const { data: message } = await client.sendText({
24
- channel_type: "sms",
25
+ const { data: message } = await client.sendMessage({
26
+ channel_type: "whatsapp",
25
27
  to: "+23276123456",
26
28
  text: "Your order is ready.",
27
29
  idempotencyKey: "order-123-ready",
@@ -30,45 +32,86 @@ const { data: message } = await client.sendText({
30
32
  console.log(message.id, message.status);
31
33
  ```
32
34
 
33
- Use `channel_type: "whatsapp"` to send WhatsApp text. An optional `channel_id`
34
- selects a WhatsApp channel; omitting it uses the default channel.
35
+ WhatsApp messages use your default channel. To choose another, pass its
36
+ `channel_id`. For SMS, use `channel_type: "sms"`.
37
+
38
+ `sendMessage` requires `text` for text and list messages. For image messages, omit
39
+ `text` or leave it empty and use `image.caption` for a caption.
40
+
41
+ Use `sendMessage` for any supported message type, or the `sendText`, `sendImage`,
42
+ and `sendList` helpers when you want a type-specific method. Request and response
43
+ types are exported from `ziphjs`.
44
+
45
+ Every send needs a nonblank string `idempotencyKey`. The client does not impose
46
+ a key-length limit. Use a new key for each message. If you're unsure whether a
47
+ request succeeded, retry with the same key and unchanged request. The client
48
+ does not retry automatically.
49
+
50
+ ## Typing incoming webhook payloads
51
+
52
+ `MessageReceivedEvent` is exported for incoming WhatsApp text and interactive
53
+ replies. In a JavaScript Hono handler, annotate the parsed body with JSDoc:
54
+
55
+ ```js
56
+ /** @type {import("ziphjs").MessageReceivedEvent} */
57
+ const data = await c.req.json();
58
+
59
+ const reply = data.message.button_reply?.id ?? data.message.list_reply?.id;
60
+ const phone = data.message.sender_phone;
61
+ ```
62
+
63
+ In TypeScript, import the type and supply it to Hono's JSON reader:
64
+
65
+ ```ts
66
+ import type { MessageReceivedEvent } from "ziphjs";
35
67
 
36
- The client also exposes `sendImage`, `sendList`, and `sendMessage`. Public request
37
- and response types are exported from `ziphjs`.
68
+ const data = await c.req.json<MessageReceivedEvent>();
69
+ ```
38
70
 
39
- Every send requires an `idempotencyKey` of 1–255 bytes. Use a new key per logical
40
- message, and reuse that key with the unchanged request when retrying an uncertain
41
- outcome. The client sends once, without automatic retries. An accepted message is
42
- not confirmation of delivery.
71
+ `sender_name`, `sender_phone`, and `sender_lid` are omitted when unavailable.
72
+ Check that `sender_phone` exists before using it as a send recipient. The
73
+ `sender` address and `sender_lid` may be opaque WhatsApp identifiers, not phone
74
+ numbers; `sender_name` is an unverified display name.
75
+
76
+ These annotations provide static typing, not runtime validation. Verify webhook
77
+ signatures against the raw body before parsing, validate the payload, and
78
+ deduplicate event IDs before performing business actions.
43
79
 
44
80
  ## Errors
45
81
 
46
- Unsuccessful HTTP responses throw `ZiphError`, with `status`, `code`, `details`,
47
- and `meta` properties. Network errors are not wrapped. Invalid client options or
82
+ Failed HTTP responses throw `ZiphError`, which includes `status`, `code`, `details`,
83
+ and `meta`. Network errors pass through unchanged. Invalid client options or
48
84
  idempotency keys throw `TypeError`.
49
85
 
50
- ## Development and releases
86
+ The constructor rejects missing, non-string, or whitespace-only API keys with
87
+ `TypeError: apiKey must be a non-empty string.`
51
88
 
52
- Run `npm ci`, `npm run format:check`, `npm run typecheck`, `npm test`, and
53
- `npm run build` before releasing. The test command currently discovers no tests.
54
- Use `npm pack --dry-run` to inspect the package contents without publishing.
89
+ WhatsApp sends can fail with `NUMBER_LIMIT_EXCEEDED` (HTTP 409) when your
90
+ workspace has more channels than its plan allows. This differs from
91
+ `MESSAGE_QUOTA_EXCEEDED` (HTTP 429), which means the remaining WhatsApp message
92
+ or SMS segment allowance is insufficient.
93
+
94
+ ## Removed read-response types
55
95
 
56
- The Release workflow runs only on pushed `v*` tags. The tag must match the version
57
- in `package.json`, for example `v0.0.1`. It checks the package, builds it, publishes
58
- to npm using OIDC, then creates a GitHub Release with generated release notes.
59
- Pushing a release tag publishes the package; it is not a preview.
96
+ `MessageDetail`, `MessageDetailEnvelope`, `MessageList`, `MessageListEnvelope`,
97
+ `MessageStatusEvent`, and `Message.events` have been removed. They described
98
+ lookup/list responses, not send responses. Consumers importing these types must
99
+ remove those imports. Send methods still return `MessageEnvelope`, whose `data`
100
+ is a `Message`; WhatsApp list-menu types and `sendList` are unchanged.
60
101
 
61
- Before using the workflow, configure npm trusted publishing for the package:
102
+ ## Development and releases
62
103
 
63
- - Organization: `spikenardco`
64
- - Repository: `ziphjs`
65
- - Workflow filename: `release.yml`
66
- - Allow direct `npm publish`
104
+ The runtime is plain ESM JavaScript in `src/index.js`. TypeScript declarations
105
+ live in `types/index.d.ts` and `types/models.d.ts`; consumers can import types
106
+ directly from `ziphjs`. There is no compilation or bundling step.
67
107
 
68
- If the package does not yet exist on npm, first publish it manually with a
69
- maintainer account so its package settings are available, then configure trusted
70
- publishing for subsequent versions. Do not tag that already-published version for
71
- the publish workflow. No long-lived npm token is needed in GitHub Actions.
108
+ Run `npm ci`, `npm run format:check`, and `npm run typecheck` before releasing.
109
+ Typechecking checks the JavaScript through JSDoc and the public declarations
110
+ under both NodeNext and bundler resolution.
111
+
112
+ Use `npm pack --dry-run` to inspect the package contents without publishing.
113
+ The package ships `src` and `types` directly. Keep public declarations and
114
+ implementation annotations in sync when changing the API.
72
115
 
73
116
  ## License
74
117
 
package/package.json CHANGED
@@ -1,29 +1,29 @@
1
1
  {
2
2
  "name": "ziphjs",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "Lightweight server-side JavaScript and TypeScript client for sending WhatsApp and SMS messages with Ziph.",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": ">=20.0.0"
8
8
  },
9
+ "types": "./types/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "default": "./dist/index.js"
12
+ "types": "./types/index.d.ts",
13
+ "import": "./src/index.js",
14
+ "default": "./src/index.js"
14
15
  }
15
16
  },
16
17
  "sideEffects": false,
17
18
  "files": [
18
- "dist"
19
+ "src",
20
+ "types"
19
21
  ],
20
22
  "scripts": {
21
23
  "format": "biome check --write .",
22
24
  "format:check": "biome check .",
23
- "test": "node --test",
24
- "typecheck": "tsc --noEmit",
25
- "build": "rm -rf dist && esbuild src/index.js --bundle --platform=node --format=esm --outfile=dist/index.js --target=node20 --minify && tsc --emitDeclarationOnly --rootDir src",
26
- "prepublishOnly": "npm run build"
25
+ "typecheck": "tsc && tsc --module ESNext --moduleResolution bundler",
26
+ "prepublishOnly": "npm run format:check && npm run typecheck"
27
27
  },
28
28
  "repository": {
29
29
  "type": "git",
@@ -53,7 +53,6 @@
53
53
  "devDependencies": {
54
54
  "@biomejs/biome": "^2.5.12",
55
55
  "@types/node": "^26.4.1",
56
- "esbuild": "^0.28.2",
57
56
  "typescript": "^7.0.2"
58
57
  }
59
58
  }
package/src/index.js ADDED
@@ -0,0 +1,111 @@
1
+ /** @import {
2
+ ApiError,
3
+ ErrorEnvelope,
4
+ MessageEnvelope,
5
+ Meta,
6
+ SendImageInput,
7
+ SendListInput,
8
+ SendMessageInput,
9
+ SendTextInput,
10
+ ZiphOptions,
11
+ } from "../types/models.js" */
12
+
13
+ /** An unsuccessful HTTP response from Ziph. Network errors are not wrapped. */
14
+ export class ZiphError extends Error {
15
+ /**
16
+ * @param {number} status
17
+ * @param {ApiError | null} [error]
18
+ * @param {Meta | null} [meta]
19
+ */
20
+ constructor(status, error = null, meta = null) {
21
+ super(error?.message ?? `Ziph request failed with HTTP ${status}.`);
22
+ this.name = "ZiphError";
23
+ this.status = status;
24
+ this.code = error?.code ?? null;
25
+ this.details = error?.details ?? [];
26
+ this.meta = meta;
27
+ }
28
+ }
29
+
30
+ /** Server-side client for sending WhatsApp and SMS messages. */
31
+ export class ZiphClient {
32
+ /** @type {string} */
33
+ #apiKey;
34
+ /** @type {URL} */
35
+ #messageUrl;
36
+
37
+ /** @param {ZiphOptions} options */
38
+ constructor({ apiKey, baseUrl = "https://api.ziph.dev" }) {
39
+ if (typeof apiKey !== "string" || !apiKey.trim()) {
40
+ throw new TypeError("apiKey must be a non-empty string.");
41
+ }
42
+
43
+ this.#apiKey = apiKey;
44
+ this.#messageUrl = new URL(`${baseUrl.replace(/\/+$/, "")}/v1/messages`);
45
+
46
+ if (!["http:", "https:"].includes(this.#messageUrl.protocol)) {
47
+ throw new TypeError("baseUrl must use HTTP or HTTPS.");
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Sends a WhatsApp or SMS text message. text is required.
53
+ * @param {SendTextInput} input
54
+ * @returns {Promise<MessageEnvelope>}
55
+ */
56
+ sendText(input) {
57
+ return this.sendMessage(input);
58
+ }
59
+
60
+ /**
61
+ * Sends a WhatsApp image. Use image.caption for accompanying text.
62
+ * @param {SendImageInput} input
63
+ * @returns {Promise<MessageEnvelope>}
64
+ */
65
+ sendImage(input) {
66
+ return this.sendMessage({ ...input, channel_type: "whatsapp" });
67
+ }
68
+
69
+ /**
70
+ * Sends a WhatsApp list menu. Both text and list are required.
71
+ * @param {SendListInput} input
72
+ * @returns {Promise<MessageEnvelope>}
73
+ */
74
+ sendList(input) {
75
+ return this.sendMessage({ ...input, channel_type: "whatsapp" });
76
+ }
77
+
78
+ /**
79
+ * Sends once, without automatic retries. Reuse the same key and unchanged
80
+ * request if retrying after a network error or an uncertain outcome.
81
+ * Acceptance does not confirm delivery. idempotencyKey is sent only as a header.
82
+ * @param {SendMessageInput} input
83
+ * @returns {Promise<MessageEnvelope>}
84
+ */
85
+ async sendMessage({ idempotencyKey, ...request }) {
86
+ if (typeof idempotencyKey !== "string" || !idempotencyKey.trim()) {
87
+ throw new TypeError("idempotencyKey must be a non-empty string.");
88
+ }
89
+
90
+ const response = await fetch(this.#messageUrl, {
91
+ method: "POST",
92
+ redirect: "error",
93
+ headers: {
94
+ Authorization: `Bearer ${this.#apiKey}`,
95
+ "Content-Type": "application/json",
96
+ "Idempotency-Key": idempotencyKey,
97
+ },
98
+ body: JSON.stringify(request),
99
+ });
100
+
101
+ if (!response.ok) {
102
+ // Proxies may return HTML or empty bodies instead of an API envelope.
103
+ const body = /** @type {ErrorEnvelope | null} */ (
104
+ await response.json().catch(() => null)
105
+ );
106
+ throw new ZiphError(response.status, body?.error, body?.meta);
107
+ }
108
+
109
+ return /** @type {Promise<MessageEnvelope>} */ (response.json());
110
+ }
111
+ }
@@ -0,0 +1,42 @@
1
+ // biome-ignore-all lint/correctness/noUnusedPrivateClassMembers: The declaration preserves the runtime class's private-field identity.
2
+ import type {
3
+ ApiError,
4
+ ErrorCode,
5
+ FieldError,
6
+ MessageEnvelope,
7
+ Meta,
8
+ SendImageInput,
9
+ SendListInput,
10
+ SendMessageInput,
11
+ SendTextInput,
12
+ ZiphOptions,
13
+ } from "./models.js";
14
+
15
+ export type * from "./models.js";
16
+
17
+ /** An unsuccessful HTTP response from Ziph. Network errors are not wrapped. */
18
+ export declare class ZiphError extends Error {
19
+ status: number;
20
+ code: ErrorCode | null;
21
+ details: FieldError[];
22
+ meta: Meta | null;
23
+ constructor(status: number, error?: ApiError | null, meta?: Meta | null);
24
+ }
25
+
26
+ /** Server-side client for sending WhatsApp and SMS messages. */
27
+ export declare class ZiphClient {
28
+ #private;
29
+ constructor(options: ZiphOptions);
30
+ /** Sends a WhatsApp or SMS text message. text is required. */
31
+ sendText(input: SendTextInput): Promise<MessageEnvelope>;
32
+ /** Sends a WhatsApp image. Use image.caption for accompanying text. */
33
+ sendImage(input: SendImageInput): Promise<MessageEnvelope>;
34
+ /** Sends a WhatsApp list menu. Both text and list are required. */
35
+ sendList(input: SendListInput): Promise<MessageEnvelope>;
36
+ /**
37
+ * Sends once, without automatic retries. Reuse the same key and unchanged
38
+ * request if retrying after a network error or an uncertain outcome.
39
+ * Acceptance does not confirm delivery. idempotencyKey is sent only as a header.
40
+ */
41
+ sendMessage(input: SendMessageInput): Promise<MessageEnvelope>;
42
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Public types for the Ziph API,
3
+ *
4
+ * Wire fields keep the API's snake_case names.
5
+ */
6
+
7
+ export type ChannelType = "whatsapp" | "sms";
8
+
9
+ export type MessageStatus =
10
+ | "processing"
11
+ | "accepted"
12
+ | "delivered"
13
+ | "read"
14
+ | "failed"
15
+ | "unknown";
16
+
17
+ /** Buttons: 1–3 per message, WhatsApp only. */
18
+ export interface QuickReplyButton {
19
+ /** Defaults to quick_reply when omitted. */
20
+ type?: "" | "quick_reply";
21
+ /** Unique per message, 1–128 bytes. */
22
+ id: string;
23
+ /** 1–25 characters. */
24
+ title: string;
25
+ url?: never;
26
+ copy_code?: never;
27
+ phone_number?: never;
28
+ }
29
+
30
+ export interface UrlButton {
31
+ type: "url";
32
+ title: string;
33
+ /** Absolute http(s) URL. */
34
+ url: string;
35
+ id?: never;
36
+ copy_code?: never;
37
+ phone_number?: never;
38
+ }
39
+
40
+ export interface CopyButton {
41
+ type: "copy";
42
+ title: string;
43
+ copy_code: string;
44
+ id?: never;
45
+ url?: never;
46
+ phone_number?: never;
47
+ }
48
+
49
+ export interface CallButton {
50
+ type: "call";
51
+ title: string;
52
+ /** International format, e.g. +23276123456. */
53
+ phone_number: string;
54
+ id?: never;
55
+ url?: never;
56
+ copy_code?: never;
57
+ }
58
+
59
+ export type MessageButton =
60
+ | QuickReplyButton
61
+ | UrlButton
62
+ | CopyButton
63
+ | CallButton;
64
+
65
+ export type MessageButtons =
66
+ | [MessageButton]
67
+ | [MessageButton, MessageButton]
68
+ | [MessageButton, MessageButton, MessageButton];
69
+
70
+ /** WhatsApp image: JPEG or PNG, up to 5 MiB, publicly accessible without redirects. */
71
+ export interface MessageImage {
72
+ url: string;
73
+ /** Up to 4096 bytes. Use this instead of text when sending an image. */
74
+ caption?: string;
75
+ }
76
+
77
+ /** Single-select WhatsApp list menu. Cannot be combined with buttons or an image. */
78
+ export interface ListRow {
79
+ /** Unique per message, 1–128 bytes. */
80
+ id: string;
81
+ /** 1–24 characters. */
82
+ title: string;
83
+ /** Up to 72 characters. */
84
+ description?: string;
85
+ }
86
+
87
+ export interface ListSection {
88
+ /** 1–24 characters. */
89
+ title: string;
90
+ rows: [ListRow, ...ListRow[]];
91
+ }
92
+
93
+ export interface MessageListMenu {
94
+ /** Caption of the menu button, 1–20 characters. */
95
+ button_text: string;
96
+ /** 1–10 sections, at most 10 rows in total. */
97
+ sections: [ListSection, ...ListSection[]];
98
+ }
99
+
100
+ /** SMS is text only. */
101
+ export interface SmsMessage {
102
+ channel_type: "sms";
103
+ /** Recipient in international format, e.g. +23276123456. */
104
+ to: string;
105
+ channel_id?: never;
106
+ /** 1–4096 bytes. */
107
+ text: string;
108
+ buttons?: never;
109
+ image?: never;
110
+ list?: never;
111
+ }
112
+
113
+ export interface WhatsAppTextMessage {
114
+ channel_type: "whatsapp";
115
+ /** Recipient in international format, e.g. +23276123456. */
116
+ to: string;
117
+ /** Uses the default channel when omitted or null. */
118
+ channel_id?: string | null;
119
+ /** 1–4096 bytes. Must include non-whitespace text when adding buttons. */
120
+ text: string;
121
+ buttons?: MessageButtons;
122
+ image?: never;
123
+ list?: never;
124
+ }
125
+
126
+ export interface WhatsAppImageMessage {
127
+ channel_type: "whatsapp";
128
+ /** Recipient in international format, e.g. +23276123456. */
129
+ to: string;
130
+ /** Uses the default channel when omitted or null. */
131
+ channel_id?: string | null;
132
+ /** Omit, or pass an empty string, and use image.caption instead. */
133
+ text?: "";
134
+ buttons?: MessageButtons;
135
+ image: MessageImage;
136
+ list?: never;
137
+ }
138
+
139
+ export interface WhatsAppListMessage {
140
+ channel_type: "whatsapp";
141
+ /** Recipient in international format, e.g. +23276123456. */
142
+ to: string;
143
+ /** Uses the default channel when omitted or null. */
144
+ channel_id?: string | null;
145
+ /** 1–4096 bytes. */
146
+ text: string;
147
+ buttons?: never;
148
+ image?: never;
149
+ list: MessageListMenu;
150
+ }
151
+
152
+ export type SendMessageRequest =
153
+ | SmsMessage
154
+ | WhatsAppTextMessage
155
+ | WhatsAppImageMessage
156
+ | WhatsAppListMessage;
157
+
158
+ export type ZiphOptions = {
159
+ /** Server-side API key. Never expose it in browser code. */
160
+ apiKey: string;
161
+ /** API root without /v1. Defaults to https://api.ziph.dev. */
162
+ baseUrl?: string;
163
+ };
164
+
165
+ /** The key must be a nonblank string. Reuse it with the unchanged request when retrying. */
166
+ export type SendMessageInput = SendMessageRequest & { idempotencyKey: string };
167
+
168
+ export type SendTextInput = (
169
+ | Pick<SmsMessage, "channel_type" | "to" | "text">
170
+ | Pick<
171
+ WhatsAppTextMessage,
172
+ "channel_type" | "to" | "text" | "channel_id" | "buttons"
173
+ >
174
+ ) & { idempotencyKey: string };
175
+
176
+ export type SendImageInput = Pick<
177
+ WhatsAppImageMessage,
178
+ "to" | "channel_id" | "image" | "buttons"
179
+ > & { idempotencyKey: string };
180
+
181
+ export type SendListInput = Pick<
182
+ WhatsAppListMessage,
183
+ "to" | "channel_id" | "text" | "list"
184
+ > & { idempotencyKey: string };
185
+
186
+ /** Selection returned when a recipient answers a quick-reply or list message. */
187
+ export interface InteractiveReply {
188
+ id: string;
189
+ title: string;
190
+ quoted_provider_message_id?: string;
191
+ }
192
+
193
+ export interface ReceivedMessage {
194
+ provider_message_id: string;
195
+ /** Original provider address. An @lid address is not a phone number. */
196
+ sender: string;
197
+ /** Unverified display name. Omitted when unavailable. */
198
+ sender_name?: string;
199
+ /** International +digits phone number. Omitted when unknown. */
200
+ sender_phone?: string;
201
+ /** Opaque @lid address without a device suffix. Omitted when unavailable. */
202
+ sender_lid?: string;
203
+ conversation: string;
204
+ text: string;
205
+ button_reply?: InteractiveReply;
206
+ list_reply?: InteractiveReply;
207
+ }
208
+
209
+ export interface MessageReceivedEvent {
210
+ version: 1;
211
+ id: string;
212
+ event: "message.received";
213
+ channel_id: string;
214
+ timestamp: string;
215
+ message: ReceivedMessage;
216
+ }
217
+
218
+ export interface Message {
219
+ id: string;
220
+ channel_id: string | null;
221
+ channel_type: ChannelType;
222
+ recipient_masked: string;
223
+ status: MessageStatus;
224
+ provider_message_id: string | null;
225
+ failure_code: string | null;
226
+ created_at: string;
227
+ updated_at: string;
228
+ }
229
+
230
+ export interface Meta {
231
+ request_id?: string;
232
+ timestamp: string;
233
+ }
234
+
235
+ export interface ResponseEnvelope<T> {
236
+ data: T;
237
+ meta: Meta;
238
+ }
239
+
240
+ export type MessageEnvelope = ResponseEnvelope<Message>;
241
+
242
+ export type ErrorCode =
243
+ | "AUTH_REQUIRED"
244
+ | "MESSAGE_QUOTA_EXCEEDED"
245
+ | "PLAN_EXPIRED"
246
+ | "NUMBER_LIMIT_EXCEEDED"
247
+ | "VALIDATION_ERROR"
248
+ | "NOT_FOUND"
249
+ | "CHANNEL_DISCONNECTED"
250
+ | "PROVIDER_UNAVAILABLE"
251
+ | "PROVIDER_TIMEOUT"
252
+ | "PROVIDER_REJECTED"
253
+ | "IDEMPOTENCY_CONFLICT"
254
+ | "CHANNEL_TYPE_UNAVAILABLE"
255
+ | "CHANNEL_TYPE_MISMATCH"
256
+ | "MESSAGE_TYPE_UNAVAILABLE"
257
+ | "INTERNAL_SERVER_ERROR";
258
+
259
+ export interface FieldError {
260
+ field: string;
261
+ message: string;
262
+ }
263
+
264
+ export interface ApiError {
265
+ code: ErrorCode;
266
+ message: string;
267
+ details: FieldError[];
268
+ }
269
+
270
+ export interface ErrorEnvelope {
271
+ data: null;
272
+ error: ApiError;
273
+ meta: Meta;
274
+ }
package/dist/index.d.ts DELETED
@@ -1,90 +0,0 @@
1
- export * from "./types.js";
2
- export type ZiphOptions = {
3
- /**
4
- * Server-side API key. Never expose it in browser code.
5
- */
6
- apiKey: string;
7
- /**
8
- * API root without /v1. Defaults to https://api.ziph.dev.
9
- */
10
- baseUrl?: string;
11
- };
12
- export type SendMessageInput = import('./types.js').SendMessageRequest & {
13
- idempotencyKey: string;
14
- };
15
- export type SendTextInput = (Pick<import('./types.js').SmsMessage, 'channel_type' | 'to' | 'text'> | Pick<import('./types.js').WhatsAppTextMessage, 'channel_type' | 'to' | 'text' | 'channel_id' | 'buttons'>) & {
16
- idempotencyKey: string;
17
- };
18
- export type SendImageInput = Pick<import('./types.js').WhatsAppImageMessage, 'to' | 'channel_id' | 'image' | 'buttons'> & {
19
- idempotencyKey: string;
20
- };
21
- export type SendListInput = Pick<import('./types.js').WhatsAppListMessage, 'to' | 'channel_id' | 'text' | 'list'> & {
22
- idempotencyKey: string;
23
- };
24
- /**
25
- * @typedef {object} ZiphOptions
26
- * @property {string} apiKey Server-side API key. Never expose it in browser code.
27
- * @property {string} [baseUrl] API root without /v1. Defaults to https://api.ziph.dev.
28
- */
29
- /**
30
- * @typedef {import('./types.js').SendMessageRequest & { idempotencyKey: string }} SendMessageInput
31
- * The key must be 1–255 bytes. Reuse it with the unchanged request when retrying.
32
- */
33
- /**
34
- * @typedef {(Pick<import('./types.js').SmsMessage, 'channel_type' | 'to' | 'text'> | Pick<import('./types.js').WhatsAppTextMessage, 'channel_type' | 'to' | 'text' | 'channel_id' | 'buttons'>) & { idempotencyKey: string }} SendTextInput
35
- */
36
- /**
37
- * @typedef {Pick<import('./types.js').WhatsAppImageMessage, 'to' | 'channel_id' | 'image' | 'buttons'> & { idempotencyKey: string }} SendImageInput
38
- */
39
- /**
40
- * @typedef {Pick<import('./types.js').WhatsAppListMessage, 'to' | 'channel_id' | 'text' | 'list'> & { idempotencyKey: string }} SendListInput
41
- */
42
- /** An unsuccessful HTTP response from Ziph. Network errors are not wrapped. */
43
- export declare class ZiphError extends Error {
44
- /** @readonly */
45
- status: number;
46
- /** @readonly */
47
- code: import("./types.js").ErrorCode | null;
48
- /** @readonly */
49
- details: import("./types.js").FieldError[];
50
- /** @readonly */
51
- meta: import("./types.js").Meta | null;
52
- /**
53
- * @param {number} status
54
- * @param {import('./types.js').ApiError | null} [error]
55
- * @param {import('./types.js').Meta | null} [meta]
56
- */
57
- constructor(status: number, error?: import('./types.js').ApiError | null, meta?: import('./types.js').Meta | null);
58
- }
59
- /** Server-side client for sending WhatsApp and SMS messages. */
60
- export declare class ZiphClient {
61
- #private;
62
- /** @param {ZiphOptions} options */
63
- constructor({ apiKey, baseUrl }: ZiphOptions);
64
- /**
65
- * Sends a WhatsApp or SMS text message. text is required.
66
- * @param {SendTextInput} input
67
- * @returns {Promise<import('./types.js').MessageEnvelope>}
68
- */
69
- sendText(input: SendTextInput): Promise<import('./types.js').MessageEnvelope>;
70
- /**
71
- * Sends a WhatsApp image. Use image.caption for accompanying text.
72
- * @param {SendImageInput} input
73
- * @returns {Promise<import('./types.js').MessageEnvelope>}
74
- */
75
- sendImage(input: SendImageInput): Promise<import('./types.js').MessageEnvelope>;
76
- /**
77
- * Sends a WhatsApp list menu. Both text and list are required.
78
- * @param {SendListInput} input
79
- * @returns {Promise<import('./types.js').MessageEnvelope>}
80
- */
81
- sendList(input: SendListInput): Promise<import('./types.js').MessageEnvelope>;
82
- /**
83
- * Sends once, without automatic retries. Reuse the same key and unchanged
84
- * request if retrying after a network error or an uncertain outcome.
85
- * Acceptance does not confirm delivery. idempotencyKey is sent only as a header.
86
- * @param {SendMessageInput} input
87
- * @returns {Promise<import('./types.js').MessageEnvelope>}
88
- */
89
- sendMessage({ idempotencyKey, ...request }: SendMessageInput): Promise<import('./types.js').MessageEnvelope>;
90
- }
package/dist/index.js DELETED
@@ -1 +0,0 @@
1
- var r=class extends Error{constructor(e,t=null,s=null){super(t?.message??`Ziph request failed with HTTP ${e}.`),this.name="ZiphError",this.status=e,this.code=t?.code??null,this.details=t?.details??[],this.meta=s}},a=class{#t;#e;constructor({apiKey:e,baseUrl:t="https://api.ziph.dev"}){if(typeof e!="string"||!e.trim())throw new TypeError("apiKey is required.");if(this.#t=e,this.#e=new URL(`${t.replace(/\/+$/,"")}/v1/messages`),!["http:","https:"].includes(this.#e.protocol))throw new TypeError("baseUrl must use HTTP or HTTPS.")}sendText(e){return this.sendMessage(e)}sendImage(e){return this.sendMessage({...e,channel_type:"whatsapp"})}sendList(e){return this.sendMessage({...e,channel_type:"whatsapp"})}async sendMessage({idempotencyKey:e,...t}){if(typeof e!="string"||!e.trim()||Buffer.byteLength(e)>255)throw new TypeError("idempotencyKey must be between 1 and 255 bytes.");let s=await fetch(this.#e,{method:"POST",redirect:"error",headers:{Authorization:`Bearer ${this.#t}`,"Content-Type":"application/json","Idempotency-Key":e},body:JSON.stringify(t)});if(!s.ok){let n=await s.json().catch(()=>null);throw new r(s.status,n?.error,n?.meta)}return s.json()}};export{a as ZiphClient,r as ZiphError};
package/dist/types.d.ts DELETED
@@ -1,196 +0,0 @@
1
- /**
2
- * Public types for the Ziph API,
3
- *
4
- * Wire fields keep the API's snake_case names.
5
- */
6
- export type ChannelType = "whatsapp" | "sms";
7
- export type MessageStatus = "processing" | "accepted" | "delivered" | "read" | "failed" | "unknown";
8
- /** Buttons: 1–3 per message, WhatsApp only. */
9
- export interface QuickReplyButton {
10
- /** Defaults to quick_reply when omitted. */
11
- type?: "" | "quick_reply";
12
- /** Unique per message, 1–128 bytes. */
13
- id: string;
14
- /** 1–25 characters. */
15
- title: string;
16
- url?: never;
17
- copy_code?: never;
18
- phone_number?: never;
19
- }
20
- export interface UrlButton {
21
- type: "url";
22
- title: string;
23
- /** Absolute http(s) URL. */
24
- url: string;
25
- id?: never;
26
- copy_code?: never;
27
- phone_number?: never;
28
- }
29
- export interface CopyButton {
30
- type: "copy";
31
- title: string;
32
- copy_code: string;
33
- id?: never;
34
- url?: never;
35
- phone_number?: never;
36
- }
37
- export interface CallButton {
38
- type: "call";
39
- title: string;
40
- /** International format, e.g. +23276123456. */
41
- phone_number: string;
42
- id?: never;
43
- url?: never;
44
- copy_code?: never;
45
- }
46
- export type MessageButton = QuickReplyButton | UrlButton | CopyButton | CallButton;
47
- export type MessageButtons = [MessageButton] | [MessageButton, MessageButton] | [MessageButton, MessageButton, MessageButton];
48
- /** WhatsApp image: JPEG or PNG, up to 5 MiB, publicly accessible without redirects. */
49
- export interface MessageImage {
50
- url: string;
51
- /** Up to 4096 bytes. Use this instead of text when sending an image. */
52
- caption?: string;
53
- }
54
- /** Single-select WhatsApp list menu. Cannot be combined with buttons or an image. */
55
- export interface ListRow {
56
- /** Unique per message, 1–128 bytes. */
57
- id: string;
58
- /** 1–24 characters. */
59
- title: string;
60
- /** Up to 72 characters. */
61
- description?: string;
62
- }
63
- export interface ListSection {
64
- /** 1–24 characters. */
65
- title: string;
66
- rows: [ListRow, ...ListRow[]];
67
- }
68
- export interface MessageListMenu {
69
- /** Caption of the menu button, 1–20 characters. */
70
- button_text: string;
71
- /** 1–10 sections, at most 10 rows in total. */
72
- sections: [ListSection, ...ListSection[]];
73
- }
74
- /** SMS is text only. */
75
- export interface SmsMessage {
76
- channel_type: "sms";
77
- /** Recipient in international format, e.g. +23276123456. */
78
- to: string;
79
- channel_id?: never;
80
- /** 1–4096 bytes. */
81
- text: string;
82
- buttons?: never;
83
- image?: never;
84
- list?: never;
85
- }
86
- export interface WhatsAppTextMessage {
87
- channel_type: "whatsapp";
88
- /** Recipient in international format, e.g. +23276123456. */
89
- to: string;
90
- /** Uses the default channel when omitted or null. */
91
- channel_id?: string | null;
92
- /** 1–4096 bytes. Must include non-whitespace text when adding buttons. */
93
- text: string;
94
- buttons?: MessageButtons;
95
- image?: never;
96
- list?: never;
97
- }
98
- export interface WhatsAppImageMessage {
99
- channel_type: "whatsapp";
100
- /** Recipient in international format, e.g. +23276123456. */
101
- to: string;
102
- /** Uses the default channel when omitted or null. */
103
- channel_id?: string | null;
104
- /** Omit, or pass an empty string, and use image.caption instead. */
105
- text?: "";
106
- buttons?: MessageButtons;
107
- image: MessageImage;
108
- list?: never;
109
- }
110
- export interface WhatsAppListMessage {
111
- channel_type: "whatsapp";
112
- /** Recipient in international format, e.g. +23276123456. */
113
- to: string;
114
- /** Uses the default channel when omitted or null. */
115
- channel_id?: string | null;
116
- /** 1–4096 bytes. */
117
- text: string;
118
- buttons?: never;
119
- image?: never;
120
- list: MessageListMenu;
121
- }
122
- export type SendMessageRequest = SmsMessage | WhatsAppTextMessage | WhatsAppImageMessage | WhatsAppListMessage;
123
- /** Selection returned when a recipient answers a quick-reply or list message. */
124
- export interface InteractiveReply {
125
- id: string;
126
- title: string;
127
- quoted_provider_message_id?: string;
128
- }
129
- export interface ReceivedMessage {
130
- provider_message_id: string;
131
- sender: string;
132
- conversation: string;
133
- text: string;
134
- button_reply?: InteractiveReply;
135
- list_reply?: InteractiveReply;
136
- }
137
- export interface MessageReceivedEvent {
138
- version: 1;
139
- id: string;
140
- event: "message.received";
141
- channel_id: string;
142
- timestamp: string;
143
- message: ReceivedMessage;
144
- }
145
- export interface MessageStatusEvent {
146
- id: string;
147
- status: MessageStatus;
148
- failure_code: string | null;
149
- occurred_at: string;
150
- }
151
- export interface Message {
152
- id: string;
153
- channel_id: string | null;
154
- channel_type: ChannelType;
155
- recipient_masked: string;
156
- status: MessageStatus;
157
- provider_message_id: string | null;
158
- failure_code: string | null;
159
- created_at: string;
160
- updated_at: string;
161
- events?: MessageStatusEvent[];
162
- }
163
- export interface MessageDetail extends Message {
164
- events: MessageStatusEvent[];
165
- }
166
- export interface MessageList {
167
- messages: Message[];
168
- /** Pass as `before` when listing; null on the last page. */
169
- next_cursor: string | null;
170
- }
171
- export interface Meta {
172
- request_id?: string;
173
- timestamp: string;
174
- }
175
- export interface ResponseEnvelope<T> {
176
- data: T;
177
- meta: Meta;
178
- }
179
- export type MessageEnvelope = ResponseEnvelope<Message>;
180
- export type MessageDetailEnvelope = ResponseEnvelope<MessageDetail>;
181
- export type MessageListEnvelope = ResponseEnvelope<MessageList>;
182
- export type ErrorCode = "AUTH_REQUIRED" | "MESSAGE_QUOTA_EXCEEDED" | "PLAN_EXPIRED" | "VALIDATION_ERROR" | "NOT_FOUND" | "CHANNEL_DISCONNECTED" | "PROVIDER_UNAVAILABLE" | "PROVIDER_TIMEOUT" | "PROVIDER_REJECTED" | "IDEMPOTENCY_CONFLICT" | "CHANNEL_TYPE_UNAVAILABLE" | "CHANNEL_TYPE_MISMATCH" | "MESSAGE_TYPE_UNAVAILABLE" | "INTERNAL_SERVER_ERROR";
183
- export interface FieldError {
184
- field: string;
185
- message: string;
186
- }
187
- export interface ApiError {
188
- code: ErrorCode;
189
- message: string;
190
- details: FieldError[];
191
- }
192
- export interface ErrorEnvelope {
193
- data: null;
194
- error: ApiError;
195
- meta: Meta;
196
- }