@type-bridge/node 1.5.6 → 1.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/model.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Attribute } from "./attribute.js";
2
2
  import type { ValueType } from "./index.js";
3
- import type { AttributeSchemaEntry, EntityDescriptor, RelationDescriptor } from "./index.js";
3
+ import type { Annotation, AttributeSchemaEntry, EntityDescriptor, RelationDescriptor } from "./index.js";
4
4
  import { type CardSpec, type FlagInput, type ResolvedTypeFlags } from "./flags.js";
5
5
  import { type IidBearing } from "./iid.js";
6
6
  import { type ManagerConnection, type TypedEntityManager, type TypedRelationManager } from "./manager.js";
@@ -13,7 +13,12 @@ export type AttributeClass = (new (value: never) => Attribute<unknown, string>)
13
13
  type ModelClassLike = (new (values: never) => object) & {
14
14
  readonly typeName: string;
15
15
  };
16
+ declare const modelClassBrand: unique symbol;
17
+ declare const modelOwnerBrand: unique symbol;
16
18
  type ModelToken = string | ModelClassLike;
19
+ type ModelDependencyClass = ModelClassLike & {
20
+ readonly schema: Record<string, SchemaSpec>;
21
+ };
17
22
  /**
18
23
  * A model class that also exposes its schema, used as a parent reference.
19
24
  * The schema constraint lets `Entity()` / `Relation()` merge parent fields into
@@ -29,6 +34,11 @@ export type ParentModelClass<ParentSchema extends Record<string, SchemaSpec> = R
29
34
  export interface ParentOption<ParentSchema extends Record<string, SchemaSpec>> {
30
35
  readonly parent: ParentModelClass<ParentSchema>;
31
36
  }
37
+ type OwnerBrandedParentOption<ParentSchema extends Record<string, SchemaSpec>, ParentOwners extends string> = Readonly<{
38
+ parent: ParentModelClass<ParentSchema> & {
39
+ readonly [modelClassBrand]: ParentOwners;
40
+ };
41
+ }>;
32
42
  /**
33
43
  * Merge two schema records: parent fields followed by child-local fields.
34
44
  * Child keys shadow parent keys when both declare the same field name.
@@ -56,6 +66,9 @@ export declare class FieldSpec<Attr extends AttributeClass, Optional extends boo
56
66
  * when optional, `Attr[]` when required.
57
67
  */
58
68
  list<const Min extends number, const Max extends number | null>(card: CardSpec<Min, Max>): ListFieldSpec<Attr, Min extends 0 ? true : false>;
69
+ /** Declare an ordered TypeDB list (`owns attr[]`), optionally with a card. */
70
+ ordered(): ListFieldSpec<Attr, Optional>;
71
+ ordered<const Min extends number, const Max extends number | null>(card: CardSpec<Min, Max>): ListFieldSpec<Attr, Min extends 0 ? true : false>;
59
72
  }
60
73
  /**
61
74
  * A declared multi-value (list) owned-attribute field. Produced by
@@ -68,8 +81,8 @@ export declare class FieldSpec<Attr extends AttributeClass, Optional extends boo
68
81
  export declare class ListFieldSpec<Attr extends AttributeClass, Optional extends boolean = false> {
69
82
  readonly attrType: Attr;
70
83
  readonly kind = "list-field";
71
- /** Explicit cardinality `[min, max | null]`. Always present for list fields. */
72
- readonly card: [number, number | null];
84
+ /** Explicit cardinality `[min, max | null]`, or null for bare ordered lists. */
85
+ readonly card: [number, number | null] | null;
73
86
  readonly isOptional: Optional;
74
87
  /** True when the parent FieldSpec carried the `Ordered` flag. A multi-value
75
88
  * `Card` field is a set, not a TypeDB list: only the `Ordered` flag makes
@@ -77,7 +90,15 @@ export declare class ListFieldSpec<Attr extends AttributeClass, Optional extends
77
90
  readonly isOrdered: boolean;
78
91
  /** True when the parent FieldSpec carried the `Distinct` flag. */
79
92
  readonly isDistinct: boolean;
80
- constructor(attrType: Attr, cardSpec: CardSpec, isOrdered?: boolean, isDistinct?: boolean);
93
+ /** TypeDB 3.12+ `@doc("...")` from the parent FieldSpec's flags. */
94
+ readonly doc: string | null;
95
+ /** TypeDB 3.12+ `@meta` annotations from the parent FieldSpec's flags. */
96
+ readonly meta: Record<string, string>;
97
+ /** Non-cardinality annotations retained from the parent field flags. */
98
+ readonly annotations: readonly Annotation[];
99
+ constructor(attrType: Attr, cardSpec: CardSpec | null, isOrdered?: boolean, isDistinct?: boolean, doc?: string | null, meta?: Record<string, string>, annotations?: readonly Annotation[], optional?: Optional | null);
100
+ /** Add `@distinct` to an ordered list while preserving its value shape. */
101
+ distinct(): ListFieldSpec<Attr, Optional>;
81
102
  }
82
103
  /**
83
104
  * A declared relation role: its permitted player model(s), optional
@@ -105,14 +126,25 @@ export declare class RoleSpec<Players extends readonly ModelToken[]> {
105
126
  readonly ordered: boolean;
106
127
  /** When ``true``, emits ``@distinct`` on the relates clause. Requires ``ordered``. */
107
128
  readonly distinct: boolean;
