@ragion/sdk 0.1.0-alpha.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.
@@ -0,0 +1,235 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ const DEFAULT_CONFIG = {
11
+ baseUrl: "https://api.ragion.com.br",
12
+ timeout: 30000,
13
+ retryAttempts: 3,
14
+ retryDelay: 1000,
15
+ };
16
+ const generateRequestId = () => {
17
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
18
+ };
19
+ const sleep = (ms) => {
20
+ return new Promise(resolve => setTimeout(resolve, ms));
21
+ };
22
+ const isRetryableError = (status) => {
23
+ return status >= 500 || status === 429;
24
+ };
25
+ const safeJsonParse = (response) => __awaiter(void 0, void 0, void 0, function* () {
26
+ const text = yield response.text();
27
+ if (!text)
28
+ return null;
29
+ try {
30
+ return JSON.parse(text);
31
+ }
32
+ catch (_a) {
33
+ return null;
34
+ }
35
+ });
36
+ const buildErrorResponse = (error, requestId, status) => {
37
+ if (error instanceof Error) {
38
+ return {
39
+ data: null,
40
+ status: status || 0,
41
+ ok: false,
42
+ error: {
43
+ error: "NetworkError",
44
+ message: error.message,
45
+ statusCode: status || 0,
46
+ requestId,
47
+ },
48
+ requestId,
49
+ };
50
+ }
51
+ return {
52
+ data: null,
53
+ status: status || 500,
54
+ ok: false,
55
+ error: {
56
+ error: "UnknownError",
57
+ message: "An unknown error occurred",
58
+ statusCode: status || 500,
59
+ requestId,
60
+ },
61
+ requestId,
62
+ };
63
+ };
64
+ const combineAbortSignals = (signal1, signal2) => {
65
+ const combinedController = new AbortController();
66
+ signal1.addEventListener("abort", () => combinedController.abort());
67
+ signal2.addEventListener("abort", () => combinedController.abort());
68
+ return combinedController.signal;
69
+ };
70
+ export class RagionClient {
71
+ constructor(config) {
72
+ var _a;
73
+ this.createHeaders = (customHeaders) => {
74
+ const headers = Object.assign({ "Content-Type": "application/json", "x-Api-Key": this.config.apiKey }, customHeaders);
75
+ return headers;
76
+ };
77
+ this.getBaseUrl = () => {
78
+ return this.config.baseUrl;
79
+ };
80
+ this.fetchWithTimeout = (url, options, timeout) => __awaiter(this, void 0, void 0, function* () {
81
+ const controller = new AbortController();
82
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
83
+ try {
84
+ const signal = options.signal ? combineAbortSignals(options.signal, controller.signal) : controller.signal;
85
+ const response = yield fetch(url, Object.assign(Object.assign({}, options), { signal }));
86
+ clearTimeout(timeoutId);
87
+ return response;
88
+ }
89
+ catch (error) {
90
+ clearTimeout(timeoutId);
91
+ if (error instanceof Error && error.name === "AbortError") {
92
+ throw new Error(`Request timeout after ${timeout}ms`);
93
+ }
94
+ throw error;
95
+ }
96
+ });
97
+ this.prepareHeaders = (options) => {
98
+ const isMultipart = options.body instanceof FormData;
99
+ const headers = {};
100
+ if (!isMultipart) {
101
+ Object.assign(headers, this.createHeaders());
102
+ }
103
+ else {
104
+ const authHeaders = this.createHeaders();
105
+ Object.entries(authHeaders).forEach(([key, value]) => {
106
+ if (key.toLowerCase() !== "content-type") {
107
+ headers[key] = value;
108
+ }
109
+ });
110
+ }
111
+ if (options.headers) {
112
+ Object.assign(headers, options.headers);
113
+ }
114
+ return headers;
115
+ };
116
+ this.prepareBody = (body) => {
117
+ if (!body)
118
+ return undefined;
119
+ if (body instanceof FormData) {
120
+ return body;
121
+ }
122
+ return JSON.stringify(body);
123
+ };
124
+ this.handleErrorResponse = (response, data, requestId, attempt) => {
125
+ const errorData = data || {
126
+ error: "HTTPError",
127
+ message: response.statusText,
128
+ statusCode: response.status,
129
+ };
130
+ if (response.status < 500 && response.status !== 429) {
131
+ return {
132
+ data: null,
133
+ status: response.status,
134
+ ok: false,
135
+ error: Object.assign(Object.assign({}, errorData), { requestId }),
136
+ requestId,
137
+ };
138
+ }
139
+ if (attempt < this.config.retryAttempts && isRetryableError(response.status)) {
140
+ return null;
141
+ }
142
+ return {
143
+ data: null,
144
+ status: response.status,
145
+ ok: false,
146
+ error: Object.assign(Object.assign({}, errorData), { requestId }),
147
+ requestId,
148
+ };
149
+ };
150
+ this.request = (endpoint_1, ...args_1) => __awaiter(this, [endpoint_1, ...args_1], void 0, function* (endpoint, options = {}) {
151
+ var _a;
152
+ const requestId = generateRequestId();
153
+ const url = `${this.config.baseUrl}${endpoint}`;
154
+ const method = options.method || "GET";
155
+ const timeout = options.timeout || this.config.timeout;
156
+ const headers = this.prepareHeaders(options);
157
+ const body = this.prepareBody(options.body);
158
+ let lastError = null;
159
+ let lastStatus;
160
+ for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
161
+ try {
162
+ const response = yield this.fetchWithTimeout(url, {
163
+ method,
164
+ headers,
165
+ body,
166
+ signal: options.signal,
167
+ }, timeout);
168
+ lastStatus = response.status;
169
+ const data = yield safeJsonParse(response);
170
+ if (!response.ok) {
171
+ const errorResponse = this.handleErrorResponse(response, data, requestId, attempt);
172
+ if (errorResponse === null) {
173
+ yield sleep(this.config.retryDelay * (attempt + 1));
174
+ continue;
175
+ }
176
+ return errorResponse;
177
+ }
178
+ return {
179
+ data: data,
180
+ status: response.status,
181
+ ok: true,
182
+ requestId,
183
+ };
184
+ }
185
+ catch (error) {
186
+ lastError = error instanceof Error ? error : new Error(String(error));
187
+ if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
188
+ return buildErrorResponse(lastError, requestId, 0);
189
+ }
190
+ if (attempt < this.config.retryAttempts) {
191
+ yield sleep(this.config.retryDelay * (attempt + 1));
192
+ continue;
193
+ }
194
+ }
195
+ }
196
+ return buildErrorResponse(lastError || new Error("Request failed"), requestId, lastStatus);
197
+ });
198
+ this.get = (endpoint, options) => __awaiter(this, void 0, void 0, function* () {
199
+ return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "GET" }));
200
+ });
201
+ this.post = (endpoint, body, options) => __awaiter(this, void 0, void 0, function* () {
202
+ return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "POST", body }));
203
+ });
204
+ this.patch = (endpoint, body, options) => __awaiter(this, void 0, void 0, function* () {
205
+ return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "PATCH", body }));
206
+ });
207
+ this.delete = (endpoint, options) => __awaiter(this, void 0, void 0, function* () {
208
+ return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "DELETE" }));
209
+ });
210
+ this.updateConfig = (config) => {
211
+ if (config.apiKey) {
212
+ this.config.apiKey = config.apiKey;
213
+ }
214
+ if (config.timeout !== undefined) {
215
+ this.config.timeout = config.timeout;
216
+ }
217
+ if (config.retryAttempts !== undefined) {
218
+ this.config.retryAttempts = config.retryAttempts;
219
+ }
220
+ if (config.retryDelay !== undefined) {
221
+ this.config.retryDelay = config.retryDelay;
222
+ }
223
+ };
224
+ if (!config.apiKey) {
225
+ throw new Error("API Key is required");
226
+ }
227
+ this.config = {
228
+ apiKey: config.apiKey,
229
+ baseUrl: DEFAULT_CONFIG.baseUrl,
230
+ timeout: config.timeout || DEFAULT_CONFIG.timeout,
231
+ retryAttempts: (_a = config.retryAttempts) !== null && _a !== void 0 ? _a : DEFAULT_CONFIG.retryAttempts,
232
+ retryDelay: config.retryDelay || DEFAULT_CONFIG.retryDelay,
233
+ };
234
+ }
235
+ }
@@ -0,0 +1,4 @@
1
+ export { ChatModule } from "./chat";
2
+ export { RagionClient } from "./client";
3
+ export { RagionSDK } from "./sdk";
4
+ export { createStreamingRequest, SSEParser } from "./streaming";
@@ -0,0 +1,37 @@
1
+ import { ChatModule } from "./chat";
2
+ import { RagionClient } from "./client";
3
+ /**
4
+ * Main SDK class for interacting with Ragion API
5
+ * @example
6
+ * ```typescript
7
+ * const sdk = new RagionSDK({
8
+ * apiKey: 'your-api-key'
9
+ * });
10
+ * ```
11
+ */
12
+ export class RagionSDK {
13
+ /**
14
+ * Creates a new instance of RagionSDK
15
+ * @param config - Configuration object containing API key and optional settings
16
+ * @param config.apiKey - Your API key for authentication (required)
17
+ * @param config.timeout - Request timeout in milliseconds (optional, default: 30000)
18
+ * @param config.retryAttempts - Number of retry attempts for failed requests (optional, default: 3)
19
+ * @param config.retryDelay - Delay between retries in milliseconds (optional, default: 1000)
20
+ * @throws {Error} If API key is not provided
21
+ */
22
+ constructor(config) {
23
+ /**
24
+ * Updates the SDK configuration
25
+ * @param config - Partial configuration object with properties to update
26
+ * @example
27
+ * ```typescript
28
+ * sdk.updateConfig({ timeout: 60000 });
29
+ * ```
30
+ */
31
+ this.updateConfig = (config) => {
32
+ this.client.updateConfig(config);
33
+ };
34
+ this.client = new RagionClient(config);
35
+ this.chat = new ChatModule(this.client);
36
+ }
37
+ }
@@ -0,0 +1,143 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export class SSEParser {
11
+ constructor() {
12
+ this.buffer = "";
13
+ this.processChunk = (chunk, callbacks) => {
14
+ var _a;
15
+ this.buffer += this.decoder.decode(chunk, { stream: true });
16
+ const lines = this.buffer.split("\n");
17
+ this.buffer = lines.pop() || "";
18
+ for (const line of lines) {
19
+ const trimmedLine = line.trim();
20
+ if (!trimmedLine)
21
+ continue;
22
+ if (trimmedLine.startsWith("data: ")) {
23
+ const data = trimmedLine.slice(6);
24
+ if (data === "[DONE]") {
25
+ (_a = callbacks.onDone) === null || _a === void 0 ? void 0 : _a.call(callbacks);
26
+ return;
27
+ }
28
+ this.processDataLine(data, callbacks);
29
+ }
30
+ }
31
+ };
32
+ this.processDataLine = (data, callbacks) => {
33
+ var _a, _b, _c;
34
+ try {
35
+ const parsedData = JSON.parse(data);
36
+ if (parsedData.type === "error" || parsedData.error) {
37
+ const error = new Error(parsedData.message || parsedData.error || "Unknown error occurred");
38
+ (_a = callbacks.onError) === null || _a === void 0 ? void 0 : _a.call(callbacks, error);
39
+ return;
40
+ }
41
+ (_b = callbacks.onData) === null || _b === void 0 ? void 0 : _b.call(callbacks, data);
42
+ }
43
+ catch (_d) {
44
+ (_c = callbacks.onData) === null || _c === void 0 ? void 0 : _c.call(callbacks, data);
45
+ }
46
+ };
47
+ this.processFinal = (callbacks) => {
48
+ var _a, _b;
49
+ if (this.buffer.trim()) {
50
+ const trimmedLine = this.buffer.trim();
51
+ if (trimmedLine.startsWith("data: ")) {
52
+ const data = trimmedLine.slice(6);
53
+ if (data !== "[DONE]") {
54
+ (_a = callbacks.onData) === null || _a === void 0 ? void 0 : _a.call(callbacks, data);
55
+ }
56
+ }
57
+ }
58
+ (_b = callbacks.onDone) === null || _b === void 0 ? void 0 : _b.call(callbacks);
59
+ };
60
+ this.reset = () => {
61
+ this.buffer = "";
62
+ };
63
+ this.decoder = new TextDecoder();
64
+ }
65
+ }
66
+ export const createStreamingRequest = (url, options) => {
67
+ const { method = "POST", headers = {}, body, signal, timeout = 30000, onChunk, onComplete, onError } = options;
68
+ const abortController = new AbortController();
69
+ const combinedSignal = signal
70
+ ? (() => {
71
+ const combined = new AbortController();
72
+ signal.addEventListener("abort", () => combined.abort());
73
+ abortController.signal.addEventListener("abort", () => combined.abort());
74
+ return combined.signal;
75
+ })()
76
+ : abortController.signal;
77
+ const timeoutId = setTimeout(() => {
78
+ abortController.abort();
79
+ }, timeout);
80
+ const parser = new SSEParser();
81
+ const performStream = () => __awaiter(void 0, void 0, void 0, function* () {
82
+ var _a;
83
+ try {
84
+ const requestHeaders = new Headers(headers);
85
+ requestHeaders.set("Accept", "text/event-stream");
86
+ const response = yield fetch(url, {
87
+ method,
88
+ headers: requestHeaders,
89
+ body: body ? JSON.stringify(body) : undefined,
90
+ signal: combinedSignal,
91
+ });
92
+ clearTimeout(timeoutId);
93
+ if (!response.ok) {
94
+ const errorText = yield response.text().catch(() => "Unknown error");
95
+ throw new Error(`HTTP ${response.status}: ${response.statusText} - ${errorText}`);
96
+ }
97
+ const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();
98
+ if (!reader) {
99
+ throw new Error("Response body is not readable");
100
+ }
101
+ while (true) {
102
+ const { done, value } = yield reader.read();
103
+ if (done) {
104
+ parser.processFinal({
105
+ onData: onChunk,
106
+ onDone: onComplete,
107
+ });
108
+ break;
109
+ }
110
+ parser.processChunk(value, {
111
+ onData: onChunk,
112
+ onError: error => {
113
+ reader.cancel();
114
+ onError === null || onError === void 0 ? void 0 : onError(error);
115
+ },
116
+ onDone: () => {
117
+ reader.cancel();
118
+ onComplete === null || onComplete === void 0 ? void 0 : onComplete();
119
+ },
120
+ });
121
+ }
122
+ }
123
+ catch (error) {
124
+ clearTimeout(timeoutId);
125
+ if (error instanceof Error && error.name === "AbortError") {
126
+ onError === null || onError === void 0 ? void 0 : onError(new Error("Request aborted"));
127
+ }
128
+ else if (error instanceof Error) {
129
+ onError === null || onError === void 0 ? void 0 : onError(error);
130
+ }
131
+ else {
132
+ onError === null || onError === void 0 ? void 0 : onError(new Error(String(error)));
133
+ }
134
+ }
135
+ });
136
+ performStream();
137
+ return {
138
+ abort: () => {
139
+ clearTimeout(timeoutId);
140
+ abortController.abort();
141
+ },
142
+ };
143
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ export { ChatModule } from "./chat";
2
+ export { RagionClient } from "./client";
3
+ export { RagionSDK } from "./sdk";
4
+ export { createStreamingRequest, SSEParser } from "./streaming";
5
+ export type { ApiError, ApiResponse, ChatMessage, ChatOptions, RagionConfig, RequestOptions, StreamingController } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SSEParser = exports.createStreamingRequest = exports.RagionSDK = exports.RagionClient = exports.ChatModule = void 0;
4
+ var chat_1 = require("./chat");
5
+ Object.defineProperty(exports, "ChatModule", { enumerable: true, get: function () { return chat_1.ChatModule; } });
6
+ var client_1 = require("./client");
7
+ Object.defineProperty(exports, "RagionClient", { enumerable: true, get: function () { return client_1.RagionClient; } });
8
+ var sdk_1 = require("./sdk");
9
+ Object.defineProperty(exports, "RagionSDK", { enumerable: true, get: function () { return sdk_1.RagionSDK; } });
10
+ var streaming_1 = require("./streaming");
11
+ Object.defineProperty(exports, "createStreamingRequest", { enumerable: true, get: function () { return streaming_1.createStreamingRequest; } });
12
+ Object.defineProperty(exports, "SSEParser", { enumerable: true, get: function () { return streaming_1.SSEParser; } });
package/dist/sdk.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { ChatModule } from "./chat";
2
+ import type { RagionConfig } from "./types";
3
+ /**
4
+ * Main SDK class for interacting with Ragion API
5
+ * @example
6
+ * ```typescript
7
+ * const sdk = new RagionSDK({
8
+ * apiKey: 'your-api-key'
9
+ * });
10
+ * ```
11
+ */
12
+ export declare class RagionSDK {
13
+ readonly chat: ChatModule;
14
+ private client;
15
+ /**
16
+ * Creates a new instance of RagionSDK
17
+ * @param config - Configuration object containing API key and optional settings
18
+ * @param config.apiKey - Your API key for authentication (required)
19
+ * @param config.timeout - Request timeout in milliseconds (optional, default: 30000)
20
+ * @param config.retryAttempts - Number of retry attempts for failed requests (optional, default: 3)
21
+ * @param config.retryDelay - Delay between retries in milliseconds (optional, default: 1000)
22
+ * @throws {Error} If API key is not provided
23
+ */
24
+ constructor(config: RagionConfig);
25
+ /**
26
+ * Updates the SDK configuration
27
+ * @param config - Partial configuration object with properties to update
28
+ * @example
29
+ * ```typescript
30
+ * sdk.updateConfig({ timeout: 60000 });
31
+ * ```
32
+ */
33
+ updateConfig: (config: Partial<RagionConfig>) => void;
34
+ }
package/dist/sdk.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RagionSDK = void 0;
4
+ const chat_1 = require("./chat");
5
+ const client_1 = require("./client");
6
+ /**
7
+ * Main SDK class for interacting with Ragion API
8
+ * @example
9
+ * ```typescript
10
+ * const sdk = new RagionSDK({
11
+ * apiKey: 'your-api-key'
12
+ * });
13
+ * ```
14
+ */
15
+ class RagionSDK {
16
+ /**
17
+ * Creates a new instance of RagionSDK
18
+ * @param config - Configuration object containing API key and optional settings
19
+ * @param config.apiKey - Your API key for authentication (required)
20
+ * @param config.timeout - Request timeout in milliseconds (optional, default: 30000)
21
+ * @param config.retryAttempts - Number of retry attempts for failed requests (optional, default: 3)
22
+ * @param config.retryDelay - Delay between retries in milliseconds (optional, default: 1000)
23
+ * @throws {Error} If API key is not provided
24
+ */
25
+ constructor(config) {
26
+ /**
27
+ * Updates the SDK configuration
28
+ * @param config - Partial configuration object with properties to update
29
+ * @example
30
+ * ```typescript
31
+ * sdk.updateConfig({ timeout: 60000 });
32
+ * ```
33
+ */
34
+ this.updateConfig = (config) => {
35
+ this.client.updateConfig(config);
36
+ };
37
+ this.client = new client_1.RagionClient(config);
38
+ this.chat = new chat_1.ChatModule(this.client);
39
+ }
40
+ }
41
+ exports.RagionSDK = RagionSDK;
@@ -0,0 +1,28 @@
1
+ export declare class SSEParser {
2
+ private buffer;
3
+ private decoder;
4
+ constructor();
5
+ processChunk: (chunk: Uint8Array, callbacks: {
6
+ onData?: (data: string) => void;
7
+ onError?: (error: Error) => void;
8
+ onDone?: () => void;
9
+ }) => void;
10
+ private processDataLine;
11
+ processFinal: (callbacks: {
12
+ onData?: (data: string) => void;
13
+ onDone?: () => void;
14
+ }) => void;
15
+ reset: () => void;
16
+ }
17
+ export declare const createStreamingRequest: (url: string, options: {
18
+ method?: string;
19
+ headers?: HeadersInit;
20
+ body?: unknown;
21
+ signal?: AbortSignal;
22
+ timeout?: number;
23
+ onChunk?: (chunk: string) => void;
24
+ onComplete?: () => void;
25
+ onError?: (error: Error) => void;
26
+ }) => {
27
+ abort: () => void;
28
+ };