@takyonic/sdk 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.
package/dist/client.js ADDED
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TakyonicClient = void 0;
4
+ const table_builder_1 = require("./table-builder");
5
+ const errors_1 = require("./errors");
6
+ /**
7
+ * Default configuration values
8
+ */
9
+ const DEFAULT_TIMEOUT = 30000;
10
+ /**
11
+ * Takyonic Client - The main entry point for interacting with the Takyonic engine.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const db = new TakyonicClient({
16
+ * endpoint: 'http://localhost:8080',
17
+ * token: 'your-api-token'
18
+ * });
19
+ *
20
+ * // Query a table
21
+ * const logs = await db.table('logs').where('severity', '>', 4).get();
22
+ *
23
+ * // Insert a record
24
+ * await db.table('users').insert({ id: 'user-1', name: 'John' });
25
+ * ```
26
+ */
27
+ class TakyonicClient {
28
+ endpoint;
29
+ token;
30
+ timeout;
31
+ constructor(config) {
32
+ // Remove trailing slash from endpoint
33
+ this.endpoint = config.endpoint.replace(/\/+$/, '');
34
+ this.token = config.token;
35
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
36
+ }
37
+ /**
38
+ * Creates a TableBuilder for the specified table.
39
+ * This is the starting point for all table operations.
40
+ *
41
+ * @param name - The name of the table to query
42
+ * @returns A TableBuilder instance for fluent query building
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const results = await db.table('logs')
47
+ * .where('severity', '>=', 3)
48
+ * .get();
49
+ * ```
50
+ */
51
+ table(name) {
52
+ return new table_builder_1.TableBuilder(this, name);
53
+ }
54
+ /**
55
+ * Fetches server statistics including cache hits, misses, and performance metrics.
56
+ *
57
+ * @returns Promise resolving to server statistics
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const stats = await db.stats();
62
+ * console.log(`Cache hit rate: ${stats.cache_hits / stats.total_requests * 100}%`);
63
+ * ```
64
+ */
65
+ async stats() {
66
+ return this.request({
67
+ method: 'GET',
68
+ path: '/v1/stats',
69
+ });
70
+ }
71
+ /**
72
+ * Fetches the database schema including all tables, columns, and relationships.
73
+ *
74
+ * @returns Promise resolving to the schema information
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const schema = await db.schema();
79
+ * for (const table of schema.tables) {
80
+ * console.log(`Table: ${table.name}, Columns: ${table.columns.length}`);
81
+ * }
82
+ * ```
83
+ */
84
+ async schema() {
85
+ const tables = await this.request({
86
+ method: 'GET',
87
+ path: '/v1/schema',
88
+ });
89
+ return { tables };
90
+ }
91
+ /**
92
+ * Fetches the database schema as a formatted .takyonic DSL string.
93
+ * This is the authoritative format from the Rust backend.
94
+ *
95
+ * @returns Promise resolving to the DSL string content
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const dsl = await db.schemaDsl();
100
+ * fs.writeFileSync('.takyonic', dsl);
101
+ * ```
102
+ */
103
+ async schemaDsl() {
104
+ const url = `${this.endpoint}/v1/schema/dsl`;
105
+ const controller = new AbortController();
106
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
107
+ try {
108
+ const response = await fetch(url, {
109
+ method: 'GET',
110
+ headers: {
111
+ 'Authorization': `Bearer ${this.token}`,
112
+ },
113
+ signal: controller.signal,
114
+ });
115
+ clearTimeout(timeoutId);
116
+ if (!response.ok) {
117
+ let errorResponse;
118
+ try {
119
+ errorResponse = await response.json();
120
+ }
121
+ catch {
122
+ // Response body might not be valid JSON
123
+ }
124
+ throw (0, errors_1.createErrorFromStatus)(response.status, errorResponse);
125
+ }
126
+ return await response.text();
127
+ }
128
+ catch (error) {
129
+ clearTimeout(timeoutId);
130
+ if (error instanceof Error && error.name.includes('Error') && 'statusCode' in error) {
131
+ throw error;
132
+ }
133
+ if (error instanceof Error && error.name === 'AbortError') {
134
+ throw new errors_1.NetworkError(`Request timed out after ${this.timeout}ms`);
135
+ }
136
+ if (error instanceof TypeError) {
137
+ throw new errors_1.NetworkError(`Network request failed: ${error.message}`);
138
+ }
139
+ throw error;
140
+ }
141
+ }
142
+ /**
143
+ * Internal method to make HTTP requests to the Takyonic server.
144
+ * Handles authentication, error handling, and response parsing.
145
+ *
146
+ * @internal
147
+ */
148
+ async request(options) {
149
+ const { method, path, body, queryParams } = options;
150
+ // Build URL with query parameters
151
+ let url = `${this.endpoint}${path}`;
152
+ if (queryParams && Object.keys(queryParams).length > 0) {
153
+ const searchParams = new URLSearchParams();
154
+ for (const [key, value] of Object.entries(queryParams)) {
155
+ searchParams.append(key, value);
156
+ }
157
+ url += `?${searchParams.toString()}`;
158
+ }
159
+ // Build request options
160
+ const fetchOptions = {
161
+ method,
162
+ headers: {
163
+ 'Content-Type': 'application/json',
164
+ 'Authorization': `Bearer ${this.token}`,
165
+ },
166
+ };
167
+ if (body !== undefined) {
168
+ fetchOptions.body = JSON.stringify(body);
169
+ }
170
+ // Create abort controller for timeout
171
+ const controller = new AbortController();
172
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
173
+ fetchOptions.signal = controller.signal;
174
+ try {
175
+ const response = await fetch(url, fetchOptions);
176
+ clearTimeout(timeoutId);
177
+ // Handle non-OK responses
178
+ if (!response.ok) {
179
+ let errorResponse;
180
+ try {
181
+ errorResponse = await response.json();
182
+ }
183
+ catch {
184
+ // Response body might not be valid JSON
185
+ }
186
+ throw (0, errors_1.createErrorFromStatus)(response.status, errorResponse);
187
+ }
188
+ // Handle empty responses (like 204 No Content)
189
+ const contentType = response.headers.get('content-type');
190
+ if (!contentType || !contentType.includes('application/json')) {
191
+ return {};
192
+ }
193
+ return await response.json();
194
+ }
195
+ catch (error) {
196
+ clearTimeout(timeoutId);
197
+ // Re-throw TakyonicError instances
198
+ if (error instanceof Error && error.name.includes('Error') && 'statusCode' in error) {
199
+ throw error;
200
+ }
201
+ // Handle abort (timeout)
202
+ if (error instanceof Error && error.name === 'AbortError') {
203
+ throw new errors_1.NetworkError(`Request timed out after ${this.timeout}ms`);
204
+ }
205
+ // Handle network errors
206
+ if (error instanceof TypeError) {
207
+ throw new errors_1.NetworkError(`Network request failed: ${error.message}`);
208
+ }
209
+ // Re-throw unknown errors
210
+ throw error;
211
+ }
212
+ }
213
+ /**
214
+ * Gets the configured endpoint URL.
215
+ * @internal
216
+ */
217
+ getEndpoint() {
218
+ return this.endpoint;
219
+ }
220
+ /**
221
+ * Gets the configured timeout.
222
+ * @internal
223
+ */
224
+ getTimeout() {
225
+ return this.timeout;
226
+ }
227
+ }
228
+ exports.TakyonicClient = TakyonicClient;
229
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,mDAA+C;AAC/C,qCAA+D;AAU/D;;GAEG;AACH,MAAM,eAAe,GAAG,KAAK,CAAC;AAE9B;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,cAAc;IACR,QAAQ,CAAS;IACjB,KAAK,CAAS;IACd,OAAO,CAAS;IAEjC,YAAY,MAAsB;QAChC,sCAAsC;QACtC,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACpD,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,eAAe,CAAC;IACnD,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,KAAK,CAAoE,IAAY;QACnF,OAAO,IAAI,4BAAY,CAAI,IAAI,EAAE,IAAI,CAAC,CAAC;IACzC,CAAC;IAED;;;;;;;;;;OAUG;IACH,KAAK,CAAC,KAAK;QACT,OAAO,IAAI,CAAC,OAAO,CAAc;YAC/B,MAAM,EAAE,KAAK;YACb,IAAI,EAAE,WAAW;SAClB,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,MAAM;QACV,MAAM,MAAM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CAAC;YACd,CAAC;YAED,yBAAyB;YACzB,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;gBAC1D,MAAM,IAAI,qBAAY,CAAC,2BAA2B,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC;YACtE,CAAC;YAED,wBAAwB;YACxB,IAAI,KAAK,YAAY,SAAS,EAAE,CAAC;gBAC/B,MAAM,IAAI,qBAAY,CAAC,2BAA2B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACrE,CAAC;YAED,0BAA0B;YAC1B,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF;AAhOD,wCAgOC"}
@@ -0,0 +1,47 @@
1
+ import type { ErrorResponse } from './types';
2
+ /**
3
+ * Base error class for all Takyonic SDK errors
4
+ */
5
+ export declare class TakyonicError extends Error {
6
+ /** HTTP status code from the response */
7
+ readonly statusCode: number;
8
+ /** Raw error response from the server */
9
+ readonly response?: ErrorResponse;
10
+ constructor(message: string, statusCode: number, response?: ErrorResponse);
11
+ }
12
+ /**
13
+ * Error thrown when authentication fails (401 Unauthorized)
14
+ */
15
+ export declare class AuthenticationError extends TakyonicError {
16
+ constructor(message?: string, response?: ErrorResponse);
17
+ }
18
+ /**
19
+ * Error thrown when a resource is not found (404 Not Found)
20
+ */
21
+ export declare class NotFoundError extends TakyonicError {
22
+ constructor(message?: string, response?: ErrorResponse);
23
+ }
24
+ /**
25
+ * Error thrown when request validation fails (400 Bad Request)
26
+ */
27
+ export declare class ValidationError extends TakyonicError {
28
+ constructor(message?: string, response?: ErrorResponse);
29
+ }
30
+ /**
31
+ * Error thrown when the server encounters an internal error (500 Internal Server Error)
32
+ */
33
+ export declare class ServerError extends TakyonicError {
34
+ constructor(message?: string, response?: ErrorResponse);
35
+ }
36
+ /**
37
+ * Error thrown when a network request fails or times out
38
+ */
39
+ export declare class NetworkError extends TakyonicError {
40
+ constructor(message?: string);
41
+ }
42
+ /**
43
+ * Creates the appropriate error based on HTTP status code
44
+ * @internal
45
+ */
46
+ export declare function createErrorFromStatus(statusCode: number, response?: ErrorResponse): TakyonicError;
47
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C;;GAEG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACtC,yCAAyC;IACzC,SAAgB,UAAU,EAAE,MAAM,CAAC;IACnC,yCAAyC;IACzC,SAAgB,QAAQ,CAAC,EAAE,aAAa,CAAC;gBAE7B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,aAAa;CAW1E;AAED;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,aAAa;gBACxC,OAAO,GAAE,MAAuD,EAAE,QAAQ,CAAC,EAAE,aAAa;CAIvG;AAED;;GAEG;AACH,qBAAa,aAAc,SAAQ,aAAa;gBAClC,OAAO,GAAE,MAA8B,EAAE,QAAQ,CAAC,EAAE,aAAa;CAI9E;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,aAAa;gBACpC,OAAO,GAAE,MAA6B,EAAE,QAAQ,CAAC,EAAE,aAAa;CAI7E;AAED;;GAEG;AACH,qBAAa,WAAY,SAAQ,aAAa;gBAChC,OAAO,GAAE,MAAiC,EAAE,QAAQ,CAAC,EAAE,aAAa;CAIjF;AAED;;GAEG;AACH,qBAAa,YAAa,SAAQ,aAAa;gBACjC,OAAO,GAAE,MAAkC;CAIxD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,aAAa,GACvB,aAAa,CAkBf"}
package/dist/errors.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NetworkError = exports.ServerError = exports.ValidationError = exports.NotFoundError = exports.AuthenticationError = exports.TakyonicError = void 0;
4
+ exports.createErrorFromStatus = createErrorFromStatus;
5
+ /**
6
+ * Base error class for all Takyonic SDK errors
7
+ */
8
+ class TakyonicError extends Error {
9
+ /** HTTP status code from the response */
10
+ statusCode;
11
+ /** Raw error response from the server */
12
+ response;
13
+ constructor(message, statusCode, response) {
14
+ super(message);
15
+ this.name = 'TakyonicError';
16
+ this.statusCode = statusCode;
17
+ this.response = response;
18
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
19
+ if (Error.captureStackTrace) {
20
+ Error.captureStackTrace(this, this.constructor);
21
+ }
22
+ }
23
+ }
24
+ exports.TakyonicError = TakyonicError;
25
+ /**
26
+ * Error thrown when authentication fails (401 Unauthorized)
27
+ */
28
+ class AuthenticationError extends TakyonicError {
29
+ constructor(message = 'Authentication failed. Check your API token.', response) {
30
+ super(message, 401, response);
31
+ this.name = 'AuthenticationError';
32
+ }
33
+ }
34
+ exports.AuthenticationError = AuthenticationError;
35
+ /**
36
+ * Error thrown when a resource is not found (404 Not Found)
37
+ */
38
+ class NotFoundError extends TakyonicError {
39
+ constructor(message = 'Resource not found.', response) {
40
+ super(message, 404, response);
41
+ this.name = 'NotFoundError';
42
+ }
43
+ }
44
+ exports.NotFoundError = NotFoundError;
45
+ /**
46
+ * Error thrown when request validation fails (400 Bad Request)
47
+ */
48
+ class ValidationError extends TakyonicError {
49
+ constructor(message = 'Validation failed.', response) {
50
+ super(message, 400, response);
51
+ this.name = 'ValidationError';
52
+ }
53
+ }
54
+ exports.ValidationError = ValidationError;
55
+ /**
56
+ * Error thrown when the server encounters an internal error (500 Internal Server Error)
57
+ */
58
+ class ServerError extends TakyonicError {
59
+ constructor(message = 'Internal server error.', response) {
60
+ super(message, 500, response);
61
+ this.name = 'ServerError';
62
+ }
63
+ }
64
+ exports.ServerError = ServerError;
65
+ /**
66
+ * Error thrown when a network request fails or times out
67
+ */
68
+ class NetworkError extends TakyonicError {
69
+ constructor(message = 'Network request failed.') {
70
+ super(message, 0);
71
+ this.name = 'NetworkError';
72
+ }
73
+ }
74
+ exports.NetworkError = NetworkError;
75
+ /**
76
+ * Creates the appropriate error based on HTTP status code
77
+ * @internal
78
+ */
79
+ function createErrorFromStatus(statusCode, response) {
80
+ const message = response?.message || response?.error || 'Unknown error';
81
+ switch (statusCode) {
82
+ case 400:
83
+ return new ValidationError(message, response);
84
+ case 401:
85
+ return new AuthenticationError(message, response);
86
+ case 404:
87
+ return new NotFoundError(message, response);
88
+ case 500:
89
+ case 502:
90
+ case 503:
91
+ case 504:
92
+ return new ServerError(message, response);
93
+ default:
94
+ return new TakyonicError(message, statusCode, response);
95
+ }
96
+ }
97
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AA8EA,sDAqBC;AAjGD;;GAEG;AACH,MAAa,aAAc,SAAQ,KAAK;IACtC,yCAAyC;IACzB,UAAU,CAAS;IACnC,yCAAyC;IACzB,QAAQ,CAAiB;IAEzC,YAAY,OAAe,EAAE,UAAkB,EAAE,QAAwB;QACvE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,qFAAqF;QACrF,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC5B,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF;AAjBD,sCAiBC;AAED;;GAEG;AACH,MAAa,mBA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KAAK,GAAG;YACN,OAAO,IAAI,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAChD,KAAK,GAAG;YACN,OAAO,IAAI,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpD,KAAK,GAAG;YACN,OAAO,IAAI,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC9C,KAAK,GAAG,CAAC;QACT,KAAK,GAAG,CAAC;QACT,KAAK,GAAG,CAAC;QACT,KAAK,GAAG;YACN,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC5C;YACE,OAAO,IAAI,aAAa,CAAC,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @takyonic/sdk - Official Node.js SDK for Takyonic
3
+ *
4
+ * A high-performance caching engine client with fluent API.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { TakyonicClient } from '@takyonic/sdk';
9
+ *
10
+ * const db = new TakyonicClient({
11
+ * endpoint: 'http://localhost:8080',
12
+ * token: 'your-api-token'
13
+ * });
14
+ *
15
+ * // Query with filters
16
+ * const logs = await db.table('logs')
17
+ * .where('severity', '>', 4)
18
+ * .get();
19
+ *
20
+ * // Insert a record
21
+ * await db.table('users').insert({
22
+ * id: 'user-1',
23
+ * name: 'John Doe'
24
+ * });
25
+ *
26
+ * // Bulk insert with automatic batching
27
+ * await db.table('logs').insertMany(thousandsOfRecords);
28
+ * ```
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ export { TakyonicClient } from './client';
33
+ export { AdminClient } from './admin-client';
34
+ export { TableBuilder } from './table-builder';
35
+ export { TakyonicError, AuthenticationError, NotFoundError, ValidationError, ServerError, NetworkError, } from './errors';
36
+ export type { TakyonicConfig, AdminConfig, ComparisonOperator, Filter, BaseRecord, WriteResult, BulkInsertResult, MigrationResult, ServerStats, SchemaResponse, TableSchema, ColumnSchema, IndexInfo, ForeignKeyInfo, ErrorResponse, } from './types';
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAG1C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAG7C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAG/C,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,WAAW,EACX,YAAY,GACb,MAAM,UAAU,CAAC;AAGlB,YAAY,EACV,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,MAAM,EACN,UAAU,EACV,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,cAAc,EACd,WAAW,EACX,YAAY,EACZ,SAAS,EACT,cAAc,EACd,aAAa,GACd,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * @takyonic/sdk - Official Node.js SDK for Takyonic
4
+ *
5
+ * A high-performance caching engine client with fluent API.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { TakyonicClient } from '@takyonic/sdk';
10
+ *
11
+ * const db = new TakyonicClient({
12
+ * endpoint: 'http://localhost:8080',
13
+ * token: 'your-api-token'
14
+ * });
15
+ *
16
+ * // Query with filters
17
+ * const logs = await db.table('logs')
18
+ * .where('severity', '>', 4)
19
+ * .get();
20
+ *
21
+ * // Insert a record
22
+ * await db.table('users').insert({
23
+ * id: 'user-1',
24
+ * name: 'John Doe'
25
+ * });
26
+ *
27
+ * // Bulk insert with automatic batching
28
+ * await db.table('logs').insertMany(thousandsOfRecords);
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.NetworkError = exports.ServerError = exports.ValidationError = exports.NotFoundError = exports.AuthenticationError = exports.TakyonicError = exports.TableBuilder = exports.AdminClient = exports.TakyonicClient = void 0;
35
+ // Main client
36
+ var client_1 = require("./client");
37
+ Object.defineProperty(exports, "TakyonicClient", { enumerable: true, get: function () { return client_1.TakyonicClient; } });
38
+ // Admin client for privileged operations
39
+ var admin_client_1 = require("./admin-client");
40
+ Object.defineProperty(exports, "AdminClient", { enumerable: true, get: function () { return admin_client_1.AdminClient; } });
41
+ // Table builder for fluent API
42
+ var table_builder_1 = require("./table-builder");
43
+ Object.defineProperty(exports, "TableBuilder", { enumerable: true, get: function () { return table_builder_1.TableBuilder; } });
44
+ // Error classes
45
+ var errors_1 = require("./errors");
46
+ Object.defineProperty(exports, "TakyonicError", { enumerable: true, get: function () { return errors_1.TakyonicError; } });
47
+ Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_1.AuthenticationError; } });
48
+ Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_1.NotFoundError; } });
49
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_1.ValidationError; } });
50
+ Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_1.ServerError; } });
51
+ Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return errors_1.NetworkError; } });
52
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;;AAEH,cAAc;AACd,mCAA0C;AAAjC,wGAAA,cAAc,OAAA;AAEvB,yCAAyC;AACzC,+CAA6C;AAApC,2GAAA,WAAW,OAAA;AAEpB,+BAA+B;AAC/B,iDAA+C;AAAtC,6GAAA,YAAY,OAAA;AAErB,gBAAgB;AAChB,mCAOkB;AANhB,uGAAA,aAAa,OAAA;AACb,6GAAA,mBAAmB,OAAA;AACnB,uGAAA,aAAa,OAAA;AACb,yGAAA,eAAe,OAAA;AACf,qGAAA,WAAW,OAAA;AACX,sGAAA,YAAY,OAAA"}
@@ -0,0 +1,159 @@
1
+ import type { TakyonicClient } from './client';
2
+ import type { ComparisonOperator, BaseRecord, WriteResult, BulkInsertResult } from './types';
3
+ /**
4
+ * TableBuilder provides a fluent/chainable API for querying and modifying table data.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * // Search with filters
9
+ * const logs = await db.table('logs')
10
+ * .where('severity', '>', 4)
11
+ * .where('event', '=', 'error')
12
+ * .get();
13
+ *
14
+ * // Find a single record
15
+ * const user = await db.table('users').findById('user-123');
16
+ *
17
+ * // Insert records
18
+ * await db.table('logs').insert({ id: 'log-1', message: 'Hello' });
19
+ *
20
+ * // Bulk insert with automatic batching
21
+ * await db.table('logs').insertMany(thousandsOfRecords);
22
+ * ```
23
+ */
24
+ export declare class TableBuilder<T extends BaseRecord = BaseRecord> {
25
+ private readonly client;
26
+ private readonly tableName;
27
+ private filters;
28
+ constructor(client: TakyonicClient, tableName: string);
29
+ /**
30
+ * Adds a filter condition to the query.
31
+ * Multiple calls to where() are combined with AND logic.
32
+ *
33
+ * @param column - The column name to filter on
34
+ * @param operator - Comparison operator ('>', '<', '>=', '<=', '=', '!=')
35
+ * @param value - The value to compare against
36
+ * @returns The TableBuilder instance for chaining
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const results = await db.table('logs')
41
+ * .where('severity', '>=', 3)
42
+ * .where('event', '=', 'login')
43
+ * .get();
44
+ * ```
45
+ */
46
+ where(column: string, operator: ComparisonOperator, value: string | number | boolean): TableBuilder<T>;
47
+ /**
48
+ * Adds a full-text search filter using PostgreSQL FTS.
49
+ * Uses GIN indexes for sub-millisecond text searching across large datasets.
50
+ * Multiple search() calls are combined with AND logic.
51
+ *
52
+ * @param column - The column name to search in (text, varchar, or jsonb)
53
+ * @param query - The search terms (words are combined with AND logic)
54
+ * @returns The TableBuilder instance for chaining
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // Find logs containing "critical" in the event field
59
+ * const logs = await db.table('logs')
60
+ * .search('event', 'critical')
61
+ * .get();
62
+ *
63
+ * // Combine FTS with regular filters
64
+ * const errorLogs = await db.table('logs')
65
+ * .search('payload', 'database connection')
66
+ * .where('severity', '>', 3)
67
+ * .get();
68
+ * ```
69
+ */
70
+ search(column: string, query: string): TableBuilder<T>;
71
+ /**
72
+ * Executes the query with all applied filters and returns the matching records.
73
+ *
74
+ * @returns Promise resolving to an array of matching records
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const logs = await db.table('logs')
79
+ * .where('severity', '>', 4)
80
+ * .get();
81
+ * ```
82
+ */
83
+ get(): Promise<T[]>;
84
+ /**
85
+ * Fetches a single record by its ID.
86
+ *
87
+ * @param id - The unique identifier of the record
88
+ * @returns Promise resolving to the record, or null if not found
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const user = await db.table('users').findById('user-123');
93
+ * if (user) {
94
+ * console.log(user.name);
95
+ * }
96
+ * ```
97
+ */
98
+ findById(id: string): Promise<T | null>;
99
+ /**
100
+ * Inserts a new record or updates an existing one (upsert).
101
+ * The record must have an 'id' field.
102
+ *
103
+ * @param data - The record data to insert
104
+ * @returns Promise resolving to the write result
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * await db.table('users').insert({
109
+ * id: 'user-123',
110
+ * name: 'John Doe',
111
+ * email: 'john@example.com'
112
+ * });
113
+ * ```
114
+ */
115
+ insert(data: T): Promise<WriteResult>;
116
+ /**
117
+ * Alias for insert(). Inserts a new record or updates an existing one.
118
+ *
119
+ * @param data - The record data to upsert
120
+ * @returns Promise resolving to the write result
121
+ */
122
+ upsert(data: T): Promise<WriteResult>;
123
+ /**
124
+ * Inserts multiple records with automatic batching.
125
+ * Large arrays are automatically chunked into batches of 1000 records
126
+ * to comply with the server's bulk write limit.
127
+ *
128
+ * @param records - Array of records to insert
129
+ * @returns Promise resolving to the bulk insert result
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const logs = Array.from({ length: 5000 }, (_, i) => ({
134
+ * id: `log-${i}`,
135
+ * message: `Log entry ${i}`,
136
+ * severity: Math.floor(Math.random() * 5)
137
+ * }));
138
+ *
139
+ * const result = await db.table('logs').insertMany(logs);
140
+ * console.log(`Inserted ${result.totalInserted} records in ${result.batchesProcessed} batches`);
141
+ * ```
142
+ */
143
+ insertMany(records: T[]): Promise<BulkInsertResult>;
144
+ /**
145
+ * Invalidates the cache for a specific record.
146
+ * This forces the next read to fetch from the database.
147
+ *
148
+ * @param id - The unique identifier of the record to invalidate
149
+ * @returns Promise that resolves when the cache is invalidated
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * // After an external update, invalidate the cache
154
+ * await db.table('users').invalidateCache('user-123');
155
+ * ```
156
+ */
157
+ invalidateCache(id: string): Promise<void>;
158
+ }
159
+ //# sourceMappingURL=table-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"table-builder.d.ts","sourceRoot":"","sources":["../src/table-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,KAAK,EAEV,kBAAkB,EAClB,UAAU,EACV,WAAW,EACX,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAQjB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,YAAY,CAAC,CAAC,SAAS,UAAU,GAAG,UAAU;IACzD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,OAAO,CAAgB;gBAEnB,MAAM,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM;IAMrD;;;;;;;;;;;;;;;;OAgBG;IACH,KAAK,CACH,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,kBAAkB,EAC5B,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GA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