-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathQueryEngine.ts
More file actions
731 lines (658 loc) · 22 KB
/
Copy pathQueryEngine.ts
File metadata and controls
731 lines (658 loc) · 22 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import { TFile, App } from "obsidian";
import type DiscourseGraphPlugin from "~/index";
import { BulkImportPattern, BulkImportCandidate, DiscourseNode } from "~/types";
import { getDiscourseNodeFormatExpression } from "~/utils/getDiscourseNodeFormatExpression";
import { extractContentFromTitle } from "~/utils/extractContentFromTitle";
// This is a workaround to get the datacore API.
// TODO: Remove once we can use datacore npm package
export type AppWithPlugins = App & {
plugins: {
plugins: {
[key: string]: {
api: unknown;
};
};
};
};
type DatacorePage = {
$name: string;
$path?: string;
};
type DatacoreApi = {
core?: {
initialized?: boolean;
};
query: (query: string) => DatacorePage[];
};
export class QueryEngine {
private app: App;
private dc: DatacoreApi | undefined;
private readonly MIN_QUERY_LENGTH = 2;
constructor(app: App) {
const appWithPlugins = app as AppWithPlugins;
this.dc = appWithPlugins.plugins?.plugins?.["datacore"]?.api as
| DatacoreApi
| undefined;
this.app = app;
}
functional = () => !!this.dc;
/**
* Search across all discourse nodes (files that have frontmatter nodeTypeId)
*/
searchDiscourseNodesByTitle = (
query: string,
nodeTypeId?: string,
): TFile[] => {
if (!query || query.length < this.MIN_QUERY_LENGTH) {
return [];
}
const datacore = this.getReadyDatacore();
if (!datacore) {
return this.fallbackSearchDiscourseNodesByTitle(query, nodeTypeId);
}
try {
const dcQuery = nodeTypeId
? `@page and exists(nodeTypeId) and nodeTypeId = "${nodeTypeId}"`
: "@page and exists(nodeTypeId)";
const potentialNodes = datacore.query(dcQuery);
const searchResults = potentialNodes.filter((p: DatacorePage) =>
this.fuzzySearch(p.$name, query),
);
const files = searchResults
.map((dcFile: DatacorePage) => {
if (dcFile && dcFile.$path) {
const realFile = this.app.vault.getAbstractFileByPath(dcFile.$path);
if (realFile && realFile instanceof TFile) return realFile;
}
return null;
})
.filter((f): f is TFile => f instanceof TFile);
return files.reverse();
} catch (error) {
console.error("Error in searchDiscourseNodesByTitle:", error);
return this.fallbackSearchDiscourseNodesByTitle(query, nodeTypeId);
}
};
/**
* Search across all discourse nodes that have nodeInstanceId
*/
getDiscourseNodeById = (nodeInstanceId: string): TFile | null => {
if (!nodeInstanceId.match(/^[-.+\w]+$/)) {
console.error("Malformed id:", nodeInstanceId);
return null;
}
const datacore = this.getReadyDatacore();
if (!datacore) {
return this.fallbackGetDiscourseNodeById(nodeInstanceId);
}
try {
const dcQuery = `@page and exists(nodeInstanceId) and nodeInstanceId = "${nodeInstanceId}"`;
const potentialNodes = datacore.query(dcQuery);
const path = potentialNodes.at(0)?.$path;
if (!path) return null;
return this.app.vault.getFileByPath(path);
} catch (error) {
console.error("Error in searchDiscourseNodeById:", error);
return this.fallbackGetDiscourseNodeById(nodeInstanceId);
}
};
searchCompatibleNodeByTitle = ({
query,
compatibleNodeTypeIds,
activeFile,
selectedRelationType,
}: {
query: string;
compatibleNodeTypeIds: string[];
activeFile: TFile;
selectedRelationType: string;
}): TFile[] => {
if (!query || query.length < this.MIN_QUERY_LENGTH) {
return [];
}
const datacore = this.getReadyDatacore();
if (!datacore) {
return this.fallbackSearchCompatibleNodeByTitle({
query,
compatibleNodeTypeIds,
activeFile,
selectedRelationType,
});
}
try {
const dcQuery = `@page and exists(nodeTypeId) and ${compatibleNodeTypeIds
.map((id) => `nodeTypeId = "${id}"`)
.join(" or ")}`;
const potentialNodes = datacore.query(dcQuery);
const searchResults = potentialNodes.filter((p: DatacorePage) => {
return this.fuzzySearch(p.$name, query);
});
let existingRelatedFiles: string[] = [];
if (selectedRelationType) {
const fileCache = this.app.metadataCache.getFileCache(activeFile);
const existingRelations: string[] =
(fileCache?.frontmatter?.[selectedRelationType] as string[]) || [];
existingRelatedFiles = existingRelations.map((relation: string) => {
const match = relation.match(/\[\[(.*?)(?:\|.*?)?\]\]/);
return match?.[1] ?? relation.replace(/^\[\[|\]\]$/g, "");
});
}
const finalResults = searchResults
.map((dcFile: DatacorePage) => {
if (dcFile && dcFile.$path) {
const realFile = this.app.vault.getAbstractFileByPath(dcFile.$path);
if (realFile && realFile instanceof TFile) {
return realFile;
}
}
return null;
})
.filter((f): f is TFile => f instanceof TFile)
.filter((file: TFile) => {
if (file.path === activeFile.path) return false;
if (
selectedRelationType &&
existingRelatedFiles.some((existingFile) => {
return (
file.basename === existingFile.replace(/\.md$/, "") ||
file.name === existingFile
);
})
) {
return false;
}
return true;
});
return finalResults;
} catch (error) {
console.error("Error in searchNodeByTitle:", error);
return this.fallbackSearchCompatibleNodeByTitle({
query,
compatibleNodeTypeIds,
activeFile,
selectedRelationType,
});
}
};
/**
* Enhanced fuzzy search implementation
* Returns true if the search term is found within the target string
* with tolerance for typos and partial matches
*/
fuzzySearch(target: string, search: string): boolean {
if (!search || !target) return false;
const targetLower = target.toLowerCase();
const searchLower = search.toLowerCase();
if (targetLower.includes(searchLower)) {
return true;
}
if (searchLower.length > targetLower.length) {
return false;
}
if (targetLower.startsWith(searchLower)) {
return true;
}
let searchIndex = 0;
let consecutiveMatches = 0;
const MIN_CONSECUTIVE = Math.min(2, searchLower.length);
for (
let i = 0;
i < targetLower.length && searchIndex < searchLower.length;
i++
) {
if (targetLower[i] === searchLower[searchIndex]) {
searchIndex++;
consecutiveMatches++;
if (
consecutiveMatches >= MIN_CONSECUTIVE &&
searchIndex >= searchLower.length * 0.7
) {
return true;
}
} else {
consecutiveMatches = 0;
}
}
return searchIndex === searchLower.length;
}
scanForBulkImportCandidates(
patterns: BulkImportPattern[],
validNodeTypes: DiscourseNode[],
): BulkImportCandidate[] {
const candidates: BulkImportCandidate[] = [];
const datacore = this.getReadyDatacore();
if (!datacore) {
return this.fallbackScanVault(patterns, validNodeTypes);
}
try {
let dcQuery: string;
if (validNodeTypes.length === 0) {
dcQuery = "@page";
} else {
const validIdConditions = validNodeTypes
.map((nt) => `nodeTypeId != "${nt.id}"`)
.join(" and ");
dcQuery = `@page and (!exists(nodeTypeId) or (${validIdConditions}))`;
}
const potentialPages = datacore.query(dcQuery);
for (const page of potentialPages) {
const fileName = page.$name;
for (const pattern of patterns) {
if (!pattern.enabled || !pattern.alternativePattern.trim()) continue;
const regex = getDiscourseNodeFormatExpression(
pattern.alternativePattern,
);
if (regex.test(fileName)) {
if (!page.$path) continue;
const file = this.app.vault.getAbstractFileByPath(page.$path);
if (file && file instanceof TFile) {
const extractedContent = extractContentFromTitle(
pattern.alternativePattern,
fileName,
);
const matchedNodeType = validNodeTypes.find(
(nt) => nt.id === pattern.nodeTypeId,
);
if (!matchedNodeType) {
continue;
}
candidates.push({
file,
matchedNodeType,
alternativePattern: pattern.alternativePattern,
extractedContent,
selected: false,
});
}
break; // Stop checking other patterns for this file
}
}
}
return candidates;
} catch (error) {
console.error(
"Error in datacore bulk scan, falling back to vault iteration:",
error,
);
return this.fallbackScanVault(patterns, validNodeTypes);
}
}
/**
* Return all markdown pages under import/ that have importedFromRid and nodeInstanceId.
* Uses DataCore when available; falls back to vault iteration otherwise.
*/
getImportedNodePages = (): TFile[] => {
const datacore = this.getReadyDatacore();
if (datacore) {
try {
const dcQuery = `@page and path("import") and exists(importedFromRid) and exists(nodeInstanceId)`;
const pages = datacore.query(dcQuery);
const files: TFile[] = [];
for (const page of pages) {
if (page.$path) {
const file = this.app.vault.getAbstractFileByPath(page.$path);
if (file && file instanceof TFile) files.push(file);
}
}
return files;
} catch (error) {
console.warn("DataCore query for imported nodes failed:", error);
}
}
return this.fallbackGetImportedNodePages();
};
/**
* Return all markdown files that have nodeInstanceId in frontmatter.
* Uses DataCore when available; falls back to vault iteration otherwise.
*/
getFilesWithNodeInstanceId = (): TFile[] => {
const datacore = this.getReadyDatacore();
if (datacore) {
try {
const dcQuery = `@page and exists(nodeInstanceId)`;
const pages = datacore.query(dcQuery);
const files: TFile[] = [];
for (const page of pages) {
if (page.$path) {
const file = this.app.vault.getAbstractFileByPath(page.$path);
if (file && file instanceof TFile) files.push(file);
}
}
return files;
} catch (error) {
console.warn(
"DataCore query for files with nodeInstanceId failed:",
error,
);
}
}
return this.fallbackGetFilesWithNodeInstanceId();
};
/**
* Return all markdown files that have nodeTypeId in frontmatter.
* When excludeImported is true, only returns files without importedFromRid.
* Uses DataCore when available; falls back to vault iteration otherwise.
*/
getFilesWithNodeTypeId = (opts?: { excludeImported?: boolean }): TFile[] => {
const datacore = this.getReadyDatacore();
if (datacore) {
try {
const dcQuery = `@page and exists(nodeTypeId)`;
const pages = datacore.query(dcQuery);
const files: TFile[] = [];
for (const page of pages) {
if (!page.$path) continue;
const file = this.app.vault.getAbstractFileByPath(page.$path);
if (!(file && file instanceof TFile)) continue;
if (opts?.excludeImported) {
const fm = this.app.metadataCache.getFileCache(file)
?.frontmatter as Record<string, unknown> | undefined;
if (fm?.importedFromRid) continue;
}
files.push(file);
}
return files;
} catch (error) {
console.warn("DataCore query for files with nodeTypeId failed:", error);
}
}
return this.fallbackGetFilesWithNodeTypeId(opts);
};
/**
* Find a file by importedFromRid in frontmatter.
* Uses DataCore when available; falls back to vault iteration otherwise.
*/
getFileByImportedFromRid = (importedFromRid: string): TFile | null => {
const datacore = this.getReadyDatacore();
if (datacore) {
try {
const safeUri = importedFromRid
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
const dcQuery = `@page and importedFromRid = "${safeUri}"`;
const results = datacore.query(dcQuery);
const path = results.at(0)?.$path;
if (path) {
const file = this.app.vault.getAbstractFileByPath(path);
if (file && file instanceof TFile) return file;
}
} catch (error) {
console.warn(
"DataCore query for file by importedFromRid failed:",
error,
);
}
}
const allFiles = this.app.vault.getMarkdownFiles();
for (const f of allFiles) {
const fm = this.app.metadataCache.getFileCache(f)?.frontmatter;
if (
(fm as Record<string, unknown> | undefined)?.importedFromRid ===
importedFromRid
) {
return f;
}
}
return null;
};
/**
* Find a file by nodeInstanceId or importedFromRid (endpoint id).
* Tries DataCore getDiscourseNodeById and getFileByImportedFromRid when available;
* falls back to iterating files with nodeInstanceId and matching either field.
*/
getFileByEndpoint = (endpointId: string): TFile | null => {
if (this.getReadyDatacore()) {
const byId = this.getDiscourseNodeById(endpointId);
if (byId) return byId;
const byRid = this.getFileByImportedFromRid(endpointId);
if (byRid) return byRid;
}
const files = this.getFilesWithNodeInstanceId();
for (const file of files) {
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter as
| Record<string, unknown>
| undefined;
const id = fm?.nodeInstanceId as string | undefined;
const rid = fm?.importedFromRid as string | undefined;
if (id === endpointId || rid === endpointId) return file;
}
return null;
};
/**
* Find an existing imported file by nodeInstanceId and importedFromRid
* Uses DataCore when available; falls back to vault iteration otherwise
* Returns the file if found, null otherwise
*/
findExistingImportedFile = (
nodeInstanceId: string,
importedFromRid: string,
): TFile | null => {
const datacore = this.getReadyDatacore();
if (datacore) {
try {
const safeId = nodeInstanceId
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
const safeUri = importedFromRid
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
const dcQuery = `@page and nodeInstanceId = "${safeId}" and importedFromRid = "${safeUri}"`;
const results = datacore.query(dcQuery);
for (const page of results) {
if (page.$path) {
const file = this.app.vault.getAbstractFileByPath(page.$path);
if (file && file instanceof TFile) {
return file;
}
}
}
} catch (error) {
// DataCore query may fail; vault-iteration fallback below handles this
}
}
// Fallback: DataCore absent, query failed, or indexed field mismatch
const allFiles = this.app.vault.getMarkdownFiles();
for (const f of allFiles) {
const fm = this.app.metadataCache.getFileCache(f)?.frontmatter;
if (
fm?.nodeInstanceId === nodeInstanceId &&
fm.importedFromRid === importedFromRid
) {
return f;
}
}
return null;
};
private getReadyDatacore(): DatacoreApi | null {
return this.dc?.core?.initialized ? this.dc : null;
}
private fallbackSearchDiscourseNodesByTitle(
query: string,
nodeTypeId?: string,
): TFile[] {
return this.app.vault
.getMarkdownFiles()
.filter((file) => {
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter as
| Record<string, unknown>
| undefined;
if (!fm?.nodeTypeId) return false;
if (nodeTypeId && fm.nodeTypeId !== nodeTypeId) return false;
return this.fuzzySearch(file.basename, query);
})
.reverse();
}
private fallbackGetDiscourseNodeById(nodeInstanceId: string): TFile | null {
for (const file of this.app.vault.getMarkdownFiles()) {
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter as
| Record<string, unknown>
| undefined;
if (fm?.nodeInstanceId === nodeInstanceId) return file;
}
return null;
}
private fallbackSearchCompatibleNodeByTitle({
query,
compatibleNodeTypeIds,
activeFile,
selectedRelationType,
}: {
query: string;
compatibleNodeTypeIds: string[];
activeFile: TFile;
selectedRelationType: string;
}): TFile[] {
const fileCache = this.app.metadataCache.getFileCache(activeFile);
const frontmatter = fileCache?.frontmatter as
| Record<string, unknown>
| undefined;
const rawExistingRelations = frontmatter?.[selectedRelationType];
const existingRelations = Array.isArray(rawExistingRelations)
? (rawExistingRelations as string[])
: rawExistingRelations
? [String(rawExistingRelations)]
: [];
const existingRelatedFiles = existingRelations.map((relation) => {
const match = relation.match(/\[\[(.*?)(?:\|.*?)?\]\]/);
return match?.[1] ?? relation.replace(/^\[\[|\]\]$/g, "");
});
return this.app.vault
.getMarkdownFiles()
.filter((file) => {
if (file.path === activeFile.path) return false;
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter as
| Record<string, unknown>
| undefined;
if (!compatibleNodeTypeIds.includes(String(fm?.nodeTypeId ?? ""))) {
return false;
}
if (!this.fuzzySearch(file.basename, query)) return false;
return !existingRelatedFiles.some(
(existingFile) =>
file.basename === existingFile.replace(/\.md$/, "") ||
file.name === existingFile,
);
})
.reverse();
}
private fallbackGetImportedNodePages(): TFile[] {
const files: TFile[] = [];
const allFiles = this.app.vault.getMarkdownFiles();
for (const f of allFiles) {
if (!f.path.startsWith("import/")) continue;
const fm = this.app.metadataCache.getFileCache(f)?.frontmatter;
if (
(fm as Record<string, unknown> | undefined)?.importedFromRid &&
(fm as Record<string, unknown> | undefined)?.nodeInstanceId
) {
files.push(f);
}
}
return files;
}
private fallbackGetFilesWithNodeInstanceId(): TFile[] {
const files: TFile[] = [];
const allFiles = this.app.vault.getMarkdownFiles();
for (const f of allFiles) {
const fm = this.app.metadataCache.getFileCache(f)?.frontmatter;
if ((fm as Record<string, unknown> | undefined)?.nodeInstanceId) {
files.push(f);
}
}
return files;
}
private fallbackGetFilesWithNodeTypeId(opts?: {
excludeImported?: boolean;
}): TFile[] {
const files: TFile[] = [];
const allFiles = this.app.vault.getMarkdownFiles();
for (const f of allFiles) {
const fm = this.app.metadataCache.getFileCache(f)?.frontmatter as
| Record<string, unknown>
| undefined;
const nodeTypeId = fm?.nodeTypeId;
if (!nodeTypeId) continue;
if (
opts?.excludeImported &&
(fm?.importedFromRid || fm?.importedFromSpaceUri)
) {
continue;
}
files.push(f);
}
return files;
}
private fallbackScanVault(
patterns: BulkImportPattern[],
validNodeTypes: DiscourseNode[],
): BulkImportCandidate[] {
const candidates: BulkImportCandidate[] = [];
const allFiles = this.app.vault.getMarkdownFiles();
for (const file of allFiles) {
const fileName = file.basename;
const fileCache = this.app.metadataCache.getFileCache(file);
const currentNodeTypeId = fileCache?.frontmatter?.nodeTypeId as
| string
| undefined;
if (
currentNodeTypeId &&
validNodeTypes.some((nt) => nt.id === currentNodeTypeId)
) {
continue;
}
for (const pattern of patterns) {
if (!pattern.enabled || !pattern.alternativePattern.trim()) continue;
const regex = getDiscourseNodeFormatExpression(
pattern.alternativePattern,
);
if (regex.test(fileName)) {
const extractedContent = extractContentFromTitle(
pattern.alternativePattern,
fileName,
);
const matchedNodeType = validNodeTypes.find(
(nt) => nt.id === pattern.nodeTypeId,
);
if (!matchedNodeType) {
continue;
}
candidates.push({
file,
matchedNodeType,
alternativePattern: pattern.alternativePattern,
extractedContent,
selected: false,
});
break;
}
}
}
return candidates;
}
}
/**
* Returns raw imported node entries from import/ folder (no DB).
* Uses DataCore when available; otherwise iterates vault. Only includes files
* that have both importedFromRid and nodeInstanceId in frontmatter.
*/
export const getImportedNodesRaw = ({
queryEngine,
plugin,
}: {
queryEngine?: QueryEngine;
plugin: DiscourseGraphPlugin;
}): { importedFromRid: string; nodeInstanceId: string }[] => {
const engine = queryEngine ?? new QueryEngine(plugin.app);
const files = engine.getImportedNodePages();
const entries: { importedFromRid: string; nodeInstanceId: string }[] = [];
for (const file of files) {
const cache = plugin.app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter;
const importedFromRid = frontmatter?.importedFromRid as string | undefined;
const nodeInstanceId = frontmatter?.nodeInstanceId as string | undefined;
if (importedFromRid && nodeInstanceId) {
entries.push({ importedFromRid, nodeInstanceId });
}
}
return entries;
};