Add NostrURI class

This commit is contained in:
Alex Gleason committed 2025-12-23 00:57:18 -06:00
1 parent c84acfdcaa
commit 46a89a67d9
7 files changed
+573 -125

No files matched your search

+3 -3
View File
@@ -8,7 +8,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { NostrURI } from '@/lib/NostrURI';
interface RepositoryCardProps {
repo: Repository;
@@ -22,11 +22,11 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const nostrURI = new NostrURI({ pubkey: repo.pubkey, identifier: repo.repoId });
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
navigate(`/clone?url=${encodeURIComponent(nostrURI.toString())}`);
};
return (
@@ -11,11 +11,11 @@ import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useFS } from '@/hooks/useFS';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
import { DotAI } from '@/lib/DotAI';
import type { ConfigureRepoStepProps } from '../types';
import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
export function ConfigureRepoStep({
projectId,
@@ -90,13 +90,13 @@ export function ConfigureRepoStep({
}
// Construct Nostr URI
const nostrUri = `nostr://${nip19.npubEncode(repoEvent.pubkey)}/${projectId}`;
const nostrURI = new NostrURI({ pubkey: repoEvent.pubkey, identifier: projectId });
// Configure the Nostr URI as the origin
await git.addRemote({
dir,
remote: 'origin',
url: nostrUri,
url: nostrURI.toString(),
force: true,
});
+283
View File
@@ -0,0 +1,283 @@
import { describe, it, expect } from 'vitest';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
describe('NostrURI', () => {
const testPubkey = 'a'.repeat(64); // Valid hex pubkey
const testNpub = nip19.npubEncode(testPubkey);
const testIdentifier = 'my-repo';
const testRelay = 'wss://relay.example.com/';
describe('constructor', () => {
it('creates a NostrURI from parts without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('creates a NostrURI from parts with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe(testRelay);
});
});
describe('parse', () => {
it('parses a simple nostr URI without relay', async () => {
const uriString = `nostr://${testNpub}/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('parses a nostr URI with relay', async () => {
const uriString = `nostr://${testNpub}/relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe('wss://relay.example.com/');
});
it('parses a nostr URI with wss:// relay', async () => {
const uriString = `nostr://${testNpub}/wss://relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe('wss://relay.example.com/');
});
it('throws on invalid URI prefix', async () => {
await expect(NostrURI.parse('https://example.com')).rejects.toThrow(
'Invalid Nostr URI: must start with "nostr://"'
);
});
it('throws on too few path segments', async () => {
await expect(NostrURI.parse('nostr://npub1abc')).rejects.toThrow(
'Invalid Nostr URI: must have at least pubkey/identifier'
);
});
it('throws on too many path segments', async () => {
await expect(
NostrURI.parse(`nostr://${testNpub}/relay/identifier/extra`)
).rejects.toThrow('Invalid Nostr URI: too many path segments');
});
it('throws on invalid npub', async () => {
await expect(NostrURI.parse('nostr://invalid/identifier')).rejects.toThrow(
'Invalid Nostr URI: identifier must be npub or NIP-05 address'
);
});
});
describe('toString', () => {
it('converts to string without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/${testIdentifier}`);
});
it('converts to string with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/relay.example.com/${testIdentifier}`);
});
it('removes wss:// prefix and trailing slash from relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: 'wss://relay.example.com/',
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/relay.example.com/${testIdentifier}`);
});
});
describe('toNaddr', () => {
it('converts to naddr without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const naddr = uri.toNaddr(30617);
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.pubkey).toBe(testPubkey);
expect(decoded.data.identifier).toBe(testIdentifier);
expect(decoded.data.kind).toBe(30617);
// nip19.naddrEncode returns an empty array when no relays are provided
expect(decoded.data.relays).toEqual([]);
}
});
it('converts to naddr with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const naddr = uri.toNaddr(30617);
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.pubkey).toBe(testPubkey);
expect(decoded.data.identifier).toBe(testIdentifier);
expect(decoded.data.kind).toBe(30617);
expect(decoded.data.relays).toEqual([testRelay]);
}
});
it('uses default kind 30617 when not specified', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const naddr = uri.toNaddr();
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.kind).toBe(30617);
}
});
});
describe('fromNaddr', () => {
it('creates NostrURI from naddr without relay', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('creates NostrURI from naddr with relay', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
relays: [testRelay],
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe(testRelay);
});
it('uses first relay when multiple relays provided', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
relays: [testRelay, 'wss://another-relay.com/'],
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.relay).toBe(testRelay);
});
it('throws on invalid naddr', () => {
expect(() => NostrURI.fromNaddr('invalid')).toThrow('Failed to parse naddr');
});
it('throws on non-naddr identifier', () => {
const npub = nip19.npubEncode(testPubkey);
expect(() => NostrURI.fromNaddr(npub)).toThrow(
'Invalid naddr: must be an addressable event pointer'
);
});
});
describe('toJSON', () => {
it('returns the component parts', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const parts = uri.toJSON();
expect(parts).toEqual({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
});
});
describe('round-trip conversions', () => {
it('parse -> toString round-trip works', async () => {
const original = `nostr://${testNpub}/${testIdentifier}`;
const uri = await NostrURI.parse(original);
const result = uri.toString();
expect(result).toBe(original);
});
it('parse -> toString round-trip works with relay', async () => {
const original = `nostr://${testNpub}/relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(original);
const result = uri.toString();
expect(result).toBe(original);
});
it('toNaddr -> fromNaddr round-trip works', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const naddr = uri.toNaddr(30617);
const result = NostrURI.fromNaddr(naddr);
expect(result.pubkey).toBe(uri.pubkey);
expect(result.identifier).toBe(uri.identifier);
expect(result.relay).toBe(uri.relay);
});
});
});
+249
View File
@@ -0,0 +1,249 @@
import { NIP05 } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
/**
* Represents a parsed Nostr URI with its components
*/
export interface NostrURIParts {
/** The public key (hex format) */
pubkey: string;
/** The identifier (d-tag value) */
identifier: string;
/** Optional relay URL */
relay?: string;
}
/**
* NostrURI class for parsing and constructing Nostr URIs
*
* Supports formats:
* - nostr://npub/identifier
* - nostr://npub/relay/identifier
* - nostr://nip05@domain/identifier
* - nostr://nip05@domain/relay/identifier
*
* @example
* ```ts
* // Construct from parts
* const uri = new NostrURI({
* pubkey: 'abc123...',
* identifier: 'my-repo',
* relay: 'relay.example.com'
* });
*
* // Parse from string
* const uri = await NostrURI.parse('nostr://npub1.../my-repo');
* ```
*/
export class NostrURI {
public readonly pubkey: string;
public readonly identifier: string;
public readonly relay?: string;
/**
* Construct a NostrURI from its component parts
*/
constructor(parts: NostrURIParts) {
this.pubkey = parts.pubkey;
this.identifier = parts.identifier;
this.relay = parts.relay;
}
/**
* Parse a Nostr URI string into a NostrURI instance
*
* @param uri - The Nostr URI string to parse
* @returns A NostrURI instance
* @throws Error if the URI format is invalid
*
* @example
* ```ts
* const uri = await NostrURI.parse('nostr://npub1abc.../my-repo');
* console.log(uri.pubkey); // hex pubkey
* console.log(uri.identifier); // 'my-repo'
* ```
*/
static async parse(uri: string): Promise<NostrURI> {
if (!uri.startsWith('nostr://')) {
throw new Error('Invalid Nostr URI: must start with "nostr://"');
}
const path = uri.slice(8); // Remove 'nostr://' prefix
const parts = path.split('/');
if (parts.length < 2) {
throw new Error('Invalid Nostr URI: must have at least pubkey/identifier');
}
const identifierPart = parts[0];
let pubkey: string;
// Try to decode as npub first
try {
const decoded = nip19.decode(identifierPart);
if (decoded.type === 'npub') {
pubkey = decoded.data;
} else {
throw new Error('Invalid Nostr URI: identifier must be npub or NIP-05 address');
}
} catch {
// If decoding fails, check if it's a NIP-05 identifier
if (identifierPart.includes('@')) {
try {
const pointer = await NIP05.lookup(identifierPart, {
signal: AbortSignal.timeout(3000),
});
pubkey = pointer.pubkey;
} catch (error) {
throw new Error(`Invalid Nostr URI: failed to resolve NIP-05 identifier: ${error}`);
}
} else {
throw new Error('Invalid Nostr URI: identifier must be npub or NIP-05 address');
}
}
// Parse the remaining parts based on length
if (parts.length === 2) {
// Format: nostr://npub/identifier
return new NostrURI({
pubkey,
identifier: parts[1],
});
} else if (parts.length === 3) {
// Format: nostr://npub/relay/identifier
const relay = parts[1].startsWith('wss://') ? parts[1] : `wss://${parts[1]}/`;
return new NostrURI({
pubkey,
relay,
identifier: parts[2],
});
} else {
// Handle the case where wss:// is included in the URI
// When split by /, wss://relay.example.com becomes ['wss:', '', 'relay.example.com']
// So we need to reconstruct the relay URL
// Find where 'wss:' appears in the parts array
const wssIndex = parts.findIndex(part => part === 'wss:');
if (wssIndex > 0 && parts.length > wssIndex + 2) {
// Reconstruct the relay URL: wss://hostname/
const hostname = parts[wssIndex + 2]; // Skip the empty string after wss:
const relay = `wss://${hostname}/`;
const identifier = parts[wssIndex + 3];
return new NostrURI({
pubkey,
relay,
identifier,
});
}
throw new Error('Invalid Nostr URI: too many path segments');
}
}
/**
* Convert the NostrURI to a string representation
*
* @returns The Nostr URI as a string
*
* @example
* ```ts
* const uri = new NostrURI({ pubkey: 'abc...', identifier: 'my-repo' });
* console.log(uri.toString()); // 'nostr://npub1.../my-repo'
* ```
*/
toString(): string {
const npub = nip19.npubEncode(this.pubkey);
if (this.relay) {
try {
const url = new URL(this.relay);
return `nostr://${npub}/${url.hostname}/${this.identifier}`;
} catch {
// fallthrough
}
}
return `nostr://${npub}/${this.identifier}`;
}
/**
* Convert to an naddr (NIP-19 addressable event identifier)
*
* @param kind - The event kind (default: 30617 for repository announcements)
* @returns An naddr string
*
* @example
* ```ts
* const uri = new NostrURI({ pubkey: 'abc...', identifier: 'my-repo' });
* const naddr = uri.toNaddr(30617);
* ```
*/
toNaddr(kind: number = 30617): string {
const data: {
kind: number;
pubkey: string;
identifier: string;
relays?: string[];
} = {
kind,
pubkey: this.pubkey,
identifier: this.identifier,
};
// Only add relays if we have a relay (avoid empty array)
if (this.relay) {
data.relays = [this.relay];
}
return nip19.naddrEncode(data);
}
/**
* Create a NostrURI from an naddr (NIP-19 addressable event identifier)
*
* @param naddr - The naddr string to parse
* @returns A NostrURI instance
* @throws Error if the naddr is invalid or not an addressable event pointer
*
* @example
* ```ts
* const uri = NostrURI.fromNaddr('naddr1...');
* console.log(uri.pubkey);
* console.log(uri.identifier);
* ```
*/
static fromNaddr(naddr: string): NostrURI {
try {
const decoded = nip19.decode(naddr);
if (decoded.type !== 'naddr') {
throw new Error('Invalid naddr: must be an addressable event pointer');
}
const data = decoded.data;
return new NostrURI({
pubkey: data.pubkey,
identifier: data.identifier,
relay: data.relays?.[0], // Use first relay if available
});
} catch (error) {
throw new Error(`Failed to parse naddr: ${error}`);
}
}
/**
* Convert to a JSON-serializable object with the component parts
*
* @returns The component parts of the URI
*/
toJSON(): NostrURIParts {
return {
pubkey: this.pubkey,
identifier: this.identifier,
relay: this.relay,
};
}
}
+1
View File
@@ -12,6 +12,7 @@ vi.mock('nostr-tools', () => ({
nip19: {
decode: vi.fn(),
naddrEncode: vi.fn(),
npubEncode: vi.fn((pubkey: string) => `npub1${pubkey.slice(0, 10)}`),
},
}));
vi.mock('@nostrify/nostrify', () => ({
+24 -108
View File
@@ -1,9 +1,8 @@
import git, { AuthCallback, FetchResult, GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
import { NIP05 } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { proxyUrl } from './proxyUrl';
import { readGitSettings } from './configUtils';
import { parseRepositoryAnnouncement, RepositoryAnnouncement } from './announceRepository';
import { NostrURI } from './NostrURI';
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
import type { JSRuntimeFS } from './JSRuntime';
@@ -17,12 +16,6 @@ export interface GitOptions {
signer?: NostrSigner;
}
interface NostrCloneURI {
pubkey: string;
d: string;
relay?: string;
}
/**
* Git class that wraps isomorphic-git and provides a cleaner interface.
* Instantiate with an fs implementation, optional corsProxy string, and optional corsProxyRegex.
@@ -62,10 +55,7 @@ export class Git {
async clone(options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>) {
// Check if the URL is a Nostr URI
if (options.url.startsWith('nostr://')) {
const nostrURI = await this.parseNostrCloneURI(options.url);
if (!nostrURI) {
throw new Error('Invalid Nostr clone URI format');
}
const nostrURI = await NostrURI.parse(options.url);
// Try cloning from Nostr
return this.nostrClone(nostrURI, options);
}
@@ -111,7 +101,7 @@ export class Git {
// Commits and history
async commit(options: Omit<Parameters<typeof git.commit>[0], 'fs' | 'author'>) {
const { author, coAuthorEnabled } = await this.getGitSettings();
// Add system co-author if enabled
let message = options.message;
if (coAuthorEnabled) {
@@ -201,7 +191,8 @@ export class Git {
async getRemoteInfo(options: Omit<Parameters<typeof git.getRemoteInfo>[0], 'http' | 'corsProxy'>) {
// Check if the URL is a Nostr URI
if (options.url.startsWith('nostr://')) {
return this.getNostrRemoteInfo(options.url);
const nostrURI = await NostrURI.parse(options.url);
return this.getNostrRemoteInfo(nostrURI);
}
return git.getRemoteInfo({
@@ -218,7 +209,8 @@ export class Git {
const remoteUrl = await this.getRemoteURL(dir, remote);
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
return this.nostrFetch(remoteUrl, { ...options, remote, dir });
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrFetch(nostrURI, { ...options, remote, dir });
}
// Regular Git fetch
@@ -238,7 +230,8 @@ export class Git {
const { author } = await this.getGitSettings();
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
return this.nostrPull(remoteUrl, { ...options, author, remote, dir });
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrPull(nostrURI, { ...options, author, remote, dir });
}
// Regular Git pull
@@ -258,7 +251,8 @@ export class Git {
const remoteUrl = await this.getRemoteURL(dir, remote);
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
return this.nostrPush(remoteUrl, { ...options, remote, dir: dir });
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrPush(nostrURI, { ...options, remote, dir: dir });
}
return git.push({
@@ -613,18 +607,12 @@ export class Git {
/**
* Get remote info for a Nostr repository URI
*/
private async getNostrRemoteInfo(nostrUrl: string): Promise<{
private async getNostrRemoteInfo(nostrURI: NostrURI): Promise<{
capabilities: string[];
refs: Record<string, string>;
HEAD?: string;
}> {
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Getting remote info for Nostr repository: ${nostrUrl}`);
console.log(`Getting remote info for Nostr repository: ${nostrURI.toString()}`);
// Fetch the repository announcement and state from Nostr
const { repo, state } = await this.fetchNostrRepoEvents(nostrURI);
@@ -910,63 +898,7 @@ export class Git {
return { valid, warnings };
}
private async parseNostrCloneURI(uri: string): Promise<NostrCloneURI | null> {
try {
if (!uri.startsWith('nostr://')) {
return null;
}
const path = uri.slice(8); // Remove 'nostr://' prefix
const parts = path.split('/');
if (parts.length < 2) {
return null;
}
const identifier = parts[0];
let pubkey: string;
// Try to decode as npub first, otherwise assume it's already a hex pubkey
try {
const decoded = nip19.decode(identifier);
if (decoded.type === 'npub') {
pubkey = decoded.data;
} else {
return null;
}
} catch {
// If decoding fails, check if it's a NIP-05 identifier
if (identifier.split('@').length === 2) {
const pointer = await NIP05.lookup(identifier, {
signal: AbortSignal.timeout(3000),
});
pubkey = pointer.pubkey;
} else {
return null;
}
}
// Check if we have relay and d-tag or just d-tag
if (parts.length === 3) {
// Format: nostr://npub/relay/d
return {
pubkey,
relay: `wss://${parts[1]}/`,
d: parts[2],
};
} else if (parts.length === 2) {
// Format: nostr://npub/d
return {
pubkey,
d: parts[1],
};
}
return null;
} catch {
return null;
}
}
/**
* Process GRASP server mismatch between configured servers and announcement servers.
@@ -994,7 +926,7 @@ export class Git {
}
}
private async fetchNostrRepoEvents(nostrURI: NostrCloneURI): Promise<{
private async fetchNostrRepoEvents(nostrURI: NostrURI): Promise<{
repo: RepositoryAnnouncement;
state?: RespositoryState;
serversWithoutAnnouncement?: string[];
@@ -1007,7 +939,7 @@ export class Git {
const filter = {
kinds: [30617, 30618],
authors: [nostrURI.pubkey],
'#d': [nostrURI.d],
'#d': [nostrURI.identifier],
};
// Track all servers we've queried to avoid duplicates
@@ -1172,7 +1104,7 @@ export class Git {
};
}
private async nostrClone(nostrURI: NostrCloneURI, options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>): Promise<void> {
private async nostrClone(nostrURI: NostrURI, options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>): Promise<void> {
// Fetch events from Nostr
const { repo, state } = await this.fetchNostrRepoEvents(nostrURI);
@@ -1367,11 +1299,7 @@ export class Git {
await this.setConfig({
dir: options.dir,
path: 'nostr.repo',
value: nip19.naddrEncode({
kind: 30617,
pubkey: nostrURI.pubkey,
identifier: nostrURI.d,
})
value: nostrURI.toNaddr(30617),
});
// Validate the cloned repository against the expected state
@@ -1671,14 +1599,8 @@ export class Git {
return differences;
}
private async nostrFetch(nostrUrl: string, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<FetchResult> {
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Fetching updates from Nostr repository: ${nostrUrl}`);
private async nostrFetch(nostrURI: NostrURI, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<FetchResult> {
console.log(`Fetching updates from Nostr repository: ${nostrURI.toString()}`);
// Fetch the latest repository state from Nostr
const { repo, state, serversWithoutLatestAnnouncement, serversWithoutLatestState } = await this.fetchNostrRepoEvents(nostrURI);
@@ -1765,9 +1687,9 @@ export class Git {
}
}
private async nostrPull(nostrUrl: string, options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<void> {
private async nostrPull(nostrURI: NostrURI, options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<void> {
// First, fetch the latest state
const fetchResult = await this.nostrFetch(nostrUrl, options);
const fetchResult = await this.nostrFetch(nostrURI, options);
// Get the current branch
const currentBranch = await git.currentBranch({ fs: this.fs, dir: options.dir });
@@ -1853,7 +1775,7 @@ export class Git {
}
}
private async nostrPush(nostrUrl: string, options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'onAuth' | 'corsProxy'>) {
private async nostrPush(nostrURI: NostrURI, options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'onAuth' | 'corsProxy'>) {
if (!this.signer) {
throw new Error('Nostr signer is required for pushing to Nostr repositories');
}
@@ -1863,13 +1785,7 @@ export class Git {
const remoteRef = options.remoteRef || ref;
const force = options.force || false;
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Pushing to Nostr repository: ${nostrUrl}`);
console.log(`Pushing to Nostr repository: ${nostrURI.toString()}`);
// Fetch the repository announcement and state to get relay information and current remote state
// Also check which servers don't have the latest announcement
@@ -2005,7 +1921,7 @@ export class Git {
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, this.signer);
} else {
// No existing state event - create initial state from repository
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.d, this.signer);
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.identifier, this.signer);
}
// Publish the state event to Nostr relays
+10 -11
View File
@@ -24,6 +24,7 @@ import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import { NSchema as n } from '@nostrify/nostrify';
import type { NostrMetadata } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
export default function Clone() {
const { t } = useTranslation();
@@ -83,20 +84,18 @@ export default function Clone() {
description: t('cloneGitRepository'),
});
const extractRepoName = (url: string): string => {
const extractRepoName = async (url: string): Promise<string> => {
try {
const cleanUrl = url.trim();
// Handle Nostr clone URIs
if (cleanUrl.startsWith('nostr://')) {
const path = cleanUrl.slice(8); // Remove 'nostr://' prefix
const parts = path.split('/');
// Return the d-tag (last part) as the repo name
if (parts.length >= 2) {
return parts[parts.length - 1] || 'nostr-repo';
try {
const nostrURI = await NostrURI.parse(cleanUrl);
return nostrURI.identifier || 'nostr-repo';
} catch {
return 'nostr-repo';
}
return 'nostr-repo';
}
// Extract from GitHub URLs, GitLab URLs, etc.
@@ -154,7 +153,7 @@ export default function Clone() {
await projectsManager.init();
// Extract repository name
const repoName = extractRepoName(targetUrl);
const repoName = await extractRepoName(targetUrl);
// Clone the repository (Git class handles both regular Git URLs and Nostr URIs)
const project = await projectsManager.cloneProject(repoName, targetUrl.trim());
@@ -254,7 +253,7 @@ export default function Clone() {
}
const lowerQuery = query.toLowerCase();
return repos.filter((repo) => {
// Filter by repository name
if (repo.name.toLowerCase().includes(lowerQuery)) {
@@ -404,7 +403,7 @@ export default function Clone() {
Follows
</TabsTrigger>
</TabsList>
{/* Search Input */}
{(repositories.length > 0 || followedRepositories.length > 0) && (
<div className="relative flex-1 min-w-[200px] max-w-md">