speki-app 0.1.0

ontological flashcard app
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
import * as git from "https://esm.sh/isomorphic-git@1.27.1";
import http from "https://esm.sh/isomorphic-git@1.27.1/http/web";
import * as path from "https://esm.sh/path-browserify";

let fs;

console.log("utils.js loaded!!!");



const initBrowserFS = new Promise((resolve, reject) => {
    BrowserFS.configure({ fs: "IndexedDB", options: {} }, (err) => {
        if (err) {
            console.error("Failed to initialize BrowserFS:", err);
            reject(err);
        } else {
            fs = BrowserFS.BFSRequire("fs"); 
            console.log("BrowserFS initialized");
            resolve();
        }
    });
});


export async function loadFile(path) {
    await initBrowserFS;
    return new Promise((resolve, reject) => {
        fs.readFile(path, "utf8", (err, data) => {
            if (err) {
                if (err.code === "ENOENT") {
                    resolve(null);
                } else {
                    console.error("Error reading file:", err);
                    reject("Error reading file: " + err);
                }
            } else {
                resolve(data); // Return file contents as a string
            }
        });
    });
}


export async function allPaths(repoPath) {
    const subdirs = ["cards", "attributes", "reviews"];
    const allFilePaths = [];

    for (const subdir of subdirs) {
        const fullSubdirPath = `${repoPath}/${subdir}`;
        console.log(fullSubdirPath);
        try {
            const filePaths = await getFilePaths(fullSubdirPath); 
            console.log(filePaths);

            const relativePaths = filePaths.map((filePath) =>
                filePath.replace(`${repoPath}/`, '') 
            );

            console.log(relativePaths);

            allFilePaths.push(...relativePaths);
        } catch (err) {
            console.error(`Failed to get files from ${fullSubdirPath}: ${err}`);
        }
    }

    return allFilePaths;
}




async function getFilePaths(folderPath) {
    await initBrowserFS;

    return new Promise((resolve, reject) => {
        fs.readdir(folderPath, (err, files) => {
            if (err) {
                reject(`Error reading directory: ${err}`);
                return;
            }

            // Prepend the folder path to each file name to get the full path
            const fullPaths = files.map((file) => `${folderPath}/${file}`);
            resolve(fullPaths);
        });
    });
}




export async function cloneRepo(path, url, token, proxy) {
    const output = document.getElementById("output");

    await initBrowserFS;


    try {
        console.log(`starting clone from ${url} files to ${path} with token ${token} through proxy ${proxy}!`);
	let cache = {};
        await git.clone({
            fs,
            http,
	    cache,
            dir: path, 
            url: url, 
            corsProxy: proxy,
            onProgress: (progress) => {
                console.log(`${progress.phase}: ${progress.loaded} of ${progress.total}`);
              },
            onAuth: () => ({
                username: 'x-access-token',
                password: token
            })
        });
        console.log(`successsddd nice`);
        output.textContent = "Repository cloned successfully!";
    } catch (error) {
        output.textContent = "Failed to clone repository: " + error;
    }
}

//////////////





async function addFile(repoPath, filepath) {
    console.log(`the file to add: ${filepath} `);
    await git.add({ fs, dir: repoPath, filepath });
    console.log("adding file...");
}




///////////////////////////////////////////////////////////////




// A utility function to check the git status of a repository
export async function gitStatus(path) {
    const output = document.getElementById("output");

    await initBrowserFS;

    try {
        console.log(`Checking git status for repo at ${path}...`);
        
        // Use the isomorphic-git `statusMatrix` function
        const statusMatrix = await git.statusMatrix({
            fs,
            dir: path
        });

        let statusSummary = "";

        // Analyze the status matrix
        for (const [filepath, head, workdir, stage] of statusMatrix) {
            if (head !== workdir || workdir !== stage) {
                statusSummary += `${filepath}: `;
                if (head === 0 && workdir !== 0) {
                    statusSummary += "Untracked\n";
                } else if (head !== workdir && workdir === stage) {
                    statusSummary += "Modified\n";
                } else if (workdir !== stage) {
                    statusSummary += "Staged\n";
                }
            }
        }

        if (!statusSummary) {
            statusSummary = "Working directory clean!";
        }

        output.textContent = statusSummary;
        return statusSummary;
    } catch (error) {
        const errorMsg = `Failed to get git status: ${error}`;
        output.textContent = errorMsg;
        throw new Error(errorMsg);
    }
}

