@onchaindb/sdk 0.4.5 → 1.0.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.
Files changed (97) hide show
  1. package/.claude/settings.local.json +10 -2
  2. package/README.md +422 -355
  3. package/dist/batch.d.ts +1 -10
  4. package/dist/batch.d.ts.map +1 -1
  5. package/dist/batch.js +4 -26
  6. package/dist/batch.js.map +1 -1
  7. package/dist/client.d.ts +29 -43
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +198 -323
  10. package/dist/client.js.map +1 -1
  11. package/dist/database.d.ts +14 -131
  12. package/dist/database.d.ts.map +1 -1
  13. package/dist/database.js +35 -131
  14. package/dist/database.js.map +1 -1
  15. package/dist/index.d.ts +6 -9
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -15
  18. package/dist/index.js.map +1 -1
  19. package/dist/query-sdk/ConditionBuilder.d.ts +3 -11
  20. package/dist/query-sdk/ConditionBuilder.d.ts.map +1 -1
  21. package/dist/query-sdk/ConditionBuilder.js +10 -48
  22. package/dist/query-sdk/ConditionBuilder.js.map +1 -1
  23. package/dist/query-sdk/NestedBuilders.d.ts +33 -30
  24. package/dist/query-sdk/NestedBuilders.d.ts.map +1 -1
  25. package/dist/query-sdk/NestedBuilders.js +46 -43
  26. package/dist/query-sdk/NestedBuilders.js.map +1 -1
  27. package/dist/query-sdk/QueryBuilder.d.ts +4 -2
  28. package/dist/query-sdk/QueryBuilder.d.ts.map +1 -1
  29. package/dist/query-sdk/QueryBuilder.js +47 -169
  30. package/dist/query-sdk/QueryBuilder.js.map +1 -1
  31. package/dist/query-sdk/QueryResult.d.ts +0 -38
  32. package/dist/query-sdk/QueryResult.d.ts.map +1 -1
  33. package/dist/query-sdk/QueryResult.js +1 -227
  34. package/dist/query-sdk/QueryResult.js.map +1 -1
  35. package/dist/query-sdk/index.d.ts +1 -1
  36. package/dist/query-sdk/index.d.ts.map +1 -1
  37. package/dist/query-sdk/index.js.map +1 -1
  38. package/dist/query-sdk/operators.d.ts +32 -28
  39. package/dist/query-sdk/operators.d.ts.map +1 -1
  40. package/dist/query-sdk/operators.js +45 -155
  41. package/dist/query-sdk/operators.js.map +1 -1
  42. package/dist/types.d.ts +153 -1
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/jest.config.js +4 -0
  46. package/package.json +1 -1
  47. package/skills.md +0 -1
  48. package/src/client.ts +242 -745
  49. package/src/database.ts +70 -493
  50. package/src/index.ts +40 -193
  51. package/src/query-sdk/ConditionBuilder.ts +37 -89
  52. package/src/query-sdk/NestedBuilders.ts +90 -92
  53. package/src/query-sdk/QueryBuilder.ts +59 -218
  54. package/src/query-sdk/QueryResult.ts +4 -330
  55. package/src/query-sdk/README.md +214 -583
  56. package/src/query-sdk/index.ts +1 -1
  57. package/src/query-sdk/operators.ts +91 -200
  58. package/src/query-sdk/tests/FieldConditionBuilder.test.ts +70 -71
  59. package/src/query-sdk/tests/LogicalOperator.test.ts +43 -82
  60. package/src/query-sdk/tests/NestedBuilders.test.ts +229 -309
  61. package/src/query-sdk/tests/QueryBuilder.test.ts +5 -5
  62. package/src/query-sdk/tests/QueryResult.test.ts +41 -435
  63. package/src/query-sdk/tests/comprehensive.test.ts +4 -185
  64. package/src/tests/client-requests.test.ts +280 -0
  65. package/src/tests/client-validation.test.ts +80 -0
  66. package/src/types.ts +229 -8
  67. package/src/batch.ts +0 -257
  68. package/src/query-sdk/dist/ConditionBuilder.d.ts +0 -22
  69. package/src/query-sdk/dist/ConditionBuilder.js +0 -90
  70. package/src/query-sdk/dist/FieldConditionBuilder.d.ts +0 -1
  71. package/src/query-sdk/dist/FieldConditionBuilder.js +0 -6
  72. package/src/query-sdk/dist/NestedBuilders.d.ts +0 -43
  73. package/src/query-sdk/dist/NestedBuilders.js +0 -144
  74. package/src/query-sdk/dist/OnChainDB.d.ts +0 -19
  75. package/src/query-sdk/dist/OnChainDB.js +0 -123
  76. package/src/query-sdk/dist/QueryBuilder.d.ts +0 -70
  77. package/src/query-sdk/dist/QueryBuilder.js +0 -295
  78. package/src/query-sdk/dist/QueryResult.d.ts +0 -52
  79. package/src/query-sdk/dist/QueryResult.js +0 -293
  80. package/src/query-sdk/dist/SelectionBuilder.d.ts +0 -20
  81. package/src/query-sdk/dist/SelectionBuilder.js +0 -80
  82. package/src/query-sdk/dist/adapters/HttpClientAdapter.d.ts +0 -27
  83. package/src/query-sdk/dist/adapters/HttpClientAdapter.js +0 -170
  84. package/src/query-sdk/dist/index.d.ts +0 -36
  85. package/src/query-sdk/dist/index.js +0 -27
  86. package/src/query-sdk/dist/operators.d.ts +0 -56
  87. package/src/query-sdk/dist/operators.js +0 -289
  88. package/src/query-sdk/dist/tests/setup.d.ts +0 -15
  89. package/src/query-sdk/dist/tests/setup.js +0 -46
  90. package/src/query-sdk/jest.config.js +0 -25
  91. package/src/query-sdk/package.json +0 -46
  92. package/src/query-sdk/tests/aggregations.test.ts +0 -653
  93. package/src/query-sdk/tests/integration.test.ts +0 -608
  94. package/src/query-sdk/tests/operators.test.ts +0 -327
  95. package/src/query-sdk/tests/unit.test.ts +0 -794
  96. package/src/query-sdk/tsconfig.json +0 -26
  97. package/src/query-sdk/yarn.lock +0 -3092
