@type-bridge/node 1.5.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.
@@ -0,0 +1,106 @@
1
+ export interface Cardinality {
2
+ min: number;
3
+ max: number | null;
4
+ }
5
+ export interface OwnedAttribute {
6
+ name: string;
7
+ is_key: boolean;
8
+ is_unique: boolean;
9
+ is_cascade: boolean;
10
+ subkey_group: string | null;
11
+ cardinality: Cardinality | null;
12
+ ordered: boolean;
13
+ distinct: boolean;
14
+ }
15
+ export interface PlayedRole {
16
+ role_ref: string;
17
+ cardinality: Cardinality | null;
18
+ }
19
+ export interface RoleSpec {
20
+ name: string;
21
+ overrides: string | null;
22
+ cardinality: Cardinality | null;
23
+ distinct: boolean;
24
+ ordered: boolean;
25
+ is_abstract: boolean;
26
+ }
27
+ export interface EntityType {
28
+ name: string;
29
+ parent: string | null;
30
+ is_abstract: boolean;
31
+ owns: OwnedAttribute[];
32
+ owns_order: string[];
33
+ plays: PlayedRole[];
34
+ }
35
+ export interface RelationType {
36
+ name: string;
37
+ parent: string | null;
38
+ is_abstract: boolean;
39
+ roles: RoleSpec[];
40
+ owns: OwnedAttribute[];
41
+ owns_order: string[];
42
+ plays: PlayedRole[];
43
+ }
44
+ export interface AttributeType {
45
+ name: string;
46
+ value_type: string;
47
+ parent: string | null;
48
+ is_abstract: boolean;
49
+ is_independent: boolean;
50
+ regex: string | null;
51
+ allowed_values: string[] | null;
52
+ range_min: string | null;
53
+ range_max: string | null;
54
+ }
55
+ export interface Parameter {
56
+ name: string;
57
+ type: string;
58
+ }
59
+ export interface ReturnTypeItem {
60
+ name: string;
61
+ optional: boolean;
62
+ }
63
+ export interface ReturnType {
64
+ is_stream: boolean;
65
+ types: ReturnTypeItem[];
66
+ }
67
+ export interface FunctionType {
68
+ name: string;
69
+ parameters: Parameter[];
70
+ return_type: ReturnType;
71
+ }
72
+ export interface StructField {
73
+ name: string;
74
+ value_type: string;
75
+ optional: boolean;
76
+ }
77
+ export interface StructType {
78
+ name: string;
79
+ fields: StructField[];
80
+ }
81
+ /** The complete parsed and inheritance-resolved TypeDB schema. */
82
+ export interface TypeSchema {
83
+ entities: Record<string, EntityType>;
84
+ relations: Record<string, RelationType>;
85
+ attributes: Record<string, AttributeType>;
86
+ functions: Record<string, FunctionType>;
87
+ structs: Record<string, StructType>;
88
+ }
89
+ /**
90
+ * The slice of the native module the parser needs. The full native module
91
+ * (the `loadNative()` result from the package root) satisfies this; callers
92
+ * inject it, matching the runtime convention used everywhere else in the
93
+ * surface (e.g. `Model.manager(db)`). Injection keeps this module free of any
94
+ * native-resolution path, so it survives the package layout migration intact.
95
+ */
96
+ export interface SchemaParserNative {
97
+ parseSchemaJson(input: string): string;
98
+ }
99
+ /**
100
+ * Parse a TQL `define` block and return the fully-resolved {@link TypeSchema}.
101
+ *
102
+ * Marshalling-only: parsing and inheritance resolution happen in the Rust core
103
+ * behind `parseSchemaJson`; this deserializes the JSON result. Throws on parse
104
+ * or serialization errors (propagated from the Rust core as native errors).
105
+ */
106
+ export declare function parseSchema(tql: string, native: SchemaParserNative): TypeSchema;
package/dist/parser.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ // ---------------------------------------------------------------------------
3
+ // TypeSchema interface — mirrors the Rust `TypeSchema` serde JSON shape.
4
+ //
5
+ // Field names match the Rust struct field names exactly (serde default).
6
+ // Inheritance is already resolved by the Rust core before serialization;
7
+ // the TypeScript side only deserializes.
8
+ // ---------------------------------------------------------------------------
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.parseSchema = parseSchema;
11
+ /**
12
+ * Parse a TQL `define` block and return the fully-resolved {@link TypeSchema}.
13
+ *
14
+ * Marshalling-only: parsing and inheritance resolution happen in the Rust core
15
+ * behind `parseSchemaJson`; this deserializes the JSON result. Throws on parse
16
+ * or serialization errors (propagated from the Rust core as native errors).
17
+ */
18
+ function parseSchema(tql, native) {
19
+ return JSON.parse(native.parseSchemaJson(tql));
20
+ }
@@ -0,0 +1,109 @@
1
+ import type { AggregateInput, AttributeValue, DynamicComparisonOp, DynamicExpr, DynamicQuerySpec, DynamicSort, DynamicSortDir } from "./index.js";
2
+ import type { AttributeClass } from "./model.js";
3
+ /** Raised when a Rust aggregate/group-by result does not match the documented shape. */
4
+ export declare class TypedQueryError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /**
8
+ * A typed query-filter expression. Subclasses serialize to the wire `DynamicExpr`
9
+ * tree that the Rust core lowers into a database query; the boolean combinators
10
+ * (`and_`, `or_`, `not_`) build nested expressions so a whole filter tree is one
11
+ * value.
12
+ */
13
+ export declare abstract class QueryExpr {
14
+ /** Serialize to the Rust `DynamicExpr` wire shape. */
15
+ abstract toExpr(): DynamicExpr;
16
+ and_(...others: QueryExpr[]): QueryExpr;
17
+ or_(...others: QueryExpr[]): QueryExpr;
18
+ not_(): QueryExpr;
19
+ }
20
+ /**
21
+ * Attribute comparison or string-operator leaf. String operators
22
+ * (`starts_with`/`ends_with`) carry the raw literal — Rust owns anchoring and
23
+ * escaping (Plan 09 Gap B).
24
+ */
25
+ export declare class ComparisonExpr extends QueryExpr {
26
+ private readonly attrName;
27
+ private readonly operator;
28
+ private readonly value;
29
+ constructor(attrName: string, operator: DynamicComparisonOp, value: AttributeValue);
30
+ toExpr(): DynamicExpr;
31
+ }
32
+ /** Conjunction/disjunction of child expressions. */
33
+ export declare class BooleanExpr extends QueryExpr {
34
+ private readonly op;
35
+ private readonly children;
36
+ constructor(op: "and" | "or", children: QueryExpr[]);
37
+ toExpr(): DynamicExpr;
38
+ }
39
+ /** Negation of a child expression. */
40
+ export declare class NotExpr extends QueryExpr {
41
+ private readonly child;
42
+ constructor(child: QueryExpr);
43
+ toExpr(): DynamicExpr;
44
+ }
45
+ /** A typed sort key produced by `Attr.asc()` / `Attr.desc()`. */
46
+ export declare class SortExpr {
47
+ private readonly attrName;
48
+ private readonly direction;
49
+ constructor(attrName: string, direction: DynamicSortDir);
50
+ toSort(): DynamicSort;
51
+ }
52
+ /**
53
+ * A typed aggregate produced by `Attr.avg()` / `agg.count()` etc. `input.result_key`
54
+ * is the wire reduce variable (must be a valid identifier — attribute names with
55
+ * `-` are sanitized to `_`); `resultKey` is the user-facing key in the normalized
56
+ * result, which preserves the original attribute name. The wire `function` is the
57
+ * TypeDB reduce name (`mean` for `avg`).
58
+ */
59
+ export declare class AggregateSpec {
60
+ readonly input: AggregateInput;
61
+ readonly resultKey: string;
62
+ constructor(input: AggregateInput, resultKey: string);
63
+ }
64
+ /** Field-independent aggregate helpers. */
65
+ export declare const agg: {
66
+ /** Count matching rows. Normalizes to the `count` result key. */
67
+ readonly count: () => AggregateSpec;
68
+ };
69
+ type DynamicManagerLike<Row> = {
70
+ query(spec: DynamicQuerySpec): Row[];
71
+ queryCount(spec: DynamicQuerySpec): bigint;
72
+ queryAggregate(spec: DynamicQuerySpec, aggregates: AggregateInput[]): unknown[];
73
+ queryGroupByAggregate(spec: DynamicQuerySpec, groupFields: string[], aggregates: AggregateInput[]): unknown[];
74
+ };
75
+ /**
76
+ * Builder for a typed query over one entity or relation manager. Filters, sort,
77
+ * and pagination accumulate into a `DynamicQuerySpec`; terminal methods
78
+ * (`all`/`first`/`count`/`exists`/`aggregate`/`groupBy`) execute through the Rust
79
+ * dynamic query seam. Reads hydrate through the manager's `hydrate` callback,
80
+ * preserving Plan 08 typed instances and `_iid`.
81
+ */
82
+ export declare class TypedQuery<T, Row> {
83
+ #private;
84
+ constructor(manager: DynamicManagerLike<Row>, hydrate: (rows: Row[]) => T[]);
85
+ /** Add filter expressions. Multiple calls (and multiple args) are ANDed in Rust. */
86
+ filter(...exprs: QueryExpr[]): this;
87
+ orderBy(...sorts: SortExpr[]): this;
88
+ limit(limit: number): this;
89
+ offset(offset: number): this;
90
+ all(): T[];
91
+ execute(): T[];
92
+ first(): T | null;
93
+ count(): bigint;
94
+ exists(): boolean;
95
+ /** Reduce matching rows to one normalized result object keyed by aggregate result keys. */
96
+ aggregate(...aggregates: AggregateSpec[]): Record<string, unknown>;
97
+ groupBy(...attrs: AttributeClass[]): TypedGroupByQuery<Row>;
98
+ }
99
+ /**
100
+ * Grouped-aggregate query produced by `TypedQuery.groupBy(...)`. `aggregate(...)`
101
+ * delegates to the Rust group-by seam and normalizes each group row into an
102
+ * object keyed by group-attribute names plus aggregate result keys.
103
+ */
104
+ export declare class TypedGroupByQuery<Row> {
105
+ #private;
106
+ constructor(manager: DynamicManagerLike<Row>, exprs: DynamicExpr[], groupAttrs: AttributeClass[]);
107
+ aggregate(...aggregates: AggregateSpec[]): Record<string, unknown>[];
108
+ }
109
+ export {};
package/dist/query.js ADDED
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TypedGroupByQuery = exports.TypedQuery = exports.agg = exports.AggregateSpec = exports.SortExpr = exports.NotExpr = exports.BooleanExpr = exports.ComparisonExpr = exports.QueryExpr = exports.TypedQueryError = void 0;
4
+ /** Raised when a Rust aggregate/group-by result does not match the documented shape. */
5
+ class TypedQueryError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "TypedQueryError";
9
+ }
10
+ }
11
+ exports.TypedQueryError = TypedQueryError;
12
+ /**
13
+ * A typed query-filter expression. Subclasses serialize to the wire `DynamicExpr`
14
+ * tree that the Rust core lowers into a database query; the boolean combinators
15
+ * (`and_`, `or_`, `not_`) build nested expressions so a whole filter tree is one
16
+ * value.
17
+ */
18
+ class QueryExpr {
19
+ and_(...others) {
20
+ return new BooleanExpr("and", [this, ...others]);
21
+ }
22
+ or_(...others) {
23
+ return new BooleanExpr("or", [this, ...others]);
24
+ }
25
+ not_() {
26
+ return new NotExpr(this);
27
+ }
28
+ }
29
+ exports.QueryExpr = QueryExpr;
30
+ /**
31
+ * Attribute comparison or string-operator leaf. String operators
32
+ * (`starts_with`/`ends_with`) carry the raw literal — Rust owns anchoring and
33
+ * escaping (Plan 09 Gap B).
34
+ */
35
+ class ComparisonExpr extends QueryExpr {
36
+ attrName;
37
+ operator;
38
+ value;
39
+ constructor(attrName, operator, value) {
40
+ super();
41
+ this.attrName = attrName;
42
+ this.operator = operator;
43
+ this.value = value;
44
+ }
45
+ toExpr() {
46
+ return { kind: "compare", attr_name: this.attrName, operator: this.operator, value: this.value };
47
+ }
48
+ }
49
+ exports.ComparisonExpr = ComparisonExpr;
50
+ /** Conjunction/disjunction of child expressions. */
51
+ class BooleanExpr extends QueryExpr {
52
+ op;
53
+ children;
54
+ constructor(op, children) {
55
+ super();
56
+ this.op = op;
57
+ this.children = children;
58
+ }
59
+ toExpr() {
60
+ const exprs = this.children.map((child) => child.toExpr());
61
+ return this.op === "and" ? { kind: "and", exprs } : { kind: "or", exprs };
62
+ }
63
+ }
64
+ exports.BooleanExpr = BooleanExpr;
65
+ /** Negation of a child expression. */
66
+ class NotExpr extends QueryExpr {
67
+ child;
68
+ constructor(child) {
69
+ super();
70
+ this.child = child;
71
+ }
72
+ toExpr() {
73
+ return { kind: "not", expr: this.child.toExpr() };
74
+ }
75
+ }
76
+ exports.NotExpr = NotExpr;
77
+ /** A typed sort key produced by `Attr.asc()` / `Attr.desc()`. */
78
+ class SortExpr {
79
+ attrName;
80
+ direction;
81
+ constructor(attrName, direction) {
82
+ this.attrName = attrName;
83
+ this.direction = direction;
84
+ }
85
+ toSort() {
86
+ return { kind: "attribute", attr_name: this.attrName, direction: this.direction };
87
+ }
88
+ }
89
+ exports.SortExpr = SortExpr;
90
+ /**
91
+ * A typed aggregate produced by `Attr.avg()` / `agg.count()` etc. `input.result_key`
92
+ * is the wire reduce variable (must be a valid identifier — attribute names with
93
+ * `-` are sanitized to `_`); `resultKey` is the user-facing key in the normalized
94
+ * result, which preserves the original attribute name. The wire `function` is the
95
+ * TypeDB reduce name (`mean` for `avg`).
96
+ */
97
+ class AggregateSpec {
98
+ input;
99
+ resultKey;
100
+ constructor(input, resultKey) {
101
+ this.input = input;
102
+ this.resultKey = resultKey;
103
+ }
104
+ }
105
+ exports.AggregateSpec = AggregateSpec;
106
+ /** Field-independent aggregate helpers. */
107
+ exports.agg = {
108
+ /** Count matching rows. Normalizes to the `count` result key. */
109
+ count() {
110
+ return new AggregateSpec({ result_key: "count", function: "count", attr_name: null }, "count");
111
+ },
112
+ };
113
+ /**
114
+ * Builder for a typed query over one entity or relation manager. Filters, sort,
115
+ * and pagination accumulate into a `DynamicQuerySpec`; terminal methods
116
+ * (`all`/`first`/`count`/`exists`/`aggregate`/`groupBy`) execute through the Rust
117
+ * dynamic query seam. Reads hydrate through the manager's `hydrate` callback,
118
+ * preserving Plan 08 typed instances and `_iid`.
119
+ */
120
+ class TypedQuery {
121
+ #manager;
122
+ #hydrate;
123
+ #exprs = [];
124
+ #sorts = [];
125
+ #limit = null;
126
+ #offset = null;
127
+ constructor(manager, hydrate) {
128
+ this.#manager = manager;
129
+ this.#hydrate = hydrate;
130
+ }
131
+ /** Add filter expressions. Multiple calls (and multiple args) are ANDed in Rust. */
132
+ filter(...exprs) {
133
+ for (const expr of exprs) {
134
+ this.#exprs.push(expr.toExpr());
135
+ }
136
+ return this;
137
+ }
138
+ orderBy(...sorts) {
139
+ for (const sort of sorts) {
140
+ this.#sorts.push(sort.toSort());
141
+ }
142
+ return this;
143
+ }
144
+ limit(limit) {
145
+ this.#limit = limit;
146
+ return this;
147
+ }
148
+ offset(offset) {
149
+ this.#offset = offset;
150
+ return this;
151
+ }
152
+ all() {
153
+ return this.#hydrate(this.#manager.query(this.#spec()));
154
+ }
155
+ execute() {
156
+ return this.all();
157
+ }
158
+ first() {
159
+ const rows = this.#manager.query({ ...this.#spec(), limit: 1 });
160
+ return this.#hydrate(rows)[0] ?? null;
161
+ }
162
+ count() {
163
+ return this.#manager.queryCount({ expr: [...this.#exprs] });
164
+ }
165
+ exists() {
166
+ return this.count() > 0n;
167
+ }
168
+ /** Reduce matching rows to one normalized result object keyed by aggregate result keys. */
169
+ aggregate(...aggregates) {
170
+ const rows = this.#manager.queryAggregate({ expr: [...this.#exprs] }, aggregates.map((a) => a.input));
171
+ if (rows.length !== 1) {
172
+ throw new TypedQueryError(`Expected exactly one aggregate row, got ${rows.length}`);
173
+ }
174
+ return normalizeAggregateRow(rows[0], aggregates);
175
+ }
176
+ groupBy(...attrs) {
177
+ return new TypedGroupByQuery(this.#manager, [...this.#exprs], attrs);
178
+ }
179
+ #spec() {
180
+ return {
181
+ expr: [...this.#exprs],
182
+ sort: [...this.#sorts],
183
+ limit: this.#limit,
184
+ offset: this.#offset,
185
+ };
186
+ }
187
+ }
188
+ exports.TypedQuery = TypedQuery;
189
+ /**
190
+ * Grouped-aggregate query produced by `TypedQuery.groupBy(...)`. `aggregate(...)`
191
+ * delegates to the Rust group-by seam and normalizes each group row into an
192
+ * object keyed by group-attribute names plus aggregate result keys.
193
+ */
194
+ class TypedGroupByQuery {
195
+ #manager;
196
+ #exprs;
197
+ #groupAttrs;
198
+ constructor(manager, exprs, groupAttrs) {
199
+ this.#manager = manager;
200
+ this.#exprs = exprs;
201
+ this.#groupAttrs = groupAttrs;
202
+ }
203
+ aggregate(...aggregates) {
204
+ const groupNames = this.#groupAttrs.map((attr) => attr.attrName);
205
+ const rows = this.#manager.queryGroupByAggregate({ expr: [...this.#exprs] }, groupNames, aggregates.map((a) => a.input));
206
+ return rows.map((row) => normalizeGroupRow(row, groupNames, aggregates));
207
+ }
208
+ }
209
+ exports.TypedGroupByQuery = TypedGroupByQuery;
210
+ function normalizeAggregateRow(row, aggregates) {
211
+ const out = {};
212
+ for (const aggregate of aggregates) {
213
+ out[aggregate.resultKey] = unwrapAggregateValue(row, aggregate.input.result_key, aggregate.resultKey);
214
+ }
215
+ return out;
216
+ }
217
+ function normalizeGroupRow(row, groupNames, aggregates) {
218
+ const out = {};
219
+ groupNames.forEach((name, index) => {
220
+ out[name] = unwrapAggregateValue(row, `group${index}`, name);
221
+ });
222
+ for (const aggregate of aggregates) {
223
+ out[aggregate.resultKey] = unwrapAggregateValue(row, aggregate.input.result_key, aggregate.resultKey);
224
+ }
225
+ return out;
226
+ }
227
+ // Rust returns reduce rows as TypeDB concept documents: keys are the reduce
228
+ // variables (`count`, `group0`, ...) and each value is a concept document whose
229
+ // `value` field holds the scalar. Unwrap both layers, failing loudly on any
230
+ // other shape.
231
+ function unwrapAggregateValue(row, wireKey, label) {
232
+ if (!(wireKey in row)) {
233
+ throw new TypedQueryError(`Aggregate result missing key "${label}"`);
234
+ }
235
+ const entry = row[wireKey];
236
+ if (typeof entry !== "object" || entry === null || !("value" in entry)) {
237
+ throw new TypedQueryError(`Aggregate result "${label}" is not a { value } document`);
238
+ }
239
+ return entry.value;
240
+ }
Binary file
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@type-bridge/node",
3
+ "version": "1.5.0",
4
+ "description": "Node.js NAPI facade for the type-bridge Rust ORM runtime",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "*.node",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "build": "npm run build:native && npm run build:types",
22
+ "prepublishOnly": "npm run build",
23
+ "build:native": "node scripts/build-native.js",
24
+ "build:types": "tsc -p tsconfig.json",
25
+ "build:typed-integration": "tsc -p tsconfig.typed-integration.json",
26
+ "build:parity-reader": "tsc -p tsconfig.parity.json",
27
+ "build:generator-parity": "tsc -p tsconfig.generator-parity.json",
28
+ "scope:probe": "node tests/scope-probe.cjs",
29
+ "dts:parity": "node tests/dts-parity.cjs",
30
+ "dts:baseline": "node tests/dts-parity.cjs --update",
31
+ "test:dts": "node --test tests/dts-parity.test.cjs",
32
+ "smoke:package": "node tests/package-smoke.cjs",
33
+ "test:unit": "tsc -p tsconfig.unit.json && node --test ../../../tmp/node-unit/tests/unit/*.test.js",
34
+ "typecheck": "tsc --noEmit",
35
+ "typecheck:integration": "tsc -p tsconfig.integration.json",
36
+ "test:typed-integration": "npm run build:typed-integration && node --test ../../../tmp/node-typed-integration/tests/typed-integration/*.test.js ../../../tmp/node-typed-integration/tests/integration/typed/*.test.js",
37
+ "test:integration": "node scripts/run-integration.js"
38
+ },
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "napi": {
43
+ "name": "type_bridge_node",
44
+ "triples": {
45
+ "defaults": true
46
+ }
47
+ },
48
+ "devDependencies": {
49
+ "@napi-rs/cli": "^2.18.4",
50
+ "@types/node": "^25.9.1",
51
+ "typescript": "^5.5.0"
52
+ }
53
+ }