@rainfall-devkit/sdk 0.1.5 → 0.1.7

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,785 @@
1
+ // src/errors.ts
2
+ var RainfallError = class _RainfallError extends Error {
3
+ constructor(message, code, statusCode, details) {
4
+ super(message);
5
+ this.code = code;
6
+ this.statusCode = statusCode;
7
+ this.details = details;
8
+ this.name = "RainfallError";
9
+ Object.setPrototypeOf(this, _RainfallError.prototype);
10
+ }
11
+ toJSON() {
12
+ return {
13
+ name: this.name,
14
+ code: this.code,
15
+ message: this.message,
16
+ statusCode: this.statusCode,
17
+ details: this.details
18
+ };
19
+ }
20
+ };
21
+ var AuthenticationError = class _AuthenticationError extends RainfallError {
22
+ constructor(message = "Invalid API key", details) {
23
+ super(message, "AUTHENTICATION_ERROR", 401, details);
24
+ this.name = "AuthenticationError";
25
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
26
+ }
27
+ };
28
+ var RateLimitError = class _RateLimitError extends RainfallError {
29
+ retryAfter;
30
+ limit;
31
+ remaining;
32
+ resetAt;
33
+ constructor(message = "Rate limit exceeded", retryAfter = 60, limit = 0, remaining = 0, resetAt) {
34
+ super(message, "RATE_LIMIT_ERROR", 429, { retryAfter, limit, remaining });
35
+ this.name = "RateLimitError";
36
+ this.retryAfter = retryAfter;
37
+ this.limit = limit;
38
+ this.remaining = remaining;
39
+ this.resetAt = resetAt || new Date(Date.now() + retryAfter * 1e3);
40
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
41
+ }
42
+ };
43
+ var ValidationError = class _ValidationError extends RainfallError {
44
+ constructor(message, details) {
45
+ super(message, "VALIDATION_ERROR", 400, details);
46
+ this.name = "ValidationError";
47
+ Object.setPrototypeOf(this, _ValidationError.prototype);
48
+ }
49
+ };
50
+ var NotFoundError = class _NotFoundError extends RainfallError {
51
+ constructor(resource, identifier) {
52
+ super(
53
+ `${resource}${identifier ? ` '${identifier}'` : ""} not found`,
54
+ "NOT_FOUND_ERROR",
55
+ 404,
56
+ { resource, identifier }
57
+ );
58
+ this.name = "NotFoundError";
59
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
60
+ }
61
+ };
62
+ var ServerError = class _ServerError extends RainfallError {
63
+ constructor(message = "Internal server error", statusCode = 500) {
64
+ super(message, "SERVER_ERROR", statusCode);
65
+ this.name = "ServerError";
66
+ Object.setPrototypeOf(this, _ServerError.prototype);
67
+ }
68
+ };
69
+ var TimeoutError = class _TimeoutError extends RainfallError {
70
+ constructor(timeoutMs) {
71
+ super(`Request timed out after ${timeoutMs}ms`, "TIMEOUT_ERROR", 408);
72
+ this.name = "TimeoutError";
73
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
74
+ }
75
+ };
76
+ var NetworkError = class _NetworkError extends RainfallError {
77
+ constructor(message = "Network error", details) {
78
+ super(message, "NETWORK_ERROR", void 0, details);
79
+ this.name = "NetworkError";
80
+ Object.setPrototypeOf(this, _NetworkError.prototype);
81
+ }
82
+ };
83
+ var ToolNotFoundError = class _ToolNotFoundError extends RainfallError {
84
+ constructor(toolId) {
85
+ super(`Tool '${toolId}' not found`, "TOOL_NOT_FOUND", 404, { toolId });
86
+ this.name = "ToolNotFoundError";
87
+ Object.setPrototypeOf(this, _ToolNotFoundError.prototype);
88
+ }
89
+ };
90
+ function parseErrorResponse(response, data) {
91
+ const statusCode = response.status;
92
+ if (statusCode === 429) {
93
+ const retryAfter = parseInt(response.headers.get("retry-after") || "60", 10);
94
+ const limit = parseInt(response.headers.get("x-ratelimit-limit") || "0", 10);
95
+ const remaining = parseInt(response.headers.get("x-ratelimit-remaining") || "0", 10);
96
+ const resetHeader = response.headers.get("x-ratelimit-reset");
97
+ const resetAt = resetHeader ? new Date(parseInt(resetHeader, 10) * 1e3) : void 0;
98
+ return new RateLimitError(
99
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Rate limit exceeded",
100
+ retryAfter,
101
+ limit,
102
+ remaining,
103
+ resetAt
104
+ );
105
+ }
106
+ switch (statusCode) {
107
+ case 401:
108
+ return new AuthenticationError(
109
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid API key"
110
+ );
111
+ case 404:
112
+ return new NotFoundError(
113
+ typeof data === "object" && data && "resource" in data ? String(data.resource) : "Resource",
114
+ typeof data === "object" && data && "identifier" in data ? String(data.identifier) : void 0
115
+ );
116
+ case 400:
117
+ return new ValidationError(
118
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid request",
119
+ typeof data === "object" && data && "details" in data ? data.details : void 0
120
+ );
121
+ case 500:
122
+ case 502:
123
+ case 503:
124
+ case 504:
125
+ return new ServerError(
126
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Server error",
127
+ statusCode
128
+ );
129
+ default:
130
+ return new RainfallError(
131
+ typeof data === "object" && data && "message" in data ? String(data.message) : `HTTP ${statusCode}`,
132
+ "UNKNOWN_ERROR",
133
+ statusCode,
134
+ typeof data === "object" ? data : void 0
135
+ );
136
+ }
137
+ }
138
+
139
+ // src/client.ts
140
+ var DEFAULT_BASE_URL = "https://olympic-api.pragma-digital.org/v1";
141
+ var DEFAULT_TIMEOUT = 3e4;
142
+ var DEFAULT_RETRIES = 3;
143
+ var DEFAULT_RETRY_DELAY = 1e3;
144
+ var RainfallClient = class {
145
+ apiKey;
146
+ baseUrl;
147
+ defaultTimeout;
148
+ defaultRetries;
149
+ defaultRetryDelay;
150
+ lastRateLimitInfo;
151
+ subscriberId;
152
+ constructor(config) {
153
+ this.apiKey = config.apiKey;
154
+ this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
155
+ this.defaultTimeout = config.timeout || DEFAULT_TIMEOUT;
156
+ this.defaultRetries = config.retries ?? DEFAULT_RETRIES;
157
+ this.defaultRetryDelay = config.retryDelay || DEFAULT_RETRY_DELAY;
158
+ }
159
+ /**
160
+ * Get the last rate limit info from the API
161
+ */
162
+ getRateLimitInfo() {
163
+ return this.lastRateLimitInfo;
164
+ }
165
+ /**
166
+ * Make an authenticated request to the Rainfall API
167
+ */
168
+ async request(path, options = {}, requestOptions) {
169
+ const timeout = requestOptions?.timeout ?? this.defaultTimeout;
170
+ const maxRetries = requestOptions?.retries ?? this.defaultRetries;
171
+ const retryDelay = requestOptions?.retryDelay ?? this.defaultRetryDelay;
172
+ const url = `${this.baseUrl}${path}`;
173
+ const method = options.method || "GET";
174
+ let lastError;
175
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
176
+ try {
177
+ const controller = new AbortController();
178
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
179
+ const response = await fetch(url, {
180
+ method,
181
+ headers: {
182
+ "x-api-key": this.apiKey,
183
+ "Content-Type": "application/json",
184
+ "Accept": "application/json",
185
+ "X-Rainfall-SDK-Version": "0.1.0",
186
+ ...options.headers
187
+ },
188
+ body: options.body ? JSON.stringify(options.body) : void 0,
189
+ signal: controller.signal
190
+ });
191
+ clearTimeout(timeoutId);
192
+ const limit = response.headers.get("x-ratelimit-limit");
193
+ const remaining = response.headers.get("x-ratelimit-remaining");
194
+ const reset = response.headers.get("x-ratelimit-reset");
195
+ if (limit && remaining && reset) {
196
+ this.lastRateLimitInfo = {
197
+ limit: parseInt(limit, 10),
198
+ remaining: parseInt(remaining, 10),
199
+ resetAt: new Date(parseInt(reset, 10) * 1e3)
200
+ };
201
+ }
202
+ let data;
203
+ const contentType = response.headers.get("content-type");
204
+ if (contentType?.includes("application/json")) {
205
+ data = await response.json();
206
+ } else {
207
+ data = await response.text();
208
+ }
209
+ if (!response.ok) {
210
+ throw parseErrorResponse(response, data);
211
+ }
212
+ return data;
213
+ } catch (error) {
214
+ if (error instanceof RainfallError) {
215
+ if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
216
+ throw error;
217
+ }
218
+ if (error.statusCode === 401) {
219
+ throw error;
220
+ }
221
+ }
222
+ if (error instanceof Error && error.name === "AbortError") {
223
+ lastError = new TimeoutError(timeout);
224
+ } else if (error instanceof TypeError) {
225
+ lastError = new NetworkError(error.message);
226
+ } else {
227
+ lastError = error instanceof Error ? error : new Error(String(error));
228
+ }
229
+ if (attempt >= maxRetries) {
230
+ break;
231
+ }
232
+ const delay = retryDelay * Math.pow(2, attempt) + Math.random() * 1e3;
233
+ await this.sleep(delay);
234
+ }
235
+ }
236
+ throw lastError || new RainfallError("Request failed", "REQUEST_FAILED");
237
+ }
238
+ /**
239
+ * Execute a tool/node by ID
240
+ */
241
+ async executeTool(toolId, params, options) {
242
+ const subscriberId = await this.ensureSubscriberId();
243
+ return this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}`, {
244
+ method: "POST",
245
+ body: params
246
+ }, options);
247
+ }
248
+ /**
249
+ * List all available tools
250
+ */
251
+ async listTools() {
252
+ const subscriberId = await this.ensureSubscriberId();
253
+ const result = await this.request(`/olympic/subscribers/${subscriberId}/nodes/_utils/node-list`);
254
+ if (result.keys && Array.isArray(result.keys)) {
255
+ const toolPromises = result.keys.map(async (key) => {
256
+ try {
257
+ const schema = await this.getToolSchema(key);
258
+ return {
259
+ id: key,
260
+ name: schema.name || key,
261
+ description: schema.description || "",
262
+ category: schema.category || "general"
263
+ };
264
+ } catch {
265
+ return {
266
+ id: key,
267
+ name: key,
268
+ description: "",
269
+ category: "general"
270
+ };
271
+ }
272
+ });
273
+ return Promise.all(toolPromises);
274
+ }
275
+ return result.nodes || [];
276
+ }
277
+ /**
278
+ * Get tool schema/parameters
279
+ */
280
+ async getToolSchema(toolId) {
281
+ const subscriberId = await this.ensureSubscriberId();
282
+ return this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}/params`);
283
+ }
284
+ /**
285
+ * Get subscriber info
286
+ */
287
+ async getMe() {
288
+ const result = await this.request("/olympic/subscribers/me");
289
+ if (result.subscriber?.id) {
290
+ this.subscriberId = result.subscriber.id;
291
+ }
292
+ const subscriber = result.subscriber;
293
+ return {
294
+ id: subscriber.id,
295
+ name: subscriber.name,
296
+ email: subscriber.google_id,
297
+ billingStatus: subscriber.billing_status,
298
+ plan: subscriber.billing_status,
299
+ usage: {
300
+ callsThisMonth: subscriber.metadata?.usage?.callsThisMonth ?? 0,
301
+ callsLimit: subscriber.metadata?.usage?.callsLimit ?? 5e3
302
+ }
303
+ };
304
+ }
305
+ /**
306
+ * Ensure we have a subscriber ID, fetching it if necessary
307
+ */
308
+ async ensureSubscriberId() {
309
+ if (this.subscriberId) {
310
+ return this.subscriberId;
311
+ }
312
+ const me = await this.getMe();
313
+ if (!me.id) {
314
+ throw new RainfallError("Failed to get subscriber ID", "NO_SUBSCRIBER_ID");
315
+ }
316
+ return me.id;
317
+ }
318
+ sleep(ms) {
319
+ return new Promise((resolve) => setTimeout(resolve, ms));
320
+ }
321
+ };
322
+
323
+ // src/namespaces/integrations.ts
324
+ function createIntegrations(client) {
325
+ return new IntegrationsNamespace(client);
326
+ }
327
+ var IntegrationsNamespace = class {
328
+ constructor(client) {
329
+ this.client = client;
330
+ }
331
+ get github() {
332
+ return {
333
+ issues: {
334
+ create: (params) => this.client.executeTool("github-create-issue", params),
335
+ list: (params) => this.client.executeTool("github-list-issues", params),
336
+ get: (params) => this.client.executeTool("github-get-issue", params),
337
+ update: (params) => this.client.executeTool("github-update-issue", params),
338
+ addComment: (params) => this.client.executeTool("github-add-issue-comment", params)
339
+ },
340
+ repos: {
341
+ get: (params) => this.client.executeTool("github-get-repository", params),
342
+ listBranches: (params) => this.client.executeTool("github-list-branches", params)
343
+ },
344
+ pullRequests: {
345
+ list: (params) => this.client.executeTool("github-list-pull-requests", params),
346
+ get: (params) => this.client.executeTool("github-get-pull-request", params)
347
+ }
348
+ };
349
+ }
350
+ get notion() {
351
+ return {
352
+ pages: {
353
+ create: (params) => this.client.executeTool("notion-pages-create", params),
354
+ retrieve: (params) => this.client.executeTool("notion-pages-retrieve", params),
355
+ update: (params) => this.client.executeTool("notion-pages-update", params)
356
+ },
357
+ databases: {
358
+ query: (params) => this.client.executeTool("notion-databases-query", params),
359
+ retrieve: (params) => this.client.executeTool("notion-databases-retrieve", params)
360
+ },
361
+ blocks: {
362
+ appendChildren: (params) => this.client.executeTool("notion-blocks-append-children", params),
363
+ retrieveChildren: (params) => this.client.executeTool("notion-blocks-retrieve-children", params)
364
+ }
365
+ };
366
+ }
367
+ get linear() {
368
+ return {
369
+ issues: {
370
+ create: (params) => this.client.executeTool("linear-core-issueCreate", params),
371
+ list: (params) => this.client.executeTool("linear-core-issues", params),
372
+ get: (params) => this.client.executeTool("linear-core-issue", params),
373
+ update: (params) => this.client.executeTool("linear-core-issueUpdate", params),
374
+ archive: (params) => this.client.executeTool("linear-core-issueArchive", params)
375
+ },
376
+ teams: {
377
+ list: () => this.client.executeTool("linear-core-teams", {})
378
+ }
379
+ };
380
+ }
381
+ get slack() {
382
+ return {
383
+ messages: {
384
+ send: (params) => this.client.executeTool("slack-core-postMessage", params),
385
+ list: (params) => this.client.executeTool("slack-core-listMessages", params)
386
+ },
387
+ channels: {
388
+ list: () => this.client.executeTool("slack-core-listChannels", {})
389
+ },
390
+ users: {
391
+ list: () => this.client.executeTool("slack-core-listUsers", {})
392
+ },
393
+ reactions: {
394
+ add: (params) => this.client.executeTool("slack-core-addReaction", params)
395
+ }
396
+ };
397
+ }
398
+ get figma() {
399
+ return {
400
+ files: {
401
+ get: (params) => this.client.executeTool("figma-files-getFile", { fileKey: params.fileKey }),
402
+ getNodes: (params) => this.client.executeTool("figma-files-getFileNodes", { fileKey: params.fileKey, nodeIds: params.nodeIds }),
403
+ getImages: (params) => this.client.executeTool("figma-files-getFileImage", { fileKey: params.fileKey, nodeIds: params.nodeIds, format: params.format }),
404
+ getComments: (params) => this.client.executeTool("figma-comments-getFileComments", { fileKey: params.fileKey }),
405
+ postComment: (params) => this.client.executeTool("figma-comments-postComment", { fileKey: params.fileKey, message: params.message, nodeId: params.nodeId })
406
+ },
407
+ projects: {
408
+ list: (params) => this.client.executeTool("figma-projects-getTeamProjects", { teamId: params.teamId }),
409
+ getFiles: (params) => this.client.executeTool("figma-projects-getProjectFiles", { projectId: params.projectId })
410
+ }
411
+ };
412
+ }
413
+ get stripe() {
414
+ return {
415
+ customers: {
416
+ create: (params) => this.client.executeTool("stripe-customers-create", params),
417
+ retrieve: (params) => this.client.executeTool("stripe-customers-retrieve", { customerId: params.customerId }),
418
+ update: (params) => this.client.executeTool("stripe-customers-update", params),
419
+ listPaymentMethods: (params) => this.client.executeTool("stripe-customers-list-payment-methods", { customerId: params.customerId })
420
+ },
421
+ paymentIntents: {
422
+ create: (params) => this.client.executeTool("stripe-payment-intents-create", params),
423
+ retrieve: (params) => this.client.executeTool("stripe-payment-intents-retrieve", { paymentIntentId: params.paymentIntentId }),
424
+ confirm: (params) => this.client.executeTool("stripe-payment-intents-confirm", { paymentIntentId: params.paymentIntentId })
425
+ },
426
+ subscriptions: {
427
+ create: (params) => this.client.executeTool("stripe-subscriptions-create", params),
428
+ retrieve: (params) => this.client.executeTool("stripe-subscriptions-retrieve", { subscriptionId: params.subscriptionId }),
429
+ cancel: (params) => this.client.executeTool("stripe-subscriptions-cancel", { subscriptionId: params.subscriptionId })
430
+ }
431
+ };
432
+ }
433
+ };
434
+
435
+ // src/namespaces/memory.ts
436
+ function createMemory(client) {
437
+ return {
438
+ create: (params) => client.executeTool("memory-create", params),
439
+ get: (params) => client.executeTool("memory-get", { memoryId: params.memoryId }),
440
+ recall: (params) => client.executeTool("memory-recall", params),
441
+ list: (params) => client.executeTool("memory-list", params ?? {}),
442
+ update: (params) => client.executeTool("memory-update", params),
443
+ delete: (params) => client.executeTool("memory-delete", { memoryId: params.memoryId })
444
+ };
445
+ }
446
+
447
+ // src/namespaces/articles.ts
448
+ function createArticles(client) {
449
+ return {
450
+ search: (params) => client.executeTool("article-search", params),
451
+ create: (params) => client.executeTool("article-create", params),
452
+ createFromUrl: (params) => client.executeTool("article-create-from-url", params),
453
+ fetch: (params) => client.executeTool("article-fetch", params),
454
+ recent: (params) => client.executeTool("article-recent", params ?? {}),
455
+ relevant: (params) => client.executeTool("article-relevant-news", params),
456
+ summarize: (params) => client.executeTool("article-summarize", params),
457
+ extractTopics: (params) => client.executeTool("article-topic-extractor", params)
458
+ };
459
+ }
460
+
461
+ // src/namespaces/web.ts
462
+ function createWeb(client) {
463
+ return {
464
+ search: {
465
+ exa: (params) => client.executeTool("exa-web-search", params),
466
+ perplexity: (params) => client.executeTool("perplexity-search", params)
467
+ },
468
+ fetch: (params) => client.executeTool("web-fetch", params),
469
+ htmlToMarkdown: (params) => client.executeTool("html-to-markdown-converter", params),
470
+ extractHtml: (params) => client.executeTool("extract-html-selector", params)
471
+ };
472
+ }
473
+
474
+ // src/namespaces/ai.ts
475
+ function createAI(client) {
476
+ return {
477
+ embeddings: {
478
+ document: (params) => client.executeTool("jina-document-embedding", params),
479
+ query: (params) => client.executeTool("jina-query-embedding", params),
480
+ image: (params) => client.executeTool("jina-image-embedding", { image: params.imageBase64 })
481
+ },
482
+ image: {
483
+ generate: (params) => client.executeTool("image-generation", params)
484
+ },
485
+ ocr: (params) => client.executeTool("ocr-text-extraction", { image: params.imageBase64 }),
486
+ vision: (params) => client.executeTool("llama-scout-vision", { image: params.imageBase64, prompt: params.prompt }),
487
+ chat: (params) => client.executeTool("xai-chat-completions", params),
488
+ complete: (params) => client.executeTool("fim", params),
489
+ classify: (params) => client.executeTool("jina-document-classifier", params),
490
+ segment: (params) => client.executeTool("jina-text-segmenter", params)
491
+ };
492
+ }
493
+
494
+ // src/namespaces/data.ts
495
+ function createData(client) {
496
+ return {
497
+ csv: {
498
+ query: (params) => client.executeTool("query-csv", params),
499
+ convert: (params) => client.executeTool("csv-convert", params)
500
+ },
501
+ scripts: {
502
+ create: (params) => client.executeTool("create-saved-script", params),
503
+ execute: (params) => client.executeTool("execute-saved-script", params),
504
+ list: () => client.executeTool("list-saved-scripts", {}),
505
+ update: (params) => client.executeTool("update-saved-script", params),
506
+ delete: (params) => client.executeTool("delete-saved-script", params)
507
+ },
508
+ similarity: {
509
+ search: (params) => client.executeTool("duck-db-similarity-search", params),
510
+ duckDbSearch: (params) => client.executeTool("duck-db-similarity-search", params)
511
+ }
512
+ };
513
+ }
514
+
515
+ // src/namespaces/utils.ts
516
+ function createUtils(client) {
517
+ return {
518
+ mermaid: (params) => client.executeTool("mermaid-diagram-generator", { mermaid: params.diagram }),
519
+ documentConvert: (params) => client.executeTool("document-format-converter", {
520
+ base64: `data:${params.mimeType};base64,${Buffer.from(params.document).toString("base64")}`,
521
+ format: params.format
522
+ }),
523
+ regex: {
524
+ match: (params) => client.executeTool("regex-match", params),
525
+ replace: (params) => client.executeTool("regex-replace", params)
526
+ },
527
+ jsonExtract: (params) => client.executeTool("json-extract", params),
528
+ digest: (params) => client.executeTool("digest-generator", { text: params.data }),
529
+ monteCarlo: (params) => client.executeTool("monte-carlo-simulation", params)
530
+ };
531
+ }
532
+
533
+ // src/sdk.ts
534
+ var Rainfall = class {
535
+ client;
536
+ _integrations;
537
+ _memory;
538
+ _articles;
539
+ _web;
540
+ _ai;
541
+ _data;
542
+ _utils;
543
+ constructor(config) {
544
+ this.client = new RainfallClient(config);
545
+ }
546
+ /**
547
+ * Integrations namespace - GitHub, Notion, Linear, Slack, Figma, Stripe
548
+ *
549
+ * @example
550
+ * ```typescript
551
+ * // GitHub
552
+ * await rainfall.integrations.github.issues.create({
553
+ * owner: 'facebook',
554
+ * repo: 'react',
555
+ * title: 'Bug report'
556
+ * });
557
+ *
558
+ * // Slack
559
+ * await rainfall.integrations.slack.messages.send({
560
+ * channelId: 'C123456',
561
+ * text: 'Hello team!'
562
+ * });
563
+ *
564
+ * // Linear
565
+ * const issues = await rainfall.integrations.linear.issues.list();
566
+ * ```
567
+ */
568
+ get integrations() {
569
+ if (!this._integrations) {
570
+ this._integrations = createIntegrations(this.client);
571
+ }
572
+ return this._integrations;
573
+ }
574
+ /**
575
+ * Memory namespace - Semantic memory storage and retrieval
576
+ *
577
+ * @example
578
+ * ```typescript
579
+ * // Store a memory
580
+ * await rainfall.memory.create({
581
+ * content: 'User prefers dark mode',
582
+ * keywords: ['preference', 'ui']
583
+ * });
584
+ *
585
+ * // Recall similar memories
586
+ * const memories = await rainfall.memory.recall({
587
+ * query: 'user preferences',
588
+ * topK: 5
589
+ * });
590
+ * ```
591
+ */
592
+ get memory() {
593
+ if (!this._memory) {
594
+ this._memory = createMemory(this.client);
595
+ }
596
+ return this._memory;
597
+ }
598
+ /**
599
+ * Articles namespace - News aggregation and article management
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * // Search news
604
+ * const articles = await rainfall.articles.search({
605
+ * query: 'artificial intelligence'
606
+ * });
607
+ *
608
+ * // Create from URL
609
+ * const article = await rainfall.articles.createFromUrl({
610
+ * url: 'https://example.com/article'
611
+ * });
612
+ *
613
+ * // Summarize
614
+ * const summary = await rainfall.articles.summarize({
615
+ * text: article.content
616
+ * });
617
+ * ```
618
+ */
619
+ get articles() {
620
+ if (!this._articles) {
621
+ this._articles = createArticles(this.client);
622
+ }
623
+ return this._articles;
624
+ }
625
+ /**
626
+ * Web namespace - Web search, scraping, and content extraction
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * // Search with Exa
631
+ * const results = await rainfall.web.search.exa({
632
+ * query: 'latest AI research'
633
+ * });
634
+ *
635
+ * // Fetch and convert
636
+ * const html = await rainfall.web.fetch({ url: 'https://example.com' });
637
+ * const markdown = await rainfall.web.htmlToMarkdown({ html });
638
+ *
639
+ * // Extract specific elements
640
+ * const links = await rainfall.web.extractHtml({
641
+ * html,
642
+ * selector: 'a[href]'
643
+ * });
644
+ * ```
645
+ */
646
+ get web() {
647
+ if (!this._web) {
648
+ this._web = createWeb(this.client);
649
+ }
650
+ return this._web;
651
+ }
652
+ /**
653
+ * AI namespace - Embeddings, image generation, OCR, vision, chat
654
+ *
655
+ * @example
656
+ * ```typescript
657
+ * // Generate embeddings
658
+ * const embedding = await rainfall.ai.embeddings.document({
659
+ * text: 'Hello world'
660
+ * });
661
+ *
662
+ * // Generate image
663
+ * const image = await rainfall.ai.image.generate({
664
+ * prompt: 'A serene mountain landscape'
665
+ * });
666
+ *
667
+ * // OCR
668
+ * const text = await rainfall.ai.ocr({ imageBase64: '...' });
669
+ *
670
+ * // Chat
671
+ * const response = await rainfall.ai.chat({
672
+ * messages: [{ role: 'user', content: 'Hello!' }]
673
+ * });
674
+ * ```
675
+ */
676
+ get ai() {
677
+ if (!this._ai) {
678
+ this._ai = createAI(this.client);
679
+ }
680
+ return this._ai;
681
+ }
682
+ /**
683
+ * Data namespace - CSV processing, scripts, similarity search
684
+ *
685
+ * @example
686
+ * ```typescript
687
+ * // Query CSV with SQL
688
+ * const results = await rainfall.data.csv.query({
689
+ * sql: 'SELECT * FROM data WHERE value > 100'
690
+ * });
691
+ *
692
+ * // Execute saved script
693
+ * const result = await rainfall.data.scripts.execute({
694
+ * name: 'my-script',
695
+ * params: { input: 'data' }
696
+ * });
697
+ * ```
698
+ */
699
+ get data() {
700
+ if (!this._data) {
701
+ this._data = createData(this.client);
702
+ }
703
+ return this._data;
704
+ }
705
+ /**
706
+ * Utils namespace - Mermaid diagrams, document conversion, regex, JSON extraction
707
+ *
708
+ * @example
709
+ * ```typescript
710
+ * // Generate diagram
711
+ * const diagram = await rainfall.utils.mermaid({
712
+ * diagram: 'graph TD; A-->B;'
713
+ * });
714
+ *
715
+ * // Convert document
716
+ * const pdf = await rainfall.utils.documentConvert({
717
+ * document: markdownContent,
718
+ * mimeType: 'text/markdown',
719
+ * format: 'pdf'
720
+ * });
721
+ *
722
+ * // Extract JSON from text
723
+ * const json = await rainfall.utils.jsonExtract({
724
+ * text: 'Here is some data: {"key": "value"}'
725
+ * });
726
+ * ```
727
+ */
728
+ get utils() {
729
+ if (!this._utils) {
730
+ this._utils = createUtils(this.client);
731
+ }
732
+ return this._utils;
733
+ }
734
+ /**
735
+ * Get the underlying HTTP client for advanced usage
736
+ */
737
+ getClient() {
738
+ return this.client;
739
+ }
740
+ /**
741
+ * List all available tools
742
+ */
743
+ async listTools() {
744
+ return this.client.listTools();
745
+ }
746
+ /**
747
+ * Get schema for a specific tool
748
+ */
749
+ async getToolSchema(toolId) {
750
+ return this.client.getToolSchema(toolId);
751
+ }
752
+ /**
753
+ * Execute any tool by ID (low-level access)
754
+ */
755
+ async executeTool(toolId, params) {
756
+ return this.client.executeTool(toolId, params);
757
+ }
758
+ /**
759
+ * Get current subscriber info and usage
760
+ */
761
+ async getMe() {
762
+ return this.client.getMe();
763
+ }
764
+ /**
765
+ * Get current rate limit info
766
+ */
767
+ getRateLimitInfo() {
768
+ return this.client.getRateLimitInfo();
769
+ }
770
+ };
771
+
772
+ export {
773
+ RainfallError,
774
+ AuthenticationError,
775
+ RateLimitError,
776
+ ValidationError,
777
+ NotFoundError,
778
+ ServerError,
779
+ TimeoutError,
780
+ NetworkError,
781
+ ToolNotFoundError,
782
+ parseErrorResponse,
783
+ RainfallClient,
784
+ Rainfall
785
+ };