@@ -1,52 +0,0 @@
1
- export declare class QueryResult<T = any> {
2
- data: T[];
3
- constructor(data: T[]);
4
- len(): number;
5
- length(): number;
6
- isEmpty(): boolean;
7
- first(): T | undefined;
8
- last(): T | undefined;
9
- get(index: number): T | undefined;
10
- any(predicate: (item: T) => boolean): boolean;
11
- all(predicate: (item: T) => boolean): boolean;
12
- find(predicate: (item: T) => boolean): T | undefined;
13
- filter(predicate: (item: T) => boolean): T[];
14
- map<U>(transform: (item: T) => U): U[];
15
- forEach(callback: (item: T, index: number) => void): void;
16
- reduce<U>(callback: (accumulator: U, item: T, index: number) => U, initialValue: U): U;
17
- groupBy(field: string): Record<string, T[]>;
18
- pluck(field: string): any[];
19
- pluckStrings(field: string): (string | null)[];
20
- pluckNumbers(field: string): (number | null)[];
21
- summarizeNumeric(field: string): NumericSummary | null;
22
- sortBy(field: string, ascending?: boolean): T[];
23
- sortByMultiple(fields: Array<{
24
- field: string;
25
- ascending?: boolean;
26
- }>): T[];
27
- paginate(page: number, pageSize: number): T[];
28
- chunk(size: number): T[][];
29
- distinctBy(field: string): T[];
30
- unique(): T[];
31
- count(predicate?: (item: T) => boolean): number;
32
- countBy(field: string): Record<string, number>;
33
- private getNestedValue;
34
- toArray(): T[];
35
- toJSON(): string;
36
- cast<U>(): QueryResult<U>;
37
- innerJoin<U>(other: QueryResult<U>, thisKey: string, otherKey: string): Array<T & U>;
38
- leftJoin<U>(other: QueryResult<U>, thisKey: string, otherKey: string): Array<T & Partial<U>>;
39
- toCsv(delimiter?: string): string;
40
- inspect(limit?: number): void;
41
- }
42
- export interface NumericSummary {
43
- count: number;
44
- sum: number;
45
- mean: number;
46
- median: number;
47
- min: number;
48
- max: number;
49
- standardDeviation: number;
50
- variance: number;
51
- }
52
- export declare function createQueryResult<T>(data: T[]): QueryResult<T>;
@@ -1,293 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryResult = void 0;
4
- exports.createQueryResult = createQueryResult;
5
- // Query result utilities class matching Rust SDK functionality
6
- class QueryResult {
7
- constructor(data) {
8
- this.data = Array.isArray(data) ? data : [data];
9
- }
10
- // ===== BASIC UTILITIES =====
11
- len() {
12
- return this.data.length;
13
- }
14
- length() {
15
- return this.len();
16
- }
17
- isEmpty() {
18
- return this.data.length === 0;
19
- }
20
- first() {
21
- return this.data[0];
22
- }
23
- last() {
24
- return this.data[this.data.length - 1];
25
- }
26
- get(index) {
27
- return this.data[index];
28
- }
29
- // ===== ITERATION UTILITIES =====
30
- any(predicate) {
31
- return this.data.some(predicate);
32
- }
33
- all(predicate) {
34
- return this.data.every(predicate);
35
- }
36
- find(predicate) {
37
- return this.data.find(predicate);
38
- }
39
- filter(predicate) {
40
- return this.data.filter(predicate);
41
- }
42
- map(transform) {
43
- return this.data.map(transform);
44
- }
45
- forEach(callback) {
46
- this.data.forEach(callback);
47
- }
48
- reduce(callback, initialValue) {
49
- return this.data.reduce(callback, initialValue);
50
- }
51
- // ===== AGGREGATION UTILITIES =====
52
- groupBy(field) {
53
- const groups = {};
54
- this.data.forEach(item => {
55
- const key = this.getNestedValue(item, field);
56
- const keyString = String(key ?? 'null');
57
- if (!groups[keyString]) {
58
- groups[keyString] = [];
59
- }
60
- groups[keyString].push(item);
61
- });
62
- return groups;
63
- }
64
- // Pluck values from a specific field across all records
65
- pluck(field) {
66
- return this.data.map(item => this.getNestedValue(item, field));
67
- }
68
- pluckStrings(field) {
69
- return this.data.map(item => {
70
- const value = this.getNestedValue(item, field);
71
- return typeof value === 'string' ? value : (value != null ? String(value) : null);
72
- });
73
- }
74
- pluckNumbers(field) {
75
- return this.data.map(item => {
76
- const value = this.getNestedValue(item, field);
77
- if (typeof value === 'number' && !isNaN(value)) {
78
- return value;
79
- }
80
- const parsed = Number(value);
81
- return !isNaN(parsed) ? parsed : null;
82
- });
83
- }
84
- // ===== NUMERIC SUMMARY =====
85
- summarizeNumeric(field) {
86
- const numbers = this.pluckNumbers(field).filter(n => n !== null);
87
- if (numbers.length === 0) {
88
- return null;
89
- }
90
- const sum = numbers.reduce((acc, n) => acc + n, 0);
91
- const mean = sum / numbers.length;
92
- const min = Math.min(...numbers);
93
- const max = Math.max(...numbers);
94
- // Calculate median
95
- const sortedNumbers = [...numbers].sort((a, b) => a - b);
96
- const mid = Math.floor(sortedNumbers.length / 2);
97
- const median = sortedNumbers.length % 2 !== 0
98
- ? sortedNumbers[mid]
99
- : (sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2;
100
- // Calculate standard deviation
101
- const variance = numbers.reduce((acc, n) => acc + Math.pow(n - mean, 2), 0) / numbers.length;
102
- const standardDeviation = Math.sqrt(variance);
103
- return {
104
- count: numbers.length,
105
- sum,
106
- mean,
107
- median,
108
- min,
109
- max,
110
- standardDeviation,
111
- variance
112
- };
113
- }
114
- // ===== SORTING =====
115
- sortBy(field, ascending = true) {
116
- const sorted = [...this.data].sort((a, b) => {
117
- const valueA = this.getNestedValue(a, field);
118
- const valueB = this.getNestedValue(b, field);
119
- // Handle null/undefined values
120
- if (valueA == null && valueB == null)
121
- return 0;
122
- if (valueA == null)
123
- return ascending ? -1 : 1;
124
- if (valueB == null)
125
- return ascending ? 1 : -1;
126
- // Compare values
127
- let comparison = 0;
128
- if (valueA < valueB)
129
- comparison = -1;
130
- else if (valueA > valueB)
131
- comparison = 1;
132
- return ascending ? comparison : -comparison;
133
- });
134
- return sorted;
135
- }
136
- // Multiple field sorting
137
- sortByMultiple(fields) {
138
- const sorted = [...this.data].sort((a, b) => {
139
- for (const { field, ascending = true } of fields) {
140
- const valueA = this.getNestedValue(a, field);
141
- const valueB = this.getNestedValue(b, field);
142
- // Handle null/undefined values
143
- if (valueA == null && valueB == null)
144
- continue;
145
- if (valueA == null)
146
- return ascending ? -1 : 1;
147
- if (valueB == null)
148
- return ascending ? 1 : -1;
149
- // Compare values
150
- let comparison = 0;
151
- if (valueA < valueB)
152
- comparison = -1;
153
- else if (valueA > valueB)
154
- comparison = 1;
155
- if (comparison !== 0) {
156
- return ascending ? comparison : -comparison;
157
- }
158
- }
159
- return 0;
160
- });
161
- return sorted;
162
- }
163
- // ===== PAGINATION =====
164
- paginate(page, pageSize) {
165
- const startIndex = (page - 1) * pageSize;
166
- const endIndex = startIndex + pageSize;
167
- return this.data.slice(startIndex, endIndex);
168
- }
169
- chunk(size) {
170
- const chunks = [];
171
- for (let i = 0; i < this.data.length; i += size) {
172
- chunks.push(this.data.slice(i, i + size));
173
- }
174
- return chunks;
175
- }
176
- // ===== DISTINCT/UNIQUE =====
177
- distinctBy(field) {
178
- const seen = new Set();
179
- return this.data.filter(item => {
180
- const value = this.getNestedValue(item, field);
181
- const key = String(value);
182
- if (seen.has(key)) {
183
- return false;
184
- }
185
- seen.add(key);
186
- return true;
187
- });
188
- }
189
- unique() {
190
- return [...new Set(this.data)];
191
- }
192
- // ===== STATISTICAL FUNCTIONS =====
193
- count(predicate) {
194
- if (predicate) {
195
- return this.data.filter(predicate).length;
196
- }
197
- return this.data.length;
198
- }
199
- countBy(field) {
200
- const counts = {};
201
- this.data.forEach(item => {
202
- const key = String(this.getNestedValue(item, field) ?? 'null');
203
- counts[key] = (counts[key] || 0) + 1;
204
- });
205
- return counts;
206
- }
207
- // ===== UTILITY METHODS =====
208
- // Get nested field value using dot notation
209
- getNestedValue(obj, path) {
210
- return path.split('.').reduce((current, key) => {
211
- return current && typeof current === 'object' ? current[key] : undefined;
212
- }, obj);
213
- }
214
- // ===== TRANSFORMATION =====
215
- toArray() {
216
- return [...this.data];
217
- }
218
- toJSON() {
219
- return JSON.stringify(this.data);
220
- }
221
- // Convert to QueryResult with different type
222
- cast() {
223
- return new QueryResult(this.data);
224
- }
225
- // ===== JOINING (similar to SQL joins) =====
226
- innerJoin(other, thisKey, otherKey) {
227
- const results = [];
228
- this.data.forEach(thisItem => {
229
- const thisValue = this.getNestedValue(thisItem, thisKey);
230
- other.data.forEach(otherItem => {
231
- const otherValue = this.getNestedValue(otherItem, otherKey);
232
- if (thisValue === otherValue) {
233
- results.push({ ...thisItem, ...otherItem });
234
- }
235
- });
236
- });
237
- return results;
238
- }
239
- leftJoin(other, thisKey, otherKey) {
240
- const results = [];
241
- this.data.forEach(thisItem => {
242
- const thisValue = this.getNestedValue(thisItem, thisKey);
243
- const matches = other.data.filter(otherItem => this.getNestedValue(otherItem, otherKey) === thisValue);
244
- if (matches.length > 0) {
245
- matches.forEach(match => {
246
- results.push({ ...thisItem, ...match });
247
- });
248
- }
249
- else {
250
- results.push({ ...thisItem });
251
- }
252
- });
253
- return results;
254
- }
255
- // ===== EXPORT/FORMATTING =====
256
- toCsv(delimiter = ',') {
257
- if (this.data.length === 0)
258
- return '';
259
- // Get all unique keys from all objects
260
- const allKeys = new Set();
261
- this.data.forEach(item => {
262
- if (typeof item === 'object' && item !== null) {
263
- Object.keys(item).forEach(key => allKeys.add(key));
264
- }
265
- });
266
- const headers = Array.from(allKeys);
267
- const csvRows = [headers.join(delimiter)];
268
- this.data.forEach(item => {
269
- const row = headers.map(header => {
270
- const value = typeof item === 'object' && item !== null ? item[header] : '';
271
- // Escape values that contain the delimiter
272
- const stringValue = String(value ?? '');
273
- return stringValue.includes(delimiter) ? `"${stringValue}"` : stringValue;
274
- });
275
- csvRows.push(row.join(delimiter));
276
- });
277
- return csvRows.join('\n');
278
- }
279
- // ===== DEBUGGING =====
280
- inspect(limit) {
281
- const itemsToShow = limit ? this.data.slice(0, limit) : this.data;
282
- console.log('QueryResult:', {
283
- count: this.data.length,
284
- showing: itemsToShow.length,
285
- data: itemsToShow
286
- });
287
- }
288
- }
289
- exports.QueryResult = QueryResult;
290
- // Utility function to create QueryResult
291
- function createQueryResult(data) {
292
- return new QueryResult(data);
293
- }
@@ -1,20 +0,0 @@
1
- import { SelectionMap } from '../index';
2
- export declare class SelectionBuilder {
3
- private selections;
4
- constructor();
5
- static new(): SelectionBuilder;
6
- static all(): SelectionMap;
7
- field(fieldName: string): SelectionBuilder;
8
- fields(fieldNames: string[]): SelectionBuilder;
9
- nested<T>(fieldName: string, builderFn: (nested: SelectionBuilder) => T): SelectionBuilder;
10
- exclude(fieldName: string): SelectionBuilder;
11
- excludeFields(fieldNames: string[]): SelectionBuilder;
12
- build(): SelectionMap;
13
- clear(): SelectionBuilder;
14
- isEmpty(): boolean;
15
- getSelectionCount(): number;
16
- hasField(fieldName: string): boolean;
17
- isFieldExcluded(fieldName: string): boolean;
18
- getSelectedFields(): string[];
19
- getExcludedFields(): string[];
20
- }
@@ -1,80 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SelectionBuilder = void 0;
4
- class SelectionBuilder {
5
- constructor() {
6
- this.selections = {};
7
- }
8
- static new() {
9
- return new SelectionBuilder();
10
- }
11
- // Static method to create selection that includes all fields
12
- static all() {
13
- return { "*": true }; // Empty selection map means select all fields
14
- }
15
- // Select specific fields
16
- field(fieldName) {
17
- this.selections[fieldName] = true; // true indicates field should be included
18
- return this;
19
- }
20
- // Select multiple fields at once
21
- fields(fieldNames) {
22
- fieldNames.forEach(field => {
23
- this.selections[field] = true;
24
- });
25
- return this;
26
- }
27
- // Select nested fields with a builder function
28
- nested(fieldName, builderFn) {
29
- const nestedBuilder = new SelectionBuilder();
30
- builderFn(nestedBuilder);
31
- this.selections[fieldName] = nestedBuilder.build();
32
- return this;
33
- }
34
- // Exclude specific fields (useful when selecting most fields)
35
- exclude(fieldName) {
36
- this.selections[fieldName] = false; // false indicates field should be excluded
37
- return this;
38
- }
39
- // Exclude multiple fields
40
- excludeFields(fieldNames) {
41
- fieldNames.forEach(field => {
42
- this.selections[field] = false;
43
- });
44
- return this;
45
- }
46
- // Build and return the selection map
47
- build() {
48
- return { ...this.selections };
49
- }
50
- // Reset the builder
51
- clear() {
52
- this.selections = {};
53
- return this;
54
- }
55
- // Check if any selections have been made
56
- isEmpty() {
57
- return Object.keys(this.selections).length === 0;
58
- }
59
- // Get current selection count
60
- getSelectionCount() {
61
- return Object.keys(this.selections).length;
62
- }
63
- // Check if a specific field is selected
64
- hasField(fieldName) {
65
- return fieldName in this.selections && this.selections[fieldName] === true;
66
- }
67
- // Check if a specific field is excluded
68
- isFieldExcluded(fieldName) {
69
- return fieldName in this.selections && this.selections[fieldName] === false;
70
- }
71
- // Get all selected field names
72
- getSelectedFields() {
73
- return Object.keys(this.selections).filter(field => this.selections[field] === true);
74
- }
75
- // Get all excluded field names
76
- getExcludedFields() {
77
- return Object.keys(this.selections).filter(field => this.selections[field] === false);
78
- }
79
- }
80
- exports.SelectionBuilder = SelectionBuilder;
@@ -1,27 +0,0 @@
1
- import { HttpClient } from "../index";
2
- declare global {
3
- interface Window {
4
- any: any;
5
- }
6
- }
7
- export declare class FetchHttpClient implements HttpClient {
8
- private fetchFn;
9
- constructor(fetchImplementation?: typeof fetch);
10
- post(url: string, data: any, headers?: Record<string, string>): Promise<any>;
11
- }
12
- export declare class AxiosHttpClient implements HttpClient {
13
- private axios;
14
- constructor(axiosInstance: any);
15
- post(url: string, data: any, headers?: Record<string, string>): Promise<any>;
16
- }
17
- export declare class NodeHttpClient implements HttpClient {
18
- private timeout;
19
- constructor(timeout?: number);
20
- post(url: string, data: any, headers?: Record<string, string>): Promise<any>;
21
- }
22
- export declare function createHttpClient(options?: {
23
- type?: 'fetch' | 'axios' | 'node';
24
- fetchImplementation?: typeof fetch;
25
- axiosInstance?: any;
26
- timeout?: number;
27
- }): HttpClient;
@@ -1,170 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NodeHttpClient = exports.AxiosHttpClient = exports.FetchHttpClient = void 0;
4
- exports.createHttpClient = createHttpClient;
5
- // Adapter for fetch API (works in both browser and Node.js with node-fetch)
6
- class FetchHttpClient {
7
- constructor(fetchImplementation) {
8
- // Use provided fetch implementation or global fetch
9
- this.fetchFn = fetchImplementation || (globalThis.fetch?.bind(globalThis));
10
- if (!this.fetchFn) {
11
- throw new Error('Fetch is not available. Please provide a fetch implementation or use in an environment that supports fetch.');
12
- }
13
- }
14
- async post(url, data, headers = {}) {
15
- try {
16
- const response = await this.fetchFn(url, {
17
- method: 'POST',
18
- headers: {
19
- 'Content-Type': 'application/json',
20
- ...headers,
21
- },
22
- body: JSON.stringify(data),
23
- });
24
- if (!response.ok) {
25
- const errorText = await response.text();
26
- throw new Error(`HTTP ${response.status}: ${errorText}`);
27
- }
28
- const contentType = response.headers.get('content-type');
29
- if (contentType && contentType.includes('application/json')) {
30
- return await response.json();
31
- }
32
- else {
33
- return await response.text();
34
- }
35
- }
36
- catch (error) {
37
- if (error instanceof Error) {
38
- throw error;
39
- }
40
- throw new Error(`Request failed: ${error}`);
41
- }
42
- }
43
- }
44
- exports.FetchHttpClient = FetchHttpClient;
45
- // Adapter for axios (if user prefers axios)
46
- class AxiosHttpClient {
47
- constructor(axiosInstance) {
48
- if (!axiosInstance) {
49
- throw new Error('Axios instance is required');
50
- }
51
- this.axios = axiosInstance;
52
- }
53
- async post(url, data, headers = {}) {
54
- try {
55
- const response = await this.axios.post(url, data, {
56
- headers: {
57
- 'Content-Type': 'application/json',
58
- ...headers,
59
- },
60
- });
61
- return response.data;
62
- }
63
- catch (error) {
64
- if (error.response) {
65
- throw new Error(`HTTP ${error.response.status}: ${JSON.stringify(error.response.data)}`);
66
- }
67
- else if (error.request) {
68
- throw new Error('No response received from server');
69
- }
70
- else {
71
- throw new Error(`Request setup error: ${error.message}`);
72
- }
73
- }
74
- }
75
- }
76
- exports.AxiosHttpClient = AxiosHttpClient;
77
- // Simple HTTP client using Node.js built-in modules (for Node.js environments)
78
- class NodeHttpClient {
79
- constructor(timeout = 30000) {
80
- this.timeout = timeout;
81
- }
82
- async post(url, data, headers = {}) {
83
- return new Promise((resolve, reject) => {
84
- const urlObj = new URL(url);
85
- const isHttps = urlObj.protocol === 'https:';
86
- // Dynamic import to avoid issues in browser environments
87
- const httpModule = isHttps ? require('https') : require('http');
88
- const postData = JSON.stringify(data);
89
- const options = {
90
- hostname: urlObj.hostname,
91
- port: urlObj.port || (isHttps ? 443 : 80),
92
- path: urlObj.pathname + urlObj.search,
93
- method: 'POST',
94
- headers: {
95
- 'Content-Type': 'application/json',
96
- 'Content-Length': Buffer.byteLength(postData),
97
- ...headers,
98
- },
99
- timeout: this.timeout,
100
- };
101
- const req = httpModule.request(options, (res) => {
102
- let responseData = '';
103
- res.on('data', (chunk) => {
104
- responseData += chunk;
105
- });
106
- res.on('end', () => {
107
- try {
108
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
109
- const contentType = res.headers['content-type'] || '';
110
- if (contentType.includes('application/json')) {
111
- resolve(JSON.parse(responseData));
112
- }
113
- else {
114
- resolve(responseData);
115
- }
116
- }
117
- else {
118
- reject(new Error(`HTTP ${res.statusCode}: ${responseData}`));
119
- }
120
- }
121
- catch (error) {
122
- reject(new Error(`Failed to parse response: ${error}`));
123
- }
124
- });
125
- });
126
- req.on('error', (error) => {
127
- reject(new Error(`Request failed: ${error.message}`));
128
- });
129
- req.on('timeout', () => {
130
- req.destroy();
131
- reject(new Error(`Request timed out after ${this.timeout}ms`));
132
- });
133
- req.write(postData);
134
- req.end();
135
- });
136
- }
137
- }
138
- exports.NodeHttpClient = NodeHttpClient;
139
- // Factory function to create appropriate HTTP client based on environment
140
- function createHttpClient(options = {}) {
141
- const { type, fetchImplementation, axiosInstance, timeout } = options;
142
- // Auto-detect environment if type is not specified
143
- if (!type) {
144
- if (typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function') {
145
- return new FetchHttpClient(fetchImplementation);
146
- }
147
- else { // @ts-ignore
148
- if (typeof window !== 'undefined') {
149
- throw new Error('Fetch is not available in this browser environment. Please provide a fetch implementation.');
150
- }
151
- else {
152
- // Assume Node.js environment
153
- return new NodeHttpClient(timeout);
154
- }
155
- }
156
- }
157
- switch (type) {
158
- case 'fetch':
159
- return new FetchHttpClient(fetchImplementation);
160
- case 'axios':
161
- if (!axiosInstance) {
162
- throw new Error('Axios instance is required when using axios client');
163
- }
164
- return new AxiosHttpClient(axiosInstance);
165
- case 'node':
166
- return new NodeHttpClient(timeout);
167
- default:
168
- throw new Error(`Unknown HTTP client type: ${type}`);
169
- }
170
- }
@@ -1,36 +0,0 @@
1
- export interface HttpClient {
2
- post(url: string, data: any, headers?: Record<string, string>): Promise<any>;
3
- }
4
- export interface QueryValue {
5
- find: any;
6
- select: any;
7
- }
8
- export type QueryRequest = QueryValue & {
9
- limit?: number;
10
- offset?: number;
11
- sort?: string[];
12
- };
13
- export interface QueryResponse<T = any> {
14
- records: T[];
15
- total?: number;
16
- error?: string;
17
- }
18
- export type SelectionMap = Record<string, any>;
19
- export type FieldMap = Record<string, string>;
20
- export type Val = string | number | boolean | null | Val[] | Date | RegExp;
21
- export interface BetweenValue {
22
- min: Val;
23
- max: Val;
24
- }
25
- export interface DateRange {
26
- start: Date | string | number;
27
- end: Date | string | number;
28
- }
29
- export { OnChainDB } from './OnChainDB';
30
- export { QueryBuilder } from './QueryBuilder';
31
- export { SelectionBuilder } from './SelectionBuilder';
32
- export { ConditionBuilder } from './ConditionBuilder';
33
- export { FieldConditionBuilder, LogicalOperator, Condition } from './operators';
34
- export { NestedConditionBuilder, NestedFieldConditionBuilder } from './NestedBuilders';
35
- export { QueryResult, NumericSummary, createQueryResult } from './QueryResult';
36
- export { FetchHttpClient, AxiosHttpClient, NodeHttpClient, createHttpClient } from './adapters/HttpClientAdapter';