108
- constructor(players: Players, cardinality?: CardSpec | null, playsCardinality?: CardSpec | null, overrides?: string, isAbstract?: boolean, ordered?: boolean, distinct?: boolean);
129
+ /** TypeDB 3.12+ `@doc("...")` documentation for the relates clause. */
130
+ readonly doc: string | null;
131
+ /** TypeDB 3.12+ `@meta("key", "value")` annotations for the relates clause. */
132
+ readonly meta: Record<string, string>;
133
+ constructor(players: Players, cardinality?: CardSpec | null, playsCardinality?: CardSpec | null, overrides?: string, isAbstract?: boolean, ordered?: boolean, distinct?: boolean, doc?: string | null, meta?: Record<string, string>);
109
134
  }
110
135
  export type SchemaSpec = FieldSpec<AttributeClass, boolean> | ListFieldSpec<AttributeClass, boolean> | RoleSpec<readonly ModelToken[]>;
111
136
  export type EntitySchema = Record<string, FieldSpec<AttributeClass, boolean> | ListFieldSpec<AttributeClass, boolean>>;
112
137
  export type RelationSchema = Record<string, SchemaSpec>;
138
+ /** Value accepted for one model-constructor field. */
113
139
  export type FieldValue<Spec> = Spec extends ListFieldSpec<infer Attr, boolean> ? InstanceType<Attr>[] : Spec extends FieldSpec<infer Attr, boolean> ? InstanceType<Attr> : Spec extends RoleSpec<infer Players> ? RoleValue<Players> : never;
140
+ type MaterializedFieldValue<Spec> = Spec extends RoleSpec<infer Players> ? MaterializedRoleValue<Players> : FieldValue<Spec>;
141
+ /**
142
+ * Fields exposed by a materialized model. Relation-valued role players are
143
+ * shallow: their IID and attributes are present, while their own role fields
144
+ * are explicitly `undefined` to prevent recursive graph hydration.
145
+ */
114
146
  export type InstanceFields<Schema extends Record<string, SchemaSpec>> = {
115
- readonly [Key in keyof Schema]: Schema[Key] extends FieldSpec<AttributeClass, true> | ListFieldSpec<AttributeClass, true> ? FieldValue<Schema[Key]> | undefined : FieldValue<Schema[Key]>;
147
+ readonly [Key in keyof Schema]: Schema[Key] extends FieldSpec<AttributeClass, true> | ListFieldSpec<AttributeClass, true> ? MaterializedFieldValue<Schema[Key]> | undefined : MaterializedFieldValue<Schema[Key]>;
116
148
  };
117
149
  /**
118
150
  * The plain primitive value corresponding to a schema field spec, used as the
@@ -157,6 +189,17 @@ type OptionalKeys<Schema extends Record<string, SchemaSpec>> = {
157
189
  type RequiredKeys<Schema extends Record<string, SchemaSpec>> = Exclude<keyof Schema, OptionalKeys<Schema>>;
158
190
  type RoleValue<Players extends readonly ModelToken[]> = Players extends readonly [] ? undefined : RolePlayerInstance<Players[number]> | readonly RolePlayerInstance<Players[number]>[];
159
191
  type RolePlayerInstance<Token> = Token extends string ? object : Token extends new (values: never) => infer Instance ? Instance : never;
192
+ type MaterializedRoleValue<Players extends readonly ModelToken[]> = Players extends readonly [] ? undefined : MaterializedRolePlayerInstance<Players[number]> | readonly MaterializedRolePlayerInstance<Players[number]>[];
193
+ type MaterializedRolePlayerInstance<Token> = Token extends string ? object : Token extends (new (values: never) => infer Instance) & {
194
+ readonly schema: infer Schema extends Record<string, SchemaSpec>;
195
+ descriptor(): infer Descriptor;
196
+ } ? Descriptor extends RelationDescriptor ? ShallowRelationInstance<Instance, Schema> : Instance : never;
197
+ type RelationRoleKeys<Schema extends Record<string, SchemaSpec>> = {
198
+ [Key in keyof Schema]: Schema[Key] extends RoleSpec<readonly ModelToken[]> ? Key : never;
199
+ }[keyof Schema];
200
+ type ShallowRelationInstance<Instance, Schema extends Record<string, SchemaSpec>> = Omit<Instance, RelationRoleKeys<Schema>> & {
201
+ readonly [Key in RelationRoleKeys<Schema>]: undefined;
202
+ };
160
203
  /**
161
204
  * The canonical hydrated-instance type for a model schema. This is the single
162
205
  * source of truth for what `class X extends Entity(...) {}` produces AND what a
@@ -203,6 +246,22 @@ export type ModelClass<Schema extends Record<string, SchemaSpec>, Descriptor ext
203
246
  fromDict(data: InstanceDict<Schema>): ModelInstance<Schema>;
204
247
  manager(db: ManagerConnection): Descriptor extends EntityDescriptor ? TypedEntityManager<ModelInstance<Schema>> : TypedRelationManager<ModelInstance<Schema>>;
205
248
  };
249
+ type OwnerBrandedModelInstance<Schema extends Record<string, SchemaSpec>, Owners extends string> = ModelInstance<Schema> & {
250
+ readonly [modelOwnerBrand]: Owners;
251
+ };
252
+ type OwnerBrandedModelClass<Schema extends Record<string, SchemaSpec>, Descriptor extends EntityDescriptor | RelationDescriptor, TypeName extends string = string, Owners extends string = TypeName> = (new (values: ConstructorInput<Schema>) => OwnerBrandedModelInstance<Schema, Owners>) & {
253
+ readonly typeName: TypeName;
254
+ readonly [modelClassBrand]: Owners;
255
+ readonly schema: Schema;
256
+ readonly flags: ResolvedTypeFlags;
257
+ descriptor(): Descriptor;
258
+ fromDict(data: InstanceDict<Schema>): OwnerBrandedModelInstance<Schema, Owners>;
259
+ manager(db: ManagerConnection): Descriptor extends EntityDescriptor ? TypedEntityManager<OwnerBrandedModelInstance<Schema, Owners>> : TypedRelationManager<OwnerBrandedModelInstance<Schema, Owners>>;
260
+ };
261
+ /** Return the nominal declaring-type lineage carried by a typed model instance. */
262
+ export type ModelOwnerToken<Model> = Model extends {
263
+ readonly [modelOwnerBrand]: infer Owners extends string;
264
+ } ? Owners : never;
206
265
  /** Declare an owned-attribute field on a model schema, with optional flags. */
