prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import debug from "debug";
import EventEmitter from "eventemitter3";
import { Relay, relayInit, Sub } from "nostr-tools";
import "websocket-polyfill";
import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js";
import { NDKSubscription } from "../subscription/index.js";
import User from "../user/index.js";
import { NDKRelayScore } from "./score.js";
export enum NDKRelayStatus {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
RECONNECTING,
FLAPPING,
}
export interface NDKRelayConnectionStats {
/**
* The number of times a connection has been attempted.
*/
attempts: number;
/**
* The number of times a connection has been successfully established.
*/
success: number;
/**
* The durations of the last 100 connections in milliseconds.
*/
durations: number[];
/**
* The time the current connection was established in milliseconds.
*/
connectedAt?: number;
}
/**
* The NDKRelay class represents a connection to a relay.
*
* @emits NDKRelay#connect
* @emits NDKRelay#disconnect
* @emits NDKRelay#notice
* @emits NDKRelay#event
* @emits NDKRelay#published when an event is published to the relay
* @emits NDKRelay#publish:failed when an event fails to publish to the relay
* @emits NDKRelay#eose
*/
export class NDKRelay extends EventEmitter {
readonly url: string;
readonly scores: Map<User, NDKRelayScore>;
private relay: Relay;
private _status: NDKRelayStatus;
private connectedAt?: number;
private _connectionStats: NDKRelayConnectionStats = {
attempts: 0,
success: 0,
durations: [],
};
public complaining = false;
private debug: debug.Debugger;
/**
* Active subscriptions this relay is connected to
*/
public activeSubscriptions = new Set<NDKSubscription>();
public constructor(url: string) {
super();
this.url = url;
this.relay = relayInit(url);
this.scores = new Map<User, NDKRelayScore>();
this._status = NDKRelayStatus.DISCONNECTED;
this.debug = debug(`ndk:relay:${url}`);
this.relay.on("connect", () => {
this.updateConnectionStats.connected();
this._status = NDKRelayStatus.CONNECTED;
this.emit("connect");
});
this.relay.on("disconnect", () => {
this.updateConnectionStats.disconnected();
if (this._status === NDKRelayStatus.CONNECTED) {
this._status = NDKRelayStatus.DISCONNECTED;
this.handleReconnection();
}
this.emit("disconnect");
});
this.relay.on("notice", (notice: string) => this.handleNotice(notice));
}
/**
* Evaluates the connection stats to determine if the relay is flapping.
*/
private isFlapping(): boolean {
const durations = this._connectionStats.durations;
if (durations.length < 10) return false;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = sum / durations.length;
const variance =
durations
.map((x) => Math.pow(x - avg, 2))
.reduce((a, b) => a + b, 0) / durations.length;
const stdDev = Math.sqrt(variance);
const isFlapping = stdDev < 1000;
return isFlapping;
}
/**
* Called when the relay is unexpectedly disconnected.
*/
private handleReconnection() {
if (this.isFlapping()) {
this.emit("flapping", this, this._connectionStats);
this._status = NDKRelayStatus.FLAPPING;
}
if (this.connectedAt && Date.now() - this.connectedAt < 5000) {
setTimeout(() => this.connect(), 60000);
} else {
this.connect();
}
}
get status(): NDKRelayStatus {
return this._status;
}
/**
* Connects to the relay.
*/
public async connect(): Promise<void> {
try {
this.updateConnectionStats.attempt();
this._status = NDKRelayStatus.CONNECTING;
await this.relay.connect();
} catch (e) {
this.debug("Failed to connect", e);
this._status = NDKRelayStatus.DISCONNECTED;
throw e;
}
}
/**
* Disconnects from the relay.
*/
public disconnect(): void {
this._status = NDKRelayStatus.DISCONNECTING;
this.relay.close();
}
async handleNotice(notice: string) {
// This is a prototype; if the relay seems to be complaining
// remove it from relay set selection for a minute.
if (notice.includes("oo many") || notice.includes("aximum")) {
this.disconnect();
// fixme
setTimeout(() => this.connect(), 2000);
this.debug(this.relay.url, "Relay complaining?", notice);
// this.complaining = true;
// setTimeout(() => {
// this.complaining = false;
// console.log(this.relay.url, 'Reactivate relay');
// }, 60000);
}
this.emit("notice", this, notice);
}
/**
* Subscribes to a subscription.
*/
public | subscribe(subscription: NDKSubscription): Sub { |
const { filters } = subscription;
const sub = this.relay.sub(filters, {
id: subscription.subId,
});
this.debug(`Subscribed to ${JSON.stringify(filters)}`);
sub.on("event", (event: NostrEvent) => {
const e = new NDKEvent(undefined, event);
e.relay = this;
subscription.eventReceived(e, this);
});
sub.on("eose", () => {
subscription.eoseReceived(this);
});
const unsub = sub.unsub;
sub.unsub = () => {
this.debug(`Unsubscribing from ${JSON.stringify(filters)}`);
this.activeSubscriptions.delete(subscription);
unsub();
};
this.activeSubscriptions.add(subscription);
subscription.on("close", () => {
this.activeSubscriptions.delete(subscription);
});
return sub;
}
/**
* Publishes an event to the relay with an optional timeout.
*
* If the relay is not connected, the event will be published when the relay connects,
* unless the timeout is reached before the relay connects.
*
* @param event The event to publish
* @param timeoutMs The timeout for the publish operation in milliseconds
* @returns A promise that resolves when the event has been published or rejects if the operation times out
*/
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
if (this.status === NDKRelayStatus.CONNECTED) {
return this.publishEvent(event, timeoutMs);
} else {
this.once("connect", () => {
this.publishEvent(event, timeoutMs);
});
return true;
}
}
private async publishEvent(
event: NDKEvent,
timeoutMs?: number
): Promise<boolean> {
const nostrEvent = await event.toNostrEvent();
const publish = this.relay.publish(nostrEvent as any);
let publishTimeout: NodeJS.Timeout | number;
const publishPromise = new Promise<boolean>((resolve, reject) => {
publish
.then(() => {
clearTimeout(publishTimeout as unknown as NodeJS.Timeout);
this.emit("published", event);
resolve(true);
})
.catch((err) => {
clearTimeout(publishTimeout as NodeJS.Timeout);
this.debug("Publish failed", err, event.id);
this.emit("publish:failed", event, err);
reject(err);
});
});
// If no timeout is specified, just return the publish promise
if (!timeoutMs) {
return publishPromise;
}
// Create a promise that rejects after timeoutMs milliseconds
const timeoutPromise = new Promise<boolean>((_, reject) => {
publishTimeout = setTimeout(() => {
this.debug("Publish timed out", event.rawEvent());
this.emit("publish:failed", event, "Timeout");
reject(new Error("Publish operation timed out"));
}, timeoutMs);
});
// wait for either the publish operation to complete or the timeout to occur
return Promise.race([publishPromise, timeoutPromise]);
}
/**
* Called when this relay has responded with an event but
* wasn't the fastest one.
* @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public scoreSlowerEvent(timeDiffInMs: number): void {
// TODO
}
/**
* Utility functions to update the connection stats.
*/
private updateConnectionStats = {
connected: () => {
this._connectionStats.success++;
this._connectionStats.connectedAt = Date.now();
},
disconnected: () => {
if (this._connectionStats.connectedAt) {
this._connectionStats.durations.push(
Date.now() - this._connectionStats.connectedAt
);
if (this._connectionStats.durations.length > 100) {
this._connectionStats.durations.shift();
}
}
this._connectionStats.connectedAt = undefined;
},
attempt: () => {
this._connectionStats.attempts++;
},
};
/**
* Returns the connection stats.
*/
get connectionStats(): NDKRelayConnectionStats {
return this._connectionStats;
}
public tagReference(marker?: string): NDKTag {
const tag = ["r", this.relay.url];
if (marker) {
tag.push(marker);
}
return tag;
}
}
| src/relay/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " *\n * @param relay - The relay to add to the pool.\n * @param connect - Whether or not to connect to the relay.\n */\n public addRelay(relay: NDKRelay, connect = true) {\n const relayUrl = relay.url;\n relay.on(\"notice\", (relay, notice) =>\n this.emit(\"notice\", relay, notice)\n );\n relay.on(\"connect\", () => this.handleRelayConnect(relayUrl));",
"score": 36.85033689743568
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) {\n const sub = relay.subscribe(subscription);\n subscription.relaySubscriptions.set(relay, sub);\n }\n /**\n * Calculates an ID of this specific combination of relays.\n */\n public getId() {\n const urls = Array.from(this.relays).map((r) => r.url);",
"score": 27.319757067055235
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " const urlString = urls.sort().join(\",\");\n return bytesToHex(sha256(urlString));\n }\n /**\n * Add a subscription to this relay set\n */\n public subscribe(subscription: NDKSubscription): NDKSubscription {\n const subGroupableId = subscription.groupableId();\n const groupableId = `${this.getId()}:${subGroupableId}`;\n if (!subGroupableId) {",
"score": 26.98011876302644
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,",
"score": 23.179417583786805
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " }\n this.encryptedTagsLength = this.content.length;\n return (this._encryptedTags = []);\n } catch (e) {\n console.log(`error decrypting ${this.content}`);\n }\n }\n } catch (e) {\n // console.trace(e);\n // throw e;",
"score": 22.553900010068126
}
] | typescript | subscribe(subscription: NDKSubscription): Sub { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
| export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { |
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 21.946497326568313
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 20.23780141488219
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": "}\nfunction formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {\n if (!commits.length) {\n return [];\n }\n const lines: string[] = ['', formatTitle(sectionName, options), ''];\n const scopes = groupBy(commits, 'scope');\n let useScopeGroup = options.group;\n // group scopes only when one of the scope have multiple commits\n if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {",
"score": 20.117656134705836
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 18.246520227243977
},
{
"filename": "src/generate.ts",
"retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}",
"score": 17.97337440783147
}
] | typescript | export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { NDKCacheAdapter } from "./cache/index.js";
import dedupEvent from "./events/dedup.js";
import NDKEvent from "./events/index.js";
import type { NDKRelay } from "./relay/index.js";
import { NDKPool } from "./relay/pool/index.js";
import { calculateRelaySetFromEvent } from "./relay/sets/calculate.js";
import { NDKRelaySet } from "./relay/sets/index.js";
import { correctRelaySet } from "./relay/sets/utils.js";
import type { NDKSigner } from "./signers/index.js";
import {
NDKFilter,
NDKSubscription,
NDKSubscriptionOptions,
filterFromId,
relaysFromBech32,
} from "./subscription/index.js";
import NDKUser, { NDKUserParams } from "./user/index.js";
import { NDKUserProfile } from "./user/profile.js";
export { NDKEvent, NDKUser, NDKFilter, NDKUserProfile, NDKCacheAdapter };
export * from "./events/index.js";
export * from "./events/kinds/index.js";
export * from "./events/kinds/article.js";
export * from "./events/kinds/dvm/index.js";
export * from "./events/kinds/lists/index.js";
export * from "./events/kinds/repost.js";
export * from "./relay/index.js";
export * from "./relay/sets/index.js";
export * from "./signers/index.js";
export * from "./signers/nip07/index.js";
export * from "./signers/nip46/backend/index.js";
export * from "./signers/nip46/rpc.js";
export * from "./signers/nip46/index.js";
export * from "./signers/private-key/index.js";
export * from "./subscription/index.js";
export * from "./user/profile.js";
export { NDKZapInvoice, zapInvoiceFromEvent } from "./zap/invoice.js";
export interface NDKConstructorParams {
explicitRelayUrls?: string[];
devWriteRelayUrls?: string[];
signer?: NDKSigner;
cacheAdapter?: NDKCacheAdapter;
debug?: debug.Debugger;
}
export interface GetUserParams extends NDKUserParams {
npub?: string;
hexpubkey?: string;
}
export default class NDK extends EventEmitter {
public pool: NDKPool;
| public signer?: NDKSigner; |
public cacheAdapter?: NDKCacheAdapter;
public debug: debug.Debugger;
public devWriteRelaySet?: NDKRelaySet;
public delayedSubscriptions: Map<string, NDKSubscription[]>;
public constructor(opts: NDKConstructorParams = {}) {
super();
this.debug = opts.debug || debug("ndk");
this.pool = new NDKPool(opts.explicitRelayUrls || [], this);
this.signer = opts.signer;
this.cacheAdapter = opts.cacheAdapter;
this.delayedSubscriptions = new Map();
if (opts.devWriteRelayUrls) {
this.devWriteRelaySet = NDKRelaySet.fromRelayUrls(
opts.devWriteRelayUrls,
this
);
}
}
public toJSON(): string {
return { relayCount: this.pool.relays.size }.toString();
}
/**
* Connect to relays with optional timeout.
* If the timeout is reached, the connection will be continued to be established in the background.
*/
public async connect(timeoutMs?: number): Promise<void> {
this.debug("Connecting to relays", { timeoutMs });
return this.pool.connect(timeoutMs);
}
/**
* Get a NDKUser object
*
* @param opts
* @returns
*/
public getUser(opts: GetUserParams): NDKUser {
const user = new NDKUser(opts);
user.ndk = this;
return user;
}
/**
* Create a new subscription. Subscriptions automatically start and finish when all relays
* on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this)
*
* @param filters
* @param opts
* @param relaySet explicit relay set to use
* @param autoStart automatically start the subscription
* @returns NDKSubscription
*/
public subscribe(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
autoStart = true
): NDKSubscription {
const subscription = new NDKSubscription(this, filters, opts, relaySet);
// Signal to the relays that they are explicitly being used
if (relaySet) {
for (const relay of relaySet.relays) {
this.pool.useTemporaryRelay(relay);
}
}
if (autoStart) subscription.start();
return subscription;
}
/**
* Publish an event to a relay
* @param event event to publish
* @param relaySet explicit relay set to use
* @param timeoutMs timeout in milliseconds to wait for the event to be published
* @returns The relays the event was published to
*
* @deprecated Use `event.publish()` instead
*/
public async publish(
event: NDKEvent,
relaySet?: NDKRelaySet,
timeoutMs?: number
): Promise<Set<NDKRelay>> {
this.debug("Deprecated: Use `event.publish()` instead");
if (!relaySet) {
// If we have a devWriteRelaySet, use it to publish all events
relaySet =
this.devWriteRelaySet ||
calculateRelaySetFromEvent(this, event);
}
return relaySet.publish(event, timeoutMs);
}
/**
* Fetch a single event.
*
* @param idOrFilter event id in bech32 format or filter
* @param opts subscription options
* @param relaySet explicit relay set to use
*/
public async fetchEvent(
idOrFilter: string | NDKFilter,
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<NDKEvent | null> {
let filter: NDKFilter;
// if no relayset has been provided, try to get one from the event id
if (!relaySet && typeof idOrFilter === "string") {
const relays = relaysFromBech32(idOrFilter);
if (relays.length > 0) {
relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);
// Make sure we have connected relays in this set
relaySet = correctRelaySet(relaySet, this.pool);
}
}
if (typeof idOrFilter === "string") {
filter = filterFromId(idOrFilter);
} else {
filter = idOrFilter;
}
if (!filter) {
throw new Error(`Invalid filter: ${JSON.stringify(idOrFilter)}`);
}
return new Promise((resolve) => {
const s = this.subscribe(
filter,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
s.on("event", (event) => {
event.ndk = this;
resolve(event);
});
s.on("eose", () => {
resolve(null);
});
s.start();
});
}
/**
* Fetch events
*/
public async fetchEvents(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<Set<NDKEvent>> {
return new Promise((resolve) => {
const events: Map<string, NDKEvent> = new Map();
const relaySetSubscription = this.subscribe(
filters,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
const onEvent = (event: NDKEvent) => {
const dedupKey = event.deduplicationKey();
const existingEvent = events.get(dedupKey);
if (existingEvent) {
event = dedupEvent(existingEvent, event);
}
event.ndk = this;
events.set(dedupKey, event);
};
// We want to inspect duplicated events
// so we can dedup them
relaySetSubscription.on("event", onEvent);
relaySetSubscription.on("event:dup", onEvent);
relaySetSubscription.on("eose", () => {
resolve(new Set(events.values()));
});
relaySetSubscription.start();
});
}
/**
* Ensures that a signer is available to sign an event.
*/
public async assertSigner() {
if (!this.signer) {
this.emit("signerRequired");
throw new Error("Signer required");
}
}
}
| src/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": "}\nexport class NDKNostrRpc extends EventEmitter {\n private ndk: NDK;\n private signer: NDKSigner;\n private debug: debug.Debugger;\n public constructor(ndk: NDK, signer: NDKSigner, debug: debug.Debugger) {\n super();\n this.ndk = ndk;\n this.signer = signer;\n this.debug = debug.extend(\"rpc\");",
"score": 42.930338887991155
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " */\nexport class NDKNip46Signer implements NDKSigner {\n private ndk: NDK;\n public remoteUser: NDKUser;\n public remotePubkey: string;\n public token: string | undefined;\n public localSigner: NDKSigner;\n private rpc: NDKNostrRpc;\n private debug: debug.Debugger;\n /**",
"score": 31.78403684810505
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": "export default class NDKEvent extends EventEmitter {\n public ndk?: NDK;\n public created_at?: number;\n public content = \"\";\n public tags: NDKTag[] = [];\n public kind?: NDKKind | number;\n public id = \"\";\n public sig?: string;\n public pubkey = \"\";\n /**",
"score": 31.200143487241128
},
{
"filename": "src/zap/index.ts",
"retrieved_chunk": "type ZapConstructorParamsRequired = Required<\n Pick<ZapConstructorParams, \"zappedEvent\">\n> &\n Pick<ZapConstructorParams, \"zappedUser\"> &\n ZapConstructorParams;\nexport default class Zap extends EventEmitter {\n public ndk?: NDK;\n public zappedEvent?: NDKEvent;\n public zappedUser: User;\n public constructor(args: ZapConstructorParamsRequired) {",
"score": 27.859652112647915
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " npub?: string;\n hexpubkey?: string;\n nip05?: string;\n relayUrls?: string[];\n}\n/**\n * Represents a pubkey.\n */\nexport default class NDKUser {\n public ndk: NDK | undefined;",
"score": 27.447624790539074
}
] | typescript | public signer?: NDKSigner; |
#!/usr/bin/env node
import { blue, bold, cyan, dim, red, yellow } from 'kolorist';
import cac from 'cac';
import { version } from '../package.json';
import { generate } from './generate';
import { hasTagOnGitHub, sendRelease } from './github';
import { isRepoShallow } from './git';
import type { ChangelogOptions } from './types';
const cli = cac('githublogen');
cli
.version(version)
.option('-t, --token <path>', 'GitHub Token')
.option('--from <ref>', 'From tag')
.option('--to <ref>', 'To tag')
.option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen')
.option('--name <name>', 'Name of the release')
.option('--contributors', 'Show contributors section')
.option('--prerelease', 'Mark release as prerelease')
.option('-d, --draft', 'Mark release as draft')
.option('--output <path>', 'Output to file instead of sending to GitHub')
.option('--capitalize', 'Should capitalize for each comment message')
.option('--emoji', 'Use emojis in section titles', { default: true })
.option('--group', 'Nest commit messages under their scopes')
.option('--dry', 'Dry run')
.help();
cli.command('').action(async (args: any) => {
try {
console.log();
console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));
const cwd = process.cwd();
const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);
const markdown = md.replace(/ /g, '');
console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));
console.log(dim('--------------'));
console.log();
console.log(markdown);
console.log();
console.log(dim('--------------'));
if (config.dry) {
console.log(yellow('Dry run. Release skipped.'));
return;
}
if (!(await hasTagOnGitHub(config.to, config))) {
console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`));
process.exitCode = 1;
return;
}
| if (!commits.length && (await isRepoShallow())) { |
console.error(
yellow(
'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.'
)
);
process.exitCode = 1;
return;
}
await sendRelease(config, md);
} catch (e: any) {
console.error(red(String(e)));
if (e?.stack) {
console.error(dim(e.stack?.split('\n').slice(1).join('\n')));
}
process.exit(1);
}
});
cli.parse();
| src/cli.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`",
"score": 29.259734116034412
},
{
"filename": "src/config.ts",
"retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;",
"score": 28.013286248054847
},
{
"filename": "src/github.ts",
"retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();",
"score": 22.32407460867522
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.",
"score": 20.869420979695295
},
{
"filename": "src/git.ts",
"retrieved_chunk": "}\nexport async function getLastGitTag(delta = 0) {\n const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\\n'));\n return tags[tags.length + delta - 1];\n}\nexport async function isRefGitTag(to: string) {\n const { execa } = await import('execa');\n try {\n await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });\n return true;",
"score": 16.987581397572146
}
] | typescript | if (!commits.length && (await isRepoShallow())) { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { NDKCacheAdapter } from "./cache/index.js";
import dedupEvent from "./events/dedup.js";
import NDKEvent from "./events/index.js";
import type { NDKRelay } from "./relay/index.js";
import { NDKPool } from "./relay/pool/index.js";
import { calculateRelaySetFromEvent } from "./relay/sets/calculate.js";
import { NDKRelaySet } from "./relay/sets/index.js";
import { correctRelaySet } from "./relay/sets/utils.js";
import type { NDKSigner } from "./signers/index.js";
import {
NDKFilter,
NDKSubscription,
NDKSubscriptionOptions,
filterFromId,
relaysFromBech32,
} from "./subscription/index.js";
import NDKUser, { NDKUserParams } from "./user/index.js";
import { NDKUserProfile } from "./user/profile.js";
export { NDKEvent, NDKUser, NDKFilter, NDKUserProfile, NDKCacheAdapter };
export * from "./events/index.js";
export * from "./events/kinds/index.js";
export * from "./events/kinds/article.js";
export * from "./events/kinds/dvm/index.js";
export * from "./events/kinds/lists/index.js";
export * from "./events/kinds/repost.js";
export * from "./relay/index.js";
export * from "./relay/sets/index.js";
export * from "./signers/index.js";
export * from "./signers/nip07/index.js";
export * from "./signers/nip46/backend/index.js";
export * from "./signers/nip46/rpc.js";
export * from "./signers/nip46/index.js";
export * from "./signers/private-key/index.js";
export * from "./subscription/index.js";
export * from "./user/profile.js";
export { NDKZapInvoice, zapInvoiceFromEvent } from "./zap/invoice.js";
export interface NDKConstructorParams {
explicitRelayUrls?: string[];
devWriteRelayUrls?: string[];
signer?: NDKSigner;
cacheAdapter?: NDKCacheAdapter;
debug?: debug.Debugger;
}
export interface GetUserParams extends NDKUserParams {
npub?: string;
hexpubkey?: string;
}
export default class NDK extends EventEmitter {
public pool: NDKPool;
public signer?: NDKSigner;
public cacheAdapter?: NDKCacheAdapter;
public debug: debug.Debugger;
public devWriteRelaySet?: NDKRelaySet;
public delayedSubscriptions: Map<string, NDKSubscription[]>;
public constructor(opts: NDKConstructorParams = {}) {
super();
this.debug = opts.debug || debug("ndk");
this.pool = new NDKPool(opts.explicitRelayUrls || [], this);
this.signer = opts.signer;
this.cacheAdapter = opts.cacheAdapter;
this.delayedSubscriptions = new Map();
if (opts.devWriteRelayUrls) {
this.devWriteRelaySet = NDKRelaySet.fromRelayUrls(
opts.devWriteRelayUrls,
this
);
}
}
public toJSON(): string {
return { relayCount: this.pool.relays.size }.toString();
}
/**
* Connect to relays with optional timeout.
* If the timeout is reached, the connection will be continued to be established in the background.
*/
public async connect(timeoutMs?: number): Promise<void> {
this.debug("Connecting to relays", { timeoutMs });
return this.pool.connect(timeoutMs);
}
/**
* Get a NDKUser object
*
* @param opts
* @returns
*/
public getUser(opts: GetUserParams): NDKUser {
const user = new NDKUser(opts);
user.ndk = this;
return user;
}
/**
* Create a new subscription. Subscriptions automatically start and finish when all relays
* on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this)
*
* @param filters
* @param opts
* @param relaySet explicit relay set to use
* @param autoStart automatically start the subscription
* @returns NDKSubscription
*/
public subscribe(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
autoStart = true
): NDKSubscription {
const subscription = new NDKSubscription(this, filters, opts, relaySet);
// Signal to the relays that they are explicitly being used
if (relaySet) {
for (const relay of relaySet.relays) {
this.pool.useTemporaryRelay(relay);
}
}
if (autoStart) subscription.start();
return subscription;
}
/**
* Publish an event to a relay
* @param event event to publish
* @param relaySet explicit relay set to use
* @param timeoutMs timeout in milliseconds to wait for the event to be published
* @returns The relays the event was published to
*
* @deprecated Use `event.publish()` instead
*/
public async publish(
event: NDKEvent,
relaySet?: NDKRelaySet,
timeoutMs?: number
): Promise<Set<NDKRelay>> {
this.debug("Deprecated: Use `event.publish()` instead");
if (!relaySet) {
// If we have a devWriteRelaySet, use it to publish all events
relaySet =
this.devWriteRelaySet ||
calculateRelaySetFromEvent(this, event);
}
return relaySet.publish(event, timeoutMs);
}
/**
* Fetch a single event.
*
* @param idOrFilter event id in bech32 format or filter
* @param opts subscription options
* @param relaySet explicit relay set to use
*/
public async fetchEvent(
idOrFilter: string | NDKFilter,
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<NDKEvent | null> {
let filter: NDKFilter;
// if no relayset has been provided, try to get one from the event id
if (!relaySet && typeof idOrFilter === "string") {
const relays = relaysFromBech32(idOrFilter);
if (relays.length > 0) {
relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);
// Make sure we have connected relays in this set
relaySet = correctRelaySet(relaySet, this.pool);
}
}
if (typeof idOrFilter === "string") {
filter = filterFromId(idOrFilter);
} else {
filter = idOrFilter;
}
if (!filter) {
throw new Error(`Invalid filter: ${JSON.stringify(idOrFilter)}`);
}
return new Promise((resolve) => {
const s = this.subscribe(
filter,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
s.on("event", (event) => {
event.ndk = this;
resolve(event);
});
s.on("eose", () => {
resolve(null);
});
s.start();
});
}
/**
* Fetch events
*/
public async fetchEvents(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<Set<NDKEvent>> {
return new Promise((resolve) => {
const events: Map<string, NDKEvent> = new Map();
const relaySetSubscription = this.subscribe(
filters,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
const onEvent = (event: NDKEvent) => {
const dedupKey = event.deduplicationKey();
const existingEvent = events.get(dedupKey);
if (existingEvent) {
| event = dedupEvent(existingEvent, event); |
}
event.ndk = this;
events.set(dedupKey, event);
};
// We want to inspect duplicated events
// so we can dedup them
relaySetSubscription.on("event", onEvent);
relaySetSubscription.on("event:dup", onEvent);
relaySetSubscription.on("eose", () => {
resolve(new Set(events.values()));
});
relaySetSubscription.start();
});
}
/**
* Ensures that a signer is available to sign an event.
*/
public async assertSigner() {
if (!this.signer) {
this.emit("signerRequired");
throw new Error("Signer required");
}
}
}
| src/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/user/index.ts",
"retrieved_chunk": " closeOnEose: true,\n groupable: false,\n }\n );\n opts = {\n cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,\n closeOnEose: true,\n };\n }\n if (!setMetadataEvents || setMetadataEvents.size === 0) {",
"score": 20.617173915819514
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " event: NDKEvent,\n relay: NDKRelay | undefined,\n fromCache = false\n ) {\n if (relay) event.relay = relay;\n if (!relay) relay = event.relay;\n if (!fromCache && relay) {\n // track the event per relay\n let events = this.eventsPerRelay.get(relay);\n if (!events) {",
"score": 16.73839078522833
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " // for (const tag of event.tags) {\n // if (tag[0] === tagKey && tag[1] === tagValue) {\n // return false;\n // }\n // }\n // }\n // }\n // return true;\n }\n private forwardEvent(event: NDKEvent, relay: NDKRelay) {",
"score": 15.31959263670483
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " this.on(\"event:dup\", this.forwardEventDup);\n this.on(\"eose\", this.forwardEose);\n this.on(\"close\", this.forwardClose);\n }\n private isEventForSubscription(\n event: NDKEvent,\n subscription: NDKSubscription\n ): boolean {\n const { filters } = subscription;\n if (!filters) return false;",
"score": 14.920246458179328
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " */\nexport const defaultOpts: NDKSubscriptionOptions = {\n closeOnEose: true,\n cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,\n groupable: true,\n groupableDelay: 100,\n};\n/**\n * Represents a subscription to an NDK event stream.\n *",
"score": 14.87682327654239
}
] | typescript | event = dedupEvent(existingEvent, event); |
import type { RawGitCommit, RepoConfig } from './types';
export async function getGitHubRepo() {
const url = await execCommand('git', ['config', '--get', 'remote.origin.url']);
const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i);
if (!match) {
throw new Error(`Can not parse GitHub repo from url ${url}`);
}
return `${match[1]}/${match[2]}`;
}
export async function getGitMainBranchName() {
const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']);
return main;
}
export async function getCurrentGitBranch() {
const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']);
const main = getGitMainBranchName();
return result1 || main;
}
export async function isRepoShallow() {
return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true';
}
export async function getLastGitTag(delta = 0) {
const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n'));
return tags[tags.length + delta - 1];
}
export async function isRefGitTag(to: string) {
const { execa } = await import('execa');
try {
await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });
return true;
} catch {
return false;
}
}
export function getFirstGitCommit() {
return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']);
}
export function isPrerelease(version: string) {
return !/^[^.]*[\d.]+$/.test(version);
}
async function execCommand(cmd: string, args: string[]) {
const { execa } = await import('execa');
const res = await execa(cmd, args);
return res.stdout.trim();
}
export async function getGitDiff(from | : string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> { |
// https://git-scm.com/docs/pretty-formats
const r = await execCommand('git', [
'--no-pager',
'log',
`${from ? `${from}...` : ''}${to}`,
'--pretty="----%n%s|%h|%an|%ae%n%b"',
'--name-status'
]);
return r
.split('----\n')
.splice(1)
.map(line => {
const [firstLine, ..._body] = line.split('\n');
const [message, shortHash, authorName, authorEmail] = firstLine.split('|');
const $r: RawGitCommit = {
message,
shortHash,
author: { name: authorName, email: authorEmail },
body: _body.join('\n')
};
return $r;
});
}
export function getGitRemoteURL(cwd: string, remote = 'origin') {
return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);
}
export function getGitPushUrl(config: RepoConfig, token?: string) {
if (!token) return null;
return `https://${token}@${config.domain}/${config.repo}`;
}
| src/git.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 25.442011638979544
},
{
"filename": "src/config.ts",
"retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,",
"score": 18.30427863850742
},
{
"filename": "src/github.ts",
"retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();",
"score": 15.620027691418699
},
{
"filename": "src/cli.ts",
"retrieved_chunk": " .option('--capitalize', 'Should capitalize for each comment message')\n .option('--emoji', 'Use emojis in section titles', { default: true })\n .option('--group', 'Nest commit messages under their scopes')\n .option('--dry', 'Dry run')\n .help();\ncli.command('').action(async (args: any) => {\n try {\n console.log();\n console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));\n const cwd = process.cwd();",
"score": 15.062904532575898
},
{
"filename": "src/github.ts",
"retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {",
"score": 14.886906728181856
}
] | typescript | : string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { NDKCacheAdapter } from "./cache/index.js";
import dedupEvent from "./events/dedup.js";
import NDKEvent from "./events/index.js";
import type { NDKRelay } from "./relay/index.js";
import { NDKPool } from "./relay/pool/index.js";
import { calculateRelaySetFromEvent } from "./relay/sets/calculate.js";
import { NDKRelaySet } from "./relay/sets/index.js";
import { correctRelaySet } from "./relay/sets/utils.js";
import type { NDKSigner } from "./signers/index.js";
import {
NDKFilter,
NDKSubscription,
NDKSubscriptionOptions,
filterFromId,
relaysFromBech32,
} from "./subscription/index.js";
import NDKUser, { NDKUserParams } from "./user/index.js";
import { NDKUserProfile } from "./user/profile.js";
export { NDKEvent, NDKUser, NDKFilter, NDKUserProfile, NDKCacheAdapter };
export * from "./events/index.js";
export * from "./events/kinds/index.js";
export * from "./events/kinds/article.js";
export * from "./events/kinds/dvm/index.js";
export * from "./events/kinds/lists/index.js";
export * from "./events/kinds/repost.js";
export * from "./relay/index.js";
export * from "./relay/sets/index.js";
export * from "./signers/index.js";
export * from "./signers/nip07/index.js";
export * from "./signers/nip46/backend/index.js";
export * from "./signers/nip46/rpc.js";
export * from "./signers/nip46/index.js";
export * from "./signers/private-key/index.js";
export * from "./subscription/index.js";
export * from "./user/profile.js";
export { NDKZapInvoice, zapInvoiceFromEvent } from "./zap/invoice.js";
export interface NDKConstructorParams {
explicitRelayUrls?: string[];
devWriteRelayUrls?: string[];
signer?: NDKSigner;
cacheAdapter?: NDKCacheAdapter;
debug?: debug.Debugger;
}
export interface GetUserParams extends NDKUserParams {
npub?: string;
hexpubkey?: string;
}
export default class NDK extends EventEmitter {
public pool: NDKPool;
public signer?: NDKSigner;
public cacheAdapter?: NDKCacheAdapter;
public debug: debug.Debugger;
public devWriteRelaySet?: NDKRelaySet;
public delayedSubscriptions: Map<string, NDKSubscription[]>;
public constructor(opts: NDKConstructorParams = {}) {
super();
this.debug = opts.debug || debug("ndk");
this.pool = new NDKPool(opts.explicitRelayUrls || [], this);
this.signer = opts.signer;
this.cacheAdapter = opts.cacheAdapter;
this.delayedSubscriptions = new Map();
if (opts.devWriteRelayUrls) {
this.devWriteRelaySet = NDKRelaySet.fromRelayUrls(
opts.devWriteRelayUrls,
this
);
}
}
public toJSON(): string {
return { relayCount: this.pool.relays.size }.toString();
}
/**
* Connect to relays with optional timeout.
* If the timeout is reached, the connection will be continued to be established in the background.
*/
public async connect(timeoutMs?: number): Promise<void> {
this.debug("Connecting to relays", { timeoutMs });
return this.pool.connect(timeoutMs);
}
/**
* Get a NDKUser object
*
* @param opts
* @returns
*/
public getUser(opts: GetUserParams): NDKUser {
const user = new NDKUser(opts);
user.ndk = this;
return user;
}
/**
* Create a new subscription. Subscriptions automatically start and finish when all relays
* on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this)
*
* @param filters
* @param opts
* @param relaySet explicit relay set to use
* @param autoStart automatically start the subscription
* @returns NDKSubscription
*/
public subscribe(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
autoStart = true
): NDKSubscription {
const subscription = new NDKSubscription(this, filters, opts, relaySet);
// Signal to the relays that they are explicitly being used
if (relaySet) {
for (const relay of relaySet.relays) {
this.pool.useTemporaryRelay(relay);
}
}
if (autoStart) subscription.start();
return subscription;
}
/**
* Publish an event to a relay
* @param event event to publish
* @param relaySet explicit relay set to use
* @param timeoutMs timeout in milliseconds to wait for the event to be published
* @returns The relays the event was published to
*
* @deprecated Use `event.publish()` instead
*/
public async publish(
event: NDKEvent,
relaySet?: NDKRelaySet,
timeoutMs?: number
): Promise<Set<NDKRelay>> {
this.debug("Deprecated: Use `event.publish()` instead");
if (!relaySet) {
// If we have a devWriteRelaySet, use it to publish all events
relaySet =
this.devWriteRelaySet ||
calculateRelaySetFromEvent(this, event);
}
return relaySet.publish(event, timeoutMs);
}
/**
* Fetch a single event.
*
* @param idOrFilter event id in bech32 format or filter
* @param opts subscription options
* @param relaySet explicit relay set to use
*/
public async fetchEvent(
idOrFilter: string | NDKFilter,
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<NDKEvent | null> {
let filter: NDKFilter;
// if no relayset has been provided, try to get one from the event id
if (!relaySet && typeof idOrFilter === "string") {
const relays = relaysFromBech32(idOrFilter);
if (relays.length > 0) {
relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);
// Make sure we have connected relays in this set
| relaySet = correctRelaySet(relaySet, this.pool); |
}
}
if (typeof idOrFilter === "string") {
filter = filterFromId(idOrFilter);
} else {
filter = idOrFilter;
}
if (!filter) {
throw new Error(`Invalid filter: ${JSON.stringify(idOrFilter)}`);
}
return new Promise((resolve) => {
const s = this.subscribe(
filter,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
s.on("event", (event) => {
event.ndk = this;
resolve(event);
});
s.on("eose", () => {
resolve(null);
});
s.start();
});
}
/**
* Fetch events
*/
public async fetchEvents(
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet
): Promise<Set<NDKEvent>> {
return new Promise((resolve) => {
const events: Map<string, NDKEvent> = new Map();
const relaySetSubscription = this.subscribe(
filters,
{ ...(opts || {}), closeOnEose: true },
relaySet,
false
);
const onEvent = (event: NDKEvent) => {
const dedupKey = event.deduplicationKey();
const existingEvent = events.get(dedupKey);
if (existingEvent) {
event = dedupEvent(existingEvent, event);
}
event.ndk = this;
events.set(dedupKey, event);
};
// We want to inspect duplicated events
// so we can dedup them
relaySetSubscription.on("event", onEvent);
relaySetSubscription.on("event:dup", onEvent);
relaySetSubscription.on("eose", () => {
resolve(new Set(events.values()));
});
relaySetSubscription.start();
});
}
/**
* Ensures that a signer is available to sign an event.
*/
public async assertSigner() {
if (!this.signer) {
this.emit("signerRequired");
throw new Error("Signer required");
}
}
}
| src/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/sets/utils.ts",
"retrieved_chunk": "import { NDKPool } from \"../../relay/pool/index.js\";\nimport { NDKRelaySet } from \"../../relay/sets/index.js\";\n/**\n * If the provided relay set does not include connected relays in the pool\n * the relaySet will have the connected relays added to it.\n */\nexport function correctRelaySet(\n relaySet: NDKRelaySet,\n pool: NDKPool\n): NDKRelaySet {",
"score": 71.99484014769101
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 61.38518766465646
},
{
"filename": "src/relay/sets/utils.ts",
"retrieved_chunk": " // if connected relays is empty (such us when we're first starting, add all relays)\n if (connectedRelays.length === 0) {\n for (const relay of pool.relays.values()) {\n relaySet.addRelay(relay);\n }\n }\n return relaySet;\n}",
"score": 59.1111741098079
},
{
"filename": "src/relay/sets/utils.ts",
"retrieved_chunk": " const connectedRelays = pool.connectedRelays();\n const includesConnectedRelay = Array.from(relaySet.relays).some((relay) => {\n return connectedRelays.map((r) => r.url).includes(relay.url);\n });\n if (!includesConnectedRelay) {\n // Add connected relays to the relay set\n for (const relay of connectedRelays) {\n relaySet.addRelay(relay);\n }\n }",
"score": 48.71962824909274
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " }\n private startWithRelaySet(): void {\n if (!this.relaySet) {\n this.relaySet = calculateRelaySetFromFilter(\n this.ndk,\n this.filters[0]\n );\n }\n if (this.relaySet) {\n this.relaySet.subscribe(this);",
"score": 47.06841737230182
}
] | typescript | relaySet = correctRelaySet(relaySet, this.pool); |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
. | map((a, idx) => { |
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 22.669824976509382
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 21.9725908787624
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 20.912437582203474
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " array.forEach((e, idx, arr) => {\n let i = 0;\n for (const filter of filters) {\n if (filter(e, idx, arr)) {\n result[i].push(e);\n return;\n }\n i += 1;\n }\n result[i].push(e);",
"score": 14.609348280389879
},
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 13.942331402217718
}
] | typescript | map((a, idx) => { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { Relay, relayInit, Sub } from "nostr-tools";
import "websocket-polyfill";
import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js";
import { NDKSubscription } from "../subscription/index.js";
import User from "../user/index.js";
import { NDKRelayScore } from "./score.js";
export enum NDKRelayStatus {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
RECONNECTING,
FLAPPING,
}
export interface NDKRelayConnectionStats {
/**
* The number of times a connection has been attempted.
*/
attempts: number;
/**
* The number of times a connection has been successfully established.
*/
success: number;
/**
* The durations of the last 100 connections in milliseconds.
*/
durations: number[];
/**
* The time the current connection was established in milliseconds.
*/
connectedAt?: number;
}
/**
* The NDKRelay class represents a connection to a relay.
*
* @emits NDKRelay#connect
* @emits NDKRelay#disconnect
* @emits NDKRelay#notice
* @emits NDKRelay#event
* @emits NDKRelay#published when an event is published to the relay
* @emits NDKRelay#publish:failed when an event fails to publish to the relay
* @emits NDKRelay#eose
*/
export class NDKRelay extends EventEmitter {
readonly url: string;
readonly scores: Map<User, NDKRelayScore>;
private relay: Relay;
private _status: NDKRelayStatus;
private connectedAt?: number;
private _connectionStats: NDKRelayConnectionStats = {
attempts: 0,
success: 0,
durations: [],
};
public complaining = false;
private debug: debug.Debugger;
/**
* Active subscriptions this relay is connected to
*/
public activeSubscriptions = new Set<NDKSubscription>();
public constructor(url: string) {
super();
this.url = url;
this.relay = relayInit(url);
this.scores = new Map<User, NDKRelayScore>();
this._status = NDKRelayStatus.DISCONNECTED;
this.debug = debug(`ndk:relay:${url}`);
this.relay.on("connect", () => {
this.updateConnectionStats.connected();
this._status = NDKRelayStatus.CONNECTED;
this.emit("connect");
});
this.relay.on("disconnect", () => {
this.updateConnectionStats.disconnected();
if (this._status === NDKRelayStatus.CONNECTED) {
this._status = NDKRelayStatus.DISCONNECTED;
this.handleReconnection();
}
this.emit("disconnect");
});
this.relay.on("notice", (notice: string) => this.handleNotice(notice));
}
/**
* Evaluates the connection stats to determine if the relay is flapping.
*/
private isFlapping(): boolean {
const durations = this._connectionStats.durations;
if (durations.length < 10) return false;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = sum / durations.length;
const variance =
durations
.map((x) => Math.pow(x - avg, 2))
.reduce((a, b) => a + b, 0) / durations.length;
const stdDev = Math.sqrt(variance);
const isFlapping = stdDev < 1000;
return isFlapping;
}
/**
* Called when the relay is unexpectedly disconnected.
*/
private handleReconnection() {
if (this.isFlapping()) {
this.emit("flapping", this, this._connectionStats);
this._status = NDKRelayStatus.FLAPPING;
}
if (this.connectedAt && Date.now() - this.connectedAt < 5000) {
setTimeout(() => this.connect(), 60000);
} else {
this.connect();
}
}
get status(): NDKRelayStatus {
return this._status;
}
/**
* Connects to the relay.
*/
public async connect(): Promise<void> {
try {
this.updateConnectionStats.attempt();
this._status = NDKRelayStatus.CONNECTING;
await this.relay.connect();
} catch (e) {
this.debug("Failed to connect", e);
this._status = NDKRelayStatus.DISCONNECTED;
throw e;
}
}
/**
* Disconnects from the relay.
*/
public disconnect(): void {
this._status = NDKRelayStatus.DISCONNECTING;
this.relay.close();
}
async handleNotice(notice: string) {
// This is a prototype; if the relay seems to be complaining
// remove it from relay set selection for a minute.
if (notice.includes("oo many") || notice.includes("aximum")) {
this.disconnect();
// fixme
setTimeout(() => this.connect(), 2000);
this.debug(this.relay.url, "Relay complaining?", notice);
// this.complaining = true;
// setTimeout(() => {
// this.complaining = false;
// console.log(this.relay.url, 'Reactivate relay');
// }, 60000);
}
this.emit("notice", this, notice);
}
/**
* Subscribes to a subscription.
*/
public subscribe(subscription: NDKSubscription): Sub {
const { filters } = subscription;
const sub = this.relay.sub(filters, {
id: subscription.subId,
});
this.debug(`Subscribed to ${JSON.stringify(filters)}`);
sub.on("event", (event: NostrEvent) => {
const e = new NDKEvent(undefined, event);
e.relay = this;
subscription.eventReceived(e, this);
});
sub.on("eose", () => {
subscription.eoseReceived(this);
});
const unsub = sub.unsub;
sub.unsub = () => {
this.debug(`Unsubscribing from ${JSON.stringify(filters)}`);
this.activeSubscriptions.delete(subscription);
unsub();
};
this.activeSubscriptions.add(subscription);
subscription.on("close", () => {
this.activeSubscriptions.delete(subscription);
});
return sub;
}
/**
* Publishes an event to the relay with an optional timeout.
*
* If the relay is not connected, the event will be published when the relay connects,
* unless the timeout is reached before the relay connects.
*
* @param event The event to publish
* @param timeoutMs The timeout for the publish operation in milliseconds
* @returns A promise that resolves when the event has been published or rejects if the operation times out
*/
| public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { |
if (this.status === NDKRelayStatus.CONNECTED) {
return this.publishEvent(event, timeoutMs);
} else {
this.once("connect", () => {
this.publishEvent(event, timeoutMs);
});
return true;
}
}
private async publishEvent(
event: NDKEvent,
timeoutMs?: number
): Promise<boolean> {
const nostrEvent = await event.toNostrEvent();
const publish = this.relay.publish(nostrEvent as any);
let publishTimeout: NodeJS.Timeout | number;
const publishPromise = new Promise<boolean>((resolve, reject) => {
publish
.then(() => {
clearTimeout(publishTimeout as unknown as NodeJS.Timeout);
this.emit("published", event);
resolve(true);
})
.catch((err) => {
clearTimeout(publishTimeout as NodeJS.Timeout);
this.debug("Publish failed", err, event.id);
this.emit("publish:failed", event, err);
reject(err);
});
});
// If no timeout is specified, just return the publish promise
if (!timeoutMs) {
return publishPromise;
}
// Create a promise that rejects after timeoutMs milliseconds
const timeoutPromise = new Promise<boolean>((_, reject) => {
publishTimeout = setTimeout(() => {
this.debug("Publish timed out", event.rawEvent());
this.emit("publish:failed", event, "Timeout");
reject(new Error("Publish operation timed out"));
}, timeoutMs);
});
// wait for either the publish operation to complete or the timeout to occur
return Promise.race([publishPromise, timeoutPromise]);
}
/**
* Called when this relay has responded with an event but
* wasn't the fastest one.
* @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public scoreSlowerEvent(timeDiffInMs: number): void {
// TODO
}
/**
* Utility functions to update the connection stats.
*/
private updateConnectionStats = {
connected: () => {
this._connectionStats.success++;
this._connectionStats.connectedAt = Date.now();
},
disconnected: () => {
if (this._connectionStats.connectedAt) {
this._connectionStats.durations.push(
Date.now() - this._connectionStats.connectedAt
);
if (this._connectionStats.durations.length > 100) {
this._connectionStats.durations.shift();
}
}
this._connectionStats.connectedAt = undefined;
},
attempt: () => {
this._connectionStats.attempts++;
},
};
/**
* Returns the connection stats.
*/
get connectionStats(): NDKRelayConnectionStats {
return this._connectionStats;
}
public tagReference(marker?: string): NDKTag {
const tag = ["r", this.relay.url];
if (marker) {
tag.push(marker);
}
return tag;
}
}
| src/relay/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,",
"score": 89.670577660749
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 88.76748735189895
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " * @returns {Promise<void>} A promise that resolves when all connection attempts have completed.\n * @throws {Error} If any of the connection attempts result in an error or timeout.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n const promises: Promise<void>[] = [];\n this.debug(\n `Connecting to ${this.relays.size} relays${\n timeoutMs ? `, timeout ${timeoutMs}...` : \"\"\n }`\n );",
"score": 66.25050483360486
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 65.51670260551597
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 65.4788489642293
}
] | typescript | public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { |
import type { RawGitCommit, RepoConfig } from './types';
export async function getGitHubRepo() {
const url = await execCommand('git', ['config', '--get', 'remote.origin.url']);
const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i);
if (!match) {
throw new Error(`Can not parse GitHub repo from url ${url}`);
}
return `${match[1]}/${match[2]}`;
}
export async function getGitMainBranchName() {
const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']);
return main;
}
export async function getCurrentGitBranch() {
const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']);
const main = getGitMainBranchName();
return result1 || main;
}
export async function isRepoShallow() {
return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true';
}
export async function getLastGitTag(delta = 0) {
const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n'));
return tags[tags.length + delta - 1];
}
export async function isRefGitTag(to: string) {
const { execa } = await import('execa');
try {
await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });
return true;
} catch {
return false;
}
}
export function getFirstGitCommit() {
return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']);
}
export function isPrerelease(version: string) {
return !/^[^.]*[\d.]+$/.test(version);
}
async function execCommand(cmd: string, args: string[]) {
const { execa } = await import('execa');
const res = await execa(cmd, args);
return res.stdout.trim();
}
export async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {
// https://git-scm.com/docs/pretty-formats
const r = await execCommand('git', [
'--no-pager',
'log',
`${from ? `${from}...` : ''}${to}`,
'--pretty="----%n%s|%h|%an|%ae%n%b"',
'--name-status'
]);
return r
.split('----\n')
.splice(1)
.map(line => {
const [firstLine, ..._body] = line.split('\n');
const [message, shortHash, authorName, authorEmail] = firstLine.split('|');
const $r: RawGitCommit = {
message,
shortHash,
author: { name: authorName, email: authorEmail },
body: _body.join('\n')
};
return $r;
});
}
export function getGitRemoteURL(cwd: string, remote = 'origin') {
return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);
}
export | function getGitPushUrl(config: RepoConfig, token?: string) { |
if (!token) return null;
return `https://${token}@${config.domain}/${config.repo}`;
}
| src/git.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/repo.ts",
"retrieved_chunk": " const pkg = await readPackageJSON(cwd).catch(() => {});\n if (pkg && pkg.repository) {\n const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;\n return getRepoConfig(url);\n }\n const gitRemote = await getGitRemoteURL(cwd).catch(() => {});\n if (gitRemote) {\n return getRepoConfig(gitRemote);\n }\n return {};",
"score": 14.371564381844514
},
{
"filename": "src/repo.ts",
"retrieved_chunk": " 'bitbucket.org': 'bitbucket'\n};\n// https://regex101.com/r/NA4Io6/1\nconst providerURLRegex = /^(?:(?<user>\\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\\w+\\/\\w+)(?:\\.git)?$/;\nfunction baseUrl(config: RepoConfig) {\n return `https://${config.domain}/${config.repo}`;\n}\nexport function formatReference(ref: Reference, repo?: RepoConfig) {\n if (!repo?.provider || !(repo.provider in providerToRefSpec)) {\n return ref.value;",
"score": 13.599590135879083
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease';\nexport type RepoProvider = 'github' | 'gitlab' | 'bitbucket';\nexport type RepoConfig = {\n domain?: string;\n repo?: string;\n provider?: RepoProvider;\n token?: string;\n};\nexport interface ChangelogConfig {\n cwd: string;",
"score": 12.911742285608767
},
{
"filename": "src/config.ts",
"retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;",
"score": 10.96425966084651
},
{
"filename": "src/repo.ts",
"retrieved_chunk": " }\n const refSpec = providerToRefSpec[repo.provider];\n return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;\n}\nexport function formatCompareChanges(v: string, config: ChangelogConfig) {\n const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';\n return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;\n}\nexport async function resolveRepoConfig(cwd: string) {\n // Try closest package.json",
"score": 10.594959009892762
}
] | typescript | function getGitPushUrl(config: RepoConfig, token?: string) { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { Relay, relayInit, Sub } from "nostr-tools";
import "websocket-polyfill";
import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js";
import { NDKSubscription } from "../subscription/index.js";
import User from "../user/index.js";
import { NDKRelayScore } from "./score.js";
export enum NDKRelayStatus {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
RECONNECTING,
FLAPPING,
}
export interface NDKRelayConnectionStats {
/**
* The number of times a connection has been attempted.
*/
attempts: number;
/**
* The number of times a connection has been successfully established.
*/
success: number;
/**
* The durations of the last 100 connections in milliseconds.
*/
durations: number[];
/**
* The time the current connection was established in milliseconds.
*/
connectedAt?: number;
}
/**
* The NDKRelay class represents a connection to a relay.
*
* @emits NDKRelay#connect
* @emits NDKRelay#disconnect
* @emits NDKRelay#notice
* @emits NDKRelay#event
* @emits NDKRelay#published when an event is published to the relay
* @emits NDKRelay#publish:failed when an event fails to publish to the relay
* @emits NDKRelay#eose
*/
export class NDKRelay extends EventEmitter {
readonly url: string;
readonly scores: Map<User, NDKRelayScore>;
private relay: Relay;
private _status: NDKRelayStatus;
private connectedAt?: number;
private _connectionStats: NDKRelayConnectionStats = {
attempts: 0,
success: 0,
durations: [],
};
public complaining = false;
private debug: debug.Debugger;
/**
* Active subscriptions this relay is connected to
*/
public activeSubscriptions = new Set<NDKSubscription>();
public constructor(url: string) {
super();
this.url = url;
this.relay = relayInit(url);
this.scores = new Map<User, NDKRelayScore>();
this._status = NDKRelayStatus.DISCONNECTED;
this.debug = debug(`ndk:relay:${url}`);
this.relay.on("connect", () => {
this.updateConnectionStats.connected();
this._status = NDKRelayStatus.CONNECTED;
this.emit("connect");
});
this.relay.on("disconnect", () => {
this.updateConnectionStats.disconnected();
if (this._status === NDKRelayStatus.CONNECTED) {
this._status = NDKRelayStatus.DISCONNECTED;
this.handleReconnection();
}
this.emit("disconnect");
});
this.relay.on("notice", (notice: string) => this.handleNotice(notice));
}
/**
* Evaluates the connection stats to determine if the relay is flapping.
*/
private isFlapping(): boolean {
const durations = this._connectionStats.durations;
if (durations.length < 10) return false;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = sum / durations.length;
const variance =
durations
.map((x) => Math.pow(x - avg, 2))
.reduce((a, b) => a + b, 0) / durations.length;
const stdDev = Math.sqrt(variance);
const isFlapping = stdDev < 1000;
return isFlapping;
}
/**
* Called when the relay is unexpectedly disconnected.
*/
private handleReconnection() {
if (this.isFlapping()) {
this.emit("flapping", this, this._connectionStats);
this._status = NDKRelayStatus.FLAPPING;
}
if (this.connectedAt && Date.now() - this.connectedAt < 5000) {
setTimeout(() => this.connect(), 60000);
} else {
this.connect();
}
}
get status(): NDKRelayStatus {
return this._status;
}
/**
* Connects to the relay.
*/
public async connect(): Promise<void> {
try {
this.updateConnectionStats.attempt();
this._status = NDKRelayStatus.CONNECTING;
await this.relay.connect();
} catch (e) {
this.debug("Failed to connect", e);
this._status = NDKRelayStatus.DISCONNECTED;
throw e;
}
}
/**
* Disconnects from the relay.
*/
public disconnect(): void {
this._status = NDKRelayStatus.DISCONNECTING;
this.relay.close();
}
async handleNotice(notice: string) {
// This is a prototype; if the relay seems to be complaining
// remove it from relay set selection for a minute.
if (notice.includes("oo many") || notice.includes("aximum")) {
this.disconnect();
// fixme
setTimeout(() => this.connect(), 2000);
this.debug(this.relay.url, "Relay complaining?", notice);
// this.complaining = true;
// setTimeout(() => {
// this.complaining = false;
// console.log(this.relay.url, 'Reactivate relay');
// }, 60000);
}
this.emit("notice", this, notice);
}
/**
* Subscribes to a subscription.
*/
public subscribe(subscription: NDKSubscription): Sub {
const { filters } = subscription;
const sub = this.relay.sub(filters, {
id: subscription.subId,
});
this.debug(`Subscribed to ${JSON.stringify(filters)}`);
sub.on("event", (event: NostrEvent) => {
const e = new NDKEvent(undefined, event);
e.relay = this;
subscription.eventReceived(e, this);
});
sub.on("eose", () => {
subscription.eoseReceived(this);
});
const unsub = sub.unsub;
sub.unsub = () => {
this.debug(`Unsubscribing from ${JSON.stringify(filters)}`);
this.activeSubscriptions.delete(subscription);
unsub();
};
this.activeSubscriptions.add(subscription);
subscription.on("close", () => {
this.activeSubscriptions.delete(subscription);
});
return sub;
}
/**
* Publishes an event to the relay with an optional timeout.
*
* If the relay is not connected, the event will be published when the relay connects,
* unless the timeout is reached before the relay connects.
*
* @param event The event to publish
* @param timeoutMs The timeout for the publish operation in milliseconds
* @returns A promise that resolves when the event has been published or rejects if the operation times out
*/
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
if (this.status === NDKRelayStatus.CONNECTED) {
return this.publishEvent(event, timeoutMs);
} else {
this.once("connect", () => {
this.publishEvent(event, timeoutMs);
});
return true;
}
}
private async publishEvent(
event: NDKEvent,
timeoutMs?: number
): Promise<boolean> {
const nostrEvent = await event.toNostrEvent();
const publish = this.relay.publish(nostrEvent as any);
let publishTimeout: NodeJS.Timeout | number;
const publishPromise = new Promise<boolean>((resolve, reject) => {
publish
.then(() => {
clearTimeout(publishTimeout as unknown as NodeJS.Timeout);
this.emit("published", event);
resolve(true);
})
.catch((err) => {
clearTimeout(publishTimeout as NodeJS.Timeout);
this.debug("Publish failed", err, event.id);
this.emit("publish:failed", event, err);
reject(err);
});
});
// If no timeout is specified, just return the publish promise
if (!timeoutMs) {
return publishPromise;
}
// Create a promise that rejects after timeoutMs milliseconds
const timeoutPromise = new Promise<boolean>((_, reject) => {
publishTimeout = setTimeout(() => {
this.debug("Publish timed out", event.rawEvent());
this.emit("publish:failed", event, "Timeout");
reject(new Error("Publish operation timed out"));
}, timeoutMs);
});
// wait for either the publish operation to complete or the timeout to occur
return Promise.race([publishPromise, timeoutPromise]);
}
/**
* Called when this relay has responded with an event but
* wasn't the fastest one.
* @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public scoreSlowerEvent(timeDiffInMs: number): void {
// TODO
}
/**
* Utility functions to update the connection stats.
*/
private updateConnectionStats = {
connected: () => {
this._connectionStats.success++;
this._connectionStats.connectedAt = Date.now();
},
disconnected: () => {
if (this._connectionStats.connectedAt) {
this._connectionStats.durations.push(
Date.now() - this._connectionStats.connectedAt
);
if (this._connectionStats.durations.length > 100) {
this._connectionStats.durations.shift();
}
}
this._connectionStats.connectedAt = undefined;
},
attempt: () => {
this._connectionStats.attempts++;
},
};
/**
* Returns the connection stats.
*/
get connectionStats(): NDKRelayConnectionStats {
return this._connectionStats;
}
public tagReference | (marker?: string): NDKTag { |
const tag = ["r", this.relay.url];
if (marker) {
tag.push(marker);
}
return tag;
}
}
| src/relay/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * ```typescript\n * reply.tag(opEvent, \"reply\");\n * // reply.tags => [[\"e\", <id>, <relay>, \"reply\"]]\n * ```\n */\n public tag(event: NDKEvent, marker?: string): void;\n public tag(userOrEvent: NDKUser | NDKEvent, marker?: string): void {\n const tag = userOrEvent.tagReference();\n if (marker) tag.push(marker);\n this.tags.push(tag);",
"score": 15.416822323994575
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " }\n public size(): number {\n return this.relays.size;\n }\n /**\n * Returns the status of each relay in the pool.\n * @returns {NDKPoolStats} An object containing the number of relays in each status.\n */\n public stats(): NDKPoolStats {\n const stats: NDKPoolStats = {",
"score": 14.197077910659052
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " /**\n * Get the tag that can be used to reference this user in an event\n * @returns {NDKTag} an NDKTag\n */\n public tagReference(): NDKTag {\n return [\"p\", this.hexpubkey()];\n }\n /**\n * Publishes the current profile.\n */",
"score": 14.00672689385784
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " this.emit(\"relay:connect\", this.relays.get(relayUrl));\n if (this.stats().connected === this.relays.size) {\n this.emit(\"connect\");\n }\n }\n /**\n * Attempts to establish a connection to each relay in the pool.\n *\n * @async\n * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.",
"score": 13.965406369318078
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " }\n /**\n * Returns the unecrypted items in this list.\n */\n get items(): NDKTag[] {\n return this.tags.filter((t) => {\n return ![\"d\", \"name\", \"description\"].includes(t[0]);\n });\n }\n /**",
"score": 13.803652656833947
}
] | typescript | (marker?: string): NDKTag { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions | , info: AuthorInfo) { |
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 15.669732009212105
},
{
"filename": "src/config.ts",
"retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,",
"score": 14.52034018911413
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 11.028523883691006
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 10.70870363578711
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### ${$name}`;",
"score": 8.848920113955117
}
] | typescript | , info: AuthorInfo) { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { Relay, relayInit, Sub } from "nostr-tools";
import "websocket-polyfill";
import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js";
import { NDKSubscription } from "../subscription/index.js";
import User from "../user/index.js";
import { NDKRelayScore } from "./score.js";
export enum NDKRelayStatus {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
RECONNECTING,
FLAPPING,
}
export interface NDKRelayConnectionStats {
/**
* The number of times a connection has been attempted.
*/
attempts: number;
/**
* The number of times a connection has been successfully established.
*/
success: number;
/**
* The durations of the last 100 connections in milliseconds.
*/
durations: number[];
/**
* The time the current connection was established in milliseconds.
*/
connectedAt?: number;
}
/**
* The NDKRelay class represents a connection to a relay.
*
* @emits NDKRelay#connect
* @emits NDKRelay#disconnect
* @emits NDKRelay#notice
* @emits NDKRelay#event
* @emits NDKRelay#published when an event is published to the relay
* @emits NDKRelay#publish:failed when an event fails to publish to the relay
* @emits NDKRelay#eose
*/
export class NDKRelay extends EventEmitter {
readonly url: string;
readonly scores: Map<User, NDKRelayScore>;
private relay: Relay;
private _status: NDKRelayStatus;
private connectedAt?: number;
private _connectionStats: NDKRelayConnectionStats = {
attempts: 0,
success: 0,
durations: [],
};
public complaining = false;
private debug: debug.Debugger;
/**
* Active subscriptions this relay is connected to
*/
public | activeSubscriptions = new Set<NDKSubscription>(); |
public constructor(url: string) {
super();
this.url = url;
this.relay = relayInit(url);
this.scores = new Map<User, NDKRelayScore>();
this._status = NDKRelayStatus.DISCONNECTED;
this.debug = debug(`ndk:relay:${url}`);
this.relay.on("connect", () => {
this.updateConnectionStats.connected();
this._status = NDKRelayStatus.CONNECTED;
this.emit("connect");
});
this.relay.on("disconnect", () => {
this.updateConnectionStats.disconnected();
if (this._status === NDKRelayStatus.CONNECTED) {
this._status = NDKRelayStatus.DISCONNECTED;
this.handleReconnection();
}
this.emit("disconnect");
});
this.relay.on("notice", (notice: string) => this.handleNotice(notice));
}
/**
* Evaluates the connection stats to determine if the relay is flapping.
*/
private isFlapping(): boolean {
const durations = this._connectionStats.durations;
if (durations.length < 10) return false;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = sum / durations.length;
const variance =
durations
.map((x) => Math.pow(x - avg, 2))
.reduce((a, b) => a + b, 0) / durations.length;
const stdDev = Math.sqrt(variance);
const isFlapping = stdDev < 1000;
return isFlapping;
}
/**
* Called when the relay is unexpectedly disconnected.
*/
private handleReconnection() {
if (this.isFlapping()) {
this.emit("flapping", this, this._connectionStats);
this._status = NDKRelayStatus.FLAPPING;
}
if (this.connectedAt && Date.now() - this.connectedAt < 5000) {
setTimeout(() => this.connect(), 60000);
} else {
this.connect();
}
}
get status(): NDKRelayStatus {
return this._status;
}
/**
* Connects to the relay.
*/
public async connect(): Promise<void> {
try {
this.updateConnectionStats.attempt();
this._status = NDKRelayStatus.CONNECTING;
await this.relay.connect();
} catch (e) {
this.debug("Failed to connect", e);
this._status = NDKRelayStatus.DISCONNECTED;
throw e;
}
}
/**
* Disconnects from the relay.
*/
public disconnect(): void {
this._status = NDKRelayStatus.DISCONNECTING;
this.relay.close();
}
async handleNotice(notice: string) {
// This is a prototype; if the relay seems to be complaining
// remove it from relay set selection for a minute.
if (notice.includes("oo many") || notice.includes("aximum")) {
this.disconnect();
// fixme
setTimeout(() => this.connect(), 2000);
this.debug(this.relay.url, "Relay complaining?", notice);
// this.complaining = true;
// setTimeout(() => {
// this.complaining = false;
// console.log(this.relay.url, 'Reactivate relay');
// }, 60000);
}
this.emit("notice", this, notice);
}
/**
* Subscribes to a subscription.
*/
public subscribe(subscription: NDKSubscription): Sub {
const { filters } = subscription;
const sub = this.relay.sub(filters, {
id: subscription.subId,
});
this.debug(`Subscribed to ${JSON.stringify(filters)}`);
sub.on("event", (event: NostrEvent) => {
const e = new NDKEvent(undefined, event);
e.relay = this;
subscription.eventReceived(e, this);
});
sub.on("eose", () => {
subscription.eoseReceived(this);
});
const unsub = sub.unsub;
sub.unsub = () => {
this.debug(`Unsubscribing from ${JSON.stringify(filters)}`);
this.activeSubscriptions.delete(subscription);
unsub();
};
this.activeSubscriptions.add(subscription);
subscription.on("close", () => {
this.activeSubscriptions.delete(subscription);
});
return sub;
}
/**
* Publishes an event to the relay with an optional timeout.
*
* If the relay is not connected, the event will be published when the relay connects,
* unless the timeout is reached before the relay connects.
*
* @param event The event to publish
* @param timeoutMs The timeout for the publish operation in milliseconds
* @returns A promise that resolves when the event has been published or rejects if the operation times out
*/
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
if (this.status === NDKRelayStatus.CONNECTED) {
return this.publishEvent(event, timeoutMs);
} else {
this.once("connect", () => {
this.publishEvent(event, timeoutMs);
});
return true;
}
}
private async publishEvent(
event: NDKEvent,
timeoutMs?: number
): Promise<boolean> {
const nostrEvent = await event.toNostrEvent();
const publish = this.relay.publish(nostrEvent as any);
let publishTimeout: NodeJS.Timeout | number;
const publishPromise = new Promise<boolean>((resolve, reject) => {
publish
.then(() => {
clearTimeout(publishTimeout as unknown as NodeJS.Timeout);
this.emit("published", event);
resolve(true);
})
.catch((err) => {
clearTimeout(publishTimeout as NodeJS.Timeout);
this.debug("Publish failed", err, event.id);
this.emit("publish:failed", event, err);
reject(err);
});
});
// If no timeout is specified, just return the publish promise
if (!timeoutMs) {
return publishPromise;
}
// Create a promise that rejects after timeoutMs milliseconds
const timeoutPromise = new Promise<boolean>((_, reject) => {
publishTimeout = setTimeout(() => {
this.debug("Publish timed out", event.rawEvent());
this.emit("publish:failed", event, "Timeout");
reject(new Error("Publish operation timed out"));
}, timeoutMs);
});
// wait for either the publish operation to complete or the timeout to occur
return Promise.race([publishPromise, timeoutPromise]);
}
/**
* Called when this relay has responded with an event but
* wasn't the fastest one.
* @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public scoreSlowerEvent(timeDiffInMs: number): void {
// TODO
}
/**
* Utility functions to update the connection stats.
*/
private updateConnectionStats = {
connected: () => {
this._connectionStats.success++;
this._connectionStats.connectedAt = Date.now();
},
disconnected: () => {
if (this._connectionStats.connectedAt) {
this._connectionStats.durations.push(
Date.now() - this._connectionStats.connectedAt
);
if (this._connectionStats.durations.length > 100) {
this._connectionStats.durations.shift();
}
}
this._connectionStats.connectedAt = undefined;
},
attempt: () => {
this._connectionStats.attempts++;
},
};
/**
* Returns the connection stats.
*/
get connectionStats(): NDKRelayConnectionStats {
return this._connectionStats;
}
public tagReference(marker?: string): NDKTag {
const tag = ["r", this.relay.url];
if (marker) {
tag.push(marker);
}
return tag;
}
}
| src/relay/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }",
"score": 24.75274323449968
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " private executeSubscriptions(subscriptions: NDKSubscription[]) {\n const ndk = subscriptions[0].ndk;\n const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);\n this.executeSubscription(subGroup);\n }\n private executeSubscription(\n subscription: NDKSubscription\n ): NDKSubscription {\n this.debug(\"subscribing\", { filters: subscription.filters });\n for (const relay of this.relays) {",
"score": 24.064915651506936
},
{
"filename": "src/relay/sets/calculate.ts",
"retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);",
"score": 23.36938454515846
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);",
"score": 22.35193825887952
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": "}\nexport class NDKNostrRpc extends EventEmitter {\n private ndk: NDK;\n private signer: NDKSigner;\n private debug: debug.Debugger;\n public constructor(ndk: NDK, signer: NDKSigner, debug: debug.Debugger) {\n super();\n this.ndk = ndk;\n this.signer = signer;\n this.debug = debug.extend(\"rpc\");",
"score": 22.10735274723893
}
] | typescript | activeSubscriptions = new Set<NDKSubscription>(); |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a | , idx) => { |
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 22.669824976509382
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 21.9725908787624
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 20.912437582203474
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " array.forEach((e, idx, arr) => {\n let i = 0;\n for (const filter of filters) {\n if (filter(e, idx, arr)) {\n result[i].push(e);\n return;\n }\n i += 1;\n }\n result[i].push(e);",
"score": 14.609348280389879
},
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 13.942331402217718
}
] | typescript | , idx) => { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import NDK from "../../index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
export type NDKPoolStats = {
total: number;
connected: number;
disconnected: number;
connecting: number;
};
/**
* Handles connections to all relays. A single pool should be used per NDK instance.
*
* @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.
* @emit notice - Emitted when a relay in the pool sends a notice.
* @emit flapping - Emitted when a relay in the pool is flapping.
* @emit relay:connect - Emitted when a relay in the pool connects.
* @emit relay:disconnect - Emitted when a relay in the pool disconnects.
*/
export class NDKPool extends EventEmitter {
public relays = new Map<string, NDKRelay>();
private debug: debug.Debugger;
private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();
public constructor(relayUrls: string[] = [], ndk: NDK) {
super();
this.debug = ndk.debug.extend("pool");
for (const relayUrl of relayUrls) {
const relay = new NDKRelay(relayUrl);
this.addRelay(relay, false);
}
}
/**
* Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time.
* @param relay - The relay to add to the pool.
* @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used.
*/
| public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { |
const relayAlreadyInPool = this.relays.has(relay.url);
// check if the relay is already in the pool
if (!relayAlreadyInPool) {
this.addRelay(relay);
}
// check if the relay already has a disconnecting timer
const existingTimer = this.temporaryRelayTimers.get(relay.url);
if (existingTimer) {
clearTimeout(existingTimer);
}
// add a disconnecting timer only if the relay was not already in the pool
// or if it had an existing timer
// this prevents explicit relays from being removed from the pool
if (!relayAlreadyInPool || existingTimer) {
// set a timer to remove the relay from the pool if it is not used within the specified time
const timer = setTimeout(() => {
this.removeRelay(relay.url);
}, removeIfUnusedAfter) as unknown as NodeJS.Timeout;
this.temporaryRelayTimers.set(relay.url, timer);
}
}
/**
* Adds a relay to the pool.
*
* @param relay - The relay to add to the pool.
* @param connect - Whether or not to connect to the relay.
*/
public addRelay(relay: NDKRelay, connect = true) {
const relayUrl = relay.url;
relay.on("notice", (relay, notice) =>
this.emit("notice", relay, notice)
);
relay.on("connect", () => this.handleRelayConnect(relayUrl));
relay.on("disconnect", () => this.emit("relay:disconnect", relay));
relay.on("flapping", () => this.handleFlapping(relay));
this.relays.set(relayUrl, relay);
if (connect) {
relay.connect();
}
}
/**
* Removes a relay from the pool.
* @param relayUrl - The URL of the relay to remove.
* @returns {boolean} True if the relay was removed, false if it was not found.
*/
public removeRelay(relayUrl: string): boolean {
const relay = this.relays.get(relayUrl);
if (relay) {
relay.disconnect();
this.relays.delete(relayUrl);
this.emit("relay:disconnect", relay);
return true;
}
// remove the relay from the temporary relay timers
const existingTimer = this.temporaryRelayTimers.get(relayUrl);
if (existingTimer) {
clearTimeout(existingTimer);
this.temporaryRelayTimers.delete(relayUrl);
}
return false;
}
private handleRelayConnect(relayUrl: string) {
this.debug(`Relay ${relayUrl} connected`);
this.emit("relay:connect", this.relays.get(relayUrl));
if (this.stats().connected === this.relays.size) {
this.emit("connect");
}
}
/**
* Attempts to establish a connection to each relay in the pool.
*
* @async
* @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.
* @returns {Promise<void>} A promise that resolves when all connection attempts have completed.
* @throws {Error} If any of the connection attempts result in an error or timeout.
*/
public async connect(timeoutMs?: number): Promise<void> {
const promises: Promise<void>[] = [];
this.debug(
`Connecting to ${this.relays.size} relays${
timeoutMs ? `, timeout ${timeoutMs}...` : ""
}`
);
for (const relay of this.relays.values()) {
if (timeoutMs) {
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(
() => reject(`Timed out after ${timeoutMs}ms`),
timeoutMs
);
});
promises.push(
Promise.race([relay.connect(), timeoutPromise]).catch(
(e) => {
this.debug(
`Failed to connect to relay ${relay.url}: ${e}`
);
}
)
);
} else {
promises.push(relay.connect());
}
}
// If we are running with a timeout, check if we need to emit a `connect` event
// in case some, but not all, relays were connected
if (timeoutMs) {
setTimeout(() => {
const allConnected =
this.stats().connected === this.relays.size;
const someConnected = this.stats().connected > 0;
if (!allConnected && someConnected) {
this.emit("connect");
}
}, timeoutMs);
}
await Promise.all(promises);
}
private handleFlapping(relay: NDKRelay) {
this.debug(`Relay ${relay.url} is flapping`);
// TODO: Be smarter about this.
this.relays.delete(relay.url);
this.emit("flapping", relay);
}
public size(): number {
return this.relays.size;
}
/**
* Returns the status of each relay in the pool.
* @returns {NDKPoolStats} An object containing the number of relays in each status.
*/
public stats(): NDKPoolStats {
const stats: NDKPoolStats = {
total: 0,
connected: 0,
disconnected: 0,
connecting: 0,
};
for (const relay of this.relays.values()) {
stats.total++;
if (relay.status === NDKRelayStatus.CONNECTED) {
stats.connected++;
} else if (relay.status === NDKRelayStatus.DISCONNECTED) {
stats.disconnected++;
} else if (relay.status === NDKRelayStatus.CONNECTING) {
stats.connecting++;
}
}
return stats;
}
public connectedRelays(): NDKRelay[] {
return Array.from(this.relays.values()).filter(
(relay) => relay.status === NDKRelayStatus.CONNECTED
);
}
/**
* Get a list of all relay urls in the pool.
*/
public urls(): string[] {
return Array.from(this.relays.keys());
}
}
| src/relay/pool/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/sets/utils.ts",
"retrieved_chunk": "import { NDKPool } from \"../../relay/pool/index.js\";\nimport { NDKRelaySet } from \"../../relay/sets/index.js\";\n/**\n * If the provided relay set does not include connected relays in the pool\n * the relaySet will have the connected relays added to it.\n */\nexport function correctRelaySet(\n relaySet: NDKRelaySet,\n pool: NDKPool\n): NDKRelaySet {",
"score": 59.457677328953324
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,",
"score": 56.842841177525415
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * The time the current connection was established in milliseconds.\n */\n connectedAt?: number;\n}\n/**\n * The NDKRelay class represents a connection to a relay.\n *\n * @emits NDKRelay#connect\n * @emits NDKRelay#disconnect\n * @emits NDKRelay#notice",
"score": 54.973747468420896
},
{
"filename": "src/relay/sets/calculate.ts",
"retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);",
"score": 53.14324619672538
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 53.02295776503044
}
] | typescript | public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
| const description = options.capitalize ? capitalize(commit.description) : commit.description; |
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const [breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " const nameSet = new Set<string>();\n return resolved\n .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))\n .filter(i => {\n if (i.login && loginSet.has(i.login)) {\n return false;\n }\n if (i.login) {\n loginSet.add(i.login);\n } else {",
"score": 46.77787969309027
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };",
"score": 43.786869254615695
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 35.65999072992281
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 34.94122202494962
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " array.forEach((e, idx, arr) => {\n let i = 0;\n for (const filter of filters) {\n if (filter(e, idx, arr)) {\n result[i].push(e);\n return;\n }\n i += 1;\n }\n result[i].push(e);",
"score": 33.005209810399954
}
] | typescript | const description = options.capitalize ? capitalize(commit.description) : commit.description; |
import debug from "debug";
import EventEmitter from "eventemitter3";
import NDK from "../../index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
export type NDKPoolStats = {
total: number;
connected: number;
disconnected: number;
connecting: number;
};
/**
* Handles connections to all relays. A single pool should be used per NDK instance.
*
* @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.
* @emit notice - Emitted when a relay in the pool sends a notice.
* @emit flapping - Emitted when a relay in the pool is flapping.
* @emit relay:connect - Emitted when a relay in the pool connects.
* @emit relay:disconnect - Emitted when a relay in the pool disconnects.
*/
export class NDKPool extends EventEmitter {
public relays = new Map<string, NDKRelay>();
private debug: debug.Debugger;
private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();
public constructor(relayUrls: string[] = [], ndk: NDK) {
super();
this.debug = ndk.debug.extend("pool");
for (const relayUrl of relayUrls) {
const relay = new NDKRelay(relayUrl);
this.addRelay(relay, false);
}
}
/**
* Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time.
* @param relay - The relay to add to the pool.
* @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used.
*/
public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) {
const relayAlreadyInPool = this.relays.has(relay.url);
// check if the relay is already in the pool
if (!relayAlreadyInPool) {
this.addRelay(relay);
}
// check if the relay already has a disconnecting timer
const existingTimer = this.temporaryRelayTimers.get(relay.url);
if (existingTimer) {
clearTimeout(existingTimer);
}
// add a disconnecting timer only if the relay was not already in the pool
// or if it had an existing timer
// this prevents explicit relays from being removed from the pool
if (!relayAlreadyInPool || existingTimer) {
// set a timer to remove the relay from the pool if it is not used within the specified time
const timer = setTimeout(() => {
this.removeRelay(relay.url);
}, removeIfUnusedAfter) as unknown as NodeJS.Timeout;
this.temporaryRelayTimers.set(relay.url, timer);
}
}
/**
* Adds a relay to the pool.
*
* @param relay - The relay to add to the pool.
* @param connect - Whether or not to connect to the relay.
*/
public addRelay(relay: NDKRelay, connect = true) {
const relayUrl = relay.url;
| relay.on("notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
relay.on("connect", () => this.handleRelayConnect(relayUrl));
relay.on("disconnect", () => this.emit("relay:disconnect", relay));
relay.on("flapping", () => this.handleFlapping(relay));
this.relays.set(relayUrl, relay);
if (connect) {
relay.connect();
}
}
/**
* Removes a relay from the pool.
* @param relayUrl - The URL of the relay to remove.
* @returns {boolean} True if the relay was removed, false if it was not found.
*/
public removeRelay(relayUrl: string): boolean {
const relay = this.relays.get(relayUrl);
if (relay) {
relay.disconnect();
this.relays.delete(relayUrl);
this.emit("relay:disconnect", relay);
return true;
}
// remove the relay from the temporary relay timers
const existingTimer = this.temporaryRelayTimers.get(relayUrl);
if (existingTimer) {
clearTimeout(existingTimer);
this.temporaryRelayTimers.delete(relayUrl);
}
return false;
}
private handleRelayConnect(relayUrl: string) {
this.debug(`Relay ${relayUrl} connected`);
this.emit("relay:connect", this.relays.get(relayUrl));
if (this.stats().connected === this.relays.size) {
this.emit("connect");
}
}
/**
* Attempts to establish a connection to each relay in the pool.
*
* @async
* @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.
* @returns {Promise<void>} A promise that resolves when all connection attempts have completed.
* @throws {Error} If any of the connection attempts result in an error or timeout.
*/
public async connect(timeoutMs?: number): Promise<void> {
const promises: Promise<void>[] = [];
this.debug(
`Connecting to ${this.relays.size} relays${
timeoutMs ? `, timeout ${timeoutMs}...` : ""
}`
);
for (const relay of this.relays.values()) {
if (timeoutMs) {
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(
() => reject(`Timed out after ${timeoutMs}ms`),
timeoutMs
);
});
promises.push(
Promise.race([relay.connect(), timeoutPromise]).catch(
(e) => {
this.debug(
`Failed to connect to relay ${relay.url}: ${e}`
);
}
)
);
} else {
promises.push(relay.connect());
}
}
// If we are running with a timeout, check if we need to emit a `connect` event
// in case some, but not all, relays were connected
if (timeoutMs) {
setTimeout(() => {
const allConnected =
this.stats().connected === this.relays.size;
const someConnected = this.stats().connected > 0;
if (!allConnected && someConnected) {
this.emit("connect");
}
}, timeoutMs);
}
await Promise.all(promises);
}
private handleFlapping(relay: NDKRelay) {
this.debug(`Relay ${relay.url} is flapping`);
// TODO: Be smarter about this.
this.relays.delete(relay.url);
this.emit("flapping", relay);
}
public size(): number {
return this.relays.size;
}
/**
* Returns the status of each relay in the pool.
* @returns {NDKPoolStats} An object containing the number of relays in each status.
*/
public stats(): NDKPoolStats {
const stats: NDKPoolStats = {
total: 0,
connected: 0,
disconnected: 0,
connecting: 0,
};
for (const relay of this.relays.values()) {
stats.total++;
if (relay.status === NDKRelayStatus.CONNECTED) {
stats.connected++;
} else if (relay.status === NDKRelayStatus.DISCONNECTED) {
stats.disconnected++;
} else if (relay.status === NDKRelayStatus.CONNECTING) {
stats.connecting++;
}
}
return stats;
}
public connectedRelays(): NDKRelay[] {
return Array.from(this.relays.values()).filter(
(relay) => relay.status === NDKRelayStatus.CONNECTED
);
}
/**
* Get a list of all relay urls in the pool.
*/
public urls(): string[] {
return Array.from(this.relays.keys());
}
}
| src/relay/pool/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // remove it from relay set selection for a minute.\n if (notice.includes(\"oo many\") || notice.includes(\"aximum\")) {\n this.disconnect();\n // fixme\n setTimeout(() => this.connect(), 2000);\n this.debug(this.relay.url, \"Relay complaining?\", notice);\n // this.complaining = true;\n // setTimeout(() => {\n // this.complaining = false;\n // console.log(this.relay.url, 'Reactivate relay');",
"score": 70.56125654919558
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " this.emit(\"disconnect\");\n });\n this.relay.on(\"notice\", (notice: string) => this.handleNotice(notice));\n }\n /**\n * Evaluates the connection stats to determine if the relay is flapping.\n */\n private isFlapping(): boolean {\n const durations = this._connectionStats.durations;\n if (durations.length < 10) return false;",
"score": 65.17775354042824
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * The time the current connection was established in milliseconds.\n */\n connectedAt?: number;\n}\n/**\n * The NDKRelay class represents a connection to a relay.\n *\n * @emits NDKRelay#connect\n * @emits NDKRelay#disconnect\n * @emits NDKRelay#notice",
"score": 62.421759284571614
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 59.779509898607294
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " }\n /**\n * Disconnects from the relay.\n */\n public disconnect(): void {\n this._status = NDKRelayStatus.DISCONNECTING;\n this.relay.close();\n }\n async handleNotice(notice: string) {\n // This is a prototype; if the relay seems to be complaining",
"score": 58.042078639794326
}
] | typescript | relay.on("notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
| const scopes = groupBy(commits, 'scope'); |
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const [breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/cli.ts",
"retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/ /g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));",
"score": 23.20689029834491
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 21.825070537390918
},
{
"filename": "src/github.ts",
"retrieved_chunk": " info.login = data.items[0].login;\n } catch {}\n if (info.login) return info;\n if (info.commits.length) {\n try {\n const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {\n headers: getHeaders(options)\n });\n info.login = data.author.login;\n } catch (e) {}",
"score": 16.740685331765867
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };",
"score": 16.664456991834065
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n if (!map.has(a.email)) {\n map.set(a.email, {\n commits: [],\n name: a.name,\n email: a.email\n });\n }\n const info = map.get(a.email)!;\n // record commits only for the first author",
"score": 16.11812668214124
}
] | typescript | const scopes = groupBy(commits, 'scope'); |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
| if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { |
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const [breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " info.login = data.items[0].login;\n } catch {}\n if (info.login) return info;\n if (info.commits.length) {\n try {\n const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {\n headers: getHeaders(options)\n });\n info.login = data.author.login;\n } catch (e) {}",
"score": 23.990281481518075
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 22.26256252174178
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n if (!map.has(a.email)) {\n map.set(a.email, {\n commits: [],\n name: a.name,\n email: a.email\n });\n }\n const info = map.get(a.email)!;\n // record commits only for the first author",
"score": 20.496172474451487
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " });\n return result;\n}\nexport function notNullish<T>(v?: T | null): v is NonNullable<T> {\n return v !== null && v !== undefined;\n}\nexport function groupBy<T>(items: T[], key: string, groups: Record<string, T[]> = {}) {\n for (const item of items) {\n const v = (item as any)[key] as string;\n groups[v] = groups[v] || [];",
"score": 20.114045147230925
},
{
"filename": "src/cli.ts",
"retrieved_chunk": " .option('--capitalize', 'Should capitalize for each comment message')\n .option('--emoji', 'Use emojis in section titles', { default: true })\n .option('--group', 'Nest commit messages under their scopes')\n .option('--dry', 'Dry run')\n .help();\ncli.command('').action(async (args: any) => {\n try {\n console.log();\n console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));\n const cwd = process.cwd();",
"score": 18.65181700581028
}
] | typescript | if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse | ().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); |
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const [breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 39.67399459945425
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 35.53562943450217
},
{
"filename": "src/types.ts",
"retrieved_chunk": " tag_name: string;\n name?: string;\n body?: string;\n draft?: boolean;\n prerelease?: boolean;\n}\nexport interface GitCommit extends RawGitCommit {\n description: string;\n type: string;\n scope: string;",
"score": 19.6471723457862
},
{
"filename": "src/types.ts",
"retrieved_chunk": " breakingChanges?: string;\n };\n /**\n * Capitalize commit messages\n * @default true\n */\n capitalize?: boolean;\n /**\n * Nest commit messages under their scopes\n * @default true",
"score": 17.76829460969813
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 17.39376523231823
}
] | typescript | ().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); |
import { notNullish } from './shared';
import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types';
// https://www.conventionalcommits.org/en/v1.0.0/
// https://regex101.com/r/FSfNvA/1
const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i;
const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim;
const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm;
const IssueRE = /(#\d+)/gm;
export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {
const match = commit.message.match(ConventionalCommitRegex);
if (!match?.groups) {
return null;
}
const type = match.groups.type;
let scope = match.groups.scope || '';
scope = config.scopeMap[scope] || scope;
const isBreaking = Boolean(match.groups.breaking);
let description = match.groups.description;
// Extract references from message
const references: Reference[] = [];
for (const m of description.matchAll(PullRequestRE)) {
references.push({ type: 'pull-request', value: m[1] });
}
for (const m of description.matchAll(IssueRE)) {
if (!references.some(i => i.value === m[1])) {
references.push({ type: 'issue', value: m[1] });
}
}
references.push({ value: commit.shortHash, type: 'hash' });
// Remove references and normalize
description = description.replace(PullRequestRE, '').trim();
// Find all authors
| const authors: GitCommitAuthor[] = [commit.author]; |
const matchs = commit.body.matchAll(CoAuthoredByRegex);
for (const $match of matchs) {
const { name = '', email = '' } = $match.groups || {};
const author: GitCommitAuthor = {
name: name.trim(),
email: email.trim()
};
authors.push(author);
}
return {
...commit,
authors,
description,
type,
scope,
references,
isBreaking
};
}
export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {
return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);
}
| src/parse.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 39.3343735304053
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### ${$name}`;",
"score": 36.718768019144065
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 32.91614545389348
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 28.993998901506725
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';",
"score": 28.25245589791652
}
] | typescript | const authors: GitCommitAuthor[] = [commit.author]; |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const [breaking, changes] = partition(commits | , c => c.isBreaking); |
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 23.33437038612311
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 19.110776817266046
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 17.119198115235363
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 16.059821876998978
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 13.93575441031903
}
] | typescript | , c => c.isBreaking); |
import { readPackageJSON } from 'pkg-types';
import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';
import { getGitRemoteURL } from './git';
const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {
github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },
gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },
bitbucket: {
'pull-request': 'pull-requests',
hash: 'commit',
issue: 'issues'
}
};
const providerToDomain: Record<RepoProvider, string> = {
github: 'github.com',
gitlab: 'gitlab.com',
bitbucket: 'bitbucket.org'
};
const domainToProvider: Record<string, RepoProvider> = {
'github.com': 'github',
'gitlab.com': 'gitlab',
'bitbucket.org': 'bitbucket'
};
// https://regex101.com/r/NA4Io6/1
const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/;
function baseUrl(config: RepoConfig) {
return `https://${config.domain}/${config.repo}`;
}
export function formatReference(ref: Reference, repo?: RepoConfig) {
if (!repo?.provider || !(repo.provider in providerToRefSpec)) {
return ref.value;
}
const refSpec = providerToRefSpec[repo.provider];
return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;
}
| export function formatCompareChanges(v: string, config: ChangelogConfig) { |
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;
}
export async function resolveRepoConfig(cwd: string) {
// Try closest package.json
const pkg = await readPackageJSON(cwd).catch(() => {});
if (pkg && pkg.repository) {
const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;
return getRepoConfig(url);
}
const gitRemote = await getGitRemoteURL(cwd).catch(() => {});
if (gitRemote) {
return getRepoConfig(gitRemote);
}
return {};
}
export function getRepoConfig(repoUrl = ''): RepoConfig {
let provider: RepoProvider | undefined;
let repo: string | undefined;
let domain: string | undefined;
let url: URL | undefined;
try {
url = new URL(repoUrl);
} catch {}
const m = repoUrl.match(providerURLRegex)?.groups ?? {};
if (m.repo && m.provider) {
repo = m.repo;
provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider);
domain = provider in providerToDomain ? providerToDomain[provider] : provider;
} else if (url) {
domain = url.hostname;
repo = url.pathname
.split('/')
.slice(1, 3)
.join('/')
.replace(/\.git$/, '');
provider = domainToProvider[domain];
} else if (m.repo) {
repo = m.repo;
provider = 'github';
domain = providerToDomain[provider];
}
return {
provider,
repo,
domain
};
}
| src/repo.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 43.28591573337019
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 38.293322879243675
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease';\nexport type RepoProvider = 'github' | 'gitlab' | 'bitbucket';\nexport type RepoConfig = {\n domain?: string;\n repo?: string;\n provider?: RepoProvider;\n token?: string;\n};\nexport interface ChangelogConfig {\n cwd: string;",
"score": 33.6059619169737
},
{
"filename": "src/github.ts",
"retrieved_chunk": " await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {\n headers: getHeaders(options)\n });\n return true;\n } catch (e) {\n return false;\n }\n}",
"score": 28.40761011929844
},
{
"filename": "src/git.ts",
"retrieved_chunk": " return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);\n}\nexport function getGitPushUrl(config: RepoConfig, token?: string) {\n if (!token) return null;\n return `https://${token}@${config.domain}/${config.repo}`;\n}",
"score": 28.1896601297737
}
] | typescript | export function formatCompareChanges(v: string, config: ChangelogConfig) { |
import { notNullish } from './shared';
import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types';
// https://www.conventionalcommits.org/en/v1.0.0/
// https://regex101.com/r/FSfNvA/1
const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i;
const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim;
const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm;
const IssueRE = /(#\d+)/gm;
export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {
const match = commit.message.match(ConventionalCommitRegex);
if (!match?.groups) {
return null;
}
const type = match.groups.type;
let scope = match.groups.scope || '';
scope = config.scopeMap[scope] || scope;
const isBreaking = Boolean(match.groups.breaking);
let description = match.groups.description;
// Extract references from message
const references: Reference[] = [];
for (const m of description.matchAll(PullRequestRE)) {
references.push({ type: 'pull-request', value: m[1] });
}
for (const m of description.matchAll(IssueRE)) {
if (!references.some(i => i.value === m[1])) {
references.push({ type: 'issue', value: m[1] });
}
}
references.push({ value: commit.shortHash, type: 'hash' });
// Remove references and normalize
description = description.replace(PullRequestRE, '').trim();
// Find all authors
const authors: GitCommitAuthor[] = [commit.author];
const matchs = commit.body.matchAll(CoAuthoredByRegex);
for (const $match of matchs) {
const { name = '', email = '' } = $match.groups || {};
const author: GitCommitAuthor = {
name: name.trim(),
email: email.trim()
};
authors.push(author);
}
return {
...commit,
authors,
description,
type,
scope,
references,
isBreaking
};
}
export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {
return commits | .map(commit => parseGitCommit(commit, config)).filter(notNullish); |
}
| src/parse.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/types.ts",
"retrieved_chunk": " tag_name: string;\n name?: string;\n body?: string;\n draft?: boolean;\n prerelease?: boolean;\n}\nexport interface GitCommit extends RawGitCommit {\n description: string;\n type: string;\n scope: string;",
"score": 16.590909232605256
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 16.46374176856977
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 15.59866017461801
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 15.128867140035831
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### ${$name}`;",
"score": 13.888048039458031
}
] | typescript | .map(commit => parseGitCommit(commit, config)).filter(notNullish); |
import type { RawGitCommit, RepoConfig } from './types';
export async function getGitHubRepo() {
const url = await execCommand('git', ['config', '--get', 'remote.origin.url']);
const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i);
if (!match) {
throw new Error(`Can not parse GitHub repo from url ${url}`);
}
return `${match[1]}/${match[2]}`;
}
export async function getGitMainBranchName() {
const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']);
return main;
}
export async function getCurrentGitBranch() {
const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']);
const main = getGitMainBranchName();
return result1 || main;
}
export async function isRepoShallow() {
return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true';
}
export async function getLastGitTag(delta = 0) {
const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n'));
return tags[tags.length + delta - 1];
}
export async function isRefGitTag(to: string) {
const { execa } = await import('execa');
try {
await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });
return true;
} catch {
return false;
}
}
export function getFirstGitCommit() {
return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']);
}
export function isPrerelease(version: string) {
return !/^[^.]*[\d.]+$/.test(version);
}
async function execCommand(cmd: string, args: string[]) {
const { execa } = await import('execa');
const res = await execa(cmd, args);
return res.stdout.trim();
}
export async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {
// https://git-scm.com/docs/pretty-formats
const r = await execCommand('git', [
'--no-pager',
'log',
`${from ? `${from}...` : ''}${to}`,
'--pretty="----%n%s|%h|%an|%ae%n%b"',
'--name-status'
]);
return r
.split('----\n')
.splice(1)
.map(line => {
const [firstLine, ..._body] = line.split('\n');
const [message, shortHash, authorName, authorEmail] = firstLine.split('|');
const $r: RawGitCommit = {
message,
shortHash,
author: { name: authorName, email: authorEmail },
body: _body.join('\n')
};
return $r;
});
}
export function getGitRemoteURL(cwd: string, remote = 'origin') {
return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);
}
| export function getGitPushUrl(config: RepoConfig, token?: string) { |
if (!token) return null;
return `https://${token}@${config.domain}/${config.repo}`;
}
| src/git.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GitCommitAuthor {\n name: string;\n email: string;\n}\nexport interface RawGitCommit {\n message: string;\n body: string;\n shortHash: string;\n author: GitCommitAuthor;\n}",
"score": 14.467818844194628
},
{
"filename": "src/repo.ts",
"retrieved_chunk": " const pkg = await readPackageJSON(cwd).catch(() => {});\n if (pkg && pkg.repository) {\n const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;\n return getRepoConfig(url);\n }\n const gitRemote = await getGitRemoteURL(cwd).catch(() => {});\n if (gitRemote) {\n return getRepoConfig(gitRemote);\n }\n return {};",
"score": 14.371564381844514
},
{
"filename": "src/repo.ts",
"retrieved_chunk": " 'bitbucket.org': 'bitbucket'\n};\n// https://regex101.com/r/NA4Io6/1\nconst providerURLRegex = /^(?:(?<user>\\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\\w+\\/\\w+)(?:\\.git)?$/;\nfunction baseUrl(config: RepoConfig) {\n return `https://${config.domain}/${config.repo}`;\n}\nexport function formatReference(ref: Reference, repo?: RepoConfig) {\n if (!repo?.provider || !(repo.provider in providerToRefSpec)) {\n return ref.value;",
"score": 13.599590135879083
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n if (!map.has(a.email)) {\n map.set(a.email, {\n commits: [],\n name: a.name,\n email: a.email\n });\n }\n const info = map.get(a.email)!;\n // record commits only for the first author",
"score": 13.19543041513283
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease';\nexport type RepoProvider = 'github' | 'gitlab' | 'bitbucket';\nexport type RepoConfig = {\n domain?: string;\n repo?: string;\n provider?: RepoProvider;\n token?: string;\n};\nexport interface ChangelogConfig {\n cwd: string;",
"score": 12.911742285608767
}
] | typescript | export function getGitPushUrl(config: RepoConfig, token?: string) { |
#!/usr/bin/env node
import { blue, bold, cyan, dim, red, yellow } from 'kolorist';
import cac from 'cac';
import { version } from '../package.json';
import { generate } from './generate';
import { hasTagOnGitHub, sendRelease } from './github';
import { isRepoShallow } from './git';
import type { ChangelogOptions } from './types';
const cli = cac('githublogen');
cli
.version(version)
.option('-t, --token <path>', 'GitHub Token')
.option('--from <ref>', 'From tag')
.option('--to <ref>', 'To tag')
.option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen')
.option('--name <name>', 'Name of the release')
.option('--contributors', 'Show contributors section')
.option('--prerelease', 'Mark release as prerelease')
.option('-d, --draft', 'Mark release as draft')
.option('--output <path>', 'Output to file instead of sending to GitHub')
.option('--capitalize', 'Should capitalize for each comment message')
.option('--emoji', 'Use emojis in section titles', { default: true })
.option('--group', 'Nest commit messages under their scopes')
.option('--dry', 'Dry run')
.help();
cli.command('').action(async (args: any) => {
try {
console.log();
console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));
const cwd = process.cwd();
const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);
const markdown = md.replace(/ /g, '');
console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));
console.log(dim('--------------'));
console.log();
console.log(markdown);
console.log();
console.log(dim('--------------'));
if (config.dry) {
console.log(yellow('Dry run. Release skipped.'));
return;
}
if (!(await hasTagOnGitHub(config.to, config))) {
console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`));
process.exitCode = 1;
return;
}
if (! | commits.length && (await isRepoShallow())) { |
console.error(
yellow(
'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.'
)
);
process.exitCode = 1;
return;
}
await sendRelease(config, md);
} catch (e: any) {
console.error(red(String(e)));
if (e?.stack) {
console.error(dim(e.stack?.split('\n').slice(1).join('\n')));
}
process.exit(1);
}
});
cli.parse();
| src/cli.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`",
"score": 29.259734116034412
},
{
"filename": "src/config.ts",
"retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;",
"score": 24.2318982220979
},
{
"filename": "src/github.ts",
"retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();",
"score": 22.32407460867522
},
{
"filename": "src/git.ts",
"retrieved_chunk": "}\nexport async function getLastGitTag(delta = 0) {\n const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\\n'));\n return tags[tags.length + delta - 1];\n}\nexport async function isRefGitTag(to: string) {\n const { execa } = await import('execa');\n try {\n await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });\n return true;",
"score": 16.987581397572146
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.",
"score": 16.5624769694068
}
] | typescript | commits.length && (await isRepoShallow())) { |
import { readPackageJSON } from 'pkg-types';
import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';
import { getGitRemoteURL } from './git';
const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {
github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },
gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },
bitbucket: {
'pull-request': 'pull-requests',
hash: 'commit',
issue: 'issues'
}
};
const providerToDomain: Record<RepoProvider, string> = {
github: 'github.com',
gitlab: 'gitlab.com',
bitbucket: 'bitbucket.org'
};
const domainToProvider: Record<string, RepoProvider> = {
'github.com': 'github',
'gitlab.com': 'gitlab',
'bitbucket.org': 'bitbucket'
};
// https://regex101.com/r/NA4Io6/1
const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/;
function baseUrl(config: RepoConfig) {
return `https://${config.domain}/${config.repo}`;
}
export function formatReference(ref: Reference, repo?: RepoConfig) {
if (!repo?.provider || !(repo.provider in providerToRefSpec)) {
return ref.value;
}
const refSpec = providerToRefSpec[repo.provider];
return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;
}
export function formatCompareChanges(v: string, config: ChangelogConfig) {
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;
}
export async function resolveRepoConfig(cwd: string) {
// Try closest package.json
const pkg = await readPackageJSON(cwd).catch(() => {});
if (pkg && pkg.repository) {
const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;
return getRepoConfig(url);
}
| const gitRemote = await getGitRemoteURL(cwd).catch(() => {}); |
if (gitRemote) {
return getRepoConfig(gitRemote);
}
return {};
}
export function getRepoConfig(repoUrl = ''): RepoConfig {
let provider: RepoProvider | undefined;
let repo: string | undefined;
let domain: string | undefined;
let url: URL | undefined;
try {
url = new URL(repoUrl);
} catch {}
const m = repoUrl.match(providerURLRegex)?.groups ?? {};
if (m.repo && m.provider) {
repo = m.repo;
provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider);
domain = provider in providerToDomain ? providerToDomain[provider] : provider;
} else if (url) {
domain = url.hostname;
repo = url.pathname
.split('/')
.slice(1, 3)
.join('/')
.replace(/\.git$/, '');
provider = domainToProvider[domain];
} else if (m.repo) {
repo = m.repo;
provider = 'github';
domain = providerToDomain[provider];
}
return {
provider,
repo,
domain
};
}
| src/repo.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/config.ts",
"retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;",
"score": 27.309973161703322
},
{
"filename": "src/git.ts",
"retrieved_chunk": "import type { RawGitCommit, RepoConfig } from './types';\nexport async function getGitHubRepo() {\n const url = await execCommand('git', ['config', '--get', 'remote.origin.url']);\n const match = url.match(/github\\.com[\\/:]([\\w\\d._-]+?)\\/([\\w\\d._-]+?)(\\.git)?$/i);\n if (!match) {\n throw new Error(`Can not parse GitHub repo from url ${url}`);\n }\n return `${match[1]}/${match[2]}`;\n}\nexport async function getGitMainBranchName() {",
"score": 26.07948871440461
},
{
"filename": "src/git.ts",
"retrieved_chunk": " return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);\n}\nexport function getGitPushUrl(config: RepoConfig, token?: string) {\n if (!token) return null;\n return `https://${token}@${config.domain}/${config.repo}`;\n}",
"score": 25.725400394124485
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 25.266016426745004
},
{
"filename": "src/github.ts",
"retrieved_chunk": " const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {\n headers\n });\n if (exists.url) {\n url = exists.url;\n method = 'PATCH';\n }\n } catch (e) {}\n const body = {\n body: content,",
"score": 25.046413661438066
}
] | typescript | const gitRemote = await getGitRemoteURL(cwd).catch(() => {}); |
import debug from "debug";
import EventEmitter from "eventemitter3";
import NDK from "../../index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
export type NDKPoolStats = {
total: number;
connected: number;
disconnected: number;
connecting: number;
};
/**
* Handles connections to all relays. A single pool should be used per NDK instance.
*
* @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.
* @emit notice - Emitted when a relay in the pool sends a notice.
* @emit flapping - Emitted when a relay in the pool is flapping.
* @emit relay:connect - Emitted when a relay in the pool connects.
* @emit relay:disconnect - Emitted when a relay in the pool disconnects.
*/
export class NDKPool extends EventEmitter {
public relays = new Map<string, NDKRelay>();
private debug: debug.Debugger;
private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();
public constructor(relayUrls: string[] = [], ndk: NDK) {
super();
this.debug = ndk.debug.extend("pool");
for (const relayUrl of relayUrls) {
const relay = new NDKRelay(relayUrl);
this.addRelay(relay, false);
}
}
/**
* Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time.
* @param relay - The relay to add to the pool.
* @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used.
*/
public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) {
const relayAlreadyInPool = this.relays.has(relay.url);
// check if the relay is already in the pool
if (!relayAlreadyInPool) {
this.addRelay(relay);
}
// check if the relay already has a disconnecting timer
const existingTimer = this.temporaryRelayTimers.get(relay.url);
if (existingTimer) {
clearTimeout(existingTimer);
}
// add a disconnecting timer only if the relay was not already in the pool
// or if it had an existing timer
// this prevents explicit relays from being removed from the pool
if (!relayAlreadyInPool || existingTimer) {
// set a timer to remove the relay from the pool if it is not used within the specified time
const timer = setTimeout(() => {
this.removeRelay(relay.url);
}, removeIfUnusedAfter) as unknown as NodeJS.Timeout;
this.temporaryRelayTimers.set(relay.url, timer);
}
}
/**
* Adds a relay to the pool.
*
* @param relay - The relay to add to the pool.
* @param connect - Whether or not to connect to the relay.
*/
public addRelay(relay: NDKRelay, connect = true) {
const relayUrl = relay.url;
relay.on( | "notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
relay.on("connect", () => this.handleRelayConnect(relayUrl));
relay.on("disconnect", () => this.emit("relay:disconnect", relay));
relay.on("flapping", () => this.handleFlapping(relay));
this.relays.set(relayUrl, relay);
if (connect) {
relay.connect();
}
}
/**
* Removes a relay from the pool.
* @param relayUrl - The URL of the relay to remove.
* @returns {boolean} True if the relay was removed, false if it was not found.
*/
public removeRelay(relayUrl: string): boolean {
const relay = this.relays.get(relayUrl);
if (relay) {
relay.disconnect();
this.relays.delete(relayUrl);
this.emit("relay:disconnect", relay);
return true;
}
// remove the relay from the temporary relay timers
const existingTimer = this.temporaryRelayTimers.get(relayUrl);
if (existingTimer) {
clearTimeout(existingTimer);
this.temporaryRelayTimers.delete(relayUrl);
}
return false;
}
private handleRelayConnect(relayUrl: string) {
this.debug(`Relay ${relayUrl} connected`);
this.emit("relay:connect", this.relays.get(relayUrl));
if (this.stats().connected === this.relays.size) {
this.emit("connect");
}
}
/**
* Attempts to establish a connection to each relay in the pool.
*
* @async
* @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.
* @returns {Promise<void>} A promise that resolves when all connection attempts have completed.
* @throws {Error} If any of the connection attempts result in an error or timeout.
*/
public async connect(timeoutMs?: number): Promise<void> {
const promises: Promise<void>[] = [];
this.debug(
`Connecting to ${this.relays.size} relays${
timeoutMs ? `, timeout ${timeoutMs}...` : ""
}`
);
for (const relay of this.relays.values()) {
if (timeoutMs) {
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(
() => reject(`Timed out after ${timeoutMs}ms`),
timeoutMs
);
});
promises.push(
Promise.race([relay.connect(), timeoutPromise]).catch(
(e) => {
this.debug(
`Failed to connect to relay ${relay.url}: ${e}`
);
}
)
);
} else {
promises.push(relay.connect());
}
}
// If we are running with a timeout, check if we need to emit a `connect` event
// in case some, but not all, relays were connected
if (timeoutMs) {
setTimeout(() => {
const allConnected =
this.stats().connected === this.relays.size;
const someConnected = this.stats().connected > 0;
if (!allConnected && someConnected) {
this.emit("connect");
}
}, timeoutMs);
}
await Promise.all(promises);
}
private handleFlapping(relay: NDKRelay) {
this.debug(`Relay ${relay.url} is flapping`);
// TODO: Be smarter about this.
this.relays.delete(relay.url);
this.emit("flapping", relay);
}
public size(): number {
return this.relays.size;
}
/**
* Returns the status of each relay in the pool.
* @returns {NDKPoolStats} An object containing the number of relays in each status.
*/
public stats(): NDKPoolStats {
const stats: NDKPoolStats = {
total: 0,
connected: 0,
disconnected: 0,
connecting: 0,
};
for (const relay of this.relays.values()) {
stats.total++;
if (relay.status === NDKRelayStatus.CONNECTED) {
stats.connected++;
} else if (relay.status === NDKRelayStatus.DISCONNECTED) {
stats.disconnected++;
} else if (relay.status === NDKRelayStatus.CONNECTING) {
stats.connecting++;
}
}
return stats;
}
public connectedRelays(): NDKRelay[] {
return Array.from(this.relays.values()).filter(
(relay) => relay.status === NDKRelayStatus.CONNECTED
);
}
/**
* Get a list of all relay urls in the pool.
*/
public urls(): string[] {
return Array.from(this.relays.keys());
}
}
| src/relay/pool/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // remove it from relay set selection for a minute.\n if (notice.includes(\"oo many\") || notice.includes(\"aximum\")) {\n this.disconnect();\n // fixme\n setTimeout(() => this.connect(), 2000);\n this.debug(this.relay.url, \"Relay complaining?\", notice);\n // this.complaining = true;\n // setTimeout(() => {\n // this.complaining = false;\n // console.log(this.relay.url, 'Reactivate relay');",
"score": 66.8084413601384
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " this.emit(\"disconnect\");\n });\n this.relay.on(\"notice\", (notice: string) => this.handleNotice(notice));\n }\n /**\n * Evaluates the connection stats to determine if the relay is flapping.\n */\n private isFlapping(): boolean {\n const durations = this._connectionStats.durations;\n if (durations.length < 10) return false;",
"score": 60.87440309611881
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * The time the current connection was established in milliseconds.\n */\n connectedAt?: number;\n}\n/**\n * The NDKRelay class represents a connection to a relay.\n *\n * @emits NDKRelay#connect\n * @emits NDKRelay#disconnect\n * @emits NDKRelay#notice",
"score": 57.20409890334279
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 55.398293704648275
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " }\n /**\n * Disconnects from the relay.\n */\n public disconnect(): void {\n this._status = NDKRelayStatus.DISCONNECTING;\n this.relay.close();\n }\n async handleNotice(notice: string) {\n // This is a prototype; if the relay seems to be complaining",
"score": 51.85202207613401
}
] | typescript | "notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
| const [breaking, changes] = partition(commits, c => c.isBreaking); |
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 23.989476658203408
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 21.00700738424665
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 19.75730768726418
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 19.64494530651201
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 16.059821876998978
}
] | typescript | const [breaking, changes] = partition(commits, c => c.isBreaking); |
#!/usr/bin/env node
import { blue, bold, cyan, dim, red, yellow } from 'kolorist';
import cac from 'cac';
import { version } from '../package.json';
import { generate } from './generate';
import { hasTagOnGitHub, sendRelease } from './github';
import { isRepoShallow } from './git';
import type { ChangelogOptions } from './types';
const cli = cac('githublogen');
cli
.version(version)
.option('-t, --token <path>', 'GitHub Token')
.option('--from <ref>', 'From tag')
.option('--to <ref>', 'To tag')
.option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen')
.option('--name <name>', 'Name of the release')
.option('--contributors', 'Show contributors section')
.option('--prerelease', 'Mark release as prerelease')
.option('-d, --draft', 'Mark release as draft')
.option('--output <path>', 'Output to file instead of sending to GitHub')
.option('--capitalize', 'Should capitalize for each comment message')
.option('--emoji', 'Use emojis in section titles', { default: true })
.option('--group', 'Nest commit messages under their scopes')
.option('--dry', 'Dry run')
.help();
cli.command('').action(async (args: any) => {
try {
console.log();
console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));
const cwd = process.cwd();
const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);
const markdown = md.replace(/ /g, '');
console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));
console.log(dim('--------------'));
console.log();
console.log(markdown);
console.log();
console.log(dim('--------------'));
if (config.dry) {
console.log(yellow('Dry run. Release skipped.'));
return;
}
| if (!(await hasTagOnGitHub(config.to, config))) { |
console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`));
process.exitCode = 1;
return;
}
if (!commits.length && (await isRepoShallow())) {
console.error(
yellow(
'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.'
)
);
process.exitCode = 1;
return;
}
await sendRelease(config, md);
} catch (e: any) {
console.error(red(String(e)));
if (e?.stack) {
console.error(dim(e.stack?.split('\n').slice(1).join('\n')));
}
process.exit(1);
}
});
cli.parse();
| src/cli.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();",
"score": 65.21156217133499
},
{
"filename": "src/github.ts",
"retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`",
"score": 54.348524851930776
},
{
"filename": "src/git.ts",
"retrieved_chunk": "async function execCommand(cmd: string, args: string[]) {\n const { execa } = await import('execa');\n const res = await execa(cmd, args);\n return res.stdout.trim();\n}\nexport async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {\n // https://git-scm.com/docs/pretty-formats\n const r = await execCommand('git', [\n '--no-pager',\n 'log',",
"score": 18.681242614321047
},
{
"filename": "src/config.ts",
"retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;",
"score": 16.00980344822583
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.",
"score": 15.22768185953925
}
] | typescript | if (!(await hasTagOnGitHub(config.to, config))) { |
import debug from "debug";
import EventEmitter from "eventemitter3";
import NDK from "../../index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
export type NDKPoolStats = {
total: number;
connected: number;
disconnected: number;
connecting: number;
};
/**
* Handles connections to all relays. A single pool should be used per NDK instance.
*
* @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.
* @emit notice - Emitted when a relay in the pool sends a notice.
* @emit flapping - Emitted when a relay in the pool is flapping.
* @emit relay:connect - Emitted when a relay in the pool connects.
* @emit relay:disconnect - Emitted when a relay in the pool disconnects.
*/
export class NDKPool extends EventEmitter {
public relays = new Map<string, NDKRelay>();
private debug: debug.Debugger;
private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();
public constructor(relayUrls: string[] = [], ndk: NDK) {
super();
this.debug = ndk.debug.extend("pool");
for (const relayUrl of relayUrls) {
const relay = new NDKRelay(relayUrl);
this.addRelay(relay, false);
}
}
/**
* Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time.
* @param relay - The relay to add to the pool.
* @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used.
*/
public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) {
const relayAlreadyInPool = this.relays.has(relay.url);
// check if the relay is already in the pool
if (!relayAlreadyInPool) {
this.addRelay(relay);
}
// check if the relay already has a disconnecting timer
const existingTimer = this.temporaryRelayTimers.get(relay.url);
if (existingTimer) {
clearTimeout(existingTimer);
}
// add a disconnecting timer only if the relay was not already in the pool
// or if it had an existing timer
// this prevents explicit relays from being removed from the pool
if (!relayAlreadyInPool || existingTimer) {
// set a timer to remove the relay from the pool if it is not used within the specified time
const timer = setTimeout(() => {
this.removeRelay(relay.url);
}, removeIfUnusedAfter) as unknown as NodeJS.Timeout;
this.temporaryRelayTimers.set(relay.url, timer);
}
}
/**
* Adds a relay to the pool.
*
* @param relay - The relay to add to the pool.
* @param connect - Whether or not to connect to the relay.
*/
public addRelay(relay: NDKRelay, connect = true) {
const relayUrl = relay.url;
relay.on("notice", (relay, notice) =>
this.emit("notice", relay, notice)
);
relay.on("connect", () => this.handleRelayConnect(relayUrl));
relay.on("disconnect", () => this.emit("relay:disconnect", relay));
relay.on("flapping", () => this.handleFlapping(relay));
this.relays.set(relayUrl, relay);
if (connect) {
relay.connect();
}
}
/**
* Removes a relay from the pool.
* @param relayUrl - The URL of the relay to remove.
* @returns {boolean} True if the relay was removed, false if it was not found.
*/
public removeRelay(relayUrl: string): boolean {
const relay = this.relays.get(relayUrl);
if (relay) {
relay.disconnect();
this.relays.delete(relayUrl);
this.emit("relay:disconnect", relay);
return true;
}
// remove the relay from the temporary relay timers
const existingTimer = this.temporaryRelayTimers.get(relayUrl);
if (existingTimer) {
clearTimeout(existingTimer);
this.temporaryRelayTimers.delete(relayUrl);
}
return false;
}
private handleRelayConnect(relayUrl: string) {
this.debug(`Relay ${relayUrl} connected`);
this.emit("relay:connect", this.relays.get(relayUrl));
if (this.stats().connected === this.relays.size) {
this.emit("connect");
}
}
/**
* Attempts to establish a connection to each relay in the pool.
*
* @async
* @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.
* @returns {Promise<void>} A promise that resolves when all connection attempts have completed.
* @throws {Error} If any of the connection attempts result in an error or timeout.
*/
public async connect(timeoutMs?: number): Promise<void> {
const promises: Promise<void>[] = [];
this.debug(
`Connecting to ${this.relays.size} relays${
timeoutMs ? `, timeout ${timeoutMs}...` : ""
}`
);
for (const relay of this.relays.values()) {
if (timeoutMs) {
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(
() => reject(`Timed out after ${timeoutMs}ms`),
timeoutMs
);
});
promises.push(
Promise.race([relay.connect(), timeoutPromise]).catch(
(e) => {
this.debug(
`Failed to connect to relay ${relay.url}: ${e}`
);
}
)
);
} else {
promises.push(relay.connect());
}
}
// If we are running with a timeout, check if we need to emit a `connect` event
// in case some, but not all, relays were connected
if (timeoutMs) {
setTimeout(() => {
const allConnected =
this.stats().connected === this.relays.size;
const someConnected = this.stats().connected > 0;
if (!allConnected && someConnected) {
this.emit("connect");
}
}, timeoutMs);
}
await Promise.all(promises);
}
private handleFlapping(relay: NDKRelay) {
this.debug(`Relay ${relay.url} is flapping`);
// TODO: Be smarter about this.
this.relays.delete(relay.url);
this.emit("flapping", relay);
}
public size(): number {
return this.relays.size;
}
/**
* Returns the status of each relay in the pool.
* @returns {NDKPoolStats} An object containing the number of relays in each status.
*/
public stats(): NDKPoolStats {
const stats: NDKPoolStats = {
total: 0,
connected: 0,
disconnected: 0,
connecting: 0,
};
for (const relay of this.relays.values()) {
stats.total++;
if (relay.status === NDKRelayStatus.CONNECTED) {
stats.connected++;
} else if (relay.status === NDKRelayStatus.DISCONNECTED) {
stats.disconnected++;
} else if (relay.status === NDKRelayStatus.CONNECTING) {
stats.connecting++;
}
}
return stats;
}
| public connectedRelays(): NDKRelay[] { |
return Array.from(this.relays.values()).filter(
(relay) => relay.status === NDKRelayStatus.CONNECTED
);
}
/**
* Get a list of all relay urls in the pool.
*/
public urls(): string[] {
return Array.from(this.relays.keys());
}
}
| src/relay/pool/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " } else {\n this.connect();\n }\n }\n get status(): NDKRelayStatus {\n return this._status;\n }\n /**\n * Connects to the relay.\n */",
"score": 33.81685354909224
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " this.updateConnectionStats.connected();\n this._status = NDKRelayStatus.CONNECTED;\n this.emit(\"connect\");\n });\n this.relay.on(\"disconnect\", () => {\n this.updateConnectionStats.disconnected();\n if (this._status === NDKRelayStatus.CONNECTED) {\n this._status = NDKRelayStatus.DISCONNECTED;\n this.handleReconnection();\n }",
"score": 31.459182306752073
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,",
"score": 29.948221344201922
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " };\n /**\n * Returns the connection stats.\n */\n get connectionStats(): NDKRelayConnectionStats {\n return this._connectionStats;\n }\n public tagReference(marker?: string): NDKTag {\n const tag = [\"r\", this.relay.url];\n if (marker) {",
"score": 29.745531300467274
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }",
"score": 25.49160394345901
}
] | typescript | public connectedRelays(): NDKRelay[] { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
| const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { |
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 21.10341006136765
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 20.251323625680108
},
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 18.77040213954379
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 17.32541432644538
},
{
"filename": "src/repo.ts",
"retrieved_chunk": " }\n};\nconst providerToDomain: Record<RepoProvider, string> = {\n github: 'github.com',\n gitlab: 'gitlab.com',\n bitbucket: 'bitbucket.org'\n};\nconst domainToProvider: Record<string, RepoProvider> = {\n 'github.com': 'github',\n 'gitlab.com': 'gitlab',",
"score": 16.82623748367757
}
] | typescript | const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
| if (info.login) return info; |
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 15.669732009212105
},
{
"filename": "src/config.ts",
"retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,",
"score": 14.52034018911413
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 11.494957707112553
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 11.247694393121595
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### ${$name}`;",
"score": 9.61599565623697
}
] | typescript | if (info.login) return info; |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
| .map((a, idx) => { |
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 30.495310687557147
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 22.669824976509382
},
{
"filename": "src/types.ts",
"retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}",
"score": 22.067258377697733
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 20.912437582203474
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 15.486470157856958
}
] | typescript | .map((a, idx) => { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
| if (info.commits.length) { |
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/types.ts",
"retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}",
"score": 18.351473927588394
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 18.295640064050264
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 17.451684677983987
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const [breaking, changes] = partition(commits, c => c.isBreaking);\n const group = groupBy(changes, 'type');\n lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));\n for (const type of Object.keys(options.types)) {\n const items = group[type] || [];\n lines.push(...formatSection(items, options.types[type].title, options));\n }\n if (!lines.length) {\n lines.push('*No significant changes*');\n }",
"score": 15.544196832990039
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 14.92272215858253
}
] | typescript | if (info.commits.length) { |
import { convert } from 'convert-gitmoji';
import { partition, groupBy, capitalize, join } from './shared';
import type { Reference, Commit, ResolvedChangelogOptions } from './types';
const emojisRE =
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;
function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {
const refs = references
.filter(i => {
if (type === 'issues') {
return i.type === 'issue' || i.type === 'pull-request';
}
return i.type === 'hash';
})
.map(ref => {
if (!github) {
return ref.value;
}
if (ref.type === 'pull-request' || ref.type === 'issue') {
return `https://github.com/${github}/issues/${ref.value.slice(1)}`;
}
return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;
});
const referencesString = join(refs).trim();
if (type === 'issues') {
return referencesString && `in ${referencesString}`;
}
return referencesString;
}
function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');
const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))
])?.trim();
if (authors) {
authors = `by ${authors}`;
}
let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');
if (refs) {
refs = ` - ${refs}`;
}
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' ');
}
function formatTitle(name: string, options: ResolvedChangelogOptions) {
let $name = name.trim();
if (!options.emoji) {
$name = name.replace(emojisRE, '').trim();
}
return `### ${$name}`;
}
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
if (!commits.length) {
return [];
}
const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group;
// group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false;
}
Object.keys(scopes)
.sort()
.forEach(scope => {
let padding = '';
let prefix = '';
const scopeText = `**${options.scopeMap[scope] || scope}**`;
if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) {
lines.push(`- ${scopeText}:`);
padding = ' ';
} else if (scope) {
prefix = `${scopeText}: `;
}
lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
});
return lines;
}
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
const lines: string[] = [];
const | [breaking, changes] = partition(commits, c => c.isBreaking); |
const group = groupBy(changes, 'type');
lines.push(...formatSection(breaking, options.titles.breakingChanges!, options));
for (const type of Object.keys(options.types)) {
const items = group[type] || [];
lines.push(...formatSection(items, options.types[type].title, options));
}
if (!lines.length) {
lines.push('*No significant changes*');
}
const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;
lines.push('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 23.33437038612311
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 19.110776817266046
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking",
"score": 17.119198115235363
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 16.059821876998978
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 13.93575441031903
}
] | typescript | [breaking, changes] = partition(commits, c => c.isBreaking); |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map | ((a, idx) => { |
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => {
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 22.669824976509382
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 21.9725908787624
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}",
"score": 20.912437582203474
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " array.forEach((e, idx, arr) => {\n let i = 0;\n for (const filter of filters) {\n if (filter(e, idx, arr)) {\n result[i].push(e);\n return;\n }\n i += 1;\n }\n result[i].push(e);",
"score": 14.609348280389879
},
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 13.942331402217718
}
] | typescript | ((a, idx) => { |
import { $fetch } from 'ohmyfetch';
import { cyan, green, red, yellow } from 'kolorist';
import { notNullish } from './shared';
import type { AuthorInfo, ChangelogOptions, Commit } from './types';
export async function sendRelease(options: ChangelogOptions, content: string) {
const headers = getHeaders(options);
const github = options.repo.repo!;
let url = `https://api.github.com/repos/${github}/releases`;
let method = 'POST';
try {
const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {
headers
});
if (exists.url) {
url = exists.url;
method = 'PATCH';
}
} catch (e) {}
const body = {
body: content,
draft: options.draft || false,
name: options.name || options.to,
prerelease: options.prerelease,
tag_name: options.to
};
const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(
String(body.name)
)}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${
options.prerelease
}`;
try {
console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));
const res = await $fetch(url, {
method,
body: JSON.stringify(body),
headers
});
console.log(green(`Released on ${res.html_url}`));
} catch (e) {
console.log();
console.error(red('Failed to create the release. Using the following link to create it manually:'));
console.error(yellow(webUrl));
console.log();
throw e;
}
}
function getHeaders(options: ChangelogOptions) {
return {
accept: 'application/vnd.github.v3+json',
authorization: `token ${options.tokens.github}`
};
}
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving
if (!options.tokens.github) return info;
try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options)
});
info.login = data.items[0].login;
} catch {}
if (info.login) return info;
if (info.commits.length) {
try {
const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, {
headers: getHeaders(options)
});
info.login = data.author.login;
} catch (e) {}
}
return info;
}
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>();
commits.forEach(commit => {
commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) {
return null;
}
if (!map.has(a.email)) {
map.set(a.email, {
commits: [],
name: a.name,
email: a.email
});
}
const info = map.get(a.email)!;
// record commits only for the first author
if (idx === 0) {
info.commits.push(commit.shortHash);
}
return info;
})
.filter(notNullish);
});
const authors = Array.from(map.values());
const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));
const loginSet = new Set<string>();
const nameSet = new Set<string>();
return resolved
.sort((a, b) | => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => { |
if (i.login && loginSet.has(i.login)) {
return false;
}
if (i.login) {
loginSet.add(i.login);
} else {
if (nameSet.has(i.name)) {
return false;
}
nameSet.add(i.name);
}
return true;
});
}
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
try {
await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options)
});
return true;
} catch (e) {
return false;
}
}
| src/github.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 47.83640947991162
},
{
"filename": "src/git.ts",
"retrieved_chunk": " `${from ? `${from}...` : ''}${to}`,\n '--pretty=\"----%n%s|%h|%an|%ae%n%b\"',\n '--name-status'\n ]);\n return r\n .split('----\\n')\n .splice(1)\n .map(line => {\n const [firstLine, ..._body] = line.split('\\n');\n const [message, shortHash, authorName, authorEmail] = firstLine.split('|');",
"score": 25.56939851912322
},
{
"filename": "src/generate.ts",
"retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);",
"score": 22.119546828073155
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };",
"score": 21.99364038075798
},
{
"filename": "src/parse.ts",
"retrieved_chunk": "import { notNullish } from './shared';\nimport type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types';\n// https://www.conventionalcommits.org/en/v1.0.0/\n// https://regex101.com/r/FSfNvA/1\nconst ConventionalCommitRegex = /(?<type>[a-z]+)(\\((?<scope>.+)\\))?(?<breaking>!)?: (?<description>.+)/i;\nconst CoAuthoredByRegex = /co-authored-by:\\s*(?<name>.+)(<(?<email>.+)>)/gim;\nconst PullRequestRE = /\\([a-z]*(#\\d+)\\s*\\)/gm;\nconst IssueRE = /(#\\d+)/gm;\nexport function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {\n const match = commit.message.match(ConventionalCommitRegex);",
"score": 21.12991233306493
}
] | typescript | => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => { |
import { readPackageJSON } from 'pkg-types';
import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';
import { getGitRemoteURL } from './git';
const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {
github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },
gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },
bitbucket: {
'pull-request': 'pull-requests',
hash: 'commit',
issue: 'issues'
}
};
const providerToDomain: Record<RepoProvider, string> = {
github: 'github.com',
gitlab: 'gitlab.com',
bitbucket: 'bitbucket.org'
};
const domainToProvider: Record<string, RepoProvider> = {
'github.com': 'github',
'gitlab.com': 'gitlab',
'bitbucket.org': 'bitbucket'
};
// https://regex101.com/r/NA4Io6/1
const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/;
function baseUrl(config: RepoConfig) {
return `https://${config.domain}/${config.repo}`;
}
export function formatReference(ref: Reference, repo?: RepoConfig) {
if (!repo?.provider || !(repo.provider in providerToRefSpec)) {
return ref.value;
}
const refSpec = providerToRefSpec[repo.provider];
return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;
}
export function formatCompareChanges(v: string, config: ChangelogConfig) {
| const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare'; |
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;
}
export async function resolveRepoConfig(cwd: string) {
// Try closest package.json
const pkg = await readPackageJSON(cwd).catch(() => {});
if (pkg && pkg.repository) {
const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;
return getRepoConfig(url);
}
const gitRemote = await getGitRemoteURL(cwd).catch(() => {});
if (gitRemote) {
return getRepoConfig(gitRemote);
}
return {};
}
export function getRepoConfig(repoUrl = ''): RepoConfig {
let provider: RepoProvider | undefined;
let repo: string | undefined;
let domain: string | undefined;
let url: URL | undefined;
try {
url = new URL(repoUrl);
} catch {}
const m = repoUrl.match(providerURLRegex)?.groups ?? {};
if (m.repo && m.provider) {
repo = m.repo;
provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider);
domain = provider in providerToDomain ? providerToDomain[provider] : provider;
} else if (url) {
domain = url.hostname;
repo = url.pathname
.split('/')
.slice(1, 3)
.join('/')
.replace(/\.git$/, '');
provider = domainToProvider[domain];
} else if (m.repo) {
repo = m.repo;
provider = 'github';
domain = providerToDomain[provider];
}
return {
provider,
repo,
domain
};
}
| src/repo.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 42.81176069120929
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease';\nexport type RepoProvider = 'github' | 'gitlab' | 'bitbucket';\nexport type RepoConfig = {\n domain?: string;\n repo?: string;\n provider?: RepoProvider;\n token?: string;\n};\nexport interface ChangelogConfig {\n cwd: string;",
"score": 38.196255350445014
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 36.44297609707397
},
{
"filename": "src/github.ts",
"retrieved_chunk": " await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {\n headers: getHeaders(options)\n });\n return true;\n } catch (e) {\n return false;\n }\n}",
"score": 26.4151461297002
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface Reference {\n type: 'hash' | 'issue' | 'pull-request';\n value: string;\n}\nexport interface GithubOptions {\n repo: string;\n token: string;\n}\nexport interface GithubRelease {\n id?: string;",
"score": 25.987963147303066
}
] | typescript | const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare'; |
import { notNullish } from './shared';
import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types';
// https://www.conventionalcommits.org/en/v1.0.0/
// https://regex101.com/r/FSfNvA/1
const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i;
const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim;
const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm;
const IssueRE = /(#\d+)/gm;
export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {
const match = commit.message.match(ConventionalCommitRegex);
if (!match?.groups) {
return null;
}
const type = match.groups.type;
let scope = match.groups.scope || '';
scope = config.scopeMap[scope] || scope;
const isBreaking = Boolean(match.groups.breaking);
let description = match.groups.description;
// Extract references from message
const references: Reference[] = [];
for (const m of description.matchAll(PullRequestRE)) {
references.push({ type: 'pull-request', value: m[1] });
}
for (const m of description.matchAll(IssueRE)) {
if (!references.some(i => i.value === m[1])) {
references.push({ type: 'issue', value: m[1] });
}
}
references.push({ value: commit.shortHash, type: 'hash' });
// Remove references and normalize
description = description.replace(PullRequestRE, '').trim();
// Find all authors
const authors: GitCommitAuthor[] = [commit.author];
const matchs = commit.body.matchAll(CoAuthoredByRegex);
for (const $match of matchs) {
const { name = '', email = '' } = $match.groups || {};
const author: GitCommitAuthor = {
name: name.trim(),
email: email.trim()
};
authors.push(author);
}
return {
...commit,
authors,
description,
type,
scope,
references,
isBreaking
};
}
export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {
| return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish); |
}
| src/parse.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/github.ts",
"retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();",
"score": 19.57927490649645
},
{
"filename": "src/github.ts",
"retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;",
"score": 17.96623890998377
},
{
"filename": "src/types.ts",
"retrieved_chunk": " tag_name: string;\n name?: string;\n body?: string;\n draft?: boolean;\n prerelease?: boolean;\n}\nexport interface GitCommit extends RawGitCommit {\n description: string;\n type: string;\n scope: string;",
"score": 16.590909232605256
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];",
"score": 16.46374176856977
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 16.233027987893877
}
] | typescript | return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish); |
import { readPackageJSON } from 'pkg-types';
import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';
import { getGitRemoteURL } from './git';
const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {
github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },
gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },
bitbucket: {
'pull-request': 'pull-requests',
hash: 'commit',
issue: 'issues'
}
};
const providerToDomain: Record<RepoProvider, string> = {
github: 'github.com',
gitlab: 'gitlab.com',
bitbucket: 'bitbucket.org'
};
const domainToProvider: Record<string, RepoProvider> = {
'github.com': 'github',
'gitlab.com': 'gitlab',
'bitbucket.org': 'bitbucket'
};
// https://regex101.com/r/NA4Io6/1
const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/;
function baseUrl(config: RepoConfig) {
return `https://${config.domain}/${config.repo}`;
}
export function formatReference(ref: Reference, repo?: RepoConfig) {
if (!repo?.provider || !(repo.provider in providerToRefSpec)) {
return ref.value;
}
const refSpec = providerToRefSpec[repo.provider];
return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;
}
export function formatCompareChanges(v: string, config: ChangelogConfig) {
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
| return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`; |
}
export async function resolveRepoConfig(cwd: string) {
// Try closest package.json
const pkg = await readPackageJSON(cwd).catch(() => {});
if (pkg && pkg.repository) {
const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;
return getRepoConfig(url);
}
const gitRemote = await getGitRemoteURL(cwd).catch(() => {});
if (gitRemote) {
return getRepoConfig(gitRemote);
}
return {};
}
export function getRepoConfig(repoUrl = ''): RepoConfig {
let provider: RepoProvider | undefined;
let repo: string | undefined;
let domain: string | undefined;
let url: URL | undefined;
try {
url = new URL(repoUrl);
} catch {}
const m = repoUrl.match(providerURLRegex)?.groups ?? {};
if (m.repo && m.provider) {
repo = m.repo;
provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider);
domain = provider in providerToDomain ? providerToDomain[provider] : provider;
} else if (url) {
domain = url.hostname;
repo = url.pathname
.split('/')
.slice(1, 3)
.join('/')
.replace(/\.git$/, '');
provider = domainToProvider[domain];
} else if (m.repo) {
repo = m.repo;
provider = 'github';
domain = providerToDomain[provider];
}
return {
provider,
repo,
domain
};
}
| src/repo.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 44.7746681016701
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease';\nexport type RepoProvider = 'github' | 'gitlab' | 'bitbucket';\nexport type RepoConfig = {\n domain?: string;\n repo?: string;\n provider?: RepoProvider;\n token?: string;\n};\nexport interface ChangelogConfig {\n cwd: string;",
"score": 39.64159940666026
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 36.58880262737943
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### [View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}",
"score": 34.67773508349122
},
{
"filename": "src/git.ts",
"retrieved_chunk": " return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);\n}\nexport function getGitPushUrl(config: RepoConfig, token?: string) {\n if (!token) return null;\n return `https://${token}@${config.domain}/${config.repo}`;\n}",
"score": 29.471108560875848
}
] | typescript | return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`; |
import { notNullish } from './shared';
import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types';
// https://www.conventionalcommits.org/en/v1.0.0/
// https://regex101.com/r/FSfNvA/1
const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i;
const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim;
const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm;
const IssueRE = /(#\d+)/gm;
export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {
const match = commit.message.match(ConventionalCommitRegex);
if (!match?.groups) {
return null;
}
const type = match.groups.type;
let scope = match.groups.scope || '';
scope = config.scopeMap[scope] || scope;
const isBreaking = Boolean(match.groups.breaking);
let description = match.groups.description;
// Extract references from message
const references: Reference[] = [];
for (const m of description.matchAll(PullRequestRE)) {
references.push({ type: 'pull-request', value: m[1] });
}
for (const m of description.matchAll(IssueRE)) {
if (!references.some(i => i.value === m[1])) {
references.push({ type: 'issue', value: m[1] });
}
}
references.push({ value: commit.shortHash, type: 'hash' });
// Remove references and normalize
description = description.replace(PullRequestRE, '').trim();
// Find all authors
const authors: | GitCommitAuthor[] = [commit.author]; |
const matchs = commit.body.matchAll(CoAuthoredByRegex);
for (const $match of matchs) {
const { name = '', email = '' } = $match.groups || {};
const author: GitCommitAuthor = {
name: name.trim(),
email: email.trim()
};
authors.push(author);
}
return {
...commit,
authors,
description,
type,
scope,
references,
isBreaking
};
}
export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {
return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);
}
| src/parse.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/markdown.ts",
"retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = ` - ${refs}`;",
"score": 38.61760795322445
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');",
"score": 31.838285845205707
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### ${$name}`;",
"score": 29.987317070087993
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }",
"score": 28.993998901506725
},
{
"filename": "src/markdown.ts",
"retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';",
"score": 27.323333862711145
}
] | typescript | GitCommitAuthor[] = [commit.author]; |
import Event from "../../events/index.js";
import NDK from "../../index.js";
import { NDKFilter } from "../../subscription/index.js";
import { NDKRelay } from "../index.js";
import { NDKRelaySet } from "./index.js";
/**
* Creates a NDKRelaySet for the specified event.
* TODO: account for relays where tagged pubkeys or hashtags
* tend to write to.
* @param ndk {NDK}
* @param event {Event}
* @returns Promise<NDKRelaySet>
*/
export function calculateRelaySetFromEvent(
ndk: NDK,
event: Event
): NDKRelaySet {
const relays: Set<NDKRelay> = new Set();
ndk.pool?.relays.forEach((relay) => relays.add(relay));
return new NDKRelaySet(relays, ndk);
}
/**
* Creates a NDKRelaySet for the specified filter
* @param ndk
* @param filter
* @returns Promise<NDKRelaySet>
*/
export function calculateRelaySetFromFilter(
ndk: NDK,
filter: NDKFilter
): NDKRelaySet {
const relays: Set<NDKRelay> = new Set();
ndk.pool?.relays.forEach((relay) => {
if (!relay.complaining) {
relays.add(relay);
} else {
ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);
}
});
return new NDKRelaySet(relays, ndk);
}
/**
* Calculates a number of RelaySets for each filter.
* @param ndk
* @param filters
*/
export function calculateRelaySetsFromFilters(
ndk: NDK,
filters: | NDKFilter[]
): Map<NDKFilter, NDKRelaySet> { |
const sets: Map<NDKFilter, NDKRelaySet> = new Map();
filters.forEach((filter) => {
const set = calculateRelaySetFromFilter(ndk, filter);
sets.set(filter, set);
});
return sets;
}
| src/relay/sets/calculate.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " ndk: NDK,\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n subId?: string\n ) {\n super();\n this.ndk = ndk;\n this.opts = { ...defaultOpts, ...(opts || {}) };\n this.filters = filters instanceof Array ? filters : [filters];",
"score": 29.66119116156912
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 26.490198991480117
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": "export function mergeFilters(filters: NDKFilter[]): NDKFilter {\n const result: any = {};\n filters.forEach((filter) => {\n Object.entries(filter).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n if (result[key] === undefined) {\n result[key] = [...value];\n } else {\n result[key] = Array.from(\n new Set([...result[key], ...value])",
"score": 23.692681971157498
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " readonly subId: string;\n readonly filters: NDKFilter[];\n readonly opts: NDKSubscriptionOptions;\n public relaySet?: NDKRelaySet;\n public ndk: NDK;\n public relaySubscriptions: Map<NDKRelay, Sub>;\n private debug: debug.Debugger;\n /**\n * Events that have been seen by the subscription, with the time they were first seen.\n */",
"score": 20.867792992210834
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 20.094447835810033
}
] | typescript | NDKFilter[]
): Map<NDKFilter, NDKRelaySet> { |
import Event from "../../events/index.js";
import NDK from "../../index.js";
import { NDKFilter } from "../../subscription/index.js";
import { NDKRelay } from "../index.js";
import { NDKRelaySet } from "./index.js";
/**
* Creates a NDKRelaySet for the specified event.
* TODO: account for relays where tagged pubkeys or hashtags
* tend to write to.
* @param ndk {NDK}
* @param event {Event}
* @returns Promise<NDKRelaySet>
*/
export function calculateRelaySetFromEvent(
ndk: NDK,
event: Event
): NDKRelaySet {
const relays: Set<NDKRelay> = new Set();
ndk.pool?.relays.forEach((relay) => relays.add(relay));
return new NDKRelaySet(relays, ndk);
}
/**
* Creates a NDKRelaySet for the specified filter
* @param ndk
* @param filter
* @returns Promise<NDKRelaySet>
*/
export function calculateRelaySetFromFilter(
ndk: NDK,
filter: NDKFilter
): NDKRelaySet {
const relays: Set<NDKRelay> = new Set();
ndk.pool?.relays.forEach((relay) => {
if (!relay.complaining) {
relays.add(relay);
} else {
ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);
}
});
return new NDKRelaySet(relays, ndk);
}
/**
* Calculates a number of RelaySets for each filter.
* @param ndk
* @param filters
*/
export function calculateRelaySetsFromFilters(
ndk: NDK,
filters: NDKFilter[]
| ): Map<NDKFilter, NDKRelaySet> { |
const sets: Map<NDKFilter, NDKRelaySet> = new Map();
filters.forEach((filter) => {
const set = calculateRelaySetFromFilter(ndk, filter);
sets.set(filter, set);
});
return sets;
}
| src/relay/sets/calculate.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " ndk: NDK,\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n subId?: string\n ) {\n super();\n this.ndk = ndk;\n this.opts = { ...defaultOpts, ...(opts || {}) };\n this.filters = filters instanceof Array ? filters : [filters];",
"score": 29.66119116156912
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 26.490198991480117
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": "export function mergeFilters(filters: NDKFilter[]): NDKFilter {\n const result: any = {};\n filters.forEach((filter) => {\n Object.entries(filter).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n if (result[key] === undefined) {\n result[key] = [...value];\n } else {\n result[key] = Array.from(\n new Set([...result[key], ...value])",
"score": 23.692681971157498
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " readonly subId: string;\n readonly filters: NDKFilter[];\n readonly opts: NDKSubscriptionOptions;\n public relaySet?: NDKRelaySet;\n public ndk: NDK;\n public relaySubscriptions: Map<NDKRelay, Sub>;\n private debug: debug.Debugger;\n /**\n * Events that have been seen by the subscription, with the time they were first seen.\n */",
"score": 20.867792992210834
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 20.094447835810033
}
] | typescript | ): Map<NDKFilter, NDKRelaySet> { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
| nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);",
"score": 25.102305057858402
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));",
"score": 23.358468255986065
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " */\n public activeSubscriptions = new Set<NDKSubscription>();\n public constructor(url: string) {\n super();\n this.url = url;\n this.relay = relayInit(url);\n this.scores = new Map<User, NDKRelayScore>();\n this._status = NDKRelayStatus.DISCONNECTED;\n this.debug = debug(`ndk:relay:${url}`);\n this.relay.on(\"connect\", () => {",
"score": 18.02438446635088
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }",
"score": 17.081350534331573
},
{
"filename": "src/events/repost.ts",
"retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);",
"score": 16.44031311166483
}
] | typescript | nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub. | on("event", (e) => this.handleIncomingEvent(e)); |
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " const localUser = await this.signer.user();\n const remoteUser = this.ndk.getUser({ hexpubkey: remotePubkey });\n const event = new NDKEvent(this.ndk, {\n kind,\n content: JSON.stringify(res),\n tags: [[\"p\", remotePubkey]],\n pubkey: localUser.hexpubkey(),\n } as NostrEvent);\n event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);",
"score": 38.89264997875221
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " }\n /**\n * Subscribe to a filter. This function will resolve once the subscription is ready.\n */\n public async subscribe(filter: NDKFilter): Promise<NDKSubscription> {\n const sub = this.ndk.subscribe(filter, { closeOnEose: false });\n sub.on(\"event\", async (event: NDKEvent) => {\n try {\n const parsedEvent = await this.parseEvent(event);\n if ((parsedEvent as NDKRpcRequest).method) {",
"score": 33.853514089730474
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);",
"score": 33.786281187319595
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " const user = this.ndk.getUser({ npub: localUser.npub });\n // Generates subscription, single subscription for the lifetime of our connection\n await this.rpc.subscribe({\n kinds: [24133 as number],\n \"#p\": [localUser.hexpubkey()],\n });\n return new Promise((resolve, reject) => {\n // There is a race condition between the subscription and sending the request;\n // introducing a small delay here to give a clear priority to the subscription\n // to happen first",
"score": 33.45687370420806
},
{
"filename": "src/events/repost.ts",
"retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);",
"score": 31.674488150143475
}
] | typescript | on("event", (e) => this.handleIncomingEvent(e)); |
import { sha256 } from "@noble/hashes/sha256";
import { bytesToHex } from "@noble/hashes/utils";
import NDKEvent from "../../events/index.js";
import type NDK from "../../index.js";
import {
NDKSubscription,
NDKSubscriptionGroup,
} from "../../subscription/index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
/**
* A relay set is a group of relays. This grouping can be short-living, for a single
* REQ or can be long-lasting, for example for the explicit relay list the user
* has specified.
*
* Requests to relays should be sent through this interface.
*/
export class NDKRelaySet {
readonly relays: Set<NDKRelay>;
private debug: debug.Debugger;
private ndk: NDK;
public constructor(relays: Set<NDKRelay>, ndk: NDK) {
this.relays = relays;
this.ndk = ndk;
this.debug = ndk.debug.extend("relayset");
}
/**
* Adds a relay to this set.
*/
public addRelay(relay: NDKRelay) {
this.relays.add(relay);
}
/**
* Creates a relay set from a list of relay URLs.
*
* This is useful for testing in development to pass a local relay
* to publish methods.
*
* @param relayUrls - list of relay URLs to include in this set
* @param ndk
* @returns NDKRelaySet
*/
static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {
const relays = new Set<NDKRelay>();
for (const url of relayUrls) {
const relay = ndk.pool.relays.get(url);
if (relay) {
relays.add(relay);
}
}
return new NDKRelaySet(new Set(relays), ndk);
}
private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) {
const sub = relay.subscribe(subscription);
subscription.relaySubscriptions.set(relay, sub);
}
/**
* Calculates an ID of this specific combination of relays.
*/
public getId() {
const urls = Array.from(this.relays).map((r) => r.url);
const urlString = urls.sort().join(",");
return bytesToHex(sha256(urlString));
}
/**
* Add a subscription to this relay set
*/
public subscribe(subscription: NDKSubscription): NDKSubscription {
const subGroupableId = subscription.groupableId();
const groupableId = `${this.getId()}:${subGroupableId}`;
if (!subGroupableId) {
this.executeSubscription(subscription);
return subscription;
}
const delayedSubscription =
this.ndk.delayedSubscriptions.get(groupableId);
if (delayedSubscription) {
delayedSubscription.push(subscription);
} else {
setTimeout(() => {
this.executeDelayedSubscription(groupableId);
}, subscription.opts.groupableDelay);
this.ndk.delayedSubscriptions.set(groupableId, [subscription]);
}
return subscription;
}
private executeDelayedSubscription(groupableId: string) {
const subscriptions = this.ndk.delayedSubscriptions.get(groupableId);
this.ndk.delayedSubscriptions.delete(groupableId);
if (subscriptions) {
if (subscriptions.length > 1) {
this.executeSubscriptions(subscriptions);
} else {
this.executeSubscription(subscriptions[0]);
}
}
}
/**
* This function takes a similar group of subscriptions, merges the filters
* and sends a single subscription to the relay.
*/
private executeSubscriptions(subscriptions: NDKSubscription[]) {
const ndk = subscriptions[0].ndk;
const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);
this.executeSubscription(subGroup);
}
private executeSubscription(
subscription: NDKSubscription
): NDKSubscription {
this.debug("subscribing", { filters: subscription.filters });
for (const relay of this.relays) {
if (relay.status === NDKRelayStatus.CONNECTED) {
// If the relay is already connected, subscribe immediately
this.subscribeOnRelay(relay, subscription);
} else {
// If the relay is not connected, add a one-time listener to wait for the 'connected' event
const connectedListener = () => {
this.debug(
"new relay coming online for active subscription",
{
relay: relay.url,
filters: subscription.filters,
}
);
this.subscribeOnRelay(relay, subscription);
};
relay.once("connect", connectedListener);
// Add a one-time listener to remove the connectedListener when the subscription stops
subscription.once("close", () => {
relay.removeListener("connect", connectedListener);
});
}
}
return subscription;
}
/**
* Publish an event to all relays in this set. Returns the number of relays that have received the event.
* @param event
* @param timeoutMs - timeout in milliseconds for each publish operation and connection operation
* @returns A set where the event was successfully published to
*/
public async publish(
event | : NDKEvent,
timeoutMs?: number
): Promise<Set<NDKRelay>> { |
const publishedToRelays: Set<NDKRelay> = new Set();
// go through each relay and publish the event
const promises: Promise<void>[] = Array.from(this.relays).map(
(relay: NDKRelay) => {
return new Promise<void>((resolve) => {
relay
.publish(event, timeoutMs)
.then(() => {
publishedToRelays.add(relay);
resolve();
})
.catch((err) => {
this.debug("error publishing to relay", {
relay: relay.url,
err,
});
resolve();
});
});
}
);
await Promise.all(promises);
if (publishedToRelays.size === 0) {
throw new Error("No relay was able to receive the event");
}
return publishedToRelays;
}
public size(): number {
return this.relays.size;
}
}
| src/relay/sets/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @param timeoutMs The timeout for the publish operation in milliseconds\n * @returns A promise that resolves when the event has been published or rejects if the operation times out\n */\n public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {\n if (this.status === NDKRelayStatus.CONNECTED) {\n return this.publishEvent(event, timeoutMs);\n } else {\n this.once(\"connect\", () => {\n this.publishEvent(event, timeoutMs);\n });",
"score": 67.50440831192849
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,",
"score": 66.18418635735323
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 57.95092414020647
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " * @returns {Promise<void>} A promise that resolves when all connection attempts have completed.\n * @throws {Error} If any of the connection attempts result in an error or timeout.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n const promises: Promise<void>[] = [];\n this.debug(\n `Connecting to ${this.relays.size} relays${\n timeoutMs ? `, timeout ${timeoutMs}...` : \"\"\n }`\n );",
"score": 57.759664683077126
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " this.emit(\"relay:connect\", this.relays.get(relayUrl));\n if (this.stats().connected === this.relays.size) {\n this.emit(\"connect\");\n }\n }\n /**\n * Attempts to establish a connection to each relay in the pool.\n *\n * @async\n * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.",
"score": 53.113065285482925
}
] | typescript | : NDKEvent,
timeoutMs?: number
): Promise<Set<NDKRelay>> { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
| senderUser: NDKUser,
payload: string
) { |
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/nip04-decrypt.ts",
"retrieved_chunk": " const [senderPubkey, payload] = params;\n const senderUser = new NDKUser({ hexpubkey: senderPubkey });\n const decryptedPayload = await backend.decrypt(\n remotePubkey,\n senderUser,\n payload\n );\n return JSON.stringify([decryptedPayload]);\n }\n}",
"score": 25.030520198713226
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public async decrypt(sender: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for decryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_decrypt\",\n [sender.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {\n if (!response.error) {",
"score": 14.26169861504397
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " */\nexport class NDKNip46Signer implements NDKSigner {\n private ndk: NDK;\n public remoteUser: NDKUser;\n public remotePubkey: string;\n public token: string | undefined;\n public localSigner: NDKSigner;\n private rpc: NDKNostrRpc;\n private debug: debug.Debugger;\n /**",
"score": 13.113228482709076
},
{
"filename": "src/signers/private-key/index.ts",
"retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to encrypt without a private key\");\n }\n const recipientHexPubKey = recipient.hexpubkey();\n return await nip04.encrypt(this.privateKey, recipientHexPubKey, value);\n }\n public async decrypt(sender: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {",
"score": 12.876257537146952
},
{
"filename": "src/signers/nip46/backend/nip04-encrypt.ts",
"retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04EncryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {",
"score": 12.565433514488888
}
] | typescript | senderUser: NDKUser,
payload: string
) { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key | : new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/get-public-key.ts",
"retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class GetPublicKeyHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n return backend.localUser?.hexpubkey();",
"score": 14.507798504988175
},
{
"filename": "src/signers/nip46/backend/connect.ts",
"retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;",
"score": 14.507798504988175
},
{
"filename": "src/signers/nip46/backend/nip04-encrypt.ts",
"retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class DescribeHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const keys = Object.keys(backend.handlers);",
"score": 14.16875159626697
},
{
"filename": "src/signers/nip46/backend/nip04-decrypt.ts",
"retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04EncryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {",
"score": 14.16875159626697
},
{
"filename": "src/signers/nip46/backend/describe.ts",
"retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04DecryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {",
"score": 14.16875159626697
}
] | typescript | : new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
| nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);",
"score": 25.102305057858402
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));",
"score": 23.358468255986065
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " */\n public activeSubscriptions = new Set<NDKSubscription>();\n public constructor(url: string) {\n super();\n this.url = url;\n this.relay = relayInit(url);\n this.scores = new Map<User, NDKRelayScore>();\n this._status = NDKRelayStatus.DISCONNECTED;\n this.debug = debug(`ndk:relay:${url}`);\n this.relay.on(\"connect\", () => {",
"score": 18.02438446635088
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }",
"score": 17.081350534331573
},
{
"filename": "src/events/repost.ts",
"retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);",
"score": 16.44031311166483
}
] | typescript | nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
}; |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
| describe: new DescribeEventHandlingStrategy(),
}; |
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);",
"score": 25.102305057858402
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));",
"score": 23.358468255986065
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " */\n public activeSubscriptions = new Set<NDKSubscription>();\n public constructor(url: string) {\n super();\n this.url = url;\n this.relay = relayInit(url);\n this.scores = new Map<User, NDKRelayScore>();\n this._status = NDKRelayStatus.DISCONNECTED;\n this.debug = debug(`ndk:relay:${url}`);\n this.relay.on(\"connect\", () => {",
"score": 18.02438446635088
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }",
"score": 17.081350534331573
},
{
"filename": "src/events/repost.ts",
"retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);",
"score": 16.44031311166483
}
] | typescript | describe: new DescribeEventHandlingStrategy(),
}; |
import { sha256 } from "@noble/hashes/sha256";
import { bytesToHex } from "@noble/hashes/utils";
import NDKEvent from "../../events/index.js";
import type NDK from "../../index.js";
import {
NDKSubscription,
NDKSubscriptionGroup,
} from "../../subscription/index.js";
import { NDKRelay, NDKRelayStatus } from "../index.js";
/**
* A relay set is a group of relays. This grouping can be short-living, for a single
* REQ or can be long-lasting, for example for the explicit relay list the user
* has specified.
*
* Requests to relays should be sent through this interface.
*/
export class NDKRelaySet {
readonly relays: Set<NDKRelay>;
private debug: debug.Debugger;
private ndk: NDK;
public constructor(relays: Set<NDKRelay>, ndk: NDK) {
this.relays = relays;
this.ndk = ndk;
this.debug = ndk.debug.extend("relayset");
}
/**
* Adds a relay to this set.
*/
public addRelay(relay: NDKRelay) {
this.relays.add(relay);
}
/**
* Creates a relay set from a list of relay URLs.
*
* This is useful for testing in development to pass a local relay
* to publish methods.
*
* @param relayUrls - list of relay URLs to include in this set
* @param ndk
* @returns NDKRelaySet
*/
static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {
const relays = new Set<NDKRelay>();
for (const url of relayUrls) {
const relay = ndk.pool.relays.get(url);
if (relay) {
relays.add(relay);
}
}
return new NDKRelaySet(new Set(relays), ndk);
}
private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) {
const sub = relay.subscribe(subscription);
subscription.relaySubscriptions.set(relay, sub);
}
/**
* Calculates an ID of this specific combination of relays.
*/
public getId() {
const urls = Array.from(this.relays).map((r) => r.url);
const urlString = urls.sort().join(",");
return bytesToHex(sha256(urlString));
}
/**
* Add a subscription to this relay set
*/
public subscribe(subscription: NDKSubscription): NDKSubscription {
const subGroupableId = subscription.groupableId();
const groupableId = `${this.getId()}:${subGroupableId}`;
if (!subGroupableId) {
this.executeSubscription(subscription);
return subscription;
}
const delayedSubscription =
this.ndk.delayedSubscriptions.get(groupableId);
if (delayedSubscription) {
delayedSubscription.push(subscription);
} else {
setTimeout(() => {
this.executeDelayedSubscription(groupableId);
}, subscription.opts.groupableDelay);
this.ndk.delayedSubscriptions.set(groupableId, [subscription]);
}
return subscription;
}
private executeDelayedSubscription(groupableId: string) {
const subscriptions = this.ndk.delayedSubscriptions.get(groupableId);
this.ndk.delayedSubscriptions.delete(groupableId);
if (subscriptions) {
if (subscriptions.length > 1) {
this.executeSubscriptions(subscriptions);
} else {
this.executeSubscription(subscriptions[0]);
}
}
}
/**
* This function takes a similar group of subscriptions, merges the filters
* and sends a single subscription to the relay.
*/
private executeSubscriptions(subscriptions: NDKSubscription[]) {
const ndk = subscriptions[0].ndk;
const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);
this.executeSubscription(subGroup);
}
private executeSubscription(
subscription: NDKSubscription
): NDKSubscription {
this.debug("subscribing", { filters: subscription.filters });
for (const relay of this.relays) {
if (relay.status === NDKRelayStatus.CONNECTED) {
// If the relay is already connected, subscribe immediately
this.subscribeOnRelay(relay, subscription);
} else {
// If the relay is not connected, add a one-time listener to wait for the 'connected' event
const connectedListener = () => {
this.debug(
"new relay coming online for active subscription",
{
relay: relay.url,
filters: subscription.filters,
}
);
this.subscribeOnRelay(relay, subscription);
};
relay.once("connect", connectedListener);
// Add a one-time listener to remove the connectedListener when the subscription stops
subscription.once("close", () => {
relay.removeListener("connect", connectedListener);
});
}
}
return subscription;
}
/**
* Publish an event to all relays in this set. Returns the number of relays that have received the event.
* @param event
* @param timeoutMs - timeout in milliseconds for each publish operation and connection operation
* @returns A set where the event was successfully published to
*/
public async publish(
event: | NDKEvent,
timeoutMs?: number
): Promise<Set<NDKRelay>> { |
const publishedToRelays: Set<NDKRelay> = new Set();
// go through each relay and publish the event
const promises: Promise<void>[] = Array.from(this.relays).map(
(relay: NDKRelay) => {
return new Promise<void>((resolve) => {
relay
.publish(event, timeoutMs)
.then(() => {
publishedToRelays.add(relay);
resolve();
})
.catch((err) => {
this.debug("error publishing to relay", {
relay: relay.url,
err,
});
resolve();
});
});
}
);
await Promise.all(promises);
if (publishedToRelays.size === 0) {
throw new Error("No relay was able to receive the event");
}
return publishedToRelays;
}
public size(): number {
return this.relays.size;
}
}
| src/relay/sets/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @param timeoutMs The timeout for the publish operation in milliseconds\n * @returns A promise that resolves when the event has been published or rejects if the operation times out\n */\n public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {\n if (this.status === NDKRelayStatus.CONNECTED) {\n return this.publishEvent(event, timeoutMs);\n } else {\n this.once(\"connect\", () => {\n this.publishEvent(event, timeoutMs);\n });",
"score": 67.50440831192849
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,",
"score": 66.18418635735323
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 57.95092414020647
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " * @returns {Promise<void>} A promise that resolves when all connection attempts have completed.\n * @throws {Error} If any of the connection attempts result in an error or timeout.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n const promises: Promise<void>[] = [];\n this.debug(\n `Connecting to ${this.relays.size} relays${\n timeoutMs ? `, timeout ${timeoutMs}...` : \"\"\n }`\n );",
"score": 57.759664683077126
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " this.emit(\"relay:connect\", this.relays.get(relayUrl));\n if (this.stats().connected === this.relays.size) {\n this.emit(\"connect\");\n }\n }\n /**\n * Attempts to establish a connection to each relay in the pool.\n *\n * @async\n * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt.",
"score": 53.113065285482925
}
] | typescript | NDKEvent,
timeoutMs?: number
): Promise<Set<NDKRelay>> { |
import debug from "debug";
import type { NostrEvent } from "../../events/index.js";
import NDKUser from "../../user/index.js";
import { NDKSigner } from "../index.js";
type Nip04QueueItem = {
type: "encrypt" | "decrypt";
counterpartyHexpubkey: string;
value: string;
resolve: (value: string) => void;
reject: (reason?: Error) => void;
};
/**
* NDKNip07Signer implements the NDKSigner interface for signing Nostr events
* with a NIP-07 browser extension (e.g., getalby, nos2x).
*/
export class NDKNip07Signer implements NDKSigner {
private _userPromise: Promise<NDKUser> | undefined;
public nip04Queue: Nip04QueueItem[] = [];
private nip04Processing = false;
private debug: debug.Debugger;
public constructor() {
if (!window.nostr) {
throw new Error("NIP-07 extension not available");
}
this.debug = debug("ndk:nip07");
}
public async blockUntilReady(): Promise<NDKUser> {
const pubkey = await window.nostr?.getPublicKey();
// If the user rejects granting access, error out
if (!pubkey) {
throw new Error("User rejected access");
}
return new NDKUser({ hexpubkey: pubkey });
}
/**
* Getter for the user property.
* @returns The NDKUser instance.
*/
public async user(): Promise<NDKUser> {
if (!this._userPromise) {
this._userPromise = this.blockUntilReady();
}
return this._userPromise;
}
/**
* Signs the given Nostr event.
* @param event - The Nostr event to be signed.
* @returns The signature of the signed event.
* @throws Error if the NIP-07 is not available on the window object.
*/
public async sign(event: NostrEvent): Promise<string> {
if (!window.nostr) {
throw new Error("NIP-07 extension not available");
}
const signedEvent = await window.nostr.signEvent(event);
return signedEvent.sig;
}
public async encrypt(recipient: NDKUser, value: string): Promise<string> {
if (!window.nostr) {
throw new Error("NIP-07 extension not available");
}
const recipientHexPubKey = recipient.hexpubkey();
return this.queueNip04("encrypt", recipientHexPubKey, value);
}
public async decrypt(sender: NDKUser, value: string): Promise<string> {
if (!window.nostr) {
throw new Error("NIP-07 extension not available");
}
const senderHexPubKey = sender.hexpubkey();
return this.queueNip04("decrypt", senderHexPubKey, value);
}
private async queueNip04(
type: "encrypt" | "decrypt",
counterpartyHexpubkey: string,
value: string
): Promise<string> {
return new Promise((resolve, reject) => {
this.nip04Queue.push({
type,
counterpartyHexpubkey,
value,
resolve,
reject,
});
if (!this.nip04Processing) {
this.processNip04Queue();
}
});
}
private async processNip04Queue(
item?: Nip04QueueItem,
retries = 0
): Promise<void> {
if (!item && this.nip04Queue.length === 0) {
this.nip04Processing = false;
return;
}
this.nip04Processing = true;
const { type, counterpartyHexpubkey, value, resolve, reject } =
item || this.nip04Queue.shift()!;
this.debug("Processing encryption queue item", {
type,
counterpartyHexpubkey,
value,
});
try {
let result;
if (type === "encrypt") {
result = await window.nostr!.nip04.encrypt(
counterpartyHexpubkey,
value
);
} else {
result = await window.nostr!.nip04.decrypt(
counterpartyHexpubkey,
value
);
}
resolve(result);
} catch (error: any) {
// retry a few times if the call is already executing
if (
error.message &&
error.message.includes("call already executing")
) {
if (retries < 5) {
this.debug("Retrying encryption queue item", {
type,
counterpartyHexpubkey,
value,
retries,
});
setTimeout(() => {
this.processNip04Queue(item, retries + 1);
}, 50 * retries);
return;
}
}
reject(error);
}
this.processNip04Queue();
}
}
declare global {
interface Window {
nostr?: {
getPublicKey(): Promise<string>;
| signEvent(event: NostrEvent): Promise<{ sig: string }>; |
nip04: {
encrypt(
recipientHexPubKey: string,
value: string
): Promise<string>;
decrypt(
senderHexPubKey: string,
value: string
): Promise<string>;
};
};
}
}
| src/signers/nip07/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public async decrypt(sender: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for decryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_decrypt\",\n [sender.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {\n if (!response.error) {",
"score": 16.712769154422222
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public async sign(event: NostrEvent): Promise<string> {\n this.debug(\"asking for a signature\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"sign_event\",\n [JSON.stringify(event)],\n 24133,\n (response: NDKRpcResponse) => {\n this.debug(\"got a response\", response);",
"score": 15.986250362594495
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " if (!response.error) {\n const json = JSON.parse(response.result);\n resolve(json.sig);\n } else {\n reject(response.error);\n }\n }\n );\n });\n return promise;",
"score": 14.74410338812054
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for encryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_encrypt\",\n [recipient.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {",
"score": 13.96219743960076
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " pubkey: string;\n method: string;\n params: string[];\n event: NDKEvent;\n}\nexport interface NDKRpcResponse {\n id: string;\n result: string;\n error?: string;\n event: NDKEvent;",
"score": 13.903448442667003
}
] | typescript | signEvent(event: NostrEvent): Promise<{ sig: string }>; |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
| protected async handleIncomingEvent(event: NDKEvent) { |
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/connect.ts",
"retrieved_chunk": " const debug = backend.debug.extend(\"connect\");\n debug(`connection request from ${pubkey}`);\n if (token && backend.applyToken) {\n debug(`applying token`);\n await backend.applyToken(pubkey, token);\n }\n if (await backend.pubkeyAllowed(pubkey, \"connect\", token)) {\n debug(`connection request from ${pubkey} allowed`);\n return \"ack\";\n } else {",
"score": 55.83590805768049
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param ndk - The NDK instance to use\n * @param token - connection token, in the form \"npub#otp\"\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, token: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remoteNpub - The npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */",
"score": 52.44564357004233
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public constructor(ndk: NDK, remoteNpub: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remotePubkey - The public key of the npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, remotePubkey: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param tokenOrRemotePubkey - The public key, or a connection token, of the npub that wants to be published as",
"score": 43.0407517548155
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 41.72488098927543
},
{
"filename": "src/signers/nip46/backend/connect.ts",
"retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;",
"score": 36.47555887717566
}
] | typescript | protected async handleIncomingEvent(event: NDKEvent) { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: | NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) { |
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public constructor(ndk: NDK, remoteNpub: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remotePubkey - The public key of the npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, remotePubkey: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param tokenOrRemotePubkey - The public key, or a connection token, of the npub that wants to be published as",
"score": 63.107585657730965
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param ndk - The NDK instance to use\n * @param token - connection token, in the form \"npub#otp\"\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, token: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remoteNpub - The npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */",
"score": 53.32202230085126
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 29.394419858456345
},
{
"filename": "src/signers/private-key/index.test.ts",
"retrieved_chunk": " \"00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff\";\n const signer = new NDKPrivateKeySigner(privateKey);\n expect(signer).toBeInstanceOf(NDKPrivateKeySigner);\n expect(signer.privateKey).toBe(privateKey);\n });\n it(\"returns a user instance with a public key corresponding to the private key\", async () => {\n const privateKey =\n \"e8eb7464168139c6ccb9111f768777f332fa1289dff11244ccfe89970ff776d4\";\n const signer = new NDKPrivateKeySigner(privateKey);\n const user = await signer.user();",
"score": 26.995747769244467
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,",
"score": 24.96370684529333
}
] | typescript | NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
| recipientUser: NDKUser,
payload: string
) { |
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise<NDKEvent | undefined> {
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/nip04-decrypt.ts",
"retrieved_chunk": " const [senderPubkey, payload] = params;\n const senderUser = new NDKUser({ hexpubkey: senderPubkey });\n const decryptedPayload = await backend.decrypt(\n remotePubkey,\n senderUser,\n payload\n );\n return JSON.stringify([decryptedPayload]);\n }\n}",
"score": 42.183689796204604
},
{
"filename": "src/signers/nip46/backend/nip04-encrypt.ts",
"retrieved_chunk": " const [recipientPubkey, payload] = params;\n const recipientUser = new NDKUser({ hexpubkey: recipientPubkey });\n const decryptedPayload = await backend.encrypt(\n remotePubkey,\n recipientUser,\n payload\n );\n return decryptedPayload;\n }\n}",
"score": 39.16748974493024
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}",
"score": 27.795052935990647
},
{
"filename": "src/signers/private-key/index.ts",
"retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to encrypt without a private key\");\n }\n const recipientHexPubKey = recipient.hexpubkey();\n return await nip04.encrypt(this.privateKey, recipientHexPubKey, value);\n }\n public async decrypt(sender: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {",
"score": 26.575665373379795
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " public async decrypt(sender: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for decryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_decrypt\",\n [sender.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {\n if (!response.error) {",
"score": 26.189049283683776
}
] | typescript | recipientUser: NDKUser,
payload: string
) { |
import NDK, {
NDKPrivateKeySigner,
NDKSigner,
NDKUser,
NostrEvent,
} from "../../index.js";
import { NDKNostrRpc, NDKRpcResponse } from "./rpc.js";
/**
* This NDKSigner implements NIP-46, which allows remote signing of events.
* This class is meant to be used client-side, paired with the NDKNip46Backend or a NIP-46 backend (like Nostr-Connect)
*/
export class NDKNip46Signer implements NDKSigner {
private ndk: NDK;
public remoteUser: NDKUser;
public remotePubkey: string;
public token: string | undefined;
public localSigner: NDKSigner;
private rpc: NDKNostrRpc;
private debug: debug.Debugger;
/**
* @param ndk - The NDK instance to use
* @param token - connection token, in the form "npub#otp"
* @param localSigner - The signer that will be used to request events to be signed
*/
public constructor(ndk: NDK, token: string, localSigner?: NDKSigner);
/**
* @param ndk - The NDK instance to use
* @param remoteNpub - The npub that wants to be published as
* @param localSigner - The signer that will be used to request events to be signed
*/
public constructor(ndk: NDK, remoteNpub: string, localSigner?: NDKSigner);
/**
* @param ndk - The NDK instance to use
* @param remotePubkey - The public key of the npub that wants to be published as
* @param localSigner - The signer that will be used to request events to be signed
*/
public constructor(ndk: NDK, remotePubkey: string, localSigner?: NDKSigner);
/**
* @param ndk - The NDK instance to use
* @param tokenOrRemotePubkey - The public key, or a connection token, of the npub that wants to be published as
* @param localSigner - The signer that will be used to request events to be signed
*/
public constructor(
ndk: NDK,
tokenOrRemotePubkey: string,
localSigner?: NDKSigner
) {
let remotePubkey: string;
let token: string | undefined;
if (tokenOrRemotePubkey.includes("#")) {
const parts = tokenOrRemotePubkey.split("#");
remotePubkey = new NDKUser({ npub: parts[0] }).hexpubkey();
token = parts[1];
} else if (tokenOrRemotePubkey.startsWith("npub")) {
remotePubkey = new NDKUser({
npub: tokenOrRemotePubkey,
}).hexpubkey();
} else {
remotePubkey = tokenOrRemotePubkey;
}
this.ndk = ndk;
this.remotePubkey = remotePubkey;
this.token = token;
this.debug = ndk.debug.extend("nip46:signer");
this.remoteUser = new NDKUser({ hexpubkey: remotePubkey });
if (!localSigner) {
this.localSigner = NDKPrivateKeySigner.generate();
} else {
this.localSigner = localSigner;
}
this.rpc = new NDKNostrRpc(ndk, this.localSigner, this.debug);
}
/**
* Get the user that is being published as
*/
public async user(): Promise<NDKUser> {
return this.remoteUser;
}
public async blockUntilReady(): Promise<NDKUser> {
const localUser = await this.localSigner.user();
const user = this.ndk.getUser({ npub: localUser.npub });
// Generates subscription, single subscription for the lifetime of our connection
await this.rpc.subscribe({
kinds: [24133 as number],
"#p": [localUser.hexpubkey()],
});
return new Promise((resolve, reject) => {
// There is a race condition between the subscription and sending the request;
// introducing a small delay here to give a clear priority to the subscription
// to happen first
setTimeout(() => {
const connectParams = [localUser.hexpubkey()];
if (this.token) {
connectParams.push(this.token);
}
this.rpc.sendRequest(
this.remotePubkey,
"connect",
connectParams,
24133,
| (response: NDKRpcResponse) => { |
if (response.result === "ack") {
resolve(user);
} else {
reject(response.error);
}
}
);
}, 100);
});
}
public async encrypt(recipient: NDKUser, value: string): Promise<string> {
this.debug("asking for encryption");
const promise = new Promise<string>((resolve, reject) => {
this.rpc.sendRequest(
this.remotePubkey,
"nip04_encrypt",
[recipient.hexpubkey(), value],
24133,
(response: NDKRpcResponse) => {
if (!response.error) {
resolve(response.result);
} else {
reject(response.error);
}
}
);
});
return promise;
}
public async decrypt(sender: NDKUser, value: string): Promise<string> {
this.debug("asking for decryption");
const promise = new Promise<string>((resolve, reject) => {
this.rpc.sendRequest(
this.remotePubkey,
"nip04_decrypt",
[sender.hexpubkey(), value],
24133,
(response: NDKRpcResponse) => {
if (!response.error) {
const value = JSON.parse(response.result);
resolve(value[0]);
} else {
reject(response.error);
}
}
);
});
return promise;
}
public async sign(event: NostrEvent): Promise<string> {
this.debug("asking for a signature");
const promise = new Promise<string>((resolve, reject) => {
this.rpc.sendRequest(
this.remotePubkey,
"sign_event",
[JSON.stringify(event)],
24133,
(response: NDKRpcResponse) => {
this.debug("got a response", response);
if (!response.error) {
const json = JSON.parse(response.result);
resolve(json.sig);
} else {
reject(response.error);
}
}
);
});
return promise;
}
}
| src/signers/nip46/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " public async sendRequest(\n remotePubkey: string,\n method: string,\n params: string[] = [],\n kind = 24133,\n cb?: (res: NDKRpcResponse) => void\n ) {\n const id = Math.random().toString(36).substring(7);\n const localUser = await this.signer.user();\n const remoteUser = this.ndk.getUser({ hexpubkey: remotePubkey });",
"score": 31.46408734915375
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " } else {\n this.debug(\"unsupported method\", { method, params });\n }\n if (response) {\n this.debug(`sending response to ${remotePubkey}`, response);\n this.rpc.sendResponse(id, remotePubkey, response);\n } else {\n this.rpc.sendResponse(\n id,\n remotePubkey,",
"score": 27.892100486478995
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " */\n async applyToken(pubkey: string, token: string): Promise<void> {\n throw new Error(\"connection token not supported\");\n }\n protected async handleIncomingEvent(event: NDKEvent) {\n const { id, method, params } = (await this.rpc.parseEvent(\n event\n )) as any;\n const remotePubkey = event.pubkey;\n let response: string | undefined;",
"score": 26.77305544427018
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " const request = { id, method, params };\n const promise = new Promise<NDKRpcResponse>((resolve) => {\n if (cb) this.once(`response-${id}`, cb);\n });\n const event = new NDKEvent(this.ndk, {\n kind,\n content: JSON.stringify(request),\n tags: [[\"p\", remotePubkey]],\n pubkey: localUser.hexpubkey(),\n } as NostrEvent);",
"score": 24.334538852372912
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " const localUser = await this.signer.user();\n const remoteUser = this.ndk.getUser({ hexpubkey: remotePubkey });\n const event = new NDKEvent(this.ndk, {\n kind,\n content: JSON.stringify(res),\n tags: [[\"p\", remotePubkey]],\n pubkey: localUser.hexpubkey(),\n } as NostrEvent);\n event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);",
"score": 20.928214838679523
}
] | typescript | (response: NDKRpcResponse) => { |
import { verifySignature, Event } from "nostr-tools";
import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js";
import { NDKNostrRpc } from "../rpc.js";
import ConnectEventHandlingStrategy from "./connect.js";
import DescribeEventHandlingStrategy from "./describe.js";
import GetPublicKeyHandlingStrategy from "./get-public-key.js";
import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js";
import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js";
import SignEventHandlingStrategy from "./sign-event.js";
export type Nip46PermitCallback = (
pubkey: string,
method: string,
params?: any
) => Promise<boolean>;
export type Nip46ApplyTokenCallback = (
pubkey: string,
token: string
) => Promise<void>;
export interface IEventHandlingStrategy {
handle(
backend: NDKNip46Backend,
remotePubkey: string,
params: string[]
): Promise<string | undefined>;
}
/**
* This class implements a NIP-46 backend, meaning that it will hold a private key
* of the npub that wants to be published as.
*
* This backend is meant to be used by an NDKNip46Signer, which is the class that
* should run client-side, where the user wants to sign events from.
*/
export class NDKNip46Backend {
readonly ndk: NDK;
readonly signer: NDKPrivateKeySigner;
public localUser?: NDKUser;
readonly debug: debug.Debugger;
private rpc: NDKNostrRpc;
private permitCallback: Nip46PermitCallback;
/**
* @param ndk The NDK instance to use
* @param privateKey The private key of the npub that wants to be published as
*/
public constructor(
ndk: NDK,
privateKey: string,
permitCallback: Nip46PermitCallback
) {
this.ndk = ndk;
this.signer = new NDKPrivateKeySigner(privateKey);
this.debug = ndk.debug.extend("nip46:backend");
this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);
this.permitCallback = permitCallback;
}
/**
* This method starts the backend, which will start listening for incoming
* requests.
*/
public async start() {
this.localUser = await this.signer.user();
const sub = this.ndk.subscribe(
{
kinds: [24133 as number],
"#p": [this.localUser.hexpubkey()],
},
{ closeOnEose: false }
);
sub.on("event", (e) => this.handleIncomingEvent(e));
}
public handlers: { [method: string]: IEventHandlingStrategy } = {
connect: new ConnectEventHandlingStrategy(),
sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(),
get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(),
};
/**
* Enables the user to set a custom strategy for handling incoming events.
* @param method - The method to set the strategy for
* @param strategy - The strategy to set
*/
public setStrategy(method: string, strategy: IEventHandlingStrategy) {
this.handlers[method] = strategy;
}
/**
* Overload this method to apply tokens, which can
* wrap permission sets to be applied to a pubkey.
* @param pubkey public key to apply token to
* @param token token to apply
*/
async applyToken(pubkey: string, token: string): Promise<void> {
throw new Error("connection token not supported");
}
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent(
event
)) as any;
const remotePubkey = event.pubkey;
let response: string | undefined;
this.debug("incoming event", { id, method, params });
// validate signature explicitly
if (!verifySignature(event.rawEvent() as Event<any>)) {
this.debug("invalid signature", event.rawEvent());
return;
}
const strategy = this.handlers[method];
if (strategy) {
try {
response = await strategy.handle(this, remotePubkey, params);
} catch (e: any) {
this.debug("error handling event", e, { id, method, params });
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
e.message
);
}
} else {
this.debug("unsupported method", { method, params });
}
if (response) {
this.debug(`sending response to ${remotePubkey}`, response);
this.rpc.sendResponse(id, remotePubkey, response);
} else {
this.rpc.sendResponse(
id,
remotePubkey,
"error",
undefined,
"Not authorized"
);
}
}
public async decrypt(
remotePubkey: string,
senderUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) {
this.debug(`decrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.decrypt(senderUser, payload);
}
public async encrypt(
remotePubkey: string,
recipientUser: NDKUser,
payload: string
) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) {
this.debug(`encrypt request from ${remotePubkey} rejected`);
return undefined;
}
return await this.signer.encrypt(recipientUser, payload);
}
public async signEvent(
remotePubkey: string,
params: string[]
): Promise | <NDKEvent | undefined> { |
const [eventString] = params;
this.debug(`sign event request from ${remotePubkey}`);
const event = new NDKEvent(this.ndk, JSON.parse(eventString));
this.debug("event to sign", event.rawEvent());
if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) {
this.debug(`sign event request from ${remotePubkey} rejected`);
return undefined;
}
this.debug(`sign event request from ${remotePubkey} allowed`);
await event.sign(this.signer);
return event;
}
/**
* This method should be overriden by the user to allow or reject incoming
* connections.
*/
public async pubkeyAllowed(
pubkey: string,
method: string,
params?: any
): Promise<boolean> {
return this.permitCallback(pubkey, method, params);
}
}
| src/signers/nip46/backend/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/nip04-encrypt.ts",
"retrieved_chunk": " const [recipientPubkey, payload] = params;\n const recipientUser = new NDKUser({ hexpubkey: recipientPubkey });\n const decryptedPayload = await backend.encrypt(\n remotePubkey,\n recipientUser,\n payload\n );\n return decryptedPayload;\n }\n}",
"score": 38.243784736816295
},
{
"filename": "src/signers/nip46/backend/sign-event.ts",
"retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);",
"score": 33.064325672084216
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}",
"score": 31.15850205964368
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for encryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_encrypt\",\n [recipient.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {",
"score": 27.362539935258912
},
{
"filename": "src/signers/private-key/index.ts",
"retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to encrypt without a private key\");\n }\n const recipientHexPubKey = recipient.hexpubkey();\n return await nip04.encrypt(this.privateKey, recipientHexPubKey, value);\n }\n public async decrypt(sender: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {",
"score": 25.507902944752644
}
] | typescript | <NDKEvent | undefined> { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions | : Map<NDKRelay, Sub>; |
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 46.31022428959896
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 34.49883565331663
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 34.13066903679356
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " * should run client-side, where the user wants to sign events from.\n */\nexport class NDKNip46Backend {\n readonly ndk: NDK;\n readonly signer: NDKPrivateKeySigner;\n public localUser?: NDKUser;\n readonly debug: debug.Debugger;\n private rpc: NDKNostrRpc;\n private permitCallback: Nip46PermitCallback;\n /**",
"score": 33.22898866590875
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 31.527404920070378
}
] | typescript | : Map<NDKRelay, Sub>; |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
| public relaySubscriptions: Map<NDKRelay, Sub>; |
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 54.32806600923712
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 41.87215407015489
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 39.31294260720486
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 34.13066903679356
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " * should run client-side, where the user wants to sign events from.\n */\nexport class NDKNip46Backend {\n readonly ndk: NDK;\n readonly signer: NDKPrivateKeySigner;\n public localUser?: NDKUser;\n readonly debug: debug.Debugger;\n private rpc: NDKNostrRpc;\n private permitCallback: Nip46PermitCallback;\n /**",
"score": 33.89512770294843
}
] | typescript | public relaySubscriptions: Map<NDKRelay, Sub>; |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
| public ndk: NDK; |
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 52.98391767758115
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 34.166924425673905
},
{
"filename": "src/subscription/utils.ts",
"retrieved_chunk": "import { NDKFilter, NDKSubscription } from \"./index.js\";\n/**\n * Checks if a subscription is fully guaranteed to have been filled.\n *\n * This is useful to determine if a cache hit fully satisfies a subscription.\n *\n * @param subscription\n * @returns\n */\nexport function queryFullyFilled(subscription: NDKSubscription): boolean {",
"score": 33.7300655185457
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " * should run client-side, where the user wants to sign events from.\n */\nexport class NDKNip46Backend {\n readonly ndk: NDK;\n readonly signer: NDKPrivateKeySigner;\n public localUser?: NDKUser;\n readonly debug: debug.Debugger;\n private rpc: NDKNostrRpc;\n private permitCallback: Nip46PermitCallback;\n /**",
"score": 32.587272064260304
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 31.972964649137385
}
] | typescript | public ndk: NDK; |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay | : Map<NDKRelay, Set<NDKEventId>> = new Map(); |
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }",
"score": 32.31279903433869
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 31.12898761946953
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " public async publish(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n const publishedToRelays: Set<NDKRelay> = new Set();\n // go through each relay and publish the event\n const promises: Promise<void>[] = Array.from(this.relays).map(\n (relay: NDKRelay) => {\n return new Promise<void>((resolve) => {\n relay",
"score": 29.052118126902823
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " */\n public activeSubscriptions = new Set<NDKSubscription>();\n public constructor(url: string) {\n super();\n this.url = url;\n this.relay = relayInit(url);\n this.scores = new Map<User, NDKRelayScore>();\n this._status = NDKRelayStatus.DISCONNECTED;\n this.debug = debug(`ndk:relay:${url}`);\n this.relay.on(\"connect\", () => {",
"score": 27.760554257335063
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 25.00109848900232
}
] | typescript | : Map<NDKRelay, Set<NDKEventId>> = new Map(); |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public | relaySet?: NDKRelaySet; |
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 51.639769345925174
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 34.166924425673905
},
{
"filename": "src/subscription/utils.ts",
"retrieved_chunk": "import { NDKFilter, NDKSubscription } from \"./index.js\";\n/**\n * Checks if a subscription is fully guaranteed to have been filled.\n *\n * This is useful to determine if a cache hit fully satisfies a subscription.\n *\n * @param subscription\n * @returns\n */\nexport function queryFullyFilled(subscription: NDKSubscription): boolean {",
"score": 33.7300655185457
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {",
"score": 30.460988338993666
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " private executeSubscriptions(subscriptions: NDKSubscription[]) {\n const ndk = subscriptions[0].ndk;\n const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);\n this.executeSubscription(subGroup);\n }\n private executeSubscription(\n subscription: NDKSubscription\n ): NDKSubscription {\n this.debug(\"subscribing\", { filters: subscription.filters });\n for (const relay of this.relays) {",
"score": 29.649742237155984
}
] | typescript | relaySet?: NDKRelaySet; |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet? | : NDKRelaySet,
subId?: string
) { |
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 47.14837825259377
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 32.54896789185439
},
{
"filename": "src/relay/sets/calculate.ts",
"retrieved_chunk": "}\n/**\n * Calculates a number of RelaySets for each filter.\n * @param ndk\n * @param filters\n */\nexport function calculateRelaySetsFromFilters(\n ndk: NDK,\n filters: NDKFilter[]\n): Map<NDKFilter, NDKRelaySet> {",
"score": 31.380667481489546
},
{
"filename": "src/relay/sets/calculate.ts",
"retrieved_chunk": " const sets: Map<NDKFilter, NDKRelaySet> = new Map();\n filters.forEach((filter) => {\n const set = calculateRelaySetFromFilter(ndk, filter);\n sets.set(filter, set);\n });\n return sets;\n}",
"score": 29.523101290715747
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);",
"score": 24.645218878573896
}
] | typescript | : NDKRelaySet,
subId?: string
) { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
| public eventFirstSeen = new Map<NDKEventId, number>(); |
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 42.56093377825676
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 41.44068452832886
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);",
"score": 37.244031599771645
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }",
"score": 37.12995852786007
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " * should run client-side, where the user wants to sign events from.\n */\nexport class NDKNip46Backend {\n readonly ndk: NDK;\n readonly signer: NDKPrivateKeySigner;\n public localUser?: NDKUser;\n readonly debug: debug.Debugger;\n private rpc: NDKNostrRpc;\n private permitCallback: Nip46PermitCallback;\n /**",
"score": 36.88322128475356
}
] | typescript | public eventFirstSeen = new Map<NDKEventId, number>(); |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if ( | queryFullyFilled(this)) { |
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " this.debug = ndk.debug.extend(\"nip46:backend\");\n this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);\n this.permitCallback = permitCallback;\n }\n /**\n * This method starts the backend, which will start listening for incoming\n * requests.\n */\n public async start() {\n this.localUser = await this.signer.user();",
"score": 20.01707915957288
},
{
"filename": "src/signers/private-key/index.ts",
"retrieved_chunk": " }\n public async user(): Promise<NDKUser> {\n await this.blockUntilReady();\n return this._user as NDKUser;\n }\n public async sign(event: NostrEvent): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to sign without a private key\");\n }\n return getSignature(event as UnsignedEvent, this.privateKey);",
"score": 19.493591094837072
},
{
"filename": "src/index.ts",
"retrieved_chunk": " relaySetSubscription.start();\n });\n }\n /**\n * Ensures that a signer is available to sign an event.\n */\n public async assertSigner() {\n if (!this.signer) {\n this.emit(\"signerRequired\");\n throw new Error(\"Signer required\");",
"score": 18.747069083288793
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " ): Promise<Set<NDKEvent> | null> {\n if (!this.ndk) throw new Error(\"NDK not set\");\n if (!this.profile) this.profile = {};\n let setMetadataEvents: Set<NDKEvent> | null = null;\n // if no options have been set and we have a cache, try to load from cache with no grouping\n // This is done in favour of simply using NDKSubscriptionCacheUsage.CACHE_FIRST since\n // we want to avoid depending on the grouping, arguably, all queries should go through this\n // type of behavior when we have a locking cache\n if (\n !opts && // if no options have been set",
"score": 18.707184526323587
},
{
"filename": "src/subscription/utils.ts",
"retrieved_chunk": "import { NDKFilter, NDKSubscription } from \"./index.js\";\n/**\n * Checks if a subscription is fully guaranteed to have been filled.\n *\n * This is useful to determine if a cache hit fully satisfies a subscription.\n *\n * @param subscription\n * @returns\n */\nexport function queryFullyFilled(subscription: NDKSubscription): boolean {",
"score": 18.69071163602647
}
] | typescript | queryFullyFilled(this)) { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
| event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) { |
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";",
"score": 32.77512921459748
},
{
"filename": "src/cache/index.ts",
"retrieved_chunk": "import NDKEvent from \"../events/index.js\";\nimport { NDKRelay } from \"../relay/index.js\";\nimport { NDKFilter, NDKSubscription } from \"../subscription/index.js\";\nexport interface NDKCacheAdapter {\n /**\n * Whether this cache adapter is expected to be fast.\n * If this is true, the cache will be queried before the relays.\n * When this is false, the cache will be queried in addition to the relays.\n */\n locking: boolean;",
"score": 32.59934682704355
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 31.12046570869522
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 29.44153703239682
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " *\n * @param relay - The relay to add to the pool.\n * @param connect - Whether or not to connect to the relay.\n */\n public addRelay(relay: NDKRelay, connect = true) {\n const relayUrl = relay.url;\n relay.on(\"notice\", (relay, notice) =>\n this.emit(\"notice\", relay, notice)\n );\n relay.on(\"connect\", () => this.handleRelayConnect(relayUrl));",
"score": 28.964974380988103
}
] | typescript | event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: | NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) { |
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";",
"score": 23.171482313944367
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 22.629565320634406
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,",
"score": 22.458652531550023
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " *\n * @param relay - The relay to add to the pool.\n * @param connect - Whether or not to connect to the relay.\n */\n public addRelay(relay: NDKRelay, connect = true) {\n const relayUrl = relay.url;\n relay.on(\"notice\", (relay, notice) =>\n this.emit(\"notice\", relay, notice)\n );\n relay.on(\"connect\", () => this.handleRelayConnect(relayUrl));",
"score": 22.34696529774513
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 20.479856061422307
}
] | typescript | NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map< | NDKRelay, Set<NDKEventId>> = new Map(); |
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }",
"score": 32.31279903433869
},
{
"filename": "src/index.ts",
"retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,",
"score": 31.12898761946953
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " public async publish(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n const publishedToRelays: Set<NDKRelay> = new Set();\n // go through each relay and publish the event\n const promises: Promise<void>[] = Array.from(this.relays).map(\n (relay: NDKRelay) => {\n return new Promise<void>((resolve) => {\n relay",
"score": 29.052118126902823
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " */\n public activeSubscriptions = new Set<NDKSubscription>();\n public constructor(url: string) {\n super();\n this.url = url;\n this.relay = relayInit(url);\n this.scores = new Map<User, NDKRelayScore>();\n this._status = NDKRelayStatus.DISCONNECTED;\n this.debug = debug(`ndk:relay:${url}`);\n this.relay.on(\"connect\", () => {",
"score": 27.760554257335063
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 25.00109848900232
}
] | typescript | NDKRelay, Set<NDKEventId>> = new Map(); |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this. | relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
); |
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " private executeSubscriptions(subscriptions: NDKSubscription[]) {\n const ndk = subscriptions[0].ndk;\n const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);\n this.executeSubscription(subGroup);\n }\n private executeSubscription(\n subscription: NDKSubscription\n ): NDKSubscription {\n this.debug(\"subscribing\", { filters: subscription.filters });\n for (const relay of this.relays) {",
"score": 19.70404637278138
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used",
"score": 19.046838368504766
},
{
"filename": "src/index.ts",
"retrieved_chunk": " timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n this.debug(\"Deprecated: Use `event.publish()` instead\");\n if (!relaySet) {\n // If we have a devWriteRelaySet, use it to publish all events\n relaySet =\n this.devWriteRelaySet ||\n calculateRelaySetFromEvent(this, event);\n }\n return relaySet.publish(event, timeoutMs);",
"score": 18.52579569211746
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " if (this.isReplaceable()) {\n this.created_at = Math.floor(Date.now() / 1000);\n }\n const nostrEvent = await this.toNostrEvent();\n this.sig = await signer.sign(nostrEvent);\n return this.sig;\n }\n /**\n * Attempt to sign and then publish an NDKEvent to a given relaySet.\n * If no relaySet is provided, the relaySet will be calculated by NDK.",
"score": 18.354291219105928
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 18.318942169899056
}
] | typescript | relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
); |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
relay: NDKRelay | undefined,
fromCache = false
) {
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
| export function relaysFromBech32(bech32: string): NDKRelay[] { |
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 25.635009489439813
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " public isParamReplaceable = isParamReplaceable.bind(this);\n /**\n * Encodes a bech32 id.\n *\n * @returns {string} - Encoded naddr, note or nevent.\n */\n public encode = encode.bind(this);\n public encrypt = encrypt.bind(this);\n public decrypt = decrypt.bind(this);\n /**",
"score": 22.10064667482582
},
{
"filename": "src/zap/index.ts",
"retrieved_chunk": "import { bech32 } from \"@scure/base\";\nimport EventEmitter from \"eventemitter3\";\nimport { nip57 } from \"nostr-tools\";\nimport type { NostrEvent } from \"../events/index.js\";\nimport NDKEvent, { NDKTag } from \"../events/index.js\";\nimport NDK from \"../index.js\";\nimport User from \"../user/index.js\";\nconst DEFAULT_RELAYS = [\n \"wss://nos.lol\",\n \"wss://relay.nostr.band\",",
"score": 16.796700260996364
},
{
"filename": "src/zap/index.ts",
"retrieved_chunk": " await this.zappedUser.fetchProfile();\n }\n lud06 = (this.zappedUser.profile || {}).lud06;\n lud16 = (this.zappedUser.profile || {}).lud16;\n }\n if (lud16) {\n const [name, domain] = lud16.split(\"@\");\n zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`;\n } else if (lud06) {\n const { words } = bech32.decode(lud06, 1000);",
"score": 16.371428550118733
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " }\n }\n /**\n * Instantiate an NDKUser from a NIP-05 string\n * @param nip05Id {string} The user's NIP-05\n * @returns {NDKUser | undefined} An NDKUser if one is found for the given NIP-05, undefined otherwise.\n */\n static async fromNip05(nip05Id: string): Promise<NDKUser | undefined> {\n const profile = await nip05.queryProfile(nip05Id);\n if (profile) {",
"score": 15.879337261827324
}
] | typescript | export function relaysFromBech32(bech32: string): NDKRelay[] { |
import { bech32 } from "@scure/base";
import EventEmitter from "eventemitter3";
import { nip57 } from "nostr-tools";
import type { NostrEvent } from "../events/index.js";
import NDKEvent, { NDKTag } from "../events/index.js";
import NDK from "../index.js";
import User from "../user/index.js";
const DEFAULT_RELAYS = [
"wss://nos.lol",
"wss://relay.nostr.band",
"wss://relay.f7z.io",
"wss://relay.damus.io",
"wss://nostr.mom",
"wss://no.str.cr",
];
interface ZapConstructorParams {
ndk: NDK;
zappedEvent?: NDKEvent;
zappedUser?: User;
}
type ZapConstructorParamsRequired = Required<
Pick<ZapConstructorParams, "zappedEvent">
> &
Pick<ZapConstructorParams, "zappedUser"> &
ZapConstructorParams;
export default class Zap extends EventEmitter {
public ndk?: NDK;
public zappedEvent?: NDKEvent;
public zappedUser: User;
public constructor(args: ZapConstructorParamsRequired) {
super();
this.ndk = args.ndk;
this.zappedEvent = args.zappedEvent;
this.zappedUser =
args.zappedUser ||
this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey });
}
public async getZapEndpoint(): Promise<string | undefined> {
let lud06: string | undefined;
let lud16: string | undefined;
let zapEndpoint: string | undefined;
let zapEndpointCallback: string | undefined;
if (this.zappedEvent) {
const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0];
if (zapTag) {
switch (zapTag[2]) {
case "lud06":
lud06 = zapTag[1];
break;
case "lud16":
lud16 = zapTag[1];
break;
default:
throw new Error(`Unknown zap tag ${zapTag}`);
}
}
}
if (this.zappedUser && !lud06 && !lud16) {
// check if user has a profile, otherwise request it
if (!this.zappedUser.profile) {
await this.zappedUser.fetchProfile();
}
lud06 = (this.zappedUser.profile || {}).lud06;
lud16 = (this.zappedUser.profile || {}).lud16;
}
if (lud16) {
const [name, domain] = lud16.split("@");
zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`;
} else if (lud06) {
const { words } = bech32.decode(lud06, 1000);
const data = bech32.fromWords(words);
const utf8Decoder = new TextDecoder("utf-8");
zapEndpoint = utf8Decoder.decode(data);
}
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
const response = await fetch(zapEndpoint);
const body = await response.json();
if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) {
zapEndpointCallback = body.callback;
}
return zapEndpointCallback;
}
/**
* Generates a kind:9734 zap request and returns the payment request
* @param amount amount to zap in millisatoshis
* @param comment optional comment to include in the zap request
* @param extraTags optional extra tags to include in the zap request
* @param relays optional relays to ask zapper to publish the zap to
* @returns the payment request
*/
public async createZapRequest(
amount: number, // amount to zap in millisatoshis
comment?: string,
| extraTags?: NDKTag[],
relays?: string[]
): Promise<string | null> { |
const zapEndpoint = await this.getZapEndpoint();
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
if (!this.zappedEvent) throw new Error("No zapped event found");
const zapRequest = nip57.makeZapRequest({
profile: this.zappedUser.hexpubkey(),
// set the event to null since nostr-tools doesn't support nip-33 zaps
event: null,
amount,
comment: comment || "",
relays: relays ?? this.relays(),
});
// add the event tag if it exists; this supports both 'e' and 'a' tags
if (this.zappedEvent) {
const tag = this.zappedEvent.tagReference();
if (tag) {
zapRequest.tags.push(tag);
}
}
zapRequest.tags.push(["lnurl", zapEndpoint]);
const zapRequestEvent = new NDKEvent(
this.ndk,
zapRequest as NostrEvent
);
if (extraTags) {
zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags);
}
await zapRequestEvent.sign();
const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent();
const response = await fetch(
`${zapEndpoint}?` +
new URLSearchParams({
amount: amount.toString(),
nostr: JSON.stringify(zapRequestNostrEvent),
})
);
const body = await response.json();
return body.pr;
}
/**
* @returns the relays to use for the zap request
*/
private relays(): string[] {
let r: string[] = [];
if (this.ndk?.pool?.relays) {
r = this.ndk.pool.urls();
}
if (!r.length) {
r = DEFAULT_RELAYS;
}
return r;
}
}
| src/zap/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " return { \"#e\": [this.tagId()] };\n }\n }\n /**\n * Create a zap request for an existing event\n *\n * @param amount The amount to zap in millisatoshis\n * @param comment A comment to add to the zap request\n * @param extraTags Extra tags to add to the zap request\n */",
"score": 85.92005706805394
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " });\n const paymentRequest = await zap.createZapRequest(\n amount,\n comment,\n extraTags\n );\n // await zap.publish(amount);\n return paymentRequest;\n }\n /**",
"score": 66.80644232099576
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " async zap(\n amount: number,\n comment?: string,\n extraTags?: NDKTag[]\n ): Promise<string | null> {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const zap = new Zap({\n ndk: this.ndk,\n zappedEvent: this,",
"score": 56.25533468057362
},
{
"filename": "src/zap/invoice.ts",
"retrieved_chunk": "import { decode } from \"light-bolt11-decoder\";\nimport NDKEvent, { type NDKEventId, type NostrEvent } from \"../events/index.js\";\nexport interface NDKZapInvoice {\n id?: NDKEventId;\n zapper: string; // pubkey of zapper app\n zappee: string; // pubkey of user sending zap\n zapped: string; // pubkey of user receiving zap\n zappedEvent?: string; // event zapped\n amount: number; // amount zapped in millisatoshis\n comment?: string;",
"score": 49.219612750664616
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 40.59317357959289
}
] | typescript | extraTags?: NDKTag[],
relays?: string[]
): Promise<string | null> { |
import EventEmitter from "eventemitter3";
import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools";
import { EventPointer } from "nostr-tools/lib/nip19";
import NDKEvent, { NDKEventId } from "../events/index.js";
import NDK from "../index.js";
import { NDKRelay } from "../relay";
import { calculateRelaySetFromFilter } from "../relay/sets/calculate";
import { NDKRelaySet } from "../relay/sets/index.js";
import { queryFullyFilled } from "./utils.js";
export type NDKFilter = NostrFilter;
export enum NDKSubscriptionCacheUsage {
// Only use cache, don't subscribe to relays
ONLY_CACHE = "ONLY_CACHE",
// Use cache, if no matches, use relays
CACHE_FIRST = "CACHE_FIRST",
// Use cache in addition to relays
PARALLEL = "PARALLEL",
// Skip cache, don't query it
ONLY_RELAY = "ONLY_RELAY",
}
export interface NDKSubscriptionOptions {
closeOnEose: boolean;
cacheUsage?: NDKSubscriptionCacheUsage;
/**
* Groupable subscriptions are created with a slight time
* delayed to allow similar filters to be grouped together.
*/
groupable?: boolean;
/**
* The delay to use when grouping subscriptions, specified in milliseconds.
* @default 100
*/
groupableDelay?: number;
/**
* The subscription ID to use for the subscription.
*/
subId?: string;
}
/**
* Default subscription options.
*/
export const defaultOpts: NDKSubscriptionOptions = {
closeOnEose: true,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST,
groupable: true,
groupableDelay: 100,
};
/**
* Represents a subscription to an NDK event stream.
*
* @event NDKSubscription#event
* Emitted when an event is received by the subscription.
* @param {NDKEvent} event - The event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#event:dup
* Emitted when a duplicate event is received by the subscription.
* @param {NDKEvent} event - The duplicate event received by the subscription.
* @param {NDKRelay} relay - The relay that received the event.
* @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.
* @param {NDKSubscription} subscription - The subscription that received the event.
*
* @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.
* @param {NDKSubscription} subscription - The subscription that received EOSE.
*
* @event NDKSubscription#close - Emitted when the subscription is closed.
* @param {NDKSubscription} subscription - The subscription that was closed.
*/
export class NDKSubscription extends EventEmitter {
readonly subId: string;
readonly filters: NDKFilter[];
readonly opts: NDKSubscriptionOptions;
public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger;
/**
* Events that have been seen by the subscription, with the time they were first seen.
*/
public eventFirstSeen = new Map<NDKEventId, number>();
/**
* Relays that have sent an EOSE.
*/
public eosesSeen = new Set<NDKRelay>();
/**
* Events that have been seen by the subscription per relay.
*/
public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor(
ndk: NDK,
filters: NDKFilter | NDKFilter[],
opts?: NDKSubscriptionOptions,
relaySet?: NDKRelaySet,
subId?: string
) {
super();
this.ndk = ndk;
this.opts = { ...defaultOpts, ...(opts || {}) };
this.filters = filters instanceof Array ? filters : [filters];
this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);
this.relaySet = relaySet;
this.relaySubscriptions = new Map<NDKRelay, Sub>();
this.debug = ndk.debug.extend(`subscription:${this.subId}`);
// validate that the caller is not expecting a persistent
// subscription while using an option that will only hit the cache
if (
this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&
!this.opts.closeOnEose
) {
throw new Error(
"Cannot use cache-only options with a persistent subscription"
);
}
}
/**
* Provides access to the first filter of the subscription for
* backwards compatibility.
*/
get filter(): NDKFilter {
return this.filters[0];
}
/**
* Calculates the groupable ID for this subscription.
*
* @returns The groupable ID, or null if the subscription is not groupable.
*/
public groupableId(): string | null {
if (!this.opts?.groupable || this.filters.length > 1) {
return null;
}
const filter = this.filters[0];
// Check if there is a kind and no time-based filters
const noTimeConstraints = !filter.since && !filter.until;
const noLimit = !filter.limit;
if (noTimeConstraints && noLimit) {
let id = filter.kinds ? filter.kinds.join(",") : "";
const keys = Object.keys(filter || {})
.sort()
.join("-");
id += `-${keys}`;
return id;
}
return null;
}
private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
}
private shouldQueryRelays(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE;
}
private shouldWaitForCache(): boolean {
return (
// Must want to close on EOSE; subscriptions
// that want to receive further updates must
// always hit the relay
this.opts.closeOnEose &&
// Cache adapter must claim to be fast
!!this.ndk.cacheAdapter?.locking &&
// If explicitly told to run in parallel, then
// we should not wait for the cache
this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL
);
}
/**
* Start the subscription. This is the main method that should be called
* after creating a subscription.
*/
public async start(): Promise<void> {
let cachePromise;
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
}
}
}
if (this.shouldQueryRelays()) {
this.startWithRelaySet();
} else {
this.emit("eose", this);
}
return;
}
public stop(): void {
this.relaySubscriptions.forEach((sub) => sub.unsub());
this.relaySubscriptions.clear();
this.emit("close", this);
}
private async startWithCache(): Promise<void> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
}
}
private startWithRelaySet(): void {
if (!this.relaySet) {
this.relaySet = calculateRelaySetFromFilter(
this.ndk,
this.filters[0]
);
}
if (this.relaySet) {
this.relaySet.subscribe(this);
}
}
// EVENT handling
/**
* Called when an event is received from a relay or the cache
* @param event
* @param relay
* @param fromCache Whether the event was received from the cache
*/
public eventReceived(
event: NDKEvent,
| relay: NDKRelay | undefined,
fromCache = false
) { |
if (relay) event.relay = relay;
if (!relay) relay = event.relay;
if (!fromCache && relay) {
// track the event per relay
let events = this.eventsPerRelay.get(relay);
if (!events) {
events = new Set();
this.eventsPerRelay.set(relay, events);
}
events.add(event.id);
// mark the event as seen
const eventAlreadySeen = this.eventFirstSeen.has(event.id);
if (eventAlreadySeen) {
const timeSinceFirstSeen =
Date.now() - (this.eventFirstSeen.get(event.id) || 0);
relay.scoreSlowerEvent(timeSinceFirstSeen);
this.emit("event:dup", event, relay, timeSinceFirstSeen, this);
return;
}
if (this.ndk.cacheAdapter) {
this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay);
}
this.eventFirstSeen.set(`${event.id}`, Date.now());
} else {
this.eventFirstSeen.set(`${event.id}`, 0);
}
this.emit("event", event, relay, this);
}
// EOSE handling
private eoseTimeout: ReturnType<typeof setTimeout> | undefined;
public eoseReceived(relay: NDKRelay): void {
if (this.opts?.closeOnEose) {
this.relaySubscriptions.get(relay)?.unsub();
this.relaySubscriptions.delete(relay);
// if this was the last relay that needed to EOSE, emit that this subscription is closed
if (this.relaySubscriptions.size === 0) {
this.emit("close", this);
}
}
this.eosesSeen.add(relay);
const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size();
if (hasSeenAllEoses) {
this.emit("eose");
} else {
if (this.eoseTimeout) {
clearTimeout(this.eoseTimeout);
}
this.eoseTimeout = setTimeout(() => {
this.emit("eose");
}, 500);
}
}
}
/**
* Represents a group of subscriptions.
*
* Events emitted from the group will be emitted from each subscription.
*/
export class NDKSubscriptionGroup extends NDKSubscription {
private subscriptions: NDKSubscription[];
constructor(ndk: NDK, subscriptions: NDKSubscription[]) {
const debug = ndk.debug.extend("subscription-group");
const filters = mergeFilters(subscriptions.map((s) => s.filters[0]));
super(
ndk,
filters,
subscriptions[0].opts, // TODO: This should be merged
subscriptions[0].relaySet // TODO: This should be merged
);
this.subscriptions = subscriptions;
debug("merged filters", {
count: subscriptions.length,
mergedFilters: this.filters[0],
});
// forward events to the matching subscriptions
this.on("event", this.forwardEvent);
this.on("event:dup", this.forwardEventDup);
this.on("eose", this.forwardEose);
this.on("close", this.forwardClose);
}
private isEventForSubscription(
event: NDKEvent,
subscription: NDKSubscription
): boolean {
const { filters } = subscription;
if (!filters) return false;
return matchFilter(filters[0], event.rawEvent() as any);
// check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position
// of the tags array of arrays and the same value in the second position
// for (const key in filter) {
// if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false;
// else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false;
// else if (key.startsWith('#')) {
// const tagKey = key.slice(1);
// const tagValue = filter[key];
// if (event.tags) {
// for (const tag of event.tags) {
// if (tag[0] === tagKey && tag[1] === tagValue) {
// return false;
// }
// }
// }
// }
// return true;
}
private forwardEvent(event: NDKEvent, relay: NDKRelay) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit("event", event, relay, subscription);
}
}
private forwardEventDup(
event: NDKEvent,
relay: NDKRelay,
timeSinceFirstSeen: number
) {
for (const subscription of this.subscriptions) {
if (!this.isEventForSubscription(event, subscription)) {
continue;
}
subscription.emit(
"event:dup",
event,
relay,
timeSinceFirstSeen,
subscription
);
}
}
private forwardEose() {
for (const subscription of this.subscriptions) {
subscription.emit("eose", subscription);
}
}
private forwardClose() {
for (const subscription of this.subscriptions) {
subscription.emit("close", subscription);
}
}
}
/**
* Go through all the passed filters, which should be
* relatively similar, and merge them.
*/
export function mergeFilters(filters: NDKFilter[]): NDKFilter {
const result: any = {};
filters.forEach((filter) => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
} else {
result[key] = Array.from(
new Set([...result[key], ...value])
);
}
} else {
result[key] = value;
}
});
});
return result as NDKFilter;
}
/**
* Creates a valid nostr filter from an event id or a NIP-19 bech32.
*/
export function filterFromId(id: string): NDKFilter {
let decoded;
try {
decoded = nip19.decode(id);
switch (decoded.type) {
case "nevent":
return { ids: [decoded.data.id] };
case "note":
return { ids: [decoded.data] };
case "naddr":
return {
authors: [decoded.data.pubkey],
"#d": [decoded.data.identifier],
kinds: [decoded.data.kind],
};
}
} catch (e) {}
return { ids: [id] };
}
/**
* Returns the specified relays from a NIP-19 bech32.
*
* @param bech32 The NIP-19 bech32.
*/
export function relaysFromBech32(bech32: string): NDKRelay[] {
try {
const decoded = nip19.decode(bech32);
if (["naddr", "nevent"].includes(decoded?.type)) {
const data = decoded.data as unknown as EventPointer;
if (data?.relays) {
return data.relays.map((r: string) => new NDKRelay(r));
}
}
} catch (e) {
/* empty */
}
return [];
}
/**
* Generates a random filter id, based on the filter keys.
*/
function generateFilterId(filter: NDKFilter) {
const keys = Object.keys(filter) || [];
const subId = [];
for (const key of keys) {
if (key === "kinds") {
const v = [key, filter.kinds!.join(",")];
subId.push(v.join(":"));
} else {
subId.push(key);
}
}
subId.push(Math.floor(Math.random() * 999999999).toString());
return subId.join("-");
}
| src/subscription/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";",
"score": 32.77512921459748
},
{
"filename": "src/cache/index.ts",
"retrieved_chunk": "import NDKEvent from \"../events/index.js\";\nimport { NDKRelay } from \"../relay/index.js\";\nimport { NDKFilter, NDKSubscription } from \"../subscription/index.js\";\nexport interface NDKCacheAdapter {\n /**\n * Whether this cache adapter is expected to be fast.\n * If this is true, the cache will be queried before the relays.\n * When this is false, the cache will be queried in addition to the relays.\n */\n locking: boolean;",
"score": 32.59934682704355
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 31.12046570869522
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 29.44153703239682
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " *\n * @param relay - The relay to add to the pool.\n * @param connect - Whether or not to connect to the relay.\n */\n public addRelay(relay: NDKRelay, connect = true) {\n const relayUrl = relay.url;\n relay.on(\"notice\", (relay, notice) =>\n this.emit(\"notice\", relay, notice)\n );\n relay.on(\"connect\", () => this.handleRelayConnect(relayUrl));",
"score": 28.964974380988103
}
] | typescript | relay: NDKRelay | undefined,
fromCache = false
) { |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{
email,
password,
planKey: "free",
}
);
spinner.stop();
const accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
);
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
| const userRes = await getRequest(`${origin}/api/user`); |
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if (!isEmailValid(email)) {
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " axios.defaults.headers[\"x-xsrf-token\"] = xsrfToken;\n axios.defaults.headers.cookie = `accessToken=${accessToken};`;\n const userRes = await getRequest(`https://${url.hostname}/api/user`);\n persistCredentials({\n origin: url.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: userRes.data.user?.firstName,\n lastName: userRes.data.user?.lastName,\n email: userRes.data.user?.email,",
"score": 33.296262926271666
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " {\n name: \"origin\",\n message: \"What is your Retool origin? (e.g., https://my-org.retool.com).\",\n type: \"input\",\n },\n ]);\n //Check if last character is a slash. If so, remove it.\n if (origin[origin.length - 1] === \"/\") {\n origin = origin.slice(0, -1);\n }",
"score": 29.80501900305238
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " // For local testing:\n // open(\"http://localhost:3000/googlelogin?retoolCliRedirect=true\");\n // open(\"https://login.retool-qa.com/googlelogin?retoolCliRedirect=true\");\n // open(\"https://admin.retool.dev/googlelogin?retoolCliRedirect=true\");\n // Step 3: Keep the server online until localhost:3020/auth is hit.\n let server_online = true;\n while (server_online) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n server.close();",
"score": 29.22926595079985
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " telemetryEnabled: true,\n });\n logSuccess();\n res.sendFile(path.join(__dirname, \"../loginPages/loginSuccess.html\"));\n server_online = false;\n });\n const server = app.listen(3020);\n // Step 1: Open up the google SSO page in the browser.\n // Step 2: User accepts the SSO request.\n open(`https://login.retool.com/googlelogin?retoolCliRedirect=true`);",
"score": 25.72369822638258
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }",
"score": 25.55726463175373
}
] | typescript | const userRes = await getRequest(`${origin}/api/user`); |
import debug from "debug";
import EventEmitter from "eventemitter3";
import { Relay, relayInit, Sub } from "nostr-tools";
import "websocket-polyfill";
import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js";
import { NDKSubscription } from "../subscription/index.js";
import User from "../user/index.js";
import { NDKRelayScore } from "./score.js";
export enum NDKRelayStatus {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
RECONNECTING,
FLAPPING,
}
export interface NDKRelayConnectionStats {
/**
* The number of times a connection has been attempted.
*/
attempts: number;
/**
* The number of times a connection has been successfully established.
*/
success: number;
/**
* The durations of the last 100 connections in milliseconds.
*/
durations: number[];
/**
* The time the current connection was established in milliseconds.
*/
connectedAt?: number;
}
/**
* The NDKRelay class represents a connection to a relay.
*
* @emits NDKRelay#connect
* @emits NDKRelay#disconnect
* @emits NDKRelay#notice
* @emits NDKRelay#event
* @emits NDKRelay#published when an event is published to the relay
* @emits NDKRelay#publish:failed when an event fails to publish to the relay
* @emits NDKRelay#eose
*/
export class NDKRelay extends EventEmitter {
readonly url: string;
readonly scores | : Map<User, NDKRelayScore>; |
private relay: Relay;
private _status: NDKRelayStatus;
private connectedAt?: number;
private _connectionStats: NDKRelayConnectionStats = {
attempts: 0,
success: 0,
durations: [],
};
public complaining = false;
private debug: debug.Debugger;
/**
* Active subscriptions this relay is connected to
*/
public activeSubscriptions = new Set<NDKSubscription>();
public constructor(url: string) {
super();
this.url = url;
this.relay = relayInit(url);
this.scores = new Map<User, NDKRelayScore>();
this._status = NDKRelayStatus.DISCONNECTED;
this.debug = debug(`ndk:relay:${url}`);
this.relay.on("connect", () => {
this.updateConnectionStats.connected();
this._status = NDKRelayStatus.CONNECTED;
this.emit("connect");
});
this.relay.on("disconnect", () => {
this.updateConnectionStats.disconnected();
if (this._status === NDKRelayStatus.CONNECTED) {
this._status = NDKRelayStatus.DISCONNECTED;
this.handleReconnection();
}
this.emit("disconnect");
});
this.relay.on("notice", (notice: string) => this.handleNotice(notice));
}
/**
* Evaluates the connection stats to determine if the relay is flapping.
*/
private isFlapping(): boolean {
const durations = this._connectionStats.durations;
if (durations.length < 10) return false;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = sum / durations.length;
const variance =
durations
.map((x) => Math.pow(x - avg, 2))
.reduce((a, b) => a + b, 0) / durations.length;
const stdDev = Math.sqrt(variance);
const isFlapping = stdDev < 1000;
return isFlapping;
}
/**
* Called when the relay is unexpectedly disconnected.
*/
private handleReconnection() {
if (this.isFlapping()) {
this.emit("flapping", this, this._connectionStats);
this._status = NDKRelayStatus.FLAPPING;
}
if (this.connectedAt && Date.now() - this.connectedAt < 5000) {
setTimeout(() => this.connect(), 60000);
} else {
this.connect();
}
}
get status(): NDKRelayStatus {
return this._status;
}
/**
* Connects to the relay.
*/
public async connect(): Promise<void> {
try {
this.updateConnectionStats.attempt();
this._status = NDKRelayStatus.CONNECTING;
await this.relay.connect();
} catch (e) {
this.debug("Failed to connect", e);
this._status = NDKRelayStatus.DISCONNECTED;
throw e;
}
}
/**
* Disconnects from the relay.
*/
public disconnect(): void {
this._status = NDKRelayStatus.DISCONNECTING;
this.relay.close();
}
async handleNotice(notice: string) {
// This is a prototype; if the relay seems to be complaining
// remove it from relay set selection for a minute.
if (notice.includes("oo many") || notice.includes("aximum")) {
this.disconnect();
// fixme
setTimeout(() => this.connect(), 2000);
this.debug(this.relay.url, "Relay complaining?", notice);
// this.complaining = true;
// setTimeout(() => {
// this.complaining = false;
// console.log(this.relay.url, 'Reactivate relay');
// }, 60000);
}
this.emit("notice", this, notice);
}
/**
* Subscribes to a subscription.
*/
public subscribe(subscription: NDKSubscription): Sub {
const { filters } = subscription;
const sub = this.relay.sub(filters, {
id: subscription.subId,
});
this.debug(`Subscribed to ${JSON.stringify(filters)}`);
sub.on("event", (event: NostrEvent) => {
const e = new NDKEvent(undefined, event);
e.relay = this;
subscription.eventReceived(e, this);
});
sub.on("eose", () => {
subscription.eoseReceived(this);
});
const unsub = sub.unsub;
sub.unsub = () => {
this.debug(`Unsubscribing from ${JSON.stringify(filters)}`);
this.activeSubscriptions.delete(subscription);
unsub();
};
this.activeSubscriptions.add(subscription);
subscription.on("close", () => {
this.activeSubscriptions.delete(subscription);
});
return sub;
}
/**
* Publishes an event to the relay with an optional timeout.
*
* If the relay is not connected, the event will be published when the relay connects,
* unless the timeout is reached before the relay connects.
*
* @param event The event to publish
* @param timeoutMs The timeout for the publish operation in milliseconds
* @returns A promise that resolves when the event has been published or rejects if the operation times out
*/
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
if (this.status === NDKRelayStatus.CONNECTED) {
return this.publishEvent(event, timeoutMs);
} else {
this.once("connect", () => {
this.publishEvent(event, timeoutMs);
});
return true;
}
}
private async publishEvent(
event: NDKEvent,
timeoutMs?: number
): Promise<boolean> {
const nostrEvent = await event.toNostrEvent();
const publish = this.relay.publish(nostrEvent as any);
let publishTimeout: NodeJS.Timeout | number;
const publishPromise = new Promise<boolean>((resolve, reject) => {
publish
.then(() => {
clearTimeout(publishTimeout as unknown as NodeJS.Timeout);
this.emit("published", event);
resolve(true);
})
.catch((err) => {
clearTimeout(publishTimeout as NodeJS.Timeout);
this.debug("Publish failed", err, event.id);
this.emit("publish:failed", event, err);
reject(err);
});
});
// If no timeout is specified, just return the publish promise
if (!timeoutMs) {
return publishPromise;
}
// Create a promise that rejects after timeoutMs milliseconds
const timeoutPromise = new Promise<boolean>((_, reject) => {
publishTimeout = setTimeout(() => {
this.debug("Publish timed out", event.rawEvent());
this.emit("publish:failed", event, "Timeout");
reject(new Error("Publish operation timed out"));
}, timeoutMs);
});
// wait for either the publish operation to complete or the timeout to occur
return Promise.race([publishPromise, timeoutPromise]);
}
/**
* Called when this relay has responded with an event but
* wasn't the fastest one.
* @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public scoreSlowerEvent(timeDiffInMs: number): void {
// TODO
}
/**
* Utility functions to update the connection stats.
*/
private updateConnectionStats = {
connected: () => {
this._connectionStats.success++;
this._connectionStats.connectedAt = Date.now();
},
disconnected: () => {
if (this._connectionStats.connectedAt) {
this._connectionStats.durations.push(
Date.now() - this._connectionStats.connectedAt
);
if (this._connectionStats.durations.length > 100) {
this._connectionStats.durations.shift();
}
}
this._connectionStats.connectedAt = undefined;
},
attempt: () => {
this._connectionStats.attempts++;
},
};
/**
* Returns the connection stats.
*/
get connectionStats(): NDKRelayConnectionStats {
return this._connectionStats;
}
public tagReference(marker?: string): NDKTag {
const tag = ["r", this.relay.url];
if (marker) {
tag.push(marker);
}
return tag;
}
}
| src/relay/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * list.addItem(secretFollow, 'person', true);\n *\n * @emits NDKList#change\n */\nexport class NDKList extends NDKEvent {\n public _encryptedTags: NDKTag[] | undefined;\n /**\n * Stores the number of bytes the content was before decryption\n * to expire the cache when the content changes.\n */",
"score": 46.81932476659011
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " public async publish(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n const publishedToRelays: Set<NDKRelay> = new Set();\n // go through each relay and publish the event\n const promises: Promise<void>[] = Array.from(this.relays).map(\n (relay: NDKRelay) => {\n return new Promise<void>((resolve) => {\n relay",
"score": 39.41226587399814
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " * @event NDKSubscription#event\n * Emitted when an event is received by the subscription.\n * @param {NDKEvent} event - The event received by the subscription.\n * @param {NDKRelay} relay - The relay that received the event.\n * @param {NDKSubscription} subscription - The subscription that received the event.\n *\n * @event NDKSubscription#event:dup\n * Emitted when a duplicate event is received by the subscription.\n * @param {NDKEvent} event - The duplicate event received by the subscription.\n * @param {NDKRelay} relay - The relay that received the event.",
"score": 38.18044112487662
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": " *\n * @param relay - The relay to add to the pool.\n * @param connect - Whether or not to connect to the relay.\n */\n public addRelay(relay: NDKRelay, connect = true) {\n const relayUrl = relay.url;\n relay.on(\"notice\", (relay, notice) =>\n this.emit(\"notice\", relay, notice)\n );\n relay.on(\"connect\", () => this.handleRelayConnect(relayUrl));",
"score": 37.367573827779346
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(",
"score": 35.72547913525244
}
] | typescript | : Map<User, NDKRelayScore>; |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await | getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " const infoResponse = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n spinner.stop();\n const { tableInfo } = infoResponse.data;\n if (tableInfo) {\n return tableInfo;\n }\n}\nexport async function deleteTable(",
"score": 37.38160298320278
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,",
"score": 36.596162099559635
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"DeleteTable\",\n payload: {\n table: tableName,\n },\n }\n );\n spinner.stop();",
"score": 30.679306764973916
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }",
"score": 27.635426370573487
},
{
"filename": "src/utils/connectionString.ts",
"retrieved_chunk": " !credentials.retoolDBUuid ||\n !credentials.hasConnectionString\n ) {\n return;\n }\n const grid = await getRequest(\n `${credentials.origin}/api/grid/retooldb/${credentials.retoolDBUuid}?env=production`,\n false\n );\n return grid.data?.gridInfo?.connectionString;",
"score": 23.148811177283218
}
] | typescript | getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
import { Credentials } from "./credentials";
import { getRequest, postRequest } from "./networking";
export type ResourceByEnv = Record<string, Resource>;
export type Resource = {
displayName: string;
id: number;
name: string;
type: string;
environment: string;
environmentId: string;
uuid: string;
organizationId: number;
resourceFolderId: number;
};
export async function getResourceByName(
resourceName: string,
credentials: Credentials
): Promise<ResourceByEnv> {
const getResourceResult = await getRequest(
`${credentials.origin}/api/resources/names/${resourceName}`
);
const { resourceByEnv } = getResourceResult.data;
if (!resourceByEnv) {
console.log("Error finding resource by that id.");
console.log(getResourceResult.data);
process.exit(1);
} else {
return resourceByEnv;
}
}
export async function createResource({
resourceType,
credentials,
displayName,
resourceFolderId,
resourceOptions,
}: {
resourceType: string;
| credentials: Credentials; |
displayName?: string;
resourceFolderId?: number;
resourceOptions?: Record<string, any>;
}): Promise<Resource> {
const createResourceResult = await postRequest(
`${credentials.origin}/api/resources/`,
{
type: resourceType,
displayName,
resourceFolderId,
options: resourceOptions ? resourceOptions : {},
},
false,
{},
false
);
const resource = createResourceResult.data;
if (!resource) {
throw new Error("Error creating resource.");
} else {
return resource;
}
}
| src/utils/resources.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/rpc.ts",
"retrieved_chunk": " type: \"input\",\n validate: async (displayName: string) => {\n try {\n const resource = await createResource({\n resourceType: \"retoolSdk\",\n credentials,\n resourceOptions: {\n requireExplicitVersion: false,\n },\n displayName,",
"score": 41.63427220452946
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " }/${tableName}?env=production`\n );\n if (credentials.hasConnectionString && printConnectionString) {\n await logConnectionStringDetails();\n }\n }\n}\nexport async function createTableFromCSV(\n csvFilePath: string,\n credentials: Credentials,",
"score": 15.525296224560337
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": " `${chalk.bold(\"View in browser:\")} ${\n credentials.origin\n }/editor/${pageUuid}`\n );\n }\n}\nexport async function deleteApp(\n appName: string,\n credentials: Credentials,\n confirmDeletion: boolean",
"score": 14.989600946194347
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": " }`\n );\n return page;\n }\n}\nexport async function createAppForTable(\n appName: string,\n tableName: string,\n columnName: string, //The column to use for search bar.\n credentials: Credentials",
"score": 14.5733558269488
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " );\n spinner.stop();\n return {\n workflows: fetchWorkflowsResponse?.data?.workflowsMetadata,\n folders: fetchWorkflowsResponse?.data?.workflowFolders,\n };\n}\nexport async function deleteWorkflow(\n workflowName: string,\n credentials: Credentials,",
"score": 14.069053018516035
}
] | typescript | credentials: Credentials; |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
| await generateCRUDWorkflow(tableName, credentials); |
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " // Handle `retool db --upload <path-to-csv>`\n if (argv.upload) {\n await createTableFromCSV(argv.upload, credentials, true, true);\n }\n // Handle `retool db --create`\n else if (argv.create) {\n const tableName = await collectTableName();\n const colNames = await collectColumnNames();\n await createTable(tableName, colNames, undefined, credentials, true);\n }",
"score": 26.97627583127199
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": "}\n// Generates a CRUD workflow for tableName from a template.\nexport async function generateCRUDWorkflow(\n tableName: string,\n credentials: Credentials\n) {\n let spinner = ora(\"Creating workflow\").start();\n // Generate workflow metadata via puppeteer.\n // Dynamic import b/c puppeteer is slow.\n const workflowMeta = await import(\"./puppeteer\").then(",
"score": 21.930616798745938
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {",
"score": 21.105819665218842
},
{
"filename": "src/commands/workflows.ts",
"retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }",
"score": 19.36038429817606
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " }/${tableName}?env=production`\n );\n if (credentials.hasConnectionString && printConnectionString) {\n await logConnectionStringDetails();\n }\n }\n}\nexport async function createTableFromCSV(\n csvFilePath: string,\n credentials: Credentials,",
"score": 18.7870626130113
}
] | typescript | await generateCRUDWorkflow(tableName, credentials); |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await | deleteApp(`${tableName} App`, credentials, false); |
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }",
"score": 29.494027334784743
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",",
"score": 27.321114963343923
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();",
"score": 25.42529652371447
},
{
"filename": "src/commands/workflows.ts",
"retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }",
"score": 24.237176926470976
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {",
"score": 23.31028937456
}
] | typescript | deleteApp(`${tableName} App`, credentials, false); |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
| const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{ |
email,
password,
planKey: "free",
}
);
spinner.stop();
const accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
);
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
const userRes = await getRequest(`${origin}/api/user`);
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if (!isEmailValid(email)) {
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }",
"score": 40.53231342381973
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " },\n {\n name: \"password\",\n message: \"What is your password?\",\n type: \"password\",\n },\n ]);\n const loginOrigin = localhost\n ? \"http://localhost:3000\"\n : \"https://login.retool.com\";",
"score": 34.99885815382872
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": "};\n// Ask the user to input their email and password.\n// Fire off a request to Retool's login & auth endpoints.\n// Persist the credentials.\nasync function loginViaEmail(localhost = false) {\n const { email, password } = await inquirer.prompt([\n {\n name: \"email\",\n message: \"What is your email?\",\n type: \"input\",",
"score": 30.861588065244124
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " telemetryEnabled: true,\n });\n logSuccess();\n res.sendFile(path.join(__dirname, \"../loginPages/loginSuccess.html\"));\n server_online = false;\n });\n const server = app.listen(3020);\n // Step 1: Open up the google SSO page in the browser.\n // Step 2: User accepts the SSO request.\n open(`https://login.retool.com/googlelogin?retoolCliRedirect=true`);",
"score": 24.850871544045454
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " // For local testing:\n // open(\"http://localhost:3000/googlelogin?retoolCliRedirect=true\");\n // open(\"https://login.retool-qa.com/googlelogin?retoolCliRedirect=true\");\n // open(\"https://admin.retool.dev/googlelogin?retoolCliRedirect=true\");\n // Step 3: Keep the server online until localhost:3020/auth is hit.\n let server_online = true;\n while (server_online) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n server.close();",
"score": 24.608103829915503
}
] | typescript | const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{ |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
| await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{ |
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }",
"score": 33.28023219453725
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"DeleteTable\",\n payload: {\n table: tableName,\n },\n }\n );\n spinner.stop();",
"score": 30.739198088042862
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " | undefined\n> {\n const genDataRes: {\n data: {\n data: string[][];\n };\n } = await postRequest(\n `${credentials.origin}/api/grid/retooldb/generateData`,\n {\n fields: retoolDBInfo.tableInfo.fields.map((field) => {",
"score": 27.25150029927665
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n ...payload,\n }\n );\n spinner.stop();\n if (!createTableResult.data.success) {\n console.log(\"Error creating table in RetoolDB.\");\n console.log(createTableResult.data);\n process.exit(1);",
"score": 22.320237233785235
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,",
"score": 21.84022629928267
}
] | typescript | await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{ |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
| await deleteWorkflow(workflowName, credentials, false); |
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }",
"score": 31.23725911313695
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " confirmDeletion: boolean\n) {\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",\n message: `Are you sure you want to delete ${workflowName}?`,\n type: \"confirm\",\n },\n ]);",
"score": 29.330049222374384
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();",
"score": 29.274357450196163
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",",
"score": 26.472143210280617
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": ") {\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",\n message: `Are you sure you want to delete ${appName}?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {",
"score": 25.967588045427966
}
] | typescript | await deleteWorkflow(workflowName, credentials, false); |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{
email,
password,
planKey: "free",
}
);
spinner.stop();
const accessToken | = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
); |
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
const userRes = await getRequest(`${origin}/api/user`);
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if (!isEmailValid(email)) {
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " );\n const { redirectUri } = authResponse.data;\n const redirectUrl = localhost\n ? new URL(loginOrigin)\n : redirectUri\n ? new URL(redirectUri)\n : undefined;\n const accessToken = accessTokenFromCookies(\n authResponse.headers[\"set-cookie\"]\n );",
"score": 21.72205964788081
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;\n spinner.stop();\n return credentials;\n}",
"score": 19.335926423292417
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " const xsrfToken = xsrfTokenFromCookies(authResponse.headers[\"set-cookie\"]);\n // Step 3: Persist the credentials.\n if (redirectUrl?.origin && accessToken && xsrfToken) {\n persistCredentials({\n origin: redirectUrl.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: authResponse.data.user?.firstName,\n lastName: authResponse.data.user?.lastName,\n email: authResponse.data.user?.email,",
"score": 18.361963302467316
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;",
"score": 15.787556670505907
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " axios.defaults.headers[\"x-xsrf-token\"] = xsrfToken;\n axios.defaults.headers.cookie = `accessToken=${accessToken};`;\n const userRes = await getRequest(`https://${url.hostname}/api/user`);\n persistCredentials({\n origin: url.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: userRes.data.user?.firstName,\n lastName: userRes.data.user?.lastName,\n email: userRes.data.user?.email,",
"score": 15.22358978101642
}
] | typescript | = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
); |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await | deleteWorkflow(workflowName, credentials, false); |
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }",
"score": 27.2536037541386
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();",
"score": 22.111555769607733
},
{
"filename": "src/commands/workflows.ts",
"retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }",
"score": 21.959833921557983
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " confirmDeletion: boolean\n) {\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",\n message: `Are you sure you want to delete ${workflowName}?`,\n type: \"confirm\",\n },\n ]);",
"score": 20.80810238419165
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",",
"score": 20.751475026981737
}
] | typescript | deleteWorkflow(workflowName, credentials, false); |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await | generateCRUDWorkflow(tableName, credentials); |
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " // Handle `retool db --upload <path-to-csv>`\n if (argv.upload) {\n await createTableFromCSV(argv.upload, credentials, true, true);\n }\n // Handle `retool db --create`\n else if (argv.create) {\n const tableName = await collectTableName();\n const colNames = await collectColumnNames();\n await createTable(tableName, colNames, undefined, credentials, true);\n }",
"score": 26.69125503949927
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": "}\n// Generates a CRUD workflow for tableName from a template.\nexport async function generateCRUDWorkflow(\n tableName: string,\n credentials: Credentials\n) {\n let spinner = ora(\"Creating workflow\").start();\n // Generate workflow metadata via puppeteer.\n // Dynamic import b/c puppeteer is slow.\n const workflowMeta = await import(\"./puppeteer\").then(",
"score": 19.63429144058172
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " }/${tableName}?env=production`\n );\n if (credentials.hasConnectionString && printConnectionString) {\n await logConnectionStringDetails();\n }\n }\n}\nexport async function createTableFromCSV(\n csvFilePath: string,\n credentials: Credentials,",
"score": 18.7870626130113
},
{
"filename": "src/utils/puppeteer.ts",
"retrieved_chunk": " resources: [],\n };\n const workflow = window.generateWorkflowFromTemplateData(payload);\n return workflow;\n },\n tableName,\n workflowTemplate,\n credentials.retoolDBUuid\n );\n await browser.close();",
"score": 17.68580842188249
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " // List all apps in root folder.\n printApps(apps);\n }\n }\n }\n // Handle `retool apps --create-from-table`\n else if (argv.t) {\n const tableName = await collectTableName();\n await verifyTableExists(tableName, credentials);\n const tableInfo = await fetchTableInfo(tableName, credentials);",
"score": 17.54088899259606
}
] | typescript | generateCRUDWorkflow(tableName, credentials); |
import { bech32 } from "@scure/base";
import EventEmitter from "eventemitter3";
import { nip57 } from "nostr-tools";
import type { NostrEvent } from "../events/index.js";
import NDKEvent, { NDKTag } from "../events/index.js";
import NDK from "../index.js";
import User from "../user/index.js";
const DEFAULT_RELAYS = [
"wss://nos.lol",
"wss://relay.nostr.band",
"wss://relay.f7z.io",
"wss://relay.damus.io",
"wss://nostr.mom",
"wss://no.str.cr",
];
interface ZapConstructorParams {
ndk: NDK;
zappedEvent?: NDKEvent;
zappedUser?: User;
}
type ZapConstructorParamsRequired = Required<
Pick<ZapConstructorParams, "zappedEvent">
> &
Pick<ZapConstructorParams, "zappedUser"> &
ZapConstructorParams;
export default class Zap extends EventEmitter {
public ndk?: NDK;
public zappedEvent?: NDKEvent;
public zappedUser: User;
public constructor(args: ZapConstructorParamsRequired) {
super();
this.ndk = args.ndk;
this.zappedEvent = args.zappedEvent;
this.zappedUser =
args.zappedUser ||
this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey });
}
public async getZapEndpoint(): Promise<string | undefined> {
let lud06: string | undefined;
let lud16: string | undefined;
let zapEndpoint: string | undefined;
let zapEndpointCallback: string | undefined;
if (this.zappedEvent) {
const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0];
if (zapTag) {
switch (zapTag[2]) {
case "lud06":
lud06 = zapTag[1];
break;
case "lud16":
lud16 = zapTag[1];
break;
default:
throw new Error(`Unknown zap tag ${zapTag}`);
}
}
}
if (this.zappedUser && !lud06 && !lud16) {
// check if user has a profile, otherwise request it
if (!this.zappedUser.profile) {
await this.zappedUser.fetchProfile();
}
lud06 = (this.zappedUser.profile || {}).lud06;
lud16 = (this.zappedUser.profile || {}).lud16;
}
if (lud16) {
const [name, domain] = lud16.split("@");
zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`;
} else if (lud06) {
const { words } = bech32.decode(lud06, 1000);
const data = bech32.fromWords(words);
const utf8Decoder = new TextDecoder("utf-8");
zapEndpoint = utf8Decoder.decode(data);
}
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
const response = await fetch(zapEndpoint);
const body = await response.json();
if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) {
zapEndpointCallback = body.callback;
}
return zapEndpointCallback;
}
/**
* Generates a kind:9734 zap request and returns the payment request
* @param amount amount to zap in millisatoshis
* @param comment optional comment to include in the zap request
* @param extraTags optional extra tags to include in the zap request
* @param relays optional relays to ask zapper to publish the zap to
* @returns the payment request
*/
public async createZapRequest(
amount: number, // amount to zap in millisatoshis
comment?: string,
extraTags | ?: NDKTag[],
relays?: string[]
): Promise<string | null> { |
const zapEndpoint = await this.getZapEndpoint();
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
if (!this.zappedEvent) throw new Error("No zapped event found");
const zapRequest = nip57.makeZapRequest({
profile: this.zappedUser.hexpubkey(),
// set the event to null since nostr-tools doesn't support nip-33 zaps
event: null,
amount,
comment: comment || "",
relays: relays ?? this.relays(),
});
// add the event tag if it exists; this supports both 'e' and 'a' tags
if (this.zappedEvent) {
const tag = this.zappedEvent.tagReference();
if (tag) {
zapRequest.tags.push(tag);
}
}
zapRequest.tags.push(["lnurl", zapEndpoint]);
const zapRequestEvent = new NDKEvent(
this.ndk,
zapRequest as NostrEvent
);
if (extraTags) {
zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags);
}
await zapRequestEvent.sign();
const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent();
const response = await fetch(
`${zapEndpoint}?` +
new URLSearchParams({
amount: amount.toString(),
nostr: JSON.stringify(zapRequestNostrEvent),
})
);
const body = await response.json();
return body.pr;
}
/**
* @returns the relays to use for the zap request
*/
private relays(): string[] {
let r: string[] = [];
if (this.ndk?.pool?.relays) {
r = this.ndk.pool.urls();
}
if (!r.length) {
r = DEFAULT_RELAYS;
}
return r;
}
}
| src/zap/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " return { \"#e\": [this.tagId()] };\n }\n }\n /**\n * Create a zap request for an existing event\n *\n * @param amount The amount to zap in millisatoshis\n * @param comment A comment to add to the zap request\n * @param extraTags Extra tags to add to the zap request\n */",
"score": 60.104559145294054
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " });\n const paymentRequest = await zap.createZapRequest(\n amount,\n comment,\n extraTags\n );\n // await zap.publish(amount);\n return paymentRequest;\n }\n /**",
"score": 53.104523209760075
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " async zap(\n amount: number,\n comment?: string,\n extraTags?: NDKTag[]\n ): Promise<string | null> {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const zap = new Zap({\n ndk: this.ndk,\n zappedEvent: this,",
"score": 45.58080823090513
},
{
"filename": "src/zap/invoice.ts",
"retrieved_chunk": "import { decode } from \"light-bolt11-decoder\";\nimport NDKEvent, { type NDKEventId, type NostrEvent } from \"../events/index.js\";\nexport interface NDKZapInvoice {\n id?: NDKEventId;\n zapper: string; // pubkey of zapper app\n zappee: string; // pubkey of user sending zap\n zapped: string; // pubkey of user receiving zap\n zappedEvent?: string; // event zapped\n amount: number; // amount zapped in millisatoshis\n comment?: string;",
"score": 42.52467053484065
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 32.302043807253746
}
] | typescript | ?: NDKTag[],
relays?: string[]
): Promise<string | null> { |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
| await deleteApp(`${tableName} App`, credentials, false); |
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
);
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }",
"score": 29.494027334784743
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",",
"score": 27.321114963343923
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();",
"score": 25.42529652371447
},
{
"filename": "src/commands/workflows.ts",
"retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }",
"score": 24.237176926470976
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {",
"score": 23.31028937456
}
] | typescript | await deleteApp(`${tableName} App`, credentials, false); |
import { bech32 } from "@scure/base";
import EventEmitter from "eventemitter3";
import { nip57 } from "nostr-tools";
import type { NostrEvent } from "../events/index.js";
import NDKEvent, { NDKTag } from "../events/index.js";
import NDK from "../index.js";
import User from "../user/index.js";
const DEFAULT_RELAYS = [
"wss://nos.lol",
"wss://relay.nostr.band",
"wss://relay.f7z.io",
"wss://relay.damus.io",
"wss://nostr.mom",
"wss://no.str.cr",
];
interface ZapConstructorParams {
ndk: NDK;
zappedEvent?: NDKEvent;
zappedUser?: User;
}
type ZapConstructorParamsRequired = Required<
Pick<ZapConstructorParams, "zappedEvent">
> &
Pick<ZapConstructorParams, "zappedUser"> &
ZapConstructorParams;
export default class Zap extends EventEmitter {
public ndk?: NDK;
public zappedEvent?: NDKEvent;
public zappedUser: User;
public constructor(args: ZapConstructorParamsRequired) {
super();
this.ndk = args.ndk;
this.zappedEvent = args.zappedEvent;
this.zappedUser =
args.zappedUser ||
this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey });
}
public async getZapEndpoint(): Promise<string | undefined> {
let lud06: string | undefined;
let lud16: string | undefined;
let zapEndpoint: string | undefined;
let zapEndpointCallback: string | undefined;
if (this.zappedEvent) {
const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0];
if (zapTag) {
switch (zapTag[2]) {
case "lud06":
lud06 = zapTag[1];
break;
case "lud16":
lud16 = zapTag[1];
break;
default:
throw new Error(`Unknown zap tag ${zapTag}`);
}
}
}
if (this.zappedUser && !lud06 && !lud16) {
// check if user has a profile, otherwise request it
if (!this.zappedUser.profile) {
await this.zappedUser.fetchProfile();
}
lud06 = (this.zappedUser.profile || {}).lud06;
lud16 = (this.zappedUser.profile || {}).lud16;
}
if (lud16) {
const [name, domain] = lud16.split("@");
zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`;
} else if (lud06) {
const { words } = bech32.decode(lud06, 1000);
const data = bech32.fromWords(words);
const utf8Decoder = new TextDecoder("utf-8");
zapEndpoint = utf8Decoder.decode(data);
}
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
const response = await fetch(zapEndpoint);
const body = await response.json();
if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) {
zapEndpointCallback = body.callback;
}
return zapEndpointCallback;
}
/**
* Generates a kind:9734 zap request and returns the payment request
* @param amount amount to zap in millisatoshis
* @param comment optional comment to include in the zap request
* @param extraTags optional extra tags to include in the zap request
* @param relays optional relays to ask zapper to publish the zap to
* @returns the payment request
*/
public async createZapRequest(
amount: number, // amount to zap in millisatoshis
comment?: string,
extraTags?: NDKTag[],
relays?: string[]
): Promise<string | null> {
const zapEndpoint = await this.getZapEndpoint();
if (!zapEndpoint) {
throw new Error("No zap endpoint found");
}
if (!this.zappedEvent) throw new Error("No zapped event found");
const zapRequest = nip57.makeZapRequest({
profile: this.zappedUser.hexpubkey(),
// set the event to null since nostr-tools doesn't support nip-33 zaps
event: null,
amount,
comment: comment || "",
relays: relays ?? this.relays(),
});
// add the event tag if it exists; this supports both 'e' and 'a' tags
if (this.zappedEvent) {
const tag = this.zappedEvent.tagReference();
if (tag) {
zapRequest.tags.push(tag);
}
}
zapRequest.tags.push(["lnurl", zapEndpoint]);
const zapRequestEvent = new NDKEvent(
this.ndk,
| zapRequest as NostrEvent
); |
if (extraTags) {
zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags);
}
await zapRequestEvent.sign();
const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent();
const response = await fetch(
`${zapEndpoint}?` +
new URLSearchParams({
amount: amount.toString(),
nostr: JSON.stringify(zapRequestNostrEvent),
})
);
const body = await response.json();
return body.pr;
}
/**
* @returns the relays to use for the zap request
*/
private relays(): string[] {
let r: string[] = [];
if (this.ndk?.pool?.relays) {
r = this.ndk.pool.urls();
}
if (!r.length) {
r = DEFAULT_RELAYS;
}
return r;
}
}
| src/zap/index.ts | nostr-dev-kit-ndk-ece64e1 | [
{
"filename": "src/events/index.ts",
"retrieved_chunk": " * ```typescript\n * reply.tag(opEvent, \"reply\");\n * // reply.tags => [[\"e\", <id>, <relay>, \"reply\"]]\n * ```\n */\n public tag(event: NDKEvent, marker?: string): void;\n public tag(userOrEvent: NDKUser | NDKEvent, marker?: string): void {\n const tag = userOrEvent.tagReference();\n if (marker) tag.push(marker);\n this.tags.push(tag);",
"score": 33.22415636783596
},
{
"filename": "src/events/kinds/dvm/NDKDVMJobResult.ts",
"retrieved_chunk": " this.tags.push([\"request\", JSON.stringify(event.rawEvent())]);\n this.tag(event);\n }\n }\n get jobRequest(): NDKEvent | undefined {\n const tag = this.tagValue(\"request\");\n if (tag === undefined) {\n return undefined;\n }\n return new NDKEvent(this.ndk, JSON.parse(tag));",
"score": 29.82637361843614
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " // NDKTag\n tag = item;\n } else {\n throw new Error(\"Invalid object type\");\n }\n if (mark) tag.push(mark);\n if (encrypted) {\n const user = await this.ndk.signer.user();\n const currentList = await this.encryptedTags();\n currentList.push(tag);",
"score": 25.965744677332637
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " if (!this.ndk) throw new Error(\"NDK instance not set\");\n if (!this.ndk.signer) throw new Error(\"NDK signer not set\");\n let tag;\n if (item instanceof NDKEvent) {\n tag = item.tagReference();\n } else if (item instanceof NDKUser) {\n tag = item.tagReference();\n } else if (item instanceof NDKRelay) {\n tag = item.tagReference();\n } else if (Array.isArray(item)) {",
"score": 24.012376865209895
},
{
"filename": "src/zap/invoice.ts",
"retrieved_chunk": " const sender = zapRequest.pubkey;\n const recipientTag = event.getMatchingTags(\"p\")[0];\n const recipient = recipientTag[1];\n let zappedEvent = event.getMatchingTags(\"e\")[0];\n if (!zappedEvent) {\n zappedEvent = event.getMatchingTags(\"a\")[0];\n }\n const zappedEventId = zappedEvent ? zappedEvent[1] : undefined;\n // ignore self-zaps (TODO: configurable?)\n // if (sender === recipient) { return null; } XXX",
"score": 22.360915593448382
}
] | typescript | zapRequest as NostrEvent
); |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{
email,
password,
planKey: "free",
}
);
spinner.stop();
const accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
);
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
const userRes = | await getRequest(`${origin}/api/user`); |
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if (!isEmailValid(email)) {
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " axios.defaults.headers[\"x-xsrf-token\"] = xsrfToken;\n axios.defaults.headers.cookie = `accessToken=${accessToken};`;\n const userRes = await getRequest(`https://${url.hostname}/api/user`);\n persistCredentials({\n origin: url.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: userRes.data.user?.firstName,\n lastName: userRes.data.user?.lastName,\n email: userRes.data.user?.email,",
"score": 33.296262926271666
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " {\n name: \"origin\",\n message: \"What is your Retool origin? (e.g., https://my-org.retool.com).\",\n type: \"input\",\n },\n ]);\n //Check if last character is a slash. If so, remove it.\n if (origin[origin.length - 1] === \"/\") {\n origin = origin.slice(0, -1);\n }",
"score": 29.80501900305238
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " // For local testing:\n // open(\"http://localhost:3000/googlelogin?retoolCliRedirect=true\");\n // open(\"https://login.retool-qa.com/googlelogin?retoolCliRedirect=true\");\n // open(\"https://admin.retool.dev/googlelogin?retoolCliRedirect=true\");\n // Step 3: Keep the server online until localhost:3020/auth is hit.\n let server_online = true;\n while (server_online) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n server.close();",
"score": 26.24042141357347
},
{
"filename": "src/utils/telemetry.ts",
"retrieved_chunk": " \"CLI Version\": version,\n email: credentials.email,\n origin: credentials.origin,\n os: process.platform,\n };\n // Send a POST request to Retool's telemetry endpoint.\n const res = await postRequest(`https://p.retool.com/v2/p`, {\n event: \"CLI DAU\",\n properties: payload,\n });",
"score": 25.15576246159047
},
{
"filename": "src/utils/validation.test.ts",
"retrieved_chunk": " ).toBe(true);\n });\n test(\"should return false for invalid access token\", () => {\n expect(isAccessTokenValid(\"asdasdasd\")).toBe(false);\n });\n});\ndescribe(\"isOriginValid\", () => {\n test(\"should return true for valid https origin\", () => {\n expect(isOriginValid(\"https://subdomain.retool.com\")).toBe(true);\n });",
"score": 25.060860141680195
}
] | typescript | await getRequest(`${origin}/api/user`); |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{
email,
password,
planKey: "free",
}
);
spinner.stop();
const accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
);
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
const userRes = await getRequest(`${origin}/api/user`);
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if ( | !isEmailValid(email)) { |
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": "};\n// Ask the user to input their email and password.\n// Fire off a request to Retool's login & auth endpoints.\n// Persist the credentials.\nasync function loginViaEmail(localhost = false) {\n const { email, password } = await inquirer.prompt([\n {\n name: \"email\",\n message: \"What is your email?\",\n type: \"input\",",
"score": 47.923051449995334
},
{
"filename": "src/utils/validation.ts",
"retrieved_chunk": "/* eslint-disable */\nconst emailRegex =\n /^[-!#$%&'*+\\/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+\\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\\.?[a-zA-Z0-9])*\\.[a-zA-Z](-?[a-zA-Z0-9])+$/;\n/* eslint-enable */\n//https://stackoverflow.com/questions/52456065/how-to-format-and-validate-email-node-js\nexport function isEmailValid(email: string) {\n if (!email) return false;\n if (email.length > 254) return false;\n if (!emailRegex.test(email)) return false;\n // Further checking of some things regex can't handle",
"score": 25.39911763420486
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " choices: [\n {\n name: \"Log in using Google SSO in a web browser\",\n value: \"browser\",\n },\n {\n name: \"Log in with email and password\",\n value: \"email\",\n },\n {",
"score": 22.8082565549768
},
{
"filename": "src/commands/rpc.ts",
"retrieved_chunk": " ],\n },\n ])) as { languageType: string };\n const { destinationPath } = (await inquirer.prompt([\n {\n name: \"destinationPath\",\n message: \"Where would you like to create your local server?\",\n type: \"input\",\n default: \"./retool_rpc\",\n },",
"score": 22.285400742883436
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " return {\n fields: colNames,\n data: generatedRows,\n };\n}\nexport async function collectTableName(): Promise<string> {\n const { tableName } = await inquirer.prompt([\n {\n name: \"tableName\",\n message: \"Table name?\",",
"score": 22.011070321147834
}
] | typescript | !isEmailValid(email)) { |
import Actor from "./actor";
import { Timer } from "./performance";
import { CancelablePromise } from "./types";
class Local {
received: any[][] = [];
localAction = (x: number, y: number, z: number): CancelablePromise<void> => {
this.received.push([x, y, z]);
return { cancel() {}, value: Promise.resolve() };
};
}
class Remote {
received: any[][] = [];
canceled = false;
remoteAction = (x: number, y: number, z: number): CancelablePromise<void> => {
this.received.push([x, y, z]);
return { cancel() {}, value: Promise.resolve() };
};
remotePromise = (x: number, timer?: Timer): CancelablePromise<number> => {
const oldNow = performance.now;
if (timer) timer.timeOrigin = 100;
performance.now = () => oldNow() - 100;
const finish = timer?.marker("fetch");
performance.now = () => oldNow() - 99;
finish?.();
performance.now = () => oldNow() + 2;
return {
cancel() {
throw new Error("not expected");
},
value: Promise.resolve(x),
};
};
remoteFail = (): CancelablePromise<number> => ({
cancel() {},
value: Promise.reject(new Error("error")),
});
remoteNever = (): CancelablePromise<number> => ({
cancel: () => {
this.canceled = true;
},
value: new Promise(() => {}),
});
}
test("send and cancel messages", async () => {
performance.now = () => 1;
const remote = new Remote();
const local = new Local();
const workerFromMainThread: Worker = {} as any as Worker;
const mainThreadFromWorker: Worker = {} as any as Worker;
workerFromMainThread.postMessage = (data) =>
//@ts-ignore
mainThreadFromWorker?.onmessage?.({ data });
mainThreadFromWorker.postMessage = (data) =>
//@ts-ignore
workerFromMainThread?.onmessage?.({ data });
| const mainActor = new Actor<Remote>(workerFromMainThread, local); |
const workerActor = new Actor<Local>(mainThreadFromWorker, remote);
mainActor.send("remoteAction", [], undefined, 1, 2, 3);
expect(remote.received).toEqual([[1, 2, 3]]);
workerActor.send("localAction", [], undefined, 4, 3, 2);
expect(local.received).toEqual([[4, 3, 2]]);
const timer = new Timer("main");
timer.timeOrigin = 0;
expect(await mainActor.send("remotePromise", [], timer, 9).value).toBe(9);
expect(timer.finish("url")).toMatchObject({
duration: 2,
fetch: 1,
marks: {
fetch: [[1, 2]],
main: [[1, 3]],
},
});
const { cancel } = mainActor.send("remoteNever", []);
expect(remote.canceled).toBeFalsy();
cancel();
expect(remote.canceled).toBeTruthy();
await expect(mainActor.send("remoteFail", []).value).rejects.toThrowError(
"Error: error",
);
});
| src/actor.test.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/e2e.test.ts",
"retrieved_chunk": " return { value: Promise.resolve(value), cancel() {} };\n});\nconst remote = new WorkerDispatch();\nconst local = new MainThreadDispatch();\nconst workerFromMainThread: Worker = {} as any as Worker;\nconst mainThreadFromWorker: Worker = {} as any as Worker;\nworkerFromMainThread.postMessage = (data) =>\n mainThreadFromWorker?.onmessage?.({ data } as any);\nmainThreadFromWorker.postMessage = (data) =>\n workerFromMainThread?.onmessage?.({ data } as any);",
"score": 154.44361007700346
},
{
"filename": "src/e2e.test.ts",
"retrieved_chunk": "const mainActor = new Actor<WorkerDispatch>(workerFromMainThread, local);\nconst workerActor = new Actor<MainThreadDispatch>(mainThreadFromWorker, remote);\nconst source = new DemSource({\n url: \"https://example/{z}/{x}/{y}.png\",\n cacheSize: 100,\n encoding: \"terrarium\",\n maxzoom: 11,\n worker: true,\n actor: mainActor,\n});",
"score": 57.11657800446393
},
{
"filename": "src/actor.ts",
"retrieved_chunk": " constructor(dest: Worker, dispatcher: any, timeoutMs: number = 20_000) {\n this.callbacks = {};\n this.cancels = {};\n this.dest = dest;\n this.timeoutMs = timeoutMs;\n this.dest.onmessage = async ({ data }) => {\n const message: Message = data;\n if (message.type === \"cancel\") {\n const cancel = this.cancels[message.id];\n delete this.cancels[message.id];",
"score": 38.64288557684108
},
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": "}\nfunction defaultActor(): Actor<WorkerDispatch> {\n if (!_actor) {\n const worker = new Worker(CONFIG.workerUrl);\n const dispatch = new MainThreadDispatch();\n _actor = new Actor(worker, dispatch);\n }\n return _actor;\n}\n/**",
"score": 29.0984426520131
},
{
"filename": "src/performance.ts",
"retrieved_chunk": " return result as any as PerformanceResourceTiming;\n}",
"score": 27.860195862146018
}
] | typescript | const mainActor = new Actor<Remote>(workerFromMainThread, local); |
import { CommandModule } from "yargs";
import { logSuccess } from "./login";
import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies";
import { doCredentialsExist, persistCredentials } from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import { logDAU } from "../utils/telemetry";
import { isEmailValid } from "../utils/validation";
const axios = require("axios");
const inquirer = require("inquirer");
const ora = require("ora");
const command = "signup";
const describe = "Create a Retool account.";
const builder = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handler = async function (argv: any) {
// Ask user if they want to overwrite existing credentials.
if (doCredentialsExist()) {
const { overwrite } = await inquirer.prompt([
{
name: "overwrite",
message:
"You're already logged in. Do you want to log out and create a new account?",
type: "confirm",
},
]);
if (!overwrite) {
return;
}
}
// Step 1: Collect a valid email/password.
let email, password, name, org;
while (!email) {
email = await collectEmail();
}
while (!password) {
password = await colllectPassword();
}
// Step 2: Call signup endpoint, get cookies.
const spinner = ora(
"Verifying that the email and password are valid on the server"
).start();
const signupResponse = await postRequest(
`https://login.retool.com/api/signup`,
{
email,
password,
planKey: "free",
}
);
spinner.stop();
const | accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
); |
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]);
if (!accessToken || !xsrfToken) {
if (process.env.DEBUG) {
console.log(signupResponse);
}
console.log(
"Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free."
);
return;
}
axios.defaults.headers["x-xsrf-token"] = xsrfToken;
axios.defaults.headers.cookie = `accessToken=${accessToken};`;
// Step 3: Collect a valid name/org.
while (!name) {
name = await collectName();
}
while (!org) {
org = await collectOrg();
}
// Step 4: Initialize organization.
await postRequest(
`https://login.retool.com/api/organization/admin/initializeOrganization`,
{
subdomain: org,
}
);
// Step 5: Persist credentials
const origin = `https://${org}.retool.com`;
const userRes = await getRequest(`${origin}/api/user`);
persistCredentials({
origin,
accessToken,
xsrf: xsrfToken,
firstName: userRes.data.user?.firstName,
lastName: userRes.data.user?.lastName,
email: userRes.data.user?.email,
telemetryEnabled: true,
});
logSuccess();
await logDAU();
};
async function collectEmail(): Promise<string | undefined> {
const { email } = await inquirer.prompt([
{
name: "email",
message: "What is your email?",
type: "input",
},
]);
if (!isEmailValid(email)) {
console.log("Invalid email, try again.");
return;
}
return email;
}
async function colllectPassword(): Promise<string | undefined> {
const { password } = await inquirer.prompt([
{
name: "password",
message: "Please create a password (min 8 characters):",
type: "password",
},
]);
const { confirmedPassword } = await inquirer.prompt([
{
name: "confirmedPassword",
message: "Please confirm password:",
type: "password",
},
]);
if (password.length < 8) {
console.log("Password must be at least 8 characters long, try again.");
return;
}
if (password !== confirmedPassword) {
console.log("Passwords do not match, try again.");
return;
}
return password;
}
async function collectName(): Promise<string | undefined> {
const { name } = await inquirer.prompt([
{
name: "name",
message: "What is your first and last name?",
type: "input",
},
]);
if (!name || name.length === 0) {
console.log("Invalid name, try again.");
return;
}
const parts = name.split(" ");
const changeNameResponse = await postRequest(
`https://login.retool.com/api/user/changeName`,
{
firstName: parts[0],
lastName: parts[1],
},
false
);
if (!changeNameResponse) {
return;
}
return name;
}
async function collectOrg(): Promise<string | undefined> {
let { org } = await inquirer.prompt([
{
name: "org",
message:
"What is your organization name? Leave blank to generate a random name.",
type: "input",
},
]);
if (!org || org.length === 0) {
// Org must start with letter, append a random string after it.
// https://stackoverflow.com/a/8084248
org = "z" + (Math.random() + 1).toString(36).substring(2);
}
const checkSubdomainAvailabilityResponse = await getRequest(
`https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`,
false
);
if (!checkSubdomainAvailabilityResponse.status) {
return;
}
return org;
}
const commandModule: CommandModule = { command, describe, builder, handler };
export default commandModule;
| src/commands/signup.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " );\n const { redirectUri } = authResponse.data;\n const redirectUrl = localhost\n ? new URL(loginOrigin)\n : redirectUri\n ? new URL(redirectUri)\n : undefined;\n const accessToken = accessTokenFromCookies(\n authResponse.headers[\"set-cookie\"]\n );",
"score": 21.72205964788081
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;\n spinner.stop();\n return credentials;\n}",
"score": 19.335926423292417
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " const xsrfToken = xsrfTokenFromCookies(authResponse.headers[\"set-cookie\"]);\n // Step 3: Persist the credentials.\n if (redirectUrl?.origin && accessToken && xsrfToken) {\n persistCredentials({\n origin: redirectUrl.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: authResponse.data.user?.firstName,\n lastName: authResponse.data.user?.lastName,\n email: authResponse.data.user?.email,",
"score": 18.361963302467316
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;",
"score": 15.787556670505907
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": " axios.defaults.headers[\"x-xsrf-token\"] = xsrfToken;\n axios.defaults.headers.cookie = `accessToken=${accessToken};`;\n const userRes = await getRequest(`https://${url.hostname}/api/user`);\n persistCredentials({\n origin: url.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: userRes.data.user?.firstName,\n lastName: userRes.data.user?.lastName,\n email: userRes.data.user?.email,",
"score": 15.22358978101642
}
] | typescript | accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
); |
/* eslint-disable no-restricted-globals */
import type Actor from "./actor";
import { offscreenCanvasSupported } from "./utils";
import type { MainThreadDispatch } from "./remote-dem-manager";
import { CancelablePromise, DemTile, Encoding } from "./types";
let offscreenCanvas: OffscreenCanvas;
let offscreenContext: OffscreenCanvasRenderingContext2D | null;
let canvas: HTMLCanvasElement;
let canvasContext: CanvasRenderingContext2D | null;
/**
* Parses a `raster-dem` image into a DemTile using OffscreenCanvas and createImageBitmap
* only supported on newer browsers.
*/
function decodeImageModern(
blob: Blob,
encoding: Encoding,
): CancelablePromise<DemTile> {
let canceled = false;
const promise = createImageBitmap(blob).then((img) => {
if (canceled) return null as any as DemTile;
if (!offscreenCanvas) {
offscreenCanvas = new OffscreenCanvas(img.width, img.height);
offscreenContext = offscreenCanvas.getContext("2d", {
willReadFrequently: true,
}) as OffscreenCanvasRenderingContext2D;
}
return getElevations(img, encoding, offscreenCanvas, offscreenContext);
});
return {
value: promise,
cancel: () => {
canceled = true;
},
};
}
/**
* Parses a `raster-dem` image into a DemTile using `<img>` element drawn to a `<canvas>`.
* Only works on the main thread, but works across all browsers.
*/
function decodeImageOld(
blob: Blob,
encoding: Encoding,
): CancelablePromise<DemTile> {
if (!canvas) {
canvas = document.createElement("canvas");
canvasContext = canvas.getContext("2d", {
willReadFrequently: true,
}) as CanvasRenderingContext2D;
}
let canceled = false;
const img: HTMLImageElement = new Image();
const value = new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => {
if (!canceled) resolve(img);
URL.revokeObjectURL(img.src);
img.onload = null;
};
img.onerror = () => reject(new Error("Could not load image."));
img.src = blob.size ? URL.createObjectURL(blob) : "";
}).then((img: HTMLImageElement) =>
getElevations(img, encoding, canvas, canvasContext),
);
return {
value,
cancel: () => {
canceled = true;
img.src = "";
},
};
}
/**
* Parses a `raster-dem` image in a worker that doesn't support OffscreenCanvas and createImageBitmap
* by running decodeImageOld on the main thread and returning the result.
*/
function decodeImageOnMainThread(
blob: Blob,
encoding: Encoding,
): CancelablePromise<DemTile> {
return ((self as any).actor as Actor<MainThreadDispatch>).send(
"decodeImage",
[],
undefined,
blob,
encoding,
);
}
function isWorker(): boolean {
return (
// @ts-ignore
typeof WorkerGlobalScope !== "undefined" &&
typeof self !== "undefined" &&
// @ts-ignore
self instanceof WorkerGlobalScope
);
}
const defaultDecoder: (
blob: Blob,
encoding: Encoding,
) => CancelablePromise<DemTile> = | offscreenCanvasSupported()
? decodeImageModern
: isWorker()
? decodeImageOnMainThread
: decodeImageOld; |
export default defaultDecoder;
function getElevations(
img: ImageBitmap | HTMLImageElement,
encoding: Encoding,
canvas: HTMLCanvasElement | OffscreenCanvas,
canvasContext:
| CanvasRenderingContext2D
| OffscreenCanvasRenderingContext2D
| null,
): DemTile {
canvas.width = img.width;
canvas.height = img.height;
if (!canvasContext) throw new Error("failed to get context");
canvasContext.drawImage(img, 0, 0, img.width, img.height);
const rgba = canvasContext.getImageData(0, 0, img.width, img.height).data;
return decodeParsedImage(img.width, img.height, encoding, rgba);
}
export function decodeParsedImage(
width: number,
height: number,
encoding: Encoding,
input: Uint8ClampedArray,
): DemTile {
const decoder: (r: number, g: number, b: number) => number =
encoding === "mapbox"
? (r, g, b) => -10000 + (r * 256 * 256 + g * 256 + b) * 0.1
: (r, g, b) => r * 256 + g + b / 256 - 32768;
const data = new Float32Array(width * height);
for (let i = 0; i < input.length; i += 4) {
data[i / 4] = decoder(input[i], input[i + 1], input[i + 2]);
}
return { width, height, data };
}
| src/decode-image.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/dem-manager.ts",
"retrieved_chunk": " maxzoom: number;\n timeoutMs: number;\n loaded = Promise.resolve();\n decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =\n decodeImage;\n constructor(\n demUrlPattern: string,\n cacheSize: number,\n encoding: Encoding,\n maxzoom: number,",
"score": 24.61015071269138
},
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " Encoding,\n FetchResponse,\n IndividualContourTileOptions,\n} from \"./types\";\nimport { prepareDemTile } from \"./utils\";\nlet _actor: Actor<WorkerDispatch> | undefined;\nlet id = 0;\nexport class MainThreadDispatch {\n decodeImage = (blob: Blob, encoding: Encoding) =>\n prepareDemTile(decodeImage(blob, encoding), false);",
"score": 19.7318626804305
},
{
"filename": "src/dem-manager.ts",
"retrieved_chunk": "}\n/**\n * Caches, decodes, and processes raster tiles in the current thread.\n */\nexport class LocalDemManager implements DemManager {\n tileCache: AsyncCache<string, FetchResponse>;\n parsedCache: AsyncCache<string, DemTile>;\n contourCache: AsyncCache<string, ContourTile>;\n demUrlPattern: string;\n encoding: Encoding;",
"score": 9.444821752247393
},
{
"filename": "src/dem-manager.ts",
"retrieved_chunk": "import AsyncCache from \"./cache\";\nimport decodeImage from \"./decode-image\";\nimport { HeightTile } from \"./height-tile\";\nimport generateIsolines from \"./isolines\";\nimport { encodeIndividualOptions, withTimeout } from \"./utils\";\nimport {\n CancelablePromise,\n ContourTile,\n DemTile,\n Encoding,",
"score": 8.817294369331801
},
{
"filename": "src/types.ts",
"retrieved_chunk": " managerId: number;\n demUrlPattern: string;\n cacheSize: number;\n encoding: Encoding;\n maxzoom: number;\n timeoutMs: number;\n}\nexport type TimingCategory = \"main\" | \"worker\" | \"fetch\" | \"decode\" | \"isoline\";\n/** Performance profile for a tile request */\nexport interface Timing {",
"score": 6.8813657826643055
}
] | typescript | offscreenCanvasSupported()
? decodeImageModern
: isWorker()
? decodeImageOnMainThread
: decodeImageOld; |
import AsyncCache from "./cache";
import decodeImage from "./decode-image";
import { HeightTile } from "./height-tile";
import generateIsolines from "./isolines";
import { encodeIndividualOptions, withTimeout } from "./utils";
import {
CancelablePromise,
ContourTile,
DemTile,
Encoding,
FetchResponse,
IndividualContourTileOptions,
} from "./types";
import encodeVectorTile, { GeomType } from "./vtpbf";
import { Timer } from "./performance";
/**
* Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary
* tiles and returns an encoded contour vector tiles.
*/
export interface DemManager {
loaded: Promise<any>;
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse>;
fetchAndParseTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile>;
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile>;
}
/**
* Caches, decodes, and processes raster tiles in the current thread.
*/
export class LocalDemManager implements DemManager {
tileCache: | AsyncCache<string, FetchResponse>; |
parsedCache: AsyncCache<string, DemTile>;
contourCache: AsyncCache<string, ContourTile>;
demUrlPattern: string;
encoding: Encoding;
maxzoom: number;
timeoutMs: number;
loaded = Promise.resolve();
decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =
decodeImage;
constructor(
demUrlPattern: string,
cacheSize: number,
encoding: Encoding,
maxzoom: number,
timeoutMs: number,
) {
this.tileCache = new AsyncCache(cacheSize);
this.parsedCache = new AsyncCache(cacheSize);
this.contourCache = new AsyncCache(cacheSize);
this.timeoutMs = timeoutMs;
this.demUrlPattern = demUrlPattern;
this.encoding = encoding;
this.maxzoom = maxzoom;
}
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse> {
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.tileCache.getCancelable(url, () => {
let cancel = () => {};
const options: RequestInit = {};
try {
const controller = new AbortController();
options.signal = controller.signal;
cancel = () => controller.abort();
} catch (e) {
// ignore
}
timer?.fetchTile(url);
const mark = timer?.marker("fetch");
return withTimeout(this.timeoutMs, {
value: fetch(url, options).then(async (response) => {
mark?.();
if (!response.ok) {
throw new Error(`Bad response: ${response.status} for ${url}`);
}
return {
data: await response.blob(),
expires: response.headers.get("expires") || undefined,
cacheControl: response.headers.get("cache-control") || undefined,
};
}),
cancel,
});
});
}
fetchAndParseTile = (
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile> => {
const self = this;
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.parsedCache.getCancelable(url, () => {
const tile = self.fetchTile(z, x, y, timer);
let canceled = false;
let alsoCancel = () => {};
return {
value: tile.value.then(async (response) => {
if (canceled) throw new Error("canceled");
const result = self.decodeImage(response.data, self.encoding);
alsoCancel = result.cancel;
const mark = timer?.marker("decode");
const value = await result.value;
mark?.();
return value;
}),
cancel: () => {
canceled = true;
alsoCancel();
tile.cancel();
},
};
});
};
fetchDem(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<HeightTile> {
const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom);
const subZ = z - zoom;
const div = 1 << subZ;
const newX = Math.floor(x / div);
const newY = Math.floor(y / div);
const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer);
const subX = x % div;
const subY = y % div;
return {
value: value.then((tile) =>
HeightTile.fromRawDem(tile).split(subZ, subX, subY),
),
cancel,
};
}
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile> {
const {
levels,
multiplier = 1,
buffer = 1,
extent = 4096,
contourLayer = "contours",
elevationKey = "ele",
levelKey = "level",
subsampleBelow = 100,
} = options;
// no levels means less than min zoom with levels specified
if (!levels || levels.length === 0) {
return {
cancel() {},
value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }),
};
}
const key = [z, x, y, encodeIndividualOptions(options)].join("/");
return this.contourCache.getCancelable(key, () => {
const max = 1 << z;
let canceled = false;
const neighborPromises: (CancelablePromise<HeightTile> | null)[] = [];
for (let iy = y - 1; iy <= y + 1; iy++) {
for (let ix = x - 1; ix <= x + 1; ix++) {
neighborPromises.push(
iy < 0 || iy >= max
? null
: this.fetchDem(z, (ix + max) % max, iy, options, timer),
);
}
}
const value = Promise.all(neighborPromises.map((n) => n?.value)).then(
async (neighbors) => {
let virtualTile = HeightTile.combineNeighbors(neighbors);
if (!virtualTile || canceled) {
return { arrayBuffer: new Uint8Array().buffer };
}
const mark = timer?.marker("isoline");
if (virtualTile.width >= subsampleBelow) {
virtualTile = virtualTile.materialize(2);
} else {
while (virtualTile.width < subsampleBelow) {
virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2);
}
}
virtualTile = virtualTile
.averagePixelCentersToGrid()
.scaleElevation(multiplier)
.materialize(1);
const isolines = generateIsolines(
levels[0],
virtualTile,
extent,
buffer,
);
mark?.();
const result = encodeVectorTile({
extent,
layers: {
[contourLayer]: {
features: Object.entries(isolines).map(([eleString, geom]) => {
const ele = Number(eleString);
return {
type: GeomType.LINESTRING,
geometry: geom,
properties: {
[elevationKey]: ele,
[levelKey]: Math.max(
...levels.map((l, i) => (ele % l === 0 ? i : 0)),
),
},
};
}),
},
},
});
mark?.();
return { arrayBuffer: result.buffer };
},
);
return {
value,
cancel() {
canceled = true;
neighborPromises.forEach((n) => n && n.cancel());
},
};
});
}
}
| src/dem-manager.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " * Caches, decodes, and processes raster tiles in a shared web worker.\n */\nexport default class RemoteDemManager implements DemManager {\n managerId: number;\n actor: Actor<WorkerDispatch>;\n loaded: Promise<any>;\n constructor(\n demUrlPattern: string,\n cacheSize: number,\n encoding: Encoding,",
"score": 42.98557976091194
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": "import { LocalDemManager } from \"./dem-manager\";\nimport { Timer } from \"./performance\";\nimport {\n CancelablePromise,\n ContourTile,\n FetchResponse,\n IndividualContourTileOptions,\n InitMessage,\n TransferrableDemTile,\n} from \"./types\";",
"score": 23.907622971786076
},
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n this.actor.send(\n \"fetchContourTile\",\n [],\n timer,",
"score": 22.38610946670233
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " );\n fetchContourTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n prepareContourTile(",
"score": 21.779088045873443
},
{
"filename": "src/performance.ts",
"retrieved_chunk": " for (const list of input) {\n result.push(...list);\n }\n return result;\n}\n/** Utility for tracking how long tiles take to generate, and where the time is going. */\nexport class Timer {\n marks: { [key in TimingCategory]?: number[][] } = {};\n urls: string[] = [];\n fetched: string[] = [];",
"score": 18.94904435598883
}
] | typescript | AsyncCache<string, FetchResponse>; |
import { Credentials } from "./credentials";
import { getRequest, postRequest } from "./networking";
export type ResourceByEnv = Record<string, Resource>;
export type Resource = {
displayName: string;
id: number;
name: string;
type: string;
environment: string;
environmentId: string;
uuid: string;
organizationId: number;
resourceFolderId: number;
};
export async function getResourceByName(
resourceName: string,
credentials: Credentials
): Promise<ResourceByEnv> {
const getResourceResult = await getRequest(
`${credentials.origin}/api/resources/names/${resourceName}`
);
const { resourceByEnv } = getResourceResult.data;
if (!resourceByEnv) {
console.log("Error finding resource by that id.");
console.log(getResourceResult.data);
process.exit(1);
} else {
return resourceByEnv;
}
}
export async function createResource({
resourceType,
credentials,
displayName,
resourceFolderId,
resourceOptions,
}: {
resourceType: string;
credentials: Credentials;
displayName?: string;
resourceFolderId?: number;
resourceOptions?: Record<string, any>;
}): Promise<Resource> {
| const createResourceResult = await postRequest(
`${credentials.origin}/api/resources/`,
{ |
type: resourceType,
displayName,
resourceFolderId,
options: resourceOptions ? resourceOptions : {},
},
false,
{},
false
);
const resource = createResourceResult.data;
if (!resource) {
throw new Error("Error creating resource.");
} else {
return resource;
}
}
| src/utils/resources.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/commands/rpc.ts",
"retrieved_chunk": " type: \"input\",\n validate: async (displayName: string) => {\n try {\n const resource = await createResource({\n resourceType: \"retoolSdk\",\n credentials,\n resourceOptions: {\n requireExplicitVersion: false,\n },\n displayName,",
"score": 31.579072834414685
},
{
"filename": "src/utils/playgroundQuery.ts",
"retrieved_chunk": " organizationId: number;\n ownerId: number;\n saveId: number;\n template: Record<string, any>;\n resourceId: number;\n resourceUuid: string;\n adhocResourceType: string;\n};\nexport async function createPlaygroundQuery(\n resourceId: number,",
"score": 24.064882517621452
},
{
"filename": "src/utils/playgroundQuery.ts",
"retrieved_chunk": " credentials: Credentials,\n queryName?: string\n): Promise<PlaygroundQuery> {\n const createPlaygroundQueryResult = await postRequest(\n `${credentials.origin}/api/playground`,\n {\n name: queryName || \"CLI Generated RPC Query\",\n description: \"\",\n shared: false,\n resourceId,",
"score": 23.40453914865724
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " const credentials = getCredentials();\n if (!credentials) {\n return;\n }\n // 1. Fetch all resources\n const resources = await getRequest(`${credentials.origin}/api/resources`);\n // 2. Filter down to Retool DB UUID\n const retoolDBs = resources?.data?.resources?.filter(\n (resource: any) => resource.displayName === \"retool_db\"\n );",
"score": 23.28855595928339
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " retoolDBInfo: DBInfoPayload,\n fields: RetoolDBField[],\n primaryKeyMaxVal: number,\n credentials: Credentials,\n exitOnFailure: boolean\n): Promise<\n | {\n fields: string[];\n data: string[][];\n }",
"score": 22.156943041769253
}
] | typescript | const createResourceResult = await postRequest(
`${credentials.origin}/api/resources/`,
{ |
import AsyncCache from "./cache";
import decodeImage from "./decode-image";
import { HeightTile } from "./height-tile";
import generateIsolines from "./isolines";
import { encodeIndividualOptions, withTimeout } from "./utils";
import {
CancelablePromise,
ContourTile,
DemTile,
Encoding,
FetchResponse,
IndividualContourTileOptions,
} from "./types";
import encodeVectorTile, { GeomType } from "./vtpbf";
import { Timer } from "./performance";
/**
* Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary
* tiles and returns an encoded contour vector tiles.
*/
export interface DemManager {
loaded: Promise<any>;
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse>;
fetchAndParseTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile>;
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile>;
}
/**
* Caches, decodes, and processes raster tiles in the current thread.
*/
export class LocalDemManager implements DemManager {
tileCache: AsyncCache<string, FetchResponse>;
parsedCache: AsyncCache<string, DemTile>;
contourCache: AsyncCache<string, ContourTile>;
demUrlPattern: string;
encoding: Encoding;
maxzoom: number;
timeoutMs: number;
loaded = Promise.resolve();
decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =
decodeImage;
constructor(
demUrlPattern: string,
cacheSize: number,
encoding: Encoding,
maxzoom: number,
timeoutMs: number,
) {
this.tileCache = new AsyncCache(cacheSize);
this.parsedCache = new AsyncCache(cacheSize);
this.contourCache = new AsyncCache(cacheSize);
this.timeoutMs = timeoutMs;
this.demUrlPattern = demUrlPattern;
this.encoding = encoding;
this.maxzoom = maxzoom;
}
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse> {
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.tileCache.getCancelable(url, () => {
let cancel = () => {};
const options: RequestInit = {};
try {
const controller = new AbortController();
options.signal = controller.signal;
cancel = () => controller.abort();
} catch (e) {
// ignore
}
timer?.fetchTile(url);
const mark = timer?.marker("fetch");
return withTimeout(this.timeoutMs, {
value: fetch(url, options).then(async (response) => {
mark?.();
if (!response.ok) {
throw new Error(`Bad response: ${response.status} for ${url}`);
}
return {
data: await response.blob(),
expires: response.headers.get("expires") || undefined,
cacheControl: response.headers.get("cache-control") || undefined,
};
}),
cancel,
});
});
}
fetchAndParseTile = (
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile> => {
const self = this;
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.parsedCache.getCancelable(url, () => {
const tile = self.fetchTile(z, x, y, timer);
let canceled = false;
let alsoCancel = () => {};
return {
value: tile.value.then(async (response) => {
if (canceled) throw new Error("canceled");
const result = self.decodeImage(response.data, self.encoding);
alsoCancel = result.cancel;
const mark = timer?.marker("decode");
const value = await result.value;
mark?.();
return value;
}),
cancel: () => {
canceled = true;
alsoCancel();
tile.cancel();
},
};
});
};
fetchDem(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
) | : CancelablePromise<HeightTile> { |
const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom);
const subZ = z - zoom;
const div = 1 << subZ;
const newX = Math.floor(x / div);
const newY = Math.floor(y / div);
const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer);
const subX = x % div;
const subY = y % div;
return {
value: value.then((tile) =>
HeightTile.fromRawDem(tile).split(subZ, subX, subY),
),
cancel,
};
}
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile> {
const {
levels,
multiplier = 1,
buffer = 1,
extent = 4096,
contourLayer = "contours",
elevationKey = "ele",
levelKey = "level",
subsampleBelow = 100,
} = options;
// no levels means less than min zoom with levels specified
if (!levels || levels.length === 0) {
return {
cancel() {},
value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }),
};
}
const key = [z, x, y, encodeIndividualOptions(options)].join("/");
return this.contourCache.getCancelable(key, () => {
const max = 1 << z;
let canceled = false;
const neighborPromises: (CancelablePromise<HeightTile> | null)[] = [];
for (let iy = y - 1; iy <= y + 1; iy++) {
for (let ix = x - 1; ix <= x + 1; ix++) {
neighborPromises.push(
iy < 0 || iy >= max
? null
: this.fetchDem(z, (ix + max) % max, iy, options, timer),
);
}
}
const value = Promise.all(neighborPromises.map((n) => n?.value)).then(
async (neighbors) => {
let virtualTile = HeightTile.combineNeighbors(neighbors);
if (!virtualTile || canceled) {
return { arrayBuffer: new Uint8Array().buffer };
}
const mark = timer?.marker("isoline");
if (virtualTile.width >= subsampleBelow) {
virtualTile = virtualTile.materialize(2);
} else {
while (virtualTile.width < subsampleBelow) {
virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2);
}
}
virtualTile = virtualTile
.averagePixelCentersToGrid()
.scaleElevation(multiplier)
.materialize(1);
const isolines = generateIsolines(
levels[0],
virtualTile,
extent,
buffer,
);
mark?.();
const result = encodeVectorTile({
extent,
layers: {
[contourLayer]: {
features: Object.entries(isolines).map(([eleString, geom]) => {
const ele = Number(eleString);
return {
type: GeomType.LINESTRING,
geometry: geom,
properties: {
[elevationKey]: ele,
[levelKey]: Math.max(
...levels.map((l, i) => (ele % l === 0 ? i : 0)),
),
},
};
}),
},
},
});
mark?.();
return { arrayBuffer: result.buffer };
},
);
return {
value,
cancel() {
canceled = true;
neighborPromises.forEach((n) => n && n.cancel());
},
};
});
}
}
| src/dem-manager.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n this.actor.send(\n \"fetchContourTile\",\n [],\n timer,",
"score": 30.88149134998
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " );\n fetchContourTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n prepareContourTile(",
"score": 30.772564023578582
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " };\n fetchTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<FetchResponse> =>\n this.managers[managerId]?.fetchTile(z, x, y, timer) || noManager(managerId);\n fetchAndParseTile = (",
"score": 23.75157369270265
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " managerId: number,\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<TransferrableDemTile> =>\n prepareDemTile(\n this.managers[managerId]?.fetchAndParseTile(z, x, y, timer) ||\n noManager(managerId),\n true,",
"score": 23.75157369270265
},
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " ): CancelablePromise<FetchResponse> =>\n this.actor.send(\"fetchTile\", [], timer, this.managerId, z, x, y);\n fetchAndParseTile = (\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<DemTile> =>\n this.actor.send(\"fetchAndParseTile\", [], timer, this.managerId, z, x, y);\n fetchContourTile = (",
"score": 23.69010636769315
}
] | typescript | : CancelablePromise<HeightTile> { |
import { CommandModule } from "yargs";
import { createAppForTable, deleteApp } from "../utils/apps";
import {
Credentials,
getAndVerifyCredentialsWithRetoolDB,
} from "../utils/credentials";
import { getRequest, postRequest } from "../utils/networking";
import {
collectColumnNames,
collectTableName,
createTable,
createTableFromCSV,
deleteTable,
generateDataWithGPT,
} from "../utils/table";
import type { DBInfoPayload } from "../utils/table";
import { logDAU } from "../utils/telemetry";
import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows";
const inquirer = require("inquirer");
const command = "scaffold";
const describe = "Scaffold a Retool DB table, CRUD Workflow, and App.";
const builder: CommandModule["builder"] = {
name: {
alias: "n",
describe: `Name of table to scaffold. Usage:
retool scaffold -n <table_name>`,
type: "string",
nargs: 1,
},
columns: {
alias: "c",
describe: `Column names in DB to scaffold. Usage:
retool scaffold -c <col1> <col2>`,
type: "array",
},
delete: {
alias: "d",
describe: `Delete a table, Workflow and App created via scaffold. Usage:
retool scaffold -d <db_name>`,
type: "string",
nargs: 1,
},
"from-csv": {
alias: "f",
describe: `Create a table, Workflow and App from a CSV file. Usage:
retool scaffold -f <path-to-csv>`,
type: "array",
},
"no-workflow": {
describe: `Modifier to avoid generating Workflow. Usage:
retool scaffold --no-workflow`,
type: "boolean",
},
};
const handler = async function (argv: any) {
const credentials = await getAndVerifyCredentialsWithRetoolDB();
// fire and forget
void logDAU(credentials);
// Handle `retool scaffold -d <db_name>`
if (argv.delete) {
const tableName = argv.delete;
const workflowName = `${tableName} CRUD Workflow`;
// Confirm deletion.
const { confirm } = await inquirer.prompt([
{
name: "confirm",
message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`,
type: "confirm",
},
]);
if (!confirm) {
process.exit(0);
}
//TODO: Could be parallelized.
//TODO: Verify existence before trying to delete.
await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
}
// Handle `retool scaffold -f <path-to-csv>`
else if (argv.f) {
const csvFileNames = argv.f;
for (const csvFileName of csvFileNames) {
const { tableName, colNames } = await createTableFromCSV(
csvFileName,
credentials,
false,
false
);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
console.log("");
}
}
// Handle `retool scaffold`
else {
let tableName = argv.name;
let colNames = argv.columns;
if (!tableName || tableName.length == 0) {
tableName = await collectTableName();
}
if (!colNames || colNames.length == 0) {
colNames = await collectColumnNames();
}
await createTable(tableName, colNames, undefined, credentials, false);
// Fire and forget
void insertSampleData(tableName, credentials);
if (!argv["no-workflow"]) {
console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
}
console.log("\n");
const searchColumnName = colNames.length > 0 ? colNames[0] : "id";
await createAppForTable(
`${tableName} App`,
tableName,
searchColumnName,
credentials
);
}
};
const insertSampleData = async function (
tableName: string,
credentials: Credentials
) {
| const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
const retoolDBInfo: DBInfoPayload = infoRes.data;
const { fields } = retoolDBInfo.tableInfo;
const generatedData = await generateDataWithGPT(
retoolDBInfo,
fields,
0,
credentials,
false
);
if (generatedData) {
await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{
kind: "BulkInsertIntoTable",
tableName: tableName,
additions: generatedData,
}
);
}
};
const commandModule: CommandModule = {
command,
describe,
builder,
handler,
};
export default commandModule;
| src/commands/scaffold.ts | tryretool-retool-cli-91b2c68 | [
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " const infoResponse = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n spinner.stop();\n const { tableInfo } = infoResponse.data;\n if (tableInfo) {\n return tableInfo;\n }\n}\nexport async function deleteTable(",
"score": 37.38160298320278
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,",
"score": 36.596162099559635
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"DeleteTable\",\n payload: {\n table: tableName,\n },\n }\n );\n spinner.stop();",
"score": 30.679306764973916
},
{
"filename": "src/commands/db.ts",
"retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }",
"score": 27.635426370573487
},
{
"filename": "src/utils/connectionString.ts",
"retrieved_chunk": " !credentials.retoolDBUuid ||\n !credentials.hasConnectionString\n ) {\n return;\n }\n const grid = await getRequest(\n `${credentials.origin}/api/grid/retooldb/${credentials.retoolDBUuid}?env=production`,\n false\n );\n return grid.data?.gridInfo?.connectionString;",
"score": 23.148811177283218
}
] | typescript | const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
import AsyncCache from "./cache";
import decodeImage from "./decode-image";
import { HeightTile } from "./height-tile";
import generateIsolines from "./isolines";
import { encodeIndividualOptions, withTimeout } from "./utils";
import {
CancelablePromise,
ContourTile,
DemTile,
Encoding,
FetchResponse,
IndividualContourTileOptions,
} from "./types";
import encodeVectorTile, { GeomType } from "./vtpbf";
import { Timer } from "./performance";
/**
* Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary
* tiles and returns an encoded contour vector tiles.
*/
export interface DemManager {
loaded: Promise<any>;
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse>;
fetchAndParseTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile>;
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile>;
}
/**
* Caches, decodes, and processes raster tiles in the current thread.
*/
export class LocalDemManager implements DemManager {
tileCache: AsyncCache<string, FetchResponse>;
parsedCache: AsyncCache<string, DemTile>;
contourCache: AsyncCache<string, ContourTile>;
demUrlPattern: string;
encoding: Encoding;
maxzoom: number;
timeoutMs: number;
loaded = Promise.resolve();
decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =
decodeImage;
constructor(
demUrlPattern: string,
cacheSize: number,
encoding: Encoding,
maxzoom: number,
timeoutMs: number,
) {
this.tileCache = new AsyncCache(cacheSize);
this.parsedCache = new AsyncCache(cacheSize);
this.contourCache = new AsyncCache(cacheSize);
this.timeoutMs = timeoutMs;
this.demUrlPattern = demUrlPattern;
this.encoding = encoding;
this.maxzoom = maxzoom;
}
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse> {
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.tileCache.getCancelable(url, () => {
let cancel = () => {};
const options: RequestInit = {};
try {
const controller = new AbortController();
options.signal = controller.signal;
cancel = () => controller.abort();
} catch (e) {
// ignore
}
timer?.fetchTile(url);
const mark = timer?.marker("fetch");
return withTimeout(this.timeoutMs, {
value: fetch(url, options).then(async (response) => {
mark?.();
if (!response.ok) {
throw new Error(`Bad response: ${response.status} for ${url}`);
}
return {
data: await response.blob(),
expires: response.headers.get("expires") || undefined,
cacheControl: response.headers.get("cache-control") || undefined,
};
}),
cancel,
});
});
}
fetchAndParseTile = (
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile> => {
const self = this;
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.parsedCache.getCancelable(url, () => {
const tile = self.fetchTile(z, x, y, timer);
let canceled = false;
let alsoCancel = () => {};
return {
value: tile.value.then(async (response) => {
if (canceled) throw new Error("canceled");
const result = self.decodeImage(response.data, self.encoding);
alsoCancel = result.cancel;
const mark = timer?.marker("decode");
const value = await result.value;
mark?.();
return value;
}),
cancel: () => {
canceled = true;
alsoCancel();
tile.cancel();
},
};
});
};
fetchDem(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<HeightTile> {
const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom);
const subZ = z - zoom;
const div = 1 << subZ;
const newX = Math.floor(x / div);
const newY = Math.floor(y / div);
const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer);
const subX = x % div;
const subY = y % div;
return {
value: value.then((tile) =>
HeightTile.fromRawDem(tile).split(subZ, subX, subY),
),
cancel,
};
}
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile> {
const {
levels,
multiplier = 1,
buffer = 1,
extent = 4096,
contourLayer = "contours",
elevationKey = "ele",
levelKey = "level",
subsampleBelow = 100,
} = options;
// no levels means less than min zoom with levels specified
if (!levels || levels.length === 0) {
return {
cancel() {},
value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }),
};
}
const key = [z, x, | y, encodeIndividualOptions(options)].join("/"); |
return this.contourCache.getCancelable(key, () => {
const max = 1 << z;
let canceled = false;
const neighborPromises: (CancelablePromise<HeightTile> | null)[] = [];
for (let iy = y - 1; iy <= y + 1; iy++) {
for (let ix = x - 1; ix <= x + 1; ix++) {
neighborPromises.push(
iy < 0 || iy >= max
? null
: this.fetchDem(z, (ix + max) % max, iy, options, timer),
);
}
}
const value = Promise.all(neighborPromises.map((n) => n?.value)).then(
async (neighbors) => {
let virtualTile = HeightTile.combineNeighbors(neighbors);
if (!virtualTile || canceled) {
return { arrayBuffer: new Uint8Array().buffer };
}
const mark = timer?.marker("isoline");
if (virtualTile.width >= subsampleBelow) {
virtualTile = virtualTile.materialize(2);
} else {
while (virtualTile.width < subsampleBelow) {
virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2);
}
}
virtualTile = virtualTile
.averagePixelCentersToGrid()
.scaleElevation(multiplier)
.materialize(1);
const isolines = generateIsolines(
levels[0],
virtualTile,
extent,
buffer,
);
mark?.();
const result = encodeVectorTile({
extent,
layers: {
[contourLayer]: {
features: Object.entries(isolines).map(([eleString, geom]) => {
const ele = Number(eleString);
return {
type: GeomType.LINESTRING,
geometry: geom,
properties: {
[elevationKey]: ele,
[levelKey]: Math.max(
...levels.map((l, i) => (ele % l === 0 ? i : 0)),
),
},
};
}),
},
},
});
mark?.();
return { arrayBuffer: result.buffer };
},
);
return {
value,
cancel() {
canceled = true;
neighborPromises.forEach((n) => n && n.cancel());
},
};
});
}
}
| src/dem-manager.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " return sortedEntries(options)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\",\");\n}\nexport function getOptionsForZoom(\n options: GlobalContourTileOptions,\n zoom: number,\n): IndividualContourTileOptions {\n const { thresholds, ...rest } = options;\n let levels: number[] = [];",
"score": 35.49284142902849
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " let maxLessThanOrEqualTo: number = -Infinity;\n Object.entries(thresholds).forEach(([zString, value]) => {\n const z = Number(zString);\n if (z <= zoom && z > maxLessThanOrEqualTo) {\n maxLessThanOrEqualTo = z;\n levels = typeof value === \"number\" ? [value] : value;\n }\n });\n return {\n levels,",
"score": 34.36142284943975
},
{
"filename": "src/utils.test.ts",
"retrieved_chunk": " levels: [1, 2],\n contourLayer: \"contour layer\",\n elevationKey: \"elevation key\",\n extent: 123,\n levelKey: \"level key\",\n multiplier: 123,\n overzoom: 3,\n };\n const origEncoded = encodeIndividualOptions(options);\n expect(encodeIndividualOptions(options)).toBe(origEncoded);",
"score": 33.452129477287116
},
{
"filename": "src/utils.test.ts",
"retrieved_chunk": " ...rest,\n levels: [100, 1000],\n });\n expect(getOptionsForZoom(fullGlobalOptions, 12)).toEqual({\n ...rest,\n levels: [100, 1000],\n });\n});\ntest(\"encode individual options\", () => {\n const options: IndividualContourTileOptions = {",
"score": 32.220965003454374
},
{
"filename": "src/utils.test.ts",
"retrieved_chunk": " const options: GlobalContourTileOptions = {\n thresholds: {\n 10: [500],\n 11: [100, 1000],\n },\n };\n expect(decodeOptions(encodeOptions(options))).toEqual(options);\n});\ntest(\"extract levels from global contour options\", () => {\n // eslint-disable-next-line",
"score": 26.32616765954411
}
] | typescript | y, encodeIndividualOptions(options)].join("/"); |
import AsyncCache from "./cache";
import decodeImage from "./decode-image";
import { HeightTile } from "./height-tile";
import generateIsolines from "./isolines";
import { encodeIndividualOptions, withTimeout } from "./utils";
import {
CancelablePromise,
ContourTile,
DemTile,
Encoding,
FetchResponse,
IndividualContourTileOptions,
} from "./types";
import encodeVectorTile, { GeomType } from "./vtpbf";
import { Timer } from "./performance";
/**
* Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary
* tiles and returns an encoded contour vector tiles.
*/
export interface DemManager {
loaded: Promise<any>;
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse>;
fetchAndParseTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile>;
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile>;
}
/**
* Caches, decodes, and processes raster tiles in the current thread.
*/
export class LocalDemManager implements DemManager {
tileCache: AsyncCache<string, FetchResponse>;
parsedCache: AsyncCache<string, DemTile>;
contourCache: AsyncCache<string, ContourTile>;
demUrlPattern: string;
encoding: Encoding;
maxzoom: number;
timeoutMs: number;
loaded = Promise.resolve();
decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =
decodeImage;
constructor(
demUrlPattern: string,
cacheSize: number,
encoding: Encoding,
maxzoom: number,
timeoutMs: number,
) {
this.tileCache = new AsyncCache(cacheSize);
this.parsedCache = new AsyncCache(cacheSize);
this.contourCache = new AsyncCache(cacheSize);
this.timeoutMs = timeoutMs;
this.demUrlPattern = demUrlPattern;
this.encoding = encoding;
this.maxzoom = maxzoom;
}
fetchTile(
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<FetchResponse> {
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.tileCache.getCancelable(url, () => {
let cancel = () => {};
const options: RequestInit = {};
try {
const controller = new AbortController();
options.signal = controller.signal;
cancel = () => controller.abort();
} catch (e) {
// ignore
}
timer?.fetchTile(url);
const mark = timer?.marker("fetch");
return withTimeout(this.timeoutMs, {
value: fetch(url, options).then(async (response) => {
mark?.();
if (!response.ok) {
throw new Error(`Bad response: ${response.status} for ${url}`);
}
return {
data: await response.blob(),
expires: response.headers.get("expires") || undefined,
cacheControl: response.headers.get("cache-control") || undefined,
};
}),
cancel,
});
});
}
fetchAndParseTile = (
z: number,
x: number,
y: number,
timer?: Timer,
): CancelablePromise<DemTile> => {
const self = this;
const url = this.demUrlPattern
.replace("{z}", z.toString())
.replace("{x}", x.toString())
.replace("{y}", y.toString());
timer?.useTile(url);
return this.parsedCache.getCancelable(url, () => {
const tile = self.fetchTile(z, x, y, timer);
let canceled = false;
let alsoCancel = () => {};
return {
value: tile.value.then(async (response) => {
if (canceled) throw new Error("canceled");
const result = self.decodeImage(response.data, self.encoding);
alsoCancel = result.cancel;
const mark = timer?.marker("decode");
const value = await result.value;
mark?.();
return value;
}),
cancel: () => {
canceled = true;
alsoCancel();
tile.cancel();
},
};
});
};
fetchDem(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<HeightTile> {
const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom);
const subZ = z - zoom;
const div = 1 << subZ;
const newX = Math.floor(x / div);
const newY = Math.floor(y / div);
const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer);
const subX = x % div;
const subY = y % div;
return {
value: value.then((tile) =>
HeightTile.fromRawDem(tile).split(subZ, subX, subY),
),
cancel,
};
}
fetchContourTile(
z: number,
x: number,
y: number,
options: IndividualContourTileOptions,
timer?: Timer,
): CancelablePromise<ContourTile> {
const {
levels,
multiplier = 1,
buffer = 1,
extent = 4096,
contourLayer = "contours",
elevationKey = "ele",
levelKey = "level",
subsampleBelow = 100,
} = options;
// no levels means less than min zoom with levels specified
if (!levels || levels.length === 0) {
return {
cancel() {},
value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }),
};
}
const key = [z, x, y, encodeIndividualOptions(options)].join("/");
return this.contourCache.getCancelable(key, () => {
const max = 1 << z;
let canceled = false;
const neighborPromises: (CancelablePromise<HeightTile> | null)[] = [];
for (let iy = y - 1; iy <= y + 1; iy++) {
for (let ix = x - 1; ix <= x + 1; ix++) {
neighborPromises.push(
iy < 0 || iy >= max
? null
: this.fetchDem(z, (ix + max) % max, iy, options, timer),
);
}
}
const value = Promise.all(neighborPromises.map((n) => n?.value)).then(
async (neighbors) => {
let virtualTile = HeightTile.combineNeighbors(neighbors);
if (!virtualTile || canceled) {
return { arrayBuffer: new Uint8Array().buffer };
}
const mark = timer?.marker("isoline");
if (virtualTile.width >= subsampleBelow) {
virtualTile = virtualTile.materialize(2);
} else {
while (virtualTile.width < subsampleBelow) {
virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2);
}
}
virtualTile = virtualTile
.averagePixelCentersToGrid()
.scaleElevation(multiplier)
.materialize(1);
const isolines = generateIsolines(
levels[0],
virtualTile,
extent,
buffer,
);
mark?.();
const result = encodeVectorTile({
extent,
layers: {
[contourLayer]: {
features: Object.entries(isolines).map(([eleString, geom]) => {
const ele = Number(eleString);
return {
| type: GeomType.LINESTRING,
geometry: geom,
properties: { |
[elevationKey]: ele,
[levelKey]: Math.max(
...levels.map((l, i) => (ele % l === 0 ? i : 0)),
),
},
};
}),
},
},
});
mark?.();
return { arrayBuffer: result.buffer };
},
);
return {
value,
cancel() {
canceled = true;
neighborPromises.forEach((n) => n && n.cancel());
},
};
});
}
}
| src/dem-manager.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/vtpbf.test.ts",
"retrieved_chunk": "test(\"simple line\", () => {\n const encoded = encodeVectorTile({\n layers: {\n contours: {\n features: [\n {\n geometry: [[0, 1, 2, 3]],\n type: GeomType.LINESTRING,\n properties: {\n key: \"value\",",
"score": 35.325398875018585
},
{
"filename": "src/vtpbf.ts",
"retrieved_chunk": " properties: { [key: string]: PropertyValue };\n geometry: number[][];\n}\nexport interface Layer {\n features: Feature[];\n extent?: number;\n}\nexport interface Tile {\n extent?: number;\n layers: { [id: string]: Layer };",
"score": 22.178798244696786
},
{
"filename": "src/e2e.test.ts",
"retrieved_chunk": " e: 10,\n l: 0,\n });\n const geom = tile.layers.c.feature(0).loadGeometry()[0];\n expect(geom.length).toEqual(253);\n let xSum = 0,\n ySum = 0;\n for (const { x, y } of geom) {\n xSum += x;\n ySum += y;",
"score": 21.0440570726277
},
{
"filename": "src/vtpbf.test.ts",
"retrieved_chunk": " ],\n type: GeomType.LINESTRING,\n properties: {\n key: 1,\n key2: true,\n },\n },\n ],\n },\n },",
"score": 20.287150019682418
},
{
"filename": "src/vtpbf.test.ts",
"retrieved_chunk": "});\ntest(\"multi line\", () => {\n const encoded = encodeVectorTile({\n layers: {\n contours: {\n features: [\n {\n geometry: [\n [0, 1, 2, 3],\n [9, 8, 7, 6],",
"score": 19.907539370263088
}
] | typescript | type: GeomType.LINESTRING,
geometry: geom,
properties: { |
import { Timer } from "./performance";
import { CancelablePromise, IsTransferrable, Timing } from "./types";
import { withTimeout } from "./utils";
let id = 0;
interface Cancel {
type: "cancel";
id: number;
}
interface Response {
type: "response";
id: number;
error?: string;
response?: any;
timings: Timing;
}
interface Request {
type: "request";
id?: number;
name: string;
args: any[];
}
type Message = Cancel | Response | Request;
type MethodsReturning<T, R> = {
[K in keyof T]: T[K] extends (...args: any) => R ? T[K] : never;
};
/**
* Utility for sending messages to a remote instance of `<T>` running in a web worker
* from the main thread, or in the main thread running from a web worker.
*/
export default class Actor<T> {
callbacks: {
[id: number]: (
error: Error | undefined,
message: any,
timings: Timing,
) => void;
};
cancels: { [id: number]: () => void };
dest: Worker;
timeoutMs: number;
constructor(dest: Worker, dispatcher: any, timeoutMs: number = 20_000) {
this.callbacks = {};
this.cancels = {};
this.dest = dest;
this.timeoutMs = timeoutMs;
this.dest.onmessage = async ({ data }) => {
const message: Message = data;
if (message.type === "cancel") {
const cancel = this.cancels[message.id];
delete this.cancels[message.id];
if (cancel) {
cancel();
}
} else if (message.type === "response") {
const callback = this.callbacks[message.id];
delete this.callbacks[message.id];
if (callback) {
callback(
message.error ? new Error(message.error) : undefined,
message.response,
message.timings,
);
}
} else if (message.type === "request") {
const timer = new Timer("worker");
const handler: Function = (dispatcher as any)[message.name];
const request = handler.apply(handler, [...message.args, timer]);
const url = `${message.name}_${message.id}`;
if (message.id && request) {
this.cancels[message.id] = request.cancel;
try {
const response = await request.value;
const transferrables = | (response as IsTransferrable)
?.transferrables; |
this.postMessage(
{
id: message.id,
type: "response",
response,
timings: timer.finish(url),
},
transferrables,
);
} catch (e: any) {
this.postMessage({
id: message.id,
type: "response",
error: e?.toString() || "error",
timings: timer.finish(url),
});
}
delete this.cancels[message.id];
}
}
};
}
postMessage(message: Message, transferrables?: Transferable[]) {
this.dest.postMessage(message, transferrables || []);
}
/** Invokes a method by name with a set of arguments in the remote context. */
send<
R,
M extends MethodsReturning<T, CancelablePromise<R>>,
K extends keyof M & string,
P extends Parameters<M[K]>,
>(
name: K,
transferrables: Transferable[],
timer?: Timer,
...args: P
): CancelablePromise<R> {
const thisId = ++id;
const value: Promise<R> = new Promise((resolve, reject) => {
this.postMessage(
{ id: thisId, type: "request", name, args },
transferrables,
);
this.callbacks[thisId] = (error, result, timings) => {
timer?.addAll(timings);
if (error) reject(error);
else resolve(result);
};
});
return withTimeout(this.timeoutMs, {
value,
cancel: () => {
delete this.callbacks[thisId];
this.postMessage({ id: thisId, type: "cancel" });
},
});
}
}
| src/actor.ts | onthegomap-maplibre-contour-0f2b64d | [
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " managers: { [id: number]: LocalDemManager } = {};\n init = (message: InitMessage): CancelablePromise<void> => {\n this.managers[message.managerId] = new LocalDemManager(\n message.demUrlPattern,\n message.cacheSize,\n message.encoding,\n message.maxzoom,\n message.timeoutMs,\n );\n return { cancel() {}, value: Promise.resolve() };",
"score": 80.12066144487603
},
{
"filename": "src/dem-source.ts",
"retrieved_chunk": " try {\n const data = await result.value;\n timing = timer.finish(request.url);\n if (canceled) return;\n response(undefined, data.arrayBuffer);\n } catch (error) {\n if (canceled) return;\n timing = timer.error(request.url);\n response(error as Error);\n }",
"score": 50.45847831621302
},
{
"filename": "src/dem-source.ts",
"retrieved_chunk": " timing = timer.finish(request.url);\n if (canceled) return;\n const arrayBuffer: ArrayBuffer = await data.data.arrayBuffer();\n if (canceled) return;\n response(undefined, arrayBuffer, data.cacheControl, data.expires);\n } catch (error) {\n timing = timer.error(request.url);\n if (canceled) return;\n response(error as Error);\n }",
"score": 42.15748963463649
},
{
"filename": "src/dem-source.ts",
"retrieved_chunk": " response: ResponseCallback,\n ): Cancelable => {\n const [z, x, y] = this.parseUrl(request.url);\n const timer = new Timer(\"main\");\n const result = this.manager.fetchTile(z, x, y, timer);\n let canceled = false;\n (async () => {\n let timing: Timing;\n try {\n const data = await result.value;",
"score": 33.583980121693536
},
{
"filename": "src/dem-source.ts",
"retrieved_chunk": " * Callback to be used with maplibre addProtocol to generate contour vector tiles according\n * to options encoded in the tile URL pattern generated by `contourProtocolUrl`.\n */\n contourProtocol = (\n request: RequestParameters,\n response: ResponseCallback,\n ): Cancelable => {\n const timer = new Timer(\"main\");\n const [z, x, y] = this.parseUrl(request.url);\n const options = decodeOptions(request.url);",
"score": 31.288370127826244
}
] | typescript | (response as IsTransferrable)
?.transferrables; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.