-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathimportPreview.ts
More file actions
440 lines (384 loc) · 13.9 KB
/
Copy pathimportPreview.ts
File metadata and controls
440 lines (384 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import type DiscourseGraphPlugin from "~/index";
import type { ImportableNode } from "~/types";
import { getLoggedInClient, getSupabaseContext } from "./supabaseContext";
import {
getImportedNodesInfo,
getLocalNodeKeyToEndpointId,
} from "./relationsStore";
import { fetchNodeTypeSchemasForInstances, getSpaceUris } from "./importNodes";
import { QueryEngine } from "~/services/QueryEngine";
import {
fetchRelationInstancesFromSpace,
type RemoteRelationInstance,
} from "./importRelations";
import { spaceUriAndLocalIdToRid } from "@repo/database/lib/rid";
export type RelationTriplet = {
sourceNodeTypeName: string;
relationTypeLabel: string;
destNodeTypeName: string;
/** Whether this specific triplet combo is new (not in discourseRelations) */
isNewTriplet: boolean;
};
export type ImportPreviewData = {
// Display data
selectedNodeCount: number;
newNodeTypeSchemas: Array<{ id: string; name: string }>;
relationInstanceCount: number;
newRelationTypeSchemas: Array<{
id: string;
label: string;
complement: string;
}>;
relationTriplets: RelationTriplet[];
// Pre-fetched data to pass through to import (avoids re-querying)
nodeKeys: Set<string>;
keyToRid: Map<string, string>;
/** Key (spaceId:source_local_id) -> endpoint id (RID) for relation import; includes local nodes */
keyToRelationEndpointId: Map<string, string>;
/** Relation instances per spaceId, for reuse during import */
relationInstancesBySpace: Map<number, RemoteRelationInstance[]>;
};
export const computeImportPreview = async ({
plugin,
selectedNodes,
}: {
plugin: DiscourseGraphPlugin;
selectedNodes: ImportableNode[];
}): Promise<ImportPreviewData> => {
const client = await getLoggedInClient(plugin);
if (!client) {
throw new Error("Cannot get Supabase client");
}
const context = await getSupabaseContext(plugin);
if (!context) {
throw new Error("Cannot get Supabase context");
}
const queryEngine = new QueryEngine(plugin.app);
// --- Node type detection (without creating) ---
const nodesBySpace = new Map<number, ImportableNode[]>();
for (const node of selectedNodes) {
if (!nodesBySpace.has(node.spaceId)) {
nodesBySpace.set(node.spaceId, []);
}
nodesBySpace.get(node.spaceId)!.push(node);
}
const spaceIds = [...nodesBySpace.keys()];
const spaceUris = await getSpaceUris(client, spaceIds);
const newNodeTypeSchemas: Array<{ id: string; name: string }> = [];
const seenNodeTypeIds = new Set<string>();
// Maps source_local_id -> name for all node type schemas we encounter (for triplet resolution)
const nodeTypeIdToName = new Map<string, string>();
// Pre-populate with local node types
for (const nt of plugin.settings.nodeTypes) {
nodeTypeIdToName.set(nt.id, nt.name);
}
for (const [spaceId, nodes] of nodesBySpace.entries()) {
const nodeTypeSchemasByInstance = await fetchNodeTypeSchemasForInstances({
client,
spaceId,
nodeInstanceIds: nodes.map((n) => n.nodeInstanceId),
});
for (const { nodeTypeId, name } of nodeTypeSchemasByInstance.values()) {
// Track name for triplet resolution
if (!nodeTypeIdToName.has(nodeTypeId)) {
nodeTypeIdToName.set(nodeTypeId, name);
}
if (seenNodeTypeIds.has(nodeTypeId)) continue;
seenNodeTypeIds.add(nodeTypeId);
// Check against local node types (mirrors mapNodeTypeIdToLocal logic without side effects)
const matchById = plugin.settings.nodeTypes.find(
(nt) => nt.id === nodeTypeId,
);
if (matchById) continue;
const matchByName = plugin.settings.nodeTypes.find(
(nt) => nt.name === name,
);
if (matchByName) continue;
// This is a new node type that would be created
newNodeTypeSchemas.push({ id: nodeTypeId, name });
}
}
// --- Relation detection ---
// Build combined nodeKeys from previously imported nodes + currently selected nodes
const { nodeKeys, keyToRid } = await getImportedNodesInfo({
queryEngine,
plugin,
client,
});
// Add currently selected nodes to the sets
for (const [spaceId, nodes] of nodesBySpace.entries()) {
const spaceUri = spaceUris.get(spaceId);
if (!spaceUri) continue;
for (const node of nodes) {
const key = `${spaceId}:${node.nodeInstanceId}`;
nodeKeys.add(key);
if (!keyToRid.has(key)) {
keyToRid.set(
key,
spaceUriAndLocalIdToRid(spaceUri, node.nodeInstanceId, "note"),
);
}
}
}
const localMap = getLocalNodeKeyToEndpointId(plugin, context.spaceId);
const keyToRelationEndpointId = new Map([...keyToRid, ...localMap]);
// Fetch relation instances per space and collect matching ones with endpoint concept ids
const relationInstancesBySpace = new Map<number, RemoteRelationInstance[]>();
const matchingRelations: Array<{
rel: RemoteRelationInstance;
sourceConceptId: number;
destConceptId: number;
spaceId: number;
}> = [];
for (const spaceId of spaceIds) {
const instances = await fetchRelationInstancesFromSpace({
client,
spaceId,
});
relationInstancesBySpace.set(spaceId, instances);
// Filter: only relations where both endpoints resolve (imported or local)
for (const rel of instances) {
const sourceData = rel.concepts_of_relation.find(
(cor) =>
cor.id ===
(rel.reference_content as Record<string, number | number[]>).source,
);
const destData = rel.concepts_of_relation.find(
(cor) =>
cor.id ===
(rel.reference_content as Record<string, number | number[]>)
.destination,
);
if (!sourceData || !destData) continue;
const sourceKey = `${sourceData.space_id}:${sourceData.source_local_id}`;
const destKey = `${destData.space_id}:${destData.source_local_id}`;
if (
keyToRelationEndpointId.has(sourceKey) &&
keyToRelationEndpointId.has(destKey)
) {
matchingRelations.push({
rel,
sourceConceptId: sourceData.id,
destConceptId: destData.id,
spaceId,
});
}
}
}
// Resolve relation schema_ids to detect new relation types
const newRelationTypeSchemas: Array<{
id: string;
label: string;
complement: string;
}> = [];
const seenRelationTypeIds = new Set<string>();
// Maps relation type source_local_id -> { label, complement } for triplet display
const relationTypeIdToInfo = new Map<
string,
{ label: string; complement: string }
>();
// Pre-populate with local relation types
for (const rt of plugin.settings.relationTypes) {
relationTypeIdToInfo.set(rt.id, {
label: rt.label,
complement: rt.complement ?? "",
});
}
const relationSchemaIds = [
...new Set(
matchingRelations
.map((m) => m.rel.schema_id)
.filter((id): id is number => id != null),
),
];
// Maps numeric schema id -> source_local_id for relation types
const relSchemaIdToLocalId = new Map<number, string>();
// Batch-fetched: schema id -> name + literal_content (few schemata, many relations)
const relSchemaIdToDetails = new Map<
number,
{ name: string; literal_content: unknown }
>();
if (relationSchemaIds.length > 0) {
const { data: schemaRows } = await client
.from("my_concepts")
.select("id, source_local_id, name, literal_content")
.in("id", relationSchemaIds);
for (const row of (schemaRows ?? []) as Array<{
id: number;
source_local_id: string;
name: string | null;
literal_content: unknown;
}>) {
relSchemaIdToLocalId.set(row.id, row.source_local_id);
if (row.name != null) {
relSchemaIdToDetails.set(row.id, {
name: row.name,
literal_content: row.literal_content,
});
}
}
const uniqueRelTypeLocalIds = [...new Set(relSchemaIdToLocalId.values())];
for (const relTypeLocalId of uniqueRelTypeLocalIds) {
if (seenRelationTypeIds.has(relTypeLocalId)) continue;
seenRelationTypeIds.add(relTypeLocalId);
const matchById = plugin.settings.relationTypes.find(
(rt) => rt.id === relTypeLocalId,
);
if (matchById) continue;
const schemaNumericId = [...relSchemaIdToLocalId.entries()].find(
([, localId]) => localId === relTypeLocalId,
)?.[0];
if (schemaNumericId == null) continue;
const schemaData = relSchemaIdToDetails.get(schemaNumericId);
if (!schemaData?.name) continue;
const obj =
typeof schemaData.literal_content === "string"
? (JSON.parse(schemaData.literal_content) as Record<string, unknown>)
: (schemaData.literal_content as Record<string, unknown>) || {};
const label = (obj.label as string) || schemaData.name;
const complement = (obj.complement as string) || "";
relationTypeIdToInfo.set(relTypeLocalId, { label, complement });
const matchByLabel = plugin.settings.relationTypes.find(
(rt) => rt.label === label,
);
if (matchByLabel) continue;
newRelationTypeSchemas.push({ id: relTypeLocalId, label, complement });
}
}
// --- Resolve relation triplets ---
// Collect all endpoint concept ids we need to resolve node types for
const allEndpointConceptIds = [
...new Set(
matchingRelations.flatMap((m) => [m.sourceConceptId, m.destConceptId]),
),
];
// Batch fetch schema_id for all endpoint concepts
const conceptIdToSchemaId = new Map<number, number>();
if (allEndpointConceptIds.length > 0) {
const { data: conceptSchemas } = await client
.from("my_concepts")
.select("id, schema_id")
.in("id", allEndpointConceptIds);
for (const row of (conceptSchemas ?? []) as Array<{
id: number;
schema_id: number | null;
}>) {
if (row.schema_id != null) {
conceptIdToSchemaId.set(row.id, row.schema_id);
}
}
}
// Batch fetch source_local_id + name for all node type schemas
const nodeSchemaNumericIds = [...new Set(conceptIdToSchemaId.values())];
// Maps numeric schema id -> { source_local_id, name }
const nodeSchemaIdToInfo = new Map<
number,
{ source_local_id: string; name: string }
>();
if (nodeSchemaNumericIds.length > 0) {
const { data: nodeSchemaRows } = await client
.from("my_concepts")
.select("id, source_local_id, name")
.in("id", nodeSchemaNumericIds);
for (const row of (nodeSchemaRows ?? []) as Array<{
id: number;
source_local_id: string;
name: string;
}>) {
nodeSchemaIdToInfo.set(row.id, {
source_local_id: row.source_local_id,
name: row.name,
});
// Also populate nodeTypeIdToName if not already there
if (!nodeTypeIdToName.has(row.source_local_id)) {
nodeTypeIdToName.set(row.source_local_id, row.name);
}
}
}
// Build unique triplets
const tripletSet = new Set<string>();
const relationTriplets: RelationTriplet[] = [];
for (const { rel, sourceConceptId, destConceptId } of matchingRelations) {
if (!rel.schema_id) continue;
const relTypeLocalId = relSchemaIdToLocalId.get(rel.schema_id);
if (!relTypeLocalId) continue;
const relInfo = relationTypeIdToInfo.get(relTypeLocalId);
if (!relInfo) continue;
// Resolve source node type name
const sourceSchemaNumId = conceptIdToSchemaId.get(sourceConceptId);
const destSchemaNumId = conceptIdToSchemaId.get(destConceptId);
if (sourceSchemaNumId == null || destSchemaNumId == null) continue;
const sourceSchemaInfo = nodeSchemaIdToInfo.get(sourceSchemaNumId);
const destSchemaInfo = nodeSchemaIdToInfo.get(destSchemaNumId);
if (!sourceSchemaInfo || !destSchemaInfo) continue;
const sourceNodeTypeName =
nodeTypeIdToName.get(sourceSchemaInfo.source_local_id) ??
sourceSchemaInfo.name;
const destNodeTypeName =
nodeTypeIdToName.get(destSchemaInfo.source_local_id) ??
destSchemaInfo.name;
const tripletKey = `${sourceSchemaInfo.source_local_id}:${relTypeLocalId}:${destSchemaInfo.source_local_id}`;
if (tripletSet.has(tripletKey)) continue;
tripletSet.add(tripletKey);
// Check if this triplet already exists in discourseRelations
// We need to check using the mapped local ids (match by id first, then by name)
const resolveLocalNodeTypeId = (
remoteId: string,
remoteName: string,
): string => {
const byId = plugin.settings.nodeTypes.find((nt) => nt.id === remoteId);
if (byId) return byId.id;
const byName = plugin.settings.nodeTypes.find(
(nt) => nt.name === remoteName,
);
if (byName) return byName.id;
return remoteId;
};
const resolveLocalRelTypeId = (
remoteId: string,
remoteLabel: string,
): string => {
const byId = plugin.settings.relationTypes.find(
(rt) => rt.id === remoteId,
);
if (byId) return byId.id;
const byLabel = plugin.settings.relationTypes.find(
(rt) => rt.label === remoteLabel,
);
if (byLabel) return byLabel.id;
return remoteId;
};
const localSourceNtId = resolveLocalNodeTypeId(
sourceSchemaInfo.source_local_id,
sourceNodeTypeName,
);
const localDestNtId = resolveLocalNodeTypeId(
destSchemaInfo.source_local_id,
destNodeTypeName,
);
const localRelTypeId = resolveLocalRelTypeId(relTypeLocalId, relInfo.label);
const isNewTriplet = !plugin.settings.discourseRelations?.some(
(dr) =>
dr.sourceId === localSourceNtId &&
dr.destinationId === localDestNtId &&
dr.relationshipTypeId === localRelTypeId,
);
relationTriplets.push({
sourceNodeTypeName,
relationTypeLabel: relInfo.label,
destNodeTypeName,
isNewTriplet,
});
}
return {
selectedNodeCount: selectedNodes.length,
newNodeTypeSchemas,
relationInstanceCount: matchingRelations.length,
newRelationTypeSchemas,
relationTriplets,
nodeKeys,
keyToRid,
keyToRelationEndpointId,
relationInstancesBySpace,
};
};