export async function newReviews(repoPath) {
    const output = document.getElementById("output");

    await initBrowserFS;

        try {
        console.log(`Counting changed files in the 'reviews' folder within repo at '${repoPath}'...`);

        // Use isomorphic-git's `statusMatrix` to get file statuses
        const statusMatrix = await git.statusMatrix({
            fs,
            dir: repoPath
        });

        console.log(`supp`);

        // Filter files in the 'reviews' folder and count those with changes
        const changedFilesCount = statusMatrix.filter(([filepath, head, workdir, stage]) =>
            filepath.startsWith('reviews/') && (head !== workdir || workdir !== stage)
        ).length;

        console.log(`hey`);

        const resultMessage = `Number of changed files in the 'reviews' folder: ${changedFilesCount}`;
        output.textContent = resultMessage;

        console.log(resultMessage);
        return changedFilesCount;
    } catch (error) {
        const errorMsg = `Failed to count changed files in the 'reviews' folder: ${error}`;
        output.textContent = errorMsg;
        console.error(errorMsg);
        throw new Error(errorMsg);
    }
}

function gitCreds(){
    return {
        fs,
        http,
        dir: repoPath,
        corsProxy: "https://cors.isomorphic-git.org",
        singleBranch: true,
        onAuth: () => ({
            username: 'x-access-token',
            password: token
        }),
        author: {
            name: "myself",
            email: "myself@mymail.com"
        }
    }

}





export async function validateUpstream(repoPath, token) {
    try {
        await initBrowserFS;

        console.log(`Validating upstream connection for repository at '${repoPath}'...`);

        const customHttpClient = {
            request: async (url, options) => {
                // Add the "Origin" header for the CORS proxy
                options.headers = {
                    ...options.headers,
                    "Origin": "http://localhost:8080" // Replace with your app's actual origin
                };

                console.log("HTTP Request:", url, options);

                const response = await fetch(url, options);
                console.log("HTTP Response:", response.status, response.statusText);

                const body = await response.text();
                console.log("HTTP Response Body:", body);

                return new Response(body, {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                });
            }
        };


        await git.fetch({
            fs,
            http,
            dir: repoPath,
            onAuth: () => ({
                username: 'x-access-token',
                password: token
            }),
            depth: 1, 
        });

        console.log("Upstream connection validated successfully!");
        return true;
    } catch (error) {
        console.error(`Failed to validate upstream connection: ${error}`);
        return false;
    }
}


export async function gitClone(dir, url, token, proxy) {
  console.log(`Initializing repository at ${dir}...`);
  await initBrowserFS;
  await git.init({ fs, dir });

  let ref = 'main';

  console.log(`Adding remote ${url} as "origin"...`);
  await git.addRemote({ fs, dir, remote: 'origin', url });

  await git.fetch({
    fs,
    http,
    corsProxy: proxy,
    dir,
    remote: 'origin',
    singleBranch: true,
    depth: 1,
    ref,
  });

const refs = await git.listBranches({ fs, dir, remote: 'origin' });
console.log('Fetched refs:', refs);

const commitOid = await git.resolveRef({ fs, dir, ref: 'refs/remotes/origin/main' });
console.log(`Commit OID for origin/main: ${commitOid}`);

const branches = await git.listBranches({ fs, dir });
console.log('Local branches:', branches);



if (!branches.includes(ref)) {
  console.log(`Creating and checking out local branch ${ref}...`);
  console.log(`Creating local branch ${ref}...`);
  await git.writeRef({
    fs,
    dir,
    ref: `refs/heads/${ref}`,
    value: commitOid, 
    force: true, 
  });

  // Update HEAD to point to the new branch
  await git.writeRef({
    fs,
    dir,
    ref: 'HEAD',
    value: `refs/heads/${ref}`,
    force: true,
  });
} else {
  console.log(`Branch ${ref} already exists locally. Checking it out...`);
  console.log(`Checking out branch ${ref}...`);
  await git.checkout({ fs, dir, ref });
}

const bs = await git.listBranches({ fs, dir });
console.log('Local branches:', bs);

const head = await git.resolveRef({ fs, dir, ref: 'HEAD' });
console.log('Current HEAD:', head);



  console.log(`Repository cloned into ${dir}`);
}



