@type-bridge/node 1.5.1 → 1.5.2

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/README.md CHANGED
@@ -60,7 +60,11 @@ const person = registry.registerEntity({
60
60
  const attrs = { name: string("Alice"), age: long(42n) };
61
61
  new Marshalling().entityAttributes(person, attrs);
62
62
 
63
- const db = RustDatabase.connect("127.0.0.1:1729", "example");
63
+ const db = RustDatabase.connect("127.0.0.1:1729", "example", {
64
+ httpPort: 8000,
65
+ // Optional: skip HTTP probing when only gRPC is reachable.
66
+ serverVersion: "3.11.5",
67
+ });
64
68
  const manager = db.entityManager(person);
65
69
  manager.insert(attrs);
66
70
  ```
@@ -1,44 +1,60 @@
1
1
  /**
2
- * TypeScript model generator — the `generate_models()` twin.
2
+ * TypeScript model generator facade.
3
3
  *
4
- * Mirrors `type_bridge/generator/__init__.py` → `generate_models()`.
5
- * Consumes a parsed `TypeSchema` (via `parseSchema`) and writes the typed
6
- * `.ts` surface to a caller-supplied output directory.
7
- *
8
- * The native module is INJECTED (not self-resolved) — callers load the native
9
- * module via the package root's `loadNative()` and pass the `SchemaParserNative`
10
- * slice in `options.native`. This keeps the generator free of any native-resolution
11
- * path, so it survives the package layout change.
12
- *
13
- * Generated files import from `@type-bridge/node` (package entrypoint), never
14
- * from a hardcoded relative path, so they are valid across packaging layout changes.
15
- *
16
- * Build-time code generation; no runtime ORM logic.
4
+ * Rendering is owned by the Rust bindgen engine. This module only injects the
5
+ * native module, requests a target package, and writes returned files.
17
6
  */
18
- import { type SchemaParserNative } from "../parser.js";
19
7
  import type { NamingOptions } from "./naming.js";
8
+ /** Output targets supported by the Rust bindgen engine. */
9
+ export type BindgenTarget = "python" | "typescript" | "rust";
10
+ /** One generated source file returned by the native bindgen engine. */
11
+ export interface GeneratedFile {
12
+ /** Relative output path. */
13
+ path: string;
14
+ /** Complete source text. */
15
+ contents: string;
16
+ }
17
+ /** Generated package payload returned by the native bindgen engine. */
18
+ export interface GeneratedPackage {
19
+ /** Target language rendered by Rust. */
20
+ target: BindgenTarget;
21
+ /** Files to write. */
22
+ files: GeneratedFile[];
23
+ }
24
+ /** Native module slice required by the generator facade. */
25
+ export interface BindgenNative {
26
+ /** Render model files as a JSON {@link GeneratedPackage}. */
27
+ renderModelsJson(input: string, target: string, optionsJson?: string | null): string;
28
+ }
29
+ /** Shared Rust bindgen render options exposed through the TypeScript facade. */
30
+ export interface BindgenRenderOptions extends NamingOptions {
31
+ /** Schema version rendered into generated Python package metadata. */
32
+ schemaVersion?: string;
33
+ /** Bundled schema filename for generated Python `schema_text()`, or `null` to omit it. */
34
+ schemaFilename?: string | null;
35
+ /** Source schema text used by generated Python registry metadata. */
36
+ schemaText?: string | null;
37
+ }
20
38
  /** Options for `generateModels`. */
21
- export interface GenerateModelsOptions extends NamingOptions {
39
+ export interface GenerateModelsOptions extends BindgenRenderOptions {
22
40
  /**
23
- * The native module slice providing `parseSchemaJson`. Callers obtain this
24
- * from the package root's `loadNative()` return value. Required — the
25
- * generator does not self-load the native module.
41
+ * The native module slice providing `renderModelsJson`. Callers obtain this
42
+ * from the package root's `loadNative()` return value.
26
43
  */
27
- native: SchemaParserNative;
44
+ native: BindgenNative;
45
+ }
46
+ /** Options for cross-target model generation. */
47
+ export interface GenerateTargetModelsOptions extends GenerateModelsOptions {
48
+ /** Target language to render. */
49
+ target: BindgenTarget;
28
50
  }
29
51
  /**
30
52
  * Generate the typed TypeScript model surface from a TQL `define` block.
31
53
  *
32
- * Mirrors Python `generate_models(tql, output_dir, implicit_key_attributes=...)`.
33
- *
34
- * Writes `attributes.ts`, `entities.ts`, `relations.ts`, and `index.ts`
35
- * (package barrel) to `outputDir`.
36
- *
37
- * @param tql - TQL schema string (a `define` block).
38
- * @param outputDir - Directory to write the generated `.ts` files into.
39
- * Created if absent. Passed by the caller; the generator
40
- * does not enforce a specific location.
41
- * @param options - `native` (required) + optional `implicitKeyAttributes`.
54
+ * Historical entrypoint: this always targets TypeScript. Use
55
+ * `generateModelsForTarget` for cross-target generation.
42
56
  */
43
57
  export declare function generateModels(tql: string, outputDir: string, options: GenerateModelsOptions): void;
58
+ /** Generate model files for any Rust-bindgen target. */
59
+ export declare function generateModelsForTarget(tql: string, outputDir: string, options: GenerateTargetModelsOptions): void;
44
60
  export { toClassName, toFieldName, type NamingOptions } from "./naming.js";
@@ -1,20 +1,9 @@
1
1
  "use strict";
2
2
  /**
3
- * TypeScript model generator — the `generate_models()` twin.
3
+ * TypeScript model generator facade.
4
4
  *
5
- * Mirrors `type_bridge/generator/__init__.py` → `generate_models()`.
6
- * Consumes a parsed `TypeSchema` (via `parseSchema`) and writes the typed
7
- * `.ts` surface to a caller-supplied output directory.
8
- *
9
- * The native module is INJECTED (not self-resolved) — callers load the native
10
- * module via the package root's `loadNative()` and pass the `SchemaParserNative`
11
- * slice in `options.native`. This keeps the generator free of any native-resolution
12
- * path, so it survives the package layout change.
13
- *
14
- * Generated files import from `@type-bridge/node` (package entrypoint), never
15
- * from a hardcoded relative path, so they are valid across packaging layout changes.
16
- *
17
- * Build-time code generation; no runtime ORM logic.
5
+ * Rendering is owned by the Rust bindgen engine. This module only injects the
6
+ * native module, requests a target package, and writes returned files.
18
7
  */
19
8
  var __importDefault = (this && this.__importDefault) || function (mod) {
20
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -22,43 +11,46 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
11
  Object.defineProperty(exports, "__esModule", { value: true });
23
12
  exports.toFieldName = exports.toClassName = void 0;
24
13
  exports.generateModels = generateModels;
14
+ exports.generateModelsForTarget = generateModelsForTarget;
25
15
  const node_fs_1 = __importDefault(require("node:fs"));
26
16
  const node_path_1 = __importDefault(require("node:path"));
27
- const parser_js_1 = require("../parser.js");
28
- const renderAttributes_js_1 = require("./renderAttributes.js");
29
- const renderEntities_js_1 = require("./renderEntities.js");
30
- const renderRelations_js_1 = require("./renderRelations.js");
31
- const renderPackage_js_1 = require("./renderPackage.js");
17
+ function requestGeneratedPackage(tql, options, target) {
18
+ const payload = {
19
+ implicit_key_attributes: options.implicitKeyAttributes ?? [],
20
+ };
21
+ if (options.schemaVersion !== undefined) {
22
+ payload.schema_version = options.schemaVersion;
23
+ }
24
+ if (options.schemaFilename !== undefined) {
25
+ payload.schema_filename = options.schemaFilename;
26
+ }
27
+ if (options.schemaText !== undefined) {
28
+ payload.schema_text = options.schemaText;
29
+ }
30
+ return JSON.parse(options.native.renderModelsJson(tql, target, JSON.stringify(payload)));
31
+ }
32
+ function writePackage(outputDir, generated) {
33
+ node_fs_1.default.mkdirSync(outputDir, { recursive: true });
34
+ for (const file of generated.files) {
35
+ const filePath = node_path_1.default.join(outputDir, file.path);
36
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(filePath), { recursive: true });
37
+ node_fs_1.default.writeFileSync(filePath, file.contents, "utf-8");
38
+ }
39
+ }
32
40
  /**
33
41
  * Generate the typed TypeScript model surface from a TQL `define` block.
34
42
  *
35
- * Mirrors Python `generate_models(tql, output_dir, implicit_key_attributes=...)`.
36
- *
37
- * Writes `attributes.ts`, `entities.ts`, `relations.ts`, and `index.ts`
38
- * (package barrel) to `outputDir`.
39
- *
40
- * @param tql - TQL schema string (a `define` block).
41
- * @param outputDir - Directory to write the generated `.ts` files into.
42
- * Created if absent. Passed by the caller; the generator
43
- * does not enforce a specific location.
44
- * @param options - `native` (required) + optional `implicitKeyAttributes`.
43
+ * Historical entrypoint: this always targets TypeScript. Use
44
+ * `generateModelsForTarget` for cross-target generation.
45
45
  */
46
46
  function generateModels(tql, outputDir, options) {
47
- // Parse: TQL string → fully-resolved TypeSchema (Rust-backed, via NAPI)
48
- const schema = (0, parser_js_1.parseSchema)(tql, options.native);
49
- // Render
50
- const attrSource = (0, renderAttributes_js_1.renderAttributes)(schema);
51
- const entitySource = (0, renderEntities_js_1.renderEntities)(schema, options);
52
- const relationSource = (0, renderRelations_js_1.renderRelations)(schema, options);
53
- const packageSource = (0, renderPackage_js_1.renderPackage)(schema);
54
- // Write
55
- node_fs_1.default.mkdirSync(outputDir, { recursive: true });
56
- node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "attributes.ts"), attrSource, "utf-8");
57
- node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "entities.ts"), entitySource, "utf-8");
58
- node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "relations.ts"), relationSource, "utf-8");
59
- node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "index.ts"), packageSource, "utf-8");
47
+ writePackage(outputDir, requestGeneratedPackage(tql, options, "typescript"));
48
+ }
49
+ /** Generate model files for any Rust-bindgen target. */
50
+ function generateModelsForTarget(tql, outputDir, options) {
51
+ writePackage(outputDir, requestGeneratedPackage(tql, options, options.target));
60
52
  }
61
- // Re-export the naming utilities and options type for callers that need them
53
+ // Re-export the naming utilities and options type for callers that need them.
62
54
  var naming_js_1 = require("./naming.js");
63
55
  Object.defineProperty(exports, "toClassName", { enumerable: true, get: function () { return naming_js_1.toClassName; } });
64
56
  Object.defineProperty(exports, "toFieldName", { enumerable: true, get: function () { return naming_js_1.toFieldName; } });
package/dist/index.d.ts CHANGED
@@ -353,11 +353,12 @@ export interface NativeDynamicRelationManager {
353
353
  queryGroupByAggregateJson(specJson: string, groupFieldsJson: string, aggregatesJson: string): string;
354
354
  }
355
355
  export interface NativeRuntime {
356
- ensureRustDatabase(address: string, database: string, username?: string | null, password?: string | null, httpPort?: number | null): void;
357
- connectRustDatabase(address: string, database: string, username?: string | null, password?: string | null, httpPort?: number | null): NativeRustDatabase;
356
+ ensureRustDatabase(address: string, database: string, username?: string | null, password?: string | null, httpPort?: number | null, serverVersion?: string | null): void;
357
+ connectRustDatabase(address: string, database: string, username?: string | null, password?: string | null, httpPort?: number | null, serverVersion?: string | null): NativeRustDatabase;
358
358
  }
359
359
  interface NativeSchemaParser {
360
360
  parseSchemaJson(input: string): string;
361
+ renderModelsJson(input: string, target: string, optionsJson?: string | null): string;
361
362
  }
362
363
  export interface NativeModule extends NativeRuntime, NativeMarshalling, NativeSchemaParser {
363
364
  NodeDescriptorRegistry: new () => NativeDescriptorRegistry;
@@ -368,12 +369,16 @@ export interface RustDatabaseConnectOptions {
368
369
  password?: string | null;
369
370
  /** Port of the TypeDB HTTP API used for the connect-time version probe. */
370
371
  httpPort?: number;
372
+ /** Exact TypeDB server version; skips HTTP probing for gRPC-only deployments. */
373
+ serverVersion?: string | null;
371
374
  }
372
375
  export interface EnsureDatabaseOptions {
373
376
  username?: string | null;
374
377
  password?: string | null;
375
378
  /** Port of the TypeDB HTTP API used for the connect-time version probe. */
376
379
  httpPort?: number;
380
+ /** Exact TypeDB server version; skips HTTP probing for gRPC-only deployments. */
381
+ serverVersion?: string | null;
377
382
  }
378
383
  /**
379
384
  * Ensure the named TypeDB database exists, creating it if absent.
@@ -474,4 +479,4 @@ export declare class RustDynamicRelationManager {
474
479
  queryGroupByAggregate(spec: DynamicQuerySpec, groupFields: string[], aggregates: AggregateInput[]): unknown[];
475
480
  deleteByIid(iid: string): void;
476
481
  }
477
- export { generateModels, type GenerateModelsOptions, type NamingOptions, } from "./generator/index.js";
482
+ export { generateModels, generateModelsForTarget, type BindgenRenderOptions, type BindgenTarget, type GenerateModelsOptions, type GenerateTargetModelsOptions, type NamingOptions, } from "./generator/index.js";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RustDynamicEntityManager = exports.RustTransactionContext = exports.RustDatabase = exports.Marshalling = exports.DescriptorRegistry = exports.loadNative = exports.parseSchema = exports.relationManagerFor = exports.entityManagerFor = exports.buildRolePlayers = exports.TypedRelationManager = exports.TypedEntityManager = exports.runtimeAttributeValueFromUnknown = exports.plainToAttribute = exports.lowerFilters = exports.lowerAttributeValue = exports.lowerAttributes = exports.keyAttributeDescriptor = exports.hydrateAttributes = exports.hydrateAttributeEntries = exports.attributeToPlain = exports.TypedCodecError = exports.role = exports.field = exports.RoleSpec = exports.Relation = exports.ListFieldSpec = exports.FieldSpec = exports.Entity = exports.resolveFlags = exports.formatTypeName = exports.Unique = exports.TypeNameCase = exports.TypeFlags = exports.Key = exports.Flag = exports.Card = exports.AttributeFlags = exports.agg = exports.TypedQueryError = exports.TypedQuery = exports.TypedGroupByQuery = exports.SortExpr = exports.QueryExpr = exports.NotExpr = exports.ComparisonExpr = exports.BooleanExpr = exports.AggregateSpec = exports.attr = exports.Attribute = void 0;
4
- exports.generateModels = exports.RustDynamicRelationManager = void 0;
4
+ exports.generateModelsForTarget = exports.generateModels = exports.RustDynamicRelationManager = void 0;
5
5
  exports.string = string;
6
6
  exports.long = long;
7
7
  exports.longFromNumberUnsafe = longFromNumberUnsafe;
@@ -117,7 +117,7 @@ function duration(value) {
117
117
  * silent skip.
118
118
  */
119
119
  function ensureDatabase(address, database, options) {
120
- (0, native_js_1.loadNative)().ensureRustDatabase(address, database, options?.username ?? null, options?.password ?? null, options?.httpPort ?? null);
120
+ (0, native_js_1.loadNative)().ensureRustDatabase(address, database, options?.username ?? null, options?.password ?? null, options?.httpPort ?? null, options?.serverVersion ?? null);
121
121
  }
122
122
  function generateDefineBlock(info) {
123
123
  return (0, native_js_1.loadNative)().generateDefineBlockJson(JSON.stringify(info));
@@ -259,7 +259,7 @@ class RustDatabase {
259
259
  }
260
260
  static connect(nativeOrAddress, addressOrDatabase, databaseOrOptions = {}, maybeOptions = {}) {
261
261
  const parsed = parseConnectArguments(nativeOrAddress, addressOrDatabase, databaseOrOptions, maybeOptions);
262
- return new RustDatabase(parsed.native.connectRustDatabase(parsed.address, parsed.database, parsed.options.username ?? null, parsed.options.password ?? null, parsed.options.httpPort ?? null));
262
+ return new RustDatabase(parsed.native.connectRustDatabase(parsed.address, parsed.database, parsed.options.username ?? null, parsed.options.password ?? null, parsed.options.httpPort ?? null, parsed.options.serverVersion ?? null));
263
263
  }
264
264
  isConnected() {
265
265
  return this.#native.isConnected();
@@ -461,3 +461,4 @@ function parseConnectArguments(nativeOrAddress, addressOrDatabase, databaseOrOpt
461
461
  // ---------------------------------------------------------------------------
462
462
  var index_js_1 = require("./generator/index.js");
463
463
  Object.defineProperty(exports, "generateModels", { enumerable: true, get: function () { return index_js_1.generateModels; } });
464
+ Object.defineProperty(exports, "generateModelsForTarget", { enumerable: true, get: function () { return index_js_1.generateModelsForTarget; } });
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@type-bridge/node",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
4
4
  "description": "Node.js NAPI facade for the type-bridge Rust ORM runtime",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
Binary file
@@ -1,15 +0,0 @@
1
- /**
2
- * Shared cardinality predicate helpers for TypeScript code generation.
3
- *
4
- * Used by both renderEntities.ts and renderRelations.ts. Each predicate
5
- * mirrors the corresponding Python `Cardinality` property in models.py.
6
- */
7
- import type { Cardinality } from "../parser.js";
8
- /** True if at most one value is allowed (max === 1). */
9
- export declare function isCardSingle(c: Cardinality): boolean;
10
- /** True if at least one value is required (min >= 1). */
11
- export declare function isCardRequired(c: Cardinality): boolean;
12
- /** True if multiple values are allowed (max === null || max > 1). */
13
- export declare function isCardMulti(c: Cardinality): boolean;
14
- /** True if zero or one value (min === 0, max === 1) — the optional-single case. */
15
- export declare function isCardOptionalSingle(c: Cardinality): boolean;
@@ -1,28 +0,0 @@
1
- "use strict";
2
- /**
3
- * Shared cardinality predicate helpers for TypeScript code generation.
4
- *
5
- * Used by both renderEntities.ts and renderRelations.ts. Each predicate
6
- * mirrors the corresponding Python `Cardinality` property in models.py.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.isCardSingle = isCardSingle;
10
- exports.isCardRequired = isCardRequired;
11
- exports.isCardMulti = isCardMulti;
12
- exports.isCardOptionalSingle = isCardOptionalSingle;
13
- /** True if at most one value is allowed (max === 1). */
14
- function isCardSingle(c) {
15
- return c.max === 1;
16
- }
17
- /** True if at least one value is required (min >= 1). */
18
- function isCardRequired(c) {
19
- return c.min >= 1;
20
- }
21
- /** True if multiple values are allowed (max === null || max > 1). */
22
- function isCardMulti(c) {
23
- return c.max === null || c.max > 1;
24
- }
25
- /** True if zero or one value (min === 0, max === 1) — the optional-single case. */
26
- function isCardOptionalSingle(c) {
27
- return c.min === 0 && c.max === 1;
28
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Render the `attributes.ts` module text from a parsed TypeSchema.
3
- *
4
- * Mirrors `type_bridge/generator/render/attributes.py` → `render_attributes()`.
5
- * Emits one branded `export class <ClassName> extends attr.<Kind>("<name>", ...) {}`
6
- * per attribute, in deterministic parent-before-child order matching the
7
- * Python generator's topological/sorted emit.
8
- *
9
- * Build-time code generation; no runtime ORM logic.
10
- */
11
- import type { TypeSchema } from "../parser.js";
12
- /**
13
- * Render the complete `attributes.ts` source text from the parsed schema.
14
- *
15
- * Each attribute emits:
16
- * export class <ClassName> extends attr.<Kind>("<schema-name>") {}
17
- *
18
- * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
19
- * never a hardcoded relative path, so generated files stay valid across
20
- * the packaging layout change.
21
- */
22
- export declare function renderAttributes(schema: TypeSchema): string;
@@ -1,153 +0,0 @@
1
- "use strict";
2
- /**
3
- * Render the `attributes.ts` module text from a parsed TypeSchema.
4
- *
5
- * Mirrors `type_bridge/generator/render/attributes.py` → `render_attributes()`.
6
- * Emits one branded `export class <ClassName> extends attr.<Kind>("<name>", ...) {}`
7
- * per attribute, in deterministic parent-before-child order matching the
8
- * Python generator's topological/sorted emit.
9
- *
10
- * Build-time code generation; no runtime ORM logic.
11
- */
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.renderAttributes = renderAttributes;
14
- const naming_js_1 = require("./naming.js");
15
- /**
16
- * Map TypeDB `value_type` strings to the `attr.*` factory method name.
17
- *
18
- * Verified against `typescript/attribute.ts` `attr` export:
19
- * attr.String -> "string"
20
- * attr.Integer -> "long" (bigint, maps to the `long` wire type)
21
- * attr.Double -> "double"
22
- * attr.Boolean -> "boolean"
23
- * attr.Date -> "date"
24
- * attr.DateTime -> "datetime"
25
- * attr.DateTimeTZ -> "datetime-tz"
26
- * attr.Decimal -> "decimal"
27
- * attr.Duration -> "duration"
28
- *
29
- * The parsed schema preserves the declared value_type: an integer attribute
30
- * arrives as "integer", not "long". Both "integer" and "long" map to attr.Integer
31
- * (whose descriptor records the "long" wire type), mirroring the Python generator.
32
- */
33
- const VALUE_TYPE_TO_KIND = {
34
- string: "String",
35
- integer: "Integer",
36
- long: "Integer",
37
- double: "Double",
38
- boolean: "Boolean",
39
- date: "Date",
40
- datetime: "DateTime",
41
- "datetime-tz": "DateTimeTZ",
42
- decimal: "Decimal",
43
- duration: "Duration",
44
- };
45
- /**
46
- * Resolve the `attr.*` factory kind for an attribute, following value_type
47
- * inheritance. Mirrors `_resolve_value_type` in `render/attributes.py`.
48
- */
49
- function resolveAttrKind(attrName, schema, visited = new Set()) {
50
- if (visited.has(attrName))
51
- return "String";
52
- visited.add(attrName);
53
- const attr = schema.attributes[attrName];
54
- if (!attr)
55
- return "String";
56
- if (attr.value_type) {
57
- const kind = VALUE_TYPE_TO_KIND[attr.value_type];
58
- if (kind === undefined) {
59
- // Fail loudly rather than emit a silently-wrong attr.String — an
60
- // unmapped value_type means a TypeDB type the generator does not handle.
61
- throw new Error(`Cannot generate attribute "${attrName}": unsupported value_type "${attr.value_type}".`);
62
- }
63
- return kind;
64
- }
65
- if (attr.parent) {
66
- return resolveAttrKind(attr.parent, schema, visited);
67
- }
68
- return "String";
69
- }
70
- /**
71
- * Return attribute names in deterministic topological order: parents before
72
- * children, with alphabetical order among unrelated attributes.
73
- */
74
- function sortedAttrNames(schema) {
75
- const sorted = [];
76
- const visited = new Set();
77
- const names = Object.keys(schema.attributes).sort();
78
- function visit(name) {
79
- if (visited.has(name))
80
- return;
81
- visited.add(name);
82
- const parent = schema.attributes[name]?.parent;
83
- if (parent && schema.attributes[parent]) {
84
- visit(parent);
85
- }
86
- sorted.push(name);
87
- }
88
- for (const name of names) {
89
- visit(name);
90
- }
91
- return sorted;
92
- }
93
- function attributeOptionsLiteral(attrName, schema, attrClassMap) {
94
- const attribute = schema.attributes[attrName];
95
- if (!attribute)
96
- return "";
97
- const fields = [];
98
- if (attribute.parent) {
99
- const parentClass = attrClassMap.get(attribute.parent);
100
- fields.push(parentClass
101
- ? `parent: ${parentClass}`
102
- : `parent: ${JSON.stringify(attribute.parent)}`);
103
- }
104
- if (attribute.is_abstract) {
105
- fields.push(`abstract: true`);
106
- }
107
- if (attribute.is_independent) {
108
- fields.push(`independent: true`);
109
- }
110
- if (attribute.regex !== null) {
111
- fields.push(`regex: ${JSON.stringify(attribute.regex)}`);
112
- }
113
- if (attribute.allowed_values !== null) {
114
- fields.push(`values: ${JSON.stringify(attribute.allowed_values)}`);
115
- }
116
- if (attribute.range_min !== null || attribute.range_max !== null) {
117
- fields.push(`range: [${optionalStringLiteral(attribute.range_min)}, ${optionalStringLiteral(attribute.range_max)}]`);
118
- }
119
- return fields.length === 0 ? "" : `, { ${fields.join(", ")} }`;
120
- }
121
- function optionalStringLiteral(value) {
122
- return value === null ? "null" : JSON.stringify(value);
123
- }
124
- /**
125
- * Render the complete `attributes.ts` source text from the parsed schema.
126
- *
127
- * Each attribute emits:
128
- * export class <ClassName> extends attr.<Kind>("<schema-name>") {}
129
- *
130
- * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
131
- * never a hardcoded relative path, so generated files stay valid across
132
- * the packaging layout change.
133
- */
134
- function renderAttributes(schema) {
135
- const names = sortedAttrNames(schema);
136
- const attrClassMap = new Map();
137
- for (const name of Object.keys(schema.attributes)) {
138
- attrClassMap.set(name, (0, naming_js_1.toClassName)(name));
139
- }
140
- const lines = [
141
- `import { attr } from "@type-bridge/node";`,
142
- ``,
143
- ];
144
- for (const name of names) {
145
- const className = attrClassMap.get(name) ?? (0, naming_js_1.toClassName)(name);
146
- const kind = resolveAttrKind(name, schema);
147
- const options = attributeOptionsLiteral(name, schema, attrClassMap);
148
- lines.push(`export class ${className} extends attr.${kind}("${name}"${options}) {}`);
149
- }
150
- // Trailing newline
151
- lines.push(``);
152
- return lines.join("\n");
153
- }
@@ -1,39 +0,0 @@
1
- /**
2
- * Render the `entities.ts` module text from a parsed TypeSchema.
3
- *
4
- * Mirrors `type_bridge/generator/render/entities.py` → `render_entities()`.
5
- * Field KEY decision logic is ported directly from `_render_attr_field`:
6
- *
7
- * 1. is_key (schema @key OR implicit key) → field(Attr, Key)
8
- * 2. is_unique (schema @unique) → field(Attr, Unique)
9
- * 3. cardinality === null || is_optional_single (min=0, max=1)
10
- * → field(Attr).optional()
11
- * 4. is_multi (max === null || max > 1) → field(Attr).list(Card(min, max))
12
- * 5. is_required && is_single (min>=1, max=1) → field(Attr) (plain required)
13
- * 6. fallback → field(Attr).optional()
14
- *
15
- * Field keys = toFieldName(attr_name) — prefix kept, no pluralization.
16
- *
17
- * Build-time code generation; no runtime ORM logic.
18
- */
19
- import type { TypeSchema } from "../parser.js";
20
- import { type NamingOptions } from "./naming.js";
21
- /**
22
- * Render the complete `entities.ts` source text from the parsed schema.
23
- *
24
- * Each entity emits:
25
- * export class <ClassName> extends Entity("<schema-name>", { ... }) {}
26
- * or for abstract entities:
27
- * export class <ClassName> extends Entity(TypeFlags({ name: "<name>", abstract: true }), { ... }) {}
28
- * and with parent:
29
- * ... Entity("<name>", { ... }, { parent: <ParentClass> }) {}
30
- *
31
- * Field keys = toFieldName(attr_name); values = the field() expression above.
32
- * Attribute imports come from "./attributes"; entity parent imports also from
33
- * the same file.
34
- *
35
- * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
36
- * never a hardcoded relative path, so generated files stay valid across
37
- * the packaging layout change.
38
- */
39
- export declare function renderEntities(schema: TypeSchema, options?: NamingOptions): string;
@@ -1,273 +0,0 @@
1
- "use strict";
2
- /**
3
- * Render the `entities.ts` module text from a parsed TypeSchema.
4
- *
5
- * Mirrors `type_bridge/generator/render/entities.py` → `render_entities()`.
6
- * Field KEY decision logic is ported directly from `_render_attr_field`:
7
- *
8
- * 1. is_key (schema @key OR implicit key) → field(Attr, Key)
9
- * 2. is_unique (schema @unique) → field(Attr, Unique)
10
- * 3. cardinality === null || is_optional_single (min=0, max=1)
11
- * → field(Attr).optional()
12
- * 4. is_multi (max === null || max > 1) → field(Attr).list(Card(min, max))
13
- * 5. is_required && is_single (min>=1, max=1) → field(Attr) (plain required)
14
- * 6. fallback → field(Attr).optional()
15
- *
16
- * Field keys = toFieldName(attr_name) — prefix kept, no pluralization.
17
- *
18
- * Build-time code generation; no runtime ORM logic.
19
- */
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.renderEntities = renderEntities;
22
- const naming_js_1 = require("./naming.js");
23
- const cardinality_js_1 = require("./cardinality.js");
24
- // ---------------------------------------------------------------------------
25
- // Single-field renderer
26
- // ---------------------------------------------------------------------------
27
- /**
28
- * Render the `field(...)` expression for one owned attribute.
29
- *
30
- * Decision logic mirrors Python `_render_attr_field` (entities.py:38-65):
31
- * Key > Unique > ordered (list) > optional_single > multi (list) > required_single > fallback optional
32
- *
33
- * Ordered list attributes use `.ordered()` / `.ordered().distinct()` instead of
34
- * `.list(Card(...))`. These correspond to `owns attr[] @distinct` in TypeQL.
35
- */
36
- function renderFieldExpr(owned, attrClassName, isKey) {
37
- const card = owned.cardinality;
38
- if (isKey) {
39
- return `field(${attrClassName}, Key)`;
40
- }
41
- if (owned.is_unique) {
42
- return `field(${attrClassName}, Unique)`;
43
- }
44
- // Ordered list attribute: field(Attr).ordered() or field(Attr).ordered().distinct()
45
- if (owned.ordered) {
46
- const base = `field(${attrClassName}).ordered()`;
47
- return owned.distinct ? `${base}.distinct()` : base;
48
- }
49
- // cardinality === null means default (optional single, same as @card(0..1))
50
- if (card === null || (0, cardinality_js_1.isCardOptionalSingle)(card)) {
51
- return `field(${attrClassName}).optional()`;
52
- }
53
- if ((0, cardinality_js_1.isCardMulti)(card)) {
54
- const maxStr = card.max === null ? "null" : String(card.max);
55
- return `field(${attrClassName}).list(Card(${card.min}, ${maxStr}))`;
56
- }
57
- if ((0, cardinality_js_1.isCardRequired)(card) && (0, cardinality_js_1.isCardSingle)(card)) {
58
- // required single: plain field, no modifier
59
- return `field(${attrClassName})`;
60
- }
61
- // Fallback: optional
62
- return `field(${attrClassName}).optional()`;
63
- }
64
- // ---------------------------------------------------------------------------
65
- // Topological sort — parents before children (mirror `_topological_sort_entities`)
66
- // ---------------------------------------------------------------------------
67
- function topologicalSortEntities(schema) {
68
- const entities = schema.entities;
69
- const names = Object.keys(entities);
70
- const sorted = [];
71
- const visited = new Set();
72
- function visit(name) {
73
- if (visited.has(name))
74
- return;
75
- visited.add(name);
76
- const parent = entities[name]?.parent;
77
- if (parent && entities[parent]) {
78
- visit(parent);
79
- }
80
- sorted.push(name);
81
- }
82
- for (const name of names) {
83
- visit(name);
84
- }
85
- return sorted;
86
- }
87
- // ---------------------------------------------------------------------------
88
- // Main renderer
89
- // ---------------------------------------------------------------------------
90
- /**
91
- * Render the complete `entities.ts` source text from the parsed schema.
92
- *
93
- * Each entity emits:
94
- * export class <ClassName> extends Entity("<schema-name>", { ... }) {}
95
- * or for abstract entities:
96
- * export class <ClassName> extends Entity(TypeFlags({ name: "<name>", abstract: true }), { ... }) {}
97
- * and with parent:
98
- * ... Entity("<name>", { ... }, { parent: <ParentClass> }) {}
99
- *
100
- * Field keys = toFieldName(attr_name); values = the field() expression above.
101
- * Attribute imports come from "./attributes"; entity parent imports also from
102
- * the same file.
103
- *
104
- * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
105
- * never a hardcoded relative path, so generated files stay valid across
106
- * the packaging layout change.
107
- */
108
- function renderEntities(schema, options) {
109
- const sortedNames = topologicalSortEntities(schema);
110
- // Collect which attribute class names are actually referenced (for the import)
111
- const referencedAttrClasses = new Set();
112
- // Pre-compute entity class name map
113
- const entityClassMap = new Map();
114
- for (const name of Object.keys(schema.entities)) {
115
- entityClassMap.set(name, (0, naming_js_1.toClassName)(name));
116
- }
117
- // Pre-compute attribute class name map
118
- const attrClassMap = new Map();
119
- for (const name of Object.keys(schema.attributes)) {
120
- attrClassMap.set(name, (0, naming_js_1.toClassName)(name));
121
- }
122
- // Collect imports by scanning all entities
123
- for (const entityName of sortedNames) {
124
- const entity = schema.entities[entityName];
125
- if (!entity)
126
- continue;
127
- // Determine which attrs this entity owns LOCALLY (not inherited from parent)
128
- const parentOwns = new Set();
129
- if (entity.parent) {
130
- const parentEntity = schema.entities[entity.parent];
131
- if (parentEntity) {
132
- for (const o of parentEntity.owns) {
133
- parentOwns.add(o.name);
134
- }
135
- }
136
- }
137
- for (const owned of entity.owns) {
138
- if (parentOwns.has(owned.name))
139
- continue;
140
- const attrClass = attrClassMap.get(owned.name);
141
- if (attrClass)
142
- referencedAttrClasses.add(attrClass);
143
- }
144
- }
145
- // Determine which factory symbols are needed
146
- const needsKey = sortedNames.some((entityName) => {
147
- const entity = schema.entities[entityName];
148
- if (!entity)
149
- return false;
150
- const parentOwns = buildParentOwns(entityName, schema);
151
- return entity.owns.some((owned) => {
152
- if (parentOwns.has(owned.name))
153
- return false;
154
- return (0, naming_js_1.isKeyAttribute)(owned.name, owned.is_key, options);
155
- });
156
- });
157
- const needsUnique = sortedNames.some((entityName) => {
158
- const entity = schema.entities[entityName];
159
- if (!entity)
160
- return false;
161
- const parentOwns = buildParentOwns(entityName, schema);
162
- return entity.owns.some((owned) => !parentOwns.has(owned.name) && owned.is_unique);
163
- });
164
- const needsCard = sortedNames.some((entityName) => {
165
- const entity = schema.entities[entityName];
166
- if (!entity)
167
- return false;
168
- const parentOwns = buildParentOwns(entityName, schema);
169
- return entity.owns.some((owned) => {
170
- if (parentOwns.has(owned.name))
171
- return false;
172
- const card = owned.cardinality;
173
- return card !== null && (0, cardinality_js_1.isCardMulti)(card);
174
- });
175
- });
176
- const needsTypeFlags = sortedNames.some((name) => schema.entities[name]?.is_abstract);
177
- const needsOrdered = sortedNames.some((entityName) => {
178
- const entity = schema.entities[entityName];
179
- if (!entity)
180
- return false;
181
- const parentOwns = buildParentOwns(entityName, schema);
182
- return entity.owns.some((owned) => !parentOwns.has(owned.name) && owned.ordered);
183
- });
184
- const needsDistinct = sortedNames.some((entityName) => {
185
- const entity = schema.entities[entityName];
186
- if (!entity)
187
- return false;
188
- const parentOwns = buildParentOwns(entityName, schema);
189
- return entity.owns.some((owned) => !parentOwns.has(owned.name) && owned.distinct);
190
- });
191
- // Build the factory import list
192
- const factoryImports = ["Entity", "field"];
193
- if (needsKey)
194
- factoryImports.push("Key");
195
- if (needsUnique)
196
- factoryImports.push("Unique");
197
- if (needsCard)
198
- factoryImports.push("Card");
199
- if (needsTypeFlags)
200
- factoryImports.push("TypeFlags");
201
- if (needsOrdered)
202
- factoryImports.push("Ordered");
203
- if (needsDistinct)
204
- factoryImports.push("Distinct");
205
- factoryImports.sort();
206
- const sortedAttrImports = [...referencedAttrClasses].sort();
207
- const lines = [`import { ${factoryImports.join(", ")} } from "@type-bridge/node";`];
208
- if (sortedAttrImports.length > 0) {
209
- lines.push(`import { ${sortedAttrImports.join(", ")} } from "./attributes.js";`);
210
- }
211
- lines.push(``);
212
- // Emit each entity class
213
- for (const entityName of sortedNames) {
214
- const entity = schema.entities[entityName];
215
- if (!entity)
216
- continue;
217
- const className = entityClassMap.get(entityName) ?? (0, naming_js_1.toClassName)(entityName);
218
- // Determine own attrs (not inherited)
219
- const parentOwns = buildParentOwns(entityName, schema);
220
- // Use owns_order for deterministic field ordering (mirrors Python `entity.owns_order`)
221
- const ownLocalAttrs = entity.owns_order.filter((n) => !parentOwns.has(n));
222
- // Build the fields object entries
223
- const fieldEntries = [];
224
- for (const attrName of ownLocalAttrs) {
225
- const owned = entity.owns.find((o) => o.name === attrName);
226
- if (!owned)
227
- continue;
228
- const attrClass = attrClassMap.get(attrName);
229
- if (!attrClass)
230
- continue;
231
- const fieldKey = (0, naming_js_1.toFieldName)(attrName);
232
- const isKey = (0, naming_js_1.isKeyAttribute)(attrName, owned.is_key, options);
233
- const fieldExpr = renderFieldExpr(owned, attrClass, isKey);
234
- fieldEntries.push(` ${fieldKey}: ${fieldExpr},`);
235
- }
236
- // First argument: TypeFlags({...}) for abstract, or plain string
237
- let firstArg;
238
- if (entity.is_abstract) {
239
- firstArg = `TypeFlags({ name: "${entityName}", abstract: true })`;
240
- }
241
- else {
242
- firstArg = `"${entityName}"`;
243
- }
244
- // Third argument: { parent: ParentClass } if parent present
245
- const parentClassName = entity.parent ? entityClassMap.get(entity.parent) : null;
246
- const thirdArg = parentClassName ? `, { parent: ${parentClassName} }` : "";
247
- if (fieldEntries.length === 0) {
248
- lines.push(`export class ${className} extends Entity(${firstArg}, {}${thirdArg}) {}`);
249
- }
250
- else {
251
- lines.push(`export class ${className} extends Entity(${firstArg}, {`);
252
- for (const entry of fieldEntries) {
253
- lines.push(entry);
254
- }
255
- lines.push(`}${thirdArg}) {}`);
256
- }
257
- lines.push(``);
258
- }
259
- return lines.join("\n");
260
- }
261
- // ---------------------------------------------------------------------------
262
- // Helpers
263
- // ---------------------------------------------------------------------------
264
- /** Build the set of attribute names owned by the direct parent entity. */
265
- function buildParentOwns(entityName, schema) {
266
- const entity = schema.entities[entityName];
267
- if (!entity?.parent)
268
- return new Set();
269
- const parent = schema.entities[entity.parent];
270
- if (!parent)
271
- return new Set();
272
- return new Set(parent.owns.map((o) => o.name));
273
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Render the output package barrel (`index.ts`) text.
3
- *
4
- * Mirrors Python `render_package_init()` in `type_bridge/generator/__init__.py`.
5
- * The barrel re-exports everything from the three generated modules so that
6
- * callers can import from a single entry point.
7
- *
8
- * This file produces the content written to `<outputDir>/index.ts`.
9
- * It is intentionally named `renderPackage.ts` (not `index.ts`) to avoid
10
- * confusion with `generator/index.ts` (the generator entry point).
11
- *
12
- * Build-time code generation; no runtime ORM logic.
13
- */
14
- import type { TypeSchema } from "../parser.js";
15
- /**
16
- * Render the package barrel `index.ts` that re-exports all generated modules.
17
- *
18
- * The `schema` parameter is accepted for API symmetry with the other renderers
19
- * (and to allow future conditional re-exports), but the barrel is unconditional:
20
- * all three modules are always re-exported.
21
- */
22
- export declare function renderPackage(_schema: TypeSchema): string;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- /**
3
- * Render the output package barrel (`index.ts`) text.
4
- *
5
- * Mirrors Python `render_package_init()` in `type_bridge/generator/__init__.py`.
6
- * The barrel re-exports everything from the three generated modules so that
7
- * callers can import from a single entry point.
8
- *
9
- * This file produces the content written to `<outputDir>/index.ts`.
10
- * It is intentionally named `renderPackage.ts` (not `index.ts`) to avoid
11
- * confusion with `generator/index.ts` (the generator entry point).
12
- *
13
- * Build-time code generation; no runtime ORM logic.
14
- */
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.renderPackage = renderPackage;
17
- /**
18
- * Render the package barrel `index.ts` that re-exports all generated modules.
19
- *
20
- * The `schema` parameter is accepted for API symmetry with the other renderers
21
- * (and to allow future conditional re-exports), but the barrel is unconditional:
22
- * all three modules are always re-exported.
23
- */
24
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
25
- function renderPackage(_schema) {
26
- const lines = [
27
- `export * from "./attributes.js";`,
28
- `export * from "./entities.js";`,
29
- `export * from "./relations.js";`,
30
- ``,
31
- ];
32
- return lines.join("\n");
33
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * Render the `relations.ts` module text from a parsed TypeSchema.
3
- *
4
- * Mirrors `type_bridge/generator/render/relations.py` → `render_relations()`.
5
- *
6
- * Role-player derivation:
7
- * Scan ALL entity `plays[]` entries for `role_ref === "<relation>:<role>"`.
8
- * Remove ancestor types when a descendant is also present (minimal set).
9
- * This is the exact algorithm of `minimal_role_players()` in models.py.
10
- *
11
- * Cardinality sources:
12
- * Relates-side cardinality comes from the relation role definition
13
- * (`RoleSpec.cardinality`). Plays-side cardinality comes from the player's
14
- * `PlayedRole.cardinality` and renders as `playsCardinality` on `role(...)`.
15
- *
16
- * Field key = toFieldName(role.name) / toFieldName(attr.name).
17
- * Class names = toClassName(typeName) for all players / attr types.
18
- *
19
- * Build-time code generation; no runtime ORM logic.
20
- */
21
- import type { TypeSchema } from "../parser.js";
22
- import { type NamingOptions } from "./naming.js";
23
- /**
24
- * Render the complete `relations.ts` source text from the parsed schema.
25
- *
26
- * Each relation emits:
27
- * export class <ClassName> extends Relation("<name>", { <fields> }) {}
28
- *
29
- * Role keys = toFieldName(role.name).
30
- * Attr keys = toFieldName(attr.name).
31
- * Player names = toClassName(entityName).
32
- *
33
- * Imports: `@type-bridge/node` for factory symbols; `./attributes.js` for
34
- * attribute classes; `./entities.js` for player entity classes.
35
- */
36
- export declare function renderRelations(schema: TypeSchema, options?: NamingOptions): string;
@@ -1,395 +0,0 @@
1
- "use strict";
2
- /**
3
- * Render the `relations.ts` module text from a parsed TypeSchema.
4
- *
5
- * Mirrors `type_bridge/generator/render/relations.py` → `render_relations()`.
6
- *
7
- * Role-player derivation:
8
- * Scan ALL entity `plays[]` entries for `role_ref === "<relation>:<role>"`.
9
- * Remove ancestor types when a descendant is also present (minimal set).
10
- * This is the exact algorithm of `minimal_role_players()` in models.py.
11
- *
12
- * Cardinality sources:
13
- * Relates-side cardinality comes from the relation role definition
14
- * (`RoleSpec.cardinality`). Plays-side cardinality comes from the player's
15
- * `PlayedRole.cardinality` and renders as `playsCardinality` on `role(...)`.
16
- *
17
- * Field key = toFieldName(role.name) / toFieldName(attr.name).
18
- * Class names = toClassName(typeName) for all players / attr types.
19
- *
20
- * Build-time code generation; no runtime ORM logic.
21
- */
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.renderRelations = renderRelations;
24
- const naming_js_1 = require("./naming.js");
25
- const cardinality_js_1 = require("./cardinality.js");
26
- // ---------------------------------------------------------------------------
27
- // Card() argument renderer — mirrors Python `_render_card_arg`
28
- //
29
- // Default (1,1) emits nothing — caller wraps with `{ cardinality: Card(...) }`.
30
- // We always emit cardinality for roles (the hand-authored parity file always
31
- // uses explicit Card()), but skip if it is the default single (1,1).
32
- // ---------------------------------------------------------------------------
33
- function renderCardArg(card, omitDefaultSingle = true) {
34
- if (card === null)
35
- return "";
36
- if (omitDefaultSingle && card.min === 1 && card.max === 1)
37
- return "";
38
- const maxStr = card.max === null ? "null" : String(card.max);
39
- return `Card(${card.min}, ${maxStr})`;
40
- }
41
- // ---------------------------------------------------------------------------
42
- // role() call renderer — mirrors `_render_role_field` in relations.py
43
- // ---------------------------------------------------------------------------
44
- function renderRoleCall(players, card, playsCardinality, overrides = null, isAbstract = false, ordered = false, distinct = false) {
45
- const cardArg = renderCardArg(card);
46
- const playsCardArg = renderCardArg(playsCardinality, false);
47
- const options = [];
48
- if (cardArg)
49
- options.push(`cardinality: ${cardArg}`);
50
- if (playsCardArg)
51
- options.push(`playsCardinality: ${playsCardArg}`);
52
- if (overrides != null)
53
- options.push(`overrides: "${overrides}"`);
54
- if (isAbstract)
55
- options.push(`abstract: true`);
56
- if (ordered)
57
- options.push(`ordered: true`);
58
- if (distinct)
59
- options.push(`distinct: true`);
60
- const cardOptions = options.length > 0 ? `{ ${options.join(", ")} }` : null;
61
- if (players.length === 1) {
62
- const args = cardOptions ? `${players[0]}, ${cardOptions}` : players[0];
63
- return `role(${args})`;
64
- }
65
- // Multi-player: role(A, B, ..., { cardinality: ... })
66
- const playerArgs = players.join(", ");
67
- const args = cardOptions ? `${playerArgs}, ${cardOptions}` : playerArgs;
68
- return `role(${args})`;
69
- }
70
- function playsCardinalityForRole(schema, relationName, roleName, players) {
71
- const roleToken = `${relationName}:${roleName}`;
72
- for (const player of players) {
73
- const entity = schema.entities[player];
74
- const played = entity?.plays.find((entry) => entry.role_ref === roleToken);
75
- if (played?.cardinality !== null && played?.cardinality !== undefined) {
76
- return played.cardinality;
77
- }
78
- }
79
- return null;
80
- }
81
- // ---------------------------------------------------------------------------
82
- // Minimal role players — mirrors `minimal_role_players` in models.py
83
- //
84
- // Scan entity plays[] for role_ref === "<relationName>:<roleName>".
85
- // Then remove ancestors when a descendant is also present.
86
- // ---------------------------------------------------------------------------
87
- function minimalRolePlayers(schema, relationName, roleName) {
88
- const roleToken = `${relationName}:${roleName}`;
89
- // Collect all entities that play this role
90
- const players = [];
91
- for (const [entityName, entity] of Object.entries(schema.entities)) {
92
- for (const played of entity.plays) {
93
- if (played.role_ref === roleToken) {
94
- players.push(entityName);
95
- break;
96
- }
97
- }
98
- }
99
- if (players.length === 0)
100
- return [];
101
- // Build parent map
102
- const parentMap = new Map();
103
- for (const [name, entity] of Object.entries(schema.entities)) {
104
- parentMap.set(name, entity.parent);
105
- }
106
- function isAncestor(candidate, target) {
107
- let current = parentMap.get(target) ?? null;
108
- while (current !== null) {
109
- if (current === candidate)
110
- return true;
111
- current = parentMap.get(current) ?? null;
112
- }
113
- return false;
114
- }
115
- // Remove ancestors when a descendant is also present
116
- const unique = new Set(players);
117
- const minimal = new Set(unique);
118
- for (const player of unique) {
119
- for (const other of unique) {
120
- if (player !== other && isAncestor(other, player) && minimal.has(player)) {
121
- minimal.delete(player);
122
- break;
123
- }
124
- }
125
- }
126
- return [...minimal].sort();
127
- }
128
- // ---------------------------------------------------------------------------
129
- // Topological sort — parents before children (mirrors `_topological_sort_relations`)
130
- // ---------------------------------------------------------------------------
131
- function topologicalSortRelations(schema) {
132
- const relations = schema.relations;
133
- const names = Object.keys(relations);
134
- const sorted = [];
135
- const visited = new Set();
136
- function visit(name) {
137
- if (visited.has(name))
138
- return;
139
- visited.add(name);
140
- const parent = relations[name]?.parent;
141
- if (parent && relations[parent]) {
142
- visit(parent);
143
- }
144
- sorted.push(name);
145
- }
146
- for (const name of names) {
147
- visit(name);
148
- }
149
- return sorted;
150
- }
151
- // ---------------------------------------------------------------------------
152
- // Import need detectors
153
- // ---------------------------------------------------------------------------
154
- function needsCardImport(schema) {
155
- for (const relation of Object.values(schema.relations)) {
156
- // Check role cardinalities
157
- for (const role of relation.roles) {
158
- if (role.cardinality !== null) {
159
- const c = role.cardinality;
160
- if (!(c.min === 1 && c.max === 1))
161
- return true;
162
- }
163
- const players = minimalRolePlayers(schema, relation.name, role.name);
164
- if (playsCardinalityForRole(schema, relation.name, role.name, players) !== null) {
165
- return true;
166
- }
167
- }
168
- // Check attribute cardinalities (multi-valued)
169
- for (const owned of relation.owns) {
170
- const c = owned.cardinality;
171
- if (c !== null && (0, cardinality_js_1.isCardMulti)(c))
172
- return true;
173
- }
174
- }
175
- return false;
176
- }
177
- function needsKeyImport(schema, options) {
178
- return Object.values(schema.relations).some((rel) => rel.owns.some((o) => (0, naming_js_1.isKeyAttribute)(o.name, o.is_key, options)));
179
- }
180
- function needsUniqueImport(schema) {
181
- return Object.values(schema.relations).some((rel) => rel.owns.some((o) => o.is_unique));
182
- }
183
- function needsTypeFlagsImport(schema) {
184
- return Object.values(schema.relations).some((rel) => rel.is_abstract);
185
- }
186
- function needsOrderedImport(schema) {
187
- return Object.values(schema.relations).some((rel) => rel.roles.some((r) => r.ordered) ||
188
- rel.owns.some((o) => o.ordered));
189
- }
190
- function needsDistinctImport(schema) {
191
- return Object.values(schema.relations).some((rel) => rel.roles.some((r) => r.distinct) ||
192
- rel.owns.some((o) => o.distinct));
193
- }
194
- // ---------------------------------------------------------------------------
195
- // Single-field renderer for owned attributes (mirrors renderEntities.ts logic)
196
- // ---------------------------------------------------------------------------
197
- function renderAttrFieldExpr(owned, attrClassName, isKey) {
198
- const card = owned.cardinality;
199
- if (isKey)
200
- return `field(${attrClassName}, Key)`;
201
- if (owned.is_unique)
202
- return `field(${attrClassName}, Unique)`;
203
- // Ordered list attribute: field(Attr).ordered() or field(Attr).ordered().distinct()
204
- if (owned.ordered) {
205
- const base = `field(${attrClassName}).ordered()`;
206
- return owned.distinct ? `${base}.distinct()` : base;
207
- }
208
- if (card === null || (0, cardinality_js_1.isCardOptionalSingle)(card))
209
- return `field(${attrClassName}).optional()`;
210
- if ((0, cardinality_js_1.isCardMulti)(card)) {
211
- const maxStr = card.max === null ? "null" : String(card.max);
212
- return `field(${attrClassName}).list(Card(${card.min}, ${maxStr}))`;
213
- }
214
- if ((0, cardinality_js_1.isCardRequired)(card) && (0, cardinality_js_1.isCardSingle)(card))
215
- return `field(${attrClassName})`;
216
- return `field(${attrClassName}).optional()`;
217
- }
218
- // ---------------------------------------------------------------------------
219
- // Main renderer
220
- // ---------------------------------------------------------------------------
221
- /**
222
- * Render the complete `relations.ts` source text from the parsed schema.
223
- *
224
- * Each relation emits:
225
- * export class <ClassName> extends Relation("<name>", { <fields> }) {}
226
- *
227
- * Role keys = toFieldName(role.name).
228
- * Attr keys = toFieldName(attr.name).
229
- * Player names = toClassName(entityName).
230
- *
231
- * Imports: `@type-bridge/node` for factory symbols; `./attributes.js` for
232
- * attribute classes; `./entities.js` for player entity classes.
233
- */
234
- function renderRelations(schema, options) {
235
- const sortedNames = topologicalSortRelations(schema);
236
- // Pre-compute class name maps
237
- const attrClassMap = new Map();
238
- for (const name of Object.keys(schema.attributes)) {
239
- attrClassMap.set(name, (0, naming_js_1.toClassName)(name));
240
- }
241
- const entityClassMap = new Map();
242
- for (const name of Object.keys(schema.entities)) {
243
- entityClassMap.set(name, (0, naming_js_1.toClassName)(name));
244
- }
245
- const relationClassMap = new Map();
246
- for (const name of Object.keys(schema.relations)) {
247
- relationClassMap.set(name, (0, naming_js_1.toClassName)(name));
248
- }
249
- // Determine which factory symbols are needed
250
- const needsCard = needsCardImport(schema);
251
- const needsKey = needsKeyImport(schema, options);
252
- const needsUnique = needsUniqueImport(schema);
253
- const needsTypeFlags = needsTypeFlagsImport(schema);
254
- const needsOrdered = needsOrderedImport(schema);
255
- const needsDistinct = needsDistinctImport(schema);
256
- const factoryImports = ["Relation", "role", "field"];
257
- if (needsCard)
258
- factoryImports.push("Card");
259
- if (needsKey)
260
- factoryImports.push("Key");
261
- if (needsUnique)
262
- factoryImports.push("Unique");
263
- if (needsTypeFlags)
264
- factoryImports.push("TypeFlags");
265
- if (needsOrdered)
266
- factoryImports.push("Ordered");
267
- if (needsDistinct)
268
- factoryImports.push("Distinct");
269
- factoryImports.sort();
270
- // Collect which attribute + entity class names are referenced (for imports)
271
- const referencedAttrClasses = new Set();
272
- const referencedEntityClasses = new Set();
273
- // Two-pass: collect all referenced classes first
274
- for (const relName of sortedNames) {
275
- const relation = schema.relations[relName];
276
- if (!relation)
277
- continue;
278
- // Parent-owned roles (skip inherited, same as Python)
279
- const parentRoleNames = new Set();
280
- if (relation.parent && schema.relations[relation.parent]) {
281
- for (const r of schema.relations[relation.parent].roles) {
282
- parentRoleNames.add(r.name);
283
- }
284
- }
285
- // Roles
286
- for (const role of relation.roles) {
287
- if (parentRoleNames.has(role.name) && !role.overrides)
288
- continue;
289
- const players = minimalRolePlayers(schema, relName, role.name);
290
- for (const p of players) {
291
- const cls = entityClassMap.get(p);
292
- if (cls)
293
- referencedEntityClasses.add(cls);
294
- }
295
- }
296
- // Attributes (only own, not inherited)
297
- const parentOwns = new Set();
298
- if (relation.parent && schema.relations[relation.parent]) {
299
- for (const o of schema.relations[relation.parent].owns) {
300
- parentOwns.add(o.name);
301
- }
302
- }
303
- for (const owned of relation.owns) {
304
- if (parentOwns.has(owned.name))
305
- continue;
306
- const cls = attrClassMap.get(owned.name);
307
- if (cls)
308
- referencedAttrClasses.add(cls);
309
- }
310
- }
311
- // Build import lines
312
- const lines = [
313
- `import { ${factoryImports.join(", ")} } from "@type-bridge/node";`,
314
- ];
315
- const sortedAttrImports = [...referencedAttrClasses].sort();
316
- if (sortedAttrImports.length > 0) {
317
- lines.push(`import { ${sortedAttrImports.join(", ")} } from "./attributes.js";`);
318
- }
319
- const sortedEntityImports = [...referencedEntityClasses].sort();
320
- if (sortedEntityImports.length > 0) {
321
- lines.push(`import { ${sortedEntityImports.join(", ")} } from "./entities.js";`);
322
- }
323
- lines.push(``);
324
- // Emit each relation class
325
- for (const relName of sortedNames) {
326
- const relation = schema.relations[relName];
327
- if (!relation)
328
- continue;
329
- const className = relationClassMap.get(relName) ?? (0, naming_js_1.toClassName)(relName);
330
- // First argument
331
- let firstArg;
332
- if (relation.is_abstract) {
333
- firstArg = `TypeFlags({ name: "${relName}", abstract: true })`;
334
- }
335
- else {
336
- firstArg = `"${relName}"`;
337
- }
338
- // Third argument: { parent: ParentClass }
339
- const parentClassName = relation.parent ? relationClassMap.get(relation.parent) : null;
340
- const thirdArg = parentClassName ? `, { parent: ${parentClassName} }` : "";
341
- // Collect parent-owned role names + attr names (skip inherited)
342
- const parentRoleNames = new Set();
343
- const parentOwns = new Set();
344
- if (relation.parent && schema.relations[relation.parent]) {
345
- const parentRel = schema.relations[relation.parent];
346
- for (const r of parentRel.roles) {
347
- parentRoleNames.add(r.name);
348
- }
349
- for (const o of parentRel.owns) {
350
- parentOwns.add(o.name);
351
- }
352
- }
353
- // Build field entries: roles first, then attrs (mirror Python relation template order)
354
- const fieldEntries = [];
355
- // Role fields
356
- for (const roleSpec of relation.roles) {
357
- if (parentRoleNames.has(roleSpec.name) && !roleSpec.overrides)
358
- continue;
359
- const players = minimalRolePlayers(schema, relName, roleSpec.name);
360
- if (players.length === 0)
361
- continue;
362
- const playerClassRefs = players.map((p) => entityClassMap.get(p) ?? (0, naming_js_1.toClassName)(p));
363
- const roleKey = (0, naming_js_1.toFieldName)(roleSpec.name);
364
- const playsCardinality = playsCardinalityForRole(schema, relName, roleSpec.name, players);
365
- const roleCall = renderRoleCall(playerClassRefs, roleSpec.cardinality, playsCardinality, roleSpec.overrides, roleSpec.is_abstract, roleSpec.ordered, roleSpec.distinct);
366
- fieldEntries.push(` ${roleKey}: ${roleCall},`);
367
- }
368
- // Attribute fields (own only, in owns_order)
369
- const ownLocalAttrs = relation.owns_order.filter((n) => !parentOwns.has(n));
370
- for (const attrName of ownLocalAttrs) {
371
- const owned = relation.owns.find((o) => o.name === attrName);
372
- if (!owned)
373
- continue;
374
- const attrClass = attrClassMap.get(attrName);
375
- if (!attrClass)
376
- continue;
377
- const fieldKey = (0, naming_js_1.toFieldName)(attrName);
378
- const isKey = (0, naming_js_1.isKeyAttribute)(attrName, owned.is_key, options);
379
- const fieldExpr = renderAttrFieldExpr(owned, attrClass, isKey);
380
- fieldEntries.push(` ${fieldKey}: ${fieldExpr},`);
381
- }
382
- if (fieldEntries.length === 0) {
383
- lines.push(`export class ${className} extends Relation(${firstArg}, {}${thirdArg}) {}`);
384
- }
385
- else {
386
- lines.push(`export class ${className} extends Relation(${firstArg}, {`);
387
- for (const entry of fieldEntries) {
388
- lines.push(entry);
389
- }
390
- lines.push(`}${thirdArg}) {}`);
391
- }
392
- lines.push(``);
393
- }
394
- return lines.join("\n");
395
- }
Binary file