@codetunezstudios/token-kit 0.1.0-beta.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.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Token-Kit SDK - Type Definitions
3
+ * TypeScript types for the Token-Kit SDK
4
+ */
5
+ type MessageRole = 'system' | 'user' | 'assistant';
6
+ interface Message {
7
+ role: MessageRole;
8
+ content: string;
9
+ }
10
+ interface ChatOptions {
11
+ /** LLM model to use (default: 'gpt-3.5-turbo') */
12
+ model?: string;
13
+ /** Maximum tokens in response (default: 500) */
14
+ maxTokens?: number;
15
+ /** Temperature for response randomness 0-2 (default: 0.7) */
16
+ temperature?: number;
17
+ }
18
+ interface ChatResponse {
19
+ /** Unique chat completion ID */
20
+ id: string;
21
+ /** Model used for completion */
22
+ model: string;
23
+ /** Assistant's response message */
24
+ message: Message;
25
+ /** Token usage statistics */
26
+ tokensUsed: {
27
+ prompt: number;
28
+ completion: number;
29
+ total: number;
30
+ };
31
+ /** Number of tokens deducted from user balance */
32
+ tokensDeducted: number;
33
+ /** Reason completion finished */
34
+ finishReason: string;
35
+ /** User's remaining token balance */
36
+ userBalance?: number;
37
+ /** Response latency in milliseconds */
38
+ latency?: number;
39
+ }
40
+ interface TokenValidationResponse {
41
+ /** Whether the token is valid */
42
+ valid: boolean;
43
+ /** User information */
44
+ user?: {
45
+ id: string;
46
+ email: string;
47
+ };
48
+ /** Current token balance */
49
+ balance?: number;
50
+ /** Daily spending so far */
51
+ dailySpending?: number;
52
+ /** Monthly spending so far */
53
+ monthlySpending?: number;
54
+ /** Spending limits */
55
+ limits?: {
56
+ dailyLimit: number;
57
+ monthlyLimit: number;
58
+ perRequestLimit: number;
59
+ };
60
+ }
61
+ interface ModelInfo {
62
+ /** Model identifier */
63
+ name: string;
64
+ /** Human-readable model name */
65
+ displayName: string;
66
+ /** Token rate multiplier */
67
+ tokenRate: number;
68
+ /** Default max tokens */
69
+ defaultMaxTokens: number;
70
+ }
71
+ interface ModelsResponse {
72
+ models: string[];
73
+ count: number;
74
+ }
75
+ interface TokenKitError extends Error {
76
+ /** Error code */
77
+ code: string;
78
+ /** HTTP status code */
79
+ statusCode?: number;
80
+ /** Additional error details */
81
+ details?: unknown;
82
+ }
83
+ declare class TokenKitAPIError extends Error implements TokenKitError {
84
+ code: string;
85
+ statusCode?: number;
86
+ details?: unknown;
87
+ constructor(message: string, code: string, statusCode?: number, details?: unknown);
88
+ }
89
+ interface TokenKitConfig {
90
+ /** Developer API key */
91
+ apiKey: string;
92
+ /** API Gateway base URL (default: https://api.token-kit.com) */
93
+ baseUrl?: string;
94
+ /** Request timeout in milliseconds (default: 60000) */
95
+ timeout?: number;
96
+ }
97
+
98
+ /**
99
+ * Token-Kit SDK - Main Entry Point
100
+ * Official TypeScript SDK for Token-Kit platform
101
+ */
102
+
103
+ /**
104
+ * TokenKit - Main SDK class
105
+ *
106
+ * Example usage:
107
+ * ```typescript
108
+ * const tokenKit = new TokenKit({ apiKey: 'your-api-key' });
109
+ *
110
+ * const response = await tokenKit.chat('user-token', [
111
+ * { role: 'user', content: 'Hello!' }
112
+ * ]);
113
+ *
114
+ * console.log(response.message.content);
115
+ * ```
116
+ */
117
+ declare class TokenKit {
118
+ private client;
119
+ private userToken;
120
+ /**
121
+ * Create a new TokenKit instance
122
+ *
123
+ * @param config - Configuration options
124
+ * @param config.apiKey - Your developer API key
125
+ * @param config.baseUrl - API base URL (optional, defaults to production)
126
+ * @param config.timeout - Request timeout in ms (optional, defaults to 60000)
127
+ */
128
+ constructor(config: TokenKitConfig);
129
+ /**
130
+ * Set the user token for subsequent requests
131
+ * This allows you to omit the userToken parameter in other methods
132
+ *
133
+ * @param userToken - The user's token
134
+ */
135
+ setUserToken(userToken: string): void;
136
+ /**
137
+ * Send a chat completion request
138
+ *
139
+ * @param userTokenOrMessages - User token string OR array of messages (if user token was set)
140
+ * @param messagesOrOptions - Array of messages OR chat options (if first param is user token)
141
+ * @param options - Chat options (only if first two params are provided)
142
+ * @returns Chat completion response
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * // With explicit user token
147
+ * const response = await tokenKit.chat('user-token', [
148
+ * { role: 'user', content: 'What is Token-Kit?' }
149
+ * ]);
150
+ *
151
+ * // With pre-set user token
152
+ * tokenKit.setUserToken('user-token');
153
+ * const response = await tokenKit.chat([
154
+ * { role: 'user', content: 'What is Token-Kit?' }
155
+ * ]);
156
+ *
157
+ * // With options
158
+ * const response = await tokenKit.chat('user-token', [
159
+ * { role: 'system', content: 'You are a helpful assistant.' },
160
+ * { role: 'user', content: 'Hello!' }
161
+ * ], {
162
+ * model: 'gpt-4',
163
+ * maxTokens: 200,
164
+ * temperature: 0.8
165
+ * });
166
+ * ```
167
+ */
168
+ chat(userTokenOrMessages: string | Message[], messagesOrOptions?: Message[] | ChatOptions, options?: ChatOptions): Promise<ChatResponse>;
169
+ /**
170
+ * Validate a user token and check balance
171
+ *
172
+ * @param userToken - User token to validate (optional if already set)
173
+ * @returns Token validation response with balance and limits
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * const validation = await tokenKit.validateToken('user-token');
178
+ * console.log('Balance:', validation.balance);
179
+ * console.log('Daily spending:', validation.dailySpending);
180
+ * ```
181
+ */
182
+ validateToken(userToken?: string): Promise<TokenValidationResponse>;
183
+ /**
184
+ * Get balance for the current user token
185
+ *
186
+ * @param userToken - User token (optional if already set)
187
+ * @returns Current token balance
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * const balance = await tokenKit.getBalance('user-token');
192
+ * console.log(`You have ${balance} tokens remaining`);
193
+ * ```
194
+ */
195
+ getBalance(userToken?: string): Promise<number>;
196
+ /**
197
+ * Get list of available LLM models
198
+ *
199
+ * @returns Array of model names
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const models = await tokenKit.getModels();
204
+ * console.log('Available models:', models);
205
+ * // ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo']
206
+ * ```
207
+ */
208
+ getModels(): Promise<string[]>;
209
+ /**
210
+ * Helper method to create a simple user message
211
+ *
212
+ * @param content - Message content
213
+ * @returns Message object
214
+ */
215
+ static user(content: string): Message;
216
+ /**
217
+ * Helper method to create a system message
218
+ *
219
+ * @param content - Message content
220
+ * @returns Message object
221
+ */
222
+ static system(content: string): Message;
223
+ /**
224
+ * Helper method to create an assistant message
225
+ *
226
+ * @param content - Message content
227
+ * @returns Message object
228
+ */
229
+ static assistant(content: string): Message;
230
+ }
231
+
232
+ export { type ChatOptions, type ChatResponse, type Message, type MessageRole, type ModelInfo, type ModelsResponse, TokenKit, TokenKitAPIError, type TokenKitConfig, type TokenValidationResponse, TokenKit as default };
package/dist/index.js ADDED
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ TokenKit: () => TokenKit,
34
+ TokenKitAPIError: () => TokenKitAPIError,
35
+ default: () => index_default
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/client.ts
40
+ var import_axios = __toESM(require("axios"));
41
+
42
+ // src/types.ts
43
+ var TokenKitAPIError = class extends Error {
44
+ constructor(message, code, statusCode, details) {
45
+ super(message);
46
+ this.name = "TokenKitAPIError";
47
+ this.code = code;
48
+ this.statusCode = statusCode;
49
+ this.details = details;
50
+ Error.captureStackTrace?.(this, this.constructor);
51
+ }
52
+ };
53
+
54
+ // src/client.ts
55
+ var TokenKitClient = class {
56
+ constructor(config) {
57
+ if (!config.apiKey) {
58
+ throw new Error("API key is required");
59
+ }
60
+ this.apiKey = config.apiKey;
61
+ this.client = import_axios.default.create({
62
+ baseURL: config.baseUrl || "https://api.token-kit.com/api/v1",
63
+ timeout: config.timeout || 6e4,
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ "Authorization": `Bearer ${this.apiKey}`
67
+ }
68
+ });
69
+ this.client.interceptors.response.use(
70
+ (response) => response,
71
+ (error) => {
72
+ return Promise.reject(this.handleError(error));
73
+ }
74
+ );
75
+ }
76
+ /**
77
+ * Send a chat completion request
78
+ */
79
+ async chat(userToken, messages, options = {}) {
80
+ try {
81
+ const response = await this.client.post("/llm/chat", {
82
+ userToken,
83
+ messages,
84
+ model: options.model,
85
+ maxTokens: options.maxTokens,
86
+ temperature: options.temperature
87
+ });
88
+ if (!response.data.success || !response.data.data) {
89
+ throw new TokenKitAPIError(
90
+ response.data.error?.message || "Chat request failed",
91
+ response.data.error?.code || "CHAT_ERROR",
92
+ response.status,
93
+ response.data.error?.details
94
+ );
95
+ }
96
+ return response.data.data;
97
+ } catch (error) {
98
+ if (error instanceof TokenKitAPIError) {
99
+ throw error;
100
+ }
101
+ throw this.handleError(error);
102
+ }
103
+ }
104
+ /**
105
+ * Validate a user token
106
+ */
107
+ async validateToken(userToken) {
108
+ try {
109
+ const response = await this.client.post(
110
+ "/tokens/validate",
111
+ { userToken }
112
+ );
113
+ if (!response.data.success || !response.data.data) {
114
+ throw new TokenKitAPIError(
115
+ response.data.error?.message || "Token validation failed",
116
+ response.data.error?.code || "VALIDATION_ERROR",
117
+ response.status,
118
+ response.data.error?.details
119
+ );
120
+ }
121
+ return response.data.data;
122
+ } catch (error) {
123
+ if (error instanceof TokenKitAPIError) {
124
+ throw error;
125
+ }
126
+ throw this.handleError(error);
127
+ }
128
+ }
129
+ /**
130
+ * Get list of available models
131
+ */
132
+ async getModels() {
133
+ try {
134
+ const response = await this.client.get("/llm/models");
135
+ if (!response.data.success || !response.data.data) {
136
+ throw new TokenKitAPIError(
137
+ response.data.error?.message || "Failed to fetch models",
138
+ response.data.error?.code || "MODELS_ERROR",
139
+ response.status,
140
+ response.data.error?.details
141
+ );
142
+ }
143
+ return response.data.data.models;
144
+ } catch (error) {
145
+ if (error instanceof TokenKitAPIError) {
146
+ throw error;
147
+ }
148
+ throw this.handleError(error);
149
+ }
150
+ }
151
+ /**
152
+ * Handle axios errors and convert to TokenKitAPIError
153
+ */
154
+ handleError(error) {
155
+ const isAxios = import_axios.default.isAxiosError(error) || typeof error === "object" && error !== null && "isAxiosError" in error;
156
+ if (isAxios) {
157
+ const axiosError = error;
158
+ if (axiosError.code === "ECONNABORTED") {
159
+ return new TokenKitAPIError(
160
+ "Request timeout",
161
+ "TIMEOUT",
162
+ 504
163
+ );
164
+ }
165
+ if (axiosError.code === "ECONNREFUSED" || !axiosError.response) {
166
+ return new TokenKitAPIError(
167
+ "Unable to connect to Token-Kit API",
168
+ "NETWORK_ERROR",
169
+ 503
170
+ );
171
+ }
172
+ if (axiosError.response?.data?.error) {
173
+ return new TokenKitAPIError(
174
+ axiosError.response.data.error.message,
175
+ axiosError.response.data.error.code,
176
+ axiosError.response.status,
177
+ axiosError.response.data.error.details
178
+ );
179
+ }
180
+ return new TokenKitAPIError(
181
+ axiosError.message || "API request failed",
182
+ "API_ERROR",
183
+ axiosError.response?.status
184
+ );
185
+ }
186
+ if (error instanceof Error) {
187
+ return new TokenKitAPIError(
188
+ error.message,
189
+ "UNKNOWN_ERROR"
190
+ );
191
+ }
192
+ return new TokenKitAPIError(
193
+ "An unknown error occurred",
194
+ "UNKNOWN_ERROR"
195
+ );
196
+ }
197
+ };
198
+
199
+ // src/index.ts
200
+ var TokenKit = class {
201
+ /**
202
+ * Create a new TokenKit instance
203
+ *
204
+ * @param config - Configuration options
205
+ * @param config.apiKey - Your developer API key
206
+ * @param config.baseUrl - API base URL (optional, defaults to production)
207
+ * @param config.timeout - Request timeout in ms (optional, defaults to 60000)
208
+ */
209
+ constructor(config) {
210
+ this.userToken = null;
211
+ this.client = new TokenKitClient(config);
212
+ }
213
+ /**
214
+ * Set the user token for subsequent requests
215
+ * This allows you to omit the userToken parameter in other methods
216
+ *
217
+ * @param userToken - The user's token
218
+ */
219
+ setUserToken(userToken) {
220
+ this.userToken = userToken;
221
+ }
222
+ /**
223
+ * Send a chat completion request
224
+ *
225
+ * @param userTokenOrMessages - User token string OR array of messages (if user token was set)
226
+ * @param messagesOrOptions - Array of messages OR chat options (if first param is user token)
227
+ * @param options - Chat options (only if first two params are provided)
228
+ * @returns Chat completion response
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * // With explicit user token
233
+ * const response = await tokenKit.chat('user-token', [
234
+ * { role: 'user', content: 'What is Token-Kit?' }
235
+ * ]);
236
+ *
237
+ * // With pre-set user token
238
+ * tokenKit.setUserToken('user-token');
239
+ * const response = await tokenKit.chat([
240
+ * { role: 'user', content: 'What is Token-Kit?' }
241
+ * ]);
242
+ *
243
+ * // With options
244
+ * const response = await tokenKit.chat('user-token', [
245
+ * { role: 'system', content: 'You are a helpful assistant.' },
246
+ * { role: 'user', content: 'Hello!' }
247
+ * ], {
248
+ * model: 'gpt-4',
249
+ * maxTokens: 200,
250
+ * temperature: 0.8
251
+ * });
252
+ * ```
253
+ */
254
+ async chat(userTokenOrMessages, messagesOrOptions, options) {
255
+ let userToken;
256
+ let messages;
257
+ let chatOptions;
258
+ if (typeof userTokenOrMessages === "string") {
259
+ userToken = userTokenOrMessages;
260
+ messages = messagesOrOptions;
261
+ chatOptions = options;
262
+ } else {
263
+ if (!this.userToken) {
264
+ throw new Error("User token not set. Call setUserToken() first or pass userToken to chat().");
265
+ }
266
+ userToken = this.userToken;
267
+ messages = userTokenOrMessages;
268
+ chatOptions = messagesOrOptions;
269
+ }
270
+ if (!messages || messages.length === 0) {
271
+ throw new Error("Messages array cannot be empty");
272
+ }
273
+ return this.client.chat(userToken, messages, chatOptions);
274
+ }
275
+ /**
276
+ * Validate a user token and check balance
277
+ *
278
+ * @param userToken - User token to validate (optional if already set)
279
+ * @returns Token validation response with balance and limits
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * const validation = await tokenKit.validateToken('user-token');
284
+ * console.log('Balance:', validation.balance);
285
+ * console.log('Daily spending:', validation.dailySpending);
286
+ * ```
287
+ */
288
+ async validateToken(userToken) {
289
+ const token = userToken || this.userToken;
290
+ if (!token) {
291
+ throw new Error("User token not set. Call setUserToken() first or pass userToken to validateToken().");
292
+ }
293
+ return this.client.validateToken(token);
294
+ }
295
+ /**
296
+ * Get balance for the current user token
297
+ *
298
+ * @param userToken - User token (optional if already set)
299
+ * @returns Current token balance
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * const balance = await tokenKit.getBalance('user-token');
304
+ * console.log(`You have ${balance} tokens remaining`);
305
+ * ```
306
+ */
307
+ async getBalance(userToken) {
308
+ const validation = await this.validateToken(userToken);
309
+ return validation.balance || 0;
310
+ }
311
+ /**
312
+ * Get list of available LLM models
313
+ *
314
+ * @returns Array of model names
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * const models = await tokenKit.getModels();
319
+ * console.log('Available models:', models);
320
+ * // ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo']
321
+ * ```
322
+ */
323
+ async getModels() {
324
+ return this.client.getModels();
325
+ }
326
+ /**
327
+ * Helper method to create a simple user message
328
+ *
329
+ * @param content - Message content
330
+ * @returns Message object
331
+ */
332
+ static user(content) {
333
+ return { role: "user", content };
334
+ }
335
+ /**
336
+ * Helper method to create a system message
337
+ *
338
+ * @param content - Message content
339
+ * @returns Message object
340
+ */
341
+ static system(content) {
342
+ return { role: "system", content };
343
+ }
344
+ /**
345
+ * Helper method to create an assistant message
346
+ *
347
+ * @param content - Message content
348
+ * @returns Message object
349
+ */
350
+ static assistant(content) {
351
+ return { role: "assistant", content };
352
+ }
353
+ };
354
+ var index_default = TokenKit;
355
+ // Annotate the CommonJS export names for ESM import in node:
356
+ 0 && (module.exports = {
357
+ TokenKit,
358
+ TokenKitAPIError
359
+ });