@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.
- package/jest.config.js +4 -4
- package/lib/index.cjs +5999 -6044
- package/lib/index.js +5977 -6038
- package/lib/src/Ad4mClient.d.ts +16 -9
- package/lib/src/Ad4mClient.js +25 -46
- package/lib/src/Ad4mClient.test.d.ts +1 -0
- package/lib/src/Ad4mClient.test.js +1204 -0
- package/lib/src/Literal.d.ts +2 -1
- package/lib/src/Literal.js +35 -38
- package/lib/src/Literal.test.d.ts +1 -0
- package/lib/src/Literal.test.js +41 -0
- package/lib/src/SmartLiteral.d.ts +2 -1
- package/lib/src/SmartLiteral.js +15 -30
- package/lib/src/agent/AgentClient.d.ts +4 -1
- package/lib/src/agent/AgentClient.js +99 -79
- package/lib/src/ai/AIClient.d.ts +2 -1
- package/lib/src/ai/AIClient.js +220 -224
- package/lib/src/expression/ExpressionClient.d.ts +1 -1
- package/lib/src/expression/ExpressionClient.js +86 -73
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/language/LanguageClient.d.ts +1 -1
- package/lib/src/language/LanguageClient.js +52 -52
- package/lib/src/model/Ad4mModel.d.ts +157 -937
- package/lib/src/model/Ad4mModel.js +212 -2797
- package/lib/src/model/Ad4mModel.test.js +1002 -561
- package/lib/src/model/decorators.d.ts +94 -426
- package/lib/src/model/decorators.js +333 -741
- package/lib/src/model/mutation.d.ts +81 -0
- package/lib/src/model/mutation.js +317 -0
- package/lib/src/model/parentUtils.d.ts +32 -0
- package/lib/src/model/parentUtils.js +64 -0
- package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
- package/lib/src/model/prolog/generatePrologFacts.js +139 -0
- package/lib/src/model/prolog/index.d.ts +1 -0
- package/lib/src/model/prolog/index.js +1 -0
- package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
- package/lib/src/model/query/ModelQueryBuilder.js +115 -0
- package/lib/src/model/query/QueryBuilder.d.ts +101 -0
- package/lib/src/model/query/QueryBuilder.js +193 -0
- package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
- package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
- package/lib/src/model/query/fetchInstance.d.ts +24 -0
- package/lib/src/model/query/fetchInstance.js +144 -0
- package/lib/src/model/query/hydration.d.ts +54 -0
- package/lib/src/model/query/hydration.js +214 -0
- package/lib/src/model/query/operations.d.ts +59 -0
- package/lib/src/model/query/operations.js +384 -0
- package/lib/src/model/query/snapshot.d.ts +59 -0
- package/lib/src/model/query/snapshot.js +106 -0
- package/lib/src/model/query/surrealCompiler.d.ts +42 -0
- package/lib/src/model/query/surrealCompiler.js +304 -0
- package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
- package/lib/src/model/schema/fromJSONSchema.js +264 -0
- package/lib/src/model/schema/metadata.d.ts +15 -0
- package/lib/src/model/schema/metadata.js +112 -0
- package/lib/src/model/subscription.d.ts +47 -0
- package/lib/src/model/subscription.js +231 -0
- package/lib/src/model/transaction.d.ts +27 -0
- package/lib/src/model/transaction.js +32 -0
- package/lib/src/model/types.d.ts +195 -0
- package/lib/src/model/types.js +8 -0
- package/lib/src/model/util.js +7 -7
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
- package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
- package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
- package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
- package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
- package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
- package/lib/src/perspectives/PerspectiveClient.js +316 -240
- package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
- package/lib/src/perspectives/PerspectiveProxy.js +803 -444
- package/lib/src/runtime/RuntimeClient.d.ts +5 -1
- package/lib/src/runtime/RuntimeClient.js +412 -238
- package/lib/src/shacl/SHACLFlow.test.js +164 -105
- package/lib/src/shacl/SHACLShape.d.ts +17 -3
- package/lib/src/shacl/SHACLShape.js +127 -90
- package/lib/src/shacl/SHACLShape.test.js +244 -176
- package/lib/src/utils.d.ts +8 -0
- package/lib/src/utils.js +21 -7
- package/package.json +8 -13
- package/src/Ad4mClient.test.ts +1564 -1315
- package/src/Ad4mClient.ts +55 -54
- package/src/Literal.test.ts +45 -26
- package/src/Literal.ts +82 -66
- package/src/SmartLiteral.ts +74 -58
- package/src/agent/AgentClient.ts +144 -99
- package/src/ai/AIClient.ts +409 -359
- package/src/expression/ExpressionClient.ts +142 -96
- package/src/index.ts +1 -1
- package/src/language/LanguageClient.ts +137 -113
- package/src/model/Ad4mModel.test.ts +1128 -647
- package/src/model/Ad4mModel.ts +485 -3247
- package/src/model/IMPROVEMENTS.md +482 -0
- package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
- package/src/model/README.md +317 -0
- package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
- package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
- package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
- package/src/model/decorators.ts +689 -1046
- package/src/model/mutation.ts +461 -0
- package/src/model/parentUtils.ts +91 -0
- package/src/model/prolog/generatePrologFacts.ts +176 -0
- package/src/model/prolog/index.ts +1 -0
- package/src/model/query/ModelQueryBuilder.ts +173 -0
- package/src/model/query/fetchInstance.ts +181 -0
- package/src/model/query/hydration.ts +273 -0
- package/src/model/query/operations.ts +510 -0
- package/src/model/query/snapshot.ts +126 -0
- package/src/model/query/surrealCompiler.ts +376 -0
- package/src/model/schema/fromJSONSchema.ts +411 -0
- package/src/model/schema/metadata.ts +148 -0
- package/src/model/subscription.ts +307 -0
- package/src/model/transaction.ts +60 -0
- package/src/model/types.ts +207 -0
- package/src/model/util.ts +47 -48
- package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
- package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
- package/src/perspectives/PerspectiveClient.ts +779 -540
- package/src/perspectives/PerspectiveProxy.ts +2860 -2053
- package/src/runtime/RuntimeClient.ts +775 -476
- package/src/shacl/SHACLFlow.test.ts +196 -129
- package/src/shacl/SHACLShape.test.ts +284 -190
- package/src/shacl/SHACLShape.ts +225 -172
- package/src/utils.ts +31 -17
- package/tsconfig.json +9 -10
- package/src/model/Subject.ts +0 -159
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dynamic model creation from JSON Schema.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from Ad4mModel.ts so it can be tested and reused independently.
|
|
5
|
+
* The main entry point — `createModelFromJSONSchema` — takes the `Ad4mModel`
|
|
6
|
+
* class as `BaseClass` to avoid a circular import between this module and the
|
|
7
|
+
* class file.
|
|
8
|
+
*/
|
|
9
|
+
import { Model, propertyRegistry, relationRegistry, } from "../decorators";
|
|
10
|
+
import { capitalize, propertyNameToSetterName } from "../util";
|
|
11
|
+
// ── Internal schema helpers ─────────────────────────────────────────────────
|
|
12
|
+
export function normalizeNamespaceString(namespace) {
|
|
13
|
+
if (!namespace)
|
|
14
|
+
return "";
|
|
15
|
+
if (namespace.includes("://")) {
|
|
16
|
+
const [scheme, rest] = namespace.split("://");
|
|
17
|
+
const path = (rest || "").replace(/\/+$/, "");
|
|
18
|
+
return `${scheme}://${path}`;
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
return namespace.replace(/\/+$/, "");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function normalizeSchemaType(type) {
|
|
25
|
+
if (!type)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (typeof type === "string")
|
|
28
|
+
return type;
|
|
29
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
30
|
+
const nonNull = type.find((t) => t !== "null");
|
|
31
|
+
return nonNull || type[0];
|
|
32
|
+
}
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
export function isSchemaType(schema, expectedType) {
|
|
36
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
37
|
+
}
|
|
38
|
+
export function isArrayType(schema) {
|
|
39
|
+
return isSchemaType(schema, "array");
|
|
40
|
+
}
|
|
41
|
+
export function isObjectType(schema) {
|
|
42
|
+
return isSchemaType(schema, "object");
|
|
43
|
+
}
|
|
44
|
+
export function isNumericType(schema) {
|
|
45
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
46
|
+
return normalized === "number" || normalized === "integer";
|
|
47
|
+
}
|
|
48
|
+
// ── Predicate + namespace resolution ───────────────────────────────────────
|
|
49
|
+
export function determineNamespace(schema, options) {
|
|
50
|
+
if (options.namespace)
|
|
51
|
+
return options.namespace;
|
|
52
|
+
if (schema["x-ad4m"]?.namespace)
|
|
53
|
+
return schema["x-ad4m"].namespace;
|
|
54
|
+
if (schema.title)
|
|
55
|
+
return `${schema.title.toLowerCase()}://`;
|
|
56
|
+
if (schema.$id) {
|
|
57
|
+
try {
|
|
58
|
+
const url = new URL(schema.$id);
|
|
59
|
+
const pathParts = url.pathname.split("/").filter((p) => p);
|
|
60
|
+
if (pathParts.length > 0) {
|
|
61
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
62
|
+
const baseName = lastPart
|
|
63
|
+
.replace(/\.schema\.json$/, "")
|
|
64
|
+
.replace(/\.json$/, "");
|
|
65
|
+
return `${baseName.toLowerCase()}://`;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// not a valid URL — fall through to error
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:\n` +
|
|
73
|
+
` - options.namespace\n` +
|
|
74
|
+
` - schema["x-ad4m"].namespace\n` +
|
|
75
|
+
` - schema.title\n` +
|
|
76
|
+
` - valid schema.$id`);
|
|
77
|
+
}
|
|
78
|
+
export function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
|
|
79
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
80
|
+
return options.propertyMapping[propertyName];
|
|
81
|
+
}
|
|
82
|
+
if (propertySchema["x-ad4m"]?.through) {
|
|
83
|
+
return propertySchema["x-ad4m"].through;
|
|
84
|
+
}
|
|
85
|
+
if (options.predicateTemplate) {
|
|
86
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
87
|
+
const [scheme, rest] = normalizedNs.includes("://")
|
|
88
|
+
? normalizedNs.split("://")
|
|
89
|
+
: ["", normalizedNs];
|
|
90
|
+
const nsNoScheme = rest || "";
|
|
91
|
+
return options.predicateTemplate
|
|
92
|
+
.replace("${namespace}", nsNoScheme)
|
|
93
|
+
.replace("${scheme}", scheme)
|
|
94
|
+
.replace("${ns}", nsNoScheme)
|
|
95
|
+
.replace("${title}", schema.title || "")
|
|
96
|
+
.replace("${property}", propertyName);
|
|
97
|
+
}
|
|
98
|
+
if (options.predicateGenerator) {
|
|
99
|
+
return options.predicateGenerator(schema.title || "", propertyName);
|
|
100
|
+
}
|
|
101
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
102
|
+
if (normalizedNs.includes("://")) {
|
|
103
|
+
return `${normalizedNs}${propertyName}`;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
return `${normalizedNs}://${propertyName}`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export function getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
|
|
110
|
+
if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
|
|
111
|
+
return options.propertyOptions[propertyName][optionName];
|
|
112
|
+
}
|
|
113
|
+
if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
|
|
114
|
+
return propertySchema["x-ad4m"][optionName];
|
|
115
|
+
}
|
|
116
|
+
if (options[optionName] !== undefined) {
|
|
117
|
+
return options[optionName];
|
|
118
|
+
}
|
|
119
|
+
return defaultValue;
|
|
120
|
+
}
|
|
121
|
+
export function getDefaultValueForType(type) {
|
|
122
|
+
switch (type) {
|
|
123
|
+
case "string":
|
|
124
|
+
return "";
|
|
125
|
+
case "number":
|
|
126
|
+
return 0;
|
|
127
|
+
case "integer":
|
|
128
|
+
return 0;
|
|
129
|
+
case "boolean":
|
|
130
|
+
return false;
|
|
131
|
+
case "array":
|
|
132
|
+
return [];
|
|
133
|
+
case "object":
|
|
134
|
+
return {};
|
|
135
|
+
default:
|
|
136
|
+
return "";
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// ── Main factory ────────────────────────────────────────────────────────────
|
|
140
|
+
/**
|
|
141
|
+
* Creates an Ad4mModel subclass dynamically from a JSON Schema definition.
|
|
142
|
+
*
|
|
143
|
+
* Takes `BaseClass` as a parameter (rather than importing `Ad4mModel` directly)
|
|
144
|
+
* to avoid a circular dependency between this module and `Ad4mModel.ts`.
|
|
145
|
+
*
|
|
146
|
+
* `Ad4mModel.fromJSONSchema()` is a thin wrapper that calls this with `this`.
|
|
147
|
+
*/
|
|
148
|
+
export function createModelFromJSONSchema(BaseClass, schema, options) {
|
|
149
|
+
if (schema?.properties &&
|
|
150
|
+
Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
|
|
151
|
+
throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
|
|
152
|
+
}
|
|
153
|
+
const namespace = determineNamespace(schema, options);
|
|
154
|
+
const DynamicModelClass = class extends BaseClass {
|
|
155
|
+
};
|
|
156
|
+
if (!options.name || options.name.trim() === "") {
|
|
157
|
+
throw new Error("options.name is required and cannot be empty");
|
|
158
|
+
}
|
|
159
|
+
DynamicModelClass.className = options.name;
|
|
160
|
+
DynamicModelClass.prototype.className = options.name;
|
|
161
|
+
const properties = {};
|
|
162
|
+
const relations = {};
|
|
163
|
+
if (schema.properties) {
|
|
164
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
165
|
+
const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);
|
|
166
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
167
|
+
const propertyType = normalizeSchemaType(propertySchema.type);
|
|
168
|
+
const isArray = isArrayType(propertySchema);
|
|
169
|
+
if (isArray) {
|
|
170
|
+
relations[propertyName] = {
|
|
171
|
+
through: predicate,
|
|
172
|
+
local: getPropertyOption(propertyName, propertySchema, options, "local"),
|
|
173
|
+
};
|
|
174
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
175
|
+
configurable: true,
|
|
176
|
+
writable: true,
|
|
177
|
+
value: [],
|
|
178
|
+
});
|
|
179
|
+
const adderName = `add${capitalize(propertyName)}`;
|
|
180
|
+
const removerName = `remove${capitalize(propertyName)}`;
|
|
181
|
+
const setterName = `set${capitalize(propertyName)}`;
|
|
182
|
+
DynamicModelClass.prototype[adderName] = function () { };
|
|
183
|
+
DynamicModelClass.prototype[removerName] = function () { };
|
|
184
|
+
DynamicModelClass.prototype[setterName] = function () { };
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, "resolveLanguage");
|
|
188
|
+
if (!resolveLanguage && options.resolveLanguage) {
|
|
189
|
+
resolveLanguage = options.resolveLanguage;
|
|
190
|
+
}
|
|
191
|
+
const local = getPropertyOption(propertyName, propertySchema, options, "local");
|
|
192
|
+
const readOnly = getPropertyOption(propertyName, propertySchema, options, "readOnly");
|
|
193
|
+
let initial = getPropertyOption(propertyName, propertySchema, options, "initial");
|
|
194
|
+
if (isObjectType(propertySchema) && !resolveLanguage) {
|
|
195
|
+
resolveLanguage = "literal";
|
|
196
|
+
console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
|
|
197
|
+
}
|
|
198
|
+
// No auto-assignment for numeric types — resolveLanguage === undefined
|
|
199
|
+
// is now the implicit 'literal' default throughout the model layer.
|
|
200
|
+
if (isRequired && !initial) {
|
|
201
|
+
if (isObjectType(propertySchema)) {
|
|
202
|
+
initial = "literal://json:{}";
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
initial = "ad4m://undefined";
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
properties[propertyName] = {
|
|
209
|
+
through: predicate,
|
|
210
|
+
required: isRequired,
|
|
211
|
+
...(readOnly && { readOnly }),
|
|
212
|
+
...(resolveLanguage && { resolveLanguage }),
|
|
213
|
+
...(local !== undefined && { local }),
|
|
214
|
+
...(initial && { initial }),
|
|
215
|
+
};
|
|
216
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
217
|
+
configurable: true,
|
|
218
|
+
writable: true,
|
|
219
|
+
value: getDefaultValueForType(propertyType),
|
|
220
|
+
});
|
|
221
|
+
if (!readOnly) {
|
|
222
|
+
const setterName = propertyNameToSetterName(propertyName);
|
|
223
|
+
DynamicModelClass.prototype[setterName] = function () { };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// Ensure at least one property has an initial value (needed for a valid SDNA constructor)
|
|
229
|
+
const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
|
|
230
|
+
if (!hasPropertyWithInitial) {
|
|
231
|
+
const typeProperty = `ad4m://type`;
|
|
232
|
+
let typeValue;
|
|
233
|
+
if (namespace.includes("://")) {
|
|
234
|
+
const [scheme, rest] = namespace.split("://");
|
|
235
|
+
const path = (rest || "").replace(/\/+$/, "");
|
|
236
|
+
typeValue = path
|
|
237
|
+
? `${scheme}://${path}/instance`
|
|
238
|
+
: `${scheme}://instance`;
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
typeValue = `${namespace.replace(/\/+$/, "")}/instance`;
|
|
242
|
+
}
|
|
243
|
+
properties["__ad4m_type"] = {
|
|
244
|
+
through: typeProperty,
|
|
245
|
+
required: true,
|
|
246
|
+
readOnly: true,
|
|
247
|
+
initial: typeValue,
|
|
248
|
+
flag: true,
|
|
249
|
+
};
|
|
250
|
+
Object.defineProperty(DynamicModelClass.prototype, "__ad4m_type", {
|
|
251
|
+
configurable: true,
|
|
252
|
+
writable: false,
|
|
253
|
+
value: typeValue,
|
|
254
|
+
});
|
|
255
|
+
console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
|
|
256
|
+
}
|
|
257
|
+
propertyRegistry.set(DynamicModelClass, properties);
|
|
258
|
+
relationRegistry.set(DynamicModelClass, relations);
|
|
259
|
+
DynamicModelClass.prototype.__jsonSchema = schema;
|
|
260
|
+
DynamicModelClass.prototype.__jsonSchemaOptions = options;
|
|
261
|
+
const ModelDecorator = Model({ name: options.name });
|
|
262
|
+
ModelDecorator(DynamicModelClass);
|
|
263
|
+
return DynamicModelClass;
|
|
264
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metadata extraction helper for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* - `getModelMetadata(ctor)` — builds a {@link ModelMetadata} descriptor from
|
|
5
|
+
* the decorator registries, or falls back to the attached JSON Schema.
|
|
6
|
+
*/
|
|
7
|
+
import type { ModelMetadata } from "../types";
|
|
8
|
+
/**
|
|
9
|
+
* Builds a {@link ModelMetadata} descriptor for `ctor` from its decorator
|
|
10
|
+
* registries, falling back to the attached JSON Schema if no decorators are
|
|
11
|
+
* found.
|
|
12
|
+
*
|
|
13
|
+
* The matching `Ad4mModel.getModelMetadata()` static method delegates here.
|
|
14
|
+
*/
|
|
15
|
+
export declare function getModelMetadata(ctor: any): ModelMetadata;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metadata extraction helper for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* - `getModelMetadata(ctor)` — builds a {@link ModelMetadata} descriptor from
|
|
5
|
+
* the decorator registries, or falls back to the attached JSON Schema.
|
|
6
|
+
*/
|
|
7
|
+
import { getPropertiesMetadata, getRelationsMetadata } from "../decorators";
|
|
8
|
+
import { isArrayType, determinePredicate, determineNamespace, } from "./fromJSONSchema";
|
|
9
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
10
|
+
// getModelMetadataForClass
|
|
11
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
12
|
+
/**
|
|
13
|
+
* Builds a {@link ModelMetadata} descriptor for `ctor` from its decorator
|
|
14
|
+
* registries, falling back to the attached JSON Schema if no decorators are
|
|
15
|
+
* found.
|
|
16
|
+
*
|
|
17
|
+
* The matching `Ad4mModel.getModelMetadata()` static method delegates here.
|
|
18
|
+
*/
|
|
19
|
+
export function getModelMetadata(ctor) {
|
|
20
|
+
const prototype = ctor.prototype;
|
|
21
|
+
if (!prototype.className || prototype.className === "Ad4mModel") {
|
|
22
|
+
throw new Error("Model class must be decorated with @Model");
|
|
23
|
+
}
|
|
24
|
+
const className = prototype.className;
|
|
25
|
+
// ── Extract from decorator registries ──────────────────────────────────────
|
|
26
|
+
const propertiesMetadata = {};
|
|
27
|
+
const prototypeProperties = getPropertiesMetadata(ctor);
|
|
28
|
+
for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
|
|
29
|
+
const options = opts;
|
|
30
|
+
propertiesMetadata[propertyName] = {
|
|
31
|
+
name: propertyName,
|
|
32
|
+
predicate: options.through || "",
|
|
33
|
+
required: options.required || false,
|
|
34
|
+
...(options.readOnly !== undefined && { readOnly: options.readOnly }),
|
|
35
|
+
...(options.initial !== undefined && { initial: options.initial }),
|
|
36
|
+
...(options.resolveLanguage !== undefined && {
|
|
37
|
+
resolveLanguage: options.resolveLanguage,
|
|
38
|
+
}),
|
|
39
|
+
...(options.getter !== undefined && { getter: options.getter }),
|
|
40
|
+
...(options.local !== undefined && { local: options.local }),
|
|
41
|
+
...(options.transform !== undefined && { transform: options.transform }),
|
|
42
|
+
...(options.flag !== undefined && { flag: options.flag }),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const relationsMetadata = {};
|
|
46
|
+
const prototypeRelations = getRelationsMetadata(ctor);
|
|
47
|
+
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
48
|
+
const options = opts;
|
|
49
|
+
relationsMetadata[relationName] = {
|
|
50
|
+
name: relationName,
|
|
51
|
+
predicate: options.through || "",
|
|
52
|
+
...(options.local !== undefined && { local: options.local }),
|
|
53
|
+
...(options.getter !== undefined && { getter: options.getter }),
|
|
54
|
+
...(opts.direction !== undefined && {
|
|
55
|
+
direction: opts.direction,
|
|
56
|
+
}),
|
|
57
|
+
...(opts.maxCount !== undefined && {
|
|
58
|
+
maxCount: opts.maxCount,
|
|
59
|
+
}),
|
|
60
|
+
...(opts.relatedModel !== undefined && {
|
|
61
|
+
relatedModel: opts.relatedModel,
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
// ── Fallback: derive from attached JSON Schema if registries are empty ──────
|
|
66
|
+
const hasMetadata = Object.keys(propertiesMetadata).length > 0 ||
|
|
67
|
+
Object.keys(relationsMetadata).length > 0;
|
|
68
|
+
if (!hasMetadata && prototype.__jsonSchema) {
|
|
69
|
+
const schema = prototype.__jsonSchema;
|
|
70
|
+
const schemaOptions = prototype.__jsonSchemaOptions || {};
|
|
71
|
+
if (schema.properties) {
|
|
72
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
73
|
+
const isArray = isArrayType(propertySchema);
|
|
74
|
+
const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, schemaOptions), schemaOptions);
|
|
75
|
+
if (isArray) {
|
|
76
|
+
relationsMetadata[propertyName] = {
|
|
77
|
+
name: propertyName,
|
|
78
|
+
predicate,
|
|
79
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && {
|
|
80
|
+
local: propertySchema["x-ad4m"].local,
|
|
81
|
+
}),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
propertiesMetadata[propertyName] = {
|
|
86
|
+
name: propertyName,
|
|
87
|
+
predicate,
|
|
88
|
+
required: schema.required?.includes(propertyName) || false,
|
|
89
|
+
...(propertySchema["x-ad4m"]?.readOnly && {
|
|
90
|
+
readOnly: true,
|
|
91
|
+
}),
|
|
92
|
+
...(propertySchema["x-ad4m"]?.resolveLanguage && {
|
|
93
|
+
resolveLanguage: propertySchema["x-ad4m"]
|
|
94
|
+
.resolveLanguage,
|
|
95
|
+
}),
|
|
96
|
+
...(propertySchema["x-ad4m"]?.initial && {
|
|
97
|
+
initial: propertySchema["x-ad4m"].initial,
|
|
98
|
+
}),
|
|
99
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && {
|
|
100
|
+
local: propertySchema["x-ad4m"].local,
|
|
101
|
+
}),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
className,
|
|
109
|
+
properties: propertiesMetadata,
|
|
110
|
+
relations: relationsMetadata,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
13
|
+
import type { Query, ModelMetadata, Subscription, SubscribeOptions } from "./types";
|
|
14
|
+
/**
|
|
15
|
+
* Creates a live subscription for a model query.
|
|
16
|
+
*
|
|
17
|
+
* Immediately invokes `callback` with the initial query results, then
|
|
18
|
+
* re-invokes it whenever a relevant link is added to or removed from the
|
|
19
|
+
* perspective.
|
|
20
|
+
*
|
|
21
|
+
* Multiple callers subscribing to the same model + query on the same
|
|
22
|
+
* perspective share a single `findAll()` execution and a single pair of link
|
|
23
|
+
* listeners via an internal registry. Callbacks are only fired when the
|
|
24
|
+
* result set has actually changed.
|
|
25
|
+
*
|
|
26
|
+
* @param findAll - The model's `findAll` static method
|
|
27
|
+
* @param getMetadata - The model's `getModelMetadata` static method
|
|
28
|
+
* @param perspective - The perspective to watch
|
|
29
|
+
* @param options - Query parameters + delivery options (debounce, onError)
|
|
30
|
+
* @param callback - Invoked with fresh results on every relevant change
|
|
31
|
+
* @returns A `Subscription` handle with `unsubscribe()` and `lastError`
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* const sub = createSubscription(
|
|
36
|
+
* (p, q) => Post.findAll(p, q),
|
|
37
|
+
* () => Post.getModelMetadata(),
|
|
38
|
+
* perspective,
|
|
39
|
+
* { where: { published: true }, debounce: 200 },
|
|
40
|
+
* (posts) => console.log("Posts updated:", posts),
|
|
41
|
+
* );
|
|
42
|
+
*
|
|
43
|
+
* // Later:
|
|
44
|
+
* sub.unsubscribe();
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export declare function createSubscription<T>(findAll: (perspective: PerspectiveProxy, query?: Query) => Promise<T[]>, getMetadata: () => ModelMetadata, perspective: PerspectiveProxy, options: SubscribeOptions, callback: (results: T[]) => void, ctor?: new (...args: any[]) => any): Subscription;
|
|
@@ -0,0 +1,231 @@
|
|
|
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
|
+
import { instanceToSerializable } from "./decorators";
|
|
13
|
+
import { normalizeParentQuery } from "./parentUtils";
|
|
14
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
15
|
+
/**
|
|
16
|
+
* Stable JSON key for a Query — sorts object keys so that equivalent queries
|
|
17
|
+
* produced from different code paths hash to the same string.
|
|
18
|
+
*/
|
|
19
|
+
function stableQueryKey(query) {
|
|
20
|
+
if (Object.keys(query).length === 0)
|
|
21
|
+
return "{}";
|
|
22
|
+
const sorted = {};
|
|
23
|
+
for (const k of Object.keys(query).sort()) {
|
|
24
|
+
sorted[k] = query[k];
|
|
25
|
+
}
|
|
26
|
+
return JSON.stringify(sorted);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Stable fingerprint for an array of model instances.
|
|
30
|
+
*
|
|
31
|
+
* Sorted by `id` so result ordering doesn't cause false positives.
|
|
32
|
+
* `id` is a prototype getter and therefore not serialised by
|
|
33
|
+
* `JSON.stringify` automatically — it is extracted explicitly.
|
|
34
|
+
*
|
|
35
|
+
* Delegates to `instanceToSerializable` (from decorators.ts) which strips
|
|
36
|
+
* all non-decorator-registered fields — including the runtime-enumerable
|
|
37
|
+
* TypeScript `private _perspective` that would otherwise cause
|
|
38
|
+
* `JSON.stringify` to throw a circular-reference error via
|
|
39
|
+
* PerspectiveProxy → Apollo InMemoryCache.
|
|
40
|
+
*/
|
|
41
|
+
function stableFingerprint(results) {
|
|
42
|
+
const sorted = [...results].sort((a, b) => {
|
|
43
|
+
const aId = a.id ?? "";
|
|
44
|
+
const bId = b.id ?? "";
|
|
45
|
+
return aId < bId ? -1 : aId > bId ? 1 : 0;
|
|
46
|
+
});
|
|
47
|
+
return JSON.stringify(sorted.map(instanceToSerializable));
|
|
48
|
+
}
|
|
49
|
+
const registry = new WeakMap();
|
|
50
|
+
function getOrCreateSharedEntry(findAll, perspective, query, metadata, debounceMs, perspEntries, key) {
|
|
51
|
+
const existing = perspEntries.get(key);
|
|
52
|
+
if (existing)
|
|
53
|
+
return existing;
|
|
54
|
+
// Minimum coalesce window — even without a user-configured debounce, a
|
|
55
|
+
// single save() emits several link events; this collapses them into one
|
|
56
|
+
// findAll() call. Not a timing workaround — SurrealDB is guaranteed
|
|
57
|
+
// committed before link-added events are published.
|
|
58
|
+
const SETTLE_MS = 50;
|
|
59
|
+
const effectiveDebounce = Math.max(debounceMs, SETTLE_MS);
|
|
60
|
+
const watchedPredicates = new Set();
|
|
61
|
+
for (const prop of Object.values(metadata.properties)) {
|
|
62
|
+
if (prop.predicate)
|
|
63
|
+
watchedPredicates.add(prop.predicate);
|
|
64
|
+
}
|
|
65
|
+
for (const rel of Object.values(metadata.relations)) {
|
|
66
|
+
if (rel.predicate)
|
|
67
|
+
watchedPredicates.add(rel.predicate);
|
|
68
|
+
}
|
|
69
|
+
// If the query is scoped to a parent via parent query, also watch the
|
|
70
|
+
// parent-relationship predicate so that adding/removing a child link
|
|
71
|
+
// triggers a live re-query even though it's not in the child model's schema.
|
|
72
|
+
if (query.parent && 'predicate' in query.parent) {
|
|
73
|
+
watchedPredicates.add(query.parent.predicate);
|
|
74
|
+
}
|
|
75
|
+
const entry = {
|
|
76
|
+
listeners: new Map(),
|
|
77
|
+
lastResults: null,
|
|
78
|
+
lastFingerprint: null,
|
|
79
|
+
debounceTimer: null,
|
|
80
|
+
active: true,
|
|
81
|
+
detach: () => { },
|
|
82
|
+
};
|
|
83
|
+
const broadcast = (results) => {
|
|
84
|
+
for (const { callback, onError, setLastError, } of entry.listeners.values()) {
|
|
85
|
+
try {
|
|
86
|
+
callback(results);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
setLastError(err);
|
|
90
|
+
(onError ?? console.error)(err);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const notifyError = (err) => {
|
|
95
|
+
for (const { onError, setLastError } of entry.listeners.values()) {
|
|
96
|
+
setLastError(err);
|
|
97
|
+
(onError ?? console.error)(err);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const rerun = async () => {
|
|
101
|
+
if (!entry.active)
|
|
102
|
+
return;
|
|
103
|
+
try {
|
|
104
|
+
const results = await findAll(perspective, query);
|
|
105
|
+
if (!entry.active)
|
|
106
|
+
return;
|
|
107
|
+
// Only broadcast if results actually changed.
|
|
108
|
+
const fingerprint = stableFingerprint(results);
|
|
109
|
+
if (fingerprint === entry.lastFingerprint)
|
|
110
|
+
return;
|
|
111
|
+
entry.lastFingerprint = fingerprint;
|
|
112
|
+
entry.lastResults = results;
|
|
113
|
+
broadcast(results);
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
notifyError(err);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const scheduleRerun = () => {
|
|
120
|
+
if (entry.debounceTimer !== null)
|
|
121
|
+
clearTimeout(entry.debounceTimer);
|
|
122
|
+
entry.debounceTimer = setTimeout(rerun, effectiveDebounce);
|
|
123
|
+
};
|
|
124
|
+
// LinkCallback must return null (see PerspectiveClient.ts type definition)
|
|
125
|
+
const linkChangedCb = (link) => {
|
|
126
|
+
if (watchedPredicates.has(link.data?.predicate ?? ""))
|
|
127
|
+
scheduleRerun();
|
|
128
|
+
return null;
|
|
129
|
+
};
|
|
130
|
+
perspective.addListener("link-added", linkChangedCb);
|
|
131
|
+
perspective.addListener("link-removed", linkChangedCb);
|
|
132
|
+
entry.detach = () => {
|
|
133
|
+
// Fire-and-forget — removeListener is async but just does an array splice.
|
|
134
|
+
// entry.active = false ensures no further callbacks fire regardless.
|
|
135
|
+
perspective.removeListener("link-added", linkChangedCb);
|
|
136
|
+
perspective.removeListener("link-removed", linkChangedCb);
|
|
137
|
+
};
|
|
138
|
+
// Fire immediately with initial results.
|
|
139
|
+
rerun();
|
|
140
|
+
perspEntries.set(key, entry);
|
|
141
|
+
return entry;
|
|
142
|
+
}
|
|
143
|
+
// ─── Public API ───────────────────────────────────────────────────────────────
|
|
144
|
+
/**
|
|
145
|
+
* Creates a live subscription for a model query.
|
|
146
|
+
*
|
|
147
|
+
* Immediately invokes `callback` with the initial query results, then
|
|
148
|
+
* re-invokes it whenever a relevant link is added to or removed from the
|
|
149
|
+
* perspective.
|
|
150
|
+
*
|
|
151
|
+
* Multiple callers subscribing to the same model + query on the same
|
|
152
|
+
* perspective share a single `findAll()` execution and a single pair of link
|
|
153
|
+
* listeners via an internal registry. Callbacks are only fired when the
|
|
154
|
+
* result set has actually changed.
|
|
155
|
+
*
|
|
156
|
+
* @param findAll - The model's `findAll` static method
|
|
157
|
+
* @param getMetadata - The model's `getModelMetadata` static method
|
|
158
|
+
* @param perspective - The perspective to watch
|
|
159
|
+
* @param options - Query parameters + delivery options (debounce, onError)
|
|
160
|
+
* @param callback - Invoked with fresh results on every relevant change
|
|
161
|
+
* @returns A `Subscription` handle with `unsubscribe()` and `lastError`
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* ```typescript
|
|
165
|
+
* const sub = createSubscription(
|
|
166
|
+
* (p, q) => Post.findAll(p, q),
|
|
167
|
+
* () => Post.getModelMetadata(),
|
|
168
|
+
* perspective,
|
|
169
|
+
* { where: { published: true }, debounce: 200 },
|
|
170
|
+
* (posts) => console.log("Posts updated:", posts),
|
|
171
|
+
* );
|
|
172
|
+
*
|
|
173
|
+
* // Later:
|
|
174
|
+
* sub.unsubscribe();
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
export function createSubscription(findAll, getMetadata, perspective, options, callback, ctor) {
|
|
178
|
+
const { debounce: debounceMs = 0, onError, ...queryOptions } = options;
|
|
179
|
+
// Normalise model-backed parent query to { id, predicate } before key
|
|
180
|
+
// computation so the shared-entry registry and predicate watcher both
|
|
181
|
+
// operate on the resolved string form.
|
|
182
|
+
const rawParent = queryOptions.parent;
|
|
183
|
+
const resolvedOptions = rawParent
|
|
184
|
+
? { ...queryOptions, parent: normalizeParentQuery(rawParent, ctor) }
|
|
185
|
+
: queryOptions;
|
|
186
|
+
const query = resolvedOptions;
|
|
187
|
+
const metadata = getMetadata();
|
|
188
|
+
const key = `${metadata.className}:${stableQueryKey(query)}`;
|
|
189
|
+
let perspEntries = registry.get(perspective);
|
|
190
|
+
if (!perspEntries) {
|
|
191
|
+
perspEntries = new Map();
|
|
192
|
+
registry.set(perspective, perspEntries);
|
|
193
|
+
}
|
|
194
|
+
const entry = getOrCreateSharedEntry(findAll, perspective, query, metadata, debounceMs, perspEntries, key);
|
|
195
|
+
const listenerId = Symbol();
|
|
196
|
+
let lastError = null;
|
|
197
|
+
entry.listeners.set(listenerId, {
|
|
198
|
+
callback: callback,
|
|
199
|
+
onError,
|
|
200
|
+
setLastError: (err) => {
|
|
201
|
+
lastError = err;
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
// Late subscriber: if the shared entry already ran at least once, fire
|
|
205
|
+
// immediately with cached results — avoids an extra findAll() round-trip.
|
|
206
|
+
if (entry.lastResults !== null) {
|
|
207
|
+
const cached = entry.lastResults;
|
|
208
|
+
Promise.resolve().then(() => {
|
|
209
|
+
if (entry.listeners.has(listenerId))
|
|
210
|
+
callback(cached);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
get lastError() {
|
|
215
|
+
return lastError;
|
|
216
|
+
},
|
|
217
|
+
unsubscribe() {
|
|
218
|
+
entry.listeners.delete(listenerId);
|
|
219
|
+
if (entry.listeners.size === 0) {
|
|
220
|
+
// Last subscriber — tear down the shared entry entirely.
|
|
221
|
+
entry.active = false;
|
|
222
|
+
if (entry.debounceTimer !== null) {
|
|
223
|
+
clearTimeout(entry.debounceTimer);
|
|
224
|
+
entry.debounceTimer = null;
|
|
225
|
+
}
|
|
226
|
+
entry.detach();
|
|
227
|
+
perspEntries.delete(key);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|