@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0
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/lib/index.cjs +4968 -4805
- package/lib/index.js +4936 -4801
- package/lib/src/agent/AgentClient.d.ts +4 -0
- package/lib/src/agent/AgentClient.js +34 -0
- package/lib/src/index.d.ts +2 -3
- package/lib/src/index.js +2 -3
- package/lib/src/model/Ad4mModel.d.ts +8 -812
- package/lib/src/model/Ad4mModel.js +78 -2390
- package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
- package/lib/src/model/ModelQueryBuilder.js +556 -0
- package/lib/src/model/decorators.d.ts +2 -20
- package/lib/src/model/decorators.js +5 -410
- package/lib/src/model/hydration.d.ts +102 -0
- package/lib/src/model/hydration.js +709 -0
- package/lib/src/model/index.d.ts +20 -0
- package/lib/src/model/index.js +20 -0
- package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
- package/lib/src/model/json-schema.js +326 -0
- package/lib/src/model/prolog-facts.d.ts +37 -0
- package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
- package/lib/src/model/query-common.d.ts +14 -0
- package/lib/src/model/query-common.js +36 -0
- package/lib/src/model/query-prolog.d.ts +15 -0
- package/lib/src/model/query-prolog.js +140 -0
- package/lib/src/model/query-surreal.d.ts +44 -0
- package/lib/src/model/query-surreal.js +249 -0
- package/lib/src/model/sdna.d.ts +14 -0
- package/lib/src/model/sdna.js +141 -0
- package/lib/src/model/shacl-gen.d.ts +31 -0
- package/lib/src/model/shacl-gen.js +246 -0
- package/lib/src/model/surreal-utils.d.ts +1 -1
- package/lib/src/model/types.d.ts +75 -96
- package/lib/src/model/types.js +4 -4
- package/lib/src/model/util.d.ts +4 -5
- package/lib/src/model/util.js +12 -32
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
- package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
- package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
- package/lib/src/runtime/RuntimeResolver.js +73 -0
- package/lib/src/schema.gql +14 -0
- package/lib/src/typeDefs.js +14 -0
- package/package.json +13 -8
- package/src/agent/AgentClient.ts +45 -0
- package/src/index.ts +2 -3
- package/src/model/Ad4mModel.ts +1084 -3818
- package/src/model/ModelQueryBuilder.ts +617 -0
- package/src/model/Subject.ts +1 -1
- package/src/model/decorators.ts +17 -475
- package/src/model/hydration.ts +796 -0
- package/src/model/index.ts +21 -0
- package/src/model/json-schema.ts +424 -0
- package/src/model/prolog-facts.ts +145 -0
- package/src/model/query-common.ts +48 -0
- package/src/model/query-prolog.ts +148 -0
- package/src/model/query-surreal.ts +280 -0
- package/src/model/relation-filtering.test.ts +0 -1
- package/src/model/sdna.ts +170 -0
- package/src/model/shacl-gen.ts +292 -0
- package/src/model/surreal-utils.ts +1 -1
- package/src/model/types.ts +182 -0
- package/src/model/util.ts +13 -36
- package/src/perspectives/PerspectiveClient.ts +1 -1
- package/src/perspectives/PerspectiveProxy.ts +1 -1
- package/src/perspectives/WakerSubscriptionManager.ts +292 -0
- package/src/runtime/RuntimeResolver.ts +53 -0
- package/lib/src/Ad4mClient.test.d.ts +0 -1
- package/lib/src/Ad4mClient.test.js +0 -1204
- package/lib/src/Literal.test.d.ts +0 -1
- package/lib/src/Literal.test.js +0 -41
- package/lib/src/model/mutation.d.ts +0 -81
- package/lib/src/model/mutation.js +0 -317
- package/lib/src/model/parentUtils.d.ts +0 -32
- package/lib/src/model/parentUtils.js +0 -64
- package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
- package/lib/src/model/prolog/index.d.ts +0 -1
- package/lib/src/model/prolog/index.js +0 -1
- package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
- package/lib/src/model/query/ModelQueryBuilder.js +0 -115
- package/lib/src/model/query/QueryBuilder.d.ts +0 -101
- package/lib/src/model/query/QueryBuilder.js +0 -193
- package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
- package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
- package/lib/src/model/query/fetchInstance.d.ts +0 -24
- package/lib/src/model/query/fetchInstance.js +0 -144
- package/lib/src/model/query/hydration.d.ts +0 -54
- package/lib/src/model/query/hydration.js +0 -214
- package/lib/src/model/query/operations.d.ts +0 -59
- package/lib/src/model/query/operations.js +0 -384
- package/lib/src/model/query/snapshot.d.ts +0 -59
- package/lib/src/model/query/snapshot.js +0 -106
- package/lib/src/model/query/surrealCompiler.d.ts +0 -42
- package/lib/src/model/query/surrealCompiler.js +0 -304
- package/lib/src/model/schema/fromJSONSchema.js +0 -264
- package/lib/src/model/schema/metadata.d.ts +0 -15
- package/lib/src/model/schema/metadata.js +0 -112
- package/lib/src/model/subscription.d.ts +0 -47
- package/lib/src/model/subscription.js +0 -231
- package/lib/src/model/transaction.d.ts +0 -27
- package/lib/src/model/transaction.js +0 -32
- package/lib/src/shims/reflect-metadata.d.ts +0 -0
- package/lib/src/shims/type-graphql.d.ts +0 -32
- package/lib/src/src/Ad4mClient.d.ts +0 -28
- package/lib/src/src/Address.d.ts +0 -1
- package/lib/src/src/DID.d.ts +0 -1
- package/lib/src/src/Exception.d.ts +0 -7
- package/lib/src/src/Literal.d.ts +0 -7
- package/lib/src/src/PubSub.d.ts +0 -17
- package/lib/src/src/SmartLiteral.d.ts +0 -12
- package/lib/src/src/agent/Agent.d.ts +0 -110
- package/lib/src/src/agent/AgentClient.d.ts +0 -62
- package/lib/src/src/agent/AgentResolver.d.ts +0 -30
- package/lib/src/src/agent/AgentStatus.d.ts +0 -8
- package/lib/src/src/ai/AIClient.d.ts +0 -32
- package/lib/src/src/ai/AIResolver.d.ts +0 -75
- package/lib/src/src/ai/Tasks.d.ts +0 -37
- package/lib/src/src/buildSchema.d.ts +0 -1
- package/lib/src/src/expression/Expression.d.ts +0 -28
- package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
- package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
- package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
- package/lib/src/src/index.d.ts +0 -35
- package/lib/src/src/jestSetup.d.ts +0 -1
- package/lib/src/src/language/Icon.d.ts +0 -4
- package/lib/src/src/language/Language.d.ts +0 -206
- package/lib/src/src/language/LanguageClient.d.ts +0 -17
- package/lib/src/src/language/LanguageContext.d.ts +0 -37
- package/lib/src/src/language/LanguageHandle.d.ts +0 -9
- package/lib/src/src/language/LanguageMeta.d.ts +0 -35
- package/lib/src/src/language/LanguageRef.d.ts +0 -6
- package/lib/src/src/language/LanguageResolver.d.ts +0 -19
- package/lib/src/src/links/Links.d.ts +0 -39
- package/lib/src/src/links/Links.test.d.ts +0 -1
- package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
- package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
- package/lib/src/src/model/Subject.d.ts +0 -25
- package/lib/src/src/model/decorators.d.ts +0 -545
- package/lib/src/src/model/util.d.ts +0 -12
- package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
- package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
- package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
- package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
- package/lib/src/src/perspectives/Perspective.d.ts +0 -38
- package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
- package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
- package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
- package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
- package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
- package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
- package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
- package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
- package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
- package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
- package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
- package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
- package/lib/src/src/typeDefs.d.ts +0 -1
- package/lib/src/src/unwrapApolloResult.d.ts +0 -2
- package/lib/src/src/utils.d.ts +0 -25
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ad4mModel — barrel re-exports.
|
|
3
|
+
*
|
|
4
|
+
* All public symbols from the model subsystem are re-exported here so that
|
|
5
|
+
* consumers can import from `"./model"` (or `"@coasys/ad4m"` via the
|
|
6
|
+
* top-level barrel) without knowing the internal file layout.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export * from "./types";
|
|
10
|
+
export * from "./Ad4mModel";
|
|
11
|
+
export * from "./decorators";
|
|
12
|
+
export * from "./Subject";
|
|
13
|
+
export * from "./query-common";
|
|
14
|
+
export * from "./query-prolog";
|
|
15
|
+
export * from "./prolog-facts";
|
|
16
|
+
export * from "./json-schema";
|
|
17
|
+
export * from "./query-surreal";
|
|
18
|
+
export * from "./hydration";
|
|
19
|
+
export * from "./ModelQueryBuilder";
|
|
20
|
+
export * from "./sdna";
|
|
21
|
+
export * from "./shacl-gen";
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema → Ad4mModel class builder and related utilities.
|
|
3
|
+
*
|
|
4
|
+
* Contains:
|
|
5
|
+
* - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
|
|
6
|
+
* - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
|
|
7
|
+
* - Predicate / namespace resolution helpers
|
|
8
|
+
* - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Ad4mModel } from "./Ad4mModel";
|
|
14
|
+
import { capitalize, propertyNameToSetterName } from "./util";
|
|
15
|
+
import type { PropertyOptions } from "./decorators";
|
|
16
|
+
import { Model, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
|
|
17
|
+
|
|
18
|
+
// ─── JSON Schema Type Definitions ────────────────────────────────────────────
|
|
19
|
+
|
|
20
|
+
export interface JSONSchemaProperty {
|
|
21
|
+
type: string | string[];
|
|
22
|
+
items?: JSONSchemaProperty;
|
|
23
|
+
properties?: { [key: string]: JSONSchemaProperty };
|
|
24
|
+
required?: string[];
|
|
25
|
+
"x-ad4m"?: {
|
|
26
|
+
through?: string;
|
|
27
|
+
resolveLanguage?: string;
|
|
28
|
+
local?: boolean;
|
|
29
|
+
writable?: boolean;
|
|
30
|
+
initial?: string;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface JSONSchema {
|
|
35
|
+
$schema?: string;
|
|
36
|
+
title?: string;
|
|
37
|
+
$id?: string;
|
|
38
|
+
type?: string;
|
|
39
|
+
properties?: { [key: string]: JSONSchemaProperty };
|
|
40
|
+
required?: string[];
|
|
41
|
+
"x-ad4m"?: {
|
|
42
|
+
namespace?: string;
|
|
43
|
+
className?: string;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface JSONSchemaToModelOptions {
|
|
48
|
+
name: string;
|
|
49
|
+
namespace?: string;
|
|
50
|
+
predicateTemplate?: string;
|
|
51
|
+
predicateGenerator?: (title: string, property: string) => string;
|
|
52
|
+
propertyMapping?: Record<string, string>;
|
|
53
|
+
resolveLanguage?: string;
|
|
54
|
+
local?: boolean;
|
|
55
|
+
propertyOptions?: Record<string, Partial<PropertyOptions>>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ─── Schema Type Helpers ─────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
export function normalizeNamespaceString(namespace: string): string {
|
|
61
|
+
if (!namespace) return '';
|
|
62
|
+
if (namespace.includes('://')) {
|
|
63
|
+
const [scheme, rest] = namespace.split('://');
|
|
64
|
+
const path = (rest || '').replace(/\/+$/,'');
|
|
65
|
+
return `${scheme}://${path}`;
|
|
66
|
+
} else {
|
|
67
|
+
return namespace.replace(/\/+$/,'');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function normalizeSchemaType(type?: string | string[]): string | undefined {
|
|
72
|
+
if (!type) return undefined;
|
|
73
|
+
if (typeof type === "string") return type;
|
|
74
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
75
|
+
const nonNull = type.find((t) => t !== "null");
|
|
76
|
+
return nonNull || type[0];
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function isSchemaType(schema: JSONSchemaProperty, expectedType: string): boolean {
|
|
82
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function isArrayType(schema: JSONSchemaProperty): boolean {
|
|
86
|
+
return isSchemaType(schema, "array");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function isObjectType(schema: JSONSchemaProperty): boolean {
|
|
90
|
+
return isSchemaType(schema, "object");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function isNumericType(schema: JSONSchemaProperty): boolean {
|
|
94
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
95
|
+
return normalized === "number" || normalized === "integer";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ─── Predicate / Namespace Resolution ────────────────────────────────────────
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Determines the namespace for predicates using cascading precedence:
|
|
102
|
+
* 1. Explicit namespace in options
|
|
103
|
+
* 2. x-ad4m metadata in schema
|
|
104
|
+
* 3. Infer from schema title
|
|
105
|
+
* 4. Try to extract from $id
|
|
106
|
+
* 5. Error if nothing works
|
|
107
|
+
*/
|
|
108
|
+
export function determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string {
|
|
109
|
+
// 1. Explicit namespace in options (highest precedence)
|
|
110
|
+
if (options.namespace) {
|
|
111
|
+
return options.namespace;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 2. x-ad4m metadata in schema
|
|
115
|
+
if (schema["x-ad4m"]?.namespace) {
|
|
116
|
+
return schema["x-ad4m"].namespace;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 3. Infer from schema title
|
|
120
|
+
if (schema.title) {
|
|
121
|
+
return `${schema.title.toLowerCase()}://`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 4. Try to extract from $id if it's a URL
|
|
125
|
+
if (schema.$id) {
|
|
126
|
+
try {
|
|
127
|
+
const url = new URL(schema.$id);
|
|
128
|
+
const pathParts = url.pathname.split('/').filter(p => p);
|
|
129
|
+
if (pathParts.length > 0) {
|
|
130
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
131
|
+
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
132
|
+
return `${baseName.toLowerCase()}://`;
|
|
133
|
+
}
|
|
134
|
+
} catch {
|
|
135
|
+
// If $id is not a valid URL, continue to error
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 5. Error if no namespace can be determined
|
|
140
|
+
throw new Error(
|
|
141
|
+
`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
142
|
+
- options.namespace
|
|
143
|
+
- schema["x-ad4m"].namespace
|
|
144
|
+
- schema.title
|
|
145
|
+
- valid schema.$id`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Determines the predicate for a specific property using cascading precedence:
|
|
151
|
+
* 1. Explicit property mapping
|
|
152
|
+
* 2. x-ad4m metadata in property schema
|
|
153
|
+
* 3. Predicate template
|
|
154
|
+
* 4. Custom predicate generator
|
|
155
|
+
* 5. Default: namespace + property name
|
|
156
|
+
*/
|
|
157
|
+
export function determinePredicate(
|
|
158
|
+
schema: JSONSchema,
|
|
159
|
+
propertyName: string,
|
|
160
|
+
propertySchema: JSONSchemaProperty,
|
|
161
|
+
namespace: string,
|
|
162
|
+
options: JSONSchemaToModelOptions
|
|
163
|
+
): string {
|
|
164
|
+
// 1. Explicit property mapping (highest precedence)
|
|
165
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
166
|
+
return options.propertyMapping[propertyName];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 2. x-ad4m metadata in property schema
|
|
170
|
+
if (propertySchema["x-ad4m"]?.through) {
|
|
171
|
+
return propertySchema["x-ad4m"].through;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 3. Generate from namespace + property name
|
|
175
|
+
if (options.predicateTemplate) {
|
|
176
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
177
|
+
const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
|
|
178
|
+
const nsNoScheme = rest || '';
|
|
179
|
+
return options.predicateTemplate
|
|
180
|
+
.replace('${namespace}', nsNoScheme)
|
|
181
|
+
.replace('${scheme}', scheme)
|
|
182
|
+
.replace('${ns}', nsNoScheme)
|
|
183
|
+
.replace('${title}', schema.title || '')
|
|
184
|
+
.replace('${property}', propertyName);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 4. Custom predicate generator
|
|
188
|
+
if (options.predicateGenerator) {
|
|
189
|
+
return options.predicateGenerator(schema.title || '', propertyName);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// 5. Default: namespace + property name
|
|
193
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
194
|
+
if (normalizedNs.includes('://')) {
|
|
195
|
+
// For namespaces like "product://", append property directly
|
|
196
|
+
return `${normalizedNs}${propertyName}`;
|
|
197
|
+
} else {
|
|
198
|
+
return `${normalizedNs}://${propertyName}`;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Gets property-specific options using cascading precedence:
|
|
204
|
+
* 1. Property-specific options
|
|
205
|
+
* 2. x-ad4m metadata in property
|
|
206
|
+
* 3. Global option
|
|
207
|
+
* 4. Default value
|
|
208
|
+
*/
|
|
209
|
+
export function getPropertyOption(
|
|
210
|
+
propertyName: string,
|
|
211
|
+
propertySchema: JSONSchemaProperty,
|
|
212
|
+
options: JSONSchemaToModelOptions,
|
|
213
|
+
optionName: keyof PropertyOptions,
|
|
214
|
+
defaultValue?: any
|
|
215
|
+
): any {
|
|
216
|
+
// 1. Property-specific options
|
|
217
|
+
if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
|
|
218
|
+
return options.propertyOptions[propertyName][optionName];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// 2. x-ad4m metadata in property
|
|
222
|
+
if (propertySchema["x-ad4m"]?.[optionName as keyof JSONSchemaProperty["x-ad4m"]] !== undefined) {
|
|
223
|
+
return propertySchema["x-ad4m"][optionName as keyof JSONSchemaProperty["x-ad4m"]];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 3. Global option
|
|
227
|
+
if (options[optionName as keyof JSONSchemaToModelOptions] !== undefined) {
|
|
228
|
+
return options[optionName as keyof JSONSchemaToModelOptions];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// 4. Default value
|
|
232
|
+
return defaultValue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Gets default value for a JSON Schema type.
|
|
237
|
+
*/
|
|
238
|
+
export function getDefaultValueForType(type?: string): any {
|
|
239
|
+
switch (type) {
|
|
240
|
+
case 'string': return '';
|
|
241
|
+
case 'number': return 0;
|
|
242
|
+
case 'integer': return 0;
|
|
243
|
+
case 'boolean': return false;
|
|
244
|
+
case 'array': return [];
|
|
245
|
+
case 'object': return {};
|
|
246
|
+
default: return '';
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ─── buildModelFromJSONSchema ────────────────────────────────────────────────
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Core implementation of `Ad4mModel.fromJSONSchema()`.
|
|
254
|
+
*
|
|
255
|
+
* Creates a dynamic Ad4mModel subclass from a JSON Schema definition,
|
|
256
|
+
* wiring up property / relation metadata, setters, and the `@Model` decorator.
|
|
257
|
+
*
|
|
258
|
+
* @param BaseClass - The Ad4mModel class (or subclass) to extend
|
|
259
|
+
* @param schema - JSON Schema definition
|
|
260
|
+
* @param options - Configuration options
|
|
261
|
+
* @returns Generated Ad4mModel subclass
|
|
262
|
+
*/
|
|
263
|
+
export function buildModelFromJSONSchema(
|
|
264
|
+
BaseClass: typeof Ad4mModel,
|
|
265
|
+
schema: JSONSchema,
|
|
266
|
+
options: JSONSchemaToModelOptions
|
|
267
|
+
): typeof Ad4mModel {
|
|
268
|
+
// Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
|
|
269
|
+
if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
|
|
270
|
+
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").');
|
|
271
|
+
}
|
|
272
|
+
// Determine namespace with cascading precedence
|
|
273
|
+
const namespace = determineNamespace(schema, options);
|
|
274
|
+
|
|
275
|
+
// Create the dynamic class
|
|
276
|
+
const DynamicModelClass = class extends (BaseClass as any) {} as unknown as typeof Ad4mModel;
|
|
277
|
+
|
|
278
|
+
// Set up class metadata
|
|
279
|
+
if (!options.name || options.name.trim() === '') {
|
|
280
|
+
throw new Error("options.name is required and cannot be empty");
|
|
281
|
+
}
|
|
282
|
+
(DynamicModelClass as any).className = options.name;
|
|
283
|
+
(DynamicModelClass.prototype as any).className = options.name;
|
|
284
|
+
|
|
285
|
+
// Generate properties and relations metadata
|
|
286
|
+
const properties: any = {};
|
|
287
|
+
const relations: any = {};
|
|
288
|
+
|
|
289
|
+
if (schema.properties) {
|
|
290
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
291
|
+
const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);
|
|
292
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
293
|
+
const propertyType = normalizeSchemaType(propertySchema.type);
|
|
294
|
+
const isArray = isArrayType(propertySchema);
|
|
295
|
+
|
|
296
|
+
if (isArray) {
|
|
297
|
+
// Handle arrays as relations
|
|
298
|
+
// Store the singular form as the relation key since SDNA generation expects singular
|
|
299
|
+
relations[propertyName] = {
|
|
300
|
+
through: predicate,
|
|
301
|
+
local: getPropertyOption(propertyName, propertySchema, options, 'local')
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
// Define the property on prototype
|
|
305
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
306
|
+
configurable: true,
|
|
307
|
+
writable: true,
|
|
308
|
+
value: []
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Add relation methods
|
|
312
|
+
const adderName = `add${capitalize(propertyName)}`;
|
|
313
|
+
const removerName = `remove${capitalize(propertyName)}`;
|
|
314
|
+
const setterName = `set${capitalize(propertyName)}`;
|
|
315
|
+
|
|
316
|
+
(DynamicModelClass.prototype as any)[adderName] = function() {
|
|
317
|
+
// Placeholder function for SDNA generation
|
|
318
|
+
};
|
|
319
|
+
(DynamicModelClass.prototype as any)[removerName] = function() {
|
|
320
|
+
// Placeholder function for SDNA generation
|
|
321
|
+
};
|
|
322
|
+
(DynamicModelClass.prototype as any)[setterName] = function() {
|
|
323
|
+
// Placeholder function for SDNA generation
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
} else {
|
|
327
|
+
// Handle regular properties
|
|
328
|
+
let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
|
|
329
|
+
// If no specific resolveLanguage for this property, use the global one
|
|
330
|
+
if (!resolveLanguage && options.resolveLanguage) {
|
|
331
|
+
resolveLanguage = options.resolveLanguage;
|
|
332
|
+
}
|
|
333
|
+
const local = getPropertyOption(propertyName, propertySchema, options, 'local');
|
|
334
|
+
// Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
|
|
335
|
+
let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');
|
|
336
|
+
if (readOnly === undefined) {
|
|
337
|
+
const xWritable = propertySchema["x-ad4m"]?.writable;
|
|
338
|
+
readOnly = xWritable !== undefined ? !xWritable : false;
|
|
339
|
+
}
|
|
340
|
+
const writable = !readOnly;
|
|
341
|
+
let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');
|
|
342
|
+
|
|
343
|
+
// Handle nested objects by serializing to JSON
|
|
344
|
+
if (isObjectType(propertySchema) && !resolveLanguage) {
|
|
345
|
+
resolveLanguage = 'literal';
|
|
346
|
+
console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Ensure numeric properties use literal language for correct typing
|
|
350
|
+
if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
|
|
351
|
+
resolveLanguage = 'literal';
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Default resolveLanguage to 'literal' for all remaining property types,
|
|
355
|
+
// matching the @Property decorator behaviour. Without this, string values
|
|
356
|
+
// stored as literal:// URLs are returned unparsed.
|
|
357
|
+
if (resolveLanguage === undefined || resolveLanguage === null) {
|
|
358
|
+
resolveLanguage = 'literal';
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// If property is required, ensure it has an initial value
|
|
362
|
+
if (isRequired && !initial) {
|
|
363
|
+
if (isObjectType(propertySchema)) {
|
|
364
|
+
initial = 'literal://json:{}';
|
|
365
|
+
} else {
|
|
366
|
+
initial = "ad4m://undefined";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
properties[propertyName] = {
|
|
371
|
+
through: predicate,
|
|
372
|
+
required: isRequired,
|
|
373
|
+
writable: writable,
|
|
374
|
+
...(resolveLanguage && { resolveLanguage }),
|
|
375
|
+
...(local !== undefined && { local }),
|
|
376
|
+
...(initial && { initial })
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
// Define the property on prototype
|
|
380
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
381
|
+
configurable: true,
|
|
382
|
+
writable: true,
|
|
383
|
+
value: getDefaultValueForType(propertyType)
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
// Add setter function if writable
|
|
387
|
+
if (writable) {
|
|
388
|
+
const setterName = propertyNameToSetterName(propertyName);
|
|
389
|
+
(DynamicModelClass.prototype as any)[setterName] = function() {
|
|
390
|
+
// This is a placeholder function that the SDNA generation looks for
|
|
391
|
+
// The actual setter logic is handled by the Ad4mModel base class
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// No auto-flag generation — models with all-optional properties use
|
|
399
|
+
// open-world structural matching. Consumers who need type discrimination
|
|
400
|
+
// should add an explicit @Flag to their model definition.
|
|
401
|
+
|
|
402
|
+
// Attach metadata to WeakMap registries
|
|
403
|
+
for (const [propName, propMeta] of Object.entries(properties)) {
|
|
404
|
+
setPropertyRegistryEntry(DynamicModelClass, propName, propMeta as any);
|
|
405
|
+
}
|
|
406
|
+
for (const [relName, relMeta] of Object.entries(relations)) {
|
|
407
|
+
setRelationRegistryEntry(DynamicModelClass, relName, {
|
|
408
|
+
predicate: (relMeta as any).through || "",
|
|
409
|
+
kind: 'hasMany',
|
|
410
|
+
...(( relMeta as any).getter !== undefined && { getter: (relMeta as any).getter }),
|
|
411
|
+
...(( relMeta as any).local !== undefined && { local: (relMeta as any).local }),
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
|
|
416
|
+
(DynamicModelClass.prototype as any).__jsonSchema = schema;
|
|
417
|
+
(DynamicModelClass.prototype as any).__jsonSchemaOptions = options;
|
|
418
|
+
|
|
419
|
+
// Apply the Model decorator to set up the generateSDNA method
|
|
420
|
+
const ModelDecorator = Model({ name: options.name });
|
|
421
|
+
ModelDecorator(DynamicModelClass);
|
|
422
|
+
|
|
423
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
424
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone Prolog fact generator for Ad4mModel classes.
|
|
3
|
+
*
|
|
4
|
+
* Converts decorator metadata into Prolog clauses that can be prepended to
|
|
5
|
+
* `perspective.infer()` calls, enabling custom Prolog rules to reference
|
|
6
|
+
* model instances and their fields.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ModelMetadata, PropertyMetadata, RelationMetadata } from "./types";
|
|
10
|
+
import type { Ad4mModel } from "./Ad4mModel";
|
|
11
|
+
|
|
12
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Convert a camelCase or PascalCase identifier to snake_case.
|
|
16
|
+
* Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
|
|
17
|
+
*/
|
|
18
|
+
function toSnakeCase(str: string): string {
|
|
19
|
+
return str
|
|
20
|
+
.replace(/([A-Z])/g, "_$1")
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.replace(/^_/, "");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function buildInstanceClause(predicateName: string, metadata: ModelMetadata): string | null {
|
|
26
|
+
const props = metadata.properties;
|
|
27
|
+
// Collect flags first — these are the strongest recognizers
|
|
28
|
+
const flags = Object.values(props).filter((p) => p.flag && p.predicate && p.initial);
|
|
29
|
+
if (flags.length > 0) {
|
|
30
|
+
const conditions = flags
|
|
31
|
+
.map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
|
|
32
|
+
.join(",\n ");
|
|
33
|
+
return `${predicateName}(X) :-\n ${conditions}.`;
|
|
34
|
+
}
|
|
35
|
+
// Fallback: required non-flag properties
|
|
36
|
+
const required = Object.values(props).filter((p) => p.required && p.predicate && !p.flag);
|
|
37
|
+
if (required.length > 0) {
|
|
38
|
+
const conditions = required
|
|
39
|
+
.map((p) => `triple(X, '${p.predicate}', _)`)
|
|
40
|
+
.join(",\n ");
|
|
41
|
+
return `${predicateName}(X) :-\n ${conditions}.`;
|
|
42
|
+
}
|
|
43
|
+
// Open-world structural fallback: match nodes that have at least one of the
|
|
44
|
+
// model's declared property predicates. Uses disjunction (;) so any single
|
|
45
|
+
// predicate is enough.
|
|
46
|
+
const allPredicates = Object.values(props)
|
|
47
|
+
.filter((p) => p.predicate)
|
|
48
|
+
.map((p) => p.predicate!);
|
|
49
|
+
if (metadata.relations) {
|
|
50
|
+
for (const rel of Object.values(metadata.relations)) {
|
|
51
|
+
if (rel.predicate) allPredicates.push(rel.predicate);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (allPredicates.length > 0) {
|
|
55
|
+
const disjunction = allPredicates
|
|
56
|
+
.map((pred) => `triple(X, '${pred}', _)`)
|
|
57
|
+
.join(" ;\n ");
|
|
58
|
+
return `${predicateName}(X) :-\n (${disjunction}).`;
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function buildPropertyClause(modelPredicateName: string, prop: PropertyMetadata): string | null {
|
|
64
|
+
if (prop.flag) return null;
|
|
65
|
+
if (!prop.predicate) return null;
|
|
66
|
+
const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
|
|
67
|
+
return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function buildRelationClause(modelPredicateName: string, relation: RelationMetadata): string | null {
|
|
71
|
+
if (!relation.predicate) return null;
|
|
72
|
+
const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
|
|
73
|
+
if (relation.direction === "reverse") {
|
|
74
|
+
return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
|
|
75
|
+
}
|
|
76
|
+
return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ── Public API ───────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Generate Prolog predicate facts from a model class's decorator metadata.
|
|
83
|
+
*
|
|
84
|
+
* Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
|
|
85
|
+
* `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
|
|
86
|
+
* Prolog clauses that can be prepended to any `perspective.infer()` call.
|
|
87
|
+
*
|
|
88
|
+
* The generated predicates are:
|
|
89
|
+
* - **Instance recognizer** — `modelName(X)` — matches instances of the model
|
|
90
|
+
* - **Property getters** — `modelName_propName(X, Value)` — one per property
|
|
91
|
+
* - **Relation getters** — `modelName_relName(X, Values)` — one per relation
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```typescript
|
|
95
|
+
* import { generatePrologFacts } from '@coasys/ad4m';
|
|
96
|
+
*
|
|
97
|
+
* const facts = generatePrologFacts(Poll);
|
|
98
|
+
* const result = await perspective.infer(\`
|
|
99
|
+
* \${facts}
|
|
100
|
+
* recent_popular_poll(X) :-
|
|
101
|
+
* poll(X),
|
|
102
|
+
* poll_vote_count(X, N), N > 10.
|
|
103
|
+
* \`);
|
|
104
|
+
* ```
|
|
105
|
+
*
|
|
106
|
+
* @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
|
|
107
|
+
* @returns A multi-line Prolog string ready for use with `perspective.infer()`
|
|
108
|
+
*/
|
|
109
|
+
export function generatePrologFacts(ModelClass: typeof Ad4mModel): string {
|
|
110
|
+
const metadata = ModelClass.getModelMetadata();
|
|
111
|
+
const predicateName = toSnakeCase(metadata.className);
|
|
112
|
+
const lines: string[] = [];
|
|
113
|
+
|
|
114
|
+
lines.push(`% ${metadata.className} — generated Prolog facts`);
|
|
115
|
+
|
|
116
|
+
// Instance recognizer
|
|
117
|
+
const instanceClause = buildInstanceClause(predicateName, metadata);
|
|
118
|
+
if (instanceClause) {
|
|
119
|
+
lines.push("");
|
|
120
|
+
lines.push(`% Instance recognizer`);
|
|
121
|
+
lines.push(instanceClause);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Property getters
|
|
125
|
+
const propClauses = Object.values(metadata.properties)
|
|
126
|
+
.map((p) => buildPropertyClause(predicateName, p))
|
|
127
|
+
.filter((c): c is string => c !== null);
|
|
128
|
+
if (propClauses.length > 0) {
|
|
129
|
+
lines.push("");
|
|
130
|
+
lines.push(`% Field getters`);
|
|
131
|
+
lines.push(...propClauses);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Relation getters
|
|
135
|
+
const relClauses = Object.values(metadata.relations)
|
|
136
|
+
.map((c) => buildRelationClause(predicateName, c))
|
|
137
|
+
.filter((c): c is string => c !== null);
|
|
138
|
+
if (relClauses.length > 0) {
|
|
139
|
+
lines.push("");
|
|
140
|
+
lines.push(`% Relation getters`);
|
|
141
|
+
lines.push(...relClauses);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return lines.join("\n");
|
|
145
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared query helpers used by both the Prolog and SurrealQL query pipelines.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { ParentScope } from "./types";
|
|
6
|
+
import { getRelationsMetadata } from "./decorators";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Resolves the predicate for a parent query.
|
|
10
|
+
*
|
|
11
|
+
* Uses TS discriminated union narrowing:
|
|
12
|
+
* - Raw form (`{ id, predicate }`) → predicate used as-is
|
|
13
|
+
* - Model form (`{ model, id, field? }`) → lookup from relation metadata
|
|
14
|
+
* - With `field`: direct key lookup
|
|
15
|
+
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
16
|
+
*/
|
|
17
|
+
export function resolveParentPredicate(
|
|
18
|
+
parent: ParentScope,
|
|
19
|
+
childCtor: Function,
|
|
20
|
+
): string {
|
|
21
|
+
// Raw form — explicit predicate
|
|
22
|
+
if ('predicate' in parent) return parent.predicate;
|
|
23
|
+
|
|
24
|
+
// Model form — resolve from relation metadata
|
|
25
|
+
const { model } = parent;
|
|
26
|
+
const relMeta = getRelationsMetadata(model);
|
|
27
|
+
|
|
28
|
+
// Direct lookup by field name when provided
|
|
29
|
+
if (parent.field) {
|
|
30
|
+
const entry = relMeta[parent.field];
|
|
31
|
+
if (!entry) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`parent(): field "${parent.field}" is not a registered relation on ${model.name}`,
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return entry.predicate;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Fallback: scan for a relation whose target matches the child class
|
|
40
|
+
for (const [, entry] of Object.entries(relMeta)) {
|
|
41
|
+
if (entry.target && entry.target() === childCtor) {
|
|
42
|
+
return entry.predicate;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
throw new Error(
|
|
46
|
+
`parent(): could not resolve predicate — no relation on ${model.name} targets ${(childCtor as any).name || 'the queried class'}`,
|
|
47
|
+
);
|
|
48
|
+
}
|