wavespeed 0.0.15 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,122 +1,22 @@
1
1
  /**
2
- * Input parameters for image generation
2
+ * WaveSpeedAI JavaScript/TypeScript Client — Official JavaScript/TypeScript SDK for WaveSpeedAI inference platform.
3
+ *
4
+ * This library provides a clean, unified, and high-performance API integration layer for your applications.
5
+ * Effortlessly connect to all WaveSpeedAI models and inference services with zero infrastructure overhead.
6
+ *
7
+ * Example usage:
8
+ * import wavespeed from 'wavespeed';
9
+ *
10
+ * const output = await wavespeed.run(
11
+ * "wavespeed-ai/z-image/turbo",
12
+ * { prompt: "A beautiful sunset" }
13
+ * );
14
+ * console.log(output["outputs"][0]);
3
15
  */
4
- /**
5
- * Prediction status
6
- */
7
- export type PredictionStatus = 'created' | 'processing' | 'completed' | 'failed';
8
- /**
9
- * Prediction URLs
10
- */
11
- export interface PredictionUrls {
12
- get: string;
13
- }
14
- export interface UploadFileResp {
15
- code: number;
16
- message: string;
17
- data: {
18
- type: string;
19
- download_url: string;
20
- filename: string;
21
- size: number;
22
- };
23
- }
24
- /**
25
- * Request options for fetch
26
- */
27
- export interface RequestOptions extends RequestInit {
28
- timeout?: number;
29
- maxRetries?: number;
30
- webhook?: string;
31
- isUpload?: boolean;
32
- filename?: string;
33
- }
34
- /**
35
- * Prediction model representing an image generation job
36
- */
37
- export declare class Prediction {
38
- id: string;
39
- model: string;
40
- status: PredictionStatus;
41
- input: Record<string, any>;
42
- outputs: string[];
43
- urls: PredictionUrls;
44
- has_nsfw_contents: boolean[];
45
- created_at: string;
46
- error?: string;
47
- executionTime?: number;
48
- private client;
49
- constructor(data: any, client: WaveSpeed);
50
- /**
51
- * Wait for the prediction to complete
52
- */
53
- wait(): Promise<Prediction>;
54
- /**
55
- * Reload the prediction status
56
- */
57
- reload(): Promise<Prediction>;
58
- }
59
- /**
60
- * WaveSpeed client for generating images
61
- */
62
- export declare class WaveSpeed {
63
- private apiKey;
64
- private baseUrl;
65
- readonly pollInterval: number;
66
- readonly timeout: number;
67
- /**
68
- * Create a new WaveSpeed client
69
- *
70
- * @param apiKey Your WaveSpeed API key (or set WAVESPEED_API_KEY environment variable)
71
- * @param options Additional client options
72
- */
73
- constructor(apiKey?: string, options?: {
74
- baseUrl?: string;
75
- pollInterval?: number;
76
- timeout?: number;
77
- });
78
- /**
79
- * Fetch with timeout support
80
- *
81
- * @param path API path
82
- * @param options Fetch options
83
- */
84
- fetchWithTimeout(path: string, options?: RequestOptions): Promise<Response>;
85
- /**
86
- * Calculate backoff time with exponential backoff and jitter
87
- * @param retryCount Current retry attempt number
88
- * @param initialBackoff Initial backoff time in ms
89
- * @returns Backoff time in ms
90
- * @private
91
- */
92
- _getBackoffTime(retryCount: number, initialBackoff: number): number;
93
- /**
94
- * Generate an image and wait for the result
95
- *
96
- * @param modelId Model ID to use for prediction
97
- * @param input Input parameters for the prediction
98
- * @param options Additional fetch options
99
- */
100
- run(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>;
101
- /**
102
- * Create a prediction without waiting for it to complete
103
- *
104
- * @param modelId Model ID to use for prediction
105
- * @param input Input parameters for the prediction
106
- * @param options Additional fetch options
107
- */
108
- create(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>;
109
- getPrediction(predictionId: string): Promise<Prediction>;
110
- /**
111
- * Upload a file (binary) to the /media/upload/binary endpoint
112
- * @param filePath Absolute path to the file to upload
113
- * @returns The API response JSON
114
- */
115
- /**
116
- * Upload a file (binary) to the /media/upload/binary endpoint (browser Blob version)
117
- * @param file Blob to upload
118
- * @returns The API response JSON
119
- */
120
- upload(file: File | Blob, options?: RequestOptions): Promise<string>;
121
- }
122
- export default WaveSpeed;
16
+ import { version } from './version';
17
+ import './config';
18
+ import { Client, run, upload } from './api';
19
+ import type { RunOptions } from './api/client';
20
+ export { version, Client, run, upload };
21
+ export type { RunOptions };
22
+ export default Client;
package/dist/index.js CHANGED
@@ -1,285 +1,30 @@
1
1
  "use strict";
2
2
  /**
3
- * Input parameters for image generation
3
+ * WaveSpeedAI JavaScript/TypeScript Client — Official JavaScript/TypeScript SDK for WaveSpeedAI inference platform.
4
+ *
5
+ * This library provides a clean, unified, and high-performance API integration layer for your applications.
6
+ * Effortlessly connect to all WaveSpeedAI models and inference services with zero infrastructure overhead.
7
+ *
8
+ * Example usage:
9
+ * import wavespeed from 'wavespeed';
10
+ *
11
+ * const output = await wavespeed.run(
12
+ * "wavespeed-ai/z-image/turbo",
13
+ * { prompt: "A beautiful sunset" }
14
+ * );
15
+ * console.log(output["outputs"][0]);
4
16
  */
5
17
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.WaveSpeed = exports.Prediction = void 0;
7
- /**
8
- * Prediction model representing an image generation job
9
- */
10
- class Prediction {
11
- constructor(data, client) {
12
- this.id = data.id;
13
- this.model = data.model;
14
- this.status = data.status;
15
- this.input = data.input;
16
- this.outputs = data.outputs || [];
17
- this.urls = data.urls;
18
- this.has_nsfw_contents = data.has_nsfw_contents || [];
19
- this.created_at = data.created_at;
20
- this.error = data.error;
21
- this.executionTime = data.executionTime;
22
- this.client = client;
23
- }
24
- /**
25
- * Wait for the prediction to complete
26
- */
27
- async wait() {
28
- if (this.status === 'completed' || this.status === 'failed') {
29
- return this;
30
- }
31
- return new Promise((resolve, reject) => {
32
- const checkStatus = async () => {
33
- try {
34
- const updated = await this.reload();
35
- if (updated.status === 'completed' || updated.status === 'failed') {
36
- resolve(updated);
37
- }
38
- else {
39
- setTimeout(checkStatus, this.client.pollInterval * 1000);
40
- }
41
- }
42
- catch (error) {
43
- reject(error);
44
- }
45
- };
46
- checkStatus();
47
- });
48
- }
49
- /**
50
- * Reload the prediction status
51
- */
52
- async reload() {
53
- const response = await this.client.fetchWithTimeout(`predictions/${this.id}/result`);
54
- if (!response.ok) {
55
- const errorText = await response.text();
56
- throw new Error(`Failed to reload prediction: ${response.status} ${errorText}`);
57
- }
58
- const data = await response.json();
59
- const updatedPrediction = new Prediction(data.data, this.client);
60
- // Update this instance with new data
61
- Object.assign(this, updatedPrediction);
62
- return this;
63
- }
64
- }
65
- exports.Prediction = Prediction;
66
- /**
67
- * WaveSpeed client for generating images
68
- */
69
- class WaveSpeed {
70
- /**
71
- * Create a new WaveSpeed client
72
- *
73
- * @param apiKey Your WaveSpeed API key (or set WAVESPEED_API_KEY environment variable)
74
- * @param options Additional client options
75
- */
76
- constructor(apiKey, options = {}) {
77
- this.baseUrl = 'https://api.wavespeed.ai/api/v3/';
78
- // Browser-friendly environment variable handling
79
- const getEnvVar = (name) => {
80
- // Try to get from process.env for Node.js environments
81
- if (typeof process !== 'undefined' && process.env && process.env[name]) {
82
- return process.env[name];
83
- }
84
- return undefined;
85
- };
86
- this.apiKey = apiKey || getEnvVar('WAVESPEED_API_KEY') || '';
87
- if (!this.apiKey) {
88
- throw new Error('API key is required. Provide it as a parameter or set the WAVESPEED_API_KEY environment variable.');
89
- }
90
- if (options.baseUrl) {
91
- this.baseUrl = options.baseUrl;
92
- }
93
- this.pollInterval = options.pollInterval || Number(getEnvVar('WAVESPEED_POLL_INTERVAL')) || 0.5;
94
- this.timeout = options.timeout || Number(getEnvVar('WAVESPEED_TIMEOUT')) || 120;
95
- }
96
- /**
97
- * Fetch with timeout support
98
- *
99
- * @param path API path
100
- * @param options Fetch options
101
- */
102
- async fetchWithTimeout(path, options = {}) {
103
- const { timeout = this.timeout * 1000, ...fetchOptions } = options;
104
- // Ensure headers exist
105
- if (options.isUpload) {
106
- fetchOptions.headers = {
107
- 'Authorization': `Bearer ${this.apiKey}`,
108
- };
109
- }
110
- else {
111
- fetchOptions.headers = {
112
- 'Authorization': `Bearer ${this.apiKey}`,
113
- 'content-type': 'application/json',
114
- ...(fetchOptions.headers || {}),
115
- };
116
- }
117
- // Default retry options
118
- const maxRetries = options.maxRetries || 3;
119
- const initialBackoff = 1000; // 1 second
120
- let retryCount = 0;
121
- // Function to determine if a response should be retried
122
- const shouldRetry = (response) => {
123
- // Retry on rate limit (429) for all requests
124
- // For GET requests, also retry on server errors (5xx)
125
- const method = (fetchOptions.method || 'GET').toUpperCase();
126
- return response.status === 429 || (method === 'GET' && response.status >= 500);
127
- };
128
- while (true) {
129
- // Use AbortController for timeout (supported in modern browsers)
130
- const controller = new AbortController();
131
- const timeoutId = setTimeout(() => controller.abort(), timeout);
132
- try {
133
- // Construct the full URL by joining baseUrl and path
134
- const baseUrl = options.isUpload ? this.baseUrl.replace('v3', 'v2') : this.baseUrl;
135
- const url = new URL(path.startsWith('/') ? path.substring(1) : path, baseUrl).toString();
136
- const response = await fetch(url, {
137
- ...fetchOptions,
138
- signal: controller.signal
139
- });
140
- // If the response is successful or we've used all retries, return it
141
- if (response.ok || !shouldRetry(response) || retryCount >= maxRetries) {
142
- return response;
143
- }
144
- // Otherwise, increment retry count and wait before retrying
145
- retryCount++;
146
- const backoffTime = this._getBackoffTime(retryCount, initialBackoff);
147
- // Log retry information if console is available
148
- if (typeof console !== 'undefined') {
149
- console.warn(`Request failed with status ${response.status}. Retrying (${retryCount}/${maxRetries}) in ${Math.round(backoffTime)}ms...`);
150
- }
151
- // Wait for backoff time before retrying
152
- await new Promise(resolve => setTimeout(resolve, backoffTime));
153
- }
154
- catch (error) {
155
- // If the error is due to timeout or network issues and we have retries left
156
- if (error instanceof Error &&
157
- (error.name === 'AbortError' || error.name === 'TypeError') &&
158
- retryCount < maxRetries) {
159
- retryCount++;
160
- const backoffTime = this._getBackoffTime(retryCount, initialBackoff);
161
- // Log retry information if console is available
162
- if (typeof console !== 'undefined') {
163
- console.warn(`Request failed with error: ${error.message}. Retrying (${retryCount}/${maxRetries}) in ${Math.round(backoffTime)}ms...`);
164
- }
165
- // Wait for backoff time before retrying
166
- await new Promise(resolve => setTimeout(resolve, backoffTime));
167
- }
168
- else {
169
- // If we're out of retries or it's a non-retryable error, throw it
170
- throw error;
171
- }
172
- }
173
- finally {
174
- clearTimeout(timeoutId);
175
- }
176
- }
177
- }
178
- /**
179
- * Calculate backoff time with exponential backoff and jitter
180
- * @param retryCount Current retry attempt number
181
- * @param initialBackoff Initial backoff time in ms
182
- * @returns Backoff time in ms
183
- * @private
184
- */
185
- _getBackoffTime(retryCount, initialBackoff) {
186
- const backoff = initialBackoff * Math.pow(2, retryCount);
187
- // Add jitter (random value between 0 and backoff/2)
188
- return backoff + Math.random() * (backoff / 2);
189
- }
190
- /**
191
- * Generate an image and wait for the result
192
- *
193
- * @param modelId Model ID to use for prediction
194
- * @param input Input parameters for the prediction
195
- * @param options Additional fetch options
196
- */
197
- async run(modelId, input, options) {
198
- const prediction = await this.create(modelId, input, options);
199
- return prediction.wait();
200
- }
201
- /**
202
- * Create a prediction without waiting for it to complete
203
- *
204
- * @param modelId Model ID to use for prediction
205
- * @param input Input parameters for the prediction
206
- * @param options Additional fetch options
207
- */
208
- async create(modelId, input, options) {
209
- // Build URL with webhook if provided in options
210
- let url = `${modelId}`;
211
- if (options === null || options === void 0 ? void 0 : options.webhook) {
212
- url += `?webhook=${options.webhook}`;
213
- }
214
- const response = await this.fetchWithTimeout(url, {
215
- method: 'POST',
216
- body: JSON.stringify(input),
217
- ...options
218
- });
219
- if (!response.ok) {
220
- const errorText = await response.text();
221
- throw new Error(`Failed to create prediction: ${response.status} ${errorText}`);
222
- }
223
- const data = await response.json();
224
- if (data.code !== 200) {
225
- throw new Error(`Failed to create prediction: ${data.code} ${data}`);
226
- }
227
- return new Prediction(data.data, this);
228
- }
229
- async getPrediction(predictionId) {
230
- const response = await this.fetchWithTimeout(`predictions/${predictionId}/result`);
231
- if (!response.ok) {
232
- const errorText = await response.text();
233
- throw new Error(`Failed to get prediction: ${response.status} ${errorText}`);
234
- }
235
- const data = await response.json();
236
- if (data.code !== 200) {
237
- throw new Error(`Failed to get prediction: ${data.code} ${data}`);
238
- }
239
- return new Prediction(data.data, this);
240
- }
241
- /**
242
- * Upload a file (binary) to the /media/upload/binary endpoint
243
- * @param filePath Absolute path to the file to upload
244
- * @returns The API response JSON
245
- */
246
- /**
247
- * Upload a file (binary) to the /media/upload/binary endpoint (browser Blob version)
248
- * @param file Blob to upload
249
- * @returns The API response JSON
250
- */
251
- async upload(file, options) {
252
- const form = new FormData();
253
- if (options === null || options === void 0 ? void 0 : options.filename) {
254
- form.append('file', file, options.filename);
255
- }
256
- else {
257
- form.append('file', file);
258
- }
259
- // Only set Authorization header; browser will set Content-Type
260
- if (options == null) {
261
- options = { isUpload: true };
262
- }
263
- else {
264
- options.isUpload = true;
265
- }
266
- const response = await this.fetchWithTimeout('media/upload/binary', {
267
- method: 'POST',
268
- body: form,
269
- ...options
270
- });
271
- if (!response.ok) {
272
- const errorText = await response.text();
273
- throw new Error(`Failed to upload file: ${response.status} ${errorText}`);
274
- }
275
- const resp = await response.json();
276
- return resp.data.download_url;
277
- }
278
- }
279
- exports.WaveSpeed = WaveSpeed;
280
- // Export default and named exports for different import styles
281
- exports.default = WaveSpeed;
282
- // Add browser global for UMD-style usage
283
- if (typeof window !== 'undefined') {
284
- window.WaveSpeed = WaveSpeed;
285
- }
18
+ exports.upload = exports.run = exports.Client = exports.version = void 0;
19
+ // Import version
20
+ const version_1 = require("./version");
21
+ Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_1.version; } });
22
+ // Import config to auto-load environment variables
23
+ require("./config");
24
+ // Import API client
25
+ const api_1 = require("./api");
26
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return api_1.Client; } });
27
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return api_1.run; } });
28
+ Object.defineProperty(exports, "upload", { enumerable: true, get: function () { return api_1.upload; } });
29
+ // Default export (Client class)
30
+ exports.default = api_1.Client;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Version information for WaveSpeed SDK.
3
+ * This file provides version information from package.json.
4
+ */
5
+ export declare const version: string;
6
+ export default version;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ /**
3
+ * Version information for WaveSpeed SDK.
4
+ * This file provides version information from package.json.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.version = void 0;
8
+ // For CommonJS build, we'll read version at runtime
9
+ let _version = '0.0.0';
10
+ try {
11
+ // Try to read from package.json
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const packagePath = path.join(__dirname, '../package.json');
15
+ if (fs.existsSync(packagePath)) {
16
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
17
+ _version = packageJson.version;
18
+ }
19
+ }
20
+ catch (err) {
21
+ // Fallback to default version if package.json cannot be read
22
+ _version = '0.1.0';
23
+ }
24
+ exports.version = _version;
25
+ exports.default = exports.version;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wavespeed",
3
- "version": "0.0.15",
3
+ "version": "0.2.2",
4
4
  "description": "WaveSpeed Client SDK for Wavespeed API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,8 +18,12 @@
18
18
  "sdk",
19
19
  "wavespeed"
20
20
  ],
21
- "author": "",
21
+ "author": "WaveSpeedAI <support@wavespeed.ai>",
22
22
  "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/WaveSpeedAI/wavespeed-javascript.git"
26
+ },
23
27
  "devDependencies": {
24
28
  "@types/jest": "^29.5.5",
25
29
  "@types/node": "^20.8.2",
@@ -30,7 +34,6 @@
30
34
  "ts-jest": "^29.1.1",
31
35
  "typescript": "^5.2.2"
32
36
  },
33
- "dependencies": {},
34
37
  "files": [
35
38
  "dist"
36
39
  ]