@coasys/ad4m 0.12.0-rc1-dev → 0.12.0-rc1-dev.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.
Files changed (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6044
  3. package/lib/index.js +5977 -6038
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2797
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3247
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -1,248 +1,54 @@
1
1
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- import { PropertyOptions } from "./decorators";
3
- interface JSONSchemaProperty {
4
- type: string | string[];
5
- items?: JSONSchemaProperty;
6
- properties?: {
7
- [key: string]: JSONSchemaProperty;
8
- };
9
- required?: string[];
10
- "x-ad4m"?: {
11
- through?: string;
12
- resolveLanguage?: string;
13
- local?: boolean;
14
- writable?: boolean;
15
- initial?: string;
16
- };
17
- }
18
- interface JSONSchema {
19
- $schema?: string;
20
- title?: string;
21
- $id?: string;
22
- type?: string;
23
- properties?: {
24
- [key: string]: JSONSchemaProperty;
25
- };
26
- required?: string[];
27
- "x-ad4m"?: {
28
- namespace?: string;
29
- className?: string;
30
- };
31
- }
32
- interface JSONSchemaToModelOptions {
33
- name: string;
34
- namespace?: string;
35
- predicateTemplate?: string;
36
- predicateGenerator?: (title: string, property: string) => string;
37
- propertyMapping?: Record<string, string>;
38
- resolveLanguage?: string;
39
- local?: boolean;
40
- propertyOptions?: Record<string, Partial<PropertyOptions>>;
41
- }
42
- type ValueTuple = [name: string, value: any, resolve?: boolean];
43
- type WhereOps = {
44
- not: string | number | boolean | string[] | number[];
45
- between: [number, number];
46
- lt: number;
47
- lte: number;
48
- gt: number;
49
- gte: number;
50
- contains: string | number;
51
- };
52
- type WhereCondition = string | number | boolean | string[] | number[] | {
53
- [K in keyof WhereOps]?: WhereOps[K];
54
- };
55
- type Where = {
56
- [propertyName: string]: WhereCondition;
57
- };
58
- type Order = {
59
- [propertyName: string]: "ASC" | "DESC";
60
- };
61
- export type Query = {
62
- source?: string;
63
- properties?: string[];
64
- collections?: string[];
65
- where?: Where;
66
- order?: Order;
67
- offset?: number;
68
- limit?: number;
69
- count?: boolean;
70
- };
71
- export type AllInstancesResult = {
72
- AllInstances: Ad4mModel[];
73
- TotalCount?: number;
74
- isInit?: boolean;
75
- };
76
- export type ResultsWithTotalCount<T> = {
77
- results: T[];
78
- totalCount?: number;
79
- };
80
- export type PaginationResult<T> = {
81
- results: T[];
82
- totalCount?: number;
83
- pageSize: number;
84
- pageNumber: number;
85
- };
86
- /**
87
- * Metadata for a single property extracted from decorators.
88
- */
89
- export interface PropertyMetadata {
90
- /** The property name */
91
- name: string;
92
- /** The predicate URI (through value) */
93
- predicate: string;
94
- /** Whether the property is required */
95
- required: boolean;
96
- /** Whether the property is writable */
97
- writable: boolean;
98
- /** Initial value if specified */
99
- initial?: string;
100
- /** Language for resolution (e.g., "literal") */
101
- resolveLanguage?: string;
102
- /** Custom Prolog getter code */
103
- prologGetter?: string;
104
- /** Custom Prolog setter code */
105
- prologSetter?: string;
106
- /** Custom SurrealQL getter code */
107
- getter?: string;
108
- /** Whether stored locally only */
109
- local?: boolean;
110
- /** Transform function */
111
- transform?: (value: any) => any;
112
- /** Whether this is a flag property */
113
- flag?: boolean;
114
- }
2
+ import { SHACLShape } from "../shacl/SHACLShape";
3
+ export { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
4
+ export type { MutationContext } from "./mutation";
5
+ export type { Query, Where, Order, WhereCondition, AllInstancesResult, ResultsWithTotalCount, PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata, IncludeMap, SubscribeOptions, Subscription, ParentQuery, ParentQueryByPredicate, ParentQueryByModel, } from "./types";
115
6
  /**
116
- * Metadata for a single collection extracted from decorators.
117
- */
118
- export interface CollectionMetadata {
119
- /** The collection name */
120
- name: string;
121
- /** The predicate URI (through value) */
122
- predicate: string;
123
- /** Filter conditions */
124
- where?: {
125
- isInstance?: any;
126
- prologCondition?: string;
127
- condition?: string;
128
- };
129
- /** Custom SurrealQL getter code */
130
- getter?: string;
131
- /** Whether stored locally only */
132
- local?: boolean;
133
- }
134
- /**
135
- * Complete model metadata extracted from decorators.
136
- */
137
- export interface ModelMetadata {
138
- /** The model class name from @ModelOptions */
139
- className: string;
140
- /** Map of property name to metadata */
141
- properties: Record<string, PropertyMetadata>;
142
- /** Map of collection name to metadata */
143
- collections: Record<string, CollectionMetadata>;
144
- }
145
- /**
146
- * Base class for defining data models in AD4M.
147
- *
148
- * @description
149
- * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
150
- * Each model instance is represented as a subgraph in the perspective, with properties and collections
151
- * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
152
- * instances based on their properties and relationships.
153
- *
154
- * Key concepts:
155
- * - Each model instance has a unique base expression that serves as its identifier
156
- * - Properties are stored as links with predicates defined by the `through` option
157
- * - Collections represent one-to-many relationships as sets of links
158
- * - Queries are translated to Prolog for efficient graph pattern matching
159
- * - Changes are tracked through the perspective's subscription system
7
+ * Options for linking a newly created instance to an existing parent node.
8
+ * Pass as the third argument to `Model.create()`.
160
9
  *
161
10
  * @example
162
- * ```typescript
163
- * // Define a recipe model
164
- * @ModelOptions({ name: "Recipe" })
165
- * class Recipe extends Ad4mModel {
166
- * // Required property with literal value
167
- * @Property({
168
- * through: "recipe://name",
169
- * resolveLanguage: "literal"
170
- * })
171
- * name: string = "";
11
+ * // Field inferred — only one @HasMany on Channel points to Poll
12
+ * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId } })
172
13
  *
173
- * // Optional property with custom initial value
174
- * @Optional({
175
- * through: "recipe://status",
176
- * initial: "recipe://draft"
177
- * })
178
- * status: string = "";
179
- *
180
- * // Read-only computed property
181
- * @ReadOnly({
182
- * through: "recipe://rating",
183
- * getter: `
184
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
185
- * sum_list(Ratings, Sum),
186
- * length(Ratings, Count),
187
- * Value is Sum / Count
188
- * `
189
- * })
190
- * averageRating: number = 0;
191
- *
192
- * // Collection of ingredients
193
- * @Collection({ through: "recipe://ingredient" })
194
- * ingredients: string[] = [];
195
- *
196
- * // Collection of comments that are instances of another model
197
- * @Collection({
198
- * through: "recipe://comment",
199
- * where: { isInstance: Comment }
200
- * })
201
- * comments: Comment[] = [];
202
- * }
203
- *
204
- * // Create and save a new recipe
205
- * const recipe = new Recipe(perspective);
206
- * recipe.name = "Chocolate Cake";
207
- * recipe.ingredients = ["flour", "sugar", "cocoa"];
208
- * await recipe.save();
209
- *
210
- * // Query recipes in different ways
211
- * // Get all recipes
212
- * const allRecipes = await Recipe.findAll(perspective);
213
- *
214
- * // Find recipes with specific criteria
215
- * const desserts = await Recipe.findAll(perspective, {
216
- * where: {
217
- * status: "recipe://published",
218
- * averageRating: { gt: 4 }
219
- * },
220
- * order: { name: "ASC" },
221
- * limit: 10
222
- * });
223
- *
224
- * // Use the fluent query builder
225
- * const popularRecipes = await Recipe.query(perspective)
226
- * .where({ averageRating: { gt: 4.5 } })
227
- * .order({ averageRating: "DESC" })
228
- * .limit(5)
229
- * .get();
14
+ * // Field explicit — needed when multiple @HasMany on the parent point to the same type
15
+ * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId, field: 'featuredPolls' } })
16
+ */
17
+ export type ParentOptions = {
18
+ /** The parent model class (must have a `@HasMany` pointing to this child type). */
19
+ model: typeof Ad4mModel;
20
+ /** The ID of the parent instance. */
21
+ id: string;
22
+ /**
23
+ * The `@HasMany` field on the parent whose predicate is used for the link.
24
+ * Optional when exactly one `@HasMany` on the parent points to this child type.
25
+ */
26
+ field?: string;
27
+ };
28
+ import type { Query, ResultsWithTotalCount, PaginationResult, ModelMetadata, IncludeMap, SubscribeOptions, Subscription } from "./types";
29
+ import type { JSONSchema, JSONSchemaToModelOptions } from "./schema/fromJSONSchema";
30
+ export type { JSONSchema, JSONSchemaToModelOptions, JSONSchemaProperty, } from "./schema/fromJSONSchema";
31
+ import { ModelQueryBuilder } from "./query/ModelQueryBuilder";
32
+ export { ModelQueryBuilder };
33
+ export { buildSurrealQuery, buildSurrealCountQuery, formatSurrealValue, matchesCondition, buildGraphTraversalWhereClause, } from "./query/surrealCompiler";
34
+ export { hydrateInstanceFromLinks, evaluateCustomGetters, normalizeTimestamp, } from "./query/hydration";
35
+ export type { RawLink } from "./query/hydration";
36
+ export type { TransactionContext } from "./transaction";
37
+ /**
38
+ * Base class for all AD4M data models.
230
39
  *
231
- * // Subscribe to real-time updates
232
- * await Recipe.query(perspective)
233
- * .where({ status: "recipe://cooking" })
234
- * .subscribe(recipes => {
235
- * console.log("Currently being cooked:", recipes);
236
- * });
40
+ * Instances are subgraphs in a {@link PerspectiveProxy}; properties and relations
41
+ * map to typed links. Decorators (`@Property`, `@HasMany`, etc.) declare the schema;
42
+ * query helpers (`findAll`, `query`, `subscribe`) run SurrealQL against the
43
+ * perspective's local graph engine.
237
44
  *
238
- * // Paginate results
239
- * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
240
- * .where({ status: "recipe://published" })
241
- * .paginate(10, 1);
242
- * ```
45
+ * See [README.md](./README.md) for a full worked example and decorator reference.
243
46
  */
244
47
  export declare class Ad4mModel {
245
- #private;
48
+ private _id;
49
+ private _perspective;
50
+ /** Tracks whether save() has ever been called on this instance (even in an uncommitted batch). */
51
+ private _savedOnce;
246
52
  author: string;
247
53
  createdAt: any;
248
54
  updatedAt: any;
@@ -253,403 +59,158 @@ export declare class Ad4mModel {
253
59
  * @deprecated Use createdAt instead. This will be removed in a future version.
254
60
  */
255
61
  get timestamp(): any;
256
- /**
257
- * Extracts metadata from decorators for query building.
258
- *
259
- * @description
260
- * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
261
- * and returns it in a structured format that's easier to work with for query builders
262
- * and other systems that need to introspect model structure.
263
- *
264
- * The metadata includes:
265
- * - Class name from @ModelOptions
266
- * - Property metadata (predicates, types, constraints, etc.)
267
- * - Collection metadata (predicates, filters, etc.)
268
- *
269
- * For models created via `fromJSONSchema()`, this method will derive metadata from
270
- * the stored `__properties` and `__collections` structures that were populated during
271
- * the dynamic class creation. If these structures are empty but a JSON schema was
272
- * attached to the class, it can fall back to deriving metadata from that schema.
273
- *
274
- * @returns Structured metadata object containing className, properties, and collections
275
- * @throws Error if the class doesn't have @ModelOptions decorator
276
- *
277
- * @example
278
- * ```typescript
279
- * @ModelOptions({ name: "Recipe" })
280
- * class Recipe extends Ad4mModel {
281
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
282
- * name: string = "";
283
- *
284
- * @Collection({ through: "recipe://ingredient" })
285
- * ingredients: string[] = [];
286
- * }
287
- *
288
- * const metadata = Recipe.getModelMetadata();
289
- * console.log(metadata.className); // "Recipe"
290
- * console.log(metadata.properties.name.predicate); // "recipe://name"
291
- * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
292
- * ```
293
- */
62
+ /** Returns the class name, property predicates, and relation predicates from decorators. */
294
63
  static getModelMetadata(): ModelMetadata;
295
64
  /**
296
- * Constructs a new model instance.
297
- *
298
- * @param perspective - The perspective where this model will be stored
299
- * @param baseExpression - Optional unique identifier for this instance
300
- * @param source - Optional source expression this instance is linked to
301
- *
302
- * @example
303
- * ```typescript
304
- * // Create a new recipe with auto-generated base expression
305
- * const recipe = new Recipe(perspective);
306
- *
307
- * // Create with specific base expression
308
- * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
65
+ * Installs the SHACL/SDNA subject class in `perspective` (idempotent).
309
66
  *
310
- * // Create with source link
311
- * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
312
- * ```
313
- */
314
- constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string);
315
- /**
316
- * Gets the base expression of the subject.
317
- */
318
- get baseExpression(): string;
319
- /**
320
- * Protected getter for the perspective.
321
- * Allows subclasses to access the perspective while keeping it private from external code.
322
- */
323
- protected get perspective(): PerspectiveProxy;
324
- /**
325
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
326
- * @private
327
- */
328
- private getPropertyMetadata;
329
- /**
330
- * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
331
- * @private
332
- */
333
- private getCollectionMetadata;
334
- /**
335
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
336
- * Replaces Prolog query: property_setter(C, key, Setter)
337
- * @private
67
+ * @example `await Promise.all([Post, Comment, Tag].map(M => M.register(perspective)));`
338
68
  */
339
- private generatePropertySetterAction;
69
+ static register(perspective: PerspectiveProxy): Promise<void>;
340
70
  /**
341
- * Generate collection action from metadata (Phase 1: Prolog-free refactor)
342
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
343
- * @private
344
- */
345
- private generateCollectionAction;
346
- static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
347
- private getData;
348
- static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
349
- /**
350
- * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
351
- * @private
352
- */
353
- private static evaluateCustomGettersForInstance;
354
- /**
355
- * Generates a SurrealQL query from a Query object.
356
- *
357
- * @description
358
- * This method translates high-level query parameters into a SurrealQL query string
359
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
360
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
361
- * stored in SurrealDB.
362
- *
363
- * The generated query uses a CTE (Common Table Expression) pattern:
364
- * 1. First, identify candidate base expressions by filtering links based on where conditions
365
- * 2. Then, for each candidate base, resolve properties and collections via subqueries
366
- * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
367
- *
368
- * Key architectural notes:
369
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
370
- * - No SDNA knowledge at the database level
371
- * - Properties are resolved via subqueries that look for links with specific predicates
372
- * - Collections are similar but return multiple values instead of one
373
- * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
374
- *
375
- * @param perspective - The perspective to query (used for metadata extraction)
376
- * @param query - Query parameters (where, order, limit, offset, properties, collections)
377
- * @returns Complete SurrealQL query string ready for execution
71
+ * One-shot factory: constructs, assigns `data`, saves, and returns the new instance.
378
72
  *
379
73
  * @example
380
74
  * ```typescript
381
- * const query = Recipe.queryToSurrealQL(perspective, {
382
- * where: { name: "Pasta", rating: { gt: 4 } },
383
- * order: { timestamp: "DESC" },
384
- * limit: 10
385
- * });
386
- * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
387
- * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
75
+ * const post = await Post.create(perspective, { title: 'Hello', body: 'World' });
388
76
  * ```
389
77
  */
390
- static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
78
+ static create<T extends Ad4mModel>(this: new (perspective: PerspectiveProxy) => T, perspective: PerspectiveProxy, data: Partial<Omit<T, keyof Ad4mModel>>, options?: {
79
+ parent?: ParentOptions;
80
+ batchId?: string;
81
+ }): Promise<T>;
391
82
  /**
392
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
393
- *
394
- * @description
395
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
396
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
83
+ * Fetches the instance, merges `data` into it, then saves.
397
84
  *
398
- * Handles several condition types:
399
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
400
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
401
- * - NOT operators: Use `NOT` prefix
402
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
403
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
85
+ * This is a convenience alternative to the three-step pattern:
86
+ * ```typescript
87
+ * // Before
88
+ * const instance = new Vote(perspective, id);
89
+ * instance.score = newScore;
90
+ * await instance.save();
404
91
  *
405
- * @param metadata - Model metadata containing property predicates
406
- * @param where - Where conditions from the query
407
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
92
+ * // After
93
+ * await Vote.update(perspective, id, { score: newScore });
94
+ * ```
408
95
  *
409
- * @private
96
+ * @param data - Partial set of properties to merge into the stored instance.
97
+ * @param batchId - Optional batch identifier for grouping writes.
98
+ * @returns The updated instance with all fields populated.
410
99
  */
411
- private static buildGraphTraversalWhereClause;
100
+ static update<T extends Ad4mModel>(this: (new (perspective: PerspectiveProxy, id: string) => T) & typeof Ad4mModel, perspective: PerspectiveProxy, id: string, data: Partial<Omit<T, keyof Ad4mModel>>, batchId?: string): Promise<T>;
412
101
  /**
413
- * Builds the WHERE clause for SurrealQL queries.
414
- *
415
- * @description
416
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
417
- * For each property filter, generates a subquery that checks for links with the appropriate
418
- * predicate and target value.
102
+ * Deletes the instance with the given `id` from the perspective.
419
103
  *
420
- * Handles several condition types:
421
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
422
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
423
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
424
- * - gt, gte, lt, lte: comparison operators
425
- * - not: negation (single value or array)
426
- * - between: range check
427
- * - contains: substring/element check (uses SurrealQL CONTAINS)
428
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
429
- *
430
- * All conditions are joined with AND.
104
+ * This is a convenience alternative to:
105
+ * ```typescript
106
+ * // Before
107
+ * const instance = new Poll(perspective, id);
108
+ * await instance.delete();
431
109
  *
432
- * @param metadata - Model metadata containing property predicates
433
- * @param where - Where conditions from the query
434
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
110
+ * // After
111
+ * await Poll.delete(perspective, id);
112
+ * ```
435
113
  *
436
- * @private
114
+ * @param batchId - Optional batch identifier for grouping removals.
437
115
  */
438
- private static buildSurrealWhereClause;
116
+ static delete(perspective: PerspectiveProxy, id: string, batchId?: string): Promise<void>;
439
117
  /**
440
- * Builds the SELECT fields for SurrealQL queries.
441
- *
442
- * @description
443
- * Generates the field list for the SELECT clause, resolving properties and collections
444
- * via subqueries. Each property is fetched with a subquery that finds the link with the
445
- * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
446
- *
447
- * Field types:
448
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
449
- * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
450
- * - Author/Timestamp: Always included to provide metadata about each instance
451
- *
452
- * If properties or collections arrays are provided, only those fields are included.
453
- * Otherwise, all properties/collections from metadata are included.
454
- *
455
- * @param metadata - Model metadata containing property and collection predicates
456
- * @param properties - Optional array of property names to include (default: all)
457
- * @param collections - Optional array of collection names to include (default: all)
458
- * @returns Comma-separated SELECT field list
459
- *
460
- * @private
118
+ * Generates the SHACL shape for this model class.
119
+ * Attached dynamically by the `@Model` decorator.
461
120
  */
462
- private static buildSurrealSelectFields;
121
+ static generateSHACL(): {
122
+ shape: SHACLShape;
123
+ name: string;
124
+ };
125
+ /** @param id - Auto-generated from a random literal if omitted. */
126
+ constructor(perspective: PerspectiveProxy, id?: string);
463
127
  /**
464
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
465
- * Compatible with GROUP BY source queries.
466
- *
467
- * @private
128
+ * The unique identifier (base expression URI) of this instance.
468
129
  */
469
- private static buildSurrealSelectFieldsWithAggregation;
470
- /**
471
- * Formats a value for use in SurrealQL queries.
472
- *
473
- * @description
474
- * Handles different value types:
475
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
476
- * - Numbers/booleans: Converted to string
477
- * - Arrays: Recursively formatted and wrapped in brackets
478
- *
479
- * @param value - The value to format
480
- * @returns Formatted value string ready for SurrealQL
481
- *
482
- * @private
483
- */
484
- private static formatSurrealValue;
485
- static instancesFromPrologResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: AllInstancesResult): Promise<ResultsWithTotalCount<T>>;
130
+ get id(): string;
131
+ /** Read-only perspective access for subclasses. */
132
+ protected get perspective(): PerspectiveProxy;
133
+ /** Builds the context object for all mutation functions. */
134
+ private _mutationContext;
486
135
  /**
487
- * Converts SurrealDB query results to Ad4mModel instances.
136
+ * Generates a SurrealQL query string for this model.
488
137
  *
489
138
  * @param perspective - The perspective context
490
- * @param query - The query parameters used
491
- * @param result - Array of result objects from SurrealDB
492
- * @returns Promise resolving to results with total count
493
- *
494
- * @internal
139
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
140
+ * @returns Complete SurrealQL query string ready for execution
495
141
  */
496
- static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[]): Promise<ResultsWithTotalCount<T>>;
142
+ static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
143
+ /** @internal */
144
+ static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[], _hydrateRelations?: boolean): Promise<ResultsWithTotalCount<T>>;
497
145
  /**
498
- * Checks if a value matches a condition (for post-query filtering).
499
- * @private
146
+ * Internal implementation used by findAll and eager relation hydration.
147
+ * Pass `_hydrateRelations = false` to prevent recursive model hydration (depth guard).
500
148
  */
