Something went wrong. Try again.
A social knowledge tool for research trails, built on ATProto semble.so
research-tool social-network tools-for-thought atproto
Something went wrong. Try again.
TypeScript
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228import { ICardQueryRepository, CardQueryOptions, UrlCardQueryResultDTO, CollectionCardQueryResultDTO, UrlCardViewDTO, UrlCardView, PaginatedQueryResult, CardSortField, SortOrder, LibraryForUrlDTO, NoteCardForUrlRawDTO, UrlLibraryInfo, UrlStats, UrlConnectionCounts, UserActivityStats, SearchUrlsOptions, UrlSearchResultDTO,} from '../../domain/ICardQueryRepository';import { CardTypeEnum } from '../../domain/value-objects/CardType';import { InMemoryCardRepository } from './InMemoryCardRepository';import { InMemoryCollectionRepository } from './InMemoryCollectionRepository';import { IConnectionRepository } from '../../domain/IConnectionRepository';import { Card } from '../../domain/Card';import { CollectionId } from '../../domain/value-objects/CollectionId';import { CuratorId } from '../../domain/value-objects/CuratorId';import { UrlOrCardId } from '../../domain/value-objects/UrlOrCardId';import { URL } from '../../domain/value-objects/URL';
export class InMemoryCardQueryRepository implements ICardQueryRepository { constructor( private cardRepository: InMemoryCardRepository, private collectionRepository: InMemoryCollectionRepository, private connectionRepository?: IConnectionRepository, ) {}
async getUrlCardsOfUser( userId: string, options: CardQueryOptions, callingUserId?: string, ): Promise<PaginatedQueryResult<UrlCardQueryResultDTO>> { try { // Get all cards and filter by user's library membership const allCards = this.cardRepository.getAllCards(); let userCards = allCards.filter( (card) => card.isUrlCard && card.isInLibrary(CuratorId.create(userId).unwrap()), );
// Filter by urlType if specified if (options.urlType) { userCards = userCards.filter( (card) => card.content.urlContent?.metadata?.type === options.urlType, ); }
// Filter by tokenized searchText across title, description, and URL if (options.searchText && options.searchText.trim().length > 0) { const searchWords = options.searchText .trim() .toLowerCase() .split(/\s+/); userCards = userCards.filter((card) => { const title = card.content.urlContent?.metadata?.title?.toLowerCase() || ''; const description = card.content.urlContent?.metadata?.description?.toLowerCase() || ''; const url = card.content.urlContent?.url.value.toLowerCase() || ''; return searchWords.every( (word) => title.includes(word) || description.includes(word) || url.includes(word), ); }); }
// Filter out cards in collections if uncollected flag is set if (options.uncollected) { const allCollections = this.collectionRepository.getAllCollections(); const collectedCardIds = new Set<string>();
// Find all cards that the user added to any collection for (const collection of allCollections) { for (const cardLink of collection.cardLinks) { if (cardLink.addedBy.value === userId) { collectedCardIds.add(cardLink.cardId.getStringValue()); } } }
// Filter out cards that are in collections userCards = userCards.filter( (card) => !collectedCardIds.has(card.cardId.getStringValue()), ); }
const userCardResults = await Promise.all( userCards.map((card) => this.cardToUrlCardQueryResult(card, callingUserId), ), );
// Sort cards const sortedCards = this.sortCards( userCardResults, options.sortBy, options.sortOrder, );
// Apply pagination const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedCards = sortedCards.slice(startIndex, endIndex);
return { items: paginatedCards, totalCount: userCardResults.length, hasMore: endIndex < userCardResults.length, }; } catch (error) { throw new Error( `Failed to query URL cards: ${error instanceof Error ? error.message : String(error)}`, ); } }
private sortCards( cards: UrlCardQueryResultDTO[], sortBy: CardSortField, sortOrder: SortOrder, ): UrlCardQueryResultDTO[] { const sorted = [...cards].sort((a, b) => { let comparison = 0;
switch (sortBy) { case CardSortField.CREATED_AT: comparison = a.createdAt.getTime() - b.createdAt.getTime(); break; case CardSortField.UPDATED_AT: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; case CardSortField.LIBRARY_COUNT: comparison = a.libraryCount - b.libraryCount; break; default: comparison = 0; }
return sortOrder === SortOrder.DESC ? -comparison : comparison; });
return sorted; }
private async cardToUrlCardQueryResult( card: Card, callingUserId?: string, ): Promise<UrlCardQueryResultDTO> { if (!card.isUrlCard || !card.content.urlContent) { throw new Error('Card is not a URL card'); }
// Find collections this card belongs to by querying the collection repository const allCollections = this.collectionRepository.getAllCollections(); const collections: { id: string; name: string; authorId: string; accessType: string; }[] = [];
for (const collection of allCollections) { if ( collection.cardIds.some( (cardId) => cardId.getStringValue() === card.cardId.getStringValue(), ) ) { collections.push({ id: collection.collectionId.getStringValue(), name: collection.name.value, authorId: collection.authorId.value, accessType: collection.accessType, }); } }
// Find note card by the same author with matching parent card ID const allCards = this.cardRepository.getAllCards(); const noteCard = allCards.find( (c) => c.type.value === 'NOTE' && c.parentCardId?.equals(card.cardId) && c.curatorId.value === card.curatorId.value, // Only notes by the same author );
const note = noteCard ? { id: noteCard.cardId.getStringValue(), text: noteCard.content.noteContent?.text || '', } : undefined;
const url = card.content.urlContent.url.value;
// Compute urlInLibrary if callingUserId is provided const urlInLibrary = callingUserId ? this.isUrlInUserLibrary(url, callingUserId) : undefined;
// Get connection count and connection status const urlConnectionCount = await this.getUrlConnectionCount(url); const urlIsConnected = callingUserId ? await this.isUrlConnectedByUser(url, callingUserId) : undefined;
return { id: card.cardId.getStringValue(), type: CardTypeEnum.URL, uri: card.publishedRecordId?.uri, url, cardContent: { url, title: card.content.urlContent.metadata?.title, description: card.content.urlContent.metadata?.description, author: card.content.urlContent.metadata?.author, imageUrl: card.content.urlContent.metadata?.imageUrl, }, libraryCount: this.getLibraryCountForCard(card.cardId.getStringValue()), urlLibraryCount: this.getUrlLibraryCount(url), urlInLibrary, urlConnectionCount, urlIsConnected, createdAt: card.createdAt, updatedAt: card.updatedAt, authorId: card.curatorId.value, collections, note, }; }
private getLibraryCountForCard(cardId: string): number { const card = this.cardRepository.getStoredCard({ getStringValue: () => cardId, } as any); return card ? card.libraryMembershipCount : 0; }
private getUrlLibraryCount(url: string): number { // Get all URL cards with this URL and count unique library memberships const allCards = this.cardRepository.getAllCards(); const urlCards = allCards.filter( (card) => card.isUrlCard && card.url?.value === url, );
// Get all unique user IDs who have any card with this URL const uniqueUserIds = new Set<string>(); for (const card of urlCards) { for (const membership of card.libraryMemberships) { uniqueUserIds.add(membership.curatorId.value); } }
return uniqueUserIds.size; }
private isUrlInUserLibrary(url: string, userId: string): boolean { // Check if the user has any URL card with this URL (by checking authorId) const allCards = this.cardRepository.getAllCards(); return allCards.some( (card) => card.isUrlCard && card.url?.value === url && card.curatorId.value === userId, ); }
// URL↔URL connections only, matching the Drizzle implementation private async getUrlConnectionCounts( url: string, ): Promise<UrlConnectionCounts> { const counts: UrlConnectionCounts = { forwardTotal: 0, backwardTotal: 0, forwardByType: new Map(), backwardByType: new Map(), }; if (!this.connectionRepository) { return counts; }
const urlResult = URL.create(url); if (urlResult.isErr()) { return counts; } const urlOrCardIdResult = UrlOrCardId.createFromUrl(urlResult.value); if (urlOrCardIdResult.isErr()) { return counts; } const urlOrCardId = urlOrCardIdResult.value;
const [sourceResult, targetResult] = await Promise.all([ this.connectionRepository.findBySource(urlOrCardId), this.connectionRepository.findByTarget(urlOrCardId), ]); const forward = (sourceResult.isOk() ? sourceResult.value : []).filter( (conn) => conn.target.isUrl, ); const backward = (targetResult.isOk() ? targetResult.value : []).filter( (conn) => conn.source.isUrl, );
counts.forwardTotal = forward.length; counts.backwardTotal = backward.length; for (const conn of forward) { if (conn.type) { const type = conn.type.value; counts.forwardByType.set( type, (counts.forwardByType.get(type) ?? 0) + 1, ); } } for (const conn of backward) { if (conn.type) { const type = conn.type.value; counts.backwardByType.set( type, (counts.backwardByType.get(type) ?? 0) + 1, ); } } return counts; }
private async getUrlConnectionCount(url: string): Promise<number> { const counts = await this.getUrlConnectionCounts(url); return counts.forwardTotal + counts.backwardTotal; }
private async isUrlConnectedByUser( url: string, userId: string, ): Promise<boolean> { if (!this.connectionRepository) { return false; }
try { const curatorId = CuratorId.create(userId); if (curatorId.isErr()) { return false; }
// Get all connections by this curator const connectionsResult = await this.connectionRepository.findByCuratorId( curatorId.value, ); if (connectionsResult.isErr()) { return false; }
const connections = connectionsResult.value;
// Check if any connection involves this URL (as source or target) // URL↔URL connections only, matching the Drizzle implementation return connections.some( (conn) => conn.source.isUrl && conn.target.isUrl && (conn.source.url?.value === url || conn.target.url?.value === url), ); } catch (error) { return false; } }
async getCardsInCollection( collectionId: string, options: CardQueryOptions, callingUserId?: string, ): Promise<PaginatedQueryResult<CollectionCardQueryResultDTO>> { try { // Get the collection from the repository const collectionIdObj = CollectionId.createFromString(collectionId); if (collectionIdObj.isErr()) { throw new Error(`Invalid collection ID: ${collectionId}`); }
const collectionResult = await this.collectionRepository.findById( collectionIdObj.value, ); if (collectionResult.isErr()) { throw collectionResult.error; }
const collection = collectionResult.value; if (!collection) { return { items: [], totalCount: 0, hasMore: false, }; }
// Get cards that are in this collection const allCards = this.cardRepository.getAllCards(); const collectionCardIds = new Set( collection.cardIds.map((id) => id.getStringValue()), ); let collectionCards = allCards.filter( (card) => collectionCardIds.has(card.cardId.getStringValue()) && card.isUrlCard, );
// Filter by urlType if specified if (options.urlType) { collectionCards = collectionCards.filter( (card) => card.content.urlContent?.metadata?.type === options.urlType, ); }
const collectionCardResults = await Promise.all( collectionCards.map(async (card) => this.toCollectionCardQueryResult( await this.cardToUrlCardQueryResult(card, callingUserId), ), ), );
// Sort cards const sortedCards = this.sortCollectionCards( collectionCardResults, options.sortBy, options.sortOrder, );
// Apply pagination const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedCards = sortedCards.slice(startIndex, endIndex);
return { items: paginatedCards, totalCount: collectionCardResults.length, hasMore: endIndex < collectionCardResults.length, }; } catch (error) { throw new Error( `Failed to query collection cards: ${error instanceof Error ? error.message : String(error)}`, ); } }
private sortCollectionCards( cards: CollectionCardQueryResultDTO[], sortBy: CardSortField, sortOrder: SortOrder, ): CollectionCardQueryResultDTO[] { const sorted = [...cards].sort((a, b) => { let comparison = 0;
switch (sortBy) { case CardSortField.CREATED_AT: comparison = a.createdAt.getTime() - b.createdAt.getTime(); break; case CardSortField.UPDATED_AT: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; case CardSortField.LIBRARY_COUNT: // Sort by URL library count instead of card library count comparison = a.urlLibraryCount - b.urlLibraryCount; break; default: comparison = 0; }
return sortOrder === SortOrder.DESC ? -comparison : comparison; });
return sorted; }
private toCollectionCardQueryResult( card: UrlCardQueryResultDTO, ): CollectionCardQueryResultDTO { return { id: card.id, type: CardTypeEnum.URL, url: card.url, cardContent: card.cardContent, libraryCount: card.libraryCount, urlLibraryCount: card.urlLibraryCount, urlInLibrary: card.urlInLibrary, createdAt: card.createdAt, updatedAt: card.updatedAt, authorId: card.authorId, note: card.note, }; }
async getUrlCardView( cardId: string, callingUserId?: string, ): Promise<UrlCardViewDTO | null> { const allCards = this.cardRepository.getAllCards(); const card = allCards.find((c) => c.cardId.getStringValue() === cardId); if (!card || !card.isUrlCard) { return null; }
const urlCardResult = await this.cardToUrlCardQueryResult( card, callingUserId, );
// Get library memberships from the card itself const libraries = card.libraryMemberships.map((membership) => ({ userId: membership.curatorId.value, }));
// Find note card by the same author with matching parent card ID const noteCard = allCards.find( (c) => c.type.value === 'NOTE' && c.parentCardId?.equals(card.cardId) && c.curatorId.value === card.curatorId.value, // Only notes by the same author );
const note = noteCard ? { id: noteCard.cardId.getStringValue(), text: noteCard.content.noteContent?.text || '', } : undefined;
return { ...urlCardResult, libraries, note, }; }
async getUrlCardBasic( cardId: string, callingUserId?: string, ): Promise<UrlCardView | null> { const allCards = this.cardRepository.getAllCards(); const card = allCards.find((c) => c.cardId.getStringValue() === cardId); if (!card || !card.isUrlCard) { return null; }
// Find note card by the same author with matching parent card ID const noteCard = allCards.find( (c) => c.type.value === 'NOTE' && c.parentCardId?.equals(card.cardId) && c.curatorId.value === card.curatorId.value, // Only notes by the same author );
const note = noteCard ? { id: noteCard.cardId.getStringValue(), text: noteCard.content.noteContent?.text || '', } : undefined;
const url = card.content.urlContent!.url.value;
// Compute urlInLibrary if callingUserId is provided const urlInLibrary = callingUserId ? this.isUrlInUserLibrary(url, callingUserId) : undefined;
// Get connection count and connection status const urlConnectionCount = await this.getUrlConnectionCount(url); const urlIsConnected = callingUserId ? await this.isUrlConnectedByUser(url, callingUserId) : undefined;
return { id: card.cardId.getStringValue(), type: CardTypeEnum.URL, url, cardContent: { url, title: card.content.urlContent!.metadata?.title, description: card.content.urlContent!.metadata?.description, author: card.content.urlContent!.metadata?.author, imageUrl: card.content.urlContent!.metadata?.imageUrl, }, libraryCount: this.getLibraryCountForCard(card.cardId.getStringValue()), urlLibraryCount: this.getUrlLibraryCount(url), urlInLibrary, urlConnectionCount, urlIsConnected, createdAt: card.createdAt, updatedAt: card.updatedAt, authorId: card.curatorId.value, note, }; }
async getLibrariesForCard(cardId: string): Promise<string[]> { const allCards = this.cardRepository.getAllCards(); const card = allCards.find((c) => c.cardId.getStringValue() === cardId);
if (!card) { return []; }
return card.libraryMemberships.map( (membership) => membership.curatorId.value, ); }
async getLibrariesForUrl( url: string, options: CardQueryOptions, ): Promise<PaginatedQueryResult<LibraryForUrlDTO>> { try { // Get all cards and filter by URL const allCards = this.cardRepository.getAllCards(); const urlCards = allCards.filter( (card) => card.isUrlCard && card.url?.value === url, );
// Create library entries for each card const libraries: LibraryForUrlDTO[] = []; for (const card of urlCards) { // Skip cards without urlContent (should not happen since we filtered for URL cards) if (!card.content.urlContent) { continue; }
for (const membership of card.libraryMemberships) { const noteCard = allCards.find( (c) => c.isNoteCard && c.parentCardId?.equals(card.cardId), );
const urlLibraryCount = this.getUrlLibraryCount(url);
libraries.push({ userId: membership.curatorId.value, card: { id: card.cardId.getStringValue(), url: card.content.urlContent.url.value, cardContent: { url: card.content.urlContent.url.value, title: card.content.urlContent.metadata?.title, description: card.content.urlContent.metadata?.description, author: card.content.urlContent.metadata?.author, imageUrl: card.content.urlContent.metadata?.imageUrl, }, libraryCount: this.getLibraryCountForCard( card.cardId.getStringValue(), ), urlLibraryCount, urlInLibrary: true, createdAt: card.createdAt, updatedAt: card.updatedAt, note: noteCard ? { id: noteCard.cardId.getStringValue(), text: noteCard.content.noteContent?.text || '', } : undefined, }, }); } }
// Sort libraries (by userId for consistency) const sortedLibraries = this.sortLibraries( libraries, options.sortBy, options.sortOrder, );
// Apply pagination const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedLibraries = sortedLibraries.slice(startIndex, endIndex);
return { items: paginatedLibraries, totalCount: libraries.length, hasMore: endIndex < libraries.length, }; } catch (error) { throw new Error( `Failed to query libraries for URL: ${error instanceof Error ? error.message : String(error)}`, ); } }
private sortLibraries( libraries: LibraryForUrlDTO[], sortBy: CardSortField, sortOrder: SortOrder, ): LibraryForUrlDTO[] { const sorted = [...libraries].sort((a, b) => { let comparison = 0;
switch (sortBy) { case CardSortField.CREATED_AT: case CardSortField.UPDATED_AT: case CardSortField.LIBRARY_COUNT: // For libraries, we'll sort by userId as a fallback comparison = a.userId.localeCompare(b.userId); break; default: comparison = a.userId.localeCompare(b.userId); }
return sortOrder === SortOrder.DESC ? -comparison : comparison; });
return sorted; }
async getNoteCardsForUrl( url: string, options: CardQueryOptions, ): Promise<PaginatedQueryResult<NoteCardForUrlRawDTO>> { try { // Get all note cards with the specified URL const allCards = this.cardRepository.getAllCards(); const noteCards = allCards .filter((card) => card.isNoteCard && card.url?.value === url) .map((card) => ({ id: card.cardId.getStringValue(), note: card.content.noteContent?.text || '', authorId: card.curatorId.value, createdAt: card.createdAt, updatedAt: card.updatedAt, }));
// Sort note cards const sortedNotes = this.sortNoteCards( noteCards, options.sortBy, options.sortOrder, );
// Apply pagination const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedNotes = sortedNotes.slice(startIndex, endIndex);
return { items: paginatedNotes, totalCount: noteCards.length, hasMore: endIndex < noteCards.length, }; } catch (error) { throw new Error( `Failed to query note cards for URL: ${error instanceof Error ? error.message : String(error)}`, ); } }
private sortNoteCards( notes: NoteCardForUrlRawDTO[], sortBy: CardSortField, sortOrder: SortOrder, ): NoteCardForUrlRawDTO[] { const sorted = [...notes].sort((a, b) => { let comparison = 0;
switch (sortBy) { case CardSortField.CREATED_AT: comparison = a.createdAt.getTime() - b.createdAt.getTime(); break; case CardSortField.UPDATED_AT: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; case CardSortField.LIBRARY_COUNT: // For note cards, sort by authorId as fallback comparison = a.authorId.localeCompare(b.authorId); break; default: comparison = 0; }
return sortOrder === SortOrder.DESC ? -comparison : comparison; });
return sorted; }
async getBatchUrlCardViews( cardIds: string[], callingUserId?: string, ): Promise<Map<string, UrlCardView>> { const resultMap = new Map<string, UrlCardView>();
for (const cardId of cardIds) { const cardView = await this.getUrlCardBasic(cardId, callingUserId); if (cardView) { resultMap.set(cardId, cardView); } }
return resultMap; }
async getBatchUrlLibraryInfo( urls: string[], callingUserId?: string, ): Promise<Map<string, UrlLibraryInfo>> { const resultMap = new Map<string, UrlLibraryInfo>();
for (const url of urls) { // Get URL library count using existing helper const urlLibraryCount = this.getUrlLibraryCount(url);
// Check if URL is in calling user's library const urlInLibrary = callingUserId ? this.isUrlInUserLibrary(url, callingUserId) : undefined;
// Get connection count and connection status const urlConnectionCount = await this.getUrlConnectionCount(url); const urlIsConnected = callingUserId ? await this.isUrlConnectedByUser(url, callingUserId) : undefined;
// Get metadata from any card with this URL const allCards = this.cardRepository.getAllCards(); const urlCard = allCards.find( (card) => card.isUrlCard && card.url?.value === url, );
const metadata = urlCard?.content.urlContent ? { url: urlCard.content.urlContent.url.value, title: urlCard.content.urlContent.metadata?.title, description: urlCard.content.urlContent.metadata?.description, author: urlCard.content.urlContent.metadata?.author, publishedDate: urlCard.content.urlContent.metadata?.publishedDate, siteName: urlCard.content.urlContent.metadata?.siteName, imageUrl: urlCard.content.urlContent.metadata?.imageUrl, type: urlCard.content.urlContent.metadata?.type, retrievedAt: urlCard.content.urlContent.metadata?.retrievedAt, doi: urlCard.content.urlContent.metadata?.doi, isbn: urlCard.content.urlContent.metadata?.isbn, } : { url, };
resultMap.set(url, { urlLibraryCount, urlInLibrary, urlConnectionCount, urlIsConnected, metadata, }); }
return resultMap; }
async getBatchUrlStats( urls: string[], callingUserId?: string, ): Promise<Map<string, UrlStats>> { const resultMap = new Map<string, UrlStats>(); const allCards = this.cardRepository.getAllCards(); const allCollections = this.collectionRepository.getAllCollections();
for (const url of new Set(urls)) { const urlCardIds = new Set( allCards .filter((card) => card.isUrlCard && card.url?.value === url) .map((card) => card.cardId.getStringValue()), );
const noteCount = allCards.filter( (card) => card.isNoteCard && card.url?.value === url, ).length;
const collectionCount = allCollections.filter((collection) => collection.cardLinks.some((link) => urlCardIds.has(link.cardId.getStringValue()), ), ).length;
resultMap.set(url, { libraryCount: this.getUrlLibraryCount(url), noteCount, collectionCount, connections: await this.getUrlConnectionCounts(url), urlInLibrary: callingUserId ? this.isUrlInUserLibrary(url, callingUserId) : undefined, urlIsConnected: callingUserId ? await this.isUrlConnectedByUser(url, callingUserId) : undefined, }); }
return resultMap; }
async getUsersForUrls(urls: string[]): Promise<string[]> { const userIds = new Set<string>(); const urlSet = new Set(urls); const allCards = this.cardRepository.getAllCards();
allCards.forEach((card) => { if (card.isUrlCard && card.url && urlSet.has(card.url.value)) { userIds.add(card.curatorId.value); } });
if (this.connectionRepository) { for (const url of urls) { const urlResult = URL.create(url); if (urlResult.isErr()) continue; const urlOrCardIdResult = UrlOrCardId.createFromUrl(urlResult.value); if (urlOrCardIdResult.isErr()) continue;
const [sourceResult, targetResult] = await Promise.all([ this.connectionRepository.findBySource(urlOrCardIdResult.value), this.connectionRepository.findByTarget(urlOrCardIdResult.value), ]); if (sourceResult.isOk()) { sourceResult.value.forEach((conn) => userIds.add(conn.curatorId.value), ); } if (targetResult.isOk()) { targetResult.value.forEach((conn) => userIds.add(conn.curatorId.value), ); } } }
return Array.from(userIds); }
async getUrlsSavedByUser( userId: string, urls: string[], ): Promise<Set<string>> { const urlSet = new Set(urls); const savedUrls = new Set<string>(); const allCards = this.cardRepository.getAllCards();
allCards.forEach((card) => { if ( card.isUrlCard && card.url && card.curatorId.value === userId && urlSet.has(card.url.value) ) { savedUrls.add(card.url.value); } });
return savedUrls; }
async getBatchUserActivityStats( userIds: string[], ): Promise<Map<string, UserActivityStats>> { const resultMap = new Map<string, UserActivityStats>(); const allCards = this.cardRepository.getAllCards(); const allCollections = this.collectionRepository.getAllCollections();
for (const userId of userIds) { const stats: UserActivityStats = { cardCount: 0, collectionCount: 0, connectionCount: 0, lastActivityAt: null, };
const updateLatest = (date: Date) => { if (!stats.lastActivityAt || date > stats.lastActivityAt) { stats.lastActivityAt = date; } };
allCards.forEach((card) => { if (card.curatorId.value === userId) { stats.cardCount++; updateLatest(card.createdAt); } });
allCollections.forEach((collection) => { if (collection.authorId.value === userId) { stats.collectionCount++; } collection.cardLinks.forEach((link) => { if (link.addedBy.value === userId) { updateLatest(link.addedAt); } }); });
if (this.connectionRepository) { const curatorIdResult = CuratorId.create(userId); if (curatorIdResult.isOk()) { const connectionsResult = await this.connectionRepository.findByCuratorId( curatorIdResult.value, ); if (connectionsResult.isOk()) { stats.connectionCount = connectionsResult.value.length; connectionsResult.value.forEach((conn) => updateLatest(conn.createdAt), ); } } }
resultMap.set(userId, stats); }
return resultMap; }
async getBatchLatestCardCreatedAt( userIds: string[], ): Promise<Map<string, Date>> { const resultMap = new Map<string, Date>(); const userIdSet = new Set(userIds);
this.cardRepository.getAllCards().forEach((card) => { const userId = card.curatorId.value; if (!userIdSet.has(userId)) return; const existing = resultMap.get(userId); if (!existing || card.createdAt > existing) { resultMap.set(userId, card.createdAt); } });
return resultMap; }
async searchUrls( options: SearchUrlsOptions, ): Promise<PaginatedQueryResult<UrlSearchResultDTO>> { try { const { searchQuery, page, limit, sortBy, sortOrder, urlType } = options;
// Get all URL cards const allCards = this.cardRepository.getAllCards(); let urlCards = allCards.filter((card) => card.isUrlCard);
// Filter by urlType if specified if (urlType) { urlCards = urlCards.filter( (card) => card.content.urlContent?.metadata?.type === urlType, ); }
// Tokenize search query into words const searchWords = searchQuery.trim().toLowerCase().split(/\s+/);
// Filter cards by tokenized substring search const matchingCards = urlCards.filter((card) => { const title = card.content.urlContent?.metadata?.title?.toLowerCase() || ''; const description = card.content.urlContent?.metadata?.description?.toLowerCase() || ''; const url = card.content.urlContent?.url.value.toLowerCase() || '';
// All words must match somewhere in title, description, or url return searchWords.every((word) => { return ( title.includes(word) || description.includes(word) || url.includes(word) ); }); });
// Deduplicate by URL - keep most recent card per URL const urlMap = new Map< string, { card: Card; contentData: any; updatedAt: Date } >();
matchingCards.forEach((card) => { const url = card.content.urlContent?.url.value; if (!url) return;
const existing = urlMap.get(url); if ( !existing || card.updatedAt.getTime() > existing.updatedAt.getTime() ) { // Build contentData from card const contentData = { url: card.content.urlContent?.url.value, metadata: card.content.urlContent?.metadata ? { url: card.content.urlContent.metadata.url, title: card.content.urlContent.metadata.title, description: card.content.urlContent.metadata.description, author: card.content.urlContent.metadata.author, publishedDate: card.content.urlContent.metadata.publishedDate, siteName: card.content.urlContent.metadata.siteName, imageUrl: card.content.urlContent.metadata.imageUrl, type: card.content.urlContent.metadata.type, retrievedAt: card.content.urlContent.metadata.retrievedAt, doi: card.content.urlContent.metadata.doi, isbn: card.content.urlContent.metadata.isbn, } : undefined, };
urlMap.set(url, { card, contentData, updatedAt: card.updatedAt, }); } });
// Convert to array const uniqueUrls = Array.from(urlMap.entries()).map(([url, data]) => ({ url, contentData: data.contentData, updatedAt: data.updatedAt, card: data.card, }));
// For LIBRARY_COUNT sorting, calculate library counts if (sortBy === CardSortField.LIBRARY_COUNT) { const itemsWithCounts = uniqueUrls.map((item) => { // Use the existing helper method to get library count const libraryCount = this.getUrlLibraryCount(item.url);
return { ...item, libraryCount, }; });
// Sort by library count itemsWithCounts.sort((a, b) => { const comparison = a.libraryCount - b.libraryCount; return sortOrder === SortOrder.ASC ? comparison : -comparison; });
// Paginate const startIndex = (page - 1) * limit; const endIndex = startIndex + limit; const paginatedItems = itemsWithCounts.slice(startIndex, endIndex);
return { items: paginatedItems.map((item) => ({ url: item.url, contentData: item.contentData, updatedAt: item.updatedAt, })), totalCount: itemsWithCounts.length, hasMore: endIndex < itemsWithCounts.length, }; }
// For other sort fields (CREATED_AT, UPDATED_AT) uniqueUrls.sort((a, b) => { let comparison = 0;
switch (sortBy) { case CardSortField.CREATED_AT: comparison = a.card.createdAt.getTime() - b.card.createdAt.getTime(); break; case CardSortField.UPDATED_AT: default: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; }
return sortOrder === SortOrder.ASC ? comparison : -comparison; });
// Paginate const startIndex = (page - 1) * limit; const endIndex = startIndex + limit; const paginatedUrls = uniqueUrls.slice(startIndex, endIndex);
return { items: paginatedUrls.map((item) => ({ url: item.url, contentData: item.contentData, updatedAt: item.updatedAt, })), totalCount: uniqueUrls.length, hasMore: endIndex < uniqueUrls.length, }; } catch (error) { throw new Error( `Failed to search URLs: ${error instanceof Error ? error.message : String(error)}`, ); } }
async getProfileCardStats(authorId: string): Promise<{ urlCardCount: number; }> { const allCards = this.cardRepository.getAllCards();
// Count URL cards authored by this user const urlCardCount = allCards.filter( (c) => c.type.value === 'URL' && c.curatorId.value === authorId, ).length;
return { urlCardCount, }; }
clear(): void { // No separate state to clear }}