207
266
  export declare function field<Attr extends AttributeClass>(attrType: Attr, ...flags: FlagInput[]): FieldSpec<Attr, false>;
208
267
  /**
@@ -227,8 +286,12 @@ export declare function role<const Players extends readonly [ModelToken, ...Mode
227
286
  * `owned_attributes` (parent attrs re-listed, then child-local attrs). Inherited
228
287
  * fields are accessible on the child instance with the parent's attribute brand.
229
288
  */
230
- export declare function Entity<const Schema extends EntitySchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema): ModelClass<Schema, EntityDescriptor>;
231
- export declare function Entity<const ParentSchema extends EntitySchema, const Schema extends EntitySchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema, options: ParentOption<ParentSchema>): ModelClass<MergedSchema<ParentSchema, Schema>, EntityDescriptor>;
289
+ export declare function Entity<const TypeName extends string, const Schema extends EntitySchema>(typeNameOrFlags: TypeName, schema: Schema): OwnerBrandedModelClass<Schema, EntityDescriptor, TypeName>;
290
+ export declare function Entity<const TypeName extends string, const Schema extends EntitySchema>(typeNameOrFlags: ResolvedTypeFlags<TypeName>, schema: Schema): OwnerBrandedModelClass<Schema, EntityDescriptor, TypeName>;
291
+ export declare function Entity<const Schema extends EntitySchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema): OwnerBrandedModelClass<Schema, EntityDescriptor>;
292
+ export declare function Entity<const TypeName extends string, const ParentSchema extends EntitySchema, const ParentOwners extends string, const Schema extends EntitySchema>(typeNameOrFlags: TypeName, schema: Schema, options: OwnerBrandedParentOption<ParentSchema, ParentOwners>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, EntityDescriptor, TypeName, TypeName | ParentOwners>;
293
+ export declare function Entity<const TypeName extends string, const ParentSchema extends EntitySchema, const ParentOwners extends string, const Schema extends EntitySchema>(typeNameOrFlags: ResolvedTypeFlags<TypeName>, schema: Schema, options: OwnerBrandedParentOption<ParentSchema, ParentOwners>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, EntityDescriptor, TypeName, TypeName | ParentOwners>;
294
+ export declare function Entity<const ParentSchema extends EntitySchema, const Schema extends EntitySchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema, options: ParentOption<ParentSchema>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, EntityDescriptor>;
232
295
  /**
233
296
  * Build a hard-typed relation base class. Like `Entity`, but the schema may also
234
297
  * contain `role(...)` specs, which are emitted as `roles[*]` in the descriptor.
@@ -240,10 +303,18 @@ export declare function Entity<const ParentSchema extends EntitySchema, const Sc
240
303
  * any parent role whose name appears as the `overrides` target of a child role.
241
304
  * This mirrors the Python descriptor contract (see `internals.md`, "Descriptor Contract").
242
305
  */
243
- export declare function Relation<const Schema extends RelationSchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema): ModelClass<Schema, RelationDescriptor>;
244
- export declare function Relation<const ParentSchema extends RelationSchema, const Schema extends RelationSchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema, options: ParentOption<ParentSchema>): ModelClass<MergedSchema<ParentSchema, Schema>, RelationDescriptor>;
306
+ export declare function Relation<const TypeName extends string, const Schema extends RelationSchema>(typeNameOrFlags: TypeName, schema: Schema): OwnerBrandedModelClass<Schema, RelationDescriptor, TypeName>;
307
+ export declare function Relation<const TypeName extends string, const Schema extends RelationSchema>(typeNameOrFlags: ResolvedTypeFlags<TypeName>, schema: Schema): OwnerBrandedModelClass<Schema, RelationDescriptor, TypeName>;
308
+ export declare function Relation<const Schema extends RelationSchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema): OwnerBrandedModelClass<Schema, RelationDescriptor>;
309
+ export declare function Relation<const TypeName extends string, const ParentSchema extends RelationSchema, const ParentOwners extends string, const Schema extends RelationSchema>(typeNameOrFlags: TypeName, schema: Schema, options: OwnerBrandedParentOption<ParentSchema, ParentOwners>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, RelationDescriptor, TypeName, TypeName | ParentOwners>;
310
+ export declare function Relation<const TypeName extends string, const ParentSchema extends RelationSchema, const ParentOwners extends string, const Schema extends RelationSchema>(typeNameOrFlags: ResolvedTypeFlags<TypeName>, schema: Schema, options: OwnerBrandedParentOption<ParentSchema, ParentOwners>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, RelationDescriptor, TypeName, TypeName | ParentOwners>;
311
+ export declare function Relation<const ParentSchema extends RelationSchema, const Schema extends RelationSchema>(typeNameOrFlags: string | ResolvedTypeFlags, schema: Schema, options: ParentOption<ParentSchema>): OwnerBrandedModelClass<MergedSchema<ParentSchema, Schema>, RelationDescriptor>;
245
312
  type RelatesOnlyRoleOptions = {
246
313
  readonly cardinality?: CardSpec | null;
314
+ /** TypeDB 3.12+ `@doc("...")` documentation for the relates clause. */
315
+ readonly doc?: string | null;
316
+ /** TypeDB 3.12+ `@meta("key", "value")` annotations for the relates clause. */
317
+ readonly meta?: Record<string, string>;
247
318
  readonly playsCardinality?: never;
248
319
  readonly overrides?: string;
249
320
  readonly abstract?: boolean;
@@ -252,10 +323,20 @@ type RelatesOnlyRoleOptions = {
252
323
  };
253
324
  type RoleOptions = {
254
325
  readonly cardinality?: CardSpec | null;
326
+ /** TypeDB 3.12+ `@doc("...")` documentation for the relates clause. */
327
+ readonly doc?: string | null;
328
+ /** TypeDB 3.12+ `@meta("key", "value")` annotations for the relates clause. */
329
+ readonly meta?: Record<string, string>;
255
330
  readonly playsCardinality?: CardSpec | null;
256
331
  readonly overrides?: string;
257
332
  readonly abstract?: boolean;
258
333
  readonly ordered?: boolean;
259
334
  readonly distinct?: boolean;
260
335
  };
336
+ /**
337
+ * @internal Return constructor dependencies needed before registering a model
338
+ * in an owner-aware query session. The constructors themselves stay private to
339
+ * the session; raw string-only role targets cannot provide hydration metadata.
340
+ */
341
+ export declare function modelConstructorDependencies(model: ModelDependencyClass, includeOwnDescendants?: boolean, includeDescendant?: (model: ModelDependencyClass) => boolean): readonly ModelDependencyClass[];
261
342
  export type { IidBearing };
package/dist/model.js CHANGED
@@ -5,11 +5,14 @@ exports.field = field;
5
5
  exports.role = role;
6
6
  exports.Entity = Entity;
7
7
  exports.Relation = Relation;
8
+ exports.modelConstructorDependencies = modelConstructorDependencies;
8
9
  const flags_js_1 = require("./flags.js");
9
10
  const iid_js_1 = require("./iid.js");
10
11
  const manager_js_1 = require("./manager.js");
11
12
  const codec_js_1 = require("./codec.js");
12
13
  const ATTRIBUTE_SCHEMA_METADATA = Symbol.for("@type-bridge/node.attributeSchemaMetadata");
14
+ const modelParents = new WeakMap();
15
+ const modelChildren = new WeakMap();
13
16
  /**
14
17
  * A declared owned-attribute field: the attribute class, its resolved flags, and
15
18
  * whether it is optional. Produced by `field()`; consumed by the model factory to
@@ -38,7 +41,10 @@ class FieldSpec {
38
41
  * when optional, `Attr[]` when required.
39
42
  */
40
43
  list(card) {
41
- return new ListFieldSpec(this.attrType, card, this.flags.isOrdered, this.flags.isDistinct);
44
+ return new ListFieldSpec(this.attrType, card, this.flags.isOrdered, this.flags.isDistinct, this.flags.doc, this.flags.meta, this.flags.annotations);
45
+ }
46
+ ordered(card = null) {
47
+ return new ListFieldSpec(this.attrType, card, true, this.flags.isDistinct, this.flags.doc, this.flags.meta, this.flags.annotations, card === null ? this.isOptional : null);
42
48
  }
43
49
  }
44
50
  exports.FieldSpec = FieldSpec;
@@ -53,7 +59,7 @@ exports.FieldSpec = FieldSpec;
53
59
  class ListFieldSpec {
54
60
  attrType;
55
61
  kind = "list-field";
56
- /** Explicit cardinality `[min, max | null]`. Always present for list fields. */
62
+ /** Explicit cardinality `[min, max | null]`, or null for bare ordered lists. */
57
63
  card;
58
64
  isOptional;
59
65
  /** True when the parent FieldSpec carried the `Ordered` flag. A multi-value
@@ -62,14 +68,35 @@ class ListFieldSpec {
62
68
  isOrdered;
63
69
  /** True when the parent FieldSpec carried the `Distinct` flag. */
64
70
  isDistinct;
65
- constructor(attrType, cardSpec, isOrdered = false, isDistinct = false) {
71
+ /** TypeDB 3.12+ `@doc("...")` from the parent FieldSpec's flags. */
72
+ doc;
73
+ /** TypeDB 3.12+ `@meta` annotations from the parent FieldSpec's flags. */
74
+ meta;
75
+ /** Non-cardinality annotations retained from the parent field flags. */
76
+ annotations;
77
+ constructor(attrType, cardSpec, isOrdered = false, isDistinct = false, doc = null, meta = {}, annotations = [], optional = null) {
66
78
  this.attrType = attrType;
67
- this.card = [cardSpec.min, cardSpec.max];
79
+ this.card = cardSpec === null ? null : [cardSpec.min, cardSpec.max];
68
80
  // A list field is optional when the minimum cardinality is 0, mirroring the
69
81
  // Python `_is_optional` rule: `flags.card_min == 0`.
70
- this.isOptional = (cardSpec.min === 0);
82
+ this.isOptional = (optional ?? (cardSpec === null || cardSpec.min === 0));
71
83
  this.isOrdered = isOrdered;
72
84
  this.isDistinct = isDistinct;
85
+ this.doc = doc;
86
+ this.meta = { ...meta };
87
+ this.annotations = Object.freeze(annotations
88
+ .filter((annotation) => typeof annotation === "string")
89
+ .map(copyAnnotation));
90
+ }
91
+ /** Add `@distinct` to an ordered list while preserving its value shape. */
92
+ distinct() {
93
+ if (!this.isOrdered) {
94
+ throw new TypeError("distinct() requires an ordered list field");
95
+ }
96
+ const cardSpec = this.card === null
97
+ ? null
98
+ : { kind: "card", min: this.card[0], max: this.card[1] };
99
+ return new ListFieldSpec(this.attrType, cardSpec, this.isOrdered, true, this.doc, this.meta, this.annotations, this.isOptional);
73
100
  }
74
101
  }
75
102
  exports.ListFieldSpec = ListFieldSpec;
@@ -99,7 +126,11 @@ class RoleSpec {
99
126
  ordered;
100
127
  /** When ``true``, emits ``@distinct`` on the relates clause. Requires ``ordered``. */
101
128
  distinct;
102
- constructor(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct) {
129
+ /** TypeDB 3.12+ `@doc("...")` documentation for the relates clause. */
130
+ doc;
131
+ /** TypeDB 3.12+ `@meta("key", "value")` annotations for the relates clause. */
132
+ meta;
133
+ constructor(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct, doc, meta) {
103
134
  this.players = players;
104
135
  if (playsCardinality != null && players.length === 0) {
105
136
  throw new TypeError("playsCardinality requires at least one role player");
@@ -114,6 +145,8 @@ class RoleSpec {
114
145
  this.isAbstract = isAbstract ?? false;
115
146
  this.ordered = ordered ?? false;
116
147
  this.distinct = distinct ?? false;
148
+ this.doc = doc ?? null;
149
+ this.meta = { ...(meta ?? {}) };
117
150
  }
118
151
  }
119
152
  exports.RoleSpec = RoleSpec;
@@ -122,8 +155,8 @@ function field(attrType, ...flags) {
122
155
  return new FieldSpec(attrType, flags);
123
156
  }
124
157
  function role(...playersAndOptions) {
125
- const { players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct } = splitRoleArguments(playersAndOptions);
126
- return new RoleSpec(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct);
158
+ const { players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct, doc, meta } = splitRoleArguments(playersAndOptions);
159
+ return new RoleSpec(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct, doc, meta);
127
160
  }
128
161
  function Entity(typeNameOrFlags, schema, options) {
129
162
  return createModelClass(typeNameOrFlags, schema, "entity", options?.parent ?? null);
@@ -251,6 +284,12 @@ function createModelClass(typeNameOrFlags, schema, kind, parent = null) {
251
284
  // descriptors.json `parity-person` is the reference.
252
285
  owned_attributes: ownedAttributes(parentSchema, schema),
253
286
  };
287
+ if (flags.doc != null) {
288
+ descriptor.doc = flags.doc;
289
+ }
290
+ if (Object.keys(flags.meta).length > 0) {
291
+ descriptor.meta = { ...flags.meta };
292
+ }
254
293
  attachAttributeSchemaMetadata(descriptor, parentSchema, schema);
255
294
  if (kind === "entity") {
256
295
  return descriptor;
@@ -279,8 +318,91 @@ function createModelClass(typeNameOrFlags, schema, kind, parent = null) {
279
318
  return (0, manager_js_1.relationManagerFor)(this, db);
280
319
  }
281
320
  }
321
+ modelParents.set(TypedModel, parent);
282
322
  return TypedModel;
283
323
  }
324
+ /**
325
+ * @internal Return constructor dependencies needed before registering a model
326
+ * in an owner-aware query session. The constructors themselves stay private to
327
+ * the session; raw string-only role targets cannot provide hydration metadata.
328
+ */
329
+ function modelConstructorDependencies(model, includeOwnDescendants = false, includeDescendant = () => true) {
330
+ observeModelConstructor(model);
331
+ const dependencies = [];
332
+ const seen = new Set();
333
+ const append = (dependency) => {
334
+ if (dependency !== model && !seen.has(dependency)) {
335
+ seen.add(dependency);
336
+ dependencies.push(dependency);
337
+ }
338
+ };
339
+ const appendDescendants = (owner) => {
340
+ const pending = [...(modelChildren.get(owner) ?? [])];
341
+ const visited = new Set();
342
+ while (pending.length > 0) {
343
+ const descendant = pending.shift();
344
+ if (visited.has(descendant) || descendant === model) {
345
+ continue;
346
+ }
347
+ visited.add(descendant);
348
+ if (includeDescendant(descendant)) {
349
+ append(descendant);
350
+ }
351
+ pending.push(...(modelChildren.get(descendant) ?? []));
352
+ }
353
+ };
354
+ if (includeOwnDescendants) {
355
+ appendDescendants(model);
356
+ }
357
+ const parent = modelParent(model);
358
+ if (parent !== undefined && parent !== null) {
359
+ append(parent);
360
+ }
361
+ for (const spec of Object.values(model.schema)) {
362
+ if (!(spec instanceof RoleSpec)) {
363
+ continue;
364
+ }
365
+ for (const player of spec.players) {
366
+ if (typeof player !== "string") {
367
+ const constructor = player;
368
+ observeModelConstructor(constructor);
369
+ append(constructor);
370
+ // A declared base player can legally hydrate as any already-loaded
371
+ // concrete subtype. Register those exact constructors up front rather
372
+ // than falling back to the declared base at materialization time.
373
+ appendDescendants(constructor);
374
+ }
375
+ }
376
+ }
377
+ return Object.freeze(dependencies);
378
+ }
379
+ function observeModelConstructor(model) {
380
+ const factory = modelFactory(model);
381
+ if (factory === null || factory === model) {
382
+ return;
383
+ }
384
+ const parent = modelParents.get(factory);
385
+ if (parent === undefined || parent === null) {
386
+ return;
387
+ }
388
+ const children = modelChildren.get(parent) ?? new Set();
389
+ children.add(model);
390
+ modelChildren.set(parent, children);
391
+ }
392
+ function modelParent(model) {
393
+ const factory = modelFactory(model);
394
+ return factory === null ? undefined : modelParents.get(factory);
395
+ }
396
+ function modelFactory(model) {
397
+ let candidate = model;
398
+ while (candidate !== null) {
399
+ if (modelParents.has(candidate)) {
400
+ return candidate;
401
+ }
402
+ candidate = Object.getPrototypeOf(candidate);
403
+ }
404
+ return null;
405
+ }
284
406
  /**
285
407
  * Emit the full flattened `owned_attributes` list for a descriptor.
286
408
  *
@@ -327,12 +449,14 @@ function ownedAttributeEntry(fieldName, spec) {
327
449
  if (spec instanceof ListFieldSpec) {
328
450
  // Multi-value list field: emit the explicit Card annotation unconditionally.
329
451
  // is_optional mirrors Python's `_is_optional`: card_min == 0.
330
- const cardAnnotation = { Card: [spec.card[0], spec.card[1]] };
331
- const annotations = [cardAnnotation];
452
+ const annotations = spec.annotations.map(copyAnnotation);
453
+ if (spec.card !== null) {
454
+ annotations.push({ Card: [spec.card[0], spec.card[1]] });
455
+ }
332
456
  if (spec.isDistinct) {
333
457
  annotations.push("Distinct");
334
458
  }
335
- return {
459
+ const entry = {
336
460
  field_name: fieldName,
337
461
  attr_name: spec.attrType.attrName,
338
462
  value_type: spec.attrType.valueType,
@@ -340,9 +464,16 @@ function ownedAttributeEntry(fieldName, spec) {
340
464
  is_optional: spec.isOptional,
341
465
  is_ordered: spec.isOrdered,
342
466
  };
467
+ if (spec.doc != null) {
468
+ entry.doc = spec.doc;
469
+ }
470
+ if (Object.keys(spec.meta).length > 0) {
471
+ entry.meta = { ...spec.meta };
472
+ }
473
+ return entry;
343
474
  }
344
475
  if (spec instanceof FieldSpec) {
345
- return {
476
+ const entry = {
346
477
  field_name: fieldName,
347
478
  attr_name: spec.attrType.attrName,
348
479
  value_type: spec.attrType.valueType,
@@ -350,6 +481,13 @@ function ownedAttributeEntry(fieldName, spec) {
350
481
  is_optional: spec.isOptional,
351
482
  is_ordered: spec.flags.isOrdered,
352
483
  };
484
+ if (spec.flags.doc != null) {
485
+ entry.doc = spec.flags.doc;
486
+ }
487
+ if (Object.keys(spec.flags.meta).length > 0) {
488
+ entry.meta = { ...spec.flags.meta };
489
+ }
490
+ return entry;
353
491
  }
354
492
  // RoleSpec — not an attribute descriptor.
355
493
  return null;
@@ -419,7 +557,7 @@ function roleDescriptors(parentEffectiveRoles, childSchema) {
419
557
  for (const [roleName, spec] of Object.entries(childSchema)) {
420
558
  if (!(spec instanceof RoleSpec))
421
559
  continue;
422
- descriptors.push({
560
+ const roleDescriptor = {
423
561
  role_name: roleName,
424
562
  player_type_names: spec.players.map(typeNameFor),
425
563
  cardinality: spec.cardinality,
@@ -428,7 +566,14 @@ function roleDescriptors(parentEffectiveRoles, childSchema) {
428
566
  is_abstract: spec.isAbstract,
429
567
  ordered: spec.ordered,
430
568
  distinct: spec.distinct,
431
- });
569
+ };
570
+ if (spec.doc != null) {
571
+ roleDescriptor.doc = spec.doc;
572
+ }
573
+ if (Object.keys(spec.meta).length > 0) {
574
+ roleDescriptor.meta = { ...spec.meta };
575
+ }
576
+ descriptors.push(roleDescriptor);
432
577
  }
433
578
  return descriptors;
434
579
  }
@@ -444,7 +589,7 @@ function copyAnnotation(annotation) {
444
589
  }
445
590
  function splitRoleArguments(args) {
446
591
  if (args.length === 0) {
447
- return { players: [], cardinality: null, playsCardinality: null, overrides: undefined, isAbstract: false, ordered: false, distinct: false };
592
+ return { players: [], cardinality: null, playsCardinality: null, overrides: undefined, isAbstract: false, ordered: false, distinct: false, doc: null, meta: {} };
448
593
  }
449
594
  const maybeOptions = args[args.length - 1];
450
595
  if (isRoleOptions(maybeOptions)) {
@@ -456,6 +601,8 @@ function splitRoleArguments(args) {
456
601
  isAbstract: maybeOptions.abstract ?? false,
457
602
  ordered: maybeOptions.ordered ?? false,
458
603
  distinct: maybeOptions.distinct ?? false,
604
+ doc: maybeOptions.doc ?? null,
605
+ meta: { ...(maybeOptions.meta ?? {}) },
459
606
  };
460
607
  }
461
608
  return {
@@ -466,6 +613,8 @@ function splitRoleArguments(args) {
466
613
  isAbstract: false,
467
614
  ordered: false,
468
615
  distinct: false,
616
+ doc: null,
617
+ meta: {},
469
618
  };
470
619
  }
471
620
  // Distinguishes a trailing role-options object from a player token.
@@ -475,7 +624,7 @@ function splitRoleArguments(args) {
475
624
  function isRoleOptions(value) {
476
625
  return (typeof value === "object" &&
477
626
  value !== null &&
478
- ("cardinality" in value || "playsCardinality" in value || "overrides" in value || "abstract" in value || "ordered" in value || "distinct" in value) &&
627
+ ("cardinality" in value || "playsCardinality" in value || "overrides" in value || "abstract" in value || "ordered" in value || "distinct" in value || "doc" in value || "meta" in value) &&
479
628
  !(value instanceof FieldSpec) &&
480
629
  !(value instanceof RoleSpec));
481
630
  }
package/dist/native.d.ts CHANGED
@@ -1,4 +1,107 @@
1
- import type { NativeModule } from "./index.js";
1
+ import type { NativeModule, NativeRustDatabase, NativeRustTransactionContext } from "./index.js";
2
+ type NativeRegistryHandle = InstanceType<NativeModule["NodeDescriptorRegistry"]>;
3
+ type NativeMatchComparison = "equal" | "not_equal" | "less_than" | "less_than_or_equal" | "greater_than" | "greater_than_or_equal" | "contains" | "starts_with" | "ends_with" | "regex";
4
+ type NativeMatchDirection = "ascending" | "descending";
5
+ type NativeMatchMissingOrder = "reject" | "first" | "last";
6
+ type NativeMatchRowCardinality = "exactly_one" | "bounded_many";
7
+ declare const nativeMatchHandleKind: unique symbol;
8
+ interface NativeMatchSessionHandle {
9
+ readonly [nativeMatchHandleKind]: "session";
10
+ exact(typeName: string): NativeMatchBindingHandle;
11
+ subtypes(typeName: string): NativeMatchBindingHandle;
12
+ positional(selections: NativeMatchSelectionHandle[]): NativeMatchShapeHandle;
13
+ named(names: string[], selections: NativeMatchSelectionHandle[]): NativeMatchShapeHandle;
14
+ query(shape: NativeMatchShapeHandle): NativeMatchQueryHandle;
15
+ }
16
+ interface NativeMatchBindingHandle {
17
+ readonly [nativeMatchHandleKind]: "binding";
18
+ field(fieldName: string): NativeMatchFieldHandle;
19
+ fieldOwnedBy(ownerType: string, fieldName: string): NativeMatchFieldHandle;
20
+ role(roleName: string): NativeMatchRoleHandle;
21
+ roleOwnedBy(ownerType: string, roleName: string): NativeMatchRoleHandle;
22
+ one(): NativeMatchSelectionHandle;
23
+ collect(): NativeMatchSelectionHandle;
24
+ }
25
+ interface NativeMatchFieldHandle {
26
+ readonly [nativeMatchHandleKind]: "field";
27
+ compareValueJson(comparison: NativeMatchComparison, valueJson: string): NativeMatchPredicateHandle;
28
+ compareField(comparison: NativeMatchComparison, other: NativeMatchFieldHandle): NativeMatchPredicateHandle;
29
+ order(direction: NativeMatchDirection, missing: NativeMatchMissingOrder): NativeMatchOrderHandle;
30
+ }
31
+ interface NativeMatchRoleHandle {
32
+ readonly [nativeMatchHandleKind]: "role";
33
+ connects(player: NativeMatchBindingHandle): NativeMatchPredicateHandle;
34
+ }
35
+ interface NativeMatchPredicateHandle {
36
+ readonly [nativeMatchHandleKind]: "predicate";
37
+ and(other: NativeMatchPredicateHandle): NativeMatchPredicateHandle;
38
+ or(other: NativeMatchPredicateHandle): NativeMatchPredicateHandle;
39
+ not(): NativeMatchPredicateHandle;
40
+ }
41
+ interface NativeMatchOrderHandle {
42
+ readonly [nativeMatchHandleKind]: "order";
43
+ }
44
+ interface NativeMatchSelectionHandle {
45
+ readonly [nativeMatchHandleKind]: "selection";
46
+ distinct(distinct: boolean): NativeMatchSelectionHandle;
47
+ orderBy(order: NativeMatchOrderHandle): NativeMatchSelectionHandle;
48
+ }
49
+ interface NativeMatchShapeHandle {
50
+ readonly [nativeMatchHandleKind]: "shape";
51
+ }
52
+ interface NativeMatchQueryHandle {
53
+ readonly [nativeMatchHandleKind]: "query";
54
+ addHidden(binding: NativeMatchBindingHandle): NativeMatchQueryHandle;
55
+ wherePredicate(predicate: NativeMatchPredicateHandle): NativeMatchQueryHandle;
56
+ allowCrossJoin(left: NativeMatchBindingHandle, right: NativeMatchBindingHandle): NativeMatchQueryHandle;
57
+ fetchRowsDiagnostic(orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, cardinality: NativeMatchRowCardinality): string;
58
+ executeFetchRowsOwned(database: NativeRustDatabase, orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, cardinality: NativeMatchRowCardinality): NativeValidatedMatchResultHandle;
59
+ executeFetchRowsBorrowed(transaction: NativeRustTransactionContext, orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, cardinality: NativeMatchRowCardinality): NativeValidatedMatchResultHandle;
60
+ executePageByOwned(database: NativeRustDatabase, root: NativeMatchBindingHandle, orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, includeTotal: boolean): NativeValidatedMatchResultHandle;
61
+ executePageByBorrowed(transaction: NativeRustTransactionContext, root: NativeMatchBindingHandle, orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, includeTotal: boolean): NativeValidatedMatchResultHandle;
62
+ executeCountByOwned(database: NativeRustDatabase, root: NativeMatchBindingHandle): NativeValidatedMatchResultHandle;
63
+ executeCountByBorrowed(transaction: NativeRustTransactionContext, root: NativeMatchBindingHandle): NativeValidatedMatchResultHandle;
64
+ executeExistsByOwned(database: NativeRustDatabase, root: NativeMatchBindingHandle): NativeValidatedMatchResultHandle;
65
+ executeExistsByBorrowed(transaction: NativeRustTransactionContext, root: NativeMatchBindingHandle): NativeValidatedMatchResultHandle;
66
+ pageByDiagnostic(root: NativeMatchBindingHandle, orders: NativeMatchOrderHandle[], offset: bigint, limit: bigint, includeTotal: boolean): string;
67
+ countByDiagnostic(root: NativeMatchBindingHandle): string;
68
+ existsByDiagnostic(root: NativeMatchBindingHandle): string;
69
+ }
70
+ interface NativeValidatedMatchResultHandle {
71
+ readonly [nativeMatchHandleKind]: "validated-result";
72
+ outputSlotCount(query: NativeMatchQueryHandle): number;
73
+ outputSlotIsCollection(query: NativeMatchQueryHandle, slotIndex: number): boolean;
74
+ rowCount(query: NativeMatchQueryHandle): number;
75
+ slotCount(query: NativeMatchQueryHandle, rowIndex: number): number;
76
+ outputNames(query: NativeMatchQueryHandle): string[] | null;
77
+ slotThing(query: NativeMatchQueryHandle, rowIndex: number, slotIndex: number): NativeValidatedThingHandle;
78
+ pageEntryCount(query: NativeMatchQueryHandle): number;
79
+ pageSlotCount(query: NativeMatchQueryHandle, entryIndex: number): number;
80
+ pageSlotValueCount(query: NativeMatchQueryHandle, entryIndex: number, slotIndex: number): number;
81
+ pageSlotThing(query: NativeMatchQueryHandle, entryIndex: number, slotIndex: number, valueIndex: number): NativeValidatedThingHandle;
82
+ pageOffset(query: NativeMatchQueryHandle): bigint;
83
+ pageLimit(query: NativeMatchQueryHandle): bigint;
84
+ pageTotal(query: NativeMatchQueryHandle): bigint | null;
85
+ countValue(query: NativeMatchQueryHandle): bigint;
86
+ existsValue(query: NativeMatchQueryHandle): boolean;
87
+ }
88
+ interface NativeValidatedThingHandle {
89
+ readonly [nativeMatchHandleKind]: "validated-thing";
90
+ iid(): string;
91
+ concreteDescriptor(): string;
92
+ thingKind(): "entity" | "relation";
93
+ fieldNames(): string[];
94
+ fieldValuesJson(fieldName: string): string | null;
95
+ roleDataComplete(): boolean;
96
+ roleNames(): string[];
97
+ rolePlayerCount(roleName: string): number;
98
+ rolePlayer(roleName: string, playerIndex: number): NativeValidatedThingHandle;
99
+ }
100
+ interface NativeMatchModule {
101
+ NodeMatchSessionHandle: new (registry: NativeRegistryHandle) => NativeMatchSessionHandle;
102
+ revalidateMatchDiagnostic(registry: NativeRegistryHandle, diagnosticJson: string): string;
103
+ }
104
+ type LoadedNativeModule = NativeModule & NativeMatchModule;
2
105
  /**
3
106
  * Loads and returns the native .node module. The result is cached after the
4
107
  * first successful load; subsequent calls return the same object.
@@ -11,4 +114,5 @@ import type { NativeModule } from "./index.js";
11
114
  *
12
115
  * Throws an actionable error listing all tried paths when no candidate exists.
13
116
  */
14
- export declare function loadNative(): NativeModule;
117
+ export declare function loadNative(): LoadedNativeModule;
118
+ export {};
@@ -0,0 +1,4 @@
1
+ export { QuerySession, type MatchMode, } from "./session.js";
2
+ export type { Page } from "./page.js";
3
+ export { Query, type NamedQueryRow, type PageOptions, type QueryConnection, type QueryRow, type QuerySlotCount, type RowsOptions, type SelectedOutputs, } from "./query.js";
4
+ export { TypedMatchError, TypedReferenceError, references, type AttributeValueCategory, type BoundField, type BoundRole, type BoundVar, type Collected, type FieldRef, type ModelReferences, type Predicate, type QueryModelClass, type QueryOrder, type RoleRef, type Selection, type TypedMatchErrorCategory, type TypedMatchErrorDetail, type TypedMatchErrorPathSegment, } from "./references.js";
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.references = exports.TypedReferenceError = exports.TypedMatchError = exports.Query = exports.QuerySession = void 0;
4
+ var session_js_1 = require("./session.js");
5
+ Object.defineProperty(exports, "QuerySession", { enumerable: true, get: function () { return session_js_1.QuerySession; } });
6
+ var query_js_1 = require("./query.js");
7
+ Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_js_1.Query; } });
8
+ var references_js_1 = require("./references.js");
9
+ Object.defineProperty(exports, "TypedMatchError", { enumerable: true, get: function () { return references_js_1.TypedMatchError; } });
10
+ Object.defineProperty(exports, "TypedReferenceError", { enumerable: true, get: function () { return references_js_1.TypedReferenceError; } });
11
+ Object.defineProperty(exports, "references", { enumerable: true, get: function () { return references_js_1.references; } });