export async function loadRec(dirPath) {
  await initBrowserFS;

    const allFiles = [];
    
    await new Promise((resolve, reject) => {
        fs.readdir(dirPath, async (err, entries) => {
            if (err) {
                console.error("Error reading directory:", err);
                reject("Error reading directory: " + err);
                return;
            }

            let entriesProcessed = 0;

            if (entries.length === 0) resolve(allFiles); // Return if empty

            entries.forEach(async (entry) => {
                console.log(dirPath);
                console.log(entry);

                const entryPath = path.join(dirPath, entry);

                // Check if it's a directory or file
                fs.stat(entryPath, async (err, stats) => {
                    if (err) {
                        console.error(`Error reading file stats ${entryPath}:`, err);
                        reject("Error reading file stats: " + err);
                        return;
                    }

                    if (stats.isDirectory()) {
                        // Recursive call for directories
                        const subDirFiles = await loadRec(entryPath);
                        allFiles.push(...subDirFiles);
                    } else if (stats.isFile()) {
                        // Load the file contents
                        const fileContents = await loadAllFiles(dirPath);
                        allFiles.push(...fileContents);
                    }

                    entriesProcessed++;
                    if (entriesProcessed === entries.length) {
                        resolve(allFiles);
                    }
                });
            });
        });
    });

    return allFiles;
}

function readdir(dirPath) {
    return new Promise((resolve, reject) => {
        fs.readdir(dirPath, (err, files) => {
            if (err) reject(err);
            else resolve(files);
        });
    });
}

function stat(filePath) {
    return new Promise((resolve, reject) => {
        fs.stat(filePath, (err, stats) => {
            if (err) reject(err);
            else resolve(stats);
        });
    });
}

function unlink(filePath) {
    return new Promise((resolve, reject) => {
        fs.unlink(filePath, (err) => {
            if (err) reject(err);
            else resolve();
        });
    });
}

function rmdir(dirPath) {
    return new Promise((resolve, reject) => {
        fs.rmdir(dirPath, (err) => {
            if (err) reject(err);
            else resolve();
        });
    });
}

export async function deleteDir(dirPath) {
    await initBrowserFS;
    console.log("deleting dir: ${dirPath}");

    const entries = await readdir(dirPath);

    for (const entry of entries) {
        const fullPath = `${dirPath}/${entry}`;
        const stats = await stat(fullPath);

        if (stats.isDirectory()) {
            await deleteDir(fullPath);
        } else {
            await unlink(fullPath);
        }
    }

    await rmdir(dirPath);
    console.log("deleted!");
}

export async function lastModified(filePath) {
  await initBrowserFS;

  return new Promise((resolve, reject) => {
      fs.stat(filePath, (err, stats) => {
        if (err) {
            return resolve(null);
        }

        resolve(stats.mtime);
      });
    });
}

export async function loadFilenames(directory) {
    await initBrowserFS;
    console.log(directory);
    return new Promise((resolve, reject) => {
        fs.readdir(directory, (err, files) => {
            if (err) reject(err);
            else resolve(files);
        });
    });

}

export async function syncRepo(repoPath, token, proxy) {
    console.log("adding files..");
    await addAllFiles(repoPath);
    console.log("commiting files..");
    await commit(repoPath, token);
    console.log("pulling repo..");
    await pullRepo(repoPath, token, proxy);
    console.log("pushing repo..");
    await pushRepo(repoPath, token, proxy);
}

async function addAllFiles(repopath) {
    await initBrowserFS;

    let paths = await modifiedFiles(repopath);
    console.log(paths);

    console.log("Adding all files...");
    await Promise.all(
        paths.map((path) => addFile(repopath, path))
    );
    console.log("All files added!");
}

async function modifiedFiles(repopath) {
    await initBrowserFS;
    const FILE = 0, HEAD = 1, WORKDIR = 2

    const filenames = (await git.statusMatrix({ fs,dir: repopath }))
      .filter(row => row[HEAD] !== row[WORKDIR])
      .map(row => row[FILE]);

      console.log(filenames);
      return filenames;
}

async function commit(repoPath, token){
    await initBrowserFS;
        const { name, email } = await fetchGitHubUserDetails(token);
        await git.commit({
            fs,
            dir: repoPath,
            message: "commit",
            author: {
                name,
                email
            }
        });
}

async function fetchGitHubUserDetails(token) {
    return {
        name: "unknown user",
        email: "unknown@example.com"
    }

    const response = await fetch("https://api.github.com/user", {
        headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/vnd.github.v3+json"
        }
    });

    if (!response.ok) {
        throw new Error(`Failed to fetch user details: ${response.statusText}`);
    }

    const userData = await response.json();

    return {
        name: userData.name || "Unknown User",
        email: userData.email || "unknown@example.com" 
    };
}





export async function pullRepo(repoPath, token, proxy) {
    await fetchRepo(repoPath, token, proxy);
    await mergeRepo(repoPath, token);
}

export async function fetchRepo(path, token, proxy) {
    await initBrowserFS;
        console.log(`starting fetch from files to ${path} with token ${token} through proxy ${proxy}!`);
        await git.fetch({
            fs,
            http,
            dir: path, 
            corsProxy: proxy,
            singleBranch: true,
            onProgress: (progress) => {
                console.log(`${progress.phase}: ${progress.loaded} of ${progress.total}`);
              },
            onAuth: () => ({
                username: 'x-access-token',
                password: token
            })
        });
        console.log(`successsddd nice`);
}

async function mergeRepo(repoPath, token) {
    await initBrowserFS;

    console.log(`merging repository at '${repoPath}...`);
    const { name, email } = await fetchGitHubUserDetails(token);

    const mergeDriver = async ({ contents, path }) => {
        const baseContent = contents[0];
        const ourContent = contents[1];
        const theirContent = contents[2];

        console.log(`merging path: ${path}`);


        const pattern = /^\d{10} \d/;
        let isReview =  pattern.test(baseContent) || pattern.test(ourContent) || pattern.test(theirContent);
      
        if (!isReview) {
            console.log(`choosing upstream commit for file: ${theirContent} `);
          return { cleanMerge: true, mergedText: theirContent };
        }
      
        const combinedLines = [
          ...baseContent.split('\n'),
          ...ourContent.split('\n'),
          ...theirContent.split('\n'),
        ];
        console.log(combinedLines);
        const uniqueSortedLines = [...new Set(combinedLines)].sort();
        console.log(uniqueSortedLines);

        let mergedText = uniqueSortedLines.join('\n').trim();
        console.log(mergedText);
      
        return {
          cleanMerge: true,
          mergedText,
        };
      };

    await git.merge({
        fs,
        ours: 'main',
        theirs: 'remotes/origin/main',
        dir: repoPath,
        mergeDriver,
        author: {
            name,
            email
        }
    });

    console.log("Repository successfully merged with latest changes!");
}

export async function pushRepo(repoPath, token, proxy) {
    await initBrowserFS;

        console.log(`Pushing latest changes in the repository at '${repoPath} with token ${token}'...`);
        const { name, email } = await fetchGitHubUserDetails(token);
        let cache = {};

        await git.push({
            fs,
            http,
            cache,
            dir: repoPath,
            corsProxy: proxy,
            ref: 'main',
            onProgress: (progress) => {
                console.log(`${progress.phase}: ${progress.loaded} of ${progress.total}`);
              },
            onAuth: () => ({
                username: 'x-access-token',
                password: token
            }),
            author: {
                name,
                email
            }
        });

        const resultMessage = "Repository successfully updated with latest changes!";
        console.log(resultMessage);
        return resultMessage;
}