inputlayer-js-dev 0.1.0-dev.ec507e7

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,929 @@
1
+ import { I as IQLType, C as ColumnProxy, R as RelationRef, E as Expr, B as BoolExpr, a as Column, b as Fact, c as RelationProxy, A as AggExpr } from './proxy-CPWAPhZZ.js';
2
+ export { d as AND, e as And, f as Arithmetic, g as ColumnDef, h as Comparison, i as FieldValue, F as FuncCall, j as InExpr, L as Literal, M as MatchExpr, N as NOT, k as NegatedIn, l as Not, O as OR, m as Or, n as OrderedColumn, o as RelationSchema, T as Timestamp, V as Vector, p as VectorInt8, w as wrap } from './proxy-CPWAPhZZ.js';
3
+
4
+ /**
5
+ * Relation definitions - schema-first approach for TypeScript.
6
+ *
7
+ * Unlike Python's class-based approach with Pydantic metaclasses, TypeScript
8
+ * uses plain objects with a schema descriptor. Relations are defined as:
9
+ *
10
+ * const Employee = relation("Employee", {
11
+ * id: "int",
12
+ * name: "string",
13
+ * department: "string",
14
+ * salary: "float",
15
+ * active: "bool",
16
+ * });
17
+ *
18
+ * This returns a RelationDef with column accessors, insert helpers, etc.
19
+ */
20
+
21
+ /** Column type shorthand map for the schema definition DSL. */
22
+ type ColumnTypes = Record<string, IQLType>;
23
+ /** A relation definition created by `relation()`. */
24
+ declare class RelationDef {
25
+ /** The IQL relation name (snake_case). */
26
+ readonly relationName: string;
27
+ /** Original class-style name. */
28
+ readonly className: string;
29
+ /** Ordered column names. */
30
+ readonly columns: string[];
31
+ /** Column name -> IQL type. */
32
+ readonly columnTypes: Record<string, IQLType>;
33
+ constructor(className: string, columnTypes: ColumnTypes, name?: string);
34
+ /** Get a ColumnProxy for a column (for query building). */
35
+ col(name: string): ColumnProxy;
36
+ /**
37
+ * Create multiple independent references for self-joins.
38
+ *
39
+ * Usage:
40
+ * const [r1, r2] = Follow.refs(2);
41
+ * kg.query({ select: [r1.col("follower"), r2.col("followee")], join: [r1, r2], ... });
42
+ */
43
+ refs(n: number): RelationRef[];
44
+ }
45
+ /**
46
+ * Define a relation schema.
47
+ *
48
+ * @param className - CamelCase name (converted to snake_case for IQL)
49
+ * @param columnTypes - Column name -> type mapping
50
+ * @param opts - Optional overrides
51
+ * @returns A RelationDef for use with KnowledgeGraph operations
52
+ *
53
+ * @example
54
+ * const Employee = relation("Employee", {
55
+ * id: "int",
56
+ * name: "string",
57
+ * department: "string",
58
+ * salary: "float",
59
+ * active: "bool",
60
+ * });
61
+ */
62
+ declare function relation(className: string, columnTypes: ColumnTypes, opts?: {
63
+ name?: string;
64
+ }): RelationDef;
65
+ /** Compile a value to its IQL literal representation. */
66
+ declare function compileValue(value: unknown): string;
67
+ /** Resolve a RelationDef or string to its IQL relation name. */
68
+ declare function resolveRelationName(r: RelationDef | string): string;
69
+ /** Get ordered column names from a RelationDef. */
70
+ declare function getColumns(r: RelationDef): string[];
71
+ /** Get column types from a RelationDef. */
72
+ declare function getColumnTypes(r: RelationDef): Record<string, IQLType>;
73
+
74
+ /**
75
+ * Compiler: TypeScript objects and AST nodes -> IQL text.
76
+ *
77
+ * Every function is pure (no I/O), taking TypeScript objects and returning
78
+ * IQL strings.
79
+ */
80
+
81
+ /**
82
+ * Variable environment for tracking column->variable mappings with union-find.
83
+ * Ensures that join conditions produce shared IQL variables.
84
+ */
85
+ declare class VarEnv {
86
+ private map;
87
+ private counter;
88
+ private parent;
89
+ private find;
90
+ private union;
91
+ getVar(col: Column): string;
92
+ unify(colA: Column, colB: Column): string;
93
+ lookup(col: Column): string | undefined;
94
+ /** Direct-set a variable for conditional delete setup. */
95
+ set(key: string, varName: string): void;
96
+ }
97
+ declare function compileExpr(expr: Expr, env: VarEnv): string;
98
+ declare function compileBoolExpr(expr: BoolExpr, env: VarEnv): string[];
99
+ /** Compile a relation definition to a schema statement: +employee(id: int, name: string, ...) */
100
+ declare function compileSchema(rel: RelationDef): string;
101
+ /** Compile a single fact insert: +employee(1, "Alice", ...) */
102
+ declare function compileInsert(rel: RelationDef, fact: Fact, persistent?: boolean): string;
103
+ /** Compile a bulk insert: +employee[(1, "Alice", ...), (2, "Bob", ...)] */
104
+ declare function compileBulkInsert(rel: RelationDef, facts: Fact[], persistent?: boolean): string;
105
+ /** Compile a single fact deletion: -employee(1, "Alice", ...) */
106
+ declare function compileDelete(rel: RelationDef, fact: Fact): string;
107
+ /** Compile a conditional delete: -employee(X0, X1, ...) <- employee(X0, X1, ...), X2 = "sales" */
108
+ declare function compileConditionalDelete(rel: RelationDef, condition: BoolExpr): string;
109
+ interface QueryOptions {
110
+ /** Columns/relations to select. */
111
+ select: Array<RelationDef | Expr>;
112
+ /** Relations to join. */
113
+ join?: Array<RelationDef | RelationRef>;
114
+ /** Join condition (BoolExpr). */
115
+ on?: BoolExpr;
116
+ /** Where filter (BoolExpr). */
117
+ where?: BoolExpr;
118
+ /** Order by expression. */
119
+ orderBy?: Expr;
120
+ /** Limit number of rows. */
121
+ limit?: number;
122
+ /** Offset for pagination. */
123
+ offset?: number;
124
+ /** Computed columns: alias -> Expr. */
125
+ computed?: Record<string, Expr>;
126
+ }
127
+ /**
128
+ * Compile a query to IQL.
129
+ * Returns a single string, or an array of strings if OR conditions require splitting.
130
+ */
131
+ declare function compileQuery(opts: QueryOptions): string | string[];
132
+ interface RuleClause {
133
+ /** Body relations: [name, RelationDef, alias?] */
134
+ relations: Array<{
135
+ name: string;
136
+ def: RelationDef;
137
+ alias?: string;
138
+ }>;
139
+ /** Head column -> body Expr mapping. */
140
+ selectMap: Record<string, Expr>;
141
+ /** Optional filter condition. */
142
+ condition?: BoolExpr;
143
+ }
144
+ /** Compile a rule definition to IQL. */
145
+ declare function compileRule(headName: string, headColumns: string[], clause: RuleClause, persistent?: boolean): string;
146
+
147
+ /**
148
+ * Derived relations and the From/Where/Select rule builder.
149
+ *
150
+ * Provides a fluent API for defining rules that mirrors the Python SDK.
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * const reachableRules = [
155
+ * from(Edge).select({ src: Edge.col("x"), dst: Edge.col("y") }),
156
+ * from(Reachable, Edge)
157
+ * .where((r, e) => r.col("dst").eq(e.col("x")))
158
+ * .select({ src: Reachable.col("src"), dst: Edge.col("y") }),
159
+ * ];
160
+ *
161
+ * await kg.defineRules("reachable", ["src", "dst"], reachableRules);
162
+ * ```
163
+ */
164
+
165
+ declare class FromWhere {
166
+ private readonly relations;
167
+ private readonly condition;
168
+ constructor(relations: Array<{
169
+ name: string;
170
+ def: RelationDef;
171
+ alias?: string;
172
+ }>, condition: BoolExpr);
173
+ /**
174
+ * Map derived columns to body expressions.
175
+ * Keys must match the derived relation's column names.
176
+ */
177
+ select(columns: Record<string, ColumnProxy | Expr>): RuleClause;
178
+ }
179
+ declare class FromBuilder {
180
+ private readonly relations;
181
+ constructor(rels: Array<RelationDef | RelationRef>);
182
+ /**
183
+ * Add a filter/join condition.
184
+ * Accepts a BoolExpr or a callback receiving RelationProxy objects.
185
+ */
186
+ where(condition: BoolExpr | ((...proxies: RelationProxy[]) => BoolExpr)): FromWhere;
187
+ /**
188
+ * Map derived columns to body expressions (no filter).
189
+ * Keys must match the derived relation's column names.
190
+ */
191
+ select(columns: Record<string, ColumnProxy | Expr>): RuleClause;
192
+ }
193
+ /**
194
+ * Start building a rule clause.
195
+ *
196
+ * @param relations - The body relations for this rule clause
197
+ * @returns A FromBuilder with .where() and .select() methods
198
+ *
199
+ * @example
200
+ * from(Edge).select({ src: Edge.col("x"), dst: Edge.col("y") })
201
+ */
202
+ declare function from(...relations: Array<RelationDef | RelationRef>): FromBuilder;
203
+
204
+ /**
205
+ * Aggregation functions that compile to IQL aggregates.
206
+ */
207
+
208
+ /**
209
+ * Count rows. If a column is given, counts non-null values.
210
+ * IQL: count<Var>
211
+ */
212
+ declare function count(column?: ColumnProxy | Expr): AggExpr;
213
+ /**
214
+ * Count distinct values.
215
+ * IQL: count_distinct<Var>
216
+ */
217
+ declare function countDistinct(column: ColumnProxy | Expr): AggExpr;
218
+ /**
219
+ * Sum numeric values.
220
+ * IQL: sum<Var>
221
+ */
222
+ declare function sum(column: ColumnProxy | Expr): AggExpr;
223
+ /**
224
+ * Minimum value.
225
+ * IQL: min<Var>
226
+ */
227
+ declare function min(column: ColumnProxy | Expr): AggExpr;
228
+ /**
229
+ * Maximum value.
230
+ * IQL: max<Var>
231
+ */
232
+ declare function max(column: ColumnProxy | Expr): AggExpr;
233
+ /**
234
+ * Average value.
235
+ * IQL: avg<Var>
236
+ */
237
+ declare function avg(column: ColumnProxy | Expr): AggExpr;
238
+ /**
239
+ * Top-K aggregation with ordering.
240
+ * IQL: top_k<k, Passthrough..., OrderCol:desc>
241
+ */
242
+ declare function topK(opts: {
243
+ k: number;
244
+ passthrough?: Array<ColumnProxy | Expr>;
245
+ orderBy: ColumnProxy | Expr;
246
+ desc?: boolean;
247
+ }): AggExpr;
248
+ /**
249
+ * Top-K with threshold aggregation.
250
+ * IQL: top_k_threshold<k, threshold, Passthrough..., OrderCol:desc>
251
+ */
252
+ declare function topKThreshold(opts: {
253
+ k: number;
254
+ threshold: number;
255
+ passthrough?: Array<ColumnProxy | Expr>;
256
+ orderBy: ColumnProxy | Expr;
257
+ desc?: boolean;
258
+ }): AggExpr;
259
+ /**
260
+ * Within-radius aggregation.
261
+ * IQL: within_radius<r, Passthrough..., DistCol:asc>
262
+ */
263
+ declare function withinRadius(opts: {
264
+ maxDistance: number;
265
+ passthrough?: Array<ColumnProxy | Expr>;
266
+ distance: ColumnProxy | Expr;
267
+ asc?: boolean;
268
+ }): AggExpr;
269
+
270
+ /**
271
+ * HNSW index definition and compilation.
272
+ */
273
+
274
+ interface HnswIndexOptions {
275
+ name: string;
276
+ relation: RelationDef;
277
+ column: string;
278
+ metric?: 'cosine' | 'euclidean' | 'manhattan' | 'dot_product';
279
+ m?: number;
280
+ efConstruction?: number;
281
+ efSearch?: number;
282
+ }
283
+ /**
284
+ * HNSW vector index configuration.
285
+ */
286
+ declare class HnswIndex {
287
+ readonly name: string;
288
+ readonly relation: RelationDef;
289
+ readonly column: string;
290
+ readonly metric: string;
291
+ readonly m: number;
292
+ readonly efConstruction: number;
293
+ readonly efSearch: number;
294
+ constructor(opts: HnswIndexOptions);
295
+ /** Compile this index definition to an IQL meta command. */
296
+ toIQL(): string;
297
+ }
298
+
299
+ /**
300
+ * Exception hierarchy for the InputLayer SDK.
301
+ */
302
+ declare class InputLayerError extends Error {
303
+ constructor(message: string);
304
+ }
305
+ declare class ConnectionError extends InputLayerError {
306
+ constructor(message: string);
307
+ }
308
+ declare class AuthenticationError extends InputLayerError {
309
+ constructor(message: string);
310
+ }
311
+ declare class SchemaConflictError extends InputLayerError {
312
+ existingSchema?: Record<string, unknown>;
313
+ proposedSchema?: Record<string, unknown>;
314
+ conflicts: string[];
315
+ constructor(message: string, opts?: {
316
+ existingSchema?: Record<string, unknown>;
317
+ proposedSchema?: Record<string, unknown>;
318
+ conflicts?: string[];
319
+ });
320
+ }
321
+ declare class ValidationError extends InputLayerError {
322
+ details: Array<Record<string, unknown>>;
323
+ constructor(message: string, opts?: {
324
+ details?: Array<Record<string, unknown>>;
325
+ });
326
+ }
327
+ declare class QueryTimeoutError extends InputLayerError {
328
+ constructor(message: string);
329
+ }
330
+ declare class PermissionError extends InputLayerError {
331
+ constructor(message: string);
332
+ }
333
+ declare class KnowledgeGraphNotFoundError extends InputLayerError {
334
+ constructor(message: string);
335
+ }
336
+ declare class KnowledgeGraphExistsError extends InputLayerError {
337
+ constructor(message: string);
338
+ }
339
+ declare class CannotDropError extends InputLayerError {
340
+ constructor(message: string);
341
+ }
342
+ declare class RelationNotFoundError extends InputLayerError {
343
+ constructor(message: string);
344
+ }
345
+ declare class RuleNotFoundError extends InputLayerError {
346
+ constructor(message: string);
347
+ }
348
+ declare class IndexNotFoundError extends InputLayerError {
349
+ constructor(message: string);
350
+ }
351
+ declare class InternalError extends InputLayerError {
352
+ constructor(message: string);
353
+ }
354
+
355
+ /**
356
+ * ResultSet - typed, iterable query results.
357
+ */
358
+ type AnyRow = any[];
359
+ interface ResultSetOptions {
360
+ columns: string[];
361
+ rows: AnyRow[];
362
+ rowCount?: number;
363
+ totalCount?: number;
364
+ truncated?: boolean;
365
+ executionTimeMs?: number;
366
+ rowProvenance?: string[];
367
+ hasEphemeral?: boolean;
368
+ ephemeralSources?: string[];
369
+ warnings?: string[];
370
+ }
371
+ /**
372
+ * Container for query results.
373
+ * Supports iteration, indexing, and conversion to various formats.
374
+ */
375
+ declare class ResultSet implements Iterable<Record<string, unknown>> {
376
+ readonly columns: string[];
377
+ readonly rows: AnyRow[];
378
+ readonly rowCount: number;
379
+ readonly totalCount: number;
380
+ readonly truncated: boolean;
381
+ readonly executionTimeMs: number;
382
+ readonly rowProvenance?: string[];
383
+ hasEphemeral: boolean;
384
+ ephemeralSources: string[];
385
+ warnings: string[];
386
+ constructor(opts: ResultSetOptions);
387
+ /** Number of result rows. */
388
+ get length(): number;
389
+ /** True if there are any results. */
390
+ get isEmpty(): boolean;
391
+ /** Get a single row as a keyed object. */
392
+ get(index: number): Record<string, unknown>;
393
+ /** Get the first row or undefined if empty. */
394
+ first(): Record<string, unknown> | undefined;
395
+ /** Return the single value from a 1x1 result. */
396
+ scalar(): unknown;
397
+ /** Convert all rows to a list of keyed objects. */
398
+ toDicts(): Array<Record<string, unknown>>;
399
+ /** Convert all rows to a list of tuples (arrays). */
400
+ toTuples(): AnyRow[];
401
+ /** Iterate over rows as keyed objects. */
402
+ [Symbol.iterator](): Iterator<Record<string, unknown>>;
403
+ private rowToObj;
404
+ }
405
+
406
+ /**
407
+ * WebSocket wire protocol: message serialization and deserialization.
408
+ * Matches the AsyncAPI spec at docs/spec/asyncapi.yaml.
409
+ */
410
+ interface LoginMessage {
411
+ type: 'login';
412
+ username: string;
413
+ password: string;
414
+ }
415
+ interface AuthenticateMessage {
416
+ type: 'authenticate';
417
+ api_key: string;
418
+ }
419
+ interface ExecuteMessage {
420
+ type: 'execute';
421
+ program: string;
422
+ }
423
+ interface PingMessage {
424
+ type: 'ping';
425
+ }
426
+ type ClientMessage = LoginMessage | AuthenticateMessage | ExecuteMessage | PingMessage;
427
+ interface AuthenticatedResponse {
428
+ type: 'authenticated';
429
+ session_id: string;
430
+ knowledge_graph: string;
431
+ version: string;
432
+ role: string;
433
+ }
434
+ interface AuthErrorResponse {
435
+ type: 'auth_error';
436
+ message: string;
437
+ }
438
+ interface ResultResponse {
439
+ type: 'result';
440
+ columns: string[];
441
+ rows: any[][];
442
+ row_count: number;
443
+ total_count: number;
444
+ truncated: boolean;
445
+ execution_time_ms: number;
446
+ row_provenance?: string[];
447
+ metadata?: Record<string, any>;
448
+ switched_kg?: string;
449
+ }
450
+ interface ErrorResponse {
451
+ type: 'error';
452
+ message: string;
453
+ validation_errors?: Array<Record<string, any>>;
454
+ }
455
+ interface ResultStartResponse {
456
+ type: 'result_start';
457
+ columns: string[];
458
+ total_count: number;
459
+ truncated: boolean;
460
+ execution_time_ms: number;
461
+ metadata?: Record<string, any>;
462
+ switched_kg?: string;
463
+ }
464
+ interface ResultChunkResponse {
465
+ type: 'result_chunk';
466
+ rows: any[][];
467
+ chunk_index: number;
468
+ row_provenance?: string[];
469
+ }
470
+ interface ResultEndResponse {
471
+ type: 'result_end';
472
+ row_count: number;
473
+ chunk_count: number;
474
+ }
475
+ interface PongResponse {
476
+ type: 'pong';
477
+ }
478
+ interface NotificationResponse {
479
+ type: 'persistent_update' | 'rule_change' | 'kg_change' | 'schema_change';
480
+ seq: number;
481
+ timestamp_ms: number;
482
+ session_id?: string;
483
+ knowledge_graph?: string;
484
+ relation?: string;
485
+ operation?: string;
486
+ count?: number;
487
+ rule_name?: string;
488
+ entity?: string;
489
+ }
490
+ type ServerMessage = AuthenticatedResponse | AuthErrorResponse | ResultResponse | ErrorResponse | ResultStartResponse | ResultChunkResponse | ResultEndResponse | PongResponse | NotificationResponse;
491
+ declare function serializeMessage(msg: ClientMessage): string;
492
+ declare function deserializeMessage(data: string): ServerMessage;
493
+
494
+ /**
495
+ * Notification dispatcher for push events from the server.
496
+ */
497
+ /** A single notification event from the server. */
498
+ interface NotificationEvent {
499
+ type: string;
500
+ seq: number;
501
+ timestampMs: number;
502
+ sessionId?: string;
503
+ knowledgeGraph?: string;
504
+ relation?: string;
505
+ operation?: string;
506
+ count?: number;
507
+ ruleName?: string;
508
+ entity?: string;
509
+ }
510
+ type NotificationCallback = (event: NotificationEvent) => void | Promise<void>;
511
+ /**
512
+ * Routes notification events to registered callbacks.
513
+ */
514
+ declare class NotificationDispatcher {
515
+ private callbacks;
516
+ private _lastSeq;
517
+ private waiters;
518
+ get lastSeq(): number;
519
+ /**
520
+ * Register a callback for notifications.
521
+ *
522
+ * @param eventType - Filter by event type (e.g. "persistent_update")
523
+ * @param opts - Additional filters
524
+ * @param callback - Function to call when a matching event arrives
525
+ */
526
+ on(eventType: string | undefined, opts: {
527
+ relation?: string;
528
+ knowledgeGraph?: string;
529
+ }, callback: NotificationCallback): void;
530
+ /** Remove a previously registered callback. */
531
+ off(callback: NotificationCallback): void;
532
+ /** Dispatch a notification to matching callbacks. */
533
+ dispatch(event: NotificationEvent): void;
534
+ /** Wait for the next notification event. */
535
+ next(): Promise<NotificationEvent>;
536
+ /**
537
+ * Create an async iterable of notification events.
538
+ *
539
+ * Usage:
540
+ * for await (const event of dispatcher.events()) { ... }
541
+ */
542
+ events(): AsyncIterableIterator<NotificationEvent>;
543
+ }
544
+
545
+ /**
546
+ * WebSocket connection management with authentication and streaming support.
547
+ */
548
+
549
+ interface ConnectionOptions {
550
+ url: string;
551
+ username?: string;
552
+ password?: string;
553
+ apiKey?: string;
554
+ autoReconnect?: boolean;
555
+ reconnectDelay?: number;
556
+ maxReconnectAttempts?: number;
557
+ initialKg?: string;
558
+ lastSeq?: number;
559
+ }
560
+ /**
561
+ * Manages the WebSocket connection to an InputLayer server.
562
+ */
563
+ declare class Connection {
564
+ private readonly url;
565
+ private readonly username?;
566
+ private readonly password?;
567
+ private readonly apiKey?;
568
+ private readonly autoReconnect;
569
+ private readonly reconnectDelay;
570
+ private readonly maxReconnectAttempts;
571
+ private readonly initialKg?;
572
+ private ws;
573
+ private _sessionId?;
574
+ private _serverVersion?;
575
+ private _role?;
576
+ private _currentKg?;
577
+ private _connected;
578
+ private _lastSeq?;
579
+ private readonly _dispatcher;
580
+ private pendingResolve?;
581
+ constructor(opts: ConnectionOptions);
582
+ get connected(): boolean;
583
+ get sessionId(): string | undefined;
584
+ get serverVersion(): string | undefined;
585
+ get role(): string | undefined;
586
+ get currentKg(): string | undefined;
587
+ /** Force-set the current KG (used by KnowledgeGraph after .kg use). */
588
+ setCurrentKg(name: string): void;
589
+ get dispatcher(): NotificationDispatcher;
590
+ get lastSeq(): number;
591
+ connect(): Promise<void>;
592
+ close(): Promise<void>;
593
+ private authenticate;
594
+ /**
595
+ * Send a program/command and wait for the result.
596
+ * Transparently assembles streamed results (result_start -> chunks -> result_end).
597
+ */
598
+ execute(program: string): Promise<ResultResponse>;
599
+ private readResult;
600
+ private assembleStream;
601
+ private isNotification;
602
+ private dispatchNotification;
603
+ private reconnect;
604
+ ping(): Promise<void>;
605
+ private createWebSocket;
606
+ /** Receive exactly one message (used during auth before handler is set up). */
607
+ private receiveOne;
608
+ /** Receive the next message via the pendingResolve mechanism. */
609
+ private receiveMessage;
610
+ }
611
+
612
+ /**
613
+ * Authentication helpers - data types and meta-command compilation for user/key/ACL management.
614
+ */
615
+ interface UserInfo {
616
+ username: string;
617
+ role: string;
618
+ }
619
+ interface ApiKeyInfo {
620
+ label: string;
621
+ createdAt: string;
622
+ }
623
+ interface AclEntry {
624
+ username: string;
625
+ role: string;
626
+ }
627
+
628
+ /**
629
+ * Session - ephemeral facts and rules (no + prefix).
630
+ */
631
+
632
+ /**
633
+ * Manage session-scoped (ephemeral) data.
634
+ *
635
+ * Session inserts and rules omit the + prefix, making them ephemeral
636
+ * (cleared on disconnect or KG switch).
637
+ */
638
+ declare class Session {
639
+ private readonly conn;
640
+ constructor(connection: Connection);
641
+ /** Insert ephemeral session facts (no + prefix). */
642
+ insert(rel: RelationDef, facts: Fact | Fact[]): Promise<void>;
643
+ /** Define session-scoped rules (no + prefix). */
644
+ defineRules(headName: string, headColumns: string[], clauses: RuleClause[]): Promise<void>;
645
+ /** List session rules. */
646
+ listRules(): Promise<string[]>;
647
+ /** Drop a session rule by name, or a specific clause by index. */
648
+ dropRule(name: string, index?: number): Promise<void>;
649
+ /** Clear all session facts and rules. */
650
+ clear(): Promise<void>;
651
+ }
652
+
653
+ /**
654
+ * KnowledgeGraph - the primary workspace for data, queries, and rules.
655
+ */
656
+
657
+ interface RelationInfo {
658
+ name: string;
659
+ rowCount: number;
660
+ }
661
+ interface ColumnInfo {
662
+ name: string;
663
+ type: string;
664
+ }
665
+ interface RelationDescription {
666
+ name: string;
667
+ columns: ColumnInfo[];
668
+ rowCount: number;
669
+ sample: Array<Record<string, unknown>>;
670
+ }
671
+ interface RuleInfo {
672
+ name: string;
673
+ clauseCount: number;
674
+ }
675
+ interface IndexInfo {
676
+ name: string;
677
+ relation: string;
678
+ column: string;
679
+ metric: string;
680
+ rowCount: number;
681
+ }
682
+ interface IndexStats {
683
+ name: string;
684
+ rowCount: number;
685
+ layers: number;
686
+ memoryBytes: number;
687
+ }
688
+ interface InsertResult {
689
+ count: number;
690
+ }
691
+ interface DeleteResult {
692
+ count: number;
693
+ }
694
+ interface ClearResult {
695
+ relationsCleared: number;
696
+ factsCleared: number;
697
+ details: Array<[string, number]>;
698
+ }
699
+ interface ExplainResult {
700
+ iql: string;
701
+ plan: string;
702
+ }
703
+ interface ServerStatus {
704
+ version: string;
705
+ knowledgeGraph: string;
706
+ }
707
+ /**
708
+ * Primary workspace for interacting with a knowledge graph.
709
+ */
710
+ declare class KnowledgeGraph {
711
+ private readonly _name;
712
+ private readonly conn;
713
+ private readonly _session;
714
+ private kgActive;
715
+ constructor(name: string, connection: Connection);
716
+ get name(): string;
717
+ get session(): Session;
718
+ /** Ensure the connection is using this knowledge graph. */
719
+ private ensureKg;
720
+ /** Deploy schema definitions. Idempotent. */
721
+ define(...relations: RelationDef[]): Promise<void>;
722
+ /** List all relations in this KG. */
723
+ relations(): Promise<RelationInfo[]>;
724
+ /** Describe a relation's schema. */
725
+ describe(relation: RelationDef | string): Promise<RelationDescription>;
726
+ /** Drop a relation and all its data. */
727
+ dropRelation(relation: RelationDef | string): Promise<void>;
728
+ /** Insert facts into the knowledge graph. */
729
+ insert(rel: RelationDef, facts: Fact | Fact[]): Promise<InsertResult>;
730
+ /**
731
+ * Delete facts from the knowledge graph.
732
+ *
733
+ * @param rel - The relation definition
734
+ * @param factsOrCondition - Either specific facts to delete, or a BoolExpr condition
735
+ */
736
+ delete(rel: RelationDef, factsOrCondition: Fact | Fact[] | BoolExpr): Promise<DeleteResult>;
737
+ /**
738
+ * Query the knowledge graph.
739
+ *
740
+ * @example
741
+ * // Simple query
742
+ * const result = await kg.query({ select: [Employee] });
743
+ *
744
+ * // Filter
745
+ * const result = await kg.query({
746
+ * select: [Employee.col("name"), Employee.col("salary")],
747
+ * join: [Employee],
748
+ * where: Employee.col("department").eq("eng"),
749
+ * });
750
+ *
751
+ * // Join
752
+ * const result = await kg.query({
753
+ * select: [Employee.col("name"), Department.col("budget")],
754
+ * join: [Employee, Department],
755
+ * on: Employee.col("department").eq(Department.col("name")),
756
+ * });
757
+ */
758
+ query(opts: QueryOptions): Promise<ResultSet>;
759
+ /**
760
+ * Stream query results in batches.
761
+ *
762
+ * Returns an async generator yielding arrays of rows.
763
+ */
764
+ queryStream(opts: QueryOptions & {
765
+ batchSize?: number;
766
+ }): AsyncIterableIterator<Array<Record<string, unknown>>>;
767
+ /**
768
+ * Perform a vector similarity search.
769
+ */
770
+ vectorSearch(opts: {
771
+ relation: RelationDef;
772
+ queryVec: number[];
773
+ column?: string;
774
+ k?: number;
775
+ radius?: number;
776
+ metric?: 'cosine' | 'euclidean' | 'manhattan' | 'dot_product';
777
+ }): Promise<ResultSet>;
778
+ /** Deploy persistent rule definitions. */
779
+ defineRules(headName: string, headColumns: string[], clauses: RuleClause[]): Promise<void>;
780
+ /** List all rules in this KG. */
781
+ listRules(): Promise<RuleInfo[]>;
782
+ /** Get the IQL definition of a rule. */
783
+ ruleDefinition(name: string): Promise<string[]>;
784
+ /** Drop all clauses of a rule. */
785
+ dropRule(name: string): Promise<void>;
786
+ /** Remove a specific clause from a rule (1-based index). */
787
+ dropRuleClause(name: string, index: number): Promise<void>;
788
+ /** Replace a specific rule clause (remove + re-add). */
789
+ editRuleClause(name: string, index: number, headColumns: string[], clause: RuleClause): Promise<void>;
790
+ /** Clear a rule's materialized data. */
791
+ clearRule(name: string): Promise<void>;
792
+ /** Drop all rules whose names start with prefix. */
793
+ dropRulesByPrefix(prefix: string): Promise<void>;
794
+ /** Create an HNSW vector index. */
795
+ createIndex(index: HnswIndex): Promise<void>;
796
+ /** List all indexes. */
797
+ listIndexes(): Promise<IndexInfo[]>;
798
+ /** Get statistics for an index. */
799
+ indexStats(name: string): Promise<IndexStats>;
800
+ /** Drop an index. */
801
+ dropIndex(name: string): Promise<void>;
802
+ /** Rebuild an index. */
803
+ rebuildIndex(name: string): Promise<void>;
804
+ /** Grant per-KG access. */
805
+ grantAccess(username: string, role: string): Promise<void>;
806
+ /** Revoke per-KG access. */
807
+ revokeAccess(username: string): Promise<void>;
808
+ /** List ACL entries. */
809
+ listAcl(): Promise<AclEntry[]>;
810
+ /** Show the query plan without executing. */
811
+ explain(opts: QueryOptions): Promise<ExplainResult>;
812
+ /** Trigger storage compaction. */
813
+ compact(): Promise<void>;
814
+ /** Get server status. */
815
+ status(): Promise<ServerStatus>;
816
+ /** Load data from a file on the server. */
817
+ load(path: string, mode?: string): Promise<void>;
818
+ /** Clear all relations matching a prefix. */
819
+ clearPrefix(prefix: string): Promise<ClearResult>;
820
+ /** Execute raw IQL. */
821
+ execute(iql: string): Promise<ResultSet>;
822
+ }
823
+
824
+ /**
825
+ * InputLayer - top-level async client.
826
+ */
827
+
828
+ interface InputLayerOptions {
829
+ /** WebSocket URL (e.g. "ws://localhost:8080/ws") */
830
+ url: string;
831
+ /** Username for login auth */
832
+ username?: string;
833
+ /** Password for login auth */
834
+ password?: string;
835
+ /** API key for token auth */
836
+ apiKey?: string;
837
+ /** Enable auto-reconnect on connection loss (default: true) */
838
+ autoReconnect?: boolean;
839
+ /** Delay between reconnect attempts in seconds (default: 1.0) */
840
+ reconnectDelay?: number;
841
+ /** Max reconnect attempts before giving up (default: 10) */
842
+ maxReconnectAttempts?: number;
843
+ /** Initial knowledge graph to use (default: "default") */
844
+ initialKg?: string;
845
+ /** Last notification sequence for replay on reconnect */
846
+ lastSeq?: number;
847
+ }
848
+ /**
849
+ * Async client for InputLayer knowledge graph engine.
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * import { InputLayer, relation } from 'inputlayer';
854
+ *
855
+ * const Employee = relation("Employee", {
856
+ * id: "int",
857
+ * name: "string",
858
+ * department: "string",
859
+ * salary: "float",
860
+ * active: "bool",
861
+ * });
862
+ *
863
+ * const il = new InputLayer({ url: "ws://localhost:8080/ws", username: "admin", password: "admin" });
864
+ * await il.connect();
865
+ *
866
+ * const kg = il.knowledgeGraph("default");
867
+ * await kg.define(Employee);
868
+ * await kg.insert(Employee, { id: 1, name: "Alice", department: "eng", salary: 120000, active: true });
869
+ * const result = await kg.query({ select: [Employee] });
870
+ *
871
+ * await il.close();
872
+ * ```
873
+ */
874
+ declare class InputLayer {
875
+ private readonly conn;
876
+ private readonly kgs;
877
+ constructor(opts: InputLayerOptions);
878
+ /** Connect and authenticate. */
879
+ connect(): Promise<void>;
880
+ /** Close the connection. */
881
+ close(): Promise<void>;
882
+ get connected(): boolean;
883
+ get sessionId(): string | undefined;
884
+ get serverVersion(): string | undefined;
885
+ get role(): string | undefined;
886
+ get lastSeq(): number;
887
+ /** Get a KnowledgeGraph handle. Switches the session's active KG. */
888
+ knowledgeGraph(name: string): KnowledgeGraph;
889
+ /** List all knowledge graphs. */
890
+ listKnowledgeGraphs(): Promise<string[]>;
891
+ /** Drop a knowledge graph. */
892
+ dropKnowledgeGraph(name: string): Promise<void>;
893
+ createUser(username: string, password: string, role?: string): Promise<void>;
894
+ dropUser(username: string): Promise<void>;
895
+ setPassword(username: string, newPassword: string): Promise<void>;
896
+ setRole(username: string, role: string): Promise<void>;
897
+ listUsers(): Promise<UserInfo[]>;
898
+ /** Create an API key. Returns the key string. */
899
+ createApiKey(label: string): Promise<string>;
900
+ listApiKeys(): Promise<ApiKeyInfo[]>;
901
+ revokeApiKey(label: string): Promise<void>;
902
+ /**
903
+ * Register a notification callback.
904
+ *
905
+ * @param eventType - Filter by event type (e.g. "persistent_update")
906
+ * @param callback - Function to call when event arrives
907
+ * @param opts - Additional filters
908
+ */
909
+ on(eventType: string, callback: NotificationCallback, opts?: {
910
+ relation?: string;
911
+ knowledgeGraph?: string;
912
+ }): void;
913
+ /** Remove a notification callback. */
914
+ off(callback: NotificationCallback): void;
915
+ /** Async iterator yielding notification events. */
916
+ notifications(): AsyncIterableIterator<NotificationEvent>;
917
+ }
918
+
919
+ /**
920
+ * Naming convention utilities: CamelCase <-> snake_case, column -> IQL variable.
921
+ */
922
+ /** Convert CamelCase class name to snake_case relation name. */
923
+ declare function camelToSnake(name: string): string;
924
+ /** Convert snake_case to CamelCase. */
925
+ declare function snakeToCamel(name: string): string;
926
+ /** Convert a snake_case column name to a IQL variable (Capitalized). */
927
+ declare function columnToVariable(columnName: string): string;
928
+
929
+ export { type AclEntry, AggExpr, type ApiKeyInfo, type AuthErrorResponse, type AuthenticateMessage, type AuthenticatedResponse, AuthenticationError, BoolExpr, CannotDropError, type ClearResult, type ClientMessage, Column, type ColumnInfo, ColumnProxy, type ColumnTypes, Connection, ConnectionError, type ConnectionOptions, type DeleteResult, type ErrorResponse, type ExecuteMessage, type ExplainResult, Expr, Fact, HnswIndex, type HnswIndexOptions, IQLType, type IndexInfo, IndexNotFoundError, type IndexStats, InputLayer, InputLayerError, type InputLayerOptions, type InsertResult, InternalError, KnowledgeGraph, KnowledgeGraphExistsError, KnowledgeGraphNotFoundError, type LoginMessage, type NotificationCallback, NotificationDispatcher, type NotificationEvent, type NotificationResponse, PermissionError, type PingMessage, type PongResponse, type QueryOptions, QueryTimeoutError, RelationDef, type RelationDescription, type RelationInfo, RelationNotFoundError, RelationProxy, RelationRef, type ResultChunkResponse, type ResultEndResponse, type ResultResponse, ResultSet, type ResultSetOptions, type ResultStartResponse, type RuleClause, type RuleInfo, RuleNotFoundError, SchemaConflictError, type ServerMessage, type ServerStatus, Session, type UserInfo, ValidationError, avg, camelToSnake, columnToVariable, compileBoolExpr, compileBulkInsert, compileConditionalDelete, compileDelete, compileExpr, compileInsert, compileQuery, compileRule, compileSchema, compileValue, count, countDistinct, deserializeMessage, from, getColumnTypes, getColumns, max, min, relation, resolveRelationName, serializeMessage, snakeToCamel, sum, topK, topKThreshold, withinRadius };