501
- private static matchesCondition;
149
+ static _findAllInternal<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, _hydrateRelations?: boolean): Promise<T[]>;
502
150
  /**
503
- * Gets all instances of the model in the perspective that match the query params.
504
- *
505
- * @param perspective - The perspective to search in
506
- * @param query - Optional query parameters to filter results
507
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
508
- * @returns Array of matching models
151
+ * Returns all instances matching `query`.
509
152
  *
510
153
  * @example
511
154
  * ```typescript
512
- * // Get all recipes (uses SurrealDB by default)
513
- * const allRecipes = await Recipe.findAll(perspective);
514
- *
515
- * // Get recipes with specific criteria (uses SurrealDB)
516
155
  * const recipes = await Recipe.findAll(perspective, {
517
- * where: {
518
- * name: "Pasta",
519
- * rating: { gt: 4 }
520
- * },
521
- * order: { createdAt: "DESC" },
522
- * limit: 10
156
+ * where: { rating: { gt: 4 } }, order: { createdAt: "DESC" }, limit: 10,
523
157
  * });
524
- *
525
- * // Explicitly use Prolog (legacy, for backward compatibility)
526
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
527
158
  * ```
528
159
  */
529
- static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T[]>;
160
+ static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<T[]>;
530
161
  /**
531
- * Gets all instances with count of total matches without offset & limit applied.
532
- *
533
- * @param perspective - The perspective to search in
534
- * @param query - Optional query parameters to filter results
535
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
536
- * @returns Object containing results array and total count
162
+ * Returns the first matching instance, or `null` if none found.
537
163
  *
538
164
  * @example
539
165
  * ```typescript
540
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
541
- * where: { category: "Dessert" },
542
- * limit: 10
543
- * });
544
- * console.log(`Showing 10 of ${totalCount} dessert recipes`);
545
- *
546
- * // Use Prolog explicitly (legacy)
547
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
166
+ * const post = await TestPost.findOne(perspective, { where: { id: someId } });
548
167
  * ```
549
168
  */
