@kb-labs/core-platform 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 (56) hide show
  1. package/README.md +108 -0
  2. package/dist/adapters/index.cjs +26 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +125 -0
  5. package/dist/adapters/index.d.ts +125 -0
  6. package/dist/adapters/index.js +21 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/artifacts-BUghvkUU.d.cts +273 -0
  9. package/dist/artifacts-Bd-1UVTw.d.ts +273 -0
  10. package/dist/artifacts-DrVnkLzu.d.cts +1374 -0
  11. package/dist/artifacts-DrVnkLzu.d.ts +1374 -0
  12. package/dist/core/index.cjs +4 -0
  13. package/dist/core/index.cjs.map +1 -0
  14. package/dist/core/index.d.cts +2 -0
  15. package/dist/core/index.d.ts +2 -0
  16. package/dist/core/index.js +3 -0
  17. package/dist/core/index.js.map +1 -0
  18. package/dist/database-DGV6a1nj.d.cts +427 -0
  19. package/dist/database-DGV6a1nj.d.ts +427 -0
  20. package/dist/index.cjs +1405 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +579 -0
  23. package/dist/index.d.ts +579 -0
  24. package/dist/index.js +1381 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/log-reader-BVohbSMB.d.cts +314 -0
  27. package/dist/log-reader-uOHBLBax.d.ts +314 -0
  28. package/dist/noop/adapters/index.cjs +656 -0
  29. package/dist/noop/adapters/index.cjs.map +1 -0
  30. package/dist/noop/adapters/index.d.cts +71 -0
  31. package/dist/noop/adapters/index.d.ts +71 -0
  32. package/dist/noop/adapters/index.js +637 -0
  33. package/dist/noop/adapters/index.js.map +1 -0
  34. package/dist/noop/core/index.cjs +217 -0
  35. package/dist/noop/core/index.cjs.map +1 -0
  36. package/dist/noop/core/index.d.cts +94 -0
  37. package/dist/noop/core/index.d.ts +94 -0
  38. package/dist/noop/core/index.js +212 -0
  39. package/dist/noop/core/index.js.map +1 -0
  40. package/dist/noop/index.cjs +806 -0
  41. package/dist/noop/index.cjs.map +1 -0
  42. package/dist/noop/index.d.cts +36 -0
  43. package/dist/noop/index.d.ts +36 -0
  44. package/dist/noop/index.js +787 -0
  45. package/dist/noop/index.js.map +1 -0
  46. package/dist/resources-DaufJFad.d.cts +419 -0
  47. package/dist/resources-DaufJFad.d.ts +419 -0
  48. package/dist/serializable/index.cjs +162 -0
  49. package/dist/serializable/index.cjs.map +1 -0
  50. package/dist/serializable/index.d.cts +352 -0
  51. package/dist/serializable/index.d.ts +352 -0
  52. package/dist/serializable/index.js +152 -0
  53. package/dist/serializable/index.js.map +1 -0
  54. package/dist/snapshot-provider--COac4P-.d.ts +923 -0
  55. package/dist/snapshot-provider-nE9wuc1C.d.cts +923 -0
  56. package/package.json +92 -0
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=index.cjs.map
4
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,427 @@
1
+ /**
2
+ * @module @kb-labs/core-platform/adapters/database
3
+ * Database abstraction for SQL, Document, KV, and TimeSeries databases.
4
+ *
5
+ * Design principles:
6
+ * - Unified interface across SQL, NoSQL, KV, TimeSeries
7
+ * - Permission-aware (checked at runtime)
8
+ * - Backend-agnostic (SQLite, Postgres, Mongo, Redis, etc.)
9
+ */
10
+ /**
11
+ * Result of a SQL query execution.
12
+ */
13
+ interface SQLQueryResult<T = unknown> {
14
+ /** Rows returned by SELECT queries */
15
+ rows: T[];
16
+ /** Number of rows affected by INSERT/UPDATE/DELETE */
17
+ rowCount: number;
18
+ /** Column metadata (names, types) */
19
+ fields?: Array<{
20
+ name: string;
21
+ type: string;
22
+ }>;
23
+ }
24
+ /**
25
+ * SQL transaction interface.
26
+ * Supports ACID transactions with explicit commit/rollback.
27
+ */
28
+ interface SQLTransaction {
29
+ /**
30
+ * Execute a SQL query within the transaction.
31
+ * @param sql - SQL query string
32
+ * @param params - Query parameters (prevents SQL injection)
33
+ * @returns Query result
34
+ */
35
+ query<T = unknown>(sql: string, params?: unknown[]): Promise<SQLQueryResult<T>>;
36
+ /**
37
+ * Commit the transaction.
38
+ * All changes are persisted to the database.
39
+ */
40
+ commit(): Promise<void>;
41
+ /**
42
+ * Rollback the transaction.
43
+ * All changes are discarded.
44
+ */
45
+ rollback(): Promise<void>;
46
+ }
47
+ /**
48
+ * SQL database adapter interface.
49
+ *
50
+ * **Security model:**
51
+ * - Permission enforcement happens at runtime (SecureSQLDatabase wrapper)
52
+ * - SQL parsing extracts table names for permission checks
53
+ * - Validation-only approach (no query rewriting)
54
+ *
55
+ * **Implementations:**
56
+ * - `@kb-labs/adapters-db-sqlite` - SQLite (file-based, embedded)
57
+ * - `@kb-labs/adapters-db-postgres` - PostgreSQL (network)
58
+ * - `NoOpSQLDatabase` - No-op adapter for testing
59
+ */
60
+ interface ISQLDatabase {
61
+ /**
62
+ * Execute a SQL query.
63
+ *
64
+ * @param sql - SQL query string (SELECT, INSERT, UPDATE, DELETE, etc.)
65
+ * @param params - Query parameters (prevents SQL injection)
66
+ * @returns Query result
67
+ *
68
+ * **Security:**
69
+ * - Runtime permission check: extracts table names from SQL
70
+ * - Validates against `permissions.platform.database.sql.tables`
71
+ * - Throws PermissionError if access denied
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const result = await db.query<{ id: number; name: string }>(
76
+ * 'SELECT id, name FROM users WHERE age > ?',
77
+ * [18]
78
+ * );
79
+ * console.log(result.rows); // [{ id: 1, name: 'Alice' }, ...]
80
+ * ```
81
+ */
82
+ query<T = unknown>(sql: string, params?: unknown[]): Promise<SQLQueryResult<T>>;
83
+ /**
84
+ * Begin a SQL transaction.
85
+ *
86
+ * @returns Transaction object
87
+ *
88
+ * **Usage:**
89
+ * ```typescript
90
+ * const tx = await db.transaction();
91
+ * try {
92
+ * await tx.query('INSERT INTO users (name) VALUES (?)', ['Alice']);
93
+ * await tx.query('INSERT INTO audit_log (action) VALUES (?)', ['user_created']);
94
+ * await tx.commit();
95
+ * } catch (err) {
96
+ * await tx.rollback();
97
+ * throw err;
98
+ * }
99
+ * ```
100
+ */
101
+ transaction(): Promise<SQLTransaction>;
102
+ /**
103
+ * Close database connection.
104
+ * Should be called on shutdown.
105
+ */
106
+ close(): Promise<void>;
107
+ /**
108
+ * Execute raw SQL (for schema migrations).
109
+ * Optional utility method - not all database adapters may support this.
110
+ * Better-sqlite3's exec() handles multiple statements separated by semicolons.
111
+ *
112
+ * @param sql - Raw SQL string (may contain multiple statements)
113
+ */
114
+ exec?(sql: string): Promise<void>;
115
+ }
116
+ /**
117
+ * Base document type - all documents must have id, createdAt, updatedAt.
118
+ */
119
+ interface BaseDocument {
120
+ id: string;
121
+ createdAt: number;
122
+ updatedAt: number;
123
+ }
124
+ /**
125
+ * MongoDB-style query operators.
126
+ */
127
+ interface FilterOperators<T> {
128
+ $eq?: T;
129
+ $ne?: T;
130
+ $gt?: T;
131
+ $gte?: T;
132
+ $lt?: T;
133
+ $lte?: T;
134
+ $in?: T[];
135
+ $nin?: T[];
136
+ $exists?: boolean;
137
+ $regex?: string;
138
+ }
139
+ /**
140
+ * Document filter - MongoDB-style query syntax.
141
+ */
142
+ type DocumentFilter<T> = {
143
+ [K in keyof T]?: T[K] | FilterOperators<T[K]>;
144
+ } & {
145
+ $and?: DocumentFilter<T>[];
146
+ $or?: DocumentFilter<T>[];
147
+ };
148
+ /**
149
+ * MongoDB-style update operators.
150
+ */
151
+ interface DocumentUpdate<T> {
152
+ $set?: Partial<T>;
153
+ $unset?: {
154
+ [K in keyof T]?: 1;
155
+ };
156
+ $inc?: {
157
+ [K in keyof T]?: number;
158
+ };
159
+ $push?: {
160
+ [K in keyof T]?: unknown;
161
+ };
162
+ $pull?: {
163
+ [K in keyof T]?: unknown;
164
+ };
165
+ }
166
+ /**
167
+ * Find options (sort, limit, skip).
168
+ */
169
+ interface FindOptions {
170
+ sort?: Record<string, 1 | -1>;
171
+ limit?: number;
172
+ skip?: number;
173
+ }
174
+ /**
175
+ * Document database adapter interface.
176
+ *
177
+ * **Security model:**
178
+ * - Permission enforcement happens at runtime (SecureDocumentDatabase wrapper)
179
+ * - Validates collection access against `permissions.platform.database.document.collections`
180
+ *
181
+ * **Implementations:**
182
+ * - `@kb-labs/adapters-db-mongo` - MongoDB
183
+ * - `NoOpDocumentDatabase` - No-op adapter for testing
184
+ */
185
+ interface IDocumentDatabase {
186
+ /**
187
+ * Find documents matching a filter.
188
+ *
189
+ * @param collection - Collection name
190
+ * @param filter - MongoDB-style filter
191
+ * @param options - Sort, limit, skip
192
+ * @returns Array of matching documents
193
+ */
194
+ find<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>, options?: FindOptions): Promise<T[]>;
195
+ /**
196
+ * Find a single document by ID.
197
+ *
198
+ * @param collection - Collection name
199
+ * @param id - Document ID
200
+ * @returns Document or null if not found
201
+ */
202
+ findById<T extends BaseDocument>(collection: string, id: string): Promise<T | null>;
203
+ /**
204
+ * Insert a single document.
205
+ *
206
+ * @param collection - Collection name
207
+ * @param document - Document to insert (id, createdAt, updatedAt will be added if missing)
208
+ * @returns Inserted document with generated fields
209
+ */
210
+ insertOne<T extends BaseDocument>(collection: string, document: Omit<T, "id" | "createdAt" | "updatedAt">): Promise<T>;
211
+ /**
212
+ * Update documents matching a filter.
213
+ *
214
+ * @param collection - Collection name
215
+ * @param filter - MongoDB-style filter
216
+ * @param update - MongoDB-style update operators ($set, $inc, etc.)
217
+ * @returns Number of documents updated
218
+ */
219
+ updateMany<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>, update: DocumentUpdate<T>): Promise<number>;
220
+ /**
221
+ * Update a single document by ID.
222
+ *
223
+ * @param collection - Collection name
224
+ * @param id - Document ID
225
+ * @param update - MongoDB-style update operators
226
+ * @returns Updated document or null if not found
227
+ */
228
+ updateById<T extends BaseDocument>(collection: string, id: string, update: DocumentUpdate<T>): Promise<T | null>;
229
+ /**
230
+ * Delete documents matching a filter.
231
+ *
232
+ * @param collection - Collection name
233
+ * @param filter - MongoDB-style filter
234
+ * @returns Number of documents deleted
235
+ */
236
+ deleteMany<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>): Promise<number>;
237
+ /**
238
+ * Delete a single document by ID.
239
+ *
240
+ * @param collection - Collection name
241
+ * @param id - Document ID
242
+ * @returns True if deleted, false if not found
243
+ */
244
+ deleteById(collection: string, id: string): Promise<boolean>;
245
+ /**
246
+ * Count documents matching a filter.
247
+ *
248
+ * @param collection - Collection name
249
+ * @param filter - MongoDB-style filter
250
+ * @returns Number of matching documents
251
+ */
252
+ count<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>): Promise<number>;
253
+ /**
254
+ * Close database connection.
255
+ */
256
+ close(): Promise<void>;
257
+ }
258
+ /**
259
+ * Key-value database adapter interface.
260
+ *
261
+ * **Security model:**
262
+ * - Permission enforcement happens at runtime
263
+ * - Validates key prefix access against `permissions.platform.database.kv.prefixes`
264
+ *
265
+ * **Implementations:**
266
+ * - `@kb-labs/adapters-db-redis` - Redis
267
+ * - `NoOpKVDatabase` - No-op adapter for testing
268
+ */
269
+ interface IKeyValueDatabase {
270
+ /**
271
+ * Get value by key.
272
+ *
273
+ * @param key - Key to retrieve
274
+ * @returns Value or null if not found
275
+ */
276
+ get(key: string): Promise<string | null>;
277
+ /**
278
+ * Set value for key.
279
+ *
280
+ * @param key - Key to set
281
+ * @param value - Value to store
282
+ * @param ttlMs - Optional TTL in milliseconds
283
+ */
284
+ set(key: string, value: string, ttlMs?: number): Promise<void>;
285
+ /**
286
+ * Delete key.
287
+ *
288
+ * @param key - Key to delete
289
+ * @returns True if deleted, false if not found
290
+ */
291
+ delete(key: string): Promise<boolean>;
292
+ /**
293
+ * Check if key exists.
294
+ *
295
+ * @param key - Key to check
296
+ * @returns True if exists, false otherwise
297
+ */
298
+ exists(key: string): Promise<boolean>;
299
+ /**
300
+ * List keys matching a pattern.
301
+ *
302
+ * @param pattern - Glob pattern (e.g., 'user:*')
303
+ * @returns Array of matching keys
304
+ */
305
+ keys(pattern: string): Promise<string[]>;
306
+ /**
307
+ * Close database connection.
308
+ */
309
+ close(): Promise<void>;
310
+ }
311
+ /**
312
+ * Time-series data point.
313
+ */
314
+ interface TimeSeriesPoint {
315
+ /** Timestamp (Unix milliseconds) */
316
+ timestamp: number;
317
+ /** Metric value */
318
+ value: number;
319
+ /** Optional tags/labels */
320
+ tags?: Record<string, string>;
321
+ }
322
+ /**
323
+ * Time-series database adapter interface.
324
+ *
325
+ * **Security model:**
326
+ * - Permission enforcement happens at runtime
327
+ * - Validates metric access against `permissions.platform.database.timeseries.metrics`
328
+ *
329
+ * **Implementations:**
330
+ * - `@kb-labs/adapters-db-timescale` - TimescaleDB (PostgreSQL extension)
331
+ * - `NoOpTimeSeriesDatabase` - No-op adapter for testing
332
+ */
333
+ interface ITimeSeriesDatabase {
334
+ /**
335
+ * Write a single data point.
336
+ *
337
+ * @param metric - Metric name (e.g., 'cpu_usage')
338
+ * @param point - Data point
339
+ */
340
+ write(metric: string, point: TimeSeriesPoint): Promise<void>;
341
+ /**
342
+ * Write multiple data points (batch).
343
+ *
344
+ * @param metric - Metric name
345
+ * @param points - Array of data points
346
+ */
347
+ writeBatch(metric: string, points: TimeSeriesPoint[]): Promise<void>;
348
+ /**
349
+ * Query time-series data.
350
+ *
351
+ * @param metric - Metric name
352
+ * @param startTime - Start timestamp (Unix milliseconds)
353
+ * @param endTime - End timestamp (Unix milliseconds)
354
+ * @param tags - Optional tag filters
355
+ * @returns Array of data points
356
+ */
357
+ query(metric: string, startTime: number, endTime: number, tags?: Record<string, string>): Promise<TimeSeriesPoint[]>;
358
+ /**
359
+ * Close database connection.
360
+ */
361
+ close(): Promise<void>;
362
+ }
363
+ /**
364
+ * Database provider interface.
365
+ * Provides access to different database types (SQL, Document, KV, TimeSeries).
366
+ *
367
+ * **Usage:**
368
+ * ```typescript
369
+ * const provider = runtime.platform.database;
370
+ *
371
+ * // SQL
372
+ * const sql = await provider.getSQLDatabase('main');
373
+ * const users = await sql.query('SELECT * FROM users WHERE active = ?', [true]);
374
+ *
375
+ * // Document
376
+ * const doc = await provider.getDocumentDatabase('main');
377
+ * const posts = await doc.find('posts', { status: 'published' });
378
+ *
379
+ * // KV
380
+ * const kv = await provider.getKeyValueDatabase('cache');
381
+ * await kv.set('session:123', JSON.stringify(session), 3600000);
382
+ *
383
+ * // TimeSeries
384
+ * const ts = await provider.getTimeSeriesDatabase('metrics');
385
+ * await ts.write('api_latency', { timestamp: Date.now(), value: 42 });
386
+ * ```
387
+ */
388
+ interface IDatabaseProvider {
389
+ /**
390
+ * Get SQL database instance.
391
+ *
392
+ * @param name - Database name (from config)
393
+ * @returns SQL database adapter
394
+ * @throws Error if database not configured
395
+ */
396
+ getSQLDatabase(name: string): Promise<ISQLDatabase>;
397
+ /**
398
+ * Get document database instance.
399
+ *
400
+ * @param name - Database name (from config)
401
+ * @returns Document database adapter
402
+ * @throws Error if database not configured
403
+ */
404
+ getDocumentDatabase(name: string): Promise<IDocumentDatabase>;
405
+ /**
406
+ * Get key-value database instance.
407
+ *
408
+ * @param name - Database name (from config)
409
+ * @returns KV database adapter
410
+ * @throws Error if database not configured
411
+ */
412
+ getKeyValueDatabase(name: string): Promise<IKeyValueDatabase>;
413
+ /**
414
+ * Get time-series database instance.
415
+ *
416
+ * @param name - Database name (from config)
417
+ * @returns TimeSeries database adapter
418
+ * @throws Error if database not configured
419
+ */
420
+ getTimeSeriesDatabase(name: string): Promise<ITimeSeriesDatabase>;
421
+ /**
422
+ * Close all database connections.
423
+ */
424
+ close(): Promise<void>;
425
+ }
426
+
427
+ export type { BaseDocument as B, DocumentFilter as D, FilterOperators as F, ISQLDatabase as I, SQLQueryResult as S, TimeSeriesPoint as T, SQLTransaction as a, IDocumentDatabase as b, DocumentUpdate as c, FindOptions as d, IKeyValueDatabase as e, ITimeSeriesDatabase as f, IDatabaseProvider as g };