Skip to content

Commit

Permalink
feat: [SC-25948] 🔧 Update code organization in NameGraph SDK (#486)
Browse files Browse the repository at this point in the history
* feat: [SC-25948] 🔧 Update code organization in NameGraph SDK

* feat: [SC-25948] 📝 Add README to NameGraph SDK

* feat: [SC-25948] ♻️ Syntax updates in NameGraph SDK

* feat: [SC-25948] ♻️ Reduce changesets files from 2 to 1

* feat: [SC-25975] 📝 Update namegraph.dev README

* feat: [SC-25975] 📦 Update NameGuard SDK package and app that uses it

* feat: [SC-25948] ♻️ Update name for NameGraph instance creation inside package README

* feat: [SC-25948] ♻️ Remove duplicated changeset file

* feat: [SC-25948] ♻️ Update README of NameGraph SDK

* feat: [SC-25948] ♻️ Refactor Docs URL of NameGraph.dev

* feat: [SC-25948] 🎨 Setup beta badge in NameGraph Dev app

* hotfix: [SC-25948] 🚑 Builds hotfix

* hotfix: [SC-25948] 🚑 Update pnpm lock

* hotfix: [SC-25948] 🚑 Update pnpm lock file

* hotfix: [SC-25948] 🚑 Update NameGraph endpoint URL in SDK README

* Create page.tsx

* Revert "Create page.tsx"

This reverts commit e70cad2.
  • Loading branch information
FrancoAguzzi authored Dec 20, 2024
1 parent b5dd3d1 commit 87793a5
Show file tree
Hide file tree
Showing 19 changed files with 559 additions and 395 deletions.
5 changes: 5 additions & 0 deletions .changeset/tall-apricots-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@namehash/namegraph-sdk": minor
---

Add README to NameGraph SDK and update package's code organization
37 changes: 2 additions & 35 deletions apps/namegraph.dev/README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,3 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
# NameGraph SDK use cases

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
This is a [Next.js](https://nextjs.org/) application that showcases different [`NameGraph SDK`](https://github.com/namehash/namekit/tree/main/packages/namegraph-sdk) use cases.
Binary file modified apps/namegraph.dev/app/favicon.ico
Binary file not shown.
13 changes: 10 additions & 3 deletions apps/namegraph.dev/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Inter } from "next/font/google";
import "./globals.css";
import { Github } from "lucide-react";
import Link from "next/link";
import { NameHashLabsLogo } from "@/components/namehash-labs-logo";
import { ServiceProviderBadge } from "@/components/service-provider-badge";
Expand All @@ -10,6 +9,7 @@ import { TwitterIcon } from "@/components/twitter-icon";
import { FarcasterIcon } from "@/components/farcaster-icon";
import { TelegramIcon } from "@/components/telegram-icon";
import { Button } from "@/components/ui/button";
import NextLink from "next/link";

const inter = Inter({ subsets: ["latin"] });

Expand Down Expand Up @@ -63,7 +63,7 @@ export default function RootLayout({
<div className="min-h-screen flex flex-col">
<header className="sticky bg-white top-0 w-full z-20 border-b border-gray-300 h-[56px] py-[9px] sm:h-[70px] sm:py-4 select-none">
<div className="max-w-7xl mx-auto items-center justify-between flex flex-row px-6">
<div className="flex flex-row lg:gap-2 xl:gap-7 justify-between items-center">
<div className="flex flex-row justify-between items-center">
<div className="flex flex-row justify-between items-center gap-1 cursor-pointer flex-shrink-0 pr-2">
<a
href="/"
Expand All @@ -72,12 +72,19 @@ export default function RootLayout({
NameGraph
</a>
</div>
<NextLink href="/">
<div className="relative -top-1.5 bg-black w-fit h-fit p-[2.8px] rounded-[2.8px] flex-shrink-0">
<p className="text-white not-italic font-semibold pb-[0.5px] text-[6.857px] leading-[7.619px] sm:text-[8.409px] sm:leading-[9.343px]">
beta
</p>
</div>
</NextLink>
</div>
<div className="flex flex-row items-center justify-between md:gap-5 h-[40px]">
<div className="hidden items-center justify-center lg:flex gap-2">
<div className="hidden items-center justify-center xl:flex gap-2">
<Button variant="ghost" asChild>
<Link href="http://100.24.45.225/docs">Docs</Link>
<Link href="http://api.namegraph.dev/docs">Docs</Link>
</Button>

<Button variant="ghost" asChild>
Expand Down
6 changes: 3 additions & 3 deletions apps/namegraph.dev/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import { WritersBlockPills } from "../components/writers-block-pills";
import { Catalog } from "../components/catalog";
import { useEffect } from "react";
import { useState } from "react";
import { writersBlockSuggestions } from "@/lib/writers-block-suggestions";
import {
sampleWritersBlockSuggestions,
WritersBlockCollection,
WritersBlockSuggestion,
} from "@/lib/utils";
import { useState } from "react";
import { writersBlockSuggestions } from "@/lib/writers-block-suggestions";
} from "@namehash/namegraph-sdk/utils";

export default function Home() {
const [suggestions, setSuggestions] = useState<WritersBlockSuggestion[]>([]);
Expand Down
3 changes: 1 addition & 2 deletions apps/namegraph.dev/components/catalog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import { useRef, useState } from "react";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { WritersBlockCollection, WritersBlockSuggestion } from "@/lib/utils";
import { writersBlockSuggestions } from "@/lib/writers-block-suggestions";
import { Tooltip } from "@namehash/namekit-react/client";
import { InfoIcon } from "lucide-react";
import { WritersBlockCollection } from "@namehash/namegraph-sdk/utils";

interface CatalogProps {
onJsonChange: (parsedJson: any) => void;
Expand Down
2 changes: 1 addition & 1 deletion apps/namegraph.dev/components/writers-block-pill.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { WritersBlockSuggestion } from "@/lib/utils";
import { WritersBlockSuggestion } from "@namehash/namegraph-sdk/utils";
import Skeleton from "./skeleton";

export const WritersBlockPill = ({
Expand Down
2 changes: 1 addition & 1 deletion apps/namegraph.dev/components/writers-block-pills.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use client";

import { WritersBlockPill } from "./writers-block-pill";
import { WritersBlockSuggestion } from "@/lib/utils";
import { Button } from "./ui/button";
import { useState } from "react";
import { useEffect } from "react";
import { WritersBlockSuggestion } from "@namehash/namegraph-sdk/utils";

interface WritersBlockPillsProps {
suggestions: WritersBlockSuggestion[];
Expand Down
67 changes: 0 additions & 67 deletions apps/namegraph.dev/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,6 @@
import { writersBlockSuggestions } from "./writers-block-suggestions";
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

export type WritersBlockSuggestion = {
collectionName: string;
suggestedName: string;
tokenizedSuggestedName: string[];
};

export type WritersBlockName = {
normalized_name: string;
tokenized_name: string[];
};

export type WritersBlockCollection = {
collection_id: string;
collection_name: string;
names: WritersBlockName[];
};

const getRandomElementOfArray = <Type>(array: Type[]): Type =>
array[Math.floor(Math.random() * array.length)];

const getRandomWritersBlockSuggestion = (
array: WritersBlockCollection[],
): WritersBlockSuggestion => {
const rawWritersBlockSuggestion = getRandomElementOfArray(array);
const rawName = getRandomElementOfArray(rawWritersBlockSuggestion.names);
return {
collectionName: rawWritersBlockSuggestion.collection_name,
suggestedName: rawName.normalized_name,
tokenizedSuggestedName: rawName.tokenized_name,
};
};

// TODO: move this function to namegraph-sdk
export const sampleWritersBlockSuggestions = (
suggestionsCount: number,
catalog?: WritersBlockCollection[],
): WritersBlockSuggestion[] => {
const uniqueCollectionsNames = new Set();
const uniqueSuggestionsNames = new Set();
const result = [];

let collections = undefined;
if (catalog?.length) collections = catalog;
else collections = writersBlockSuggestions;

while (
result.length !== suggestionsCount &&
result.length !== collections.length
) {
const writersBlockSuggestion = getRandomWritersBlockSuggestion(collections);

if (
uniqueCollectionsNames.has(writersBlockSuggestion.collectionName) ||
uniqueSuggestionsNames.has(writersBlockSuggestion.suggestedName)
) {
continue;
} else {
uniqueCollectionsNames.add(writersBlockSuggestion.collectionName);
uniqueSuggestionsNames.add(writersBlockSuggestion.suggestedName);
result.push(writersBlockSuggestion);
}
}

return result;
};
2 changes: 1 addition & 1 deletion apps/namegraph.dev/lib/writers-block-suggestions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WritersBlockCollection } from "./utils";
import { WritersBlockCollection } from "@namehash/namegraph-sdk/utils";

export const writersBlockSuggestions: WritersBlockCollection[] = [
{
Expand Down
1 change: 1 addition & 0 deletions apps/namegraph.dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"lint": "next lint"
},
"dependencies": {
"@namehash/namegraph-sdk": "workspace:*",
"@namehash/namekit-react": "workspace:*",
"@radix-ui/react-scroll-area": "^1.2.1",
"@radix-ui/react-slot": "^1.1.0",
Expand Down
1 change: 0 additions & 1 deletion apps/namegraph.dev/public/next.svg

This file was deleted.

1 change: 0 additions & 1 deletion apps/namegraph.dev/public/vercel.svg

This file was deleted.

138 changes: 138 additions & 0 deletions packages/namegraph-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# NameGraph SDK

A TypeScript SDK for interacting with the NameGraph APIs, providing access to the world's largest collection of names. This SDK enables easy integration with the NameGraph API endpoints for name and collection suggestions.

## Installation

```bash
npm install namegraph-sdk
# or
yarn add namegraph-sdk
```

## Quick Start

```typescript
import { createNameGraphClient } from "namegraph-sdk";

// Create a client instance
const client = createNameGraphClient();

// Or use the default client
import { namegraph } from "namegraph-sdk";

// Get name suggestions grouped by category
const suggestions = await namegraph.groupedByCategory("zeus");
```

## Features

- **Category-based Suggestions**: Get name suggestions organized by various categories including related terms, wordplay, alternates, and more
- **Collection Management**: Find, count, and analyze collections of names
- **Smart Sampling**: Sample and fetch top members from collections
- **Advanced Search**: Search collections by string or by collection ID

## API Reference

### Client Configuration

```typescript
const client = createNameGraphClient({
namegraphEndpoint: "https://custom-api.endpoint.com", // Optional, defaults to https://api.namegraph.dev/
});
```

### Core Methods

#### Group Names by Category

```typescript
const response = await client.groupedByCategory("zeus");
```

#### Get Suggestions by Category

```typescript
const suggestions = await client.suggestionsByCategory("zeus");
```

#### Sample Collection Members

```typescript
const members = await client.sampleCollectionMembers("collection_id");
```

#### Fetch Top Collection Members

```typescript
const topMembers = await client.fetchTopCollectionMembers("collection_id");
```

#### Find Collections

```typescript
// By string
const collections = await client.findCollectionsByString("zeus god");

// By collection ID
const related = await client.findCollectionsByCollection("collection_id");

// By member
const memberCollections = await client.findCollectionsByMember("zeus");
```

#### Count Collections

```typescript
// By string
const stringCount = await client.countCollectionsByString("zeus god");

// By member
const memberCount = await client.countCollectionsByMember("zeus");
```

### Response Types

The SDK provides TypeScript types for all API responses. Key types include:

- `NameGraphSuggestion`
- `NameGraphCategory`
- `NameGraphCollection`
- `NameGraphGroupedByCategoryResponse`
- `NameGraphFetchTopCollectionMembersResponse`
- `NameGraphCountCollectionsResponse`

### Error Handling

The SDK throws `NameGraphError` for API-related errors. Handle them appropriately:

```typescript
try {
const suggestions = await client.groupedByCategory("example");
} catch (error) {
if (error instanceof NameGraphError) {
console.error(`API Error ${error.status}: ${error.message}`);
}
}
```

### Request Cancellation

Cancel ongoing requests using the `abortAllRequests` method:

```typescript
client.abortAllRequests();
```

## Categories

The SDK supports various grouping categories for name suggestions:

- `related`: Related terms and concepts
- `wordplay`: Creative word variations
- `alternates`: Alternative versions
- `emojify`: Emoji-enhanced variations
- `community`: Community-suggested names
- `expand`: Expanded versions
- `gowild`: Creative variations
- `other`: Additional suggestions
5 changes: 5 additions & 0 deletions packages/namegraph-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./utils": {
"types": "./dist/utils.d.ts",
"import": "./dist/utils.js",
"default": "./dist/utils.js"
}
},
"main": "./dist/index.js",
Expand Down
Loading

0 comments on commit 87793a5

Please sign in to comment.