@devvibex/aiflow 1.0.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 MetaCrew
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,256 @@
1
+ # @vibexnpm/aiflow
2
+
3
+ First-party LLM gateway SDK for apps generated on the VibeX platform.
4
+ No third-party API key is needed in the browser — every request is routed
5
+ through the platform gateway, which attaches the provider key server-side
6
+ and bills the project owner's credit balance.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install @vibexnpm/aiflow
12
+ # or
13
+ yarn add @vibexnpm/aiflow
14
+ # or
15
+ pnpm add @vibexnpm/aiflow
16
+ ```
17
+
18
+ Requires Node.js **18+** (or any modern browser) — uses the native `fetch`
19
+ and `ReadableStream` APIs.
20
+
21
+ ## Quick start
22
+
23
+ ```js
24
+ import AIFlowClient from '@vibexnpm/aiflow';
25
+
26
+ // No model defaults needed — the SDK fetches them from the server on
27
+ // first use (cached for the life of the client). Override only if you
28
+ // want to pin a specific model.
29
+ const aiflow = new AIFlowClient({
30
+ appId: 'YOUR_APP_ID', // injected by the platform gateway
31
+ baseUrl: 'https://api.vibe-x.io/aiflow',
32
+ });
33
+
34
+ // Optional — inspect / pre-warm the server config
35
+ const config = await aiflow.getConfig();
36
+ console.log(config.models.chat); // ["claude-sonnet-4-6", "gpt-4o", ...]
37
+ console.log(config.defaults.chat); // "claude-sonnet-4-6"
38
+
39
+ // Non-streaming chat
40
+ const res = await aiflow.chat({
41
+ system: 'You are a helpful assistant.',
42
+ messages: [{ role: 'user', content: 'Hello, who are you?' }],
43
+ });
44
+ console.log(res.content);
45
+
46
+ // Streaming chat
47
+ for await (const chunk of aiflow.chatStream({
48
+ messages: [{ role: 'user', content: 'Write a haiku about the sea.' }],
49
+ })) {
50
+ if (chunk.delta) process.stdout.write(chunk.delta);
51
+ if (chunk.done) break;
52
+ }
53
+
54
+ // Image generation
55
+ const img = await aiflow.generateImage({
56
+ prompt: 'a cozy cabin in a snowy forest, watercolour',
57
+ size: '1024x1024',
58
+ });
59
+ console.log(img.images[0].url);
60
+
61
+ // Embeddings
62
+ const emb = await aiflow.embed({ input: ['hello world'] });
63
+ console.log(emb.data[0].embedding.length);
64
+ ```
65
+
66
+ ## API
67
+
68
+ ### `new AIFlowClient(options)`
69
+
70
+ | Option | Type | Default | Notes |
71
+ | ------------------- | --------------- | ------------------ | ----------------------------------------------- |
72
+ | `appId` | `string` | **required** | Public project app id. |
73
+ | `baseUrl` | `string` | **required** | Gateway URL, e.g. `https://api.vibe-x.io/aiflow`. |
74
+ | `defaultModel` | `string` | from `GET /config` | Override — wins over server config. |
75
+ | `defaultImageModel` | `string` | from `GET /config` | Override. |
76
+ | `defaultEmbedModel` | `string` | from `GET /config` | Override. |
77
+ | `timeout` | `number` | `60000` | Per-request timeout (ms). |
78
+ | `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
79
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
80
+
81
+ When you don't pass a `defaultModel`, the SDK calls `GET /config` on the
82
+ first `chat` / `chatStream` / `generateImage` / `embed` and caches the
83
+ response. Concurrent first calls share a single in-flight config fetch.
84
+
85
+ ### `aiflow.getConfig({ refresh? })`
86
+
87
+ Returns the cached server config, fetching on demand. Pass `{ refresh: true }`
88
+ to invalidate the cache.
89
+
90
+ ```ts
91
+ {
92
+ appId: string,
93
+ models: {
94
+ chat: string[], // e.g. ["claude-sonnet-4-6", "gpt-4o", ...]
95
+ image: string[],
96
+ embed: string[],
97
+ },
98
+ defaults: { chat: string, image: string, embed: string },
99
+ limits: { maxTokens: number, maxImageN: number, maxEmbedInputs: number },
100
+ creditValue: number,
101
+ }
102
+ ```
103
+
104
+ ### `aiflow.chat({ messages, model?, system?, maxTokens?, temperature?, tools?, signal? })`
105
+
106
+ Returns `Promise<{ id, model, content, usage: { inputTokens, outputTokens, creditsUsed } }>`.
107
+
108
+ ### `aiflow.chatStream({ ... })`
109
+
110
+ Async iterable of `{ delta: string, done: boolean }` chunks. The final chunk
111
+ has `done: true`.
112
+
113
+ ### `aiflow.generateImage({ prompt, model?, size?, n?, signal? })`
114
+
115
+ Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
116
+ `url` is a short-lived signed URL (~1h).
117
+
118
+ ### `aiflow.embed({ input, model?, signal? })`
119
+
120
+ Returns `{ data: [{ embedding: number[], index }], usage: { creditsUsed } }`.
121
+
122
+ ## Error handling
123
+
124
+ All failures throw `AIFlowError` with `.status`, `.code`, and `.requestId`.
125
+
126
+ ```js
127
+ import { AIFlowError } from '@vibexnpm/aiflow';
128
+
129
+ try {
130
+ await aiflow.chat({ messages });
131
+ } catch (err) {
132
+ if (err instanceof AIFlowError && err.status === 402) {
133
+ alert('AI credits exhausted — please contact the app owner.');
134
+ } else {
135
+ throw err;
136
+ }
137
+ }
138
+ ```
139
+
140
+ | Status | Meaning | Retry? |
141
+ | ------ | ------------------------ | ---------------------------------- |
142
+ | 401 | Invalid / revoked appId | No — surface as a config error. |
143
+ | 402 | Credits exhausted | **No** — never retry. |
144
+ | 429 | Rate limited | Yes, auto (exponential backoff). |
145
+ | 5xx | Transient server error | Yes, auto (exponential backoff). |
146
+
147
+ ## Cancellation
148
+
149
+ All methods accept an `AbortSignal`:
150
+
151
+ ```js
152
+ const ctrl = new AbortController();
153
+ setTimeout(() => ctrl.abort(), 3000);
154
+ await aiflow.chat({ messages, signal: ctrl.signal });
155
+ ```
156
+
157
+ ## Publishing to npmjs
158
+
159
+ > Owned by the `@vibexnpm` org. You must be a member to publish.
160
+
161
+ ### 1. One-off setup
162
+
163
+ ```bash
164
+ # Log in with an account that has access to the @vibexnpm org
165
+ npm login
166
+ ```
167
+
168
+ Enable 2FA on the account — npm requires it for scoped org packages.
169
+
170
+ ### 2. Bump the version
171
+
172
+ Follow [semver](https://semver.org). Bump in `sdk/aiflow/package.json`:
173
+
174
+ ```bash
175
+ cd sdk/aiflow
176
+ npm version patch # or minor / major
177
+ ```
178
+
179
+ `npm version` creates a git tag automatically — push it with
180
+ `git push --follow-tags` if you want the tag in the shared repo.
181
+
182
+ ### 3. Dry-run the tarball
183
+
184
+ Double-check what will be uploaded before going public:
185
+
186
+ ```bash
187
+ npm pack --dry-run
188
+ ```
189
+
190
+ Only `src/`, `README.md`, `LICENSE`, and `package.json` should appear —
191
+ the `files` whitelist in `package.json` enforces this.
192
+
193
+ ### 4. Publish
194
+
195
+ Scoped packages default to private on npm, so explicitly publish as public
196
+ (already set via `publishConfig` in `package.json`, but pass the flag in
197
+ case):
198
+
199
+ ```bash
200
+ npm publish --access public
201
+ ```
202
+
203
+ npm will prompt for a 2FA code. On success the package appears at
204
+ <https://www.npmjs.com/package/@vibexnpm/aiflow>.
205
+
206
+ ### 5. Verify
207
+
208
+ ```bash
209
+ # From any scratch dir
210
+ npm info @vibexnpm/aiflow
211
+ npm install @vibexnpm/aiflow@latest
212
+ ```
213
+
214
+ ### 6. Deprecate / unpublish (if needed)
215
+
216
+ ```bash
217
+ # Soft-deprecate a bad version
218
+ npm deprecate @vibexnpm/aiflow@1.0.1 'bug in streaming parser — use 1.0.2+'
219
+
220
+ # Hard unpublish (only within 72h of publishing)
221
+ npm unpublish @vibexnpm/aiflow@1.0.1
222
+ ```
223
+
224
+ ### CI publishing (optional)
225
+
226
+ Add an `NPM_TOKEN` (automation token) secret to the GitHub repo, then:
227
+
228
+ ```yaml
229
+ # .github/workflows/publish-aiflow.yml
230
+ name: Publish @vibexnpm/aiflow
231
+ on:
232
+ push:
233
+ tags: ['aiflow-v*']
234
+
235
+ jobs:
236
+ publish:
237
+ runs-on: ubuntu-latest
238
+ defaults:
239
+ run:
240
+ working-directory: sdk/aiflow
241
+ steps:
242
+ - uses: actions/checkout@v4
243
+ - uses: actions/setup-node@v4
244
+ with:
245
+ node-version: '20'
246
+ registry-url: 'https://registry.npmjs.org'
247
+ - run: npm publish --access public
248
+ env:
249
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
250
+ ```
251
+
252
+ Trigger a release by pushing `git tag aiflow-v1.0.1 && git push --tags`.
253
+
254
+ ## License
255
+
256
+ MIT
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@devvibex/aiflow",
3
+ "version": "1.0.1",
4
+ "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image generation and embeddings without shipping any third-party API key.",
5
+ "keywords": [
6
+ "ai",
7
+ "llm",
8
+ "chatbot",
9
+ "claude",
10
+ "gpt",
11
+ "gemini",
12
+ "vibex",
13
+ "aiflow"
14
+ ],
15
+ "type": "module",
16
+ "main": "./src/index.js",
17
+ "module": "./src/index.js",
18
+ "types": "./src/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./src/index.d.ts",
22
+ "import": "./src/index.js",
23
+ "default": "./src/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "src",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "sideEffects": false,
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/METACREW-COMPANY/lh-dori77-platform.git",
39
+ "directory": "sdk/aiflow"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "test": "node --test test/*.test.js"
46
+ }
47
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,146 @@
1
+ export interface AIFlowErrorOptions {
2
+ status?: number;
3
+ code?: string;
4
+ requestId?: string;
5
+ cause?: unknown;
6
+ }
7
+
8
+ export class AIFlowError extends Error {
9
+ name: 'AIFlowError';
10
+ status?: number;
11
+ code?: string;
12
+ requestId?: string;
13
+ cause?: unknown;
14
+ constructor(message: string, options?: AIFlowErrorOptions);
15
+ }
16
+
17
+ export type ChatRole = 'system' | 'user' | 'assistant';
18
+
19
+ export interface ChatMessage {
20
+ role: ChatRole;
21
+ content: string;
22
+ name?: string;
23
+ }
24
+
25
+ export interface ChatTool {
26
+ name: string;
27
+ description?: string;
28
+ parameters?: Record<string, unknown>;
29
+ }
30
+
31
+ export interface ChatRequest {
32
+ messages: ChatMessage[];
33
+ model?: string;
34
+ system?: string;
35
+ maxTokens?: number;
36
+ temperature?: number;
37
+ tools?: ChatTool[];
38
+ signal?: AbortSignal;
39
+ }
40
+
41
+ export interface ChatUsage {
42
+ inputTokens: number;
43
+ outputTokens: number;
44
+ creditsUsed: number;
45
+ }
46
+
47
+ export interface ChatResponse {
48
+ id: string;
49
+ model: string;
50
+ content: string;
51
+ usage: ChatUsage;
52
+ }
53
+
54
+ export interface ChatStreamChunk {
55
+ delta: string;
56
+ done: boolean;
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ export interface ImageRequest {
61
+ prompt: string;
62
+ model?: string;
63
+ size?: '512x512' | '1024x1024' | '1024x1792' | string;
64
+ n?: number;
65
+ signal?: AbortSignal;
66
+ }
67
+
68
+ export interface GeneratedImage {
69
+ url?: string;
70
+ b64?: string;
71
+ mimeType: string;
72
+ }
73
+
74
+ export interface ImageResponse {
75
+ images: GeneratedImage[];
76
+ usage: { creditsUsed: number };
77
+ }
78
+
79
+ export interface EmbedRequest {
80
+ input: string | string[];
81
+ model?: string;
82
+ signal?: AbortSignal;
83
+ }
84
+
85
+ export interface Embedding {
86
+ embedding: number[];
87
+ index: number;
88
+ }
89
+
90
+ export interface EmbedResponse {
91
+ data: Embedding[];
92
+ usage: { creditsUsed: number };
93
+ }
94
+
95
+ export interface AIFlowClientOptions {
96
+ appId: string;
97
+ baseUrl: string;
98
+ /** Optional override — if omitted, the SDK fetches GET /config on first use. */
99
+ defaultModel?: string | null;
100
+ defaultImageModel?: string | null;
101
+ defaultEmbedModel?: string | null;
102
+ timeout?: number;
103
+ maxRetries?: number;
104
+ fetch?: typeof fetch;
105
+ }
106
+
107
+ export interface AiflowConfig {
108
+ appId: string;
109
+ models: {
110
+ chat: string[];
111
+ image: string[];
112
+ embed: string[];
113
+ };
114
+ defaults: {
115
+ chat: string;
116
+ image: string;
117
+ embed: string;
118
+ };
119
+ limits: {
120
+ maxTokens: number;
121
+ maxImageN: number;
122
+ maxEmbedInputs: number;
123
+ };
124
+ creditValue: number;
125
+ }
126
+
127
+ export class AIFlowClient {
128
+ readonly appId: string;
129
+ readonly baseUrl: string;
130
+ readonly timeout: number;
131
+ readonly maxRetries: number;
132
+
133
+ constructor(options: AIFlowClientOptions);
134
+
135
+ /**
136
+ * Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
137
+ * to force a reload.
138
+ */
139
+ getConfig(options?: { refresh?: boolean }): Promise<AiflowConfig>;
140
+ chat(request: ChatRequest): Promise<ChatResponse>;
141
+ chatStream(request: ChatRequest): AsyncGenerator<ChatStreamChunk, void, void>;
142
+ generateImage(request: ImageRequest): Promise<ImageResponse>;
143
+ embed(request: EmbedRequest): Promise<EmbedResponse>;
144
+ }
145
+
146
+ export default AIFlowClient;
package/src/index.js ADDED
@@ -0,0 +1,401 @@
1
+ /**
2
+ * @vibexnpm/aiflow — first-party LLM gateway SDK.
3
+ *
4
+ * All requests are routed through the VibeX platform gateway, which attaches
5
+ * the provider API key server-side and bills the project owner's credit
6
+ * balance. No third-party key ever lives in the browser.
7
+ */
8
+
9
+ const DEFAULT_TIMEOUT_MS = 60_000;
10
+ const DEFAULT_MAX_RETRIES = 2;
11
+ const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
12
+
13
+ export class AIFlowError extends Error {
14
+ constructor(message, { status, code, requestId, cause } = {}) {
15
+ super(message);
16
+ this.name = 'AIFlowError';
17
+ this.status = status;
18
+ this.code = code;
19
+ this.requestId = requestId;
20
+ if (cause) this.cause = cause;
21
+ }
22
+ }
23
+
24
+ export class AIFlowClient {
25
+ /**
26
+ * @param {object} options
27
+ * @param {string} options.appId Public project app id. Required.
28
+ * @param {string} options.baseUrl VibeX gateway base URL (e.g. "https://api.vibe-x.io/aiflow").
29
+ * @param {string} [options.defaultModel]
30
+ * @param {string} [options.defaultImageModel]
31
+ * @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
32
+ * @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
33
+ * @param {typeof fetch} [options.fetch] Custom fetch implementation.
34
+ */
35
+ constructor({
36
+ appId,
37
+ baseUrl,
38
+ defaultModel = null,
39
+ defaultImageModel = null,
40
+ defaultEmbedModel = null,
41
+ timeout = DEFAULT_TIMEOUT_MS,
42
+ maxRetries = DEFAULT_MAX_RETRIES,
43
+ fetch: customFetch,
44
+ } = {}) {
45
+ if (!appId) throw new AIFlowError('appId is required');
46
+ if (!baseUrl) throw new AIFlowError('baseUrl is required');
47
+
48
+ this.appId = appId;
49
+ this.baseUrl = String(baseUrl).replace(/\/+$/, '');
50
+ // Caller-provided overrides — win over server-fetched config.
51
+ this._userDefaults = {
52
+ chat: defaultModel,
53
+ image: defaultImageModel,
54
+ embed: defaultEmbedModel,
55
+ };
56
+ this.timeout = timeout;
57
+ this.maxRetries = maxRetries;
58
+ this._fetch =
59
+ customFetch ??
60
+ (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null);
61
+
62
+ if (!this._fetch) {
63
+ throw new AIFlowError(
64
+ 'global fetch is not available — pass a fetch implementation via options.fetch (Node 18+ or a polyfill).',
65
+ );
66
+ }
67
+
68
+ // Lazily-loaded server config — populated on first call to
69
+ // getConfig() / chat() / generateImage() / embed().
70
+ this._config = null;
71
+ this._configPromise = null;
72
+ }
73
+
74
+ /**
75
+ * Fetch (and cache) the server-side AIFlow config. Subsequent calls
76
+ * return the cached object; pass `{ refresh: true }` to force a reload.
77
+ *
78
+ * @returns {Promise<{appId:string, models:{chat:string[],image:string[],embed:string[]}, defaults:{chat:string,image:string,embed:string}, limits:{maxTokens:number,maxImageN:number,maxEmbedInputs:number}, creditValue:number}>}
79
+ */
80
+ async getConfig({ refresh = false } = {}) {
81
+ if (refresh) {
82
+ this._config = null;
83
+ this._configPromise = null;
84
+ }
85
+ if (this._config) return this._config;
86
+ if (!this._configPromise) {
87
+ this._configPromise = this._loadConfig().catch((err) => {
88
+ this._configPromise = null; // allow a future retry
89
+ throw err;
90
+ });
91
+ }
92
+ this._config = await this._configPromise;
93
+ return this._config;
94
+ }
95
+
96
+ async _loadConfig() {
97
+ const url = `${this.baseUrl}/config`;
98
+ const res = await this._fetch(url, {
99
+ method: 'GET',
100
+ headers: {
101
+ Accept: 'application/json',
102
+ 'x-app-id': this.appId,
103
+ },
104
+ });
105
+ if (!res.ok) {
106
+ const payload = await safeJson(res);
107
+ throw new AIFlowError(
108
+ payload?.message ||
109
+ `Failed to load AIFlow config (status ${res.status})`,
110
+ {
111
+ status: res.status,
112
+ code: payload?.code,
113
+ requestId: res.headers?.get?.('x-request-id') || undefined,
114
+ },
115
+ );
116
+ }
117
+ return await res.json();
118
+ }
119
+
120
+ async _resolveDefaultModel(kind) {
121
+ const userOverride = this._userDefaults[kind];
122
+ if (userOverride) return userOverride;
123
+ const cfg = await this.getConfig();
124
+ return cfg.defaults[kind];
125
+ }
126
+
127
+ /**
128
+ * Non-streaming chat completion.
129
+ * @returns {Promise<{id:string, model:string, content:string, usage:{inputTokens:number,outputTokens:number,creditsUsed:number}}>}
130
+ */
131
+ async chat({
132
+ messages,
133
+ model,
134
+ system,
135
+ maxTokens,
136
+ temperature,
137
+ tools,
138
+ signal,
139
+ } = {}) {
140
+ if (!Array.isArray(messages) || messages.length === 0) {
141
+ throw new AIFlowError('messages must be a non-empty array');
142
+ }
143
+ const resolvedModel = model || (await this._resolveDefaultModel('chat'));
144
+ const res = await this._request(
145
+ '/chat',
146
+ {
147
+ model: resolvedModel,
148
+ system,
149
+ messages,
150
+ maxTokens,
151
+ temperature,
152
+ tools,
153
+ },
154
+ { signal },
155
+ );
156
+ return await res.json();
157
+ }
158
+
159
+ /**
160
+ * Streaming chat completion. Yields `{ delta: string, done: boolean }`
161
+ * chunks as server-sent events arrive.
162
+ */
163
+ async *chatStream({
164
+ messages,
165
+ model,
166
+ system,
167
+ maxTokens,
168
+ temperature,
169
+ tools,
170
+ signal,
171
+ } = {}) {
172
+ if (!Array.isArray(messages) || messages.length === 0) {
173
+ throw new AIFlowError('messages must be a non-empty array');
174
+ }
175
+ const resolvedModel = model || (await this._resolveDefaultModel('chat'));
176
+ const res = await this._request(
177
+ '/chat/stream',
178
+ {
179
+ model: resolvedModel,
180
+ system,
181
+ messages,
182
+ maxTokens,
183
+ temperature,
184
+ tools,
185
+ stream: true,
186
+ },
187
+ { signal, stream: true },
188
+ );
189
+
190
+ if (!res.body || typeof res.body.getReader !== 'function') {
191
+ throw new AIFlowError(
192
+ 'Streaming response is not readable — your fetch implementation must expose a ReadableStream body.',
193
+ );
194
+ }
195
+
196
+ const reader = res.body.getReader();
197
+ const decoder = new TextDecoder();
198
+ let buffer = '';
199
+
200
+ try {
201
+ while (true) {
202
+ const { value, done } = await reader.read();
203
+ if (done) break;
204
+ buffer += decoder.decode(value, { stream: true });
205
+
206
+ let idx;
207
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
208
+ const rawEvent = buffer.slice(0, idx);
209
+ buffer = buffer.slice(idx + 2);
210
+ const parsed = parseSseEvent(rawEvent);
211
+ if (parsed === null) continue;
212
+ yield parsed;
213
+ if (parsed.done) return;
214
+ }
215
+ }
216
+ } finally {
217
+ try {
218
+ reader.releaseLock();
219
+ } catch {
220
+ /* ignore */
221
+ }
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Generate one or more images from a text prompt.
227
+ * @returns {Promise<{images: Array<{url?:string,b64?:string,mimeType:string}>, usage:{creditsUsed:number}}>}
228
+ */
229
+ async generateImage({
230
+ prompt,
231
+ model,
232
+ size = '1024x1024',
233
+ n = 1,
234
+ signal,
235
+ } = {}) {
236
+ if (!prompt || typeof prompt !== 'string') {
237
+ throw new AIFlowError('prompt is required');
238
+ }
239
+ const resolvedModel =
240
+ model || (await this._resolveDefaultModel('image'));
241
+ const res = await this._request(
242
+ '/image',
243
+ {
244
+ model: resolvedModel,
245
+ prompt,
246
+ size,
247
+ n,
248
+ },
249
+ { signal },
250
+ );
251
+ return await res.json();
252
+ }
253
+
254
+ /**
255
+ * Compute embeddings for one or more input strings.
256
+ * @returns {Promise<{data: Array<{embedding:number[], index:number}>, usage:{creditsUsed:number}}>}
257
+ */
258
+ async embed({ input, model, signal } = {}) {
259
+ if (input == null) throw new AIFlowError('input is required');
260
+ const resolvedModel =
261
+ model || (await this._resolveDefaultModel('embed'));
262
+ const res = await this._request(
263
+ '/embed',
264
+ {
265
+ model: resolvedModel,
266
+ input: Array.isArray(input) ? input : [input],
267
+ },
268
+ { signal },
269
+ );
270
+ return await res.json();
271
+ }
272
+
273
+ // ────────────────────────────────────────────────────────────────────────
274
+ // Internals
275
+ // ────────────────────────────────────────────────────────────────────────
276
+
277
+ async _request(path, body, { signal, stream = false } = {}) {
278
+ const url = `${this.baseUrl}${path}`;
279
+ const headers = {
280
+ 'Content-Type': 'application/json',
281
+ 'x-app-id': this.appId,
282
+ Accept: stream ? 'text/event-stream' : 'application/json',
283
+ };
284
+
285
+ let attempt = 0;
286
+ while (true) {
287
+ const timeoutCtrl = new AbortController();
288
+ const timer = setTimeout(
289
+ () => timeoutCtrl.abort(),
290
+ this.timeout,
291
+ );
292
+ const composedSignal = anySignal(signal, timeoutCtrl.signal);
293
+
294
+ let res;
295
+ try {
296
+ res = await this._fetch(url, {
297
+ method: 'POST',
298
+ headers,
299
+ body: JSON.stringify(body),
300
+ signal: composedSignal,
301
+ });
302
+ } catch (err) {
303
+ clearTimeout(timer);
304
+ if (signal?.aborted) throw err;
305
+ if (attempt < this.maxRetries) {
306
+ attempt += 1;
307
+ await sleep(backoffMs(attempt));
308
+ continue;
309
+ }
310
+ throw new AIFlowError(
311
+ `Network error calling ${path}: ${err?.message || err}`,
312
+ { cause: err },
313
+ );
314
+ }
315
+ clearTimeout(timer);
316
+
317
+ if (!res.ok) {
318
+ if (
319
+ RETRY_STATUSES.has(res.status) &&
320
+ attempt < this.maxRetries
321
+ ) {
322
+ attempt += 1;
323
+ await sleep(backoffMs(attempt));
324
+ continue;
325
+ }
326
+ const payload = await safeJson(res);
327
+ throw new AIFlowError(
328
+ payload?.message || `Request failed with status ${res.status}`,
329
+ {
330
+ status: res.status,
331
+ code: payload?.code,
332
+ requestId:
333
+ res.headers?.get?.('x-request-id') || undefined,
334
+ },
335
+ );
336
+ }
337
+
338
+ return res;
339
+ }
340
+ }
341
+ }
342
+
343
+ // ────────────────────────────────────────────────────────────────────────────
344
+ // Helpers
345
+ // ────────────────────────────────────────────────────────────────────────────
346
+
347
+ function parseSseEvent(rawEvent) {
348
+ const trimmed = rawEvent.trim();
349
+ if (!trimmed) return null;
350
+ const lines = trimmed.split(/\r?\n/);
351
+ let dataChunks = [];
352
+ for (const line of lines) {
353
+ if (line.startsWith(':')) continue; // SSE comment
354
+ if (line.startsWith('data:')) {
355
+ dataChunks.push(line.slice(5).trimStart());
356
+ }
357
+ }
358
+ const data = dataChunks.join('\n');
359
+ if (!data) return null;
360
+ if (data === '[DONE]') return { delta: '', done: true };
361
+ try {
362
+ const parsed = JSON.parse(data);
363
+ if (typeof parsed !== 'object' || parsed === null) {
364
+ return { delta: String(parsed), done: false };
365
+ }
366
+ return { delta: '', done: false, ...parsed };
367
+ } catch {
368
+ return { delta: data, done: false };
369
+ }
370
+ }
371
+
372
+ function anySignal(a, b) {
373
+ if (!a) return b;
374
+ if (!b) return a;
375
+ if (a.aborted) return a;
376
+ if (b.aborted) return b;
377
+ const ctrl = new AbortController();
378
+ const onAbort = (src) => () => ctrl.abort(src.reason);
379
+ a.addEventListener('abort', onAbort(a), { once: true });
380
+ b.addEventListener('abort', onAbort(b), { once: true });
381
+ return ctrl.signal;
382
+ }
383
+
384
+ function sleep(ms) {
385
+ return new Promise((resolve) => setTimeout(resolve, ms));
386
+ }
387
+
388
+ function backoffMs(attempt) {
389
+ const base = 500 * Math.pow(2, attempt - 1);
390
+ return base + Math.floor(Math.random() * 250);
391
+ }
392
+
393
+ async function safeJson(res) {
394
+ try {
395
+ return await res.json();
396
+ } catch {
397
+ return null;
398
+ }
399
+ }
400
+
401
+ export default AIFlowClient;