New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nostr-dev-kit/ndk

Package Overview
Dependencies
Maintainers
2
Versions
200
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nostr-dev-kit/ndk - npm Package Compare versions

Comparing version 2.11.2 to 2.12.0

src/events/kinds/cashu/token.ts

2

package.json
{
"name": "@nostr-dev-kit/ndk",
"version": "2.11.2",
"version": "2.12.0",
"description": "NDK - Nostr Development Kit",

@@ -5,0 +5,0 @@ "homepage": "https://ndk.fyi",

@@ -25,3 +25,9 @@ import type { NDKEvent, NDKEventId } from "../events/index.js";

query(subscription: NDKSubscription): Promise<void>;
/**
* Either synchronously or asynchronously queries the cache.
*
* Cache adapters that return values synchronously should return an array of events.
* Asynchronous cache adapters should call the subscription.eventReceived method for each event.
*/
query(subscription: NDKSubscription): NDKEvent[] | Promise<NDKEvent[]>;
setEvent(event: NDKEvent, filters: NDKFilter[], relay?: NDKRelay): Promise<void>;

@@ -28,0 +34,0 @@

@@ -66,3 +66,3 @@ /**

if (!scheme) scheme = this.content.search("\\?iv=") ? 'nip04' : 'nip44';
if (!scheme) scheme = this.content.match(/\\?iv=/) ? 'nip04' : 'nip44';

@@ -69,0 +69,0 @@ // simple check for legacy `nip04` encrypted events. adapted from Coracle

@@ -865,7 +865,4 @@ import { EventEmitter } from "tseep";

e.tag(this);
if (publish) {
await e.publish();
} else {
await e.sign();
}
if (publish) await e.publish();

@@ -872,0 +869,0 @@ return e;

@@ -22,2 +22,5 @@ export enum NDKKind {

// NIP-62
Vanish = 62,
// Nip 59 : Gift Wrap

@@ -24,0 +27,0 @@ GiftWrap = 1059,

@@ -34,2 +34,15 @@ import type { NDK } from "../../../ndk/index.js";

public _encryptedTags: NDKTag[] | undefined;
static kinds: NDKKind[] = [
NDKKind.BlossomList,
NDKKind.CategorizedBookmarkList,
NDKKind.CommunityList,
NDKKind.DirectMessageReceiveRelayList,
NDKKind.EmojiList,
NDKKind.InterestList,
NDKKind.PinList,
NDKKind.RelayList,
NDKKind.SearchRelayList,
NDKKind.BlockRelayList,
NDKKind.BookmarkList,
]

@@ -36,0 +49,0 @@ /**

import { NDKEvent } from ".";
import { NDKArticle } from "./kinds/article";
import { NDKCashuToken } from "./kinds/cashu/token";
import { NDKHighlight } from "./kinds/highlight";
import { NDKImage } from "./kinds/image";
import { NDKList } from "./kinds/lists";
import { NDKNutzap } from "./kinds/nutzap";

@@ -26,2 +28,4 @@ import { NDKCashuMintList } from "./kinds/nutzap/mint-list";

NDKSubscriptionTier,
NDKCashuToken,
NDKList,
].forEach((klass) => {

@@ -33,3 +37,3 @@ klass.kinds.forEach((kind) => {

export function wrapEvent<T extends NDKEvent>(event: NDKEvent): T | NDKEvent {
export function wrapEvent<T extends NDKEvent>(event: NDKEvent): T | Promise<T> | NDKEvent {
const klass = eventWrappingMap.get(event.kind);

@@ -36,0 +40,0 @@ if (klass) return klass.from(event);

@@ -18,2 +18,3 @@ import { NDKPool } from "./relay/pool/index.js";

export * from "./events/kinds/highlight.js";
export * from "./events/kinds/cashu/token.js";
export * from "./events/kinds/image.js";

@@ -20,0 +21,0 @@ export * from "./events/kinds/index.js";

@@ -192,2 +192,8 @@ import debug from "debug";

onEvent?: (event: NDKEvent, relay?: NDKRelay) => void;
/**
* Called with the events that synchronously loaded from the cache.
*/
onEvents?: (events: NDKEvent[]) => void;
onEose?: (sub: NDKSubscription) => void;

@@ -203,4 +209,2 @@ }

