@coasys/ad4m 0.12.0-rc1-dev.1 → 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 -6046
  3. package/lib/index.js +5977 -6040
  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 -2799
  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 -3249
  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
@@ -0,0 +1,27 @@
1
+ /** Atomic batch-transaction helper — see {@link runTransaction}. */
2
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
3
+ /**
4
+ * An open batch transaction on a perspective.
5
+ *
6
+ * Obtained from the callback argument of {@link runTransaction}. Pass
7
+ * `tx.batchId` to `save()`, `delete()` etc. to enlist those operations in the
8
+ * transaction. Commit and abort are handled automatically by `runTransaction`.
9
+ */
10
+ export interface TransactionContext {
11
+ /** The underlying batch ID — pass to save/delete/add/remove calls. */
12
+ readonly batchId: string;
13
+ /** The perspective this transaction is open on. */
14
+ readonly perspective: PerspectiveProxy;
15
+ }
16
+ /**
17
+ * Commits on success, aborts (discards batch) and re-throws on failure.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * await Ad4mModel.transaction(perspective, async (tx) => {
22
+ * await post.save(tx.batchId);
23
+ * await comment.save(tx.batchId);
24
+ * });
25
+ * ```
26
+ */
27
+ export declare function runTransaction<T>(perspective: PerspectiveProxy, callback: (tx: TransactionContext) => Promise<T>): Promise<T>;
@@ -0,0 +1,32 @@
1
+ /** Atomic batch-transaction helper — see {@link runTransaction}. */
2
+ // ─────────────────────────────────────────────────────────────────────────────
3
+ // runTransaction
4
+ // ─────────────────────────────────────────────────────────────────────────────
5
+ /**
6
+ * Commits on success, aborts (discards batch) and re-throws on failure.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * await Ad4mModel.transaction(perspective, async (tx) => {
11
+ * await post.save(tx.batchId);
12
+ * await comment.save(tx.batchId);
13
+ * });
14
+ * ```
15
+ */
16
+ export async function runTransaction(perspective, callback) {
17
+ const batchId = await perspective.createBatch();
18
+ const tx = { batchId, perspective };
19
+ try {
20
+ const result = await callback(tx);
21
+ await perspective.commitBatch(batchId);
22
+ return result;
23
+ }
24
+ catch (err) {
25
+ // PerspectiveProxy has no abortBatch — the uncommitted batch will be
26
+ // discarded by the runtime on its next GC cycle. Log at debug level
27
+ // only: the re-thrown error already carries all actionable information,
28
+ // and logging at warn would spam the console for intentional rollbacks.
29
+ console.debug(`[Ad4mModel.transaction] callback threw — batch ${batchId} was NOT committed and will be discarded.`, err);
30
+ throw err;
31
+ }
32
+ }
@@ -0,0 +1,195 @@
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
+ type WhereOps = {
9
+ not: string | number | boolean | string[] | number[];
10
+ between: [number, number];
11
+ lt: number;
12
+ lte: number;
13
+ gt: number;
14
+ gte: number;
15
+ contains: string | number;
16
+ };
17
+ export type WhereCondition = string | number | boolean | string[] | number[] | {
18
+ [K in keyof WhereOps]?: WhereOps[K];
19
+ };
20
+ export type Where = {
21
+ [propertyName: string]: WhereCondition;
22
+ };
23
+ export type Order = {
24
+ [propertyName: string]: "ASC" | "DESC";
25
+ };
26
+ /**
27
+ * Prisma-style eager-loading map.
28
+ *
29
+ * Key = relation field name on the model.
30
+ * Value = `true` (hydrate all with no filter) or a `Query` to
31
+ * filter / order / limit the nested set.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * Recipe.findAll(perspective, {
36
+ * include: {
37
+ * comments: true,
38
+ * tags: { where: { active: true }, order: { name: 'ASC' }, limit: 5 },
39
+ * },
40
+ * });
41
+ * ```
42
+ */
43
+ export type IncludeMap = {
44
+ [relationName: string]: true | Query;
45
+ };
46
+ /**
47
+ * Minimal interface a parent model class must satisfy for the model-backed
48
+ * `parent` query form. Avoids a circular import between types.ts and Ad4mModel.ts.
49
+ */
50
+ type ParentQueryParentCtor = {
51
+ getModelMetadata(): ModelMetadata;
52
+ };
53
+ /** Raw predicate form — use for ad-hoc or cross-package predicates. */
54
+ export type ParentQueryByPredicate = {
55
+ id: string;
56
+ predicate: string;
57
+ };
58
+ /**
59
+ * Model-backed form — DRY alternative that resolves the predicate from the
60
+ * parent model's `@HasMany` decorator metadata at query time.
61
+ */
62
+ export type ParentQueryByModel = {
63
+ id: string;
64
+ model: ParentQueryParentCtor;
65
+ /** The `@HasMany` field name on `model`. Optional when unambiguous. */
66
+ field?: string;
67
+ };
68
+ /** Union of the two `parent` query forms accepted by {@link Query}. */
69
+ export type ParentQuery = ParentQueryByPredicate | ParentQueryByModel;
70
+ export type Query = {
71
+ properties?: string[];
72
+ /** Eagerly hydrate relations. Key = field name; value = `true` or a sub-`Query`. See {@link IncludeMap}. */
73
+ include?: IncludeMap;
74
+ where?: Where;
75
+ order?: Order;
76
+ offset?: number;
77
+ limit?: number;
78
+ count?: boolean;
79
+ /**
80
+ * When provided, restricts results to instances reachable from the given
81
+ * parent node via the given predicate.
82
+ *
83
+ * The subscription layer also watches this predicate so that adding or
84
+ * removing a child link triggers a live re-query.
85
+ *
86
+ * Two equivalent forms are accepted:
87
+ * - Raw: `{ id, predicate }` — use for ad-hoc / foreign predicates.
88
+ * - Model-backed: `{ id, model, field? }` — DRY, refactor-safe; the
89
+ * predicate is resolved automatically from the parent model's `@HasMany`
90
+ * decorator metadata. `field` is the `@HasMany` field name; when the
91
+ * parent has exactly one `@HasMany` pointing to the child type it may be
92
+ * omitted (but is recommended for clarity).
93
+ *
94
+ * @example
95
+ * // Raw form (still valid for foreign predicates)
96
+ * parent: { id: parentId, predicate: 'custom://my_pred' }
97
+ *
98
+ * // Model-backed form (preferred for schema-declared relations)
99
+ * parent: { id: poll.id, model: Poll, field: 'answers' }
100
+ */
101
+ parent?: ParentQuery;
102
+ };
103
+ /**
104
+ * Extends `Query` (minus `count`) with subscription delivery options.
105
+ * Pass to {@link Ad4mModel.subscribe} or the builder's `.subscribe()`.
106
+ */
107
+ export type SubscribeOptions = Omit<Query, "count"> & {
108
+ /**
109
+ * Debounce delay in milliseconds. Multiple link changes within this window
110
+ * trigger only one re-query. Default: `0` (no debouncing).
111
+ */
112
+ debounce?: number;
113
+ /**
114
+ * Called when the re-query or the callback throws.
115
+ * Defaults to `console.error` so failures are always visible without
116
+ * requiring every caller to handle them.
117
+ */
118
+ onError?: (err: Error) => void;
119
+ };
120
+ /**
121
+ * Handle returned by `Ad4mModel.subscribe()`. Call `unsubscribe()` in cleanup.
122
+ * `lastError` holds the most recent unhandled error, or `null`.
123
+ */
124
+ export type Subscription = {
125
+ unsubscribe(): void;
126
+ /** The most recent unhandled error from re-query or callback, or `null`. */
127
+ readonly lastError: Error | null;
128
+ };
129
+ export type AllInstancesResult = any;
130
+ export type ResultsWithTotalCount<T> = {
131
+ results: T[];
132
+ totalCount?: number;
133
+ };
134
+ export type PaginationResult<T> = {
135
+ results: T[];
136
+ totalCount?: number;
137
+ pageSize: number;
138
+ pageNumber: number;
139
+ };
140
+ /**
141
+ * Metadata for a single property extracted from decorators.
142
+ */
143
+ export interface PropertyMetadata {
144
+ /** The property name */
145
+ name: string;
146
+ /** The predicate URI (through value) */
147
+ predicate: string;
148
+ /** Whether the property is required */
149
+ required: boolean;
150
+ /** Whether the property is read-only (default: false, i.e. writable) */
151
+ readOnly?: boolean;
152
+ /** Initial value if specified */
153
+ initial?: string;
154
+ /** Language for resolution (e.g., "literal") */
155
+ resolveLanguage?: string;
156
+ /** Custom SurrealQL getter code */
157
+ getter?: string;
158
+ /** Whether stored locally only */
159
+ local?: boolean;
160
+ /** Transform function */
161
+ transform?: (value: any) => any;
162
+ /** Whether this is a flag property */
163
+ flag?: boolean;
164
+ }
165
+ /**
166
+ * Metadata for a single relation extracted from decorators.
167
+ */
168
+ export interface RelationMetadata {
169
+ /** The relation name */
170
+ name: string;
171
+ /** The predicate URI (through value) */
172
+ predicate: string;
173
+ /** Custom SurrealQL getter code */
174
+ getter?: string;
175
+ /** Whether stored locally only */
176
+ local?: boolean;
177
+ /** Traversal direction — "forward" (default) for @HasMany/@HasOne, "reverse" for @BelongsToOne/@BelongsToMany */
178
+ direction?: "forward" | "reverse";
179
+ /** Maximum number of results (1 for @BelongsToOne / @HasOne) */
180
+ maxCount?: number;
181
+ /** Model factory for eager hydration — set when decorator is called with () => ModelClass */
182
+ relatedModel?: () => any;
183
+ }
184
+ /**
185
+ * Complete model metadata extracted from decorators.
186
+ */
187
+ export interface ModelMetadata {
188
+ /** The model class name from @ModelOptions */
189
+ className: string;
190
+ /** Map of property name to metadata */
191
+ properties: Record<string, PropertyMetadata>;
192
+ /** Map of relation name to metadata */
193
+ relations: Record<string, RelationMetadata>;
194
+ }
195
+ export {};
@@ -0,0 +1,8 @@
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
+ export {};
@@ -43,7 +43,7 @@ export function collectionAdderToName(adderName) {
43
43
  export function collectionToRemoverName(collection) {
44
44
  return `remove${capitalize(pluralToSingular(collection))}`;
45
45
  }
46
- // e.g. "removeComments" -> "comments"
46
+ // e.g. "removeComments" -> "comments"
47
47
  export function collectionRemoverToName(removerName) {
48
48
  // Extract the collection name after "remove" and lowercase first char
49
49
  // The method name already has the plural collection name (e.g., "removeComments")
@@ -51,14 +51,14 @@ export function collectionRemoverToName(removerName) {
51
51
  return collectionName.charAt(0).toLowerCase() + collectionName.slice(1);
52
52
  }
53
53
  export function collectionSetterToName(setterName) {
54
- // Extract the collection name after "setCollection" and lowercase first char
55
- // The method name already has the plural collection name (e.g., "setCollectionComments")
56
- let collectionName = setterName.substring(13);
54
+ // Extract the collection name after "set" and lowercase first char
55
+ // The method name has the plural collection name (e.g., "setComments")
56
+ let collectionName = setterName.substring(3);
57
57
  return collectionName.charAt(0).toLowerCase() + collectionName.slice(1);
58
58
  }
59
- // e.g. "comments" -> "addComment"
59
+ // e.g. "comments" -> "setComment"
60
60
  export function collectionToSetterName(collection) {
61
- return `setCollection${capitalize(pluralToSingular(collection))}`;
61
+ return `set${capitalize(pluralToSingular(collection))}`;
62
62
  }
63
63
  export function stringifyObjectLiteral(obj) {
64
64
  if (Array.isArray(obj)) {
@@ -72,5 +72,5 @@ export function stringifyObjectLiteral(obj) {
72
72
  const keyValuePairString = `${key}: ${valueString}`;
73
73
  stringifiedPairs.push(keyValuePairString);
74
74
  }
75
- return `{${stringifiedPairs.join(', ')}}`;
75
+ return `{${stringifiedPairs.join(", ")}}`;
76
76
  }
@@ -5,7 +5,9 @@ import { OnlineAgent, TelepresenceSignalCallback } from "../language/Language";
5
5
  import { Perspective, PerspectiveUnsignedInput } from "../perspectives/Perspective";
6
6
  import { PerspectiveHandle } from "../perspectives/PerspectiveHandle";
7
7
  export declare class NeighbourhoodClient {
8
- #private;
8
+ private _apolloClient;
9
+ private _signalHandlers;
10
+ private _signalSubscriptions;
9
11
  constructor(client: ApolloClient<any>);
10
12
  publishFromPerspective(perspectiveUUID: string, linkLanguage: Address, meta: Perspective): Promise<string>;
11
13
  joinFromUrl(url: string): Promise<PerspectiveHandle>;
@@ -22,4 +24,6 @@ export declare class NeighbourhoodClient {
22
24
  subscribeToSignals(perspectiveUUID: string): Promise<void>;
23
25
  addSignalHandler(perspectiveUUID: string, handler: TelepresenceSignalCallback): Promise<void>;
24
26
  removeSignalHandler(perspectiveUUID: string, handler: TelepresenceSignalCallback): void;
27
+ /** Fully tears down the Apollo subscription for a perspective UUID. */
28
+ unsubscribeFromPerspective(perspectiveUUID: string): void;
25
29
  }