-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimportNodes.ts
More file actions
1615 lines (1467 loc) · 49.5 KB
/
Copy pathimportNodes.ts
File metadata and controls
1615 lines (1467 loc) · 49.5 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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Json } from "@repo/database/dbTypes";
import matter from "gray-matter";
import { App, Notice, TFile } from "obsidian";
import type { DGSupabaseClient } from "@repo/database/lib/client";
import type DiscourseGraphPlugin from "~/index";
import { getLoggedInClient, getSupabaseContext } from "./supabaseContext";
import type { DiscourseNode, ImportableNode } from "~/types";
import { QueryEngine } from "~/services/QueryEngine";
import {
getImportedNodesInfo,
getLocalNodeKeyToEndpointId,
} from "~/utils/relationsStore";
import { spaceUriAndLocalIdToRid } from "./rid";
import type { PostgrestResponse } from "@supabase/supabase-js";
import type { Tables } from "@repo/database/dbTypes";
import { getSpaceNameIdFromRid } from "./spaceFromRid";
import {
importRelationsForImportedNodes,
type RemoteRelationInstance,
} from "./importRelations";
import { createTemplateFile } from "./templates";
import { resolveFolderForSpaceUri } from "./importFolderMetadata";
type PublishedNode = {
source_local_id: string;
space_id: number;
text: string;
createdAt: number;
modifiedAt: number;
filePath: string | undefined;
authorId: number | undefined;
};
export const getPublishedNodesForGroups = async ({
client,
groupIds,
currentSpaceId,
}: {
client: DGSupabaseClient;
groupIds: string[];
currentSpaceId: number;
}): Promise<Array<PublishedNode>> => {
if (groupIds.length === 0) {
return [];
}
// Query my_contents (RLS applied); exclude current space. Get both variants so we can use
// the latest last_modified per node and prefer "direct" for text (title).
const { data, error } = await client
.from("my_contents")
.select(
"source_local_id, space_id, text, created, last_modified, variant, metadata, author_id",
)
.neq("space_id", currentSpaceId);
if (error) {
console.error("Error fetching published nodes:", error);
throw new Error(`Failed to fetch published nodes: ${error.message}`);
}
if (!data || data.length === 0) {
return [];
}
type Row = {
source_local_id: string | null;
space_id: number | null;
text: string | null;
created: string | null;
last_modified: string | null;
variant: string | null;
author_id: number | null;
metadata: Json;
};
const key = (r: Row) => `${r.space_id ?? ""}\t${r.source_local_id ?? ""}`;
const groups = new Map<string, Row[]>();
for (const row of data as Row[]) {
if (row.source_local_id == null || row.space_id == null) continue;
const k = key(row);
if (!groups.has(k)) groups.set(k, []);
groups.get(k)!.push(row);
}
const nodes: Array<PublishedNode> = [];
for (const rows of groups.values()) {
const withDate = rows.filter(
(r) => r.last_modified != null && r.text != null,
);
if (withDate.length === 0) continue;
const latest = withDate.reduce((a, b) =>
(a.last_modified ?? "") >= (b.last_modified ?? "") ? a : b,
);
const direct = rows.find((r) => r.variant === "direct");
const text = direct?.text ?? latest.text ?? "";
const createdAt = latest.created
? new Date(latest.created + "Z").valueOf()
: 0;
const modifiedAt = latest.last_modified
? new Date(latest.last_modified + "Z").valueOf()
: 0;
const filePath: string | undefined =
direct &&
typeof direct.metadata === "object" &&
typeof (direct.metadata as Record<string, any>).filePath === "string"
? (direct.metadata as Record<string, any>).filePath
: undefined;
nodes.push({
source_local_id: latest.source_local_id!,
space_id: latest.space_id!,
text,
createdAt,
modifiedAt,
filePath,
authorId: latest.author_id ?? undefined,
});
}
return nodes;
};
export const getLocalNodeInstanceIds = (
plugin: DiscourseGraphPlugin,
): Set<string> => {
const queryEngine = new QueryEngine(plugin.app);
const files = queryEngine.getFilesWithNodeInstanceId();
const nodeInstanceIds = new Set<string>();
for (const file of files) {
const cache = plugin.app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter;
if (frontmatter?.nodeInstanceId) {
nodeInstanceIds.add(frontmatter.nodeInstanceId as string);
}
}
return nodeInstanceIds;
};
/**
* Returns the space name for a given space ID.
* Falls back to "space-{id}" if the lookup fails.
*/
export const getSpaceNameFromId = async (
client: DGSupabaseClient,
spaceId: number,
): Promise<string> => {
const { data, error } = await client
.from("Space")
.select("name")
.eq("id", spaceId)
.maybeSingle();
if (error || !data) {
console.error("Error fetching space name:", error);
return `space-${spaceId}`;
}
return data.name;
};
export { getSpaceNameIdFromRid } from "./spaceFromRid";
export const getSpaceNameFromIds = async (
client: DGSupabaseClient,
spaceIds: number[],
): Promise<Map<number, string>> => {
if (spaceIds.length === 0) {
return new Map();
}
const { data, error } = (await client
.from("my_spaces")
.select("id, name")
.in("id", spaceIds)) as PostgrestResponse<Tables<"Space">>;
if (error) {
console.error("Error fetching space names:", error);
return new Map();
}
const spaceMap = new Map<number, string>();
(data || []).forEach((space) => {
spaceMap.set(space.id, space.name);
});
return spaceMap;
};
export const getSpaceUris = async (
client: DGSupabaseClient,
spaceIds: number[],
): Promise<Map<number, string>> => {
if (spaceIds.length === 0) {
return new Map();
}
const { data, error } = (await client
.from("my_spaces")
.select("id, url")
.in("id", spaceIds)) as PostgrestResponse<Tables<"Space">>;
if (error) {
console.error("Error fetching space urls:", error);
return new Map();
}
const spaceMap = new Map<number, string>();
(data || []).forEach((space) => {
spaceMap.set(space.id, space.url);
});
return spaceMap;
};
export const fetchUserNames = async (
plugin: DiscourseGraphPlugin,
client: DGSupabaseClient,
) => {
const result = await client
.from("my_accounts")
.select("id, name")
.eq("agent_type", "person");
if (result.error || !result.data) {
console.error(result.error);
return;
}
const nameById = Object.fromEntries(
result.data.map(({ id, name }) => [id, name]) as [number, string][],
);
plugin.settings.userNames = nameById;
await plugin.saveSettings();
};
export const fetchNodeContent = async ({
client,
spaceId,
nodeInstanceId,
variant,
}: {
client: DGSupabaseClient;
spaceId: number;
nodeInstanceId: string;
variant: "direct" | "full";
}): Promise<string | null> => {
const { data, error } = await client
.from("my_contents")
.select("text")
.eq("source_local_id", nodeInstanceId)
.eq("space_id", spaceId)
.eq("variant", variant)
.maybeSingle();
if (error || !data || data.text == null) {
console.error(
`Error fetching node content (${variant}):`,
error || "No data",
);
return null;
}
return data.text;
};
export const fetchNodeContentWithMetadata = async ({
client,
spaceId,
nodeInstanceId,
variant,
}: {
client: DGSupabaseClient;
spaceId: number;
nodeInstanceId: string;
variant: "direct" | "full";
}): Promise<{
content: string;
createdAt: number;
modifiedAt: number;
} | null> => {
const { data, error } = await client
.from("my_contents")
.select("text, created, last_modified")
.eq("source_local_id", nodeInstanceId)
.eq("space_id", spaceId)
.eq("variant", variant)
.maybeSingle();
if (error || !data || data.text == null) {
console.error(
`Error fetching node content with metadata (${variant}):`,
error || "No data",
);
return null;
}
return {
content: data.text,
createdAt: data.created ? new Date(data.created + "Z").valueOf() : 0,
modifiedAt: data.last_modified
? new Date(data.last_modified + "Z").valueOf()
: 0,
};
};
/**
* Fetches both direct (title) and full (body + dates) variants in one query.
* Used by importSelectedNodes to avoid two round-trips to the content table.
*/
const fetchNodeContentForImport = async ({
client,
spaceId,
nodeInstanceId,
}: {
client: DGSupabaseClient;
spaceId: number;
nodeInstanceId: string;
}): Promise<{
fileName: string;
content: string;
createdAt: number;
modifiedAt: number;
authorId: number;
filePath?: string;
} | null> => {
const { data, error } = await client
.from("my_contents")
.select("text, created, last_modified, variant, metadata, author_id")
.eq("source_local_id", nodeInstanceId)
.eq("space_id", spaceId)
.in("variant", ["direct", "full"]);
if (error) {
console.error("Error fetching node content for import:", error);
return null;
}
const rows = (data ?? []) as Array<{
text: string | null;
created: string | null;
last_modified: string | null;
author_id: number | null;
variant: string | null;
metadata: Json;
}>;
const direct = rows.find((r) => r.variant === "direct");
const full = rows.find((r) => r.variant === "full");
const authorId = full?.author_id ?? direct?.author_id ?? null;
if (
!direct?.text ||
!full?.text ||
full.created === null ||
full.last_modified === null ||
authorId === null
) {
return null;
}
const filePath: string | undefined =
typeof direct.metadata === "object" &&
typeof (direct.metadata as Record<string, any>).filePath === "string"
? (direct.metadata as Record<string, any>).filePath
: undefined;
return {
fileName: direct.text,
content: full.text,
createdAt: new Date(full.created + "Z").valueOf(),
modifiedAt: new Date(full.last_modified + "Z").valueOf(),
filePath,
authorId,
};
};
/**
* Fetches created/last_modified from the source space Content (my_contents) for an imported node.
* Used by the discourse context view to show "last modified in original vault".
*/
export const getSourceContentDates = async ({
plugin,
nodeInstanceId,
importedFromRid,
}: {
plugin: DiscourseGraphPlugin;
nodeInstanceId: string;
importedFromRid: string;
}): Promise<{ createdAt: string; modifiedAt: string } | null> => {
const client = await getLoggedInClient(plugin);
if (!client) return null;
const { spaceId } = await getSpaceNameIdFromRid(client, importedFromRid);
if (spaceId < 0) return null;
const { data, error } = await client
.from("my_contents")
.select("created, last_modified")
.eq("source_local_id", nodeInstanceId)
.eq("space_id", spaceId)
.eq("variant", "direct")
.maybeSingle();
if (error || !data) return null;
return {
createdAt: data.created ?? new Date(0).toISOString(),
modifiedAt: data.last_modified ?? new Date(0).toISOString(),
};
};
const fetchFileReferences = async ({
client,
spaceId,
nodeInstanceId,
}: {
client: DGSupabaseClient;
spaceId: number;
nodeInstanceId: string;
}): Promise<
Array<{
filepath: string;
filehash: string;
created: number;
last_modified: number;
}>
> => {
const { data, error } = (await client
.from("my_file_references")
.select("filepath, filehash, created, last_modified")
.eq("space_id", spaceId)
.eq("source_local_id", nodeInstanceId)) as PostgrestResponse<
Tables<"FileReference">
>;
if (error) {
console.error("Error fetching file references:", error);
return [];
}
return data.map(({ filepath, filehash, created, last_modified }) => ({
filepath,
filehash,
created: created ? new Date(created + "Z").valueOf() : 0,
last_modified: last_modified ? new Date(last_modified + "Z").valueOf() : 0,
}));
};
const downloadFileFromStorage = async ({
client,
filehash,
}: {
client: DGSupabaseClient;
filehash: string;
}): Promise<ArrayBuffer | null> => {
try {
const { data, error } = await client.storage
.from("assets")
.download(filehash);
if (error) {
return null;
}
if (!data) {
return null;
}
return await data.arrayBuffer();
} catch (error) {
console.error(`Exception downloading file ${filehash}:`, error);
return null;
}
};
/** Normalize path for lookup: strip leading "./", collapse slashes. Shared so pathMapping keys match link paths. */
const normalizePathForLookup = (p: string): string =>
p.replace(/^\.\//, "").replace(/\/+/g, "/").trim();
const updateMarkdownAssetLinks = ({
content,
oldPathToNewPath,
targetFile,
app,
originalNodePath,
}: {
content: string;
oldPathToNewPath: Map<string, string>;
targetFile: TFile;
app: App;
originalNodePath?: string;
}): string => {
// Create a set of all new paths for quick lookup (used by findImportedAssetFile when pathMapping has entries)
const newPaths = new Set(oldPathToNewPath.values());
let updatedContent = content;
const noteDir = targetFile.path.includes("/")
? targetFile.path.replace(/\/[^/]*$/, "")
: "";
// When the note is under import/{spaceName}/, only treat wiki links as resolved if the target is in this folder (not some other vault file).
const pathParts = targetFile.path.split("/");
const importFolder =
pathParts[0] === "import" && pathParts.length >= 2
? pathParts.slice(0, 2).join("/")
: null;
/** Path of targetFile relative to the current note, for use in links. Obsidian resolves relative links from the note's directory. */
const getRelativeLinkPath = (assetPath: string): string => {
const noteParts = noteDir ? noteDir.split("/").filter(Boolean) : [];
const targetParts = assetPath.split("/").filter(Boolean);
let i = 0;
while (
i < noteParts.length &&
i < targetParts.length &&
noteParts[i] === targetParts[i]
) {
i++;
}
const ups = noteParts.length - i;
const down = targetParts.slice(i);
const segments = [...Array(ups).fill(".."), ...down];
return segments.join("/");
};
// Resolve a path with ".." and "." segments relative to a base directory (vault-relative).
const resolvePathRelativeToBase = (
baseDir: string,
relativePath: string,
): string => {
const baseParts = baseDir ? baseDir.split("/").filter(Boolean) : [];
const pathParts = relativePath.replace(/\/+/g, "/").trim().split("/");
const result = [...baseParts];
for (const part of pathParts) {
if (part === "..") {
result.pop();
} else if (part !== "." && part !== "") {
result.push(part);
}
}
return result.join("/");
};
// Canonical form for matching link paths to oldPath (vault-relative, no import prefix).
const getLinkCanonicalForMatch = (linkPath: string): string => {
const resolved = resolvePathRelativeToBase(noteDir, linkPath);
if (resolved.startsWith("import/")) {
const segments = resolved.split("/");
return segments.length > 2 ? segments.slice(2).join("/") : resolved;
}
return resolved;
};
// Resolve link relative to the source note's directory (for "path from current file" when imported note is flattened).
const getCanonicalFromOriginalNote = (
linkPath: string,
): string | undefined => {
if (!originalNodePath) return undefined;
const originalNoteDir = originalNodePath.includes("/")
? originalNodePath.replace(/\/[^/]*$/, "")
: "";
return normalizePathForLookup(
resolvePathRelativeToBase(originalNoteDir, linkPath),
);
};
// Look up new path by link as written in content: use canonical form (resolve relative + strip import prefix).
const getNewPathForLink = (linkPath: string): string | undefined => {
const canonical = normalizePathForLookup(
getLinkCanonicalForMatch(linkPath),
);
const byCanonical = oldPathToNewPath.get(canonical);
if (byCanonical) return byCanonical;
const byRaw = oldPathToNewPath.get(normalizePathForLookup(linkPath));
if (byRaw) return byRaw;
// "Path from current file" in source: link was relative to source note; pathMapping keys are source vault-relative.
const fromOriginal = getCanonicalFromOriginalNote(linkPath);
return fromOriginal ? oldPathToNewPath.get(fromOriginal) : undefined;
};
// Helper to find file for a link path, checking if it's one of our imported assets
const findImportedAssetFile = (linkPath: string): TFile | null => {
// Try to resolve the link
const resolvedFile = app.metadataCache.getFirstLinkpathDest(
linkPath,
targetFile.path,
);
if (resolvedFile && newPaths.has(resolvedFile.path)) {
// This file is one of our imported assets
return resolvedFile;
}
// Also check if the resolved file is in an assets folder (user may have renamed it)
if (resolvedFile && resolvedFile.path.includes("/assets/")) {
// Check if any of our new files match this one (by checking if path is similar)
for (const newPath of newPaths) {
const newFile = app.metadataCache.getFirstLinkpathDest(
newPath,
targetFile.path,
);
if (newFile && newFile.path === resolvedFile.path) {
return resolvedFile;
}
}
}
return null;
};
const processLink = (linkPath: string): string => {
// Skip external URLs
if (linkPath.startsWith("http://") || linkPath.startsWith("https://")) {
return linkPath;
}
// Separate file path from heading/block fragment (e.g. "Note.md#section" → filePath="Note.md", fragment="#section")
// so that file resolution operates only on the file path portion.
const hashIndex = linkPath.indexOf("#");
const filePath = hashIndex !== -1 ? linkPath.slice(0, hashIndex) : linkPath;
const fragment = hashIndex !== -1 ? linkPath.slice(hashIndex) : "";
const resolveFilePath = (path: string): string => {
// First, try to find if this link resolves to one of our imported assets
const importedAssetFile = findImportedAssetFile(path);
if (importedAssetFile) {
return getRelativeLinkPath(importedAssetFile.path);
}
// Direct lookup from pathMapping (record built when we downloaded each asset)
const newPath = getNewPathForLink(path);
if (newPath) {
const newFile = app.metadataCache.getFirstLinkpathDest(
newPath,
targetFile.path,
);
if (newFile) {
return getRelativeLinkPath(newFile.path);
}
}
// Only resolve to files under import/{spaceName}/ so we don't point at the wrong vault's files
const resolvedFile = app.metadataCache.getFirstLinkpathDest(
path,
targetFile.path,
);
const isInImportFolder =
importFolder &&
resolvedFile &&
resolvedFile.path.startsWith(importFolder + "/");
if (isInImportFolder && resolvedFile) {
return getRelativeLinkPath(resolvedFile.path);
}
// Unresolved (dead) link from another vault: rewrite so that when the user creates the file from this link, it is created under import/{vaultName}/ in the same relative position as in the source vault
if (importFolder && originalNodePath && !resolvedFile) {
// Vault-relative link (e.g. "Discourse Nodes/EVD - no relation testing") -> use as-is. Path-from-current-file (e.g. "EVD - no relation testing") -> resolve relative to source note dir
const canonicalSourcePath =
path.includes("/") && !path.startsWith(".") && !path.startsWith("/")
? normalizePathForLookup(path)
: (getCanonicalFromOriginalNote(path) ??
normalizePathForLookup(path));
return `${importFolder}/${canonicalSourcePath}`;
}
return path;
};
return resolveFilePath(filePath) + fragment;
};
// Match wiki links: [[path]] or [[path|alias]]
const wikiLinkRegex = /\[\[([^\]]+)\]\]/g;
updatedContent = updatedContent.replace(
wikiLinkRegex,
(match, linkContent: string) => {
// Extract path and optional alias
const [linkPath, alias] = linkContent
.split("|")
.map((s: string) => s.trim());
if (!linkPath) return match;
let processedPath = processLink(linkPath);
const hashIdx = processedPath.indexOf("#");
const pathBeforeHash =
hashIdx !== -1 ? processedPath.slice(0, hashIdx) : processedPath;
const pathAfterHash = hashIdx !== -1 ? processedPath.slice(hashIdx) : "";
if (pathBeforeHash.endsWith(".md") && !linkPath.endsWith(".md")) {
processedPath = pathBeforeHash.slice(0, -3) + pathAfterHash;
}
if (alias) {
return `[[${processedPath}|${alias}]]`;
}
return `[[${processedPath}|${linkPath}]]`;
},
);
// Match markdown links (non-image): [text](path) — internal paths resolved like wikilinks, href kept URL-encoded
const markdownLinkRegex = /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g;
updatedContent = updatedContent.replace(
markdownLinkRegex,
(match, linkText: string, linkPath: string) => {
if (!linkPath) return match;
linkPath = linkPath
.split("/")
.map((segment) => {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
})
.join("/");
if (linkPath.startsWith("http://") || linkPath.startsWith("https://")) {
return match;
}
const processedPath = encodePathForMarkdownLink(processLink(linkPath));
return `[${linkText}](${processedPath})`;
},
);
// Match markdown image links:  or 
const markdownImageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
updatedContent = updatedContent.replace(
markdownImageRegex,
(match, alt, linkPath) => {
// Remove optional title from linkPath: "path" or "path title"
const cleanPath = linkPath.replace(/\s+"[^"]*"$/, "").trim();
// Skip external URLs
if (cleanPath.startsWith("http://") || cleanPath.startsWith("https://")) {
return match;
}
// First, try to find if this link resolves to one of our imported assets
const importedAssetFile = findImportedAssetFile(cleanPath);
if (importedAssetFile) {
const linkText = getRelativeLinkPath(importedAssetFile.path);
return ``;
}
// Direct lookup from pathMapping (record built when we downloaded each asset)
const newPath = getNewPathForLink(cleanPath);
if (newPath) {
const newFile = app.metadataCache.getFirstLinkpathDest(
newPath,
targetFile.path,
);
if (newFile) {
const linkText = getRelativeLinkPath(newFile.path);
return ``;
}
}
return match;
},
);
return updatedContent;
};
/** Path of an asset relative to the note's directory (vault-relative). If asset is not under note dir, returns full path. */
const getAssetPathRelativeToNote = (
assetFilePath: string,
originalNodePath: string,
): string => {
const noteDir = originalNodePath.includes("/")
? originalNodePath.replace(/\/[^/]*$/, "")
: "";
if (!noteDir || !assetFilePath.startsWith(`${noteDir}/`)) {
return assetFilePath;
}
return assetFilePath.slice(noteDir.length + 1);
};
const importAssetsForNode = async ({
plugin,
client,
spaceId,
nodeInstanceId,
importBasePath,
targetMarkdownFile,
originalNodePath,
}: {
plugin: DiscourseGraphPlugin;
client: DGSupabaseClient;
spaceId: number;
nodeInstanceId: string;
importBasePath: string;
targetMarkdownFile: TFile;
/** Source vault path of the note (e.g. from Content metadata filePath). Used to place assets under import/{space}/ relative to note. */
originalNodePath?: string;
}): Promise<{
success: boolean;
pathMapping: Map<string, string>; // old path -> new path
errors: string[];
}> => {
const pathMapping = new Map<string, string>();
const errors: string[] = [];
const stat = {
ctime: targetMarkdownFile.stat.ctime,
mtime: targetMarkdownFile.stat.mtime,
};
const setPathMapping = (oldPath: string, newPath: string): void => {
pathMapping.set(oldPath, newPath);
pathMapping.set(normalizePathForLookup(oldPath), newPath);
};
// Fetch FileReference records for the node
const fileReferences = await fetchFileReferences({
client,
spaceId,
nodeInstanceId,
});
if (fileReferences.length === 0) {
return { success: true, pathMapping, errors };
}
// Get existing asset mappings from frontmatter
const cache = plugin.app.metadataCache.getFileCache(targetMarkdownFile);
const frontmatter = (cache?.frontmatter as Record<string, unknown>) || {};
const importedAssetsRaw = frontmatter.importedAssets;
const importedAssets: Record<string, string> =
importedAssetsRaw &&
typeof importedAssetsRaw === "object" &&
!Array.isArray(importedAssetsRaw)
? (importedAssetsRaw as Record<string, string>)
: {};
// importedAssets format: { filehash: vaultPath }
// Process each file reference
for (const fileRef of fileReferences) {
try {
const { filepath, filehash } = fileRef;
// Check if we already have a file for this hash
const existingAssetPath: string | undefined = importedAssets[filehash];
let existingFile: TFile | null = null;
if (existingAssetPath) {
// Check if the file still exists at the stored path
const file = plugin.app.vault.getAbstractFileByPath(existingAssetPath);
if (file && file instanceof TFile) {
existingFile = file;
}
}
let overwritePath: string | undefined;
if (existingFile) {
const refLastModifiedMs = fileRef.last_modified || 0;
const localModifiedAfterRef =
refLastModifiedMs > 0 && existingFile.stat.mtime > refLastModifiedMs;
if (!localModifiedAfterRef) {
setPathMapping(filepath, existingFile.path);
continue;
}
overwritePath = existingFile.path;
}
// Target path: import/{spaceName}/{path relative to note}. If sourceNotePath is set and asset
// is under the note's directory, use that relative path so assets sit under import/{space}/.
const pathForImport =
originalNodePath !== undefined
? getAssetPathRelativeToNote(filepath, originalNodePath)
: filepath;
const sanitizedAssetPath = pathForImport
.split("/")
.map(sanitizeFileName)
.join("/");
const targetPath =
overwritePath ?? `${importBasePath}/${sanitizedAssetPath}`;
// Ensure all parent folders exist before writing
const pathParts = targetPath.split("/");
for (let i = 1; i < pathParts.length - 1; i++) {
const folderPath = pathParts.slice(0, i + 1).join("/");
if (!(await plugin.app.vault.adapter.exists(folderPath))) {
await plugin.app.vault.createFolder(folderPath);
}
}
// If local mtime is newer than fileRef.last_modified, overwrite with DB version.
if (await plugin.app.vault.adapter.exists(targetPath)) {
const file = plugin.app.vault.getAbstractFileByPath(targetPath);
if (file && file instanceof TFile) {
const localMtimeMs = file.stat.mtime;
const refLastModifiedMs = fileRef.last_modified || 0;
const localModifiedAfterRef =
refLastModifiedMs > 0 && localMtimeMs > refLastModifiedMs;
const remoteIsNewer =
refLastModifiedMs > 0 && refLastModifiedMs > localMtimeMs;
if (!localModifiedAfterRef && !remoteIsNewer) {
setPathMapping(filepath, targetPath);
await plugin.app.fileManager.processFrontMatter(
targetMarkdownFile,
(fm) => {
const assetsRaw = (fm as Record<string, unknown>)
.importedAssets;
const assets: Record<string, string> =
assetsRaw &&
typeof assetsRaw === "object" &&
!Array.isArray(assetsRaw)
? (assetsRaw as Record<string, string>)
: {};
assets[filehash] = targetPath;
(fm as Record<string, unknown>).importedAssets = assets;
},
stat,
);
continue;
}
// Local file was modified OR remote is newer; overwrite with DB version
}
}
// File doesn't exist, download it
const fileContent = await downloadFileFromStorage({
client,
filehash,
});
if (!fileContent) {
errors.push(`Failed to download file: ${filepath}`);
continue;
}
const options = { mtime: fileRef.last_modified, ctime: fileRef.created };
// Save file to vault
const existingFileForOverwrite =
plugin.app.vault.getAbstractFileByPath(targetPath);
if (
existingFileForOverwrite &&
existingFileForOverwrite instanceof TFile
) {
await plugin.app.vault.modifyBinary(
existingFileForOverwrite,
fileContent,
options,
);
} else {
await plugin.app.vault.createBinary(targetPath, fileContent, options);
}
// Update frontmatter to track this mapping
await plugin.app.fileManager.processFrontMatter(
targetMarkdownFile,
(fm) => {
const assetsRaw = (fm as Record<string, unknown>).importedAssets;
const assets: Record<string, string> =
assetsRaw &&
typeof assetsRaw === "object" &&
!Array.isArray(assetsRaw)
? (assetsRaw as Record<string, string>)
: {};
assets[filehash] = targetPath;
(fm as Record<string, unknown>).importedAssets = assets;
},
stat,
);
// Track path mapping (raw + normalized key so updateMarkdownAssetLinks can lookup by link text)
setPathMapping(filepath, targetPath);
} catch (error) {
const errorMsg = `Error importing asset ${fileRef.filepath}: ${error}`;
errors.push(errorMsg);
console.error(errorMsg, error);
}
}
return {
success: errors.length === 0 || pathMapping.size > 0,
pathMapping,
errors,
};
};
const sanitizeFileName = (fileName: string): string => {
// Remove invalid characters for file names
return fileName
.replace(/[<>:"/\\|?*]/g, "")
.replace(/\s+/g, " ")
.trim();
};
/** Sanitize each path segment for use under import folder (preserves source vault folder structure). */
const sanitizePathForImport = (path: string): string => {
return path
.split("/")
.map((segment) => sanitizeFileName(segment))
.filter(Boolean)
.join("/");
};
type ParsedFrontmatter = {
nodeTypeId?: string;
nodeInstanceId?: string;
publishedToGroups?: string[];
authorId?: number;
[key: string]: unknown;
};
const parseFrontmatter = (
content: string,
): { frontmatter: ParsedFrontmatter; body: string } => {