diffio 0.4.63 → 1.0.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.
Files changed (60) hide show
  1. package/README.md +208 -296
  2. package/dist/Client.d.ts +85 -148
  3. package/dist/Client.js +73 -798
  4. package/dist/api/resources/account.d.ts +38 -0
  5. package/dist/api/resources/account.js +96 -0
  6. package/dist/api/resources/editing.d.ts +54 -0
  7. package/dist/api/resources/editing.js +168 -0
  8. package/dist/api/resources/generations.d.ts +52 -0
  9. package/dist/api/resources/generations.js +145 -0
  10. package/dist/api/resources/index.d.ts +5 -7
  11. package/dist/api/resources/index.js +18 -15
  12. package/dist/api/resources/models.d.ts +9 -0
  13. package/dist/api/resources/models.js +23 -0
  14. package/dist/api/resources/projects.d.ts +51 -0
  15. package/dist/api/resources/projects.js +128 -0
  16. package/dist/api/types.d.ts +423 -222
  17. package/dist/api/types.js +2 -0
  18. package/dist/core/edgeUpload.d.ts +39 -39
  19. package/dist/core/edgeUpload.js +170 -125
  20. package/dist/core/files.d.ts +15 -0
  21. package/dist/core/files.js +121 -0
  22. package/dist/core/node.d.ts +7 -0
  23. package/dist/core/node.js +17 -0
  24. package/dist/core/pagination.d.ts +33 -0
  25. package/dist/core/pagination.js +64 -0
  26. package/dist/core/poll.d.ts +23 -0
  27. package/dist/core/poll.js +30 -0
  28. package/dist/core/retry.d.ts +8 -7
  29. package/dist/core/retry.js +39 -25
  30. package/dist/core/transport.d.ts +75 -0
  31. package/dist/core/transport.js +220 -0
  32. package/dist/core/url.d.ts +10 -0
  33. package/dist/core/url.js +38 -0
  34. package/dist/core/webhookSignature.d.ts +20 -0
  35. package/dist/core/webhookSignature.js +147 -0
  36. package/dist/errors/index.d.ts +60 -18
  37. package/dist/errors/index.js +61 -13
  38. package/dist/index.d.ts +8 -1
  39. package/dist/index.js +9 -1
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/package.json +2 -7
  43. package/dist/BaseClient.d.ts +0 -26
  44. package/dist/BaseClient.js +0 -17
  45. package/dist/api/resources/account/client/Client.d.ts +0 -15
  46. package/dist/api/resources/account/client/Client.js +0 -15
  47. package/dist/api/resources/apiKeys/client/Client.d.ts +0 -27
  48. package/dist/api/resources/apiKeys/client/Client.js +0 -21
  49. package/dist/api/resources/audioIsolation/client/Client.d.ts +0 -43
  50. package/dist/api/resources/audioIsolation/client/Client.js +0 -33
  51. package/dist/api/resources/generations/client/Client.d.ts +0 -48
  52. package/dist/api/resources/generations/client/Client.js +0 -36
  53. package/dist/api/resources/projects/client/Client.d.ts +0 -21
  54. package/dist/api/resources/projects/client/Client.js +0 -19
  55. package/dist/api/resources/usage/client/Client.d.ts +0 -11
  56. package/dist/api/resources/usage/client/Client.js +0 -12
  57. package/dist/api/resources/webhooks/client/Client.d.ts +0 -29
  58. package/dist/api/resources/webhooks/client/Client.js +0 -76
  59. package/dist/api/serialization.d.ts +0 -21
  60. package/dist/api/serialization.js +0 -274
package/README.md CHANGED
@@ -1,378 +1,290 @@
1
1
  # Diffio JS SDK
2
2
 