550
- static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<ResultsWithTotalCount<T>>;
169
+ static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<T | null>;
551
170
  /**
552
- * Helper function for pagination with explicit page size and number.
553
- *
554
- * @param perspective - The perspective to search in
555
- * @param pageSize - Number of items per page
556
- * @param pageNumber - Which page to retrieve (1-based)
557
- * @param query - Optional additional query parameters
558
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
559
- * @returns Paginated results with metadata
171
+ * Like `findAll` but also returns the unfiltered total count (useful for pagination UI).
560
172
  *
561
173
  * @example
562
174
  * ```typescript
563
- * const page = await Recipe.paginate(perspective, 10, 1, {
564
- * where: { category: "Main Course" }
565
- * });
566
- * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
567
- *
568
- * // Use Prolog explicitly (legacy)
569
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
175
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, { limit: 10 });
176
+ * console.log(`Showing ${results.length} of ${totalCount}`);
570
177
  * ```
571
178
  */
572
- static paginate<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Query, useSurrealDB?: boolean): Promise<PaginationResult<T>>;
573
- static countQueryToProlog(perspective: PerspectiveProxy, query?: Query, modelClassName?: string | null): Promise<string>;
179
+ static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<ResultsWithTotalCount<T>>;
574
180
  /**
575
- * Generates a SurrealQL COUNT query for the model.
576
- *
577
- * @param perspective - The perspective context
578
- * @param query - Query parameters to filter the count
579
- * @returns SurrealQL COUNT query string
580
- *
581
- * @private
582
- */
583
- static countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
584
- /**
585
- * Gets a count of all matching instances.
586
- *
587
- * @param perspective - The perspective to search in
588
- * @param query - Optional query parameters to filter results
589
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
590
- * @returns Total count of matching entities
181
+ * Fetches a single page of results (`pageNumber` is 1-based).
591
182
  *
592
183
  * @example
593
184
  * ```typescript
594
- * const totalRecipes = await Recipe.count(perspective);
595
- * const activeRecipes = await Recipe.count(perspective, {
596
- * where: { status: "active" }
597
- * });
598
- *
599
- * // Use Prolog explicitly (legacy)
600
- * const countProlog = await Recipe.count(perspective, {}, false);
185
+ * const page = await Recipe.paginate(perspective, 10, 1);
186
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} items`);
601
187
  * ```
602
188
  */
