Browse Source

Cleaned up all of the parameter calls for ndk

master
silberengel 7 months ago
parent
commit
c86cc266e9
  1. 8
      src/lib/components/CommentBox.svelte
  2. 2
      src/lib/components/CommentViewer.svelte
  3. 2
      src/lib/components/EventDetails.svelte
  4. 1
      src/lib/components/EventInput.svelte
  5. 6
      src/lib/components/EventSearch.svelte
  6. 2
      src/lib/components/Navigation.svelte
  7. 6
      src/lib/components/Notifications.svelte
  8. 2
      src/lib/components/embedded_events/EmbeddedEvent.svelte
  9. 2
      src/lib/components/embedded_events/EmbeddedSnippets.svelte
  10. 6
      src/lib/components/util/ContainingIndexes.svelte
  11. 8
      src/lib/components/util/Profile.svelte
  12. 2
      src/lib/snippets/UserSnippets.svelte
  13. 6
      src/lib/stores/userStore.ts
  14. 10
      src/lib/utils/markup/markupServices.ts
  15. 4
      src/lib/utils/nostrUtils.ts
  16. 6
      src/lib/utils/user_lists.ts
  17. 2
      src/routes/events/+page.svelte
  18. 7
      src/routes/new/compose/+page.svelte
  19. 29
      src/routes/publication/[type]/[identifier]/+layout.svelte
  20. 5
      src/routes/visualize/+page.svelte
  21. 23
      tests/unit/eventInput30040.test.ts
  22. 14
      tests/unit/tagExpansion.test.ts

8
src/lib/components/CommentBox.svelte

