@coasys/ad4m 0.12.0-rc1-dev.2 → 0.12.0-rc1-dev.4

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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6893 -5884
  3. package/lib/index.js +6889 -5872
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3760 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4386 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -1,307 +0,0 @@
1
- /**
2
- * Live subscription implementation for Ad4mModel.
3
- *
4
- * Identical queries on the same perspective share a single `findAll()` call
5
- * and a single pair of link listeners via an internal registry — multiple
6
- * components subscribing to the same data cooperate rather than each running
7
- * independent queries.
8
- *
9
- * Results are fingerprinted before broadcasting: callbacks only fire when
10
- * the result set has actually changed.
11
- */
12
-
13
- import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
14
- import type { LinkExpression } from "../links/Links";
15
- import type {
16
- Query,
17
- ModelMetadata,
18
- Subscription,
19
- SubscribeOptions,
20
- } from "./types";
21
- import { instanceToSerializable } from "./decorators";
22
- import { normalizeParentQuery } from "./parentUtils";
23
-
24
- // ─── Helpers ──────────────────────────────────────────────────────────────────
25
-
26
- /**
27
- * Stable JSON key for a Query — sorts object keys so that equivalent queries
28
- * produced from different code paths hash to the same string.
29
- */
30
- function stableQueryKey(query: Query): string {
31
- if (Object.keys(query).length === 0) return "{}";
32
- const sorted: Record<string, unknown> = {};
33
- for (const k of Object.keys(query).sort()) {
34
- sorted[k] = (query as any)[k];
35
- }
36
- return JSON.stringify(sorted);
37
- }
38
-
39
- /**
40
- * Stable fingerprint for an array of model instances.
41
- *
42
- * Sorted by `id` so result ordering doesn't cause false positives.
43
- * `id` is a prototype getter and therefore not serialised by
44
- * `JSON.stringify` automatically — it is extracted explicitly.
45
- *
46
- * Delegates to `instanceToSerializable` (from decorators.ts) which strips
47
- * all non-decorator-registered fields — including the runtime-enumerable
48
- * TypeScript `private _perspective` that would otherwise cause
49
- * `JSON.stringify` to throw a circular-reference error via
50
- * PerspectiveProxy → Apollo InMemoryCache.
51
- */
52
- function stableFingerprint(results: any[]): string {
53
- const sorted = [...results].sort((a, b) => {
54
- const aId: string = a.id ?? "";
55
- const bId: string = b.id ?? "";
56
- return aId < bId ? -1 : aId > bId ? 1 : 0;
57
- });
58
- return JSON.stringify(sorted.map(instanceToSerializable));
59
- }
60
-
61
- // ─── Subscription registry ────────────────────────────────────────────────────
62
- //
63
- // Key: `${modelClassName}:${stableQueryKey(query)}`
64
- //
65
- // WeakMap: when a PerspectiveProxy is garbage-collected its inner map is
66
- // released automatically — no manual cleanup required.
67
-
68
- interface ListenerRecord {
69
- callback: (results: any[]) => void;
70
- onError: ((err: Error) => void) | undefined;
71
- /** Allows unsubscribe() to surface the last error on the Subscription handle. */
72
- setLastError: (err: Error) => void;
73
- }
74
-
75
- interface SharedEntry {
76
- listeners: Map<symbol, ListenerRecord>;
77
- /** Results from the last successful findAll(). null until first run. */
78
- lastResults: any[] | null;
79
- lastFingerprint: string | null;
80
- debounceTimer: ReturnType<typeof setTimeout> | null;
81
- /** False once the last listener unsubscribes — prevents stale async callbacks. */
82
- active: boolean;
83
- /** Removes link-added/link-removed listeners from the perspective. */
84
- detach(): void;
85
- }
86
-
87
- const registry = new WeakMap<PerspectiveProxy, Map<string, SharedEntry>>();
88
-
89
- function getOrCreateSharedEntry(
90
- findAll: (perspective: PerspectiveProxy, query?: Query) => Promise<any[]>,
91
- perspective: PerspectiveProxy,
92
- query: Query,
93
- metadata: ModelMetadata,
94
- debounceMs: number,
95
- perspEntries: Map<string, SharedEntry>,
96
- key: string,
97
- ): SharedEntry {
98
- const existing = perspEntries.get(key);
99
- if (existing) return existing;
100
-
101
- // Minimum coalesce window — even without a user-configured debounce, a
102
- // single save() emits several link events; this collapses them into one
103
- // findAll() call. Not a timing workaround — SurrealDB is guaranteed
104
- // committed before link-added events are published.
105
- const SETTLE_MS = 50;
106
- const effectiveDebounce = Math.max(debounceMs, SETTLE_MS);
107
-
108
- const watchedPredicates = new Set<string>();
109
- for (const prop of Object.values(metadata.properties)) {
110
- if (prop.predicate) watchedPredicates.add(prop.predicate);
111
- }
112
- for (const rel of Object.values(metadata.relations)) {
113
- if (rel.predicate) watchedPredicates.add(rel.predicate);
114
- }
115
- // If the query is scoped to a parent via parent query, also watch the
116
- // parent-relationship predicate so that adding/removing a child link
117
- // triggers a live re-query even though it's not in the child model's schema.
118
- if (query.parent && 'predicate' in query.parent) {
119
- watchedPredicates.add(query.parent.predicate);
120
- }
121
-
122
- const entry: SharedEntry = {
123
- listeners: new Map(),
124
- lastResults: null,
125
- lastFingerprint: null,
126
- debounceTimer: null,
127
- active: true,
128
- detach: () => {},
129
- };
130
-
131
- const broadcast = (results: any[]) => {
132
- for (const {
133
- callback,
134
- onError,
135
- setLastError,
136
- } of entry.listeners.values()) {
137
- try {
138
- callback(results);
139
- } catch (err) {
140
- setLastError(err as Error);
141
- (onError ?? console.error)(err as Error);
142
- }
143
- }
144
- };
145
-
146
- const notifyError = (err: Error) => {
147
- for (const { onError, setLastError } of entry.listeners.values()) {
148
- setLastError(err);
149
- (onError ?? console.error)(err);
150
- }
151
- };
152
-
153
- const rerun = async () => {
154
- if (!entry.active) return;
155
- try {
156
- const results = await findAll(perspective, query);
157
- if (!entry.active) return;
158
-
159
- // Only broadcast if results actually changed.
160
- const fingerprint = stableFingerprint(results);
161
- if (fingerprint === entry.lastFingerprint) return;
162
- entry.lastFingerprint = fingerprint;
163
- entry.lastResults = results;
164
-
165
- broadcast(results);
166
- } catch (err) {
167
- notifyError(err as Error);
168
- }
169
- };
170
-
171
- const scheduleRerun = () => {
172
- if (entry.debounceTimer !== null) clearTimeout(entry.debounceTimer);
173
- entry.debounceTimer = setTimeout(rerun, effectiveDebounce);
174
- };
175
-
176
- // LinkCallback must return null (see PerspectiveClient.ts type definition)
177
- const linkChangedCb = (link: LinkExpression): null => {
178
- if (watchedPredicates.has(link.data?.predicate ?? "")) scheduleRerun();
179
- return null;
180
- };
181
-
182
- perspective.addListener("link-added", linkChangedCb);
183
- perspective.addListener("link-removed", linkChangedCb);
184
- entry.detach = () => {
185
- // Fire-and-forget — removeListener is async but just does an array splice.
186
- // entry.active = false ensures no further callbacks fire regardless.
187
- perspective.removeListener("link-added", linkChangedCb);
188
- perspective.removeListener("link-removed", linkChangedCb);
189
- };
190
-
191
- // Fire immediately with initial results.
192
- rerun();
193
-
194
- perspEntries.set(key, entry);
195
- return entry;
196
- }
197
-
198
- // ─── Public API ───────────────────────────────────────────────────────────────
199
-
200
- /**
201
- * Creates a live subscription for a model query.
202
- *
203
- * Immediately invokes `callback` with the initial query results, then
204
- * re-invokes it whenever a relevant link is added to or removed from the
205
- * perspective.
206
- *
207
- * Multiple callers subscribing to the same model + query on the same
208
- * perspective share a single `findAll()` execution and a single pair of link
209
- * listeners via an internal registry. Callbacks are only fired when the
210
- * result set has actually changed.
211
- *
212
- * @param findAll - The model's `findAll` static method
213
- * @param getMetadata - The model's `getModelMetadata` static method
214
- * @param perspective - The perspective to watch
215
- * @param options - Query parameters + delivery options (debounce, onError)
216
- * @param callback - Invoked with fresh results on every relevant change
217
- * @returns A `Subscription` handle with `unsubscribe()` and `lastError`
218
- *
219
- * @example
220
- * ```typescript
221
- * const sub = createSubscription(
222
- * (p, q) => Post.findAll(p, q),
223
- * () => Post.getModelMetadata(),
224
- * perspective,
225
- * { where: { published: true }, debounce: 200 },
226
- * (posts) => console.log("Posts updated:", posts),
227
- * );
228
- *
229
- * // Later:
230
- * sub.unsubscribe();
231
- * ```
232
- */
233
- export function createSubscription<T>(
234
- findAll: (perspective: PerspectiveProxy, query?: Query) => Promise<T[]>,
235
- getMetadata: () => ModelMetadata,
236
- perspective: PerspectiveProxy,
237
- options: SubscribeOptions,
238
- callback: (results: T[]) => void,
239
- ctor?: new (...args: any[]) => any,
240
- ): Subscription {
241
- const { debounce: debounceMs = 0, onError, ...queryOptions } = options;
242
- // Normalise model-backed parent query to { id, predicate } before key
243
- // computation so the shared-entry registry and predicate watcher both
244
- // operate on the resolved string form.
245
- const rawParent = (queryOptions as Query).parent;
246
- const resolvedOptions = rawParent
247
- ? { ...queryOptions, parent: normalizeParentQuery(rawParent, ctor) }
248
- : queryOptions;
249
- const query: Query = resolvedOptions as Query;
250
- const metadata = getMetadata();
251
- const key = `${metadata.className}:${stableQueryKey(query)}`;
252
-
253
- let perspEntries = registry.get(perspective);
254
- if (!perspEntries) {
255
- perspEntries = new Map();
256
- registry.set(perspective, perspEntries);
257
- }
258
-
259
- const entry = getOrCreateSharedEntry(
260
- findAll as (p: PerspectiveProxy, q?: Query) => Promise<any[]>,
261
- perspective,
262
- query,
263
- metadata,
264
- debounceMs,
265
- perspEntries,
266
- key,
267
- );
268
-
269
- const listenerId = Symbol();
270
- let lastError: Error | null = null;
271
-
272
- entry.listeners.set(listenerId, {
273
- callback: callback as (results: any[]) => void,
274
- onError,
275
- setLastError: (err) => {
276
- lastError = err;
277
- },
278
- });
279
-
280
- // Late subscriber: if the shared entry already ran at least once, fire
281
- // immediately with cached results — avoids an extra findAll() round-trip.
282
- if (entry.lastResults !== null) {
283
- const cached = entry.lastResults as T[];
284
- Promise.resolve().then(() => {
285
- if (entry.listeners.has(listenerId)) callback(cached);
286
- });
287
- }
288
-
289
- return {
290
- get lastError(): Error | null {
291
- return lastError;
292
- },
293
- unsubscribe() {
294
- entry.listeners.delete(listenerId);
295
- if (entry.listeners.size === 0) {
296
- // Last subscriber — tear down the shared entry entirely.
297
- entry.active = false;
298
- if (entry.debounceTimer !== null) {
299
- clearTimeout(entry.debounceTimer);
300
- entry.debounceTimer = null;
301
- }
302
- entry.detach();
303
- perspEntries!.delete(key);
304
- }
305
- },
306
- };
307
- }
@@ -1,60 +0,0 @@
1
- /** Atomic batch-transaction helper — see {@link runTransaction}. */
2
-
3
- import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
-
5
- // ─────────────────────────────────────────────────────────────────────────────
6
- // TransactionContext
7
- // ─────────────────────────────────────────────────────────────────────────────
8
-
9
- /**
10
- * An open batch transaction on a perspective.
11
- *
12
- * Obtained from the callback argument of {@link runTransaction}. Pass
13
- * `tx.batchId` to `save()`, `delete()` etc. to enlist those operations in the
14
- * transaction. Commit and abort are handled automatically by `runTransaction`.
15
- */
16
- export interface TransactionContext {
17
- /** The underlying batch ID — pass to save/delete/add/remove calls. */
18
- readonly batchId: string;
19
- /** The perspective this transaction is open on. */
20
- readonly perspective: PerspectiveProxy;
21
- }
22
-
23
- // ─────────────────────────────────────────────────────────────────────────────
24
- // runTransaction
25
- // ─────────────────────────────────────────────────────────────────────────────
26
-
27
- /**
28
- * Commits on success, aborts (discards batch) and re-throws on failure.
29
- *
30
- * @example
31
- * ```typescript
32
- * await Ad4mModel.transaction(perspective, async (tx) => {
33
- * await post.save(tx.batchId);
34
- * await comment.save(tx.batchId);
35
- * });
36
- * ```
37
- */
38
- export async function runTransaction<T>(
39
- perspective: PerspectiveProxy,
40
- callback: (tx: TransactionContext) => Promise<T>,
41
- ): Promise<T> {
42
- const batchId = await perspective.createBatch();
43
- const tx: TransactionContext = { batchId, perspective };
44
-
45
- try {
46
- const result = await callback(tx);
47
- await perspective.commitBatch(batchId);
48
- return result;
49
- } catch (err) {
50
- // PerspectiveProxy has no abortBatch — the uncommitted batch will be
51
- // discarded by the runtime on its next GC cycle. Log at debug level
52
- // only: the re-thrown error already carries all actionable information,
53
- // and logging at warn would spam the console for intentional rollbacks.
54
- console.debug(
55
- `[Ad4mModel.transaction] callback threw — batch ${batchId} was NOT committed and will be discarded.`,
56
- err,
57
- );
58
- throw err;
59
- }
60
- }
@@ -1,207 +0,0 @@
1
- /**
2
- * Public types for the AD4M model layer.
3
- *
4
- * Extracted from Ad4mModel.ts so they can be imported by query builders,
5
- * hydration helpers, and external consumers without pulling in the full
6
- * Ad4mModel class.
7
- */
8
-
9
- // ── Where / Query ──────────────────────────────────────────────────────────
10
-
11
- type WhereOps = {
12
- not: string | number | boolean | string[] | number[];
13
- between: [number, number];
14
- lt: number; // less than
15
- lte: number; // less than or equal to
16
- gt: number; // greater than
17
- gte: number; // greater than or equal to
18
- contains: string | number; // substring/element check
19
- };
20
-
21
- export type WhereCondition =
22
- | string
23
- | number
24
- | boolean
25
- | string[]
26
- | number[]
27
- | { [K in keyof WhereOps]?: WhereOps[K] };
28
-
29
- export type Where = { [propertyName: string]: WhereCondition };
30
- export type Order = { [propertyName: string]: "ASC" | "DESC" };
31
-
32
- /**
33
- * Prisma-style eager-loading map.
34
- *
35
- * Key = relation field name on the model.
36
- * Value = `true` (hydrate all with no filter) or a `Query` to
37
- * filter / order / limit the nested set.
38
- *
39
- * @example
40
- * ```typescript
41
- * Recipe.findAll(perspective, {
42
- * include: {
43
- * comments: true,
44
- * tags: { where: { active: true }, order: { name: 'ASC' }, limit: 5 },
45
- * },
46
- * });
47
- * ```
48
- */
49
- export type IncludeMap = { [relationName: string]: true | Query };
50
-
51
- // ── ParentQuery ─────────────────────────────────────────────────────────────
52
-
53
- /**
54
- * Minimal interface a parent model class must satisfy for the model-backed
55
- * `parent` query form. Avoids a circular import between types.ts and Ad4mModel.ts.
56
- */
57
- type ParentQueryParentCtor = { getModelMetadata(): ModelMetadata };
58
-
59
- /** Raw predicate form — use for ad-hoc or cross-package predicates. */
60
- export type ParentQueryByPredicate = { id: string; predicate: string };
61
-
62
- /**
63
- * Model-backed form — DRY alternative that resolves the predicate from the
64
- * parent model's `@HasMany` decorator metadata at query time.
65
- */
66
- export type ParentQueryByModel = {
67
- id: string;
68
- model: ParentQueryParentCtor;
69
- /** The `@HasMany` field name on `model`. Optional when unambiguous. */
70
- field?: string;
71
- };
72
-
73
- /** Union of the two `parent` query forms accepted by {@link Query}. */
74
- export type ParentQuery = ParentQueryByPredicate | ParentQueryByModel;
75
-
76
- export type Query = {
77
- properties?: string[];
78
- /** Eagerly hydrate relations. Key = field name; value = `true` or a sub-`Query`. See {@link IncludeMap}. */
79
- include?: IncludeMap;
80
- where?: Where;
81
- order?: Order;
82
- offset?: number;
83
- limit?: number;
84
- count?: boolean;
85
- /**
86
- * When provided, restricts results to instances reachable from the given
87
- * parent node via the given predicate.
88
- *
89
- * The subscription layer also watches this predicate so that adding or
90
- * removing a child link triggers a live re-query.
91
- *
92
- * Two equivalent forms are accepted:
93
- * - Raw: `{ id, predicate }` — use for ad-hoc / foreign predicates.
94
- * - Model-backed: `{ id, model, field? }` — DRY, refactor-safe; the
95
- * predicate is resolved automatically from the parent model's `@HasMany`
96
- * decorator metadata. `field` is the `@HasMany` field name; when the
97
- * parent has exactly one `@HasMany` pointing to the child type it may be
98
- * omitted (but is recommended for clarity).
99
- *
100
- * @example
101
- * // Raw form (still valid for foreign predicates)
102
- * parent: { id: parentId, predicate: 'custom://my_pred' }
103
- *
104
- * // Model-backed form (preferred for schema-declared relations)
105
- * parent: { id: poll.id, model: Poll, field: 'answers' }
106
- */
107
- parent?: ParentQuery;
108
- };
109
-
110
- /**
111
- * Extends `Query` (minus `count`) with subscription delivery options.
112
- * Pass to {@link Ad4mModel.subscribe} or the builder's `.subscribe()`.
113
- */
114
- export type SubscribeOptions = Omit<Query, "count"> & {
115
- /**
116
- * Debounce delay in milliseconds. Multiple link changes within this window
117
- * trigger only one re-query. Default: `0` (no debouncing).
118
- */
119
- debounce?: number;
120
- /**
121
- * Called when the re-query or the callback throws.
122
- * Defaults to `console.error` so failures are always visible without
123
- * requiring every caller to handle them.
124
- */
125
- onError?: (err: Error) => void;
126
- };
127
-
128
- /**
129
- * Handle returned by `Ad4mModel.subscribe()`. Call `unsubscribe()` in cleanup.
130
- * `lastError` holds the most recent unhandled error, or `null`.
131
- */
132
- export type Subscription = {
133
- unsubscribe(): void;
134
- /** The most recent unhandled error from re-query or callback, or `null`. */
135
- readonly lastError: Error | null;
136
- };
137
-
138
- // ── Result shapes ──────────────────────────────────────────────────────────
139
-
140
- export type AllInstancesResult = any;
141
- export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
142
- export type PaginationResult<T> = {
143
- results: T[];
144
- totalCount?: number;
145
- pageSize: number;
146
- pageNumber: number;
147
- };
148
-
149
- // ── Model metadata ─────────────────────────────────────────────────────────
150
-
151
- /**
152
- * Metadata for a single property extracted from decorators.
153
- */
154
- export interface PropertyMetadata {
155
- /** The property name */
156
- name: string;
157
- /** The predicate URI (through value) */
158
- predicate: string;
159
- /** Whether the property is required */
160
- required: boolean;
161
- /** Whether the property is read-only (default: false, i.e. writable) */
162
- readOnly?: boolean;
163
- /** Initial value if specified */
164
- initial?: string;
165
- /** Language for resolution (e.g., "literal") */
166
- resolveLanguage?: string;
167
- /** Custom SurrealQL getter code */
168
- getter?: string;
169
- /** Whether stored locally only */
170
- local?: boolean;
171
- /** Transform function */
172
- transform?: (value: any) => any;
173
- /** Whether this is a flag property */
174
- flag?: boolean;
175
- }
176
-
177
- /**
178
- * Metadata for a single relation extracted from decorators.
179
- */
180
- export interface RelationMetadata {
181
- /** The relation name */
182
- name: string;
183
- /** The predicate URI (through value) */
184
- predicate: string;
185
- /** Custom SurrealQL getter code */
186
- getter?: string;
187
- /** Whether stored locally only */
188
- local?: boolean;
189
- /** Traversal direction — "forward" (default) for @HasMany/@HasOne, "reverse" for @BelongsToOne/@BelongsToMany */
190
- direction?: "forward" | "reverse";
191
- /** Maximum number of results (1 for @BelongsToOne / @HasOne) */
192
- maxCount?: number;
193
- /** Model factory for eager hydration — set when decorator is called with () => ModelClass */
194
- relatedModel?: () => any;
195
- }
196
-
197
- /**
198
- * Complete model metadata extracted from decorators.
199
- */
200
- export interface ModelMetadata {
201
- /** The model class name from @ModelOptions */
202
- className: string;
203
- /** Map of property name to metadata */
204
- properties: Record<string, PropertyMetadata>;
205
- /** Map of relation name to metadata */
206
- relations: Record<string, RelationMetadata>;
207
- }