@smschi/sdk 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ipilot7
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,244 @@
1
- # Temporary Holding Version
1
+ # @smschi/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ JavaScript/TypeScript SDK SMSchi, версия **0.1.1**. Node.js **≥22**, ESM и CommonJS, без runtime-зависимостей. Лицензия: **MIT** — полный текст в `LICENSE`.
4
+
5
+ ## Установка из npm
6
+
7
+ ```sh
8
+ npm install @smschi/sdk
9
+ ```
10
+
11
+ Пакет предназначен для серверного Node.js, а не для браузерного приложения.
12
+
13
+ ## Установка из локального архива
14
+
15
+ Получите проверенный архив у владельца SDK и установите его в своём проекте:
16
+
17
+ ```sh
18
+ npm install /absolute/path/to/smschi-sdk-0.1.1.tgz
19
+ ```
20
+
21
+ Это установка локального `.tgz`, а не команда установки из реестра. Для получения архива из исходников используется `npm pack`; используйте имя файла из вывода этой команды. TypeScript-декларации поставляются с пакетом; runtime-пакеты и `@types` именно для SDK не нужны. Для Node-проекта TypeScript настройте стандартные типы Node.js либо `lib: ["ES2022", "DOM"]` для `fetch`/`AbortSignal`. Рекомендуемые `module` и `moduleResolution`: `NodeNext`.
22
+
23
+ ## Ключ и безопасность
24
+
25
+ Нужен **API-ключ SMSchi**, передаваемый заголовком `X-API-Key`. Это не JWT и не пароль от кабинета. Не помещайте ключ в браузерный bundle, URL, репозиторий или логи. Предназначение SDK — доверенный сервер Node.js.
26
+
27
+ Приватные переменные окружения для примеров (значения ниже намеренно непригодны для отправки):
28
+
29
+ ```dotenv
30
+ SMSCHI_API_KEY=PRIVATE_API_KEY_PLACEHOLDER
31
+ SMSCHI_TO=PRIVATE_PHONE_PLACEHOLDER
32
+ ```
33
+
34
+ Подставляйте свой разрешённый тестовый номер только локально. Не присылайте ключ и номер в чат. Примеры не загружают `.env` автоматически: передайте переменные безопасным способом вашего окружения.
35
+
36
+ ## Быстрый старт: ESM
37
+
38
+ Код ниже выполняет реальную отправку при запуске с настоящими переменными окружения:
39
+
40
+ ```js
41
+ import { SmschiClient } from '@smschi/sdk';
42
+
43
+ const client = new SmschiClient({ apiKey: process.env.SMSCHI_API_KEY });
44
+ const { messages } = await client.sms.send({
45
+ to: process.env.SMSCHI_TO,
46
+ body: 'Тест интеграции SMSchi',
47
+ });
48
+ const accepted = messages[0];
49
+ console.log({ id: accepted.id, status: accepted.status });
50
+ ```
51
+
52
+ В TypeScript предварительно проверьте наличие переменных: их тип — `string | undefined`, а ключ и `to` должны быть строками. Ответ **202 Accepted — принятие в очередь**, не подтверждение отправки или доставки.
53
+
54
+ ## CommonJS
55
+
56
+ ```js
57
+ const { SmschiClient } = require('@smschi/sdk');
58
+
59
+ async function main() {
60
+ const client = new SmschiClient({ apiKey: process.env.SMSCHI_API_KEY });
61
+ const { messages } = await client.sms.send({
62
+ to: process.env.SMSCHI_TO,
63
+ body: 'Тест интеграции SMSchi',
64
+ });
65
+ console.log({ id: messages[0].id, status: messages[0].status });
66
+ }
67
+ main().catch(() => { process.exitCode = 1; });
68
+ ```
69
+
70
+ Полные примеры с безопасной обработкой ошибок: `examples/send.mjs` и `examples/send.cjs`. Они требуют явного флага `--send` и отказываются работать с плейсхолдерами:
71
+
72
+ ```sh
73
+ node examples/send.mjs --send
74
+ # либо
75
+ node examples/send.cjs --send
76
+ ```
77
+
78
+ Каждый запуск с настоящими данными создаёт **новую SMS**. Не запускайте оба примера для проверки одной отправки и не используйте их как health-check.
79
+
80
+ ## Настройки клиента
81
+
82
+ ```js
83
+ const client = new SmschiClient({
84
+ apiKey: process.env.SMSCHI_API_KEY,
85
+ baseUrl: 'https://smschi.uz',
86
+ timeoutMs: 15000,
87
+ maxRetries: 0,
88
+ retryDelayMs: 250,
89
+ // fetch: customFetch, // необязательный совместимый с globalThis.fetch транспорт
90
+ });
91
+ ```
92
+
93
+ | Поле | Значение / ограничения |
94
+ | --- | --- |
95
+ | `apiKey` | Обязательный префикс `smk_`, затем один или более печатных ASCII-символов без пробелов и других whitespace (`U+0021`–`U+007E`) |
96
+ | `baseUrl` | По умолчанию `https://smschi.uz`; origin и при необходимости префикс развёртывания |
97
+ | `timeoutMs` | По умолчанию 15000 мс; целое от 1 до 2147483647 мс |
98
+ | `maxRetries` | Целое 0–3, по умолчанию 0; только для GET |
99
+ | `retryDelayMs` | Целое 0–60000 мс, по умолчанию 250; задержка удваивается с каждой повторной попыткой GET |
100
+ | `fetch` | Необязательная реализация стандартного `fetch` |
101
+
102
+ Не добавляйте `/api/v1` в `baseUrl`: SDK формирует API-пути сам и отклоняет двойной API-префикс. Query string, fragment и `user:password@host` запрещены. Требуется HTTPS; HTTP разрешён только для тестов на `localhost`, `127.0.0.1`, `[::1]`. Префикс вроде `https://gateway.example/smschi` допустим, если прокси действительно обслуживает API под ним.
103
+
104
+ Методы отправки, чтения и списков принимают `{ timeoutMs?, signal? }` последним аргументом:
105
+
106
+ ```js
107
+ const message = await client.sms.get('message-id', {
108
+ timeoutMs: 5000,
109
+ signal: AbortSignal.timeout(6000),
110
+ });
111
+ ```
112
+
113
+ ## Доступный API
114
+
115
+ | Метод SDK | HTTP | Результат |
116
+ | --- | --- | --- |
117
+ | `sms.send(input, options?)` | POST `/api/v1/sms` | `{ messages: AcceptedMessage[] }` |
118
+ | `sms.sendBatch(messages, options?)` | POST `/api/v1/sms` | `{ messages: AcceptedMessage[] }` |
119
+ | `sms.get(id, options?)` | GET `/api/v1/sms/:id` | `Message` |
120
+ | `sms.wait(id, options?)` | Повторные GET `/api/v1/sms/:id` | `Message` |
121
+ | `sims.list(options?)` | GET `/api/v1/sims` | `Sim[]` — без обёртки `items` |
122
+ | `devices.list(options?)` | GET `/api/v1/devices` | `Device[]` — без обёртки `items` |
123
+ | `tariffs.list(options?)` | GET `/api/v1/tariffs` | `{ items: Tariff[] }` |
124
+
125
+ Тарифы — публичный HTTP endpoint, но конструктор SDK всё равно требует ключ. SDK не предоставляет JWT/login, wallet, payments, subscriptions, WebSocket, webhook-регистрацию, входящие SMS или dashboard/admin API. Наличие таких функций на сервере не делает их частью этого SDK.
126
+
127
+ ### Отправка и пакет
128
+
129
+ ```js
130
+ const item = {
131
+ to: process.env.SMSCHI_TO,
132
+ body: 'Тест интеграции SMSchi',
133
+ simId: null,
134
+ deviceId: null,
135
+ from: null,
136
+ };
137
+ await client.sms.send(item);
138
+ // Альтернатива, не дополнительный шаг для той же SMS:
139
+ // await client.sms.send({ messages: [item] });
140
+ // await client.sms.sendBatch([item]);
141
+ ```
142
+
143
+ - Поля сообщения: обязательные `to`, `body`; необязательные `simId`, `deviceId`, `from` допускают `null`. Переданные ID должны быть непустыми строками.
144
+ - `body`: **1–1600 единиц UTF-16 JavaScript**, то есть ограничение `.length`, не число символов Unicode и не число SMS-сегментов. SDK не обещает один тарифицируемый сегмент на сообщение.
145
+ - Для проверки телефона удаляются пробелы, дефисы, точки и скобки; проверяется `^\+?[0-9]{7,15}$`. Префикс `+998` не навязывается. SDK проверяет нормализованную копию, но передаёт исходную строку без изменения; сервер выполняет свою нормализацию.
146
+ - Один пакет: **1–1000 сообщений**, один POST. Автоматического разбиения, частичных повторов и idempotency key нет. Не полагайтесь на локальную TypeScript-проверку для проверки длины строк/пакета: это runtime-ограничения.
147
+ - `AcceptedMessage`: `id`, `to`, `status`, `simId`, `deviceId`; последние два — `string | null`. Ответ принятия не содержит `body` и времён доставки.
148
+
149
+ ### Статус и ожидание
150
+
151
+ ```js
152
+ const message = await client.sms.wait('message-id', {
153
+ until: 'delivered', // по умолчанию 'sent'
154
+ pollIntervalMs: 1000, // по умолчанию 1000
155
+ timeoutMs: 60000, // общий предел ожидания, по умолчанию 60000
156
+ signal: AbortSignal.timeout(65000),
157
+ });
158
+ if (message.status === 'failed') {
159
+ // Обработайте неудачу; не отправляйте сообщение повторно без сверки.
160
+ }
161
+ ```
162
+
163
+ Реальные статусы: `queued`, `dispatched`, `sent`, `delivered`, `failed`.
164
+
165
+ - `until: 'sent'` завершает ожидание на `sent`, `delivered` или `failed`.
166
+ - `until: 'delivered'` завершает ожидание на `delivered` или `failed`.
167
+ - `failed` **возвращается как сообщение**, а не выбрасывается как исключение.
168
+ - Тайм-аут ожидания — ошибка `SmschiTimeoutError`; это не смена серверного статуса. Отмена останавливает локальное ожидание, но не серверную отправку.
169
+ - Общий монотонный дедлайн включает все GET, обработку ответа и паузы polling. Даже терминальный статус, обработанный после дедлайна, отклоняется с `SmschiTimeoutError`. Синхронная блокировка event loop задерживает само отклонение, но не превращает просроченный ответ в успешный результат.
170
+ - `sent` не означает `delivered`; отчёт о доставке может не поступить.
171
+
172
+ Полный `Message` дополнительно содержит `body`, `source` (`dashboard | api | autoreply`), `simPhoneNumber`, `requestedSimId`, `requestedDeviceId`, `requestedFrom`, `apiKeyId`, `attempts`, `error`, `lastError`, `parts`, `createdAt`, `dispatchedAt`, `sentAt`, `deliveredAt`, `failedAt`. Времена — строки; все перечисленные времена кроме `createdAt` допускают `null`. `parts` — `number | null`; ошибки и необязательные ссылки — `string | null`. Ответы могут содержать персональные данные — не логируйте объект сообщения целиком.
173
+
174
+ ### SIM, устройства, тарифы
175
+
176
+ ```js
177
+ const sims = await client.sims.list();
178
+ const devices = await client.devices.list();
179
+ const { items: tariffs } = await client.tariffs.list();
180
+ ```
181
+
182
+ - `Sim`: `id`, `phoneNumber: string | null`, `carrier`, `label: string | null`, `deviceId`, `deviceName`, `online`, `enabled`, `available`, `hourlyLimit`, `dailyLimit`, `usage: { hour, day }`. Здесь нет dashboard-полей `slotIndex`, `subscriptionId`, `minIntervalSec`.
183
+ - `Device`: `id`, `name`, `status: 'online' | 'offline'`, `battery: number | null`, `sims: Sim[]`. Не расширенная dashboard-модель.
184
+ - `Tariff`: `id`, `code`, `name: { uz, ru }`, `description: { uz, ru }`, числовые `price`, `durationDays`, `includedSegments`, `maxPhones`, `overageRate`, `sortOrder`, булевы `isTrial`, `isPayg`. SDK читает каталог, но не покупает тарифы и не рассчитывает итоговую стоимость.
185
+
186
+ ## Ошибки, повторы и неизвестный результат
187
+
188
+ Все классы — именованные экспорты, наследники `Error`:
189
+
190
+ | Класс | `code` / данные |
191
+ | --- | --- |
192
+ | `SmschiApiError` | `status: number`, `code: string`, `details: unknown`, `retryAfterMs: number | null`, `rateLimit: { limit: number | null, remaining: number | null }` |
193
+ | `SmschiNetworkError` | `NETWORK_ERROR` |
194
+ | `SmschiTimeoutError` | `TIMEOUT` |
195
+ | `SmschiAbortError` | `ABORTED` |
196
+ | `SmschiProtocolError` | `INVALID_RESPONSE` |
197
+
198
+ Ошибки локальной валидации могут быть `TypeError`, а не HTTP-ошибками. `SmschiProtocolError` обозначает некорректный ответ, а не доказанный отказ отправки.
199
+
200
+ ```js
201
+ import { SmschiApiError, SmschiTimeoutError, SmschiAbortError } from '@smschi/sdk';
202
+
203
+ try {
204
+ await client.sms.get('message-id');
205
+ } catch (error) {
206
+ if (error instanceof SmschiApiError) {
207
+ console.error({ status: error.status, code: error.code });
208
+ // При необходимости используйте retryAfterMs / rateLimit для управления нагрузкой.
209
+ } else if (error instanceof SmschiTimeoutError || error instanceof SmschiAbortError) {
210
+ console.error({ code: error.code });
211
+ } else {
212
+ console.error('Не удалось завершить запрос');
213
+ }
214
+ }
215
+ ```
216
+
217
+ `SmschiApiError.message` формируется безопасно по статусу/коду, без копирования сырого серверного сообщения. Однако **`details` может содержать чувствительные серверные данные**. Не записывайте весь `error`, `details`, ответы, заголовки, ключ, номер или текст SMS в логи. Пользовательский `fetch` также обязан не раскрывать запросы и ключи.
218
+
219
+ Конструктор ошибки: `new SmschiApiError({ status, code, details?, retryAfterMs?, rateLimit? })`; по умолчанию `retryAfterMs: null`, `rateLimit: { limit: null, remaining: null }`. Числовой `Retry-After` переводится в миллисекунды с округлением вверх. Непредставимо большие значения ограничены `Number.MAX_SAFE_INTEGER` в публичном `retryAfterMs` (не точная длительность); они никогда не разрешают ранний повтор. `null` означает отсутствующий или некорректный заголовок.
220
+
221
+ **POST никогда не повторяется SDK**, даже при `maxRetries: 3`, сетевом сбое, 429 или 5xx. Сервер не предоставляет idempotency key для этого маршрута. Разрешённые повторы GET не создают SMS; по умолчанию и они отключены. Повтор GET возможен только при сетевой ошибке либо HTTP 429/500/502/503/504. Учитывается единый дедлайн операции, включая чтение ответа и паузы. Если `Retry-After` больше 60000 мс или оставшегося времени, SDK возвращает ошибку, **не сокращая задержку и не повторяя запрос раньше разрешённого срока**. `Retry-After` не означает автоматический повтор отправки.
222
+
223
+ Ответ ограничен **1 МиБ**; превышение приводит к `SmschiProtocolError`. Перенаправления запрещены, ключ не пересылается на другой адрес. `tariffs.list()` не отправляет API-ключ на публичный маршрут. В `sms.wait()` ошибки HTTP не скрываются; polling расходует лимит запросов API-ключа. При параллельном ожидании сообщений увеличьте интервал (например, до 2000–5000 мс) и учитывайте лимиты сервера. Даже пакет из допустимых 1000 сообщений может превышать серверный лимит размера JSON, особенно с длинным Unicode-текстом; автоматического разбиения нет.
224
+
225
+ **Тайм-аут, отмена, разрыв сети или некорректный ответ после POST означают возможный неизвестный исход. Нельзя слепо отправлять SMS повторно.** Если ID получен — проверяйте его через `sms.get` / `sms.wait`. Если ID не получен — сверяйте состояние через кабинет/оператора; SDK не имеет API поиска по клиентскому idempotency key. Прекращение ожидания не отзывает уже принятую SMS.
226
+
227
+ ## Разработка и проверки
228
+
229
+ Публичный репозиторий содержит исходники SDK, декларации, документацию, примеры и автономные тесты. Серверные настройки и внутренние отчёты в поставку не входят.
230
+
231
+ ```sh
232
+ npm run build
233
+ npm test
234
+ ```
235
+
236
+ Декларации: `types/index.d.ts`; сборка создаёт объявления для обеих веток ESM/CJS. Compile-only fixtures в `test/types/` проверяют положительные вызовы, формы ответов, сужение ошибок и отклонение неподдерживаемых полей/методов. После сборки:
237
+
238
+ ```sh
239
+ tsc -p test/types/tsconfig.json
240
+ ```
241
+
242
+ Требуется доступный TypeScript; эта команда не устанавливает пакеты. Для проверки исходных деклараций до сборки используйте `tsc -p test/types/tsconfig.source.json`. Fixtures не запускают и не отправляют SMS. Проверка синтаксиса примеров: `node --check examples/send.mjs` и `node --check examples/send.cjs`.
243
+
244
+ Автономные тесты используют синтетические данные, подменённый транспорт и локальные HTTP-серверы. Они не доказывают реальную доставку, совместимость с будущими версиями API, доступность устройства или стоимость.
package/dist/index.cjs ADDED
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+ const MAX_TIMER = 2_147_483_647;
3
+ function record(value, label) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new TypeError(label + ' must be a plain object');
5
+ }
6
+ function keys(value, allowed, label) {
7
+ record(value, label);
8
+ if (Reflect.ownKeys(value).some(k => typeof k !== 'string' || !allowed.includes(k))) throw new TypeError(label + ' has unsupported fields');
9
+ }
10
+ function integer(value, min, max, label) {
11
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new TypeError(label + ' is outside the supported range');
12
+ return value;
13
+ }
14
+ function phone(value) { return typeof value === 'string' && /^\+?[0-9]{7,15}$/.test(value.replace(/[\s\-().]/g, '')); }
15
+ function message(input) {
16
+ keys(input, ['to','body','simId','deviceId','from'], 'SMS input');
17
+ if (!phone(input.to) || typeof input.body !== 'string' || input.body.length < 1 || input.body.length > 1600) throw new TypeError('SMS requires a valid phone and body of 1..1600 UTF-16 code units');
18
+ for (const key of ['simId','deviceId']) if (input[key] !== undefined && input[key] !== null && (typeof input[key] !== 'string' || !input[key].length)) throw new TypeError('Invalid routing identifier');
19
+ if (input.from !== undefined && input.from !== null && !phone(input.from)) throw new TypeError('Invalid sender phone');
20
+ return { ...input };
21
+ }
22
+ function identifier(id) {
23
+ if (typeof id !== 'string' || !id.length || id === '.' || id === '..') throw new TypeError('A nonempty message identifier is required');
24
+ return encodeURIComponent(id);
25
+ }
26
+ function base(value) {
27
+ if (typeof value !== 'string' || value.trim() !== value) throw new TypeError('baseUrl must be an absolute service URL');
28
+ let url; try { url = new URL(value); } catch { throw new TypeError('Invalid baseUrl'); }
29
+ const loopback = ['localhost','127.0.0.1','[::1]'].includes(url.hostname);
30
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash) throw new TypeError('baseUrl requires HTTPS (HTTP is allowed only on loopback), without credentials, query or fragment');
31
+ const path = url.pathname.replace(/\/+$/, '');
32
+ if (path.endsWith('/api/v1')) throw new TypeError('baseUrl is the service origin or deployment prefix, not /api/v1');
33
+ return url.origin + path;
34
+ }
35
+ class SmschiApiError extends Error {
36
+ constructor({ status, code, details, retryAfterMs = null, rateLimit = { limit: null, remaining: null } }) {
37
+ super('SMSchi API error: ' + code + ' (HTTP ' + status + ')');
38
+ this.name = 'SmschiApiError'; Object.assign(this, { status, code, details, retryAfterMs, rateLimit });
39
+ }
40
+ }
41
+ class SmschiProtocolError extends Error {
42
+ constructor() { super('SMSchi returned an invalid or unexpected response'); this.name = 'SmschiProtocolError'; this.code = 'INVALID_RESPONSE'; }
43
+ }
44
+ class SmschiNetworkError extends Error { constructor() { super('Network request failed; the outcome of an SMS submission may be unknown'); this.name = 'SmschiNetworkError'; this.code = 'NETWORK_ERROR'; } }
45
+ class SmschiTimeoutError extends Error { constructor() { super('SMSchi operation timed out; this does not cancel a queued SMS'); this.name = 'SmschiTimeoutError'; this.code = 'TIMEOUT'; } }
46
+ class SmschiAbortError extends Error { constructor() { super('SMSchi operation was aborted; this does not cancel a queued SMS'); this.name = 'SmschiAbortError'; this.code = 'ABORTED'; } }
47
+ function requestOptions(value, defaultTimeout) {
48
+ const options = value === undefined ? {} : value;
49
+ keys(options, ['timeoutMs','signal'], 'Request options');
50
+ const timeoutMs = integer(options.timeoutMs === undefined ? defaultTimeout : options.timeoutMs, 1, MAX_TIMER, 'timeoutMs');
51
+ const signal = options.signal;
52
+ if (signal !== undefined && (!signal || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new TypeError('signal must be an AbortSignal');
53
+ return { timeoutMs, signal };
54
+ }
55
+ async function withDeadline(work, timeoutMs, signal) {
56
+ if (signal?.aborted) throw new SmschiAbortError();
57
+ const controller = new AbortController(); let timer; let onAbort;
58
+ const cancelled = new Promise((resolve, reject) => {
59
+ onAbort = () => { controller.abort(); reject(new SmschiAbortError()); };
60
+ signal?.addEventListener('abort', onAbort, { once: true });
61
+ timer = setTimeout(() => { controller.abort(); reject(new SmschiTimeoutError()); }, timeoutMs);
62
+ });
63
+ try { return await Promise.race([Promise.resolve().then(() => work(controller.signal)), cancelled]); }
64
+ finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); }
65
+ }
66
+ function pause(ms, signal) {
67
+ if (signal?.aborted) return Promise.reject(new SmschiAbortError());
68
+ return new Promise((resolve, reject) => {
69
+ const onAbort = () => { clearTimeout(timer); signal.removeEventListener('abort', onAbort); reject(new SmschiAbortError()); };
70
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
71
+ signal?.addEventListener('abort', onAbort, { once: true });
72
+ });
73
+ }
74
+ function headerInteger(value) { return typeof value === 'string' && /^\d+$/.test(value) && Number.isSafeInteger(Number(value)) ? Number(value) : null; }
75
+ function retryAfter(value) {
76
+ if (!value) return null;
77
+ if (/^\d+(?:\.\d+)?$/.test(value)) { const n = Number(value) * 1000; return n >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Math.ceil(n); }
78
+ const date = Date.parse(value); return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
79
+ }
80
+ const STATUSES = ['queued','dispatched','sent','delivered','failed'];
81
+ function object(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }
82
+ function receipt(value) { return object(value) && typeof value.id === 'string' && !!value.id && typeof value.to === 'string' && STATUSES.includes(value.status) && (value.simId === null || typeof value.simId === 'string') && (value.deviceId === null || typeof value.deviceId === 'string'); }
83
+ function text(value) { return typeof value === 'string'; }
84
+ function nullableText(value) { return value === null || text(value); }
85
+ function count(value) { return Number.isSafeInteger(value) && value >= 0; }
86
+ function fullMessage(value) {
87
+ return receipt(value) && text(value.body) && ['dashboard','api','autoreply'].includes(value.source)
88
+ && ['simPhoneNumber','requestedSimId','requestedDeviceId','requestedFrom','apiKeyId','error','lastError','dispatchedAt','sentAt','deliveredAt','failedAt'].every(k => nullableText(value[k]))
89
+ && count(value.attempts) && (value.parts === null || count(value.parts)) && text(value.createdAt);
90
+ }
91
+ function sim(value) {
92
+ return object(value) && text(value.id) && !!value.id && text(value.deviceId) && text(value.deviceName) && nullableText(value.phoneNumber) && text(value.carrier) && nullableText(value.label)
93
+ && ['online','enabled','available'].every(k => typeof value[k] === 'boolean') && count(value.hourlyLimit) && count(value.dailyLimit) && object(value.usage) && count(value.usage.hour) && count(value.usage.day);
94
+ }
95
+ function device(value) { return object(value) && text(value.id) && !!value.id && text(value.name) && ['online','offline'].includes(value.status) && (value.battery === null || (count(value.battery) && value.battery <= 100)) && Array.isArray(value.sims) && value.sims.every(sim); }
96
+ function tariff(value) {
97
+ return object(value) && text(value.id) && !!value.id && text(value.code) && object(value.name) && text(value.name.ru) && text(value.name.uz)
98
+ && object(value.description) && text(value.description.ru) && text(value.description.uz) && Number.isSafeInteger(value.sortOrder)
99
+ && ['price','durationDays','includedSegments','maxPhones','overageRate'].every(k => count(value[k])) && value.maxPhones >= 1 && typeof value.isTrial === 'boolean' && typeof value.isPayg === 'boolean';
100
+ }
101
+ function success(data, method, path, input) {
102
+ let valid;
103
+ if (method === 'POST') {
104
+ const n = input.messages ? input.messages.length : 1;
105
+ valid = object(data) && Array.isArray(data.messages) && data.messages.length === n && data.messages.every(receipt) && new Set(data.messages.map(m => m.id)).size === n;
106
+ } else if (path.startsWith('/sms/')) valid = fullMessage(data) && data.id === decodeURIComponent(path.slice(5));
107
+ else if (path === '/tariffs') valid = object(data) && Array.isArray(data.items) && data.items.every(tariff);
108
+ else if (path === '/sims') valid = Array.isArray(data) && data.every(sim);
109
+ else valid = Array.isArray(data) && data.every(device);
110
+ if (!valid) throw new SmschiProtocolError();
111
+ return data;
112
+ }
113
+ async function readBounded(response) {
114
+ const limit = 1024 * 1024;
115
+ if (typeof response.body?.getReader !== 'function') {
116
+ let value; try { value = await response.text(); } catch { throw new SmschiNetworkError(); }
117
+ if (typeof value !== 'string' || new TextEncoder().encode(value).byteLength > limit) throw new SmschiProtocolError();
118
+ return value;
119
+ }
120
+ const reader = response.body.getReader(); const chunks = []; let size = 0;
121
+ try {
122
+ for (;;) {
123
+ const { done, value } = await reader.read();
124
+ if (done) break;
125
+ if (!(value instanceof Uint8Array)) throw new SmschiProtocolError();
126
+ size += value.byteLength;
127
+ if (size > limit) { reader.cancel().catch(() => {}); throw new SmschiProtocolError(); }
128
+ chunks.push(value);
129
+ }
130
+ } catch (error) { if (error instanceof SmschiProtocolError) throw error; throw new SmschiNetworkError(); }
131
+ finally { reader.releaseLock(); }
132
+ const bytes = new Uint8Array(size); let offset = 0;
133
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
134
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw new SmschiProtocolError(); }
135
+ }
136
+ async function parseResponse(response, method, path, input) {
137
+ if (!response || !Number.isInteger(response.status) || typeof response.text !== 'function' || typeof response.headers?.get !== 'function' || (response.status >= 300 && response.status < 400)) throw new SmschiProtocolError();
138
+ const rawText = await readBounded(response);
139
+ let data; try { data = JSON.parse(rawText); } catch { if (response.status >= 200 && response.status < 300) throw new SmschiProtocolError(); }
140
+ if (response.status < 200 || response.status >= 300) {
141
+ const raw = object(data) && object(data.error) ? data.error : {};
142
+ const code = typeof raw.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(raw.code) ? raw.code : 'HTTP_' + response.status;
143
+ throw new SmschiApiError({ status: response.status, code, details: object(raw.details) ? raw.details : undefined,
144
+ retryAfterMs: retryAfter(response.headers.get('Retry-After')),
145
+ rateLimit: { limit: headerInteger(response.headers.get('X-RateLimit-Limit')), remaining: headerInteger(response.headers.get('X-RateLimit-Remaining')) } });
146
+ }
147
+ return success(data, method, path, input);
148
+ }
149
+ class SmschiClient {
150
+ #apiKey; #fetch; #baseUrl; #timeoutMs; #maxRetries; #retryDelayMs;
151
+ constructor(options) {
152
+ keys(options, ['apiKey','baseUrl','timeoutMs','maxRetries','retryDelayMs','fetch'], 'SDK options');
153
+ if (typeof options.apiKey !== 'string' || !/^smk_[\x21-\x7e]+$/.test(options.apiKey)) throw new TypeError('A valid smk_ API key is required');
154
+ if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new TypeError('fetch must be a function');
155
+ if (options.fetch === undefined && typeof globalThis.fetch !== 'function') throw new TypeError('A fetch implementation is required');
156
+ this.#apiKey = options.apiKey;
157
+ this.#fetch = options.fetch || globalThis.fetch.bind(globalThis);
158
+ this.#baseUrl = base(options.baseUrl === undefined ? 'https://smschi.uz' : options.baseUrl);
159
+ this.#timeoutMs = integer(options.timeoutMs === undefined ? 15000 : options.timeoutMs, 1, MAX_TIMER, 'timeoutMs');
160
+ this.#maxRetries = integer(options.maxRetries === undefined ? 0 : options.maxRetries, 0, 3, 'maxRetries');
161
+ this.#retryDelayMs = integer(options.retryDelayMs === undefined ? 250 : options.retryDelayMs, 0, 60000, 'retryDelayMs');
162
+ this.sms = Object.freeze({
163
+ send: async (input, options) => {
164
+ if (object(input) && Object.hasOwn(input, 'messages')) {
165
+ keys(input, ['messages'], 'Batch input');
166
+ return this.sms.sendBatch(input.messages, options);
167
+ }
168
+ return this.#request('POST', '/sms', message(input), options);
169
+ },
170
+ sendBatch: async (messages, options) => {
171
+ if (!Array.isArray(messages) || messages.length < 1 || messages.length > 1000) throw new TypeError('Batch must contain 1..1000 messages');
172
+ return this.#request('POST', '/sms', { messages: Array.from(messages, message) }, options);
173
+ },
174
+ get: async (id, options) => this.#request('GET', '/sms/' + identifier(id), undefined, options),
175
+ wait: async (id, options) => this.#wait(id, options),
176
+ });
177
+ this.devices = Object.freeze({ list: (options) => this.#request('GET', '/devices', undefined, options) });
178
+ this.sims = Object.freeze({ list: (options) => this.#request('GET', '/sims', undefined, options) });
179
+ this.tariffs = Object.freeze({ list: (options) => this.#request('GET', '/tariffs', undefined, options) });
180
+ }
181
+ async #wait(id, value) {
182
+ const path = '/sms/' + identifier(id);
183
+ const options = value === undefined ? {} : value;
184
+ keys(options, ['until','pollIntervalMs','timeoutMs','signal'], 'Wait options');
185
+ const until = options.until === undefined ? 'sent' : options.until;
186
+ if (!['sent','delivered'].includes(until)) throw new TypeError('until must be sent or delivered');
187
+ const interval = integer(options.pollIntervalMs === undefined ? 1000 : options.pollIntervalMs, 1, MAX_TIMER, 'pollIntervalMs');
188
+ const { timeoutMs, signal } = requestOptions({ timeoutMs: options.timeoutMs === undefined ? 60000 : options.timeoutMs, signal: options.signal }, 60000);
189
+ const deadline = performance.now() + timeoutMs;
190
+ return withDeadline(async pollingSignal => {
191
+ for (;;) {
192
+ if (pollingSignal.aborted) throw new SmschiAbortError();
193
+ const remaining = Math.ceil(deadline - performance.now());
194
+ if (remaining <= 0) throw new SmschiTimeoutError();
195
+ const result = await this.#request('GET', path, undefined, { timeoutMs: Math.min(this.#timeoutMs, remaining), signal: pollingSignal });
196
+ if (performance.now() >= deadline) throw new SmschiTimeoutError();
197
+ if (result.status === 'failed' || result.status === 'delivered' || (until === 'sent' && result.status === 'sent')) return result;
198
+ await pause(interval, pollingSignal);
199
+ }
200
+ }, timeoutMs, signal);
201
+ }
202
+ async #request(method, path, input, options) {
203
+ const { timeoutMs, signal } = requestOptions(options, this.#timeoutMs);
204
+ const deadline = performance.now() + timeoutMs;
205
+ return withDeadline(async transportSignal => {
206
+ const headers = { Accept: 'application/json' };
207
+ if (path !== '/tariffs') headers['X-API-Key'] = this.#apiKey;
208
+ if (method === 'POST') headers['Content-Type'] = 'application/json';
209
+ for (let attempt = 0; ; attempt++) {
210
+ if (performance.now() >= deadline) throw new SmschiTimeoutError();
211
+ if (transportSignal.aborted) throw new SmschiAbortError();
212
+ try {
213
+ let response;
214
+ try { response = await this.#fetch(this.#baseUrl + '/api/v1' + path, {
215
+ method, redirect: 'error', headers, body: input === undefined ? undefined : JSON.stringify(input), signal: transportSignal,
216
+ }); } catch { throw new SmschiNetworkError(); }
217
+ const result = await parseResponse(response, method, path, input);
218
+ if (performance.now() >= deadline) throw new SmschiTimeoutError();
219
+ return result;
220
+ } catch (error) {
221
+ const transient = error instanceof SmschiNetworkError || (error instanceof SmschiApiError && [429,500,502,503,504].includes(error.status));
222
+ if (method !== 'GET' || !transient || attempt >= this.#maxRetries) throw error;
223
+ if (transportSignal.aborted) throw new SmschiAbortError();
224
+ const remaining = deadline - performance.now();
225
+ if (remaining <= 0) throw new SmschiTimeoutError();
226
+ const delay = Math.max(this.#retryDelayMs * 2 ** attempt, error.retryAfterMs ?? 0);
227
+ if (delay > 60000 || delay >= remaining) throw error;
228
+ await pause(delay, transportSignal);
229
+ }
230
+ }
231
+ }, timeoutMs, signal);
232
+ }
233
+ }
234
+ module.exports = { SmschiClient, SmschiApiError, SmschiProtocolError, SmschiNetworkError, SmschiTimeoutError, SmschiAbortError };
@@ -0,0 +1,156 @@
1
+ /** SMSchi SDK. Requires Node.js >=22 and standard fetch/AbortSignal types. */
2
+ export type MessageStatus = 'queued' | 'dispatched' | 'sent' | 'delivered' | 'failed';
3
+ export type MessageSource = 'dashboard' | 'api' | 'autoreply';
4
+
5
+ export interface SendSmsInput {
6
+ /** 7–15 digits with optional leading +; spaces, hyphens, dots and parentheses accepted. */
7
+ to: string;
8
+ /** 1–1600 JavaScript UTF-16 code units; not an SMS segment limit. */
9
+ body: string;
10
+ simId?: string | null;
11
+ deviceId?: string | null;
12
+ from?: string | null;
13
+ }
14
+
15
+ export interface SendSmsBatchInput {
16
+ /** 1–1000 messages in one POST; the SDK never chunks or retries a write. */
17
+ messages: SendSmsInput[];
18
+ }
19
+
20
+ export interface AcceptedMessage {
21
+ id: string;
22
+ to: string;
23
+ status: MessageStatus;
24
+ simId: string | null;
25
+ deviceId: string | null;
26
+ }
27
+
28
+ /** HTTP 202 means accepted, not sent or delivered. */
29
+ export interface SendSmsResponse { messages: AcceptedMessage[]; }
30
+
31
+ /** Full message returned by GET /api/v1/sms/:id. Timestamps are strings, not Date objects. */
32
+ export interface Message extends AcceptedMessage {
33
+ body: string;
34
+ source: MessageSource;
35
+ simPhoneNumber: string | null;
36
+ requestedSimId: string | null;
37
+ requestedDeviceId: string | null;
38
+ requestedFrom: string | null;
39
+ apiKeyId: string | null;
40
+ attempts: number;
41
+ error: string | null;
42
+ lastError: string | null;
43
+ parts: number | null;
44
+ createdAt: string;
45
+ dispatchedAt: string | null;
46
+ sentAt: string | null;
47
+ deliveredAt: string | null;
48
+ failedAt: string | null;
49
+ }
50
+
51
+ /** Public API SIM shape, not the larger dashboard SIM shape. */
52
+ export interface Sim {
53
+ id: string;
54
+ phoneNumber: string | null;
55
+ carrier: string;
56
+ label: string | null;
57
+ deviceId: string;
58
+ deviceName: string;
59
+ online: boolean;
60
+ enabled: boolean;
61
+ available: boolean;
62
+ hourlyLimit: number;
63
+ dailyLimit: number;
64
+ usage: { hour: number; day: number };
65
+ }
66
+
67
+ export interface Device {
68
+ id: string;
69
+ name: string;
70
+ status: 'online' | 'offline';
71
+ battery: number | null;
72
+ sims: Sim[];
73
+ }
74
+
75
+ export interface LocalizedText { uz: string; ru: string; }
76
+ export interface Tariff {
77
+ id: string;
78
+ code: string;
79
+ name: LocalizedText;
80
+ description: LocalizedText;
81
+ price: number;
82
+ durationDays: number;
83
+ includedSegments: number;
84
+ maxPhones: number;
85
+ overageRate: number;
86
+ sortOrder: number;
87
+ isTrial: boolean;
88
+ isPayg: boolean;
89
+ }
90
+ export interface TariffListResponse { items: Tariff[]; }
91
+
92
+ export interface RequestOptions {
93
+ /** Positive finite timeout in milliseconds; default is client timeoutMs. */
94
+ timeoutMs?: number;
95
+ signal?: AbortSignal;
96
+ }
97
+
98
+ export interface WaitOptions {
99
+ /** Default sent. failed always terminates polling and is returned, not thrown. */
100
+ until?: 'sent' | 'delivered';
101
+ /** Positive finite polling interval in milliseconds; default 1000. */
102
+ pollIntervalMs?: number;
103
+ /** Overall polling deadline in milliseconds; default 60000. */
104
+ timeoutMs?: number;
105
+ signal?: AbortSignal;
106
+ }
107
+
108
+ export interface SmschiClientOptions {
109
+ /** Required smk_ prefix followed by one or more printable non-whitespace ASCII characters (U+0021–U+007E). Sent as X-API-Key, never a bearer token. */
110
+ apiKey: string;
111
+ /** Default https://smschi.uz. Origin + optional deployment prefix, without /api/v1. */
112
+ baseUrl?: string;
113
+ /** Default 15000 ms; positive finite number. */
114
+ timeoutMs?: number;
115
+ /** Integer 0–3; default 0. Only GET requests may be retried. */
116
+ maxRetries?: number;
117
+ /** Integer 0–60000 ms, default 250. Never retries earlier than Retry-After; gives up if delay exceeds 60000 ms or the remaining deadline. */
118
+ retryDelayMs?: number;
119
+ fetch?: typeof globalThis.fetch;
120
+ }
121
+
122
+ export interface SmsResource {
123
+ send(input: SendSmsInput | SendSmsBatchInput, options?: RequestOptions): Promise<SendSmsResponse>;
124
+ sendBatch(messages: SendSmsInput[], options?: RequestOptions): Promise<SendSmsResponse>;
125
+ get(id: string, options?: RequestOptions): Promise<Message>;
126
+ /** sent accepts sent/delivered/failed; delivered accepts delivered/failed. */
127
+ wait(id: string, options?: WaitOptions): Promise<Message>;
128
+ }
129
+
130
+ export class SmschiClient {
131
+ constructor(options: SmschiClientOptions);
132
+ readonly sms: SmsResource;
133
+ readonly sims: { list(options?: RequestOptions): Promise<Sim[]> };
134
+ readonly devices: { list(options?: RequestOptions): Promise<Device[]> };
135
+ /** Public HTTP endpoint; constructor still requires an API key. */
136
+ readonly tariffs: { list(options?: RequestOptions): Promise<TariffListResponse> };
137
+ }
138
+
139
+ export interface RateLimit { limit: number | null; remaining: number | null; }
140
+
141
+ /** Safe message; details may contain sensitive server data. Do not log the whole error. */
142
+ export class SmschiApiError extends Error {
143
+ constructor(options: { status: number; code: string; details?: unknown; retryAfterMs?: number | null; rateLimit?: RateLimit });
144
+ readonly status: number;
145
+ readonly code: string;
146
+ readonly details: unknown;
147
+ /** Numeric Retry-After milliseconds are rounded up, capped at Number.MAX_SAFE_INTEGER; null means absent/invalid. */
148
+ readonly retryAfterMs: number | null;
149
+ readonly rateLimit: RateLimit;
150
+ }
151
+ export class SmschiNetworkError extends Error { readonly code: 'NETWORK_ERROR'; }
152
+ /** A POST timeout does NOT mean the SMS was rejected. Do not blindly resend. */
153
+ export class SmschiTimeoutError extends Error { readonly code: 'TIMEOUT'; }
154
+ /** A POST abort does NOT cancel a message already accepted by the server. */
155
+ export class SmschiAbortError extends Error { readonly code: 'ABORTED'; }
156
+ export class SmschiProtocolError extends Error { readonly code: 'INVALID_RESPONSE'; }
@@ -0,0 +1,156 @@
1
+ /** SMSchi SDK. Requires Node.js >=22 and standard fetch/AbortSignal types. */
2
+ export type MessageStatus = 'queued' | 'dispatched' | 'sent' | 'delivered' | 'failed';
3
+ export type MessageSource = 'dashboard' | 'api' | 'autoreply';
4
+
5
+ export interface SendSmsInput {
6
+ /** 7–15 digits with optional leading +; spaces, hyphens, dots and parentheses accepted. */
7
+ to: string;
8
+ /** 1–1600 JavaScript UTF-16 code units; not an SMS segment limit. */
9
+ body: string;
10
+ simId?: string | null;
11
+ deviceId?: string | null;
12
+ from?: string | null;
13
+ }
14
+
15
+ export interface SendSmsBatchInput {
16
+ /** 1–1000 messages in one POST; the SDK never chunks or retries a write. */
17
+ messages: SendSmsInput[];
18
+ }
19
+
20
+ export interface AcceptedMessage {
21
+ id: string;
22
+ to: string;
23
+ status: MessageStatus;
24
+ simId: string | null;
25
+ deviceId: string | null;
26
+ }
27
+
28
+ /** HTTP 202 means accepted, not sent or delivered. */
29
+ export interface SendSmsResponse { messages: AcceptedMessage[]; }
30
+
31
+ /** Full message returned by GET /api/v1/sms/:id. Timestamps are strings, not Date objects. */
32
+ export interface Message extends AcceptedMessage {
33
+ body: string;
34
+ source: MessageSource;
35
+ simPhoneNumber: string | null;
36
+ requestedSimId: string | null;
37
+ requestedDeviceId: string | null;
38
+ requestedFrom: string | null;
39
+ apiKeyId: string | null;
40
+ attempts: number;
41
+ error: string | null;
42
+ lastError: string | null;
43
+ parts: number | null;
44
+ createdAt: string;
45
+ dispatchedAt: string | null;
46
+ sentAt: string | null;
47
+ deliveredAt: string | null;
48
+ failedAt: string | null;
49
+ }
50
+
51
+ /** Public API SIM shape, not the larger dashboard SIM shape. */
52
+ export interface Sim {
53
+ id: string;
54
+ phoneNumber: string | null;
55
+ carrier: string;
56
+ label: string | null;
57
+ deviceId: string;
58
+ deviceName: string;
59
+ online: boolean;
60
+ enabled: boolean;
61
+ available: boolean;
62
+ hourlyLimit: number;
63
+ dailyLimit: number;
64
+ usage: { hour: number; day: number };
65
+ }
66
+
67
+ export interface Device {
68
+ id: string;
69
+ name: string;
70
+ status: 'online' | 'offline';
71
+ battery: number | null;
72
+ sims: Sim[];
73
+ }
74
+
75
+ export interface LocalizedText { uz: string; ru: string; }
76
+ export interface Tariff {
77
+ id: string;
78
+ code: string;
79
+ name: LocalizedText;
80
+ description: LocalizedText;
81
+ price: number;
82
+ durationDays: number;
83
+ includedSegments: number;
84
+ maxPhones: number;
85
+ overageRate: number;
86
+ sortOrder: number;
87
+ isTrial: boolean;
88
+ isPayg: boolean;
89
+ }
90
+ export interface TariffListResponse { items: Tariff[]; }
91
+
92
+ export interface RequestOptions {
93
+ /** Positive finite timeout in milliseconds; default is client timeoutMs. */
94
+ timeoutMs?: number;
95
+ signal?: AbortSignal;
96
+ }
97
+
98
+ export interface WaitOptions {
99
+ /** Default sent. failed always terminates polling and is returned, not thrown. */
100
+ until?: 'sent' | 'delivered';
101
+ /** Positive finite polling interval in milliseconds; default 1000. */
102
+ pollIntervalMs?: number;
103
+ /** Overall polling deadline in milliseconds; default 60000. */
104
+ timeoutMs?: number;
105
+ signal?: AbortSignal;
106
+ }
107
+
108
+ export interface SmschiClientOptions {
109
+ /** Required smk_ prefix followed by one or more printable non-whitespace ASCII characters (U+0021–U+007E). Sent as X-API-Key, never a bearer token. */
110
+ apiKey: string;
111
+ /** Default https://smschi.uz. Origin + optional deployment prefix, without /api/v1. */
112
+ baseUrl?: string;
113
+ /** Default 15000 ms; positive finite number. */
114
+ timeoutMs?: number;
115
+ /** Integer 0–3; default 0. Only GET requests may be retried. */
116
+ maxRetries?: number;
117
+ /** Integer 0–60000 ms, default 250. Never retries earlier than Retry-After; gives up if delay exceeds 60000 ms or the remaining deadline. */
118
+ retryDelayMs?: number;
119
+ fetch?: typeof globalThis.fetch;
120
+ }
121
+
122
+ export interface SmsResource {
123
+ send(input: SendSmsInput | SendSmsBatchInput, options?: RequestOptions): Promise<SendSmsResponse>;
124
+ sendBatch(messages: SendSmsInput[], options?: RequestOptions): Promise<SendSmsResponse>;
125
+ get(id: string, options?: RequestOptions): Promise<Message>;
126
+ /** sent accepts sent/delivered/failed; delivered accepts delivered/failed. */
127
+ wait(id: string, options?: WaitOptions): Promise<Message>;
128
+ }
129
+
130
+ export class SmschiClient {
131
+ constructor(options: SmschiClientOptions);
132
+ readonly sms: SmsResource;
133
+ readonly sims: { list(options?: RequestOptions): Promise<Sim[]> };
134
+ readonly devices: { list(options?: RequestOptions): Promise<Device[]> };
135
+ /** Public HTTP endpoint; constructor still requires an API key. */
136
+ readonly tariffs: { list(options?: RequestOptions): Promise<TariffListResponse> };
137
+ }
138
+
139
+ export interface RateLimit { limit: number | null; remaining: number | null; }
140
+
141
+ /** Safe message; details may contain sensitive server data. Do not log the whole error. */
142
+ export class SmschiApiError extends Error {
143
+ constructor(options: { status: number; code: string; details?: unknown; retryAfterMs?: number | null; rateLimit?: RateLimit });
144
+ readonly status: number;
145
+ readonly code: string;
146
+ readonly details: unknown;
147
+ /** Numeric Retry-After milliseconds are rounded up, capped at Number.MAX_SAFE_INTEGER; null means absent/invalid. */
148
+ readonly retryAfterMs: number | null;
149
+ readonly rateLimit: RateLimit;
150
+ }
151
+ export class SmschiNetworkError extends Error { readonly code: 'NETWORK_ERROR'; }
152
+ /** A POST timeout does NOT mean the SMS was rejected. Do not blindly resend. */
153
+ export class SmschiTimeoutError extends Error { readonly code: 'TIMEOUT'; }
154
+ /** A POST abort does NOT cancel a message already accepted by the server. */
155
+ export class SmschiAbortError extends Error { readonly code: 'ABORTED'; }
156
+ export class SmschiProtocolError extends Error { readonly code: 'INVALID_RESPONSE'; }
@@ -0,0 +1,156 @@
1
+ /** SMSchi SDK. Requires Node.js >=22 and standard fetch/AbortSignal types. */
2
+ export type MessageStatus = 'queued' | 'dispatched' | 'sent' | 'delivered' | 'failed';
3
+ export type MessageSource = 'dashboard' | 'api' | 'autoreply';
4
+
5
+ export interface SendSmsInput {
6
+ /** 7–15 digits with optional leading +; spaces, hyphens, dots and parentheses accepted. */
7
+ to: string;
8
+ /** 1–1600 JavaScript UTF-16 code units; not an SMS segment limit. */
9
+ body: string;
10
+ simId?: string | null;
11
+ deviceId?: string | null;
12
+ from?: string | null;
13
+ }
14
+
15
+ export interface SendSmsBatchInput {
16
+ /** 1–1000 messages in one POST; the SDK never chunks or retries a write. */
17
+ messages: SendSmsInput[];
18
+ }
19
+
20
+ export interface AcceptedMessage {
21
+ id: string;
22
+ to: string;
23
+ status: MessageStatus;
24
+ simId: string | null;
25
+ deviceId: string | null;
26
+ }
27
+
28
+ /** HTTP 202 means accepted, not sent or delivered. */
29
+ export interface SendSmsResponse { messages: AcceptedMessage[]; }
30
+
31
+ /** Full message returned by GET /api/v1/sms/:id. Timestamps are strings, not Date objects. */
32
+ export interface Message extends AcceptedMessage {
33
+ body: string;
34
+ source: MessageSource;
35
+ simPhoneNumber: string | null;
36
+ requestedSimId: string | null;
37
+ requestedDeviceId: string | null;
38
+ requestedFrom: string | null;
39
+ apiKeyId: string | null;
40
+ attempts: number;
41
+ error: string | null;
42
+ lastError: string | null;
43
+ parts: number | null;
44
+ createdAt: string;
45
+ dispatchedAt: string | null;
46
+ sentAt: string | null;
47
+ deliveredAt: string | null;
48
+ failedAt: string | null;
49
+ }
50
+
51
+ /** Public API SIM shape, not the larger dashboard SIM shape. */
52
+ export interface Sim {
53
+ id: string;
54
+ phoneNumber: string | null;
55
+ carrier: string;
56
+ label: string | null;
57
+ deviceId: string;
58
+ deviceName: string;
59
+ online: boolean;
60
+ enabled: boolean;
61
+ available: boolean;
62
+ hourlyLimit: number;
63
+ dailyLimit: number;
64
+ usage: { hour: number; day: number };
65
+ }
66
+
67
+ export interface Device {
68
+ id: string;
69
+ name: string;
70
+ status: 'online' | 'offline';
71
+ battery: number | null;
72
+ sims: Sim[];
73
+ }
74
+
75
+ export interface LocalizedText { uz: string; ru: string; }
76
+ export interface Tariff {
77
+ id: string;
78
+ code: string;
79
+ name: LocalizedText;
80
+ description: LocalizedText;
81
+ price: number;
82
+ durationDays: number;
83
+ includedSegments: number;
84
+ maxPhones: number;
85
+ overageRate: number;
86
+ sortOrder: number;
87
+ isTrial: boolean;
88
+ isPayg: boolean;
89
+ }
90
+ export interface TariffListResponse { items: Tariff[]; }
91
+
92
+ export interface RequestOptions {
93
+ /** Positive finite timeout in milliseconds; default is client timeoutMs. */
94
+ timeoutMs?: number;
95
+ signal?: AbortSignal;
96
+ }
97
+
98
+ export interface WaitOptions {
99
+ /** Default sent. failed always terminates polling and is returned, not thrown. */
100
+ until?: 'sent' | 'delivered';
101
+ /** Positive finite polling interval in milliseconds; default 1000. */
102
+ pollIntervalMs?: number;
103
+ /** Overall polling deadline in milliseconds; default 60000. */
104
+ timeoutMs?: number;
105
+ signal?: AbortSignal;
106
+ }
107
+
108
+ export interface SmschiClientOptions {
109
+ /** Required smk_ prefix followed by one or more printable non-whitespace ASCII characters (U+0021–U+007E). Sent as X-API-Key, never a bearer token. */
110
+ apiKey: string;
111
+ /** Default https://smschi.uz. Origin + optional deployment prefix, without /api/v1. */
112
+ baseUrl?: string;
113
+ /** Default 15000 ms; positive finite number. */
114
+ timeoutMs?: number;
115
+ /** Integer 0–3; default 0. Only GET requests may be retried. */
116
+ maxRetries?: number;
117
+ /** Integer 0–60000 ms, default 250. Never retries earlier than Retry-After; gives up if delay exceeds 60000 ms or the remaining deadline. */
118
+ retryDelayMs?: number;
119
+ fetch?: typeof globalThis.fetch;
120
+ }
121
+
122
+ export interface SmsResource {
123
+ send(input: SendSmsInput | SendSmsBatchInput, options?: RequestOptions): Promise<SendSmsResponse>;
124
+ sendBatch(messages: SendSmsInput[], options?: RequestOptions): Promise<SendSmsResponse>;
125
+ get(id: string, options?: RequestOptions): Promise<Message>;
126
+ /** sent accepts sent/delivered/failed; delivered accepts delivered/failed. */
127
+ wait(id: string, options?: WaitOptions): Promise<Message>;
128
+ }
129
+
130
+ export class SmschiClient {
131
+ constructor(options: SmschiClientOptions);
132
+ readonly sms: SmsResource;
133
+ readonly sims: { list(options?: RequestOptions): Promise<Sim[]> };
134
+ readonly devices: { list(options?: RequestOptions): Promise<Device[]> };
135
+ /** Public HTTP endpoint; constructor still requires an API key. */
136
+ readonly tariffs: { list(options?: RequestOptions): Promise<TariffListResponse> };
137
+ }
138
+
139
+ export interface RateLimit { limit: number | null; remaining: number | null; }
140
+
141
+ /** Safe message; details may contain sensitive server data. Do not log the whole error. */
142
+ export class SmschiApiError extends Error {
143
+ constructor(options: { status: number; code: string; details?: unknown; retryAfterMs?: number | null; rateLimit?: RateLimit });
144
+ readonly status: number;
145
+ readonly code: string;
146
+ readonly details: unknown;
147
+ /** Numeric Retry-After milliseconds are rounded up, capped at Number.MAX_SAFE_INTEGER; null means absent/invalid. */
148
+ readonly retryAfterMs: number | null;
149
+ readonly rateLimit: RateLimit;
150
+ }
151
+ export class SmschiNetworkError extends Error { readonly code: 'NETWORK_ERROR'; }
152
+ /** A POST timeout does NOT mean the SMS was rejected. Do not blindly resend. */
153
+ export class SmschiTimeoutError extends Error { readonly code: 'TIMEOUT'; }
154
+ /** A POST abort does NOT cancel a message already accepted by the server. */
155
+ export class SmschiAbortError extends Error { readonly code: 'ABORTED'; }
156
+ export class SmschiProtocolError extends Error { readonly code: 'INVALID_RESPONSE'; }
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import sdk from './index.cjs';
2
+ export const { SmschiClient, SmschiApiError, SmschiProtocolError, SmschiNetworkError, SmschiTimeoutError, SmschiAbortError } = sdk;
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+ const { SmschiClient, SmschiApiError, SmschiNetworkError, SmschiTimeoutError, SmschiAbortError, SmschiProtocolError } = require('@smschi/sdk');
3
+
4
+ // This example sends a real SMS only with explicit --send consent.
5
+ async function main() {
6
+ if (!process.argv.includes('--send')) {
7
+ throw new Error('No request made. Add --send only after configuring private test credentials.');
8
+ }
9
+ const apiKey = process.env.SMSCHI_API_KEY;
10
+ const to = process.env.SMSCHI_TO;
11
+ if (!apiKey || !to || apiKey.includes('PLACEHOLDER') || to.includes('PLACEHOLDER')) {
12
+ throw new Error('Set private SMSCHI_API_KEY and SMSCHI_TO; do not use placeholders.');
13
+ }
14
+ const client = new SmschiClient({ apiKey, maxRetries: 0 });
15
+ const result = await client.sms.send({ to, body: 'Тест интеграции SMSchi' });
16
+ const accepted = result.messages[0];
17
+ // Keep the id for reconciliation if later polling fails. Never log phone/body/key.
18
+ console.log({ id: accepted.id, status: accepted.status });
19
+ const message = await client.sms.wait(accepted.id, {
20
+ until: 'sent', timeoutMs: 60000, pollIntervalMs: 1000,
21
+ signal: AbortSignal.timeout(65000),
22
+ });
23
+ console.log({ id: message.id, status: message.status });
24
+ if (message.status === 'failed') process.exitCode = 1;
25
+ }
26
+
27
+ main().catch(error => {
28
+ if (error instanceof SmschiApiError) {
29
+ // details can contain sensitive data. Never log error or error.details wholesale.
30
+ console.error({ status: error.status, code: error.code });
31
+ } else if (error instanceof SmschiTimeoutError || error instanceof SmschiAbortError || error instanceof SmschiNetworkError) {
32
+ console.error({ code: error.code });
33
+ console.error('Результат отправки может быть неизвестен. Не повторяйте SMS автоматически.');
34
+ } else if (error instanceof SmschiProtocolError) {
35
+ console.error({ code: error.code });
36
+ console.error('Некорректный ответ; для POST результат отправки может быть неизвестен.');
37
+ } else {
38
+ // Do not dump arbitrary errors: injected transports may include request data.
39
+ console.error('Пример остановлен. Проверьте флаг --send и приватные переменные окружения.');
40
+ }
41
+ process.exitCode = 1;
42
+ });
@@ -0,0 +1,41 @@
1
+ import { SmschiClient, SmschiApiError, SmschiNetworkError, SmschiTimeoutError, SmschiAbortError, SmschiProtocolError } from '@smschi/sdk';
2
+
3
+ // This example sends a real SMS only with explicit --send consent.
4
+ async function main() {
5
+ if (!process.argv.includes('--send')) {
6
+ throw new Error('No request made. Add --send only after configuring private test credentials.');
7
+ }
8
+ const apiKey = process.env.SMSCHI_API_KEY;
9
+ const to = process.env.SMSCHI_TO;
10
+ if (!apiKey || !to || apiKey.includes('PLACEHOLDER') || to.includes('PLACEHOLDER')) {
11
+ throw new Error('Set private SMSCHI_API_KEY and SMSCHI_TO; do not use placeholders.');
12
+ }
13
+ const client = new SmschiClient({ apiKey, maxRetries: 0 });
14
+ const result = await client.sms.send({ to, body: 'Тест интеграции SMSchi' });
15
+ const accepted = result.messages[0];
16
+ // Keep the id for reconciliation if later polling fails. Never log phone/body/key.
17
+ console.log({ id: accepted.id, status: accepted.status });
18
+ const message = await client.sms.wait(accepted.id, {
19
+ until: 'sent', timeoutMs: 60000, pollIntervalMs: 1000,
20
+ signal: AbortSignal.timeout(65000),
21
+ });
22
+ console.log({ id: message.id, status: message.status });
23
+ if (message.status === 'failed') process.exitCode = 1;
24
+ }
25
+
26
+ main().catch(error => {
27
+ if (error instanceof SmschiApiError) {
28
+ // details can contain sensitive data. Never log error or error.details wholesale.
29
+ console.error({ status: error.status, code: error.code });
30
+ } else if (error instanceof SmschiTimeoutError || error instanceof SmschiAbortError || error instanceof SmschiNetworkError) {
31
+ console.error({ code: error.code });
32
+ console.error('Результат отправки может быть неизвестен. Не повторяйте SMS автоматически.');
33
+ } else if (error instanceof SmschiProtocolError) {
34
+ console.error({ code: error.code });
35
+ console.error('Некорректный ответ; для POST результат отправки может быть неизвестен.');
36
+ } else {
37
+ // Do not dump arbitrary errors: injected transports may include request data.
38
+ console.error('Пример остановлен. Проверьте флаг --send и приватные переменные окружения.');
39
+ }
40
+ process.exitCode = 1;
41
+ });
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@smschi/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Server-side JavaScript SDK for the SMSchi public API",
5
+ "license": "MIT",
6
+ "type": "commonjs",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.mts",
14
+ "default": "./dist/index.mjs"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist/",
25
+ "README.md",
26
+ "LICENSE",
27
+ "examples/"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "scripts": {
33
+ "build": "node scripts/build.cjs",
34
+ "test": "node --test test/*.test.cjs",
35
+ "prepack": "npm run build"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/Ipilot7/smschi-sdk.git"
40
+ },
41
+ "homepage": "https://github.com/Ipilot7/smschi-sdk#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/Ipilot7/smschi-sdk/issues"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "registry": "https://registry.npmjs.org/"
48
+ }
49
+ }