603
- static count(perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): any;
604
- private setProperty;
605
- private setCollectionSetter;
606
- private setCollectionAdder;
607
- private setCollectionRemover;
189
+ static paginate<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Query): Promise<PaginationResult<T>>;
608
190
  /**
609
- * Saves the model instance to the perspective.
610
- * Creates a new instance with the base expression and links it to the source.
191
+ * Generates a SurrealQL COUNT query for this model.
192
+ * @private
193
+ */
194
+ static countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
195
+ /** Returns the count of instances matching `query`. */
196
+ static count(perspective: PerspectiveProxy, query?: Query): Promise<number>;
197
+ /**
198
+ * Persists the instance (create if new, update if existing).
611
199
  *
612
- * @param batchId - Optional batch ID for batch operations
613
- * @throws Will throw if instance creation, linking, or updating fails
200
+ * @param batchId - When provided the caller must call `perspective.commitBatch(batchId)`
614
201
  *
615
202
  * @example
616
203
  * ```typescript
617
204
  * const recipe = new Recipe(perspective);
618
205
  * recipe.name = "Spaghetti";
619
- * recipe.ingredients = ["pasta", "tomato sauce"];
620
- * await recipe.save();
621
- *
622
- * // Or with batch operations:
623
- * const batchId = await perspective.createBatch();
624
- * await recipe.save(batchId);
625
- * await perspective.commitBatch(batchId);
206
+ * await recipe.save(); // create
207
+ * recipe.name = "Bolognese";
208
+ * await recipe.save(); // update (detected automatically)
626
209
  * ```
627
210
  */
