@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
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Dirty-tracking snapshot registry for Ad4mModel instances.
|
|
3
|
-
*
|
|
4
|
-
* A lightweight WeakMap-based store that records the schema-declared field
|
|
5
|
-
* values of an instance immediately after hydration or save. `innerUpdate`
|
|
6
|
-
* consults this snapshot to skip writing fields that haven't changed since the
|
|
7
|
-
* last successful persist, preventing the "re-save duplicates relations" bug.
|
|
8
|
-
*
|
|
9
|
-
* ## Design notes
|
|
10
|
-
*
|
|
11
|
-
* - A **WeakMap** is used so snapshot entries are GC'd when the instance is
|
|
12
|
-
* collected — no manual cleanup needed.
|
|
13
|
-
* - Arrays are normalised to `string[]` on capture (model instances → their ID
|
|
14
|
-
* URI) so the comparison is stable regardless of whether `include` hydration
|
|
15
|
-
* was used.
|
|
16
|
-
* - There is **no snapshot** for a freshly constructed instance that has never
|
|
17
|
-
* been hydrated or saved. `isDirty` returns `true` in that case, preserving
|
|
18
|
-
* existing create-path behaviour (write everything).
|
|
19
|
-
* - Only Tier-1 saves (no caller-provided `batchId`) trigger a post-save
|
|
20
|
-
* rehydration via `fetchInstanceData`, which re-captures the snapshot. Tier-2
|
|
21
|
-
* / Tier-3 (caller-managed batch / `transaction()`) skip rehydration by
|
|
22
|
-
* design; fields that were not changed may be re-sent on the next Tier-1
|
|
23
|
-
* save, which is idempotent and acceptable.
|
|
24
|
-
*/
|
|
25
|
-
type SnapshotEntry = Record<string, any>;
|
|
26
|
-
/**
|
|
27
|
-
* Records the current schema-field values of `instance` as its clean baseline.
|
|
28
|
-
*
|
|
29
|
-
* Call this after every hydration (bulk or single-instance path) and after
|
|
30
|
-
* every successful internal-batch save (the latter comes for free because
|
|
31
|
-
* `saveInstance` calls `fetchInstanceData` which ends with a `captureSnapshot`
|
|
32
|
-
* call).
|
|
33
|
-
*
|
|
34
|
-
* @param instance - The Ad4mModel instance to snapshot.
|
|
35
|
-
* @param keys - Schema-declared field names to record (@Property keys +
|
|
36
|
-
* relation keys). Internal machinery (`_id`, `_perspective`,
|
|
37
|
-
* dynamically-wired `addX`/`removeX`/`setX` methods) must
|
|
38
|
-
* NOT be included.
|
|
39
|
-
*/
|
|
40
|
-
export declare function captureSnapshot(instance: object, keys: string[]): void;
|
|
41
|
-
/**
|
|
42
|
-
* Returns the snapshot entry for `instance`, or `undefined` if none has been
|
|
43
|
-
* captured yet (i.e. the instance has never been hydrated or saved via an
|
|
44
|
-
* internal batch).
|
|
45
|
-
*/
|
|
46
|
-
export declare function readSnapshot(instance: object): SnapshotEntry | undefined;
|
|
47
|
-
/**
|
|
48
|
-
* Returns `true` if `currentValue` differs from the snapshot value for `key`.
|
|
49
|
-
*
|
|
50
|
-
* Always returns `true` (→ write the field) when:
|
|
51
|
-
* - No snapshot has been captured (create path / instance never hydrated).
|
|
52
|
-
* - The key was not present in the snapshot (new field added after hydration).
|
|
53
|
-
*
|
|
54
|
-
* Array comparison is order-insensitive: both sides are sorted before checking
|
|
55
|
-
* element-wise equality, because a fresh hydration may return relation IDs in a
|
|
56
|
-
* different order than they were originally written.
|
|
57
|
-
*/
|
|
58
|
-
export declare function isDirty(instance: object, key: string, currentValue: any): boolean;
|
|
59
|
-
export {};
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Dirty-tracking snapshot registry for Ad4mModel instances.
|
|
3
|
-
*
|
|
4
|
-
* A lightweight WeakMap-based store that records the schema-declared field
|
|
5
|
-
* values of an instance immediately after hydration or save. `innerUpdate`
|
|
6
|
-
* consults this snapshot to skip writing fields that haven't changed since the
|
|
7
|
-
* last successful persist, preventing the "re-save duplicates relations" bug.
|
|
8
|
-
*
|
|
9
|
-
* ## Design notes
|
|
10
|
-
*
|
|
11
|
-
* - A **WeakMap** is used so snapshot entries are GC'd when the instance is
|
|
12
|
-
* collected — no manual cleanup needed.
|
|
13
|
-
* - Arrays are normalised to `string[]` on capture (model instances → their ID
|
|
14
|
-
* URI) so the comparison is stable regardless of whether `include` hydration
|
|
15
|
-
* was used.
|
|
16
|
-
* - There is **no snapshot** for a freshly constructed instance that has never
|
|
17
|
-
* been hydrated or saved. `isDirty` returns `true` in that case, preserving
|
|
18
|
-
* existing create-path behaviour (write everything).
|
|
19
|
-
* - Only Tier-1 saves (no caller-provided `batchId`) trigger a post-save
|
|
20
|
-
* rehydration via `fetchInstanceData`, which re-captures the snapshot. Tier-2
|
|
21
|
-
* / Tier-3 (caller-managed batch / `transaction()`) skip rehydration by
|
|
22
|
-
* design; fields that were not changed may be re-sent on the next Tier-1
|
|
23
|
-
* save, which is idempotent and acceptable.
|
|
24
|
-
*/
|
|
25
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
26
|
-
// Registry
|
|
27
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
28
|
-
const snapshots = new WeakMap();
|
|
29
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
30
|
-
// Helpers
|
|
31
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
32
|
-
/**
|
|
33
|
-
* Normalise a field value for snapshot storage and comparison.
|
|
34
|
-
*
|
|
35
|
-
* - Arrays whose items may be model instances (from `include` hydration) are
|
|
36
|
-
* reduced to their `id` URI strings so comparisons are stable.
|
|
37
|
-
* - All other values are stored as-is.
|
|
38
|
-
*/
|
|
39
|
-
function normalizeValue(value) {
|
|
40
|
-
if (Array.isArray(value)) {
|
|
41
|
-
return value.map((v) => v && typeof v === "object" && typeof v.id === "string" ? v.id : v);
|
|
42
|
-
}
|
|
43
|
-
return value;
|
|
44
|
-
}
|
|
45
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
46
|
-
// Public API
|
|
47
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
48
|
-
/**
|
|
49
|
-
* Records the current schema-field values of `instance` as its clean baseline.
|
|
50
|
-
*
|
|
51
|
-
* Call this after every hydration (bulk or single-instance path) and after
|
|
52
|
-
* every successful internal-batch save (the latter comes for free because
|
|
53
|
-
* `saveInstance` calls `fetchInstanceData` which ends with a `captureSnapshot`
|
|
54
|
-
* call).
|
|
55
|
-
*
|
|
56
|
-
* @param instance - The Ad4mModel instance to snapshot.
|
|
57
|
-
* @param keys - Schema-declared field names to record (@Property keys +
|
|
58
|
-
* relation keys). Internal machinery (`_id`, `_perspective`,
|
|
59
|
-
* dynamically-wired `addX`/`removeX`/`setX` methods) must
|
|
60
|
-
* NOT be included.
|
|
61
|
-
*/
|
|
62
|
-
export function captureSnapshot(instance, keys) {
|
|
63
|
-
const entry = {};
|
|
64
|
-
for (const key of keys) {
|
|
65
|
-
entry[key] = normalizeValue(instance[key]);
|
|
66
|
-
}
|
|
67
|
-
snapshots.set(instance, entry);
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Returns the snapshot entry for `instance`, or `undefined` if none has been
|
|
71
|
-
* captured yet (i.e. the instance has never been hydrated or saved via an
|
|
72
|
-
* internal batch).
|
|
73
|
-
*/
|
|
74
|
-
export function readSnapshot(instance) {
|
|
75
|
-
return snapshots.get(instance);
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Returns `true` if `currentValue` differs from the snapshot value for `key`.
|
|
79
|
-
*
|
|
80
|
-
* Always returns `true` (→ write the field) when:
|
|
81
|
-
* - No snapshot has been captured (create path / instance never hydrated).
|
|
82
|
-
* - The key was not present in the snapshot (new field added after hydration).
|
|
83
|
-
*
|
|
84
|
-
* Array comparison is order-insensitive: both sides are sorted before checking
|
|
85
|
-
* element-wise equality, because a fresh hydration may return relation IDs in a
|
|
86
|
-
* different order than they were originally written.
|
|
87
|
-
*/
|
|
88
|
-
export function isDirty(instance, key, currentValue) {
|
|
89
|
-
const snap = snapshots.get(instance);
|
|
90
|
-
if (!snap)
|
|
91
|
-
return true; // no snapshot → always write (create path)
|
|
92
|
-
if (!(key in snap))
|
|
93
|
-
return true; // field absent from snapshot → write
|
|
94
|
-
const snapVal = snap[key];
|
|
95
|
-
const currNorm = normalizeValue(currentValue);
|
|
96
|
-
if (Array.isArray(currNorm) && Array.isArray(snapVal)) {
|
|
97
|
-
if (currNorm.length !== snapVal.length)
|
|
98
|
-
return true;
|
|
99
|
-
// Relations are semantically sets; sort before comparing so reordering
|
|
100
|
-
// after a fresh hydration doesn't produce false positives.
|
|
101
|
-
const a = [...currNorm].sort();
|
|
102
|
-
const b = [...snapVal].sort();
|
|
103
|
-
return a.some((v, i) => v !== b[i]);
|
|
104
|
-
}
|
|
105
|
-
return currNorm !== snapVal;
|
|
106
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure SurrealQL compiler — translates high-level `Query<T>` objects into
|
|
3
|
-
* raw SurrealQL strings.
|
|
4
|
-
*
|
|
5
|
-
* All functions are stateless — they take `ModelMetadata` (and optionally a
|
|
6
|
-
* `Query`) as plain data and return strings or booleans. No dependency on the
|
|
7
|
-
* `Ad4mModel` class, which means they can be imported by tests and other
|
|
8
|
-
* modules without pulling in the full class graph.
|
|
9
|
-
*
|
|
10
|
-
* `Ad4mModel` keeps thin static wrapper methods with the original signatures so
|
|
11
|
-
* the public API is unchanged.
|
|
12
|
-
*/
|
|
13
|
-
import { ModelMetadata, Query, Where, WhereCondition } from "../types";
|
|
14
|
-
/**
|
|
15
|
-
* Formats a value for use in SurrealQL queries.
|
|
16
|
-
*
|
|
17
|
-
* - Strings: wrapped in single quotes, special characters escaped
|
|
18
|
-
* - Numbers / booleans: converted to string
|
|
19
|
-
* - Arrays: recursively formatted, wrapped in `[...]`
|
|
20
|
-
*/
|
|
21
|
-
export declare function formatSurrealValue(value: any): string;
|
|
22
|
-
/**
|
|
23
|
-
* Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
|
|
24
|
-
* Used by `buildSurrealQuery` — more efficient than subqueries because
|
|
25
|
-
* SurrealDB can use graph indexes.
|
|
26
|
-
*/
|
|
27
|
-
export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, where?: Where): string;
|
|
28
|
-
/**
|
|
29
|
-
* Builds the SurrealQL SELECT query for a given model metadata + query params.
|
|
30
|
-
* This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
|
|
31
|
-
*/
|
|
32
|
-
export declare function buildSurrealQuery(metadata: ModelMetadata, query: Query): string;
|
|
33
|
-
/**
|
|
34
|
-
* Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
|
|
35
|
-
*/
|
|
36
|
-
export declare function buildSurrealCountQuery(metadata: ModelMetadata, query: Query): string;
|
|
37
|
-
/**
|
|
38
|
-
* Checks whether a single value satisfies a WhereCondition.
|
|
39
|
-
* Used for post-query JavaScript filtering of operators that SurrealDB
|
|
40
|
-
* cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
|
|
41
|
-
*/
|
|
42
|
-
export declare function matchesCondition(value: any, condition: WhereCondition): boolean;
|
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure SurrealQL compiler — translates high-level `Query<T>` objects into
|
|
3
|
-
* raw SurrealQL strings.
|
|
4
|
-
*
|
|
5
|
-
* All functions are stateless — they take `ModelMetadata` (and optionally a
|
|
6
|
-
* `Query`) as plain data and return strings or booleans. No dependency on the
|
|
7
|
-
* `Ad4mModel` class, which means they can be imported by tests and other
|
|
8
|
-
* modules without pulling in the full class graph.
|
|
9
|
-
*
|
|
10
|
-
* `Ad4mModel` keeps thin static wrapper methods with the original signatures so
|
|
11
|
-
* the public API is unchanged.
|
|
12
|
-
*/
|
|
13
|
-
import { escapeSurrealString } from "../../utils";
|
|
14
|
-
// ── Value formatting ────────────────────────────────────────────────────────
|
|
15
|
-
/**
|
|
16
|
-
* Formats a value for use in SurrealQL queries.
|
|
17
|
-
*
|
|
18
|
-
* - Strings: wrapped in single quotes, special characters escaped
|
|
19
|
-
* - Numbers / booleans: converted to string
|
|
20
|
-
* - Arrays: recursively formatted, wrapped in `[...]`
|
|
21
|
-
*/
|
|
22
|
-
export function formatSurrealValue(value) {
|
|
23
|
-
if (typeof value === "string") {
|
|
24
|
-
const escaped = value
|
|
25
|
-
.replace(/\\/g, "\\\\")
|
|
26
|
-
.replace(/'/g, "\\'")
|
|
27
|
-
.replace(/"/g, '\\"')
|
|
28
|
-
.replace(/\n/g, "\\n")
|
|
29
|
-
.replace(/\r/g, "\\r")
|
|
30
|
-
.replace(/\t/g, "\\t");
|
|
31
|
-
return `'${escaped}'`;
|
|
32
|
-
}
|
|
33
|
-
else if (typeof value === "number" || typeof value === "boolean") {
|
|
34
|
-
return String(value);
|
|
35
|
-
}
|
|
36
|
-
else if (Array.isArray(value)) {
|
|
37
|
-
return `[${value.map(formatSurrealValue).join(", ")}]`;
|
|
38
|
-
}
|
|
39
|
-
else {
|
|
40
|
-
return String(value);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
// ── WHERE clause builders ───────────────────────────────────────────────────
|
|
44
|
-
/**
|
|
45
|
-
* Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
|
|
46
|
-
* Used by `buildSurrealQuery` — more efficient than subqueries because
|
|
47
|
-
* SurrealDB can use graph indexes.
|
|
48
|
-
*/
|
|
49
|
-
export function buildGraphTraversalWhereClause(metadata, where) {
|
|
50
|
-
if (!where)
|
|
51
|
-
return "";
|
|
52
|
-
const conditions = [];
|
|
53
|
-
for (const [propertyName, condition] of Object.entries(where)) {
|
|
54
|
-
const isSpecial = ["base", "id", "author", "timestamp"].includes(propertyName);
|
|
55
|
-
if (isSpecial) {
|
|
56
|
-
if (propertyName === "author" || propertyName === "timestamp") {
|
|
57
|
-
continue; // filtered post-query in JavaScript
|
|
58
|
-
}
|
|
59
|
-
const columnName = "uri"; // base/id → uri in node table
|
|
60
|
-
if (Array.isArray(condition)) {
|
|
61
|
-
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
62
|
-
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
63
|
-
}
|
|
64
|
-
else if (typeof condition === "object" && condition !== null) {
|
|
65
|
-
const ops = condition;
|
|
66
|
-
if (ops.not !== undefined) {
|
|
67
|
-
if (Array.isArray(ops.not)) {
|
|
68
|
-
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
69
|
-
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
if (ops.between !== undefined &&
|
|
76
|
-
Array.isArray(ops.between) &&
|
|
77
|
-
ops.between.length === 2) {
|
|
78
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
|
|
79
|
-
}
|
|
80
|
-
if (ops.gt !== undefined)
|
|
81
|
-
conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
|
|
82
|
-
if (ops.gte !== undefined)
|
|
83
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
|
|
84
|
-
if (ops.lt !== undefined)
|
|
85
|
-
conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
|
|
86
|
-
if (ops.lte !== undefined)
|
|
87
|
-
conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
|
|
88
|
-
if (ops.contains !== undefined)
|
|
89
|
-
conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
|
|
90
|
-
}
|
|
91
|
-
else {
|
|
92
|
-
conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
else {
|
|
96
|
-
const propMeta = metadata.properties[propertyName];
|
|
97
|
-
if (!propMeta) {
|
|
98
|
-
// ── Relation-based where clause ────────────────────────────────────
|
|
99
|
-
// If the where key is a relation name (e.g. `where: { post: postId }`),
|
|
100
|
-
// generate a graph-traversal filter on the link predicate.
|
|
101
|
-
//
|
|
102
|
-
// • Reverse relations (@BelongsToOne / @BelongsToMany):
|
|
103
|
-
// The link is stored as parentId --predicate--> thisId.
|
|
104
|
-
// From this node we traverse <-link (incoming) and check in.uri.
|
|
105
|
-
//
|
|
106
|
-
// • Forward relations (@HasMany / @HasOne):
|
|
107
|
-
// The link is stored as thisId --predicate--> childId.
|
|
108
|
-
// From this node we traverse ->link (outgoing) and check out.uri.
|
|
109
|
-
const relMeta = metadata.relations[propertyName];
|
|
110
|
-
if (!relMeta)
|
|
111
|
-
continue;
|
|
112
|
-
const predicate = escapeSurrealString(relMeta.predicate);
|
|
113
|
-
const isReverse = relMeta.direction === "reverse";
|
|
114
|
-
const arrow = isReverse ? "<-" : "->";
|
|
115
|
-
const uriField = isReverse ? "in.uri" : "out.uri";
|
|
116
|
-
if (Array.isArray(condition)) {
|
|
117
|
-
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
118
|
-
conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) > 0`);
|
|
119
|
-
}
|
|
120
|
-
else if (typeof condition === "object" && condition !== null) {
|
|
121
|
-
const ops = condition;
|
|
122
|
-
if (ops.not !== undefined) {
|
|
123
|
-
if (Array.isArray(ops.not)) {
|
|
124
|
-
const formattedValues = ops.not
|
|
125
|
-
.map(formatSurrealValue)
|
|
126
|
-
.join(", ");
|
|
127
|
-
conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) = 0`);
|
|
128
|
-
}
|
|
129
|
-
else {
|
|
130
|
-
conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
// Comparison operators on relation IDs are unusual but handled:
|
|
134
|
-
// they'll be caught in JS post-filtering (step 6 in operations.ts).
|
|
135
|
-
}
|
|
136
|
-
else {
|
|
137
|
-
conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(condition)}]) > 0`);
|
|
138
|
-
}
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
const predicate = escapeSurrealString(propMeta.predicate);
|
|
142
|
-
// Scalar properties (resolveLanguage === "literal" or unset) store values as
|
|
143
|
-
// literal:// URIs — use fn::parse_literal to unwrap before comparing.
|
|
144
|
-
// Only non-literal custom languages (e.g. IPFS) store raw expression URLs.
|
|
145
|
-
const targetField = !propMeta.resolveLanguage || propMeta.resolveLanguage === "literal"
|
|
146
|
-
? "fn::parse_literal(out.uri)"
|
|
147
|
-
: "out.uri";
|
|
148
|
-
if (Array.isArray(condition)) {
|
|
149
|
-
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
150
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
151
|
-
}
|
|
152
|
-
else if (typeof condition === "object" && condition !== null) {
|
|
153
|
-
const ops = condition;
|
|
154
|
-
if (ops.not !== undefined) {
|
|
155
|
-
if (Array.isArray(ops.not)) {
|
|
156
|
-
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
157
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
158
|
-
}
|
|
159
|
-
else {
|
|
160
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
const hasComparisonOps = ops.gt !== undefined ||
|
|
164
|
-
ops.gte !== undefined ||
|
|
165
|
-
ops.lt !== undefined ||
|
|
166
|
-
ops.lte !== undefined ||
|
|
167
|
-
ops.between !== undefined ||
|
|
168
|
-
ops.contains !== undefined;
|
|
169
|
-
if (hasComparisonOps) {
|
|
170
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
else {
|
|
174
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
return conditions.join(" AND ");
|
|
179
|
-
}
|
|
180
|
-
// ── Main query builders ─────────────────────────────────────────────────────
|
|
181
|
-
/**
|
|
182
|
-
* Builds the SurrealQL SELECT query for a given model metadata + query params.
|
|
183
|
-
* This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
|
|
184
|
-
*/
|
|
185
|
-
export function buildSurrealQuery(metadata, query) {
|
|
186
|
-
const { where, parent: linkedFrom } = query;
|
|
187
|
-
const graphTraversalFilters = [];
|
|
188
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
189
|
-
if (propMeta.required) {
|
|
190
|
-
if (propMeta.flag && propMeta.initial) {
|
|
191
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
192
|
-
}
|
|
193
|
-
else {
|
|
194
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
if (graphTraversalFilters.length === 0) {
|
|
199
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
200
|
-
if (propMeta.initial) {
|
|
201
|
-
if (propMeta.flag) {
|
|
202
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
203
|
-
}
|
|
204
|
-
else {
|
|
205
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
206
|
-
}
|
|
207
|
-
break;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
// Last-resort fallback: require at least one link with any of the model's
|
|
212
|
-
// own declared predicates (properties OR relations). This prevents matching
|
|
213
|
-
// SDNA registration nodes (which use sh://, ad4m://, rdf:// predicates) for
|
|
214
|
-
// models that have no @Flag, no required, and no initial-valued properties.
|
|
215
|
-
if (graphTraversalFilters.length === 0) {
|
|
216
|
-
const allPredicates = [
|
|
217
|
-
...Object.values(metadata.properties).map((p) => p.predicate),
|
|
218
|
-
...Object.values(metadata.relations).map((r) => r.predicate),
|
|
219
|
-
].filter(Boolean);
|
|
220
|
-
if (allPredicates.length > 0) {
|
|
221
|
-
const predicateConditions = allPredicates
|
|
222
|
-
.map((p) => `count(->link[WHERE predicate = '${escapeSurrealString(p)}']) > 0`)
|
|
223
|
-
.join(" OR ");
|
|
224
|
-
graphTraversalFilters.push(`(${predicateConditions})`);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
const userWhereClause = buildGraphTraversalWhereClause(metadata, where);
|
|
228
|
-
const whereConditions = [
|
|
229
|
-
...graphTraversalFilters,
|
|
230
|
-
...(userWhereClause ? [userWhereClause] : []),
|
|
231
|
-
...(linkedFrom
|
|
232
|
-
? [
|
|
233
|
-
`count(<-link[WHERE predicate = '${escapeSurrealString(linkedFrom.predicate)}' AND in.uri = '${escapeSurrealString(linkedFrom.id)}']) > 0`,
|
|
234
|
-
]
|
|
235
|
-
: []),
|
|
236
|
-
];
|
|
237
|
-
// Ensure we always have at least one condition to produce valid SurrealQL
|
|
238
|
-
const whereClause = whereConditions.length > 0
|
|
239
|
-
? whereConditions.join(" AND ")
|
|
240
|
-
: "count(->link) > 0";
|
|
241
|
-
return `
|
|
242
|
-
SELECT
|
|
243
|
-
id AS source,
|
|
244
|
-
uri AS source_uri,
|
|
245
|
-
(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links
|
|
246
|
-
FROM node
|
|
247
|
-
WHERE ${whereClause}
|
|
248
|
-
`.trim();
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
|
|
252
|
-
*/
|
|
253
|
-
export function buildSurrealCountQuery(metadata, query) {
|
|
254
|
-
const countQuery = { ...query };
|
|
255
|
-
delete countQuery.limit;
|
|
256
|
-
delete countQuery.offset;
|
|
257
|
-
return buildSurrealQuery(metadata, countQuery);
|
|
258
|
-
}
|
|
259
|
-
// ── Post-query filtering ────────────────────────────────────────────────────
|
|
260
|
-
/**
|
|
261
|
-
* Checks whether a single value satisfies a WhereCondition.
|
|
262
|
-
* Used for post-query JavaScript filtering of operators that SurrealDB
|
|
263
|
-
* cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
|
|
264
|
-
*/
|
|
265
|
-
export function matchesCondition(value, condition) {
|
|
266
|
-
if (Array.isArray(condition)) {
|
|
267
|
-
return condition.includes(value);
|
|
268
|
-
}
|
|
269
|
-
if (typeof condition === "object" && condition !== null) {
|
|
270
|
-
const ops = condition;
|
|
271
|
-
let allMet = true;
|
|
272
|
-
if (ops.not !== undefined)
|
|
273
|
-
allMet =
|
|
274
|
-
allMet &&
|
|
275
|
-
(Array.isArray(ops.not)
|
|
276
|
-
? !ops.not.includes(value)
|
|
277
|
-
: value !== ops.not);
|
|
278
|
-
if (ops.between !== undefined &&
|
|
279
|
-
Array.isArray(ops.between) &&
|
|
280
|
-
ops.between.length === 2)
|
|
281
|
-
allMet = allMet && value >= ops.between[0] && value <= ops.between[1];
|
|
282
|
-
if (ops.gt !== undefined)
|
|
283
|
-
allMet = allMet && value > ops.gt;
|
|
284
|
-
if (ops.gte !== undefined)
|
|
285
|
-
allMet = allMet && value >= ops.gte;
|
|
286
|
-
if (ops.lt !== undefined)
|
|
287
|
-
allMet = allMet && value < ops.lt;
|
|
288
|
-
if (ops.lte !== undefined)
|
|
289
|
-
allMet = allMet && value <= ops.lte;
|
|
290
|
-
if (ops.contains !== undefined) {
|
|
291
|
-
if (typeof value === "string") {
|
|
292
|
-
allMet = allMet && value.includes(String(ops.contains));
|
|
293
|
-
}
|
|
294
|
-
else if (Array.isArray(value)) {
|
|
295
|
-
allMet = allMet && value.includes(ops.contains);
|
|
296
|
-
}
|
|
297
|
-
else {
|
|
298
|
-
allMet = false;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
return allMet;
|
|
302
|
-
}
|
|
303
|
-
return value === condition;
|
|
304
|
-
}
|