@umituz/react-native-ai-gemini-provider 3.0.19 → 3.0.21

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 (29) hide show
  1. package/package.json +1 -1
  2. package/README.md +0 -191
  3. package/dist/domain/entities/error.types.d.ts +0 -96
  4. package/dist/domain/entities/gemini.types.d.ts +0 -90
  5. package/dist/domain/entities/index.d.ts +0 -6
  6. package/dist/domain/entities/models.d.ts +0 -17
  7. package/dist/index.d.ts +0 -15
  8. package/dist/infrastructure/services/BaseService.d.ts +0 -34
  9. package/dist/infrastructure/services/GeminiClient.d.ts +0 -15
  10. package/dist/infrastructure/services/GeminiProvider.d.ts +0 -10
  11. package/dist/infrastructure/services/Streaming.d.ts +0 -7
  12. package/dist/infrastructure/services/StructuredText.d.ts +0 -7
  13. package/dist/infrastructure/services/TextGeneration.d.ts +0 -8
  14. package/dist/infrastructure/services/index.d.ts +0 -5
  15. package/dist/infrastructure/telemetry/TelemetryHooks.d.ts +0 -57
  16. package/dist/infrastructure/telemetry/index.d.ts +0 -4
  17. package/dist/infrastructure/utils/async/execute-state.util.d.ts +0 -50
  18. package/dist/infrastructure/utils/async/index.d.ts +0 -4
  19. package/dist/infrastructure/utils/content-mapper.util.d.ts +0 -45
  20. package/dist/infrastructure/utils/error-mapper.util.d.ts +0 -2
  21. package/dist/infrastructure/utils/gemini-data-transformer.util.d.ts +0 -2
  22. package/dist/infrastructure/utils/json-parser.util.d.ts +0 -9
  23. package/dist/infrastructure/utils/stream-processor.util.d.ts +0 -14
  24. package/dist/presentation/hooks/index.d.ts +0 -1
  25. package/dist/presentation/hooks/useGemini.d.ts +0 -17
  26. package/dist/presentation/hooks/useOperationManager.d.ts +0 -23
  27. package/dist/providers/ConfigBuilder.d.ts +0 -50
  28. package/dist/providers/ProviderFactory.d.ts +0 -31
  29. package/dist/providers/index.d.ts +0 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/react-native-ai-gemini-provider",
3
- "version": "3.0.19",
3
+ "version": "3.0.21",
4
4
  "description": "Google Gemini AI text generation provider for React Native applications",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./dist/index.d.ts",