628
211
  save(batchId?: string): Promise<void>;
629
- private cleanCopy;
630
- private innerUpdate;
631
- /**
632
- * Updates the model instance's properties and collections.
633
- *
634
- * @param batchId - Optional batch ID for batch operations
635
- * @throws Will throw if property setting or collection updates fail
636
- *
637
- * @example
638
- * ```typescript
639
- * const recipe = await Recipe.findAll(perspective)[0];
640
- * recipe.rating = 5;
641
- * recipe.ingredients.push("garlic");
642
- * await recipe.update();
643
- *
644
- * // Or with batch operations:
645
- * const batchId = await perspective.createBatch();
646
- * await recipe.update(batchId);
647
- * await perspective.commitBatch(batchId);
648
- * ```
649
- */
650
- update(batchId?: string): Promise<void>;
651
212
  /**
652
- * Gets the model instance with all properties and collections populated.
213
+ * Gets the model instance with all properties and relations populated.
653
214
  *
654
215
  * @returns The populated model instance
655
216
  * @throws Will throw if data retrieval fails
@@ -661,414 +222,73 @@ export declare class Ad4mModel {
661
222
  * console.log(recipe.name, recipe.ingredients);
662
223
  * ```
663
224
  */
664
- get(): Promise<this>;
225
+ get(include?: IncludeMap): Promise<this>;
665
226
  /**
666
- * Deletes the model instance from the perspective.
667
- *
668
- * @param batchId - Optional batch ID for batch operations
669
- * @throws Will throw if removal fails
227
+ * Removes this instance from the perspective, including all incoming links
228
+ * that point to it (e.g. parent→child membership links created by
229
+ * `create({ parent: ... })`). This ensures that `findAll({ parent: ... })`
230
+ * will no longer return this instance after deletion.
670
231
  *
671
232
  * @example
672
- * ```typescript
673
- * const recipe = await Recipe.findAll(perspective)[0];
674
- * await recipe.delete();
233
+ * await vote.delete();
675
234
  *
676
- * // Or with batch operations:
677
- * const batchId = await perspective.createBatch();
678
- * await recipe.delete(batchId);
679
- * await perspective.commitBatch(batchId);
680
- * ```
235
+ * @param batchId - Optional batch identifier for grouping removals.
681
236
  */
682
237
  delete(batchId?: string): Promise<void>;
683
238
  /**
684
- * Creates a query builder for fluent query construction.
685
- *
686
- * @param perspective - The perspective to query
687
- * @param query - Optional initial query parameters
688
- * @returns A new query builder instance
239
+ * Returns a fluent query builder for this model.
689
240
  *
690
241
  * @example
691
242
  * ```typescript
692
- * const recipes = await Recipe.query(perspective)
243
+ * const top5 = await Recipe.query(perspective)
693
244
  * .where({ category: "Dessert" })
694
245
  * .order({ rating: "DESC" })
695
246
  * .limit(5)
696
247
  * .run();
697
- *
698
- * // With real-time updates
699
- * await Recipe.query(perspective)
700
- * .where({ status: "cooking" })
701
- * .subscribe(recipes => {
702
- * console.log("Currently cooking:", recipes);
703
- * });
704
248
  * ```
705
249
  */
706
250
  static query<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): ModelQueryBuilder<T>;
707
251
  /**
708
- * Creates an Ad4mModel class from a JSON Schema definition.
709
- *
710
- * @description
711
- * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
712
- * enabling integration with systems that use JSON Schema for type definitions.
713
- *
714
- * The method follows a cascading approach for determining predicates:
715
- * 1. Explicit configuration in options parameter (highest precedence)
716
- * 2. x-ad4m metadata in the JSON Schema
717
- * 3. Inference from schema title and property names
718
- * 4. Error if no namespace can be determined
252
+ * Runs `callback` in an atomic batch; commits on success, aborts + rethrows on failure.
719
253
  *
720
254
  * @example
721
255
  * ```typescript
722
- * // With explicit configuration
723
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
724
- * name: "Person",
725
- * namespace: "person://",
726
- * resolveLanguage: "literal"
256
+ * await Ad4mModel.transaction(perspective, async (tx) => {
257
+ * await post.save(tx.batchId);
258
+ * await comment.save(tx.batchId);
727
259
  * });
728
- *
729
- * // With property mapping
730
- * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
731
- * name: "Contact",
732
- * namespace: "contact://",
733
- * propertyMapping: {
734
- * "name": "foaf://name",
735
- * "email": "foaf://mbox"
736
- * }
737
- * });
738
- *
739
- * // With x-ad4m metadata in schema
740
- * const schema = {
741
- * "title": "Product",
742
- * "x-ad4m": { "namespace": "product://" },
743
- * "properties": {
744
- * "name": {
745
- * "type": "string",
746
- * "x-ad4m": { "through": "product://title" }
747
- * }
748
- * }
749
- * };
750
- * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
751
- * ```
752
- *
753
- * @param schema - JSON Schema definition
754
- * @param options - Configuration options
755
- * @returns Generated Ad4mModel subclass
756
- * @throws Error when namespace cannot be inferred
757
- */
758
- static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
759
- /**
760
- * Determines the namespace for predicates using cascading precedence
761
- */
762
- private static determineNamespace;
763
- /**
764
- * Determines the predicate for a specific property using cascading precedence
765
- */
766
- private static determinePredicate;
767
- /**
768
- * Gets property-specific options using cascading precedence
769
- */
770
- private static getPropertyOption;
771
- /**
772
- * Gets default value for a JSON Schema type
773
- */
774
- private static getDefaultValueForType;
775
- }
776
- /** Query builder for Ad4mModel queries.
777
- * Allows building queries with a fluent interface and either running them once
778
- * or subscribing to updates.
779
- *
780
- * @example
781
- * ```typescript
782
- * const builder = Recipe.query(perspective)
783
- * .where({ category: "Dessert" })
784
- * .order({ rating: "DESC" })
785
- * .limit(10);
786
- *
787
- * // Run once
788
- * const recipes = await builder.run();
789
- *
790
- * // Or subscribe to updates
791
- * await builder.subscribe(recipes => {
792
- * console.log("Updated recipes:", recipes);
793
- * });
794
- * ```
795
- */
796
- export declare class ModelQueryBuilder<T extends Ad4mModel> {
797
- private perspective;
798
- private queryParams;
799
- private modelClassName;
800
- private ctor;
801
- private currentSubscription?;
802
- private useSurrealDBFlag;
803
- constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query);
804
- /**
805
- * Disposes of the current subscription if one exists.
806
- *
807
- * This method:
808
- * 1. Stops the keepalive signals to the subscription
809
- * 2. Unsubscribes from GraphQL subscription updates
810
- * 3. Notifies the backend to clean up subscription resources
811
- * 4. Clears the subscription reference
812
- *
813
- * You should call this method when you're done with a subscription
814
- * to prevent memory leaks and ensure proper cleanup.
815
- */
816
- dispose(): void;
817
- /**
818
- * Adds where conditions to the query.
819
- *
820
- * @param conditions - The conditions to filter by
821
- * @returns The query builder for chaining
822
- *
823
- * @example
824
- * ```typescript
825
- * .where({
826
- * category: "Dessert",
827
- * rating: { gt: 4 },
828
- * tags: ["vegan", "quick"],
829
- * published: true
830
- * })
831
- * ```
832
- */
833
- where(conditions: Where): ModelQueryBuilder<T>;
834
- /**
835
- * Sets the order for the query results.
836
- *
837
- * @param orderBy - The ordering criteria
838
- * @returns The query builder for chaining
839
- *
840
- * @example
841
- * ```typescript
842
- * .order({ createdAt: "DESC" })
843
- * ```
844
- */
845
- order(orderBy: Order): ModelQueryBuilder<T>;
846
- /**
847
- * Sets the maximum number of results to return.
848
- *
849
- * @param limit - Maximum number of results
850
- * @returns The query builder for chaining
851
- *
852
- * @example
853
- * ```typescript
854
- * .limit(10)
855
- * ```
856
- */
857
- limit(limit: number): ModelQueryBuilder<T>;
858
- /**
859
- * Sets the number of results to skip.
860
- *
861
- * @param offset - Number of results to skip
862
- * @returns The query builder for chaining
863
- *
864
- * @example
865
- * ```typescript
866
- * .offset(20) // Skip first 20 results
867
- * ```
868
- */
869
- offset(offset: number): ModelQueryBuilder<T>;
870
- /**
871
- * Sets the source filter for the query.
872
- *
873
- * @param source - The source to filter by
874
- * @returns The query builder for chaining
875
- *
876
- * @example
877
- * ```typescript
878
- * .source("ad4m://self")
879
260
  * ```
880
261
  */