3
- The Diffio JS SDK helps you call the Diffio API from Node. This version covers project creation, edge upload, Diffio 4.7 generations, progress checks, and download URLs.
3
+ The official JavaScript and TypeScript client for [Diffio API v2](https://diffio.ai/docs) (`https://api.diffio.ai/v2`).
4
+ It restores speech in audio and video: upload a file, start a restore, wait, and download the result.
4
5
 
5
- ## Install
6
-
7
- ```bash
8
- npm install diffio
9
- ```
6
+ - One call for the whole job: `client.restoreAudio(...)`.
7
+ - Every v2 route as a typed method, with request and response fields in snake_case exactly as on the wire.
8
+ - Uploads straight to Diffio's media host in parts, retrying each part.
9
+ - Typed errors, automatic retries, `for await` pagination, end-user scoping, idempotency keys and webhook
10
+ signature checks.
11
+ - Node 18+ (file paths, Blob, Buffer) and browsers (Blob, File).
10
12
 
11
- For local development:
13
+ Version 1.0.0 talks to v2 only. Code written for the 0.x SDK (v1 endpoints) keeps working on `diffio@0.4`.
12
14
 
13
- ```bash
14
- cd diffio-js
15
- npm install
16
- ```
17
-
18
- ## Configuration
19
-
20
- Set the API key with `DIFFIO_API_KEY`. If you need to set the base URL explicitly, use the production endpoint with `DIFFIO_API_BASE_URL`.
15
+ ## Install
21
16
 
22
17
  ```bash
23
- export DIFFIO_API_KEY="diffio_live_..."
24
- export DIFFIO_API_BASE_URL="https://api.diffio.ai/v1"
18
+ npm install diffio
25
19
  ```
26
20
 
27
- ## Request options
21
+ ## Authenticate
28
22
 
29
- Use request options to override headers, timeouts, retries, or the API key per request.
23
+ Create an API key on the developer dashboard (`/developers/api-keys`) with the Write permission, then either set
24
+ `DIFFIO_API_KEY` or pass it:
30
25
 
31
26
  ```ts
32
27
  import { DiffioClient } from "diffio";
33
28
 
34
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
35
- const projects = await client.listProjects({
36
- requestOptions: {
37
- headers: { "X-Debug": "1" },
38
- timeoutInSeconds: 30,
39
- maxRetries: 2,
40
- retryBackoff: 0.5
41
- }
42
- });
29
+ const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY });
43
30
  ```
44
31
 
45
- ## Models
32
+ The key is sent as `Authorization: Bearer <key>`. Keep it on your server: in a browser, call your own backend.
46
33
 
47
- | Model | `model` value | Endpoint | Notes |
48
- |---|---|---|---|
49
- | Diffio 4.7 Flash | `diffio-4.7-flash` | `/v1/diffio-4.7-flash-generation` | Default. Fast, high quality speech restoration. |
50
- | Diffio 4.7 Pro | `diffio-4.7-pro` | `/v1/diffio-4.7-pro-generation` | Best quality. Paid accounts only. |
51
-
52
- Omitting `model` uses `diffio-4.7-flash`. Older model names still work and run Diffio 4.7 (Flash or
53
- Pro to match); they are deprecated. Earlier models (`diffio-2`, `diffio-2-flash`, `diffio-3.2`,
54
- `diffio-3.4`, `diffio-3.5`, `diffio-4.0-flash`, `diffio-4.0-pro`) are retired: the SDK refuses them
55
- before sending a request, and the API answers their endpoints with HTTP 410 `model_retired`.
56
- Generations created before a model was retired keep their original `modelKey`, so response
57
- `modelKey` fields are typed as `string`.
58
-
59
- ## Create a project and generation
60
-
61
- `createProject` creates the project, uploads the file through Diffio's upload edge, and confirms
62
- the upload, so the project is ready for a generation when it returns.
63
-
64
- The upload follows the session `create_project` returns: the SDK starts a multipart upload at
65
- `{edgeBaseUrl}/v1/uploads/start`, sends the file in parts of `partSizeBytes` (32 MiB, three at a time)
66
- to `/v1/uploads/parts/{partNumber}`, completes it with `/v1/uploads/complete`, and then calls
67
- `/v1/complete_project_upload`. Each part is tried up to four times on network errors, timeouts,
68
- `408`, `429`, and `5xx` answers. A failed upload is aborted and raises `DiffioUploadError` (a
69
- `DiffioApiError`) with `uploadErrorCode` (`upload/too-large`, `upload/unauthorized`,
70
- `upload/rejected`, `upload/network`, `upload/server`, `upload/invalid-response`, or
71
- `upload/canceled`), the edge's `edgeErrorCode` when it sent one, and the `apiProjectId`. Files
72
- larger than the session's `maxBytes` (2 GiB) are refused before any bytes are sent. The upload token
73
- is used only inside the SDK and is not part of the returned project.
34
+ ## Restore a file in one call
74
35
 
75
36
  ```ts
76
37
  import { DiffioClient } from "diffio";
77
38
 
78
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
79
- const filePath = "sample.wav";
80
-
81
- const project = await client.createProject({
82
- filePath
83
- });
84
-
85
- const generation = await client.createGeneration({
86
- apiProjectId: project.apiProjectId,
87
- model: "diffio-4.7-flash",
88
- idempotencyKey: "restore-sample-001"
89
- });
90
-
91
- console.log(generation.generationId, generation.idempotentReplay ?? false);
92
- console.log(project.upload.objectKey, project.uploadCompletion.sizeBytes);
93
- ```
94
-
95
- If `createProject` uploaded the file but the confirmation call failed, confirm it yourself. The call
96
- is idempotent, and Diffio also records the upload on its own shortly after the edge completes it.
97
-
98
- ```ts
99
- await client.projects.completeUpload({ apiProjectId: "proj_123" });
100
- ```
101
-
102
- Reuse the same `idempotencyKey` when retrying generation creation for a project. The API then
103
- returns the existing generation with `idempotentReplay: true` instead of creating another generation.
104
-
105
- Generation creation automatically retries only when you supply a nonblank `idempotencyKey`, reusing
106
- the same key and request body for every attempt. Without a key, generation creation is attempted
107
- once, including on network errors, even if client or request options enable retries. Other requests
108
- retain their configured retry policy. Reuse your original key and request body when manually
109
- retrying after an uncertain response.
110
-
111
- `waitForGeneration` and `generations.waitForComplete` wait for the overall `status` to become
112
- `complete`. Individual stages reaching 100% or `complete` do not end polling while video publication
113
- or usage settlement is still pending. They poll for up to 600 seconds unless you pass `timeout`
114
- or `timeoutInSeconds`. `complete` means restored media is ready. Diffio 4.7 transcribes the recording before
115
- restoration starts, so a completed generation has its transcript unless transcription finished as
116
- `unavailable`; while a generation runs, transcription can be `pending`, `available`, or `unavailable`. Read
117
- `progress.transcription?.status` independently. Older responses omit `transcription`; absence does
118
- not establish availability. Unavailable transcription does not fail completed media.
119
-
120
- ## Audio isolation helper
121
-
122
- ```ts
123
- import { DiffioClient } from "diffio";
39
+ const client = new DiffioClient(); // reads DIFFIO_API_KEY
124
40
 
125
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
126
- const result = await client.audioIsolation.isolate({
127
- filePath: "sample.wav",
128
- model: "diffio-4.7-flash",
129
- idempotencyKey: "restore-sample-001"
41
+ const result = await client.restoreAudio({
42
+ file: "interview.mp3",
43
+ model: "diffio-flash",
44
+ outputPath: "interview.restored.mp3",
130
45
  });
131
46
 
132
- console.log(result.generation.generationId);
47
+ console.log(result.generation.status, result.generation.model, result.output_path, result.size_bytes);
133
48
  ```
134
49
 
135
- The isolation helpers create a new project before creating its generation. Their `idempotencyKey`
136
- protects retries of that generation request; it does not deduplicate a separate helper call or upload.
137
-
138
- ## Restore audio in one call
50
+ `restoreAudio` creates a project with a generation, uploads the file, waits for the restore and downloads the
51
+ restored audio. `file` can be a path (Node), a `Blob` or `File`, or bytes (then pass `file_name`). Without
52
+ `outputPath` the bytes come back in `result.data`. Other options: `metadata`, `label`, `sampling`, `content_type`,
53
+ `downloadFile` (default `"audio"`; `"video"` for a restored video), `timeout` (seconds to wait, default 3600),
54
+ `pollInterval` (seconds, default 2), `onProgress`, `onUploadProgress`, `endUser`, `idempotencyKey`, `signal`.
139
55
 
140
- This helper runs the full flow and returns the downloaded bytes plus a metadata object.
56
+ ## Step by step
141
57
 
142
58
  ```ts
143
59
  import fs from "node:fs";
144
60
  import { DiffioClient } from "diffio";
145
61
 
146
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
147
- const [audioBytes, info] = await client.restoreAudio({
148
- filePath: "sample.wav",
149
- model: "diffio-4.7-flash",
150
- idempotencyKey: "restore-sample-001",
151
- onProgress: (progress) => console.log(progress.status)
152
- });
153
-
154
- if (info.error) {
155
- console.log(info.error);
156
- } else if (audioBytes) {
157
- fs.writeFileSync("restored.mp3", Buffer.from(audioBytes));
158
- }
62
+ const client = new DiffioClient();
159
63
 
160
- console.log(info.apiProjectId, info.generationId);
161
- ```
64
+ // 1) Create the project: the answer carries upload instructions.
65
+ const project = await client.projects.create({
66
+ file_name: "interview.mp3",
67
+ content_type: "audio/mpeg",
68
+ size_bytes: fs.statSync("interview.mp3").size,
69
+ metadata: { order_id: "1042" },
70
+ });
162
71
 
163
- ## Generation progress
72
+ // 2) Upload the bytes (parts, retries) and mark the upload complete.
73
+ await client.projects.upload(project, "interview.mp3");
164
74
 
165
- ```ts
166
- import { DiffioClient } from "diffio";
75
+ // 3) Start a restore.
76
+ const generation = await client.generations.create(project.id, { model: "diffio-flash" });
167
77
 
168
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
169
- const progress = await client.generations.getProgress({
170
- generationId: "gen_123",
171
- apiProjectId: "proj_123"
78
+ // 4) Wait for it to finish.
79
+ const done = await client.generations.wait(project.id, generation.id, {
80
+ onProgress: (g) => console.log(g.status, g.stage, g.stage_progress?.overall_percent ?? ""),
172
81
  });
173
82
 
174
- console.log(progress.status, progress.stage);
175
- console.log(progress.queue?.message ?? "not queued");
176
- console.log(progress.stageProgress?.overallPercent);
177
- console.log(progress.transcription?.status ?? "not reported");
178
-
179
- for (const warning of progress.warnings) {
180
- console.log(warning.code, warning.languages, warning.message);
181
- }
182
-
183
- if (progress.status === "failed" && progress.retryable) {
184
- // A new generation for the same project can retry this failure.
185
- }
83
+ // 5) Download the restored audio.
84
+ const file = await client.generations.download(project.id, done.id, {
85
+ file: "audio",
86
+ path: "interview.restored.mp3",
87
+ });
186
88
  ```
187
89
 
188
- `stage` names the one step the generation is in (`pending`, `preparing`, `transcribing`, `queued`,
189
- `starting`, `downloading`, `decoding`, `restoring`, `finalizing`, `uploading`, `complete`, or
190
- `failed`). While it waits for a processing worker, `queue` reports its position and why it waits;
191
- while a worker runs it, `stageProgress` reports percentages and byte counts when known.
90
+ - `projects.create` accepts `generation: { model }` to request the first restore at once; it starts by itself when
91
+ the upload is ready (`project.latest_generation` is that generation).
92
+ - `projects.upload(project, file)` follows `project.upload.requests` (start, parts of `part_size_bytes`, complete),
93
+ retries failed parts up to four times, then calls `projects.completeUpload` so the file is checked now (pass
94
+ `complete: false` to skip; the project then becomes ready by itself about 30 s later). Give it a project id instead
95
+ of the object and it fetches fresh instructions with `projects.reopenUpload`. Upload tokens last 24 hours.
96
+ - `generations.media(projectId, generationId)` returns URLs for every file (`audio`, `video`, `hls_master`,
97
+ `transcript`, `original`, ...). They need no API key and expire after 6 hours; `download` fetches one of them.
192
98
 
193
- `warnings` lists things to know about the recording; the generation still runs. It is an empty array
194
- until the transcript is ready (and when an older API version omits it). Each warning has a `code`,
195
- `languages`, and a readable `message`. Code `unsupported_language` means the transcript has speech in
196
- `languages` (ISO 639-1 codes such as `ja`, most words first) that Diffio does not support yet, so the
197
- result probably won't be usable.
198
-
199
- When `error` is present, `retryable` says whether a new generation for the same project can fix the
200
- failure (`true` when transcription did not succeed after its automatic retries; `false`, for example,
201
- when the upload has no speech). To retry, create a new generation for the project with a new
202
- `idempotencyKey`, or none; reusing the failed generation's key returns that failed generation.
99
+ ## Models
203
100
 
204
- ## Generation download
101
+ `GET /v2/models` lists every name and needs no key:
205
102
 
206
103
  ```ts
207
- import { DiffioClient } from "diffio";
208
-
209
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
210
- const download = await client.generations.getDownload({
211
- generationId: "gen_123",
212
- apiProjectId: "proj_123",
213
- downloadType: "audio"
214
- });
215
-
216
- console.log(download.downloadUrl);
104
+ const models = await client.models.list();
217
105
  ```
218
106
 
219
- `downloadUrl` is a signed, time-limited media URL that needs no `Authorization` header. The
220
- response has `generationId`, `apiProjectId`, `downloadType`, `downloadUrl`, `fileName`,
221
- `storagePath`, and `mimeType`.
107
+ Use `diffio-flash` (Diffio 4.7 Flash, $5 per hour) or `diffio-pro` (Diffio 4.7 Pro, $10 per hour); these tier names
108
+ always mean the current model. `diffio-4.7-flash` and `diffio-4.7-pro` name the model exactly. Retired names still run
109
+ on the current model of their tier; the generation then says `substituted: true` and `requested_model`.
222
110
 
223
- Set `downloadType` to `"transcript"` to fetch the transcript JSON artifact when available.
224
- Pending transcripts raise `DiffioApiError` with `statusCode === 409` and error code
225
- `TRANSCRIPT_PENDING`. Unavailable transcripts return `404` with `TRANSCRIPT_UNAVAILABLE`.
226
- The `responseBody` also includes `transcription.status`. Check the error code to distinguish
227
- these from other 409 or 404 errors.
111
+ ## Lists and pagination
228
112
 
229
113
  ```ts
230
- import { DiffioApiError } from "diffio";
114
+ // One page: data and next_cursor exactly as the API sends them.
115
+ const page = await client.projects.list({ limit: 1 });
116
+ console.log("first page:", page.data.map((p) => p.id), "next_cursor:", page.next_cursor);
231
117
 
232
- try {
233
- const transcript = await client.generations.getDownload({
234
- generationId: "gen_123",
235
- apiProjectId: "proj_123",
236
- downloadType: "transcript"
237
- });
238
- console.log(transcript.downloadUrl);
239
- } catch (error) {
240
- if (!(error instanceof DiffioApiError)) throw error;
241
- const body = error.responseBody;
242
- const code = body && typeof body === "object" && "code" in body ? body.code : undefined;
243
- if (error.statusCode === 409 && code === "TRANSCRIPT_PENDING") {
244
- console.log("Transcript pending; check progress and retry later.");
245
- } else if (error.statusCode === 404 && code === "TRANSCRIPT_UNAVAILABLE") {
246
- console.log("Transcript unavailable; restored media remains available.");
247
- } else {
248
- throw error;
249
- }
118
+ // Every project, newest first; the SDK fetches the next page when it needs it.
119
+ for await (const project of client.projects.list({ limit: 1 })) {
120
+ console.log(project.id, project.status, project.file_name, project.latest_generation?.status);
250
121
  }
251
122
  ```
252
123
 
253
- `restoreAudio` with `downloadType: "transcript"` also attempts a transcript download after
254
- media completion. It does not wait for pending transcription. With the default `raiseOnError: false`,
255
- it returns `[null, info]` and preserves `info.statusCode` and `info.responseBody`; `info.status`
256
- can still be `complete` because media restoration succeeded. With `raiseOnError: true`, it throws
257
- `DiffioApiError` and attaches metadata as `error.restoreInfo`. Poll progress and retry the download
258
- explicitly for the same generation. Audio and video downloads proceed independently of transcription.
124
+ `generations.list(projectId, { limit, cursor })` works the same way. A page also has `hasNextPage()`,
125
+ `getNextPage()` and `iterPages()`.
259
126
 
260
- ## Account, keys, usage, and webhook configuration
127
+ ## Request options
261
128
 
262
- Agent keys can manage account settings, scoped keys, usage, and webhook endpoints.
129
+ Every method takes an options object last:
263
130
 
264
131
  ```ts
265
- const settings = await client.account.getSettings();
266
- const key = await client.apiKeys.create({
267
- label: "Backend worker",
268
- scopes: ["projects:read", "projects:write", "generations:read", "generations:write", "artifacts:read"]
269
- });
270
- const usage = await client.usage.summary({ apiKeyId: key.keyId });
271
- const webhook = await client.webhooks.configure({
272
- mode: "live",
273
- url: "https://example.com/webhooks/diffio",
274
- eventTypes: ["generation.completed", "generation.failed"],
275
- apiKeyId: key.keyId
276
- });
132
+ await client.generations.create(
133
+ project.id,
134
+ { model: "diffio-pro" },
135
+ { endUser: "customer-42", idempotencyKey: "order-1042-restore", timeout: 30, maxRetries: 4 },
136
+ );
277
137
  ```
278
138
 
279
- ## List projects
139
+ | Option | What it does |
140
+ |---|---|
141
+ | `endUser` | Sent as `Diffio-End-User`: the request acts for one end user of your product and only reaches that end user's projects. Also settable on the client (`new DiffioClient({ endUser })`). `projects.create` also accepts `end_user` in its params and sends it as this header. |
142
+ | `idempotencyKey` | Sent as `Idempotency-Key` on `projects.create`, `generations.create` and `edits.create`. Repeating a call with the same key returns the same resource; reusing it for a different request is refused (409 `idempotency_key_conflict`). When you leave it out the SDK makes one per call, so its own retries never create twice. |
143
+ | `timeout` | Seconds before one HTTP attempt gives up (client default 60). |
144
+ | `maxRetries` | Retries after network errors, 408, 429 and 5xx (client default 2). Only calls that are safe to repeat are retried. |
145
+ | `signal` | An `AbortSignal` to cancel. |
146
+ | `headers`, `apiKey` | Extra headers or another key for this call. |
280
147
 
281
- ```ts
282
- import { DiffioClient } from "diffio";
283
-
284
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
285
- const projects = await client.projects.list();
286
-
287
- for (const project of projects.projects) {
288
- console.log(project.apiProjectId, project.status);
289
- }
290
- ```
148
+ Client options: `apiKey`, `baseUrl` (a host such as `https://diffio-api-dev.web.app`; `/v2` is added), `endUser`,
149
+ `timeout`, `maxRetries`, `retryBackoff`, `retryStatusCodes`, `headers`, `fetch`. `DIFFIO_API_BASE_URL` overrides the
150
+ host when `baseUrl` is not passed.
291
151
 
292
- ## List project generations
152
+ ## Errors
293
153
 
294
154
  ```ts
295
- import { DiffioClient } from "diffio";
296
-
297
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
298
- const generations = await client.projects.listGenerations({ apiProjectId: "proj_123" });
155
+ import { DiffioApiError } from "diffio";
299
156
 
300
- for (const generation of generations.generations) {
301
- console.log(generation.generationId, generation.status);
157
+ try {
158
+ await client.generations.create(project.id, { model: "nope" });
159
+ } catch (error) {
160
+ if (error instanceof DiffioApiError) {
161
+ console.log(error.status, error.code, error.message, error.request_id, error.details);
162
+ // 400 unknown_model "nope is not a Diffio model. See GET /v2/models." "f064..." { field: "model", models: [...] }
163
+ }
302
164
  }
303
165
  ```
304
166
 
305
- ## Send a test webhook event
167
+ | Class | When |
168
+ |---|---|
169
+ | `DiffioApiError` | The API refused the request. `status`, `code` (stable snake_case), `message`, `request_id` (quote it to support), `details`. |
170
+ | `DiffioUploadError` | The media host refused or lost an upload. Extends `DiffioApiError`; adds `retryable` and `project_id`. |
171
+ | `DiffioResourceFailedError` | A `wait` helper saw the generation, export or assistant turn fail. `code` and `message` come from its `error`; `resource` is the failed object. |
172
+ | `DiffioTimeoutError` | A request or a `wait` ran out of time (`resource` holds the last state read). |
173
+ | `DiffioConnectionError` | No HTTP answer after every retry. |
174
+ | `DiffioWebhookVerificationError` | A webhook delivery did not verify. |
306
175
 
307
- ```ts
308
- import { DiffioClient } from "diffio";
176
+ All extend `DiffioError`.
309
177
 
310
- const client = new DiffioClient({ apiKey: "diffio_live_..." });
311
- const event = await client.webhooks.sendTestEvent({
312
- eventType: "generation.completed",
313
- mode: "live",
314
- samplePayload: { apiProjectId: "proj_123" }
315
- });
178
+ ## Editing, mixes, exports, transcripts and shares
316
179
 
317
- console.log(event.svixMessageId);
180
+ ```ts
181
+ const transcript = await client.transcripts.get(project.id, done.id);
182
+
183
+ // Separated tracks: save a mix, then render it as a file.
184
+ await client.mix.save(project.id, done.id, { background_gain: 0.2, leveling: true });
185
+ const exported = await client.exports.create(project.id, done.id, { artifact: "mix", format: "mp3" });
186
+ const ready = await client.exports.wait(project.id, done.id, exported.id);
187
+ console.log(ready.url);
188
+
189
+ // Re-say words of a finished Pro result (bills only the windows it restores).
190
+ const estimate = await client.edits.estimate(project.id, done.id, { words });
191
+ const edit = await client.edits.create(project.id, done.id, { words });
192
+ await client.generations.wait(project.id, edit.id);
193
+
194
+ // A public, key-free view of the result.
195
+ const share = await client.shares.publish(project.id, { preview_seconds: 30 });
196
+ const view = await client.shares.getPublic(share.id);
318
197
  ```
319
198
 
320
- ## Verify webhook signatures
321
-
322
- Use the raw request body (not parsed JSON) plus the `svix-*` headers and your webhook signing secret.
199
+ ## Webhooks
323
200
 
324
- Verified events expose the same optional `event.transcription` object as generation progress.
325
- A `generation.completed` event reports `available` transcription, or `unavailable` when no
326
- transcript could be produced; completion does not wait for a later transcript. Older events can omit
327
- `transcription`. Events include `event.warnings`, in the same shape as progress `warnings`, only when
328
- the generation has warnings. A `generation.failed` event includes `event.retryable`, as progress
329
- does, when the API sends it.
201
+ Open the webhook portal with `await client.webhooks.portal()` (the key needs the `webhooks:write` scope), add your
202
+ endpoint there and copy its signing secret (`whsec_...`). Then check every delivery before trusting it:
330
203
 
331
204
  ```ts
332
- import express from "express";
333
- import { DiffioClient } from "diffio";
334
-
335
- const app = express();
336
- const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY });
337
-
338
- app.post("/webhooks/diffio", express.raw({ type: "application/json" }), (req, res) => {
339
- const payload = req.body;
340
- const headers = {
341
- "svix-id": req.header("svix-id"),
342
- "svix-timestamp": req.header("svix-timestamp"),
343
- "svix-signature": req.header("svix-signature")
344
- };
345
-
346
- try {
347
- const event = client.webhooks.verifySignature({
348
- payload,
349
- headers,
350
- secret: process.env.DIFFIO_WEBHOOK_SECRET
205
+ import http from "node:http";
206
+ import { DiffioClient, DiffioWebhookVerificationError } from "diffio";
207
+
208
+ const client = new DiffioClient();
209
+ const secret = process.env.DIFFIO_WEBHOOK_SECRET; // whsec_... from the webhook portal
210
+
211
+ http
212
+ .createServer((req, res) => {
213
+ const chunks = [];
214
+ req.on("data", (chunk) => chunks.push(chunk));
215
+ req.on("end", () => {
216
+ try {
217
+ // Pass the raw body exactly as received.
218
+ const event = client.webhooks.verifySignature(Buffer.concat(chunks), req.headers, secret);
219
+ console.log("verified", event.type, event.id, event.data.id);
220
+ res.writeHead(204).end();
221
+ } catch (error) {
222
+ if (!(error instanceof DiffioWebhookVerificationError)) throw error;
223
+ console.log("rejected", error.message);
224
+ res.writeHead(400).end();
225
+ }
351
226
  });
352
- console.log("Webhook received", event.eventType);
353
- res.status(200).send("ok");
354
- } catch (err) {
355
- res.status(400).send("Invalid signature");
356
- }
357
- });
227
+ })
228
+ .listen(Number(process.env.PORT ?? 3000));
358
229
  ```
359
230
 
360
- ## Upgrading to 0.4.0
361
-
362
- 0.4.0 adds Diffio 4.7 Flash (`diffio-4.7-flash`) and Diffio 4.7 Pro (`diffio-4.7-pro`), and the
363
- default model is now `diffio-4.7-flash`. Generation progress adds `warnings` (always an array) and
364
- `retryable`, and generation webhook events add optional `warnings` and `retryable`. If you build
365
- `GenerationProgressResponse` objects yourself, for example as test fixtures, add `warnings: []`.
366
-
367
- ## Runtime compatibility
368
-
369
- Use Node 18 or later so `fetch` is available without extra packages.
370
- Examples use ES modules. Save files with a `.mjs` extension or set `"type": "module"` in your package.json.
371
-
372
- ## Tests
231
+ `verifySignature(payload, headers, secret)` checks `svix-id`, `svix-timestamp` (within 5 minutes) and
232
+ `svix-signature` with Node's crypto and returns the event `{ type, id, created_at, data }`. On Cloudflare Workers,
233
+ Deno, Bun or in a browser use `await client.webhooks.verifySignatureAsync(...)` (WebCrypto). Both are also exported as
234
+ `verifyWebhookSignature` and `verifyWebhookSignatureAsync`, so a webhook server needs no API key. De-duplicate on
235
+ `event.id`: retries carry the same id.
236
+
237
+ ## Browsers
238
+
239
+ The SDK runs in browsers with `fetch`: pass a `File` or `Blob` to `projects.upload` or `restoreAudio`. File paths and
240
+ `download({ path })` are Node only. Do not ship your API key to browsers; create the project on your server and hand
241
+ the browser only what it needs.
242
+
243
+ ## Method reference
244
+
245
+ | Method | Route |
246
+ |---|---|
247
+ | `models.list()` | `GET /v2/models` |
248
+ | `projects.create(params)` | `POST /v2/projects` |
249
+ | `projects.upload(project, file, options?)` | media host `upload.requests`, then `POST .../upload/complete` |
250
+ | `projects.reopenUpload(projectId)` | `POST /v2/projects/{id}/upload` |
251
+ | `projects.completeUpload(projectId)` | `POST /v2/projects/{id}/upload/complete` |
252
+ | `projects.list(params?)` | `GET /v2/projects` |
253
+ | `projects.get(projectId)` | `GET /v2/projects/{id}` |
254
+ | `projects.delete(projectId)` | `DELETE /v2/projects/{id}` |
255
+ | `generations.create(projectId, params)` | `POST .../generations` |
256
+ | `generations.list(projectId, params?)` | `GET .../generations` |
257
+ | `generations.get(projectId, generationId)` | `GET .../generations/{gid}` |
258
+ | `generations.wait(projectId, generationId, options?)` | polls `get` |
259
+ | `generations.media(projectId, generationId, params?)` | `GET .../generations/{gid}/media` |
260
+ | `generations.download(projectId, generationId, options?)` | `media`, then the file URL |
261
+ | `edits.estimate(...)`, `edits.create(...)` | `POST .../edits/estimate`, `POST .../edits` |
262
+ | `mix.get(...)`, `mix.save(...)` | `GET`/`PUT .../mix` |
263
+ | `exports.create(...)`, `exports.get(...)`, `exports.wait(...)` | `POST .../exports`, `GET .../exports/{eid}` |
264
+ | `transcripts.get(...)` | `GET .../transcript` |
265
+ | `transcripts.getDraft/saveDraft/deleteDraft(...)` | `GET`/`PUT`/`DELETE .../transcript/draft` |
266
+ | `assistant.createTurn/getTurn/waitTurn(...)` | `POST`/`GET .../transcript/assistant/turns` |
267
+ | `shares.publish/get/revoke(projectId)` | `PUT`/`GET`/`DELETE /v2/projects/{id}/share` |
268
+ | `shares.getPublic(shareId)` | `GET /v2/shares/{share_id}` |
269
+ | `usage.get(params?)` | `GET /v2/usage` |
270
+ | `webhooks.portal()` | `POST /v2/webhooks/portal` |
271
+ | `webhooks.verifySignature(payload, headers, secret)` | local check |
272
+ | `restoreAudio(params)` | create, upload, wait, download |
273
+
274
+ ## Upgrading from 0.x
275
+
276
+ 1.0.0 removes every v1 method (`createProject`, `createGeneration`, `getGenerationProgress`, `waitForGeneration`,
277
+ `getGenerationDownload`, `audioIsolation`, `apiKeys`, `account`, `getUsageSummary`, `configureWebhook`,
278
+ `sendWebhookTestEvent`). Responses are v2 objects with snake_case fields (`project.id`, not `apiProjectId`). API keys,
279
+ account settings and webhook endpoints are managed on the dashboard and in the webhook portal. A base URL ending in
280
+ `/v1` is moved to `/v2`.
281
+
282
+ ## Development
373
283
 
374
284
  ```bash
375
- cd diffio-js
285
+ npm install
376
286
  npm run build
377
- npm test
287
+ npm test # unit + wire (MSW)
288
+ npm run test:unit
289
+ npm run test:wire
378
290
  ```