export class NDK extends EventEmitter<{
event: (event: NDKEvent, relay: NDKRelay) => void;
"signer:ready": (signer: NDKSigner) => void;

@@ -307,3 +311,3 @@ "signer:required": () => void;

this.blacklistRelayUrls = opts.blacklistRelayUrls || DEFAULT_BLACKLISTED_RELAYS;
this.subManager = new NDKSubscriptionManager(this.debug);
this.subManager = new NDKSubscriptionManager();
this.pool = new NDKPool(

@@ -541,7 +545,13 @@ opts.explicitRelayUrls || [],

if (autoStart) {
let eventsHandler: ((events: NDKEvent[]) => void) | undefined;
if (typeof autoStart === "object") {
if (autoStart.onEvent) subscription.on("event", autoStart.onEvent);
if (autoStart.onEose) subscription.on("eose", autoStart.onEose);
if (autoStart.onEvents) eventsHandler = autoStart.onEvents;
}
setTimeout(() => subscription.start(), 0);
setTimeout(() => {
const cachedEvents = subscription.start(!!eventsHandler);
if (cachedEvents && !!eventsHandler) eventsHandler(cachedEvents);
}, 0);
}

@@ -583,2 +593,22 @@

/**
* Fetch an event from the cache synchronously.
* @param idOrFilter event id in bech32 format or filter
* @returns events from the cache or null if the cache is empty
*/
public fetchEventSync(idOrFilter: string | NDKFilter[]): NDKEvent[] | null {
if (!this.cacheAdapter) throw new Error("Cache adapter not set");
let filters: NDKFilter[];
if (typeof idOrFilter === "string") filters = [filterFromId(idOrFilter)];
else filters = idOrFilter;
const sub = new NDKSubscription(this, filters);
const events = this.cacheAdapter.query(sub);
if (events instanceof Promise) throw new Error("Cache adapter is async");
return events
.map(e => {
e.ndk = this;
return e;
})
}
/**
* Fetch a single event.

@@ -585,0 +615,0 @@ *

@@ -13,2 +13,3 @@ import { EventEmitter } from "tseep";

import { verifiedSignatures } from "../events/validation.js";
import { wrapEvent } from "../events/wrap.js";

@@ -127,2 +128,8 @@ export type NDKSubscriptionInternalId = string;

cacheUnconstrainFilter?: (keyof NDKFilter)[];
/**
* Whether to wrap events in kind-specific classes when possible.
* @default false
*/
wrap?: boolean;
}

@@ -333,3 +340,9 @@

private shouldQueryCache(): boolean {
return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY;
// explicitly told to not query the cache
if (this.opts?.cacheUsage === NDKSubscriptionCacheUsage.ONLY_RELAY) return false;
const hasNonEphemeralKind = this.filters.some((f) => f.kinds?.some((k) => kindIsEphemeral(k)));
if (hasNonEphemeralKind) return true;
return true;
}

@@ -358,29 +371,86 @@

* after creating a subscription.
*
* @param emitCachedEvents - Whether to emit events coming from a synchronous cache
*
* When using a synchronous cache, the events will be returned immediately
* by this function. If you will use those returned events, you should
* set emitCachedEvents to false to prevent seeing them as duplicate events.
*/
public async start(): Promise<void> {
let cachePromise;
public start(emitCachedEvents: boolean = true): NDKEvent[] | null {
let cacheResult: NDKEvent[] | Promise<NDKEvent[]>;
const updateStateFromCacheResults = (events: NDKEvent[]) => {
if (emitCachedEvents) {
for (const event of events) {
this.eventReceived(event, undefined, true, false);
}
} else {
cacheResult = [];
events.forEach((event) => {
event.ndk = this.ndk;
const e = this.opts.wrap ? wrapEvent(event) : event;
if (!e) return;
if (e instanceof Promise) {
// if we get a promise, we emit it
e.then((wrappedEvent) => {
this.emitEvent(false, wrappedEvent, undefined, true, false);
});
return;
}
this.eventFirstSeen.set(e.id, Date.now());
(cacheResult as NDKEvent[]).push(e);
});
}
}
const loadFromRelays = () => {
if (this.shouldQueryRelays()) {
this.startWithRelays();
this.startPoolMonitor();
} else {
this.emit("eose", this);
}
}
if (this.shouldQueryCache()) {
cachePromise = this.startWithCache();
cachePromise.then(() => this.emit('cacheEose'))
cacheResult = this.startWithCache();
if (this.shouldWaitForCache()) {
await cachePromise;
if (cacheResult instanceof Promise) {
// The cache is asynchronous
if (this.shouldWaitForCache()) {
// If we need to wait for it
cacheResult.then((events) => {
// load the results into the subscription state
updateStateFromCacheResults(events);
// if the cache has a hit, return early
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
} else {
loadFromRelays();
}
});
return null;
} else {
cacheResult.then((events) => {
updateStateFromCacheResults(events);
});
}
// if the cache has a hit, return early
return null;
} else {
updateStateFromCacheResults(cacheResult);
if (queryFullyFilled(this)) {
this.emit("eose", this);
return;
} else {
loadFromRelays();
}
return cacheResult;
}
}
if (this.shouldQueryRelays()) {
this.startWithRelays();
this.startPoolMonitor();
} else {
this.emit("eose", this);
loadFromRelays();
return null;
}
return;
}

@@ -430,9 +500,7 @@

private async startWithCache(): Promise<void> {
private startWithCache(): NDKEvent[] | Promise<NDKEvent[]> {
if (this.ndk.cacheAdapter?.query) {
const promise = this.ndk.cacheAdapter.query(this);
if (this.ndk.cacheAdapter.locking) {
await promise;
}
return this.ndk.cacheAdapter.query(this);
} else {
return [];
}

@@ -525,8 +593,4 @@ }

// emit it
if (!fromCache && relay) {
this.ndk.emit("event", ndkEvent, relay);
}
if (!optimisticPublish || this.skipOptimisticPublishEvent !== true) {
this.emit("event", ndkEvent, relay, this, fromCache, optimisticPublish);
this.emitEvent(this.opts?.wrap, ndkEvent, relay, fromCache, optimisticPublish);
// mark the eventId as seen

@@ -554,2 +618,14 @@ this.eventFirstSeen.set(eventId, Date.now());

/**
* Optionally wraps, sync or async, and emits the event (if one comes back from the wrapper)
*/
private emitEvent(wrap = false, evt: NDKEvent, relay: NDKRelay | undefined, fromCache: boolean, optimisticPublish: boolean) {
const wrapped = wrap ? wrapEvent(evt) : evt;
if (wrapped instanceof Promise) {
wrapped.then((e) => this.emitEvent(false, e, relay, fromCache, optimisticPublish))
} else if (wrapped) {
this.emit("event", wrapped, relay, this, fromCache, optimisticPublish);
}
}
public closedReceived(relay: NDKRelay, reason: string): void {

@@ -640,1 +716,3 @@ this.emit("closed", relay, reason);

}
const kindIsEphemeral = (kind: NDKKind) => kind >= 20000 && kind < 30000;
import { NDKSubscription, NDKRelay } from "../index.js";
import NDK, { NDKEventId } from "../index.js";
import { NDKSubscriptionManager } from "./manager.js";
import debug from "debug";
const d = debug("test");
const ndk = new NDK();

@@ -13,3 +11,3 @@

beforeEach(() => {
manager = new NDKSubscriptionManager(d);
manager = new NDKSubscriptionManager();
});

@@ -16,0 +14,0 @@

@@ -5,3 +5,2 @@ import { matchFilters, type VerifiedEvent } from "nostr-tools";

import type { NDKSubscription } from "./index.js";
import type debug from "debug";

@@ -16,7 +15,5 @@ export type NDKSubscriptionId = string;

public seenEvents = new Map<NDKEventId, NDKRelay[]>();
private debug: debug.Debugger;
constructor(debug: debug.Debugger) {
constructor() {
this.subscriptions = new Map();
this.debug = debug.extend("sub-manager");
}

@@ -73,4 +70,2 @@

*/
public filterMatchingTime = 0;
public filterMatchingCount = 0;
public dispatchEvent(

@@ -86,3 +81,2 @@ event: NostrEvent,

const start = Date.now();
for (const sub of subscriptions) {

@@ -93,4 +87,2 @@ if (matchFilters(sub.filters, event as VerifiedEvent)) {

}
this.filterMatchingTime += Date.now() - start;
this.filterMatchingCount += matchingSubs.length;

@@ -97,0 +89,0 @@ for (const sub of matchingSubs) {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc