-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdatabase.ts
More file actions
2716 lines (2439 loc) · 93.7 KB
/
Copy pathdatabase.ts
File metadata and controls
2716 lines (2439 loc) · 93.7 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
/* eslint-disable */
// SPDX-License-Identifier: AGPL-3.0-or-later
import Database from "better-sqlite3";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const DEFAULT_DB_DIR = "data";
export interface ClassRow {
id: number;
library_name: string;
library_version: string;
class_name: string;
class_kind: string;
description: string | null;
documentation: string | null;
}
export interface ExtendsRow {
id: number;
class_id: number;
base_class: string;
}
export interface ComponentRow {
id: number;
class_id: number;
component_name: string;
type_name: string;
description: string | null;
causality: string | null;
variability: string | null;
}
export interface ModifierRow {
id: number;
component_id: number;
modifier_name: string;
modifier_value: string | null;
}
export interface ClassMetadata {
className: string;
classKind: string;
description: string | null;
documentation: string | null;
baseClasses: string[];
components: ComponentMetadata[];
}
export interface ComponentMetadata {
name: string;
typeName: string;
description: string | null;
causality: string | null;
variability: string | null;
modifiers: { name: string; value: string | null }[];
}
export interface TrendingTopicRow {
id: number;
concept: string;
display_name: string;
current_score: number;
last_updated_at: string;
}
export interface JobRow {
id: number;
name: string;
status: string;
type: string;
repository_id: number | null;
trigger_source: string | null;
metadata: string | null;
started_at: string;
completed_at: string | null;
}
export interface JobStepRow {
id: number;
job_id: number;
name: string;
status: string;
started_at: string;
completed_at: string | null;
}
export interface ScriptTemplateRow {
id: number;
name: string;
slug: string;
description: string;
category: string;
icon: string;
config: string;
created_at: string;
updated_at: string;
}
/**
* SQLite-backed storage for Modelica class metadata.
*/
export class LibraryDatabase {
readonly #db: Database.Database;
constructor(dbDir?: string) {
const dir = dbDir ?? DEFAULT_DB_DIR;
const dbPath = path.join(dir, "modelscript.db");
// Ensure directory exists
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
this.#db = new Database(dbPath);
this.#db.pragma("journal_mode = WAL");
this.#initialize();
}
get db(): Database.Database {
return this.#db;
}
resetDevData() {
const tables = [
"classes",
"extends",
"components",
"modifiers",
"users",
"oauth_accounts",
"follows",
"rss_feeds",
"user_rss_subscriptions",
"artifact_views",
"posts",
"likes",
"bookmarks",
"notifications",
"linked_repos",
"user_topics",
"trending_topics",
"post_topics",
"packages",
"package_versions",
"classes",
"dist_tags",
"artifacts",
"post_syndications",
"post_location_stats",
"cad_cache",
"settings",
"settings",
"user_public_keys",
"jobs",
"job_steps",
"script_templates",
];
this.#db.exec("PRAGMA foreign_keys = OFF;");
this.#db.transaction(() => {
for (const table of tables) {
this.#db.exec(`DROP TABLE IF EXISTS ${table};`);
}
})();
this.#db.exec("PRAGMA foreign_keys = ON;");
this.#initialize();
}
#initialize(): void {
this.#db.exec(`
CREATE TABLE IF NOT EXISTS classes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
library_name TEXT NOT NULL,
library_version TEXT NOT NULL,
class_name TEXT NOT NULL,
class_kind TEXT NOT NULL,
description TEXT,
documentation TEXT,
UNIQUE(library_name, library_version, class_name)
);
CREATE TABLE IF NOT EXISTS extends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
class_id INTEGER NOT NULL REFERENCES classes(id) ON DELETE CASCADE,
base_class TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS components (
id INTEGER PRIMARY KEY AUTOINCREMENT,
class_id INTEGER NOT NULL REFERENCES classes(id) ON DELETE CASCADE,
component_name TEXT NOT NULL,
type_name TEXT NOT NULL,
description TEXT,
causality TEXT,
variability TEXT
);
CREATE TABLE IF NOT EXISTS modifiers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
component_id INTEGER NOT NULL REFERENCES components(id) ON DELETE CASCADE,
modifier_name TEXT NOT NULL,
modifier_value TEXT
);
CREATE INDEX IF NOT EXISTS idx_classes_library ON classes(library_name, library_version);
CREATE INDEX IF NOT EXISTS idx_extends_class ON extends(class_id);
CREATE INDEX IF NOT EXISTS idx_components_class ON components(class_id);
CREATE INDEX IF NOT EXISTS idx_modifiers_component ON modifiers(component_id);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
password_hash TEXT,
display_name TEXT,
bio TEXT,
avatar_url TEXT DEFAULT 'https://ui-avatars.com/api/?name=User&background=random&color=fff',
banner_url TEXT DEFAULT 'https://images.unsplash.com/photo-1557682250-33bd709cbe85?auto=format&fit=crop&w=1200&q=80',
location TEXT,
website TEXT,
notification_settings TEXT DEFAULT '{}',
account_type TEXT DEFAULT 'user',
rsa_private_key TEXT,
rsa_public_key TEXT,
actor_url TEXT,
inbox_url TEXT,
outbox_url TEXT,
remote_domain TEXT,
owner_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
bot_token_hash TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS oauth_accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider TEXT NOT NULL,
provider_user_id TEXT NOT NULL,
access_token TEXT,
refresh_token TEXT,
expires_at TEXT,
UNIQUE(provider, provider_user_id)
);
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
CREATE TABLE IF NOT EXISTS follows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
follower_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
following_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(follower_id, following_id)
);
CREATE INDEX IF NOT EXISTS idx_follows_follower ON follows(follower_id);
CREATE INDEX IF NOT EXISTS idx_follows_following ON follows(following_id);
CREATE TABLE IF NOT EXISTS rss_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title TEXT,
description TEXT,
site_url TEXT,
last_fetched_at TEXT,
last_guid TEXT,
created_at TEXT DEFAULT (datetime('now')),
etag TEXT,
last_modified TEXT,
poll_interval_mins INTEGER DEFAULT 15,
last_polled_at TEXT
);
CREATE TABLE IF NOT EXISTS user_rss_subscriptions (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rss_feed_id INTEGER NOT NULL REFERENCES rss_feeds(id) ON DELETE CASCADE,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY(user_id, rss_feed_id)
);
CREATE TABLE IF NOT EXISTS artifact_views (
id INTEGER PRIMARY KEY AUTOINCREMENT,
creator_id INTEGER NOT NULL REFERENCES users(id),
view_type TEXT NOT NULL,
source_type TEXT NOT NULL,
source_ref TEXT,
title TEXT,
view_config TEXT NOT NULL,
thumbnail_url TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT,
artifact_view_id INTEGER REFERENCES artifact_views(id),
reply_to_id INTEGER REFERENCES posts(id),
quote_post_id INTEGER REFERENCES posts(id),
repost_of_id INTEGER REFERENCES posts(id),
view_count INTEGER DEFAULT 0,
ap_id TEXT UNIQUE,
url TEXT,
metadata TEXT,
reply_visibility TEXT DEFAULT 'everyone',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_posts_author ON posts(author_id);
CREATE INDEX IF NOT EXISTS idx_posts_reply ON posts(reply_to_id);
CREATE INDEX IF NOT EXISTS idx_posts_created ON posts(created_at DESC);
CREATE TABLE IF NOT EXISTS user_public_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
key_id_string TEXT NOT NULL UNIQUE,
public_key_pem TEXT NOT NULL,
device_name TEXT,
created_at TEXT DEFAULT (datetime('now')),
expires_at TEXT,
is_active INTEGER DEFAULT 1
);
CREATE INDEX IF NOT EXISTS idx_user_public_keys_user ON user_public_keys(user_id);
CREATE TABLE IF NOT EXISTS post_syndications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
target TEXT NOT NULL,
external_id TEXT NOT NULL,
url TEXT,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(post_id, target)
);
CREATE INDEX IF NOT EXISTS idx_post_syndications_post ON post_syndications(post_id);
CREATE TABLE IF NOT EXISTS likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(user_id, post_id)
);
CREATE INDEX IF NOT EXISTS idx_likes_post ON likes(post_id);
CREATE INDEX IF NOT EXISTS idx_likes_user ON likes(user_id);
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(user_id, post_id)
);
CREATE INDEX IF NOT EXISTS idx_bookmarks_user ON bookmarks(user_id);
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
actor_id INTEGER NOT NULL REFERENCES users(id),
type TEXT NOT NULL,
post_id INTEGER REFERENCES posts(id),
read INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_notifs_user ON notifications(user_id, read);
CREATE TABLE IF NOT EXISTS linked_repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider TEXT NOT NULL,
namespace TEXT NOT NULL,
project TEXT NOT NULL,
external_id TEXT,
description TEXT,
avatar_url TEXT,
pinned INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(user_id, provider, namespace, project)
);
CREATE INDEX IF NOT EXISTS idx_linked_repos_user ON linked_repos(user_id);
CREATE TABLE IF NOT EXISTS user_topics (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
concept TEXT NOT NULL,
is_active INTEGER DEFAULT 1,
UNIQUE(user_id, concept)
);
CREATE TABLE IF NOT EXISTS trending_topics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
concept TEXT NOT NULL,
location TEXT,
display_name TEXT NOT NULL,
current_score REAL DEFAULT 0.0,
last_updated_at TEXT DEFAULT (datetime('now')),
UNIQUE(concept, location)
);
CREATE INDEX IF NOT EXISTS idx_trending_score ON trending_topics(current_score DESC);
CREATE TABLE IF NOT EXISTS post_topics (
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
topic_id INTEGER REFERENCES trending_topics(id) ON DELETE CASCADE,
UNIQUE(post_id, topic_id)
);
CREATE TABLE IF NOT EXISTS post_location_stats (
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
country_code TEXT NOT NULL,
region_code TEXT,
view_count INTEGER DEFAULT 1
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_post_location_stats ON post_location_stats(post_id, country_code, COALESCE(region_code, ''));
-- ── npm registry tables ──────────────────────────────────────
CREATE TABLE IF NOT EXISTS packages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT,
readme TEXT,
readme_filename TEXT,
license TEXT,
homepage TEXT,
repository_type TEXT,
repository_url TEXT,
created_at TEXT DEFAULT (datetime('now')),
modified_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS package_versions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
version TEXT NOT NULL,
tarball_path TEXT NOT NULL,
tarball_shasum TEXT NOT NULL,
tarball_integrity TEXT,
tarball_size INTEGER NOT NULL,
manifest TEXT NOT NULL,
modelscript_meta TEXT,
published_by INTEGER REFERENCES users(id),
published_at TEXT DEFAULT (datetime('now')),
UNIQUE(package_id, version)
);
CREATE TABLE IF NOT EXISTS dist_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
tag TEXT NOT NULL,
version TEXT NOT NULL,
UNIQUE(package_id, tag)
);
CREATE TABLE IF NOT EXISTS artifacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version_id INTEGER NOT NULL REFERENCES package_versions(id) ON DELETE CASCADE,
type TEXT NOT NULL,
path TEXT NOT NULL,
metadata TEXT,
UNIQUE(version_id, path)
);
CREATE INDEX IF NOT EXISTS idx_packages_name ON packages(name);
CREATE INDEX IF NOT EXISTS idx_package_versions_pkg ON package_versions(package_id);
CREATE INDEX IF NOT EXISTS idx_dist_tags_pkg ON dist_tags(package_id);
CREATE INDEX IF NOT EXISTS idx_artifacts_version ON artifacts(version_id);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS cad_cache (
url TEXT PRIMARY KEY,
geometry_json TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
status TEXT NOT NULL,
type TEXT NOT NULL,
repository_id INTEGER REFERENCES linked_repos(id) ON DELETE CASCADE,
trigger_source TEXT,
metadata TEXT,
started_at TEXT DEFAULT (datetime('now')),
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS job_steps (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id INTEGER NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
name TEXT NOT NULL,
status TEXT NOT NULL,
started_at TEXT DEFAULT (datetime('now')),
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS script_templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
description TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'general',
icon TEXT NOT NULL DEFAULT 'terminal',
config TEXT NOT NULL DEFAULT '{}',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
`);
// Migrations
try {
this.#db.exec(`ALTER TABLE users ADD COLUMN notification_settings TEXT DEFAULT '{}'`);
} catch (e) {
// Column already exists
}
try {
this.#db.exec(`ALTER TABLE rss_feeds ADD COLUMN etag TEXT`);
this.#db.exec(`ALTER TABLE rss_feeds ADD COLUMN last_modified TEXT`);
this.#db.exec(`ALTER TABLE rss_feeds ADD COLUMN poll_interval_mins INTEGER DEFAULT 15`);
this.#db.exec(`ALTER TABLE rss_feeds ADD COLUMN last_polled_at TEXT`);
} catch (e) {
// Columns already exist
}
try {
this.#db.exec(`ALTER TABLE users ADD COLUMN rsa_private_key TEXT`);
this.#db.exec(`ALTER TABLE users ADD COLUMN rsa_public_key TEXT`);
this.#db.exec(`ALTER TABLE users ADD COLUMN actor_url TEXT`);
this.#db.exec(`ALTER TABLE users ADD COLUMN inbox_url TEXT`);
this.#db.exec(`ALTER TABLE users ADD COLUMN outbox_url TEXT`);
this.#db.exec(`ALTER TABLE users ADD COLUMN remote_domain TEXT`);
} catch (e) {
// Columns already exist
}
try {
const usersWithoutKeys = this.#db
.prepare(`SELECT id, username FROM users WHERE rsa_private_key IS NULL`)
.all() as Array<{ id: number; username: string }>;
const updateStmt = this.#db.prepare(
`UPDATE users SET rsa_private_key = ?, rsa_public_key = ?, actor_url = ?, inbox_url = ?, outbox_url = ? WHERE id = ?`,
);
const publicUrl = process.env.PUBLIC_URL || "https://hub.modelscript.org";
this.#db.transaction(() => {
for (const u of usersWithoutKeys) {
const keys = this.#generateRSAKeys();
const actorUrl = `${publicUrl}/users/${u.username}`;
updateStmt.run(keys.privateKey, keys.publicKey, actorUrl, `${actorUrl}/inbox`, `${actorUrl}/outbox`, u.id);
}
})();
} catch (e) {}
try {
this.#db.exec(`ALTER TABLE users ADD COLUMN account_type TEXT DEFAULT 'user'`);
} catch (e) {
// Column already exists
}
try {
this.#db.exec(`
UPDATE users
SET avatar_url = 'https://ui-avatars.com/api/?name=' || username || '&background=random&color=fff'
WHERE avatar_url IS NULL;
UPDATE users
SET banner_url = 'https://images.unsplash.com/photo-1557682250-33bd709cbe85?auto=format&fit=crop&w=1200&q=80'
WHERE banner_url IS NULL;
`);
} catch (e) {
// Ignore migration errors
}
try {
this.#db.exec(`ALTER TABLE posts ADD COLUMN view_count INTEGER DEFAULT 0`);
} catch (e) {
// Column already exists
}
try {
this.#db.exec(`ALTER TABLE posts ADD COLUMN ap_id TEXT UNIQUE`);
this.#db.exec(`ALTER TABLE posts ADD COLUMN url TEXT`);
} catch (e) {}
try {
this.#db.exec(`ALTER TABLE posts ADD COLUMN metadata TEXT`);
} catch (e) {}
try {
this.#db.exec(`ALTER TABLE posts ADD COLUMN reply_visibility TEXT DEFAULT 'everyone'`);
} catch (e) {}
try {
this.#db.exec(`ALTER TABLE oauth_accounts ADD COLUMN access_token TEXT`);
this.#db.exec(`ALTER TABLE oauth_accounts ADD COLUMN refresh_token TEXT`);
this.#db.exec(`ALTER TABLE oauth_accounts ADD COLUMN expires_at TEXT`);
} catch (e) {}
try {
this.#db.exec(`ALTER TABLE jobs ADD COLUMN metadata TEXT`);
} catch (e) {}
}
// ── User management ─────────────────────────────────────────────
getUserTopics(userId: number): { concept: string; is_active: boolean }[] {
return this.#db.prepare(`SELECT concept, is_active FROM user_topics WHERE user_id = ?`).all(userId) as any[];
}
updateUserTopic(userId: number, concept: string, isActive: boolean) {
this.#db
.prepare(
`INSERT INTO user_topics (user_id, concept, is_active) VALUES (?, ?, ?) ON CONFLICT(user_id, concept) DO UPDATE SET is_active = excluded.is_active`,
)
.run(userId, concept, isActive ? 1 : 0);
}
deriveUserTopics(userId: number): void {
// Derive topics from liked/bookmarked posts and insert as active (if not explicitly inactive)
this.#db
.prepare(
`
INSERT INTO user_topics (user_id, concept, is_active)
SELECT DISTINCT ?, t.concept, 1
FROM likes l
JOIN post_topics pt ON l.post_id = pt.post_id
JOIN trending_topics t ON pt.topic_id = t.id
WHERE l.user_id = ?
ON CONFLICT(user_id, concept) DO NOTHING
`,
)
.run(userId, userId);
}
// ── User management ─────────────────────────────────────────────
getOrCreateRemoteUser(actorUrl: string, profileData: any): { id: number } {
const existing = this.#db.prepare(`SELECT id FROM users WHERE actor_url = ?`).get(actorUrl) as
| { id: number }
| undefined;
if (existing) return existing;
// Use preferredUsername or fallback
const username = profileData.preferredUsername || actorUrl.split("/").pop();
const domain = new URL(actorUrl).hostname;
// Create a unique username for remote to avoid collision with local
const remoteUsername = `${username}@${domain}`;
const keys = this.#generateRSAKeys();
const result = this.#db
.prepare(
`INSERT INTO users (username, email, account_type, display_name, bio, avatar_url, rsa_private_key, rsa_public_key, actor_url, inbox_url, outbox_url, remote_domain) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
remoteUsername,
`remote-${crypto.randomUUID()}@${domain}`, // fake email for unique constraint
"remote",
profileData.name || username,
profileData.summary || "",
profileData.icon?.url || `https://ui-avatars.com/api/?name=${encodeURIComponent(remoteUsername)}`,
keys.privateKey,
keys.publicKey,
actorUrl,
profileData.inbox || `${actorUrl}/inbox`,
profileData.outbox || `${actorUrl}/outbox`,
domain,
);
return { id: Number(result.lastInsertRowid) };
}
#generateRSAKeys() {
return crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: { type: "spki", format: "pem" },
privateKeyEncoding: { type: "pkcs8", format: "pem" },
});
}
getInstanceKeys(): { publicKey: string; privateKey: string } {
const existing = this.#db.prepare(`SELECT value FROM settings WHERE key = 'instance_keys'`).get() as any;
if (existing) {
return JSON.parse(existing.value);
}
const keys = this.#generateRSAKeys();
this.#db.prepare(`INSERT INTO settings (key, value) VALUES (?, ?)`).run("instance_keys", JSON.stringify(keys));
return keys;
}
createUser(
username: string,
email: string,
passwordHash: string | null,
): { id: number; username: string; email: string } {
const avatarUrl = `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random&color=fff`;
const bannerUrl = `https://images.unsplash.com/photo-1557682250-33bd709cbe85?auto=format&fit=crop&w=1200&q=80`;
const keys = this.#generateRSAKeys();
const publicUrl = process.env.PUBLIC_URL || "https://hub.modelscript.org";
const actorUrl = `${publicUrl}/users/${username}`;
const inboxUrl = `${actorUrl}/inbox`;
const outboxUrl = `${actorUrl}/outbox`;
const result = this.#db
.prepare(
`INSERT INTO users (username, email, password_hash, avatar_url, banner_url, rsa_private_key, rsa_public_key, actor_url, inbox_url, outbox_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
username,
email,
passwordHash,
avatarUrl,
bannerUrl,
keys.privateKey,
keys.publicKey,
actorUrl,
inboxUrl,
outboxUrl,
);
return { id: result.lastInsertRowid as number, username, email };
}
createBot(
ownerId: number,
username: string,
displayName: string,
bio: string,
avatarUrl: string,
tokenHash: string,
): { id: number; username: string } {
const email = `${username}@bots.modelscript.org`; // dummy email for bots
const bannerUrl = `https://images.unsplash.com/photo-1557682250-33bd709cbe85?auto=format&fit=crop&w=1200&q=80`;
const keys = this.#generateRSAKeys();
const publicUrl = process.env.PUBLIC_URL || "https://hub.modelscript.org";
const actorUrl = `${publicUrl}/users/${username}`;
const inboxUrl = `${actorUrl}/inbox`;
const outboxUrl = `${actorUrl}/outbox`;
const result = this.#db
.prepare(
`INSERT INTO users (username, email, display_name, bio, avatar_url, banner_url, account_type, owner_id, bot_token_hash, rsa_private_key, rsa_public_key, actor_url, inbox_url, outbox_url) VALUES (?, ?, ?, ?, ?, ?, 'bot', ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
username,
email,
displayName,
bio,
avatarUrl ||
`https://ui-avatars.com/api/?name=${encodeURIComponent(displayName || username)}&background=random&color=fff`,
bannerUrl,
ownerId,
tokenHash,
keys.privateKey,
keys.publicKey,
actorUrl,
inboxUrl,
outboxUrl,
);
return { id: result.lastInsertRowid as number, username };
}
getUserBots(ownerId: number): Array<{
id: number;
username: string;
display_name: string;
avatar_url: string;
bio: string;
created_at: string;
}> {
return this.#db
.prepare(
`SELECT id, username, display_name, avatar_url, bio, created_at FROM users WHERE owner_id = ? AND account_type = 'bot' ORDER BY created_at DESC`,
)
.all(ownerId) as any;
}
deleteBot(ownerId: number, botId: number): void {
this.#db.prepare(`DELETE FROM users WHERE id = ? AND owner_id = ? AND account_type = 'bot'`).run(botId, ownerId);
}
getUserByBotTokenHash(
tokenHash: string,
): { id: number; username: string; email: string; account_type: string } | null {
const row = this.#db
.prepare(`SELECT id, username, email, account_type FROM users WHERE bot_token_hash = ? AND account_type = 'bot'`)
.get(tokenHash) as any;
return row || null;
}
createOAuthUser(
username: string,
email: string,
provider: string,
providerUserId: string,
): { id: number; username: string; email: string } {
const transaction = this.#db.transaction(() => {
const avatarUrl = `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random&color=fff`;
const bannerUrl = `https://images.unsplash.com/photo-1557682250-33bd709cbe85?auto=format&fit=crop&w=1200&q=80`;
const keys = this.#generateRSAKeys();
const publicUrl = process.env.PUBLIC_URL || "https://hub.modelscript.org";
const actorUrl = `${publicUrl}/users/${username}`;
const inboxUrl = `${actorUrl}/inbox`;
const outboxUrl = `${actorUrl}/outbox`;
const userResult = this.#db
.prepare(
`INSERT INTO users (username, email, avatar_url, banner_url, rsa_private_key, rsa_public_key, actor_url, inbox_url, outbox_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(username, email, avatarUrl, bannerUrl, keys.privateKey, keys.publicKey, actorUrl, inboxUrl, outboxUrl);
const userId = Number(userResult.lastInsertRowid);
this.#db
.prepare(`INSERT INTO oauth_accounts (user_id, provider, provider_user_id) VALUES (?, ?, ?)`)
.run(userId, provider, providerUserId);
return { id: userId, username, email };
});
return transaction();
}
getOAuthAccount(
provider: string,
providerUserId: string,
): { user_id: number; access_token?: string; refresh_token?: string; expires_at?: string } | undefined {
return this.#db
.prepare(
`SELECT user_id, access_token, refresh_token, expires_at FROM oauth_accounts WHERE provider = ? AND provider_user_id = ?`,
)
.get(provider, providerUserId) as
| { user_id: number; access_token?: string; refresh_token?: string; expires_at?: string }
| undefined;
}
getOAuthAccountByUserId(
userId: number,
provider: string,
): { provider_user_id: string; access_token?: string; refresh_token?: string; expires_at?: string } | undefined {
return this.#db
.prepare(
`SELECT provider_user_id, access_token, refresh_token, expires_at FROM oauth_accounts WHERE user_id = ? AND provider = ?`,
)
.get(userId, provider) as
| { provider_user_id: string; access_token?: string; refresh_token?: string; expires_at?: string }
| undefined;
}
getPublicOAuthAccounts(userId: number): { provider: string; provider_user_id: string }[] {
return this.#db.prepare(`SELECT provider, provider_user_id FROM oauth_accounts WHERE user_id = ?`).all(userId) as {
provider: string;
provider_user_id: string;
}[];
}
updateOAuthTokens(userId: number, provider: string, accessToken: string, refreshToken?: string, expiresAt?: string) {
this.#db
.prepare(
`UPDATE oauth_accounts SET access_token = ?, refresh_token = COALESCE(?, refresh_token), expires_at = COALESCE(?, expires_at) WHERE user_id = ? AND provider = ?`,
)
.run(accessToken, refreshToken ?? null, expiresAt ?? null, userId, provider);
}
getUserByEmail(email: string):
| {
id: number;
username: string;
email: string;
password_hash: string;
avatar_url: string;
display_name: string;
bio: string;
}
| undefined {
return this.#db
.prepare(`SELECT id, username, email, password_hash, avatar_url, display_name, bio FROM users WHERE email = ?`)
.get(email) as any;
}
getUserByUsername(username: string): { id: number; username: string; email: string } | undefined {
return this.#db.prepare(`SELECT id, username, email FROM users WHERE username = ?`).get(username) as
| { id: number; username: string; email: string }
| undefined;
}
getUserById(
id: number,
):
| { id: number; username: string; email: string; avatar_url: string; display_name: string; bio: string }
| undefined {
return this.#db
.prepare(`SELECT id, username, email, avatar_url, display_name, bio FROM users WHERE id = ?`)
.get(id) as any;
}
getFullProfileByUsername(username: string): any {
return this.#db
.prepare(
`
SELECT u.id, u.username, u.display_name, u.bio, u.avatar_url, u.banner_url, u.location, u.website, u.created_at, u.account_type, u.owner_id,
(SELECT username FROM users WHERE id = u.owner_id) as owner_username,
(SELECT COUNT(*) FROM follows WHERE following_id = u.id) as follower_count,
(SELECT COUNT(*) FROM follows WHERE follower_id = u.id) as following_count,
(SELECT COUNT(*) FROM posts WHERE author_id = u.id) as post_count
FROM users u WHERE u.username = ?
`,
)
.get(username);
}
updateProfile(
userId: number,
profile: {
display_name?: string;
bio?: string;
location?: string;
website?: string;
avatar_url?: string;
banner_url?: string;
},
) {
const fields = Object.entries(profile).filter(([_, v]) => v !== undefined);
if (fields.length === 0) return;
const setClause = fields.map(([k, _]) => `${k} = ?`).join(", ");
const values = fields.map(([_, v]) => v);
this.#db.prepare(`UPDATE users SET ${setClause} WHERE id = ?`).run(...values, userId);
}
updateAccount(userId: number, username: string, email: string) {
this.#db.prepare(`UPDATE users SET username = ?, email = ? WHERE id = ?`).run(username, email, userId);
}
updatePassword(userId: number, passwordHash: string) {
this.#db.prepare(`UPDATE users SET password_hash = ? WHERE id = ?`).run(passwordHash, userId);
}
getPasswordHash(userId: number): string | undefined {
const res = this.#db.prepare(`SELECT password_hash FROM users WHERE id = ?`).get(userId) as
| { password_hash: string }
| undefined;
return res?.password_hash;
}
getNotificationSettings(userId: number): string | undefined {
const res = this.#db.prepare(`SELECT notification_settings FROM users WHERE id = ?`).get(userId) as
| { notification_settings: string }
| undefined;
return res?.notification_settings;
}
updateNotificationSettings(userId: number, settings: string) {
this.#db.prepare(`UPDATE users SET notification_settings = ? WHERE id = ?`).run(settings, userId);
}
followUser(followerId: number, followingId: number) {
try {
this.#db.prepare(`INSERT INTO follows (follower_id, following_id) VALUES (?, ?)`).run(followerId, followingId);
} catch (err) {
// ignore unique constraint
}
}
unfollowUser(followerId: number, followingId: number) {
this.#db.prepare(`DELETE FROM follows WHERE follower_id = ? AND following_id = ?`).run(followerId, followingId);
}
isFollowing(followerId: number, followingId: number): boolean {
const res = this.#db
.prepare(`SELECT 1 FROM follows WHERE follower_id = ? AND following_id = ?`)
.get(followerId, followingId);
return !!res;
}
getUserFollowers(userId: number, currentUserId?: number): any[] {
const query = currentUserId
? `
SELECT u.id, u.username, u.display_name, u.avatar_url, u.bio, u.account_type,
EXISTS(SELECT 1 FROM follows WHERE follower_id = ? AND following_id = u.id) as is_following
FROM follows f
JOIN users u ON f.follower_id = u.id
WHERE f.following_id = ?
ORDER BY f.created_at DESC
`
: `
SELECT u.id, u.username, u.display_name, u.avatar_url, u.bio, u.account_type,
0 as is_following
FROM follows f
JOIN users u ON f.follower_id = u.id
WHERE f.following_id = ?
ORDER BY f.created_at DESC
`;
return currentUserId
? (this.#db.prepare(query).all(currentUserId, userId) as any[])
: (this.#db.prepare(query).all(userId) as any[]);
}
getUserFollowing(userId: number, currentUserId?: number): any[] {