@ -23,13 +23,15 @@ @@ -23,13 +23,15 @@
} from "$lib/utils/nostrEventService";
import { tick } from "svelte";
import { goto } from "$app/navigation";
import { activeInboxRelays, activeOutboxRelays } from "$lib/ndk";
import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
const props = $props<{
event: NDKEvent;
userRelayPreference: boolean;
}>();
const ndk = getNdkContext();
let content = $state("");
let preview = $state("");
let isSubmitting = $state(false);
@ -216,7 +218,7 @@ @@ -216,7 +218,7 @@
relays = $activeOutboxRelays.slice(0, 3); // Use first 3 outbox relays
}
const successfulRelays = await publishEvent(signedEvent, relays);
const successfulRelays = await publishEvent(signedEvent, relays, ndk);
success = {
relay: successfulRelays[0] || "Unknown relay",
@ -282,7 +284,7 @@ @@ -282,7 +284,7 @@
try {
console.log("Search promise created, waiting for result...");
const result = await searchProfiles(mentionSearch.trim());
const result = await searchProfiles(mentionSearch.trim(), ndk);
console.log("Search completed, found profiles:", result.profiles.length);
console.log("Profile details:", result.profiles);
console.log("Community status:", result.Status);

2
src/lib/components/CommentViewer.svelte

@ -40,7 +40,7 @@ @@ -40,7 +40,7 @@
if (!npub) return;
// Force fetch to ensure we get the latest profile data
const profile = await getUserMetadata(npub, true);
const profile = await getUserMetadata(npub, ndk, true);
const newProfiles = new Map(profiles);
newProfiles.set(pubkey, profile);
profiles = newProfiles;

2
src/lib/components/EventDetails.svelte

@ -196,7 +196,7 @@ @@ -196,7 +196,7 @@
return;
}
getUserMetadata(toNpub(event.pubkey) as string).then((profile) => {
getUserMetadata(toNpub(event.pubkey) as string, undefined).then((profile) => {
authorDisplayName =
profile.displayName ||
(profile as any).display_name ||

1
src/lib/components/EventInput.svelte

@ -265,6 +265,7 @@ @@ -265,6 +265,7 @@
content,
tags,
baseEvent,
ndk,
);
console.log("Index event:", indexEvent);
console.log("Section events:", sectionEvents);

6
src/lib/components/EventSearch.svelte

@ -8,6 +8,7 @@ @@ -8,6 +8,7 @@
searchBySubscription,
searchNip05,
} from "$lib/utils/search_utility";
import type { SearchCallbacks } from "$lib/utils/search_types";
import { neventEncode, naddrEncode, nprofileEncode } from "$lib/utils";
import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
import { getMatchingTags, toNpub } from "$lib/utils/nostrUtils";
@ -81,7 +82,7 @@ @@ -81,7 +82,7 @@
// AI-NOTE: 2025-01-24 - Core search handlers extracted for better organization
async function handleNip05Search(query: string) {
try {
const foundEvent = await searchNip05(query);
const foundEvent = await searchNip05(query, ndk);
if (foundEvent) {
handleFoundEvent(foundEvent);
updateSearchState(false, true, 1, "nip05");
@ -96,7 +97,7 @@ @@ -96,7 +97,7 @@
async function handleEventSearch(query: string) {
try {
const foundEvent = await searchEvent(query);
const foundEvent = await searchEvent(query, ndk);
if (!foundEvent) {
console.warn("[Events] Event not found for query:", query);
localError = "Event not found";
@ -505,6 +506,7 @@ @@ -505,6 +506,7 @@
const searchPromise = searchBySubscription(
searchType,
searchTerm,
ndk,
{
onSecondOrderUpdate: (updatedResult) => {
console.log("EventSearch: Second order update:", updatedResult);

2
src/lib/components/Navigation.svelte

@ -22,7 +22,7 @@ @@ -22,7 +22,7 @@
</NavBrand>
</div>
<div class="flex md:order-2">
<Profile isNav={true} pubkey={userState.npub || undefined} />
<Profile isNav={true} />
<NavHamburger class="btn-leather" />
</div>
<NavUl class="ul-leather">

6
src/lib/components/Notifications.svelte

@ -263,7 +263,7 @@ @@ -263,7 +263,7 @@
try {
console.log("Recipient search promise created, waiting for result...");
const result = await searchProfiles(recipientSearch.trim());
const result = await searchProfiles(recipientSearch.trim(), ndk);
console.log("Recipient search completed, found profiles:", result.profiles.length);
console.log("Profile details:", result.profiles);
console.log("Community status:", result.Status);
@ -388,7 +388,7 @@ @@ -388,7 +388,7 @@
// Get relay sets for all recipients and combine them
const relaySetPromises = recipientPubkeys.map(recipientPubkey =>
getKind24RelaySet(senderPubkey, recipientPubkey)
getKind24RelaySet(senderPubkey, recipientPubkey, ndk)
);
const relaySets = await Promise.all(relaySetPromises);
@ -623,7 +623,7 @@ @@ -623,7 +623,7 @@
// Get relay sets for all recipients and combine them
const relaySetPromises = recipientPubkeys.map(recipientPubkey =>
getKind24RelaySet(senderPubkey, recipientPubkey)
getKind24RelaySet(senderPubkey, recipientPubkey, ndk)
);
const relaySets = await Promise.all(relaySetPromises);

2
src/lib/components/embedded_events/EmbeddedEvent.svelte

@ -107,7 +107,7 @@ @@ -107,7 +107,7 @@
if (event?.pubkey) {
const npub = toNpub(event.pubkey);
if (npub) {
const userProfile = await getUserMetadata(npub);
const userProfile = await getUserMetadata(npub, ndk);
authorDisplayName =
userProfile.displayName ||
(userProfile as any).display_name ||

2
src/lib/components/embedded_events/EmbeddedSnippets.svelte

@ -104,7 +104,7 @@ @@ -104,7 +104,7 @@
if (!npub) return;
// Try cache first
let profile = await getUserMetadata(npub, false);
let profile = await getUserMetadata(npub, ndk, false);
if (profile && (profile.name || profile.displayName || profile.picture)) {
authorProfiles.set(pubkey, profile);
return;

6
src/lib/components/util/ContainingIndexes.svelte

@ -5,12 +5,14 @@ @@ -5,12 +5,14 @@
import { findContainingIndexEvents } from "$lib/utils/event_search";
import { getMatchingTags } from "$lib/utils/nostrUtils";
import { naddrEncode } from "$lib/utils";
import { activeInboxRelays, activeOutboxRelays } from "$lib/ndk";
import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
let { event } = $props<{
event: NDKEvent;
}>();
const ndk = getNdkContext();
let containingIndexes = $state<NDKEvent[]>([]);
let loading = $state(false);
let error = $state<string | null>(null);
@ -25,7 +27,7 @@ @@ -25,7 +27,7 @@
error = null;
try {
containingIndexes = await findContainingIndexEvents(event);
containingIndexes = await findContainingIndexEvents(event, ndk);
console.log(
"[ContainingIndexes] Found containing indexes:",
containingIndexes.length,

8
src/lib/components/util/Profile.svelte

@ -235,7 +235,7 @@ @@ -235,7 +235,7 @@
// Fallback to getUserMetadata
console.log("Falling back to getUserMetadata");
const freshProfile = await getUserMetadata(userState.npub, true); // Force fresh fetch
const freshProfile = await getUserMetadata(userState.npub, ndk, true); // Force fresh fetch
console.log("Fresh profile data from getUserMetadata:", freshProfile);
// Update the userStore with fresh profile data
@ -325,7 +325,7 @@ @@ -325,7 +325,7 @@
qrCodeDataUrl =
(await generateQrCode(amberSigner.nostrConnectUri)) ?? undefined;
const user = await amberSigner.blockUntilReady();
await loginWithAmber(amberSigner, user);
await loginWithAmber(amberSigner, user, ndk);
showQrCode = false;
} else {
throw new Error("Failed to generate Nostr Connect URI");
@ -343,7 +343,7 @@ @@ -343,7 +343,7 @@
const inputNpub = prompt("Enter your npub (public key):");
if (inputNpub) {
try {
await loginWithNpub(inputNpub);
await loginWithNpub(inputNpub, ndk);
} catch (err: unknown) {
showResultMessage(
`❌ npub login failed: ${err instanceof Error ? err.message : String(err)}`,
@ -355,7 +355,7 @@ @@ -355,7 +355,7 @@
async function handleSignOutClick() {
localStorage.removeItem("amber/nsec");
localStorage.removeItem("alexandria/amber/fallback");
logoutUser();
logoutUser(ndk);
}
function handleViewProfile() {

2
src/lib/snippets/UserSnippets.svelte

@ -45,7 +45,7 @@ @@ -45,7 +45,7 @@
</span>
{/await}
{:else}
{#await createProfileLinkWithVerification(npub as string, displayText)}
{#await createProfileLinkWithVerification(npub as string, displayText, undefined)}
<span class="inline-flex items-center gap-0.5">
<button
class="npub-badge bg-transparent border-none p-0 underline cursor-pointer"

6
src/lib/stores/userStore.ts

@ -178,7 +178,7 @@ export async function loginWithExtension(ndk: NDK) { @@ -178,7 +178,7 @@ export async function loginWithExtension(ndk: NDK) {
let profile: NostrProfile | null = null;
try {
console.log("Login with extension - attempting to fetch profile...");
profile = await getUserMetadata(npub, true); // Force fresh fetch
profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with extension - fetched profile:", profile);
} catch (error) {
console.warn("Failed to fetch user metadata during login:", error);
@ -253,7 +253,7 @@ export async function loginWithAmber(amberSigner: NDKSigner, user: NDKUser, ndk: @@ -253,7 +253,7 @@ export async function loginWithAmber(amberSigner: NDKSigner, user: NDKUser, ndk:
let profile: NostrProfile | null = null;
try {
profile = await getUserMetadata(npub, true); // Force fresh fetch
profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with Amber - fetched profile:", profile);
} catch (error) {
console.warn("Failed to fetch user metadata during Amber login:", error);
@ -368,7 +368,7 @@ export async function loginWithNpub(pubkeyOrNpub: string, ndk: NDK) { @@ -368,7 +368,7 @@ export async function loginWithNpub(pubkeyOrNpub: string, ndk: NDK) {
await new Promise((resolve) => setTimeout(resolve, 500));
try {
profile = await getUserMetadata(npub, true); // Force fresh fetch
profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with npub - fetched profile:", profile);
} catch (error) {
console.warn("Failed to fetch user metadata during npub login:", error);

10
src/lib/utils/markup/markupServices.ts

@ -1,3 +1,4 @@ @@ -1,3 +1,4 @@
import NDK from "@nostr-dev-kit/ndk";
import {
createProfileLink,
getUserMetadata,
@ -85,6 +86,7 @@ export function processMediaUrl(url: string, alt?: string): string { @@ -85,6 +86,7 @@ export function processMediaUrl(url: string, alt?: string): string {
*/
export async function processNostrIdentifiersInText(
text: string,
ndk?: NDK,
): Promise<string> {
let processedText = text;
@ -113,7 +115,13 @@ export async function processNostrIdentifiersInText( @@ -113,7 +115,13 @@ export async function processNostrIdentifiersInText(
}
// Get user metadata and create link
const metadata = await getUserMetadata(identifier);
let metadata;
if (ndk) {
metadata = await getUserMetadata(identifier, ndk);
} else {
// Fallback when NDK is not available - just use the identifier
metadata = { name: identifier.slice(0, 8) + "..." + identifier.slice(-4) };
}
const displayText = metadata.displayName || metadata.name;
const link = createProfileLink(identifier, displayText);

4
src/lib/utils/nostrUtils.ts

@ -67,7 +67,7 @@ function escapeRegExp(string: string): string { @@ -67,7 +67,7 @@ function escapeRegExp(string: string): string {
*/
export async function getUserMetadata(
identifier: string,
ndk: NDK,
ndk?: NDK,
force = false,
): Promise<NostrProfile> {
// Remove nostr: prefix if present
@ -175,7 +175,7 @@ export function createProfileLink( @@ -175,7 +175,7 @@ export function createProfileLink(
export async function createProfileLinkWithVerification(
identifier: string,
displayText: string | undefined,
ndk: NDK,
ndk?: NDK,
): Promise<string> {
if (!ndk) {
return createProfileLink(identifier, displayText);

6
src/lib/utils/user_lists.ts

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
import { ndkInstance, activeInboxRelays } from "../ndk.ts";
import { getNdkContext, activeInboxRelays } from "../ndk.ts";
import { get } from "svelte/store";
import type { NDKEvent } from "@nostr-dev-kit/ndk";
import { userStore } from "../stores/userStore.ts";
@ -52,7 +52,7 @@ export async function fetchUserLists( @@ -52,7 +52,7 @@ export async function fetchUserLists(
pubkey: string,
listKinds: number[] = [...PEOPLE_LIST_KINDS]
): Promise<UserListEvent[]> {
const ndk = get(ndkInstance);
const ndk = getNdkContext();
if (!ndk) {
console.warn("fetchUserLists: No NDK instance available");
return [];
@ -211,7 +211,7 @@ export async function updateProfileCacheForPubkeys(pubkeys: string[]): Promise<v @@ -211,7 +211,7 @@ export async function updateProfileCacheForPubkeys(pubkeys: string[]): Promise<v
try {
console.log(`Updating profile cache for ${pubkeys.length} pubkeys`);
const ndk = get(ndkInstance);
const ndk = getNdkContext();
if (!ndk) {
console.warn("updateProfileCacheForPubkeys: No NDK instance available");
return;

2
src/routes/events/+page.svelte

@ -76,7 +76,7 @@ @@ -76,7 +76,7 @@
const npub = toNpub(pubkey);
if (npub) {
// Force fetch to ensure profile is cached
await getUserMetadata(npub, true);
await getUserMetadata(npub, undefined, true);
console.log(`[Events Page] Cached profile for pubkey: ${pubkey}`);
}
} catch (error) {

7
src/routes/new/compose/+page.svelte

@ -6,6 +6,9 @@ @@ -6,6 +6,9 @@
import { nip19 } from "nostr-tools";
import { publishMultipleZettels } from "$lib/services/publisher";
import { parseAsciiDocWithMetadata } from "$lib/utils/asciidoc_metadata";
import { getNdkContext } from "$lib/ndk";
const ndk = getNdkContext();
let content = $state("");
let showPreview = $state(false);
@ -38,7 +41,7 @@ @@ -38,7 +41,7 @@
// Only used for catastrophic errors
publishResults = { successCount: 0, total: 0, errors: [error], successfulEvents: [], failedEvents: [] };
},
});
}, ndk);
const successCount = results.filter(r => r.success).length;
const errors = results.filter(r => !r.success && r.error).map(r => r.error!);
@ -91,7 +94,7 @@ @@ -91,7 +94,7 @@
onError: (error) => {
console.error('Retry failed:', error);
},
});
}, ndk);
if (result[0]?.success && result[0]?.eventId) {
// Update the successful events list

29
src/routes/publication/[type]/[identifier]/+layout.svelte

@ -6,27 +6,38 @@ @@ -6,27 +6,38 @@
// AI-NOTE: Use metadata from server-side load for SEO and social sharing
const { metadata } = data;
// Type assertion for optional metadata properties
const meta = metadata as typeof metadata & {
title?: string;
summary?: string;
image?: string;
};
</script>
<!-- TODO: Provide fallback metadata values to use if the publication is on an auth-to-read relay. -->
<svelte:head>
<!-- Basic meta tags -->
<title>{metadata.title}</title>
<meta name="description" content={metadata.summary} />
<title>{meta.title || "Alexandria - Nostr Publications"}</title>
<meta name="description" content={meta.summary || "Read and discover long-form content on Nostr"} />
<!-- OpenGraph meta tags -->
<meta property="og:title" content={metadata.title} />
<meta property="og:description" content={metadata.summary} />
<meta property="og:url" content={metadata.currentUrl} />
<meta property="og:title" content={meta.title || "Alexandria - Nostr Publications"} />
<meta property="og:description" content={meta.summary || "Read and discover long-form content on Nostr"} />
<meta property="og:url" content={meta.currentUrl} />
<meta property="og:type" content="article" />
<meta property="og:site_name" content="Alexandria" />
<meta property="og:image" content={metadata.image} />
{#if meta.image}
<meta property="og:image" content={meta.image} />
{/if}
<!-- Twitter Card meta tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={metadata.title} />
<meta name="twitter:description" content={metadata.summary} />
<meta name="twitter:image" content={metadata.image} />
<meta name="twitter:title" content={meta.title || "Alexandria - Nostr Publications"} />
<meta name="twitter:description" content={meta.summary || "Read and discover long-form content on Nostr"} />
{#if meta.image}
<meta name="twitter:image" content={meta.image} />
{/if}
</svelte:head>
{@render children()}

5
src/routes/visualize/+page.svelte

@ -578,7 +578,8 @@ @@ -578,7 +578,8 @@
profileEvents = await batchFetchProfiles(
Array.from(allPubkeys),
(fetched, total) => {
ndk,
(fetched: number, total: number) => {
profileLoadingProgress = { current: fetched, total };
}
);
@ -681,6 +682,7 @@ @@ -681,6 +682,7 @@
tags,
existingEventIds,
baseEvents,
ndk,
debug
);
newPublications = result.publications;
@ -698,6 +700,7 @@ @@ -698,6 +700,7 @@
await fetchProfilesForNewEvents(
newPublications,
newContentEvents,
ndk,
(progress: { current: number; total: number } | null) => { profileLoadingProgress = progress; },
debug
);

23
tests/unit/eventInput30040.test.ts

@ -18,13 +18,12 @@ vi.mock("@nostr-dev-kit/ndk", () => ({ @@ -18,13 +18,12 @@ vi.mock("@nostr-dev-kit/ndk", () => ({
})),
}));
// TODO: Replace with getNdkContext mock.
vi.mock("../../src/lib/ndk", () => ({
ndkInstance: {
subscribe: vi.fn(),
},
getNdk: vi.fn(() => ({})),
}));
// Mock NDK context
const mockNdk = {
subscribe: vi.fn(),
fetchEvents: vi.fn(),
pool: { relays: new Map() },
};
vi.mock("svelte/store", () => ({
get: vi.fn(() => ({})),
@ -67,6 +66,7 @@ This is the content of the second section.`; @@ -67,6 +66,7 @@ This is the content of the second section.`;
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -163,6 +163,7 @@ This is the content of the second section.`; @@ -163,6 +163,7 @@ This is the content of the second section.`;
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -240,6 +241,7 @@ This is the preamble content. @@ -240,6 +241,7 @@ This is the preamble content.
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -295,6 +297,7 @@ This is the preamble content. @@ -295,6 +297,7 @@ This is the preamble content.
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -343,6 +346,7 @@ index card`; @@ -343,6 +346,7 @@ index card`;
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -368,6 +372,7 @@ index card`; @@ -368,6 +372,7 @@ index card`;
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event
@ -435,6 +440,7 @@ This is the section content.`; @@ -435,6 +440,7 @@ This is the section content.`;
content,
tags,
baseEvent,
mockNdk as any,
);
// Test index event metadata
@ -574,6 +580,7 @@ This is just preamble content.`; @@ -574,6 +580,7 @@ This is just preamble content.`;
content,
tags,
baseEvent,
mockNdk as any,
);
expect(indexEvent.kind).toBe(30040);
@ -602,6 +609,7 @@ Content here.`; @@ -602,6 +609,7 @@ Content here.`;
content,
tags,
baseEvent,
mockNdk as any,
);
expect(indexEvent.kind).toBe(30040);
@ -631,6 +639,7 @@ Content here.`; @@ -631,6 +639,7 @@ Content here.`;
content,
tags,
baseEvent,
mockNdk as any,
);
expect(indexEvent.kind).toBe(30040);

14
tests/unit/tagExpansion.test.ts

@ -44,7 +44,12 @@ class MockNDKEvent { @@ -44,7 +44,12 @@ class MockNDKEvent {
// Mock NDK instance
const mockNDK = {
fetchEvents: vi.fn(),
};
pool: {},
debug: false,
mutedIds: new Set(),
queuesZapConfig: {},
// Add other required properties as needed for the mock
} as any;
// Mock the ndkInstance store
// TODO: Replace with getNdkContext mock.
@ -167,6 +172,7 @@ describe("Tag Expansion Tests", () => { @@ -167,6 +172,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"],
existingEventIds,
baseEvents,
mockNDK as any,
debug,
);
@ -205,6 +211,7 @@ describe("Tag Expansion Tests", () => { @@ -205,6 +211,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"],
existingEventIds,
baseEvents,
mockNDK as any,
debug,
);
@ -227,6 +234,7 @@ describe("Tag Expansion Tests", () => { @@ -227,6 +234,7 @@ describe("Tag Expansion Tests", () => {
[],
existingEventIds,
baseEvents,
mockNDK as any,
debug,
);
@ -336,6 +344,7 @@ describe("Tag Expansion Tests", () => { @@ -336,6 +344,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents(
mockPublications as NDKEvent[],
mockContentEvents as NDKEvent[],
mockNDK as any,
onProgressUpdate,
debug,
);
@ -357,6 +366,7 @@ describe("Tag Expansion Tests", () => { @@ -357,6 +366,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents(
[],
[],
mockNDK as any,
onProgressUpdate,
debug,
);
@ -390,6 +400,7 @@ describe("Tag Expansion Tests", () => { @@ -390,6 +400,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"],
existingEventIds,
baseEvents,
mockNDK as any,
debug,
);
@ -413,6 +424,7 @@ describe("Tag Expansion Tests", () => { @@ -413,6 +424,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents(
relayResult.publications,
relayResult.contentEvents,
mockNDK as any,
onProgressUpdate,
debug,
);

Loading…
Cancel
Save