package/README.md DELETED
@@ -1,191 +0,0 @@
1
- # @umituz/react-native-ai-gemini-provider
2
-
3
- Production-ready Google Gemini AI provider for React Native applications with built-in error handling, rate limiting, and caching.
4
-
5
- ## Features
6
-
7
- - ✅ **Production Ready** - Real API integration with proper error handling
8
- - ✅ **Type-Safe** - Full TypeScript support with structured output
9
- - ✅ **Cost Optimized** - Uses `gemini-2.5-flash-lite` by default (1000 free requests/day)
10
- - ✅ **Rate Limiting** - Built-in rate limiter to prevent API throttling
11
- - ✅ **Caching** - LRU cache with TTL for performance optimization
12
- - ✅ **Retry Logic** - Exponential backoff with jitter for resilient API calls
13
- - ✅ **No Mock Data** - Production-grade implementation
14
-
15
- ## Installation
16
-
17
- ```bash
18
- npm install @umituz/react-native-ai-gemini-provider
19
- npm install @google/generative-ai
20
- ```
21
-
22
- ## Configuration
23
-
24
- ### 1. Get API Key
25
-
26
- Visit [Google AI Studio](https://aistudio.google.com/apikey) and create an API key.
27
-
28
- ### 2. Environment Setup
29
-
30
- Create `.env` file:
31
-
32
- ```env
33
- EXPO_PUBLIC_GEMINI_API_KEY=your_api_key_here
34
- ```
35
-
36
- ### 3. Initialize Provider
37
-
38
- ```typescript
39
- import { geminiClientCoreService } from '@umituz/react-native-ai-gemini-provider';
40
-
41
- geminiClientCoreService.initialize({
42
- apiKey: process.env.EXPO_PUBLIC_GEMINI_API_KEY,
43
- textModel: 'gemini-2.5-flash-lite',
44
- maxRetries: 3,
45
- baseDelay: 1000,
46
- maxDelay: 10000,
47
- });
48
- ```
49
-
50
- ## Usage
51
-
52
- ### Simple Text Generation
53
-
54
- ```typescript
55
- import { geminiTextService } from '@umituz/react-native-ai-gemini-provider';
56
-
57
- const response = await geminiTextService.generateText(
58
- 'gemini-2.5-flash-lite',
59
- 'Write a short greeting in Turkish'
60
- );
61
- console.log(response); // "Merhaba! Bugün size nasıl yardımcı olabilirim?"
62
- ```
63
-
64
- ### Structured Output (JSON)
65
-
66
- ```typescript
67
- import { geminiStructuredTextService } from '@umituz/react-native-ai-gemini-provider';
68
-
69
- interface AnalysisResult {
70
- score: number;
71
- feedback: string;
72
- suggestions: string[];
73
- }
74
-
75
- const schema = {
76
- type: 'object',
77
- properties: {
78
- score: { type: 'number' },
79
- feedback: { type: 'string' },
80
- suggestions: { type: 'array', items: { type: 'string' } },
81
- },
82
- required: ['score', 'feedback', 'suggestions'],
83
- };
84
-
85
- const result = await geminiStructuredTextService.generateStructuredText<AnalysisResult>(
86
- 'gemini-2.5-flash-lite',
87
- 'Analyze this text',
88
- schema
89
- );
90
-
91
- console.log(result.score); // 85
92
- console.log(result.feedback); // "Good quality overall..."
93
- ```
94
-
95
- ### With Rate Limiting & Caching
96
-
97
- ```typescript
98
- import {
99
- geminiTextService,
100
- rateLimiter,
101
- SimpleCache
102
- } from '@umituz/react-native-ai-gemini-provider';
103
-
104
- const cache = new SimpleCache<string, string>({
105
- maxSize: 50,
106
- ttl: 60000 // 1 minute
107
- });
108
-
109
- const cacheKey = `text_${prompt}`;
110
- const cached = cache.get(cacheKey);
111
-
112
- if (cached) {
113
- return cached;
114
- }
115
-
116
- const response = await rateLimiter.execute(() =>
117
- geminiTextService.generateText('gemini-2.5-flash-lite', prompt)
118
- );
119
-
120
- cache.set(cacheKey, response);
121
- return response;
122
- ```
123
-
124
- ## Production Example
125
-
126
- See `examples/prod-ai-service.ts` for a complete production-ready implementation with:
127
-
128
- - ✅ Content analysis
129
- - ✅ Motivation letter analysis
130
- - ✅ Chat assistant
131
- - ✅ Text summarization
132
- - ✅ Batch processing
133
- - ✅ Error handling with retry
134
-
135
- ## Models
136
-
137
- | Model | Input | Output | Free/Day | Best For |
138
- |-------|-------|--------|-----------|----------|
139
- | `gemini-2.5-flash-lite` | $0.10 | $0.40 | 1000 | High volume, simple tasks |
140
- | `gemini-2.5-flash` | $0.15 | $0.60 | 20 | Balanced speed/quality |
141
- | `gemini-2.5-pro` | $1.25 | $10.00 | 25 | Complex reasoning |
142
-
143
- **Recommendation:** Use `gemini-2.5-flash-lite` for most use cases.
144
-
145
- ## API Reference
146
-
147
- ### Services
148
-
149
- - `geminiClientCoreService` - Client initialization and configuration
150
- - `geminiTextService` - Text generation (alias: `geminiTextGenerationService`)
151
- - `geminiStructuredTextService` - JSON structured output
152
- - `geminiRetryService` - Retry logic with exponential backoff
153
-
154
- ### Utilities
155
-
156
- - `rateLimiter` - Request rate limiting
157
- - `SimpleCache` - LRU cache with TTL
158
- - `measureAsync` / `measureSync` - Performance measurement
159
-
160
- ## Error Handling
161
-
162
- ```typescript
163
- try {
164
- const result = await geminiTextService.generateText('gemini-2.5-flash-lite', prompt);
165
- } catch (error) {
166
- if (error instanceof Error) {
167
- if (error.message.includes('API key')) {
168
- // Handle missing/invalid API key
169
- } else if (error.message.includes('429') || error.message.includes('quota')) {
170
- // Handle rate limit - wait and retry
171
- }
172
- }
173
- }
174
- ```
175
-
176
- ## Best Practices
177
-
178
- 1. **Always initialize** the client before making requests
179
- 2. **Use rate limiting** to prevent API throttling
180
- 3. **Implement caching** for frequently used prompts
181
- 4. **Handle errors** gracefully with retry logic
182
- 5. **Use structured output** for consistent JSON responses
183
- 6. **Choose the right model** based on complexity and cost
184
-
185
- ## License
186
-
187
- MIT
188
-
189
- ## Support
190
-
191
- For detailed integration guide, see: [factory/templates/docs/ai/GEMINI_AI_PROVIDER.md](https://github.com/umituz/react-native-app-factory/blob/main/factory/templates/docs/ai/GEMINI_AI_PROVIDER.md)
@@ -1,96 +0,0 @@
1
- /**
2
- * Categories of errors that can occur with Gemini API
3
- */
4
- export declare enum GeminiErrorType {
5
- /** Network connectivity issues */
6
- NETWORK = "NETWORK",
7
- /** API rate limit exceeded */
8
- RATE_LIMIT = "RATE_LIMIT",
9
- /** Authentication/authorization failures */
10
- AUTHENTICATION = "AUTHENTICATION",
11
- /** Invalid input data or parameters */
12
- VALIDATION = "VALIDATION",
13
- /** Content blocked by safety filters */
14
- SAFETY = "SAFETY",
15
- /** Server-side errors */
16
- SERVER = "SERVER",
17
- /** Request timeout */
18
- TIMEOUT = "TIMEOUT",
19
- /** API quota exceeded */
20
- QUOTA_EXCEEDED = "QUOTA_EXCEEDED",
21
- /** Requested model not found */
22
- MODEL_NOT_FOUND = "MODEL_NOT_FOUND",
23
- /** Unknown/unclassified error */
24
- UNKNOWN = "UNKNOWN"
25
- }
26
- /**
27
- * Detailed error information for Gemini API errors
28
- */
29
- export interface GeminiErrorInfo {
30
- /** Category of the error */
31
- type: GeminiErrorType;
32
- /** Message key for i18n translation */
33
- messageKey: string;
34
- /** Whether the request can be retried */
35
- retryable: boolean;
36
- /** Original error that caused this error */
37
- originalError?: unknown;
38
- /** HTTP status code if applicable */
39
- statusCode?: number;
40
- }
41
- /**
42
- * Structure of Gemini API error responses
43
- */
44
- export interface GeminiApiError {
45
- error?: {
46
- /** Error code */
47
- code?: number;
48
- /** Error message */
49
- message?: string;
50
- /** Error status */
51
- status?: string;
52
- /** Additional error details */
53
- details?: Array<{
54
- "@type"?: string;
55
- reason?: string;
56
- domain?: string;
57
- metadata?: Record<string, string>;
58
- }>;
59
- };
60
- }
61
- /**
62
- * Custom error class for Gemini API errors
63
- * Provides structured error information and retry capability
64
- */
65
- export declare class GeminiError extends Error {
66
- /** Error category */
67
- readonly type: GeminiErrorType;
68
- /** Whether the operation can be retried */
69
- readonly retryable: boolean;
70
- /** HTTP status code if applicable */
71
- readonly statusCode?: number;
72
- /** Original error that caused this error */
73
- readonly originalError?: unknown;
74
- /**
75
- * Create a new GeminiError
76
- * @param info - Error information
77
- */
78
- constructor(info: GeminiErrorInfo);
79
- /**
80
- * Check if this error is retryable
81
- * @returns true if the operation can be retried
82
- */
83
- isRetryable(): boolean;
84
- /**
85
- * Get the error type
86
- * @returns The error category
87
- */
88
- getErrorType(): GeminiErrorType;
89
- /**
90
- * Create a GeminiError from an unknown error
91
- * @param error - The original error
92
- * @param info - Error information
93
- * @returns A new GeminiError instance
94
- */
95
- static fromError(error: unknown, info: GeminiErrorInfo): GeminiError;
96
- }
@@ -1,90 +0,0 @@
1
- import type { GenerationConfig } from "@google/generative-ai";
2
- /**
3
- * Configuration for Gemini AI client initialization
4
- */
5
- export interface GeminiConfig {
6
- /** API key for authentication */
7
- apiKey: string;
8
- /** Optional base URL for API requests */
9
- baseUrl?: string;
10
- /** Default timeout in milliseconds */
11
- defaultTimeoutMs?: number;
12
- /** Default model to use for text generation */
13
- textModel?: string;
14
- }
15
- /**
16
- * Generation configuration for AI requests
17
- * Extends the SDK's GenerationConfig with proper schema typing
18
- */
19
- export type GeminiGenerationConfig = Omit<GenerationConfig, "responseSchema"> & {
20
- responseSchema?: GenerationConfig["responseSchema"];
21
- };
22
- /**
23
- * Harm categories for content safety filtering
24
- */
25
- export type GeminiHarmCategory = "HARM_CATEGORY_HARASSMENT" | "HARM_CATEGORY_HATE_SPEECH" | "HARM_CATEGORY_SEXUALLY_EXPLICIT" | "HARM_CATEGORY_DANGEROUS_CONTENT";
26
- /**
27
- * Threshold levels for blocking harmful content
28
- */
29
- export type GeminiHarmBlockThreshold = "BLOCK_NONE" | "BLOCK_LOW_AND_ABOVE" | "BLOCK_MEDIUM_AND_ABOVE" | "BLOCK_ONLY_HIGH";
30
- /**
31
- * Content structure for Gemini API requests
32
- */
33
- export interface GeminiContent {
34
- /** Array of content parts (text, images, etc.) */
35
- parts: GeminiPart[];
36
- /** Role of the content creator (user or model) */
37
- role?: "user" | "model";
38
- }
39
- /**
40
- * Individual content part
41
- */
42
- export type GeminiPart = {
43
- text: string;
44
- };
45
- /**
46
- * Response structure from Gemini API
47
- */
48
- export interface GeminiResponse {
49
- /** Array of response candidates */
50
- candidates?: GeminiCandidate[];
51
- /** Token usage information */
52
- usageMetadata?: GeminiUsageMetadata;
53
- }
54
- /**
55
- * Individual response candidate
56
- */
57
- export interface GeminiCandidate {
58
- /** Generated content */
59
- content: GeminiContent;
60
- /** Reason for generation completion */
61
- finishReason?: GeminiFinishReason;
62
- /** Safety ratings for the content */
63
- safetyRatings?: GeminiSafetyRating[];
64
- }
65
- /**
66
- * Reasons why generation finished
67
- */
68
- export type GeminiFinishReason = "FINISH_REASON_UNSPECIFIED" | "STOP" | "MAX_TOKENS" | "SAFETY" | "RECITATION" | "OTHER";
69
- /**
70
- * Safety rating for generated content
71
- */
72
- export interface GeminiSafetyRating {
73
- /** Category of safety check */
74
- category: GeminiHarmCategory;
75
- /** Probability of content being unsafe */
76
- probability: "NEGLIGIBLE" | "LOW" | "MEDIUM" | "HIGH";
77
- /** Whether the content was blocked */
78
- blocked?: boolean;
79
- }
80
- /**
81
- * Token usage metadata for the request
82
- */
83
- export interface GeminiUsageMetadata {
84
- /** Number of tokens in the prompt */
85
- promptTokenCount?: number;
86
- /** Number of tokens in the response candidates */
87
- candidatesTokenCount?: number;
88
- /** Total number of tokens used */
89
- totalTokenCount?: number;
90
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Domain Entities
3
- */
4
- export * from "./gemini.types";
5
- export * from "./error.types";
6
- export * from "./models";
@@ -1,17 +0,0 @@
1
- /**
2
- * Available Gemini AI models
3
- */
4
- export declare const GEMINI_MODELS: {
5
- /** Text generation models */
6
- readonly TEXT: {
7
- /** Lightweight flash model for fast text generation */
8
- readonly FLASH_LITE: "gemini-2.5-flash-lite";
9
- };
10
- };
11
- /**
12
- * Default models to use for each category
13
- */
14
- export declare const DEFAULT_MODELS: {
15
- /** Default model for text generation */
16
- readonly TEXT: "gemini-2.5-flash-lite";
17
- };
package/dist/index.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * @umituz/react-native-ai-gemini-provider
3
- * Google Gemini AI provider for React Native applications
4
- */
5
- export type { GeminiConfig, GeminiGenerationConfig, GeminiHarmCategory, GeminiHarmBlockThreshold, GeminiContent, GeminiPart, GeminiResponse, GeminiCandidate, GeminiFinishReason, GeminiSafetyRating, GeminiUsageMetadata, GeminiErrorInfo, GeminiApiError, } from "./domain/entities";
6
- export { GeminiErrorType, GeminiError, GEMINI_MODELS, DEFAULT_MODELS } from "./domain/entities";
7
- export { geminiClient } from "./infrastructure/services/GeminiClient";
8
- export { textGeneration } from "./infrastructure/services/TextGeneration";
9
- export { structuredText } from "./infrastructure/services/StructuredText";
10
- export { streaming } from "./infrastructure/services/Streaming";
11
- export { geminiProvider, GeminiProvider } from "./infrastructure/services/GeminiProvider";
12
- export { useGemini } from "./presentation/hooks";
13
- export type { UseGeminiOptions, UseGeminiReturn } from "./presentation/hooks";
14
- export { ConfigBuilder, providerFactory } from "./providers";
15
- export type { ProviderConfig, ProviderFactoryOptions, } from "./providers";
@@ -1,34 +0,0 @@
1
- import type { GeminiContent, GeminiGenerationConfig } from "../../domain/entities";
2
- import type { GenerativeModel } from "@google/generative-ai";
3
- export interface BaseRequestOptions {
4
- model: string;
5
- contents: GeminiContent[];
6
- generationConfig?: GeminiGenerationConfig;
7
- signal?: AbortSignal;
8
- }
9
- export declare abstract class BaseGeminiService {
10
- protected validateAndPrepare(options: BaseRequestOptions): {
11
- genModel: GenerativeModel;
12
- sdkContents: Array<{
13
- role: string;
14
- parts: Array<{
15
- text: string;
16
- }>;
17
- }>;
18
- };
19
- protected handleError(error: unknown, abortMessage: string): never;
20
- protected createRequestOptions(sdkContents: Array<{
21
- role: string;
22
- parts: Array<{
23
- text: string;
24
- }>;
25
- }>, generationConfig?: GeminiGenerationConfig): {
26
- contents: {
27
- role: string;
28
- parts: Array<{
29
- text: string;
30
- }>;
31
- }[];
32
- generationConfig: GeminiGenerationConfig | undefined;
33
- };
34
- }
@@ -1,15 +0,0 @@
1
- import { GoogleGenerativeAI, type GenerativeModel } from "@google/generative-ai";
2
- import type { GeminiConfig } from "../../domain/entities";
3
- declare class GeminiClient {
4
- private client;
5
- private config;
6
- private initialized;
7
- initialize(config: GeminiConfig): void;
8
- isInitialized(): boolean;
9
- getConfig(): GeminiConfig | null;
10
- getClient(): GoogleGenerativeAI | null;
11
- getModel(modelName?: string): GenerativeModel;
12
- reset(): void;
13
- }
14
- export declare const geminiClient: GeminiClient;
15
- export {};
@@ -1,10 +0,0 @@
1
- import type { GeminiConfig } from "../../domain/entities";
2
- export declare class GeminiProvider {
3
- readonly providerId = "gemini";
4
- readonly providerName = "Google Gemini";
5
- initialize(config: GeminiConfig): void;
6
- isInitialized(): boolean;
7
- reset(): void;
8
- generateStructuredText<T>(prompt: string, schema: Record<string, unknown>, model: string): Promise<T>;
9
- }
10
- export declare const geminiProvider: GeminiProvider;
@@ -1,7 +0,0 @@
1
- import { BaseGeminiService } from "./BaseService";
2
- import type { GeminiContent, GeminiGenerationConfig } from "../../domain/entities";
3
- declare class StreamingService extends BaseGeminiService {
4
- streamContent(model: string, contents: GeminiContent[], onChunk: (text: string) => void, generationConfig?: GeminiGenerationConfig, signal?: AbortSignal): Promise<string>;
5
- }
6
- export declare const streaming: StreamingService;
7
- export {};
@@ -1,7 +0,0 @@
1
- import type { GeminiGenerationConfig } from "../../domain/entities";
2
- declare class StructuredTextService {
3
- generateStructuredText<T>(model: string, prompt: string, schema: Record<string, unknown>, config?: Omit<GeminiGenerationConfig, "responseMimeType" | "responseSchema">, signal?: AbortSignal): Promise<T>;
4
- private parseJSONResponse;
5
- }
6
- export declare const structuredText: StructuredTextService;
7
- export {};
@@ -1,8 +0,0 @@
1
- import { BaseGeminiService } from "./BaseService";
2
- import type { GeminiContent, GeminiGenerationConfig, GeminiResponse } from "../../domain/entities";
3
- declare class TextGenerationService extends BaseGeminiService {
4
- generateContent(model: string, contents: GeminiContent[], generationConfig?: GeminiGenerationConfig, signal?: AbortSignal): Promise<GeminiResponse>;
5
- generateText(model: string, prompt: string, config?: GeminiGenerationConfig, signal?: AbortSignal): Promise<string>;
6
- }
7
- export declare const textGeneration: TextGenerationService;
8
- export {};
@@ -1,5 +0,0 @@
1
- export { geminiClient } from "./GeminiClient";
2
- export { textGeneration } from "./TextGeneration";
3
- export { structuredText } from "./StructuredText";
4
- export { streaming } from "./Streaming";
5
- export { geminiProvider, GeminiProvider } from "./GeminiProvider";
@@ -1,57 +0,0 @@
1
- export interface TelemetryEvent {
2
- type: "request" | "response" | "error" | "retry";
3
- timestamp: number;
4
- model?: string;
5
- feature?: string;
6
- duration?: number;
7
- metadata?: Record<string, unknown>;
8
- }
9
- export type TelemetryListener = (event: TelemetryEvent) => void;
10
- declare class TelemetryHooks {
11
- private listeners;
12
- private failedListeners;
13
- private readonly MAX_FAILURES;
14
- private listenerFailureCounts;
15
- /**
16
- * Register a telemetry listener
17
- */
18
- subscribe(listener: TelemetryListener): () => void;
19
- /**
20
- * Emit a telemetry event to all listeners
21
- */
22
- emit(event: TelemetryEvent): void;
23
- /**
24
- * Log request start
25
- */
26
- logRequest(model: string, feature?: string): number;
27
- /**
28
- * Log response received
29
- */
30
- logResponse(model: string, startTime: number, feature?: string, metadata?: Record<string, unknown>): void;
31
- /**
32
- * Log error
33
- */
34
- logError(model: string, error: Error, feature?: string): void;
35
- /**
36
- * Log retry attempt
37
- */
38
- logRetry(model: string, attempt: number, feature?: string): void;
39
- /**
40
- * Remove a specific listener
41
- */
42
- unsubscribe(listener: TelemetryListener): void;
43
- /**
44
- * Reset failure counts for all listeners (clear blacklist)
45
- */
46
- resetFailures(): void;
47
- /**
48
- * Clear all listeners
49
- */
50
- clear(): void;
51
- /**
52
- * Get current listener count
53
- */
54
- getListenerCount(): number;
55
- }
56
- export declare const telemetryHooks: TelemetryHooks;
57
- export {};
@@ -1,4 +0,0 @@
1
- /**
2
- * Telemetry Module
3
- */
4
- export { telemetryHooks } from "./TelemetryHooks";
@@ -1,50 +0,0 @@
1
- /**
2
- * Async State Execution Utilities
3
- * Utilities for managing asynchronous operation state
4
- */
5
- /**
6
- * Callbacks for async operation outcomes
7
- */
8
- export interface AsyncStateCallbacks<T = string> {
9
- onSuccess?: (result: T) => void;
10
- onError?: (error: string) => void;
11
- }
12
- /**
13
- * Setter functions for updating state
14
- */
15
- export interface AsyncStateSetters<T = string, U = unknown> {
16
- setIsLoading: (value: boolean) => void;
17
- setError: (value: string | null) => void;
18
- setResult: (value: T | null) => void;
19
- setSecondaryResult?: (value: U | null) => void;
20
- }
21
- /**
22
- * Configuration for executeWithState
23
- */
24
- export interface AsyncStateConfig<T = string> {
25
- resetState?: boolean;
26
- throwOnError?: boolean;
27
- transformResult?: (result: T) => T;
28
- }
29
- /**
30
- * Execute an async operation with automatic state management
31
- *
32
- * @param setters - State setter functions
33
- * @param callbacks - Optional callbacks for success/error
34
- * @param execute - The async operation to execute
35
- * @param onResult - Function to handle successful result
36
- * @param config - Optional configuration
37
- *
38
- * @returns The result or null if failed/aborted
39
- *
40
- * @example
41
- * ```ts
42
- * const result = await executeWithState(
43
- * { setIsLoading, setError, setResult },
44
- * { onSuccess: console.log },
45
- * () => apiCall(),
46
- * (data) => setResult(data)
47
- * );
48
- * ```
49
- */
50
- export declare function executeWithState<T, U = unknown>(setters: AsyncStateSetters<T, U>, callbacks: AsyncStateCallbacks<T>, execute: () => Promise<T>, onResult: (result: T) => void, config?: AsyncStateConfig<T>): Promise<T | null>;
@@ -1,4 +0,0 @@
1
- /**
2
- * Async State Management - Internal Use Only
3
- */
4
- export { executeWithState, type AsyncStateSetters, } from "./execute-state.util";
@@ -1,45 +0,0 @@
1
- /**
2
- * Content Mapper Utilities
3
- * Handles transformation between domain content and SDK format
4
- */
5
- import type { GeminiContent, GeminiPart, GeminiResponse } from "../../domain/entities";
6
- /**
7
- * Convert domain content to SDK format
8
- */
9
- export declare function toSdkContent(contents: GeminiContent[]): Array<{
10
- role: string;
11
- parts: Array<{
12
- text: string;
13
- }>;
14
- }>;
15
- /**
16
- * Create a simple text content
17
- */
18
- export declare function createTextContent(text: string, role?: "user" | "model"): GeminiContent;
19
- /**
20
- * Transform SDK response to domain format
21
- */
22
- export declare function transformResponse(response: {
23
- candidates?: Array<{
24
- content: {
25
- parts: Array<{
26
- text?: string;
27
- }>;
28
- role?: string;
29
- };
30
- finishReason?: string;
31
- safetyRatings?: Array<{
32
- category: string;
33
- probability: string;
34
- }>;
35
- }>;
36
- usageMetadata?: {
37
- promptTokenCount?: number;
38
- candidatesTokenCount?: number;
39
- totalTokenCount?: number;
40
- };
41
- }): GeminiResponse;
42
- /**
43
- * Extract text from content parts
44
- */
45
- export declare function extractTextFromParts(parts: GeminiPart[]): string;
@@ -1,2 +0,0 @@
1
- import { GeminiError } from "../../domain/entities";
2
- export declare function createGeminiError(error: unknown): GeminiError;
@@ -1,2 +0,0 @@
1
- import type { GeminiResponse } from "../../domain/entities";
2
- export declare function extractTextFromResponse(response: GeminiResponse): string;
@@ -1,9 +0,0 @@
1
- /**
2
- * JSON Parser Utilities
3
- * Handles cleaning and parsing JSON responses from AI models
4
- */
5
- /**
6
- * Parse JSON response with error handling
7
- * @throws Error if parsing fails with detailed error message
8
- */
9
- export declare function parseJsonResponse<T>(text: string): T;
@@ -1,14 +0,0 @@
1
- /**
2
- * Stream Processing Utilities
3
- * Reusable stream handling logic
4
- */
5
- interface StreamChunk {
6
- text: () => string;
7
- }
8
- type ChunkCallback = (text: string) => void;
9
- type ErrorLogger = (error: unknown, context?: string) => void;
10
- /**
11
- * Process async stream with chunk callback
12
- */
13
- export declare function processStream(stream: AsyncIterable<StreamChunk>, onChunk: ChunkCallback, onError?: ErrorLogger): Promise<string>;
14
- export {};
@@ -1 +0,0 @@
1
- export { useGemini, type UseGeminiOptions, type UseGeminiReturn } from "./useGemini";
@@ -1,17 +0,0 @@
1
- import type { GeminiGenerationConfig } from "../../domain/entities";
2
- export interface UseGeminiOptions {
3
- model?: string;
4
- generationConfig?: GeminiGenerationConfig;
5
- onSuccess?: (result: string) => void;
6
- onError?: (error: string) => void;
7
- }
8
- export interface UseGeminiReturn {
9
- generate: (prompt: string) => Promise<void>;
10
- generateJSON: <T>(prompt: string, schema?: Record<string, unknown>) => Promise<T | null>;
11
- result: string | null;
12
- jsonResult: unknown;
13
- isGenerating: boolean;
14
- error: string | null;
15
- reset: () => void;
16
- }
17
- export declare function useGemini(options?: UseGeminiOptions): UseGeminiReturn;
@@ -1,23 +0,0 @@
1
- /**
2
- * Operation Manager Hook
3
- * Reusable abort controller and operation ID management
4
- * Eliminates code duplication in hooks
5
- */
6
- export interface OperationManager {
7
- /**
8
- * Execute an operation with abort support and operation ID tracking
9
- */
10
- executeOperation: <T>(operation: (signal: AbortSignal, operationId: number) => Promise<T>) => Promise<T>;
11
- /**
12
- * Abort current operation
13
- */
14
- abort: () => void;
15
- /**
16
- * Check if current operation is active
17
- */
18
- isOperationActive: (operationId: number) => boolean;
19
- }
20
- /**
21
- * Hook for managing operations with abort control
22
- */
23
- export declare function useOperationManager(): OperationManager;
@@ -1,50 +0,0 @@
1
- /**
2
- * Config Builder Pattern
3
- * Fluent API for building provider configuration
4
- */
5
- import type { GeminiConfig } from "../domain/entities";
6
- export interface ProviderConfig {
7
- apiKey: string;
8
- textModel: string;
9
- timeout: number;
10
- strategy?: "cost" | "quality";
11
- }
12
- /**
13
- * Builder for constructing provider configuration
14
- * Provides a fluent API with validation and defaults
15
- */
16
- export declare class ConfigBuilder {
17
- private config;
18
- /**
19
- * Set API key (required)
20
- */
21
- withApiKey(apiKey: string): this;
22
- /**
23
- * Set text model
24
- */
25
- withTextModel(model: string): this;
26
- /**
27
- * Set request timeout (ms)
28
- */
29
- withTimeout(timeout: number): this;
30
- /**
31
- * Set strategy (applies preset timeout)
32
- */
33
- withStrategy(strategy: "cost" | "quality"): this;
34
- /**
35
- * Build final configuration
36
- */
37
- build(): ProviderConfig;
38
- /**
39
- * Convert to GeminiConfig format
40
- */
41
- toGeminiConfig(): GeminiConfig;
42
- /**
43
- * Create a new builder instance
44
- */
45
- static create(): ConfigBuilder;
46
- /**
47
- * Create from existing config (for updates)
48
- */
49
- static from(config: Partial<ProviderConfig>): ConfigBuilder;
50
- }
@@ -1,31 +0,0 @@
1
- import { type ProviderConfig } from "./ConfigBuilder";
2
- export { ConfigBuilder } from "./ConfigBuilder";
3
- export type { ProviderConfig } from "./ConfigBuilder";
4
- export interface ProviderFactoryOptions {
5
- apiKey: string;
6
- timeout?: number;
7
- textModel?: string;
8
- strategy?: "cost" | "quality";
9
- }
10
- declare class ProviderFactory {
11
- private currentConfig;
12
- private builder;
13
- /**
14
- * Initialize provider with configuration
15
- */
16
- initialize(options: ProviderFactoryOptions): void;
17
- /**
18
- * Get current configuration
19
- */
20
- getConfig(): ProviderConfig | null;
21
- /**
22
- * Check if provider is initialized
23
- */
24
- isInitialized(): boolean;
25
- /**
26
- * Update configuration
27
- * API key changes require re-initialization
28
- */
29
- updateConfig(updates: Partial<ProviderFactoryOptions>): void;
30
- }
31
- export declare const providerFactory: ProviderFactory;
@@ -1,7 +0,0 @@
1
- /**
2
- * Provider Configuration & Factory - Public API
3
- */
4
- export { ConfigBuilder } from "./ConfigBuilder";
5
- export type { ProviderConfig } from "./ConfigBuilder";
6
- export { providerFactory } from "./ProviderFactory";
7
- export type { ProviderFactoryOptions } from "./ProviderFactory";