881
- source(source: string): ModelQueryBuilder<T>;
262
+ static transaction<T>(perspective: PerspectiveProxy, callback: (tx: import("./transaction").TransactionContext) => Promise<T>): Promise<T>;
882
263
  /**
883
- * Specifies which properties to include in the results.
264
+ * Fires `callback` immediately with current results, then on every relevant perspective change.
884
265
  *
885
- * @param properties - Array of property names to include
886
- * @returns The query builder for chaining
266
+ * @param options - Query params plus optional `debounce` (ms) and `onError` handler
267
+ * @param callback - Receives the fresh result set on each delivery
268
+ * @returns `Subscription` with `unsubscribe()` — call it in cleanup to avoid leaks
887
269
  *
888
270
  * @example
889
271
  * ```typescript
890
- * .properties(["name", "description", "rating"])
272
+ * const sub = Post.subscribe(
273
+ * perspective,
274
+ * { where: { published: true }, debounce: 300 },
275
+ * (posts) => setPosts(posts),
276
+ * );
277
+ * sub.unsubscribe(); // in cleanup
891
278
  * ```
892
279
  */
893
- properties(properties: string[]): ModelQueryBuilder<T>;
280
+ static subscribe<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, options: SubscribeOptions, callback: (results: T[]) => void): Subscription;
894
281
  /**
895
- * Specifies which collections to include in the results.
282
+ * Generates an `Ad4mModel` subclass from a JSON Schema definition.
896
283
  *
897
- * @param collections - Array of collection names to include
898
- * @returns The query builder for chaining
284
+ * Predicate resolution order: explicit options → `x-ad4m` in schema → inferred from title/names.
899
285
  *
900
286
  * @example
901
287
  * ```typescript
902
- * .collections(["ingredients", "steps"])
903
- * ```
904
- */
905
- collections(collections: string[]): ModelQueryBuilder<T>;
906
- overrideModelClassName(className: string): ModelQueryBuilder<T>;
907
- /**
908
- * Enables or disables SurrealDB query path.
909
- *
910
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
911
- * @returns The query builder for chaining
912
- *
913
- * @example
914
- * ```typescript
915
- * // Use SurrealDB (default)
916
- * const recipes = await Recipe.query(perspective)
917
- * .where({ category: "Dessert" })
918
- * .useSurrealDB(true)
919
- * .get();
920
- *
921
- * // Use Prolog (legacy)
922
- * const recipesProlog = await Recipe.query(perspective)
923
- * .where({ category: "Dessert" })
924
- * .useSurrealDB(false)
925
- * .get();
926
- * ```
927
- *
928
- * @remarks
929
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
930
- * if useSurrealDB(true) is set (default).
931
- */
932
- useSurrealDB(enabled?: boolean): ModelQueryBuilder<T>;
933
- /**
934
- * Executes the query once and returns the results.
935
- *
936
- * @returns Array of matching entities
937
- *
938
- * @example
939
- * ```typescript
940
- * const recipes = await Recipe.query(perspective)
941
- * .where({ category: "Dessert" })
942
- * .get();
943
- * ```
944
- */
945
- get(): Promise<T[]>;
946
- /**
947
- * Subscribes to the query and receives updates when results change.
948
- *
949
- * This method:
950
- * 1. Creates and initializes a SurrealDB live query subscription (default)
951
- * 2. Sets up the callback to process future updates
952
- * 3. Returns the initial results immediately
953
- *
954
- * Remember to call dispose() when you're done with the subscription
955
- * to clean up resources.
956
- *
957
- * @param callback - Function to call with updated results
958
- * @returns Initial results array
959
- *
960
- * @example
961
- * ```typescript
962
- * const builder = Recipe.query(perspective)
963
- * .where({ status: "cooking" });
964
- *
965
- * const initialRecipes = await builder.subscribe(recipes => {
966
- * console.log("Updated recipes:", recipes);
967
- * });
968
- *
969
- * // When done with subscription:
970
- * builder.dispose();
971
- * ```
972
- *
973
- * @remarks
974
- * By default, this uses SurrealDB live queries for real-time updates.
975
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
976
- */
977
- subscribe(callback: (results: T[]) => void): Promise<T[]>;
978
- /**
979
- * Gets the total count of matching entities.
980
- *
981
- * @returns Total count
982
- *
983
- * @example
984
- * ```typescript
985
- * const totalDesserts = await Recipe.query(perspective)
986
- * .where({ category: "Dessert" })
987
- * .count();
988
- * ```
989
- */
990
- count(): Promise<number>;
991
- /**
992
- * Subscribes to count updates for matching entities.
993
- *
994
- * This method:
995
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
996
- * 2. Sets up the callback to process future count updates
997
- * 3. Returns the initial count immediately
998
- *
999
- * Remember to call dispose() when you're done with the subscription
1000
- * to clean up resources.
1001
- *
1002
- * @param callback - Function to call with updated count
1003
- * @returns Initial count
1004
- *
1005
- * @example
1006
- * ```typescript
1007
- * const builder = Recipe.query(perspective)
1008
- * .where({ status: "active" });
1009
- *
1010
- * const initialCount = await builder.countSubscribe(count => {
1011
- * console.log("Active items:", count);
1012
- * });
1013
- *
1014
- * // When done with subscription:
1015
- * builder.dispose();
1016
- * ```
1017
- *
1018
- * @remarks
1019
- * By default, this uses SurrealDB live queries for real-time updates.
1020
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1021
- */
1022
- countSubscribe(callback: (count: number) => void): Promise<number>;
1023
- /**
1024
- * Gets a page of results with pagination metadata.
1025
- *
1026
- * @param pageSize - Number of items per page
1027
- * @param pageNumber - Which page to retrieve (1-based)
1028
- * @returns Paginated results with metadata
1029
- *
1030
- * @example
1031
- * ```typescript
1032
- * const page = await Recipe.query(perspective)
1033
- * .where({ category: "Main" })
1034
- * .paginate(10, 1);
1035
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1036
- * ```
1037
- */
1038
- paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
1039
- /**
1040
- * Subscribes to paginated results updates.
1041
- *
1042
- * This method:
1043
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
1044
- * 2. Sets up the callback to process future page updates
1045
- * 3. Returns the initial page immediately
1046
- *
1047
- * Remember to call dispose() when you're done with the subscription
1048
- * to clean up resources.
1049
- *
1050
- * @param pageSize - Number of items per page
1051
- * @param pageNumber - Which page to retrieve (1-based)
1052
- * @param callback - Function to call with updated pagination results
1053
- * @returns Initial pagination results
1054
- *
1055
- * @example
1056
- * ```typescript
1057
- * const builder = Recipe.query(perspective)
1058
- * .where({ category: "Main" });
1059
- *
1060
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1061
- * console.log("Updated page:", page.results);
288
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
289
+ * name: "Person", namespace: "person://", resolveLanguage: "literal",
1062
290
  * });
1063
- *
1064
- * // When done with subscription:
1065
- * builder.dispose();
1066
291
  * ```
1067
- *
1068
- * @remarks
1069
- * By default, this uses SurrealDB live queries for real-time updates.
1070
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1071
292
  */
1072
- paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
293
+ static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1073
294
  }
1074
- export {};