@xmodeai/sdk 0.1.0

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 xMode
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 ADDED
@@ -0,0 +1,210 @@
1
+ # @xmodeai/sdk
2
+
3
+ Official TypeScript / JavaScript SDK for the [xMode API](https://dashboard.xmode.ai/docs) — AI image and video generation.
4
+
5
+ - **Zero runtime dependencies.** Uses the platform `fetch` — works on Node 18+, Bun, Deno, Cloudflare Workers and other edge runtimes.
6
+ - **Async-first.** Submit a job, then poll or receive a webhook. Helpers do the polling for you.
7
+ - **Forward-compatible.** New models and fields the API adds later never break an installed version.
8
+ - **Typed.** First-class TypeScript types with autocomplete for known models, tolerant of everything else.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @xmodeai/sdk
14
+ ```
15
+
16
+ ## Quickstart
17
+
18
+ ```ts
19
+ import XMode from '@xmodeai/sdk';
20
+
21
+ const client = new XMode({ apiKey: process.env.XMODE_API_KEY });
22
+
23
+ // Submit and wait for the result in one call.
24
+ const result = await client.generations.createAndWait({
25
+ endUserEmail: 'alice@your-product.com',
26
+ model: 'xSD4.5',
27
+ prompt: 'Editorial photo of a red panda astronaut, studio lighting, 85mm',
28
+ });
29
+
30
+ if (result.status === 'succeeded') {
31
+ console.log(result.images[0]?.url); // signed URL, valid ~23h — download or re-host
32
+ } else if (result.status === 'failed') {
33
+ console.error(result.error.code, result.error.message);
34
+ }
35
+ ```
36
+
37
+ The API key is read from the `XMODE_API_KEY` environment variable when you don't
38
+ pass `apiKey` explicitly.
39
+
40
+ ## Polling vs. webhooks
41
+
42
+ `createAndWait` polls for you (every 5s by default) and resolves once the job
43
+ reaches a terminal status. If you'd rather drive it yourself:
44
+
45
+ ```ts
46
+ const queued = await client.generations.create({ endUserEmail, model: 'xSD4.5', prompt });
47
+ // ... later
48
+ const record = await client.generations.get(queued.requestId);
49
+ // or poll an existing job until terminal:
50
+ const done = await client.generations.wait(queued.requestId, { pollInterval: 5000 });
51
+ ```
52
+
53
+ For production, prefer **webhooks**: pass `webhookUrl` to `create` and verify the
54
+ delivery (see below) instead of polling.
55
+
56
+ > `createAndWait` / `wait` **return** the terminal record — including `failed`
57
+ > and `expired`. They only throw `XModePollTimeoutError` if the wait budget
58
+ > (default 10 min for images, 20 min for videos) elapses first.
59
+
60
+ ## Videos
61
+
62
+ ```ts
63
+ const video = await client.videos.createAndWait({
64
+ endUserEmail: 'alice@your-product.com',
65
+ model: 'xW2.7S',
66
+ prompt: 'camera slowly pushing in, gentle motion',
67
+ image: 'https://your-cdn.example.com/input.png',
68
+ resolution: '1080p',
69
+ duration: 5,
70
+ });
71
+
72
+ if (video.status === 'succeeded') console.log(video.videos[0]?.url);
73
+ ```
74
+
75
+ ## Verifying webhooks
76
+
77
+ The webhook helper is published at the `@xmodeai/sdk/webhooks` subpath and uses Web
78
+ Crypto, so it runs on Node and every edge runtime. **Pass the raw request body**
79
+ — do not re-serialize the parsed JSON.
80
+
81
+ ```ts
82
+ import { verifyWebhook } from '@xmodeai/sdk/webhooks';
83
+
84
+ // Example: a framework that gives you the raw body string.
85
+ const { event } = await verifyWebhook({
86
+ payload: rawBody,
87
+ headers: request.headers,
88
+ secret: process.env.XMODE_WEBHOOK_SECRET,
89
+ });
90
+
91
+ if (event.status === 'succeeded') {
92
+ // event is the same shape as generations.get / videos.get
93
+ }
94
+ ```
95
+
96
+ Verification fails (throws `WebhookVerificationError` with a `reason`) on a bad
97
+ signature, a timestamp outside the 5-minute tolerance, or missing headers.
98
+
99
+ ## Pagination
100
+
101
+ List methods return a value you can `await` for one page or `for await` to
102
+ stream every item across all pages.
103
+
104
+ ```ts
105
+ const firstPage = await client.generations.list({ pageSize: 50 });
106
+
107
+ for await (const generation of client.generations.list({ status: 'failed' })) {
108
+ console.log(generation.requestId);
109
+ }
110
+ ```
111
+
112
+ ## Balance and end-users
113
+
114
+ ```ts
115
+ const { xTokens } = await client.balance.get();
116
+
117
+ await client.endUsers.block('alice@your-product.com');
118
+ await client.endUsers.unblock('alice@your-product.com');
119
+ await client.endUsers.delete('alice@your-product.com'); // 409 ConflictError if jobs are pending
120
+ ```
121
+
122
+ ## Error handling
123
+
124
+ Every API error is an instance of `XModeAPIError`, subclassed by the stable
125
+ error `code`:
126
+
127
+ | Class | Code | HTTP |
128
+ |---|---|---|
129
+ | `ValidationError` | `validation_error` | 400 |
130
+ | `AuthenticationError` | `unauthorized`, `account_blocked` | 401 |
131
+ | `PaymentRequiredError` | `payment_required` | 402 |
132
+ | `PermissionDeniedError` | `forbidden` | 403 |
133
+ | `NotFoundError` | `not_found` | 404 |
134
+ | `ConflictError` | `conflict` | 409 |
135
+ | `ContentPolicyError` | `content_policy` | 422 |
136
+ | `RateLimitError` | `rate_limited` | 429 |
137
+ | `ProviderError` | `provider_error`, `provider_timeout` | 5xx |
138
+ | `InternalServerError` | `internal_error` | 5xx |
139
+
140
+ ```ts
141
+ import { RateLimitError, ContentPolicyError } from '@xmodeai/sdk';
142
+
143
+ try {
144
+ await client.generations.create({ endUserEmail, model: 'xSD4.5', prompt });
145
+ } catch (err) {
146
+ if (err instanceof ContentPolicyError) {/* prompt was rejected */}
147
+ else if (err instanceof RateLimitError) {/* back off; err.retryAfter is in seconds */}
148
+ else throw err;
149
+ }
150
+ ```
151
+
152
+ Network failures throw `APIConnectionError` / `APIConnectionTimeoutError`. An
153
+ unrecognized error code yields a plain `XModeAPIError` rather than crashing, so a
154
+ new server-side code never breaks your handling.
155
+
156
+ ## Retries
157
+
158
+ Retryable requests use exponential backoff with jitter and honor `Retry-After`.
159
+ By default:
160
+
161
+ - **GET** and idempotent operations (`block`, `unblock`, `delete`) retry on
162
+ network errors, `408`, `429` and `5xx` (default `maxRetries: 2`).
163
+ - **`generations.create` / `videos.create` retry only on `429`.** They debit
164
+ xTokens and have no idempotency key, so a timed-out create is never retried
165
+ automatically — it might have succeeded server-side.
166
+
167
+ ## Using new API features before they're in the SDK
168
+
169
+ A new model that uses an existing endpoint just works — `model` accepts any
170
+ string. For a brand-new parameter or endpoint that isn't typed yet, use the
171
+ low-level escape hatch (same auth, retry and error handling):
172
+
173
+ ```ts
174
+ await client.request({
175
+ method: 'POST',
176
+ path: '/v1/videos',
177
+ body: { endUserEmail, model: 'xSV2.0', prompt, image, cameraMotion: 'orbit' },
178
+ });
179
+ ```
180
+
181
+ ## Configuration
182
+
183
+ ```ts
184
+ new XMode({
185
+ apiKey: '...', // default: process.env.XMODE_API_KEY
186
+ baseUrl: '...', // default: https://api.xmode.ai
187
+ timeout: 30_000, // per-attempt timeout in ms
188
+ maxRetries: 2, // automatic retries for retryable requests
189
+ fetch: customFetch, // custom fetch (tests / older runtimes)
190
+ defaultHeaders: { ... }, // sent with every request
191
+ });
192
+ ```
193
+
194
+ > A custom `baseUrl` receives your `Authorization: Bearer` key on every request —
195
+ > only point it at an xMode-operated host.
196
+
197
+ ## Runtime support
198
+
199
+ Node 18.17+, Bun, Deno, Cloudflare Workers and other `fetch`-capable runtimes.
200
+ The SDK can run in a browser, but doing so exposes your API key — keep keys
201
+ server-side.
202
+
203
+ ## Versioning
204
+
205
+ Pre-1.0, breaking changes bump the **minor** version and additive changes bump
206
+ the **patch** version. From 1.0.0 onward the SDK follows standard semver.
207
+
208
+ ## License
